Tuesday, August 6, 2013

Delegate in C#

Delegate
A delegate is a type that defines method signature. An instance of delegate can be associate with any compatible signatures.  Later on we can invoke any method through delegate instance.
Delegates can be used to pass method as argument to another method. This ability makes delegates ideal for defining callback methods.
Properties of delegates
  • Delegates are method pointers. Unlike C++ it is type safe. Delegates allow passing method as parameter.
  • Delegates can be used to define call back method.
  • Delegates can be combined together.
  • We can pass code block as parameter in delegates. It is called anonymous method.
  • Delegates support Covariance and Contravariance.
  • Delegates can be overloaded.

 Now let’s explore delegate more with an example.
 
  • abc is a class having one method function1. Function 1 takes one string type argument. And it has a  return type of void. 
  • A delegate mydelegate is declared with one string type parameter and void return type.
  • Creating the instance of mydelegate and associate function1 with the instance.
  • Now at last need to invoke the method by delegate.  It is very easy to invoke. Just pass the parameter with delegate object. 
Different implementation of delegate

Tuesday, July 23, 2013

SSIS - connection string from XML

SSIS - getting connection string from XML file.
 
Step 1
 
Go to SSIS and select Package Configurations.
 
 
 Step 2
 
Add new configuration.
 
 
Step 3
 
Select Configuration type as XML Configuration file. Then select Specify configuration setting directly radio button and select the configuration file.
 
 
Step 4
 
Select the property which you want to configure. Here it is Connection string. Then click next.
 
 
Step 5
 
Give a name to this configuration.  And click on finish.
 
 
 
Hey you are done with this in just 5 click.
 
 
Here is the configuration file (abc.dtsConfig)
 

<?xml version="1.0"?> <DTSConfiguration> <DTSConfigurationHeading> <DTSConfigurationFileInfo GeneratedBy="HCLTECH\hriday.dutta" GeneratedFromPackageName="Package" GeneratedFromPackageID="{9F34C6C8-7D33-4E60-AA5A-1A95DA62D08B}" GeneratedDate="7/17/2013 2:48:57 PM"/> </DTSConfigurationHeading> <Configuration ConfiguredType="Property" Path="\Package.Connections[192.168.1.1].Properties[ConnectionString]" ValueType="String"> <ConfiguredValue>Data Source=192.168.1.1;Initial Catalog=master;User ID=abc;Password=abc</ConfiguredValue> </Configuration> </DTSConfiguration>


 
 
 
 
 
 
 
 
 
 
 
 
 

Monday, July 22, 2013

Export to excel in ZIP format

Problem
 
Exporting large file from Asp.Net pages cause huge bandwidth consumption, slow response and time-out problem. In most of application there are couple of pages
where we export large data file in to excel. And the most common problems are response time-out and  slow UI response.
 
Solution
 
There are two solutions for this problem.
 
1. Enable streaming for download.
 
2. Download file in Zip format.
 
 
Streaming
 
Streaming is considered to be the best solution for downloading. But it need a dedicated streaming service(WCF/SOAP) and lots of working hour to implement this.
Streaming does not support all file types like .xls, .txt etc.
 
Zip
 
The second solution is zip. Which can be applied with all file types. And compared to streaming, it is quite easy to implement with couple of lines of code.
Zip give us up to 95% compression for excel files. So we really need not to worry for file size up to 100 MB in case of excel.  
 
Now the question is which solution we should implement in our application. Here I must say Zip if it is not a video/audio.
 
Step 1
 
Put a button control in our .aspx page.
 
 
Step 2
 
Import DotNetZip library. You can download it from CodePlex.
It is an Open Source Library with Microsoft Public License (Ms-PL).
 
Step 3
 
Import Iconic.Zip namespace to your code behind.
 
 
Step 4
 
On button click write the following code.
This is all you need to do for download file in zip format.
 
Output
 

Execute SSIS package from ASP.NET

Execute SSIS package from ASP.NET web forms. Let’s take a scenario, we will create a table in SQL server and insert data into that table using SSIS package and call the package from Web forms.
 
Step 1
 
Create a table in SQL server named “stud”.
 
 
 
Step 2
 
Prepare a parameterize insert SQL query.
 
 
  
Step 3
 
Create a SSIS package. Open SQL Server Business Intelligence Development Studio. Then create a new “Integration Services Project”.
Step 4
 
Drag a “Execute SQL Task” control in Control Flow tab.
 
 
Step 5
 
Right click on “Execute SQL Task” and select Edit. And Execute SQL Task Editor will popup.
 
Step 6
 
Now we need to configure Connection Type and Connection. For this case we use ADO.NET. And Configure the Connection.





 
 
Step 7
 
After configuration the connection type and connection string, now it’s time to configure “SQL Statement” and Parameter Mapping. Put the prepared  parameterize insert SQL query in “SQL Statement” block.
Before Parameter mapping done we need to create two variable so that we map them with parameter. For this right click on any blank space and create two string type variable Name and Roll.
 



 
Now Go to Parameter mapping and map these two Variable with  our two parameter.
Your are done with SSIS package. Now make a quick build and check everything is ok. You will find our SSIS package under Bin folder (“Package.dtsx).
 
Step 8
 
Now create and an Asp.Net web application and call the SSIS Package. Copy the Package.dtsx file to our solution. Take two textbox and a button control.
 
 
On the click event of the Button write the following code.
 
First off all you need to take reference of “Microsoft.SqlServer.ManagedDTS.dll”. You will find it in GAC.
“C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.ManagedDTS\10.0.0.0__89845dcd8080cc91”
Now include the namespace Microsoft.SqlServer.Dts.Runtime
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  
Its time to test. Run the application.  With some input value .
 
 
SQL Tables
 
 
Mission accomplished.
 
 
 

Downloads

 
You can download examples and source code from here.

 
 

Sunday, June 23, 2013

SOAP Serialization in C#

SOAP Serialization

SOAP serialization uses SOAP encoding to produce compact serialization for uses such as web service.

Example

In this example we take an employee class. It has two attribute EmpId and EmpName.

using System;
using System.Runtime.Serialization;

namespace Example_Serialization
{
    [Serializable] 
    public class Employee : ISerializable
    {
        public int EmpId { get; set; }
        public string EmpName { get; set; }
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("EmpId", EmpId);
            info.AddValue("EmpName", EmpName);           
        }
        public Employee(SerializationInfo info, StreamingContext context)
        {
            EmpId = (int)info.GetValue("EmpId", typeof(int));
            EmpName = (string)info.GetValue("EmpName", typeof(string));
        }

        public Employee()
        {
        }
    }
}  
In the above class  [Serializable] attribute should be applied. Serializable attribute tell compiler that all public and private properties should be serialized. If we don't want to serialize some properties then simply apply [NonSerialized] attribute. Some times we need more customization, in that case we implements ISerializable interface. It override serializations process. It has a method  named GetObjectData which actually serialize the object. And for desrialization we use a constructor where we write our deserialization code.
Now we can serialize and deserialize our employee class. Below code snippet will explain how to serialize our employee class using SOAP serialization.

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;


namespace Example_Serialization
{  
    class SOAPSerialization
    {      
        public void SerializeObj()
        {
            Console.WriteLine("SOAP Serialization starting");
            Employee emp = new Employee() { EmpId = 1, EmpName = "Hriday Ranjan Dutta" };
            Stream stream = File.Open("SOAPemployee.txt", FileMode.OpenOrCreate);
            SoapFormatter bformatter = new SoapFormatter();
            bformatter.Serialize(stream, emp);
            stream.Close();
            Console.WriteLine("SOAP Serialization done");
            Console.ReadLine();
        }
        public void DeserializeObj()
        {
            Console.WriteLine("SOAP Deserialization starting");
            Stream stream = File.Open("SOAPemployee.txt", FileMode.Open);
            SoapFormatter bformatter = new SoapFormatter();
            Employee emp = (Employee)bformatter.Deserialize(stream);
            stream.Close();
            Console.WriteLine("Employee ID : {0}, Employee Name : {1}",emp.EmpId.ToString(),emp.EmpName);
            Console.WriteLine("SOAP Deserialization done");
            Console.ReadLine();
        }

      
    }
}

Output Serialized file

<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<a1:Employee id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/Example_Serialization/Example_Serialization%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<_x003C_EmpId_x003E_k__BackingField>1</_x003C_EmpId_x003E_k__BackingField>
<_x003C_EmpName_x003E_k__BackingField id="ref-3">Hriday Ranjan Dutta</_x003C_EmpName_x003E_k__BackingField>
</a1:Employee>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
 

 

Saturday, June 22, 2013

Binary Serialization in C#

Binary Serialization

Binary serialization uses binary encoding to produce compact serialization for uses such as storage or socket-based network streams. It is also known as deep serialization. Because it serialize every thing of an object.

Example

In this example we take an employee class. It has two attribute EmpId and EmpName.


using System;
using System.Runtime.Serialization;

namespace Example_Serialization
{
    [Serializable] 
    public class Employee : ISerializable
    {
        public int EmpId { get; set; }
        public string EmpName { get; set; }
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("EmpId", EmpId);
            info.AddValue("EmpName", EmpName);           
        }
        public Employee(SerializationInfo info, StreamingContext context)
        {
            EmpId = (int)info.GetValue("EmpId", typeof(int));
            EmpName = (string)info.GetValue("EmpName", typeof(string));
        }

        public Employee()
        {
        }
    }
}  

In the above class  [Serializable] attribute should be applied. Serializable attribute tell compiler that all public and private properties should be serialized. If we don't want to serialize some properties then simply apply [NonSerialized] attribute. Some times we need more customization, in that case we implements ISerializable interface. It override serializations process. It has a method  named GetObjectData which actually serialize the object. And for desrialization we use a constructor where we write our deserialization code.

Now we can serialize and deserialize our employee class. Below code snippet will explain how to serialize our employee class using binary serialization.

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Example_Serialization
{   
    class BinarySerialization
    {      
        public void SerializeObj()
        {
            Console.WriteLine("Binary Serialization starting");
            Employee emp = new Employee() { EmpId = 1, EmpName = "Hriday Ranjan Dutta" };
            Stream stream = File.Open("Binaryemployee.txt", FileMode.OpenOrCreate);
            BinaryFormatter bformatter = new BinaryFormatter();
            bformatter.Serialize(stream, emp);
            stream.Close();
            Console.WriteLine("Binary Serialization done");
            Console.ReadLine();
        }
        public void DeserializeObj()
        {
            Console.WriteLine("Binary Deserialization starting");
            Stream stream = File.Open("Binaryemployee.txt", FileMode.Open);
            BinaryFormatter bformatter = new BinaryFormatter();
            Employee emp = (Employee)bformatter.Deserialize(stream);
            stream.Close();
            Console.WriteLine("Employee ID : {0}, Employee Name : {1}",emp.EmpId.ToString(),emp.EmpName);
            Console.WriteLine("Binary Deserialization done");
            Console.ReadLine();
        }       
    }
}


Output Serialized file

 ÿÿÿÿ           LExample_Serialization, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null    Example_Serialization.Employee    <EmpId>k__BackingField <EmpName>k__BackingField    Hriday Ranjan Dutta

Friday, June 21, 2013

XML Serialization in C#

XML Serialization

XML Serialization serialize only public fields, properties of an object and parameters and return value of a method. That is why it is called Shallow Serialization.  XML serialization results in strongly typed classes with public properties and fields that are converted to XML. System.Xml.Serialization has all the classes and method need for XML serialization.
 

Example

The bellow example serialize a string array using XML Serialization and store it to a XML file. And again deserialize  from that xml file to a string array.



using System;
using System.IO;
using System.Xml.Serialization;
namespace Example_Serialization
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Serializing a string array and store it in country.xml");
            string[] country = new string[] { "India", "USA", "UK", "Australia" };
            XmlSerializer serialize = new XmlSerializer(typeof(string[]));
            StreamWriter writer = new StreamWriter("country.xml");
            serialize.Serialize(writer, country);
            writer.Close();

            Console.WriteLine("Deserializing a string array from country.xml");
            country = null;
            using (Stream streamload = new FileStream("Country.xml", FileMode.Open))
            {
                country = (string[])serialize.Deserialize(streamload);
                foreach (var str in country)
                {
                    Console.WriteLine("{0}", str);
                }
            }
            Console.ReadKey();
        }
    }
}
 

Serialization and Deserialization in C#

Serialization is a process of converting object into stream of bytes. And deserialization is a process of getting object back from serialization form.

According to MSDN "Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization."

The bellow figure shows how serialization works.


















Deserialization is just opposite of serialization. It is the mechanism to getting object back from stream of bytes. 



















There are three types of serialization mechanism available in C#.


  • XML Serialization
  • Binary Serialization
  • Soap Serialization


XML Serialization

XML Serialization serialize only public fields, properties of an object and parameters and return value of a method. That is why it is called Shallow Serialization.  XML serialization results in strongly typed classes with public properties and fields that are converted to XML. System.Xml.Serialization has all the classes and method need for XML serialization. more

Binary Serialization

Binary serialization uses binary encoding to produce compact serialization for uses such as storage or socket-based network streams. It is also known as deep serialization. Because it serialize every thing of an object. more

SOAP Serialization

SOAP serialization serialize an object into XML stream with SOAP standard. This serialization is used to transmit data over network. Most common area where SOAP serialization is used is web services. more



Download

You can download examples and source code from here.

Wednesday, June 19, 2013

How to send email using C#

C# provides many built in exiting features to make developer life easy. SmtpClient class is one of them. SmtpClient has every thing that we need to send email from our application.

Namespace : System.Net

The following program illustrate how to send email using SmtpClient from our Asp.Net application.

SmtpClient s = new SmtpClient();
s.Host = "smtp host"; // here enter smtp host, for google = smtp.gmail.com
s.Port = 25;
s.UseDefaultCredentials = false;
MailMessage m = new MailMessage();
m.To.Add("xxx@xxx.com"); // enter reciepent email address
m.From = new MailAddress("xxx@xxx.com"); // enter sender email address
m.Subject = "xxxx"; // mail subject
m.Body = "xxxxxxxxx"; // mail body
m.Priority = MailPriority.High;
s.Credentials = new NetworkCredential("userid", "password"); // for gmail user id is your email address, password is your gmail password.
//s.EnableSsl = true; // for gmail remove the comment
s.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
            s.Send(m);
            Response.Write("done")
}
catch (Exception ex)
{
            Response.Write(ex.Message.ToString());
}
 


Some times the above code gives an error "Require authenticaton" after giving all correct details. It means your smtp server require mail body level authentication. In such case use the following code



Namespace : System.Web.Mail

MailMessage Message = new MailMessage();
Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "xxx@xxx.xxx"); // user id (email)
Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "xxx"); // password
Message.To ="xxx@xxx.xxx";
Message.From ="xxx@xxx.xxx";
Message.Subject = "xxx";
Message.Body = "XXXXXXXXXXX";
try
{
            SmtpMail.SmtpServer = "xxx.xxx.xxx.xxx";
            SmtpMail.Send(Message);
}
catch (System.Web.HttpException ehttp)
{
            Response.Write(ehttp.Message.ToString());
}