Aug 7, 2011

CREATING ACTIVE X OBJECTS WITH C# / CALLING C# DLL FROM JAVA SCRIPT


CREATING ACTIVE X OBJECTS WITH C# / CALLING C# DLL FROM JAVA SCRIPT

CALLING C# DLL FROM JAVA SCRIPT

Finally I did it ... It was a complete night mare for me and my team ..
k lemme stop about my night mare. Its very quite simple..

Creating Activex objects with C#  

Here i will discuss how to create a com object using c#  and how to use it in the java script. calling C# dll from java script means creating a Activex object for the com object created from our dll.

ActiveX is a Microsoft technology used for creating
re-usable components. This technology, also called Object Linking and Embedding
(OLE), along with COM is heavily used within the Microsoft environment and
application development. 

For further details go through this link http://en.wikipedia.org/wiki/ActiveX

 Anyone interested in creating reusable components should have some familiarity with
COM. A very good resource is “Essential COM” by Don Box.

The idea behind COM is to allow the creation of components
that can be consumed by a variety of clients. This means that I can create a
component using C++ which can then be used by an application written in VB, or
even a web page which we will be performing shortly. Traditionally, ActiveX
objects were usually written in C++ and VB but can actually be written in any
language as long as they are COM-aware.

This means that we can create 
COM objects with the .NET
platform
. A survey of resources/tutorials on COM and .NET on the internet by and
large only tell you how to consume unmanaged COM objects via Interop. So my aim
with this guide is to show how to use this powerful feature. Also, FYI, there is
a .NET technology very similar to what will be describe below which allows
hosting Windows Forms Controls inside of IE (don’t know the official term/name
for this).


Thats enough blaaa blaaa now.... We will go through an example....

Step1: Creating the C# DLL WHICH WILL BE CALLED BY JAVASCRIPT




using System;
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
 
namespace csharp.activex.sample
{
   /// 
   /// A very simple interface to test ActiveX with.
   /// 
   [
       Guid( "E86A9038-368D-4e8f-B389-FDEF38935B2F"),
       InterfaceType( ComInterfaceType.InterfaceIsDual),
       ComVisible( true)
   ]
   public interface IHello    
        {
       [DispId(1)]
       string Hello();
        
       [DispId(2)]
       int SayHello(string msg);
   };
 
   [
       Guid("873355E1-2D0D-476f-9BEF-C7E645024C32"),
 
       // This is basically the programmer friendly name
       // for the guid above. We define this because it will
       // be used to instantiate this class. I think this can be
       // whatever you want. Generally it is
       // [assemblyname].[classname]
       ProgId("csharpAx.CHello"),
 
       // No class interface is generated for this class and
       // no interface is marked as the default.
       // Users are expected to expose functionality through
       // interfaces that will be explicitly exposed by the object
       // This means the object can only expose interfaces we define
       ClassInterface(ClassInterfaceType.None),  
       // Set the default COM interface that will be used for
       // Automation. Languages like: C#, C++ and VB
       // allow to query for interface's we're interested in
       // but Automation only aware languages like javascript do
       // not allow to query interface(s) and create only the
       // default one
       ComDefaultInterface(typeof(IHello)),
       ComVisible(true)
   ]
   public class CHello : IHello
   {
 
       
       public string function1()
       {
           return "Hello from CHello object";
       }
 
 
       public int SayHello(string msg)
       {
           
                 return 1;
       }
     
   };
}

The HelloControl.cs file consists of one class and one interface.
So let’s start with the interface definition and follow up with the CHello class.

**IHello Interface**

An interface is generally described as a contract. Once an interface is designed
and published for use it should NEVER change. Let me repeat this, it
should NEVER change.

Several attributes have been defined for this interface.

1) Guid – This is a unique identifier. Use guidgen.exe to generate your own
2) InterfaceType – This determines which base class to expose to COM.

The InterfaceType attribute demands a little further explaination. Here is how it is defined.



Compiling & Registering
----------------------------

Once the code is written up go ahead an compile the ActiveX assembly.
The assembly will be called [projectname].dll inside the bin folder of the project.

The next step is to register. Do this opening up a command prompt and go to the
location of the dll. To register the assembly type:

Open the visual studio command prompt.

C:\Regasm C:\Build\[projectname].dll /codebase /tlb  

Make sure replace “[projectname]” with the correct name of your dll.
You should get some output that says the assembly was exported correctly.
Something like the following.


Microsoft ® .NET Framework Assembly Registration Utility 2.0.50727.42
Copyright © Microsoft Corporation 1998-2004. All rights reserved.
Types registered successfully
Assembly exported to '[TLB location]
', and the type library was registered successfully
After this a tlb file will created in the path specified above( i mean in the path of the dll)
To unregister the assembly pass the “/unregister” flag to Regasm. You will need to
unregister and close IE when changes need to be made to the assembly. If you don’t
unregister your assembly prior to making code changes you may end up with bogus
registry entries and a pain to clean up. The reason for closing IE is to make sure
that all reference to your assembly have been released.


Creating HTML Test Page
-----------------------------

We are just about done. All we need to do now is create a test page.
This should be really simple, but here it is nonetheless. The Javascript
to create the ActiveX object is also provided.


Here i am writing down a java script example. here i wrote a function in java script where it calls the dll of c#.



function myload()


{


    var myAx = new ActiveXObject("DllName");(just a dll name .dll extension should not be given)


    if(myAx != null)


    {


        var d = myAx.fucnction1();


       alert(d);


         


       


    }


    else


        alert("NOOOO... we failed");


}



To create our ActiveX object in Javascript we use the ActiveXObject(). The parameter
for this is generally the PROGID that we specified in its definition. If a
PROGID was not specified in its definition then I think you can pass in
“AssemblyName.ClassName”. The rest of the javascript simply calls our ActiveX
objects methods.


That’s it!!! We should have a fully functional example. This ability to execute ActiveX
objects from javascript is very powerful. Debates and arguments about security
and safety of ActiveX objects are well known and I will not throw more fodder
to the fire. However, imagine creating a Win32 or even a Winform application
where the UI is written in HTML via IWebBrowser2 and all the UI interaction handled
with your ActiveX object, just food for thought. Though, now that I think of it,
WPF is already doing this. Oh Well.

Hopefully you found this guide on how to create an ActiveX object with C# helpful.

Cheers for going through the same... 

Sandeep....

Jun 16, 2011

.Net code obfuscation/.Net dll obfuscation



.Net code obfuscation/ C# dll obfuscation




Obfuscation  In the context of software, obfuscation is the process of scrambling the symbols, code, and data of a program to prevent reverse engineering.In the context of software, obfuscation is the process of scrambling the symbols, code, and data of a program to prevent reverse engineering.


Please download it from http://eazfuscator.blogspot.com/ .
















We can do the obfuscation through code. It is very simple.


obfuscation  Add the following Piece of code  in a new file called ObfuscationSettings.cs
And the contents of the file will be as follows.


using System;
using System.Reflection;
[assembly: Obfuscation(Feature = "code control flow obfuscation", Exclude = false)]







Hope it helped u...
Cheers!!!!

Sandeep

Jun 7, 2011

Download a file from FTP server C#

Download a file from FTP server C#

In .Net it is always easy to write a piece of code as most of the functionalities are in built.
System.Net namespace inclusion does the work for you and it is very simple. 

Just go through the piece of code/function written below.
static void downloadFile()
        {
            //Create a WebClient.
            WebClient request = new WebClient();

            //Setup the credentials to the ftp server
            request.Credentials =
                new NetworkCredential("username",
                                        "password");

            //Download the data into a Byte array

            //@ is used to take the relative path
            byte[] fileData =
                request.DownloadData(@"Ftp path" + @"/" +
                                     @"Directorypath");

            //Create a FileStream that we'll write the byte array to.
                FileStream file =
                File.Create(@"C:\sand\Weekly Plan Excel-10-sep.xls");

            //Write the full byte array to the file.
            file.Write(fileData, 0, fileData.Length);

            //Close the file so other processes can access it.
            file.Close();
        }
        
it is as simple as that ...

Hope it helped u ....

Cheers!!!!!!!!!
Sandeep

Changing the WCF service start mode to automatic/manual

Changing the WCF service start mode to automatic/manual

Changing the wcf service to start mode or automatic is very easy. In initial stages i used to go to services.msc and change the start mode of my service to automatic or manual, but later on i found that changing the service mode is very easy and it can be done through the code.

First thing you need to do is add the INSTALLER CLASS to the wcf service project then view the code of the installer class.

Then follow the simple steps to make your service to run automatically or manually. The simplest change here is  to change the ServiceInstaller.StartType property
 Right this piece of code in the constructor of your installer class.

            InitializeComponent();
            ServiceProcessInstaller processInstaller = new ServiceProcessInstaller();
            ServiceInstaller serviceInstaller = new ServiceInstaller();

            //Specifies the type of account that should be used for the WCF service.
            processInstaller.Account = ServiceAccount.LocalSystem;
            //Specifies the name of the service that is installed.
            serviceInstaller.DisplayName = "//Specify the name of your service in the way how it should appear like in the services.msc";
            //Gives the description of the Installed service.
            serviceInstaller.Description = "Give the description of your service";
            //It tells which is the service that is installed.
            serviceInstaller.ServiceName = "Specify the name of the service here";
            //It specifies the Start type of the service.
            serviceInstaller.StartType = ServiceStartMode.Automatic;
            Installers.Add(processInstaller);
            Installers.Add(serviceInstaller);

So now you are in a great position to change the wcf service start mode.


Hope it helped you ...
Cheers...
Sandeep

May 14, 2011

ROWNUM AND ORDER BY


ROWNUM AND ORDER BY
We had a big issue in our production because of this interesting stupidity of us. When you query using them it looks to be very much fine, but the way you write the query does mean a lot. Normally many of us write the query like a simple example given below.

SELECT * FROM (your table name)
WHERE (your condition..)
and ROWNUM < 1000
ORDER BY date

if you query this way it normally gives the top 1000 rows of the table leaving the other rows and then sorts this 1000 rows, but in case if you first want to sort out the entire table  and then give you the top 1000 rows, here comes the confusion the above case certainly fails with the above query.
Just a few changes to query will solve your necessity.

SELECT FROM SELECT *  FROM (table name)
  
WHERE (your condition..)
  
ORDER BY date
WHERE ROWNUM 1000;  



Hope it helped u.....
Cheers..
Sandeep.

Feb 3, 2011

.Net convert object to XML (Serialization)


.NET OBJECT SERIALIZATION

Introduction
Serialization can be defined as the process of storing the state of an object instance to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, is converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.
When implementing a serialization mechanism in an object-oriented environment, you have to make a number of tradeoffs between ease of use and flexibility. The process can be automated to a large extent, provided you are given sufficient control over the process. For example, situations may arise where simple binary serialization is not sufficient, or there might be a specific reason to decide which fields in a class need to be serialized. The following sections examine the robust serialization mechanism provided with the .NET Framework and highlight a number of important features that allow you to customize the process to meet your needs.

XML SERIALIZATION

It is widely used when two different domains talk. I faced a same situation where i had to develop an .net application where it needs to talk to a java application. I was forced to a situation where i need to send a object from my application to the other application by calling the exe. I was wondering how is that possible then i came through something called serialization of objects.
I used xml serialization and then converted the my object to xml and passed the xml string to the other application as a argument. To know how to pass a string as a argument 


We will now see how the object is converted to xml serialization with an example
for example we have a class for which the object has to be sent.
public class MyObject
    {
        public string property1{ get; set; }
        public string property2 { get; set; }      
        public decimal property3 { get; set; }
        public int property4 { get; set; }      
    }

now we add values to all this properties
MyObject  myObject  =new MyObject();
myObject.Property1=sandeep;
myObject.Property2=naveen;
myObject.Property3=rajkumar;
myObject.Property1=rajendra

XmlSerializer xml = new XmlSerializer(myObject.GetType());
            string fileName =@ "C:/Test.xml";
            FileStream fileStream = new FileStream(fileName, FileMode.Create);
            xml.Serialize(fileStream, myObject);
Now go to the path specified you will find the object serialized into xml.

Hope this helped u..
CHEERS..
THESANDEEP
www.thesandeep.com


Jan 31, 2011

STORED PROCEDURES


Stored procedures- an important aspect for the developers in SQL
stored procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again.  So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a stored procedure and then just call the stored procedure to execute the SQL code that you saved as part of the stored procedure.

In addition to running the same SQL code over and over again you also have the ability to pass parameters to the stored procedure, so depending on what the need is the stored procedure can act accordingly based on the parameter values that were passed.

There are various options to create a strored procedure. 
First we will learn to create to a simple stored procedure

Before you create a stored procedure you need to know what your end result is, whether you are selecting data, inserting data, etc.. 
In this simple example we will just select all data from the Person.Address table that is stored in the AdventureWorks database.

So the simple T-SQL code would be as follows which will return all rows from this table.
SELECT * FROM AdventureWorks.Person.Address

To create stored procedure to do this the code would look like this:
CREATE PROCEDURE uspGetAddress
AS
SELECT * FROM AdventureWorks.Person.Address
GO

To call the procedure to return the contents from the table specified, the code would be:
EXEC uspGetAddress
--or just simply
uspGetAddress


How to create a SQL Server stored procedure with parameters


OverviewThe real power of stored procedures is the ability to pass parameters and have the stored procedure handle the differing requests that are made.  In this topic we will look at passing parameter values to a stored procedure.
ExplanationJust like you have the ability to use parameters with your SQL code you can also setup your stored procedures to except one or more parameter values.
One Parameter
In this example we will query the Person.Address table from the AdventureWorks database, but instead of getting back all records we will limit it to just a particular city.  This example assumes there will be an exact match on the City value that is passed.
CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT * 
FROM AdventureWorks.Person.Address
WHERE City = @City
GO
To call this stored procedure we would execute it as follows:
EXEC uspGetAddress @City = 'New York'
We can also do the same thing, but allow the users to give us a starting point to search the data.  Here we can change the "=" to a LIKE and use the "%" wildcard.
CREATE PROCEDURE uspGetAddress @City nvarchar(30) 
AS 
SELECT * 
FROM AdventureWorks.Person.Address 
WHERE City LIKE @City + '%' 
GO
In both of the proceeding examples it assumes that a parameter value will always be passed. If you try to execute the procedure without passing a parameter value you will get an error message such as the following:
Msg 201, Level 16, State 4, Procedure uspGetAddress, Line 0
Procedure or function 'uspGetAddress' expects parameter '@City', which was not supplied.
Default Parameter Values
In most cases it is always a good practice to pass in all parameter values, but sometimes it is not possible.  So in this example we use the NULL option to allow you to not pass in a parameter value.  If we create and run this stored procedure as is it will not return any data, because it is looking for any City values that equal NULL.
CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City
GO
We could change this stored procedure and use the ISNULL function to get around this.  So if a value is passed it will use the value to narrow the result set and if a value is not passed it will return all records.
CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = ISNULL(@City,City)
GO
Multiple Parameters
Setting up multiple parameters is very easy to do.  You just need to list each parameter and the data type separated by a comma as shown below.
CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL, @AddressLine1 nvarchar(60) = NULL
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = ISNULL(@City,City)
AND AddressLine1 LIKE '%' + ISNULL(@AddressLine1 ,AddressLine1) + '%'
GO
To execute this you could do any of the following:
EXEC uspGetAddress @City = 'Calgary'
--or
EXEC uspGetAddress @City = 'Calgary', @AddressLine1 = 'A'
--or
EXEC uspGetAddress @AddressLine1 = 'Acardia'
-- etc...

Returning stored procedure parameter values to a calling stored procedure
(OUTPUT)



Overview
In a previous topic we discussed how to pass parameters into a stored procedure, but another option is to pass parameter values back out from a stored procedure.  One option for this may be that you call another stored procedure that does not return any data, but returns parameter values to be used by the calling stored procedure.
Explanation
Setting up output paramters for a stored procedure is basically the same as setting up input parameters, the only difference is that you use the OUTPUT clause after the parameter name to specify that it should return a value.  The output clause can be specified by either using the keyword "OUTPUT" or just "OUT".
Simple Output
CREATE PROCEDURE uspGetAddressCount @City nvarchar(30), @AddressCount int OUTPUT
AS
SELECT @AddressCount = count(*) 
FROM AdventureWorks.Person.Address 
WHERE City = @City
Or it can be done this way:
CREATE PROCEDURE uspGetAddressCount @City nvarchar(30), @AddressCount int OUT
AS
SELECT @AddressCount = count(*) 
FROM AdventureWorks.Person.Address 
WHERE City = @City
To call this stored procedure we would execute it as follows.  First we are going to declare a variable, execute the stored procedure and then select the returned valued.
DECLARE @AddressCount int
EXEC uspGetAddressCount @City = 'Calgary', @AddressCount = @AddressCount OUTPUT
SELECT @AddressCount
This can also be done as follows, where the stored procedure parameter names are not passed.
DECLARE @AddressCount int
EXEC uspGetAddressCount 'Calgary', @AddressCount OUTPUT
SELECT @AddressCount



But as now you mastered the stored procedures 

we will see how best can be a stored procedure used...The best way of writing a stored procedure  is described below.
USE [DATABASE NAME]
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

IF EXISTS ( SELECT name FROM SYSOBJECTS WHERE type = 'P' AND name = 'storedprocedurename')
DROP PROCEDURE dbo.[storedprocedurename]
GO

CREATE PROCEDURE [dbo].[storedprocedurename] 
  -- Adding parameters for the stored procedure
  @parameter1   nvarchar(50)  
AS


/******************************************************************************
**    File: storedprocedurename.sql
**    Name: storedprocedurename
**    Desc: SP to get a new record in storedprocedurename
**          If a record alredy exists for the given parameter then return the existing record.
**    NOTE: 
**            
**
**              
**    Return values:
** 
**    Called by:   
**              
**    Parameters:
**    Input                                 Description
**    ----------                            -----------
**  @parameter1     parameter description
**  
**
**    Author: Sandeep kumar
**    Date:   31-01-2011
*******************************************************************************
**    Change History
*******************************************************************************
**    Date:       Author:                       Description:
**    --------    --------                      -----------------------------
**
**
*******************************************************************************/

BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
  SET NOCOUNT ON; 
   SELECT columnname1,
columnname2,
  columnname3 
FROM  tablename
  WHERE columnname = @parameter1
 
END




By now you should have mastered the usage of stored procedure.
CHEERS...
THESANDEEP
WWW.THESANDEEP.COM