Monday, June 27, 2011

PIVOT/UNPIVOT expression in SQL Server.

Pivot expression in SQL converts values returned by a query into columns. For example in below example, the temp table contains revenue data for different months for companies. If the result has to be displayed with each month as columns , then it can done easily using PIVOT expression.

Create temp table to store data
CREATE table #tmp (comp_id int,comp_name varchar(20), [month] int,rev int)


insert into #tmp values (200,'comp1',1,32144)
insert into #tmp values (200,'comp1',2,56234)
insert into #tmp values (200,'comp1',3,1000)
insert into #tmp values (211,'comp2',1,2364)
insert into #tmp values (211,'comp2',2,8762)
insert into #tmp values (211,'comp2',3,7644)
insert into #tmp values (211,'comp2',3,1111)
insert into #tmp values (211,'comp2',3,1111)
insert into #tmp values (213,'comp3',3,1111)

Now if we want to show the month as columns (like ‘1’,’2’,’3’ etc) we can use PIVOT expression as given below

 (SUM(rev) FOR [month] IN ([1],[2],[3])) pvt


We can also UNPIVOT the result as given below

/*get  ‘pivot’ data into another temp table #tmp2*/

SELECT * INTO #tmp1 FROM #tmp t PIVOT 
 (SUM(rev) FOR [month] IN ([1],[2],[3])) pvt

/*UNPIVOT the data*/
 (rev FOR [month] IN ([1],[2],[3])) pvt

Friday, June 24, 2011

Generating Excel file using .NET

Given below is an example of how to create excel file using .NET (C#)

Excel has to be installed on the machine for the below example to work, since EXCEL COM object is used to generate excel file

1. Create a (C#) console application in Visual Studio

2. Add reference to “Microsoft.Office.Interop.Excel”

3. import the required namespaces

using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Text;
using System.Data;
using System.Runtime.InteropServices;

4. The function to create EXCEL is given below

public void WriteToExcel(System.Data.DataTable dtResult, string strFileName, string strDirectoryName)
    Application xlApp = default(Application);
    Workbook xlWorkBook = default(Workbook);
    Worksheet xlWorkSheet = default(Worksheet);

    string fName = strFileName = strDirectoryName + strFileName;

        object misValue = Missing.Value;
        xlApp = new ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);

        int iRow = 1;
        int iColumn = 1;

        /*Add header to excel File*/
        StringBuilder oBuilder;
        oBuilder = new StringBuilder();
        foreach (DataColumn dc in dtResult.Columns)
            if (dc.ColumnName != null)
                xlWorkSheet.Cells[iRow, iColumn] = dc.ColumnName;
                xlWorkSheet.Cells[iRow, iColumn] = "";

            iColumn = iColumn + 1;

        /*Add data to excel File*/
        foreach (DataRow dr in dtResult.Rows)
            iColumn = 1;
            iRow = iRow + 1;
            oBuilder = new StringBuilder();
            foreach (DataColumn dc in dtResult.Columns)
                if (dr[dc.ColumnName] == null || dr[dc.ColumnName] == DBNull.Value)
                    xlWorkSheet.Cells[iRow, iColumn] = "";
                    xlWorkSheet.Cells[iRow, iColumn] = dr[dc.ColumnName].ToString();
                iColumn = iColumn + 1;

        xlWorkBook.SaveAs(fName, XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);


        if (xlApp != null)

        if (xlApp != null)
        if (xlWorkBook != null)
        if (xlWorkSheet != null)

        if (xlApp != null)

5. Now call the function by passing in the datatable ,excel name and folder path

DataTable dt = new DataTable();

DataRow dr = dt.NewRow();
dr[0] ="Name1";
dr[1] = "12";

WriteToExcel(dt, "test.xls", @"Path");

Tuesday, June 21, 2011

Delegates And Events in .NET

Today I was working on a project which required the use of 'delegates'. I wanted to see the difference in calling a function using delegates and by events; so created a simple example to show the difference in invoking methods using events and delegates.

Delegates are function pointers in .net. The advantage of using delegates is that the calling program can define the function for a specific task. For example, let us consider the logging of message or exceptions in an application. We can just expose a delegate with signature “public delegate void LogMessage (string msg);” and the calling program can decide whether to do the logging in file or database or to display in console/UI.

An event is a message sent by an object to signal the occurrence of an action.Events are raised in response of an user action or it could be program triggered. It normally has the sender and event arguments as input parameters. But for the example below, I am comparing delegate and event calls and not using sender/event argument parameters

1) Create a console application in .NET (C#).

2) Create a delegate as given below in 'Program.cs'

public delegate void LogMessage(string msg);

3) Create a class (DelegateTestClass) for delegate test

public class DelegateTestClass
        public LogMessage MessageLogger { get; set; }

        public void PerformTask1()
            MessageLogger("Performing Task1");

        public void PerformTask2()
            MessageLogger("Performing Task2");

4) Create a class for Event test as given below

class EventTestClass
        public event LogMessage MessageLogger;

        public void PerformTask1()
            MessageLogger("Performing Task1");

        public void PerformTask2()
            MessageLogger("Performing Task2");

5) In “Program.cs” create a function to handle the delegate and event

private static void ShowMessage(string strMsg)

6) Now call the event and delegate from ‘Main’ as given below

static void Main(string[] args)
            DelegateTestClass oDelegateTest = new DelegateTestClass();
            /*Specify the function to handle the message logging*/
            oDelegateTest.MessageLogger = new LogMessage(ShowMessage);


            EventTestClass oEventTest = new EventTestClass();
            /*Attach function to the event*/
            oEventTest.MessageLogger += new LogMessage(ShowMessage);



Friday, June 10, 2011

Convert image to binary and upload to database using ASP.NET

This article is about uploading images to server/database using ASP.NET. For uploading an image to database ,it has to be first converted to binary format. Then it has to be saved to a database table; the table should have a column with data type [image] for storing the binary image data.

Ok, enough of theory. Let us try out an example.

1) Create a ASP.NET web application using VS2008/2010

2) In default.aspx provide a input control of type “file” and a button

<input type="file" runat="server" id="photoupload" />
<asp:Button runat="server" ID="btnSave" Text="Save" onclick="btnSave_Click"/>

3) Create a function to convert stream to byte[]

public byte[] StreamToByteArray(Stream input)
    byte[] total_stream = new byte[0];
    byte[] stream_array = new byte[0];
    byte[] buffer = new byte[1024];

    int read = 0;
    while ((read = input.Read(buffer, 0, buffer.Length )) > 0)
 stream_array = new byte[total_stream.Length + read];
 total_stream.CopyTo(stream_array, 0);
 Array.Copy(buffer, 0, stream_array, total_stream.Length, read);
 total_stream = stream_array;

    return total_stream;

4) In the button click event, write code to get the stream from uploaded image and convert to byte array.(Import System.IO- using System.IO;)

Stream oStream = photoupload.PostedFile.InputStream;
byte[] arr = StreamToByteArray(oStream);

5) Now pass the byte[] data to database

SqlConnection oConnection= new SqlConnection("[connectionstring]”);
SqlParameter oParam1 = new SqlParameter("@data", arr);
oParam1.DbType = System.Data.DbType.Binary;
SqlParameter oParam2 = new SqlParameter("@description", photoupload.PostedFile.FileName);

SqlCommand oCommand = new SqlCommand(“[storedprocname]”);

oCommand.CommandType = CommandType.StoredProcedure;
oCommand.Connection = oConnection;
int i = oCommand.ExecuteNonQuery();

Done! Now the image is saved in database.

6) Code snippet for getting the binary data back from database is given below

/*Get binary data into dataset*/
DataSet ds = oDal.GetData("[stored procedure name]" + photoid.ToString());

byte[] arr = (byte[])ds.Tables[0].Rows[0]["data"];
MemoryStream oStream = new MemoryStream(arr);
Response.ContentType = "image/png";

Wednesday, June 1, 2011

C#.NET and Greenplum

This article is about connecting to greenplum (GP) database using C#.NET. Greenplum DB is based on the open source database PostgreSQL.

Greenplum database is optimized for faster searches. For searching data in tables having millions of rows, Greenplum is really fast.

Given below is a C# example for opening a connection to GP database and executing a search query.

1) The first step is to download the dll which connects to GP. It is called Npgsql.dll. It can be downloaded from

2) Create a C#.NET console application using Visual Studio.

3) Create a new file for GP connection. Lets name it GPDData.cs

4) Copy the dll to a local folder in the project and add a reference to the dll from project. Or you can register it in Global Assembly Cache using "gacutil".

5) Include the namespace

using Npgsql;

6) In the GPData class create method to execute query in greenplum as given below.

public DataSet FillDataSet(string strCommand,string strConnection)
NpgsqlConnection oConnection = new NpgsqlConnection(strConnection);
DataSet ds = new DataSet();

NpgsqlCommand oCommand = new NpgsqlCommand(strCommand, oConnection);
NpgsqlDataAdapter oAdp = new NpgsqlDataAdapter();
oCommand.CommandTimeout = 100;
oAdp.SelectCommand = oCommand;


return ds;

public void CloseConnection()
if (oConnection.State == System.Data.ConnectionState.Open)

7) Now you can execute query by calling the method as given below.

GPData oData = new GPData();
DataSet ds = oData.FillDataSet([command],[connectionstring]);

Tuesday, May 31, 2011

Parallel Processing in .NET 4.0

I was reading about the new features of .net 4.0 today and found the new parallel processing feature really interesting. The new parallel processing class is called “Task” and it is available in the namespace “System.Threading.Tasks”

The example given below is a comparison of how functions are called in thread model and in the new parallel task way. Though I have included the time taken for to execute the task by each method (thread and task), this example is not specifically to compare performance. It is more about the difference in invoking functions.

I used VS2010 express edition for this test. Though it is easy to do the threading tests in console application, I did this in web application. I implemented ‘ICallbackEventHandler’ and did the example in the “RaiseCallbackEvent” function. For simplicity you can use a console application also.

1) Create a function which does looping as given below

 public string Task1(int iCount)
            DateTime dtStart = DateTime.Now;
            StringBuilder oBuilder = new StringBuilder();
            for (int i = 0; i < iCount; i++)
            DateTime dtEnd = DateTime.Now; 
            string strReturn = "Time Taken for Method2 " + dtStart.ToLongTimeString() + "- " + dtEnd.Subtract(dtStart).TotalMilliseconds.ToString(); 
            return strReturn;
2) Since the “ThreadStart” object takes a pointer to void function, I created 4 other functions to test “Thread”
private void Task1Thread()
str1 = "\n" + Task1(500000);
private void Task2Thread()
str2 = "\n" + Task1(600000);

private void Task3Thread()
str3 = "\n" + Task1(700000);

private void Task4Thread()
str4 = "\n" + Task1(800000);
3) And then I wrote the code to call the functions as below.
DateTime dtStart = DateTime.Now;
switch (eventArgument)
case "1":// sequential 
data = Task1(500000);
data = data + "\n" + Task1(600000);
data = data + "\n" + Task1(700000);
data = data + "\n" + Task1(800000);
case "2": //Task - the NEW parallel processing way in .NET 4.0

Task<string> mytask1 = Task<string>.Factory.StartNew(() => Task1(500000));
Task<string> mytask2 = Task<string>.Factory.StartNew(() => Task1(600000));
Task<string> mytask3 = Task<string>.Factory.StartNew(() => Task1(700000));
Task<string> mytask4 = Task<string>.Factory.StartNew(() => Task1(800000));

data = mytask1.Result;
data = data + "\n" + mytask2.Result;
data = data + "\n" + mytask3.Result;
data = data + "\n" + mytask4.Result;

case "3":// Thread – common method of multi threading in .NET 1.1, 2.0

Thread oThread1 = new Thread(new ThreadStart(Task1Thread)); 
Thread oThread2 = new Thread(new ThreadStart(Task2Thread));
Thread oThread3 = new Thread(new ThreadStart(Task3Thread));
Thread oThread4 = new Thread(new ThreadStart(Task4Thread));



data = str1 + str2 + str3 + str4;

DateTime dtEnd = DateTime.Now;
string finalTime = "Total Time Taken - " + dtStart.ToLongTimeString() + "- " + dtEnd.Subtract(dtStart).TotalMilliseconds.ToString();

data = data + "\n" + finalTime;

You can see that calling methods using “Task” object is much easier than thread. And also its more efficient than using thread.

Friday, May 20, 2011

ASP.NET and HighCharts

High charts ( ) is a really nice tool to generate graphs/reports on web applications. This article is about how to use high charts in ASP.Net and also shows how to pass data from .net to high chart control (JS/JQuery function) using JSON.

The charts generated by HighCharts control are really nice and have lots of client side features like zoom, selecting/highlighting series etc.

Before starting the example, we need two JS files for this. Both can be obtained from high charts website ( ). The javascript file required are ‘highcharts.js’ and ‘jquery-1.4.1.min.js’ let us develop an ASP.NET web application which displays high-chart graph.

1 Create a new web application using Visual Studio

2 Include the two js files inside the head tag of default.aspx

<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="Scripts/highcharts.js"> </script>

3) Now we need X and Y coordinate data to generate the graph. Let us first create X-axis data. Since we are going to generate a revenue graph, let us include year as X-axis. Add the below code in code behind page, in page_load event

/*X axis coordinates*/
List<int> lstXaxis = new List<int>();

4) Create public properties for X and Y axis so that they can be accessed from aspx page.

public string Series1 { get; set; }
public string Xaxis { get; set; }

5) Using JavascriptSerializer, convert the x-axis data to Json

JavaScriptSerializer oSerializer = new JavaScriptSerializer();
Xaxis= oSerializer.Serialize(lstXaxis);

6) Let us now generate Y-axis data (revenue data). Create a class to store the Y-axis data

public class ChartEx
public string name { get; set; }
public List<int> data{ get; set; }

7) Fill Y-axis object with data and serialize it using Javascript serializer

/*Series1 - Yaxis*/
ChartEx oEx = new ChartEx(); = new List<int> (); = "Revenue";;;;;

JavaScriptSerializer oSerializer1 = new JavaScriptSerializer();
Series1= oSerializer1.Serialize(oEx); ;

8) Create a div container in aspx page. The graph will be rendered in this container.

<div id="container" > </div >

9) Now call the Javascript function to draw the graph and pass the serialized C# object to javascript function. (Place the below code inside script tags)


function DrawMyGraph1 () {

chart = new Highcharts.Chart({
chart: {
renderTo: 'Container',
defaultSeriesType: 'area'
title: {
text: 'Revenu'
subtitle: {
text: 'Source: Test '
xAxis: {
categories: <%=Xaxis %>
yAxis: {
title: {
text: 'Revenue Vs Profit'
tooltip: {
formatter: function () {
return + ' produced ' +
Highcharts.numberFormat(this.y, 0) + 'revenue in ' + this.x;
series: [<%=Series1 %>]

Done ! Now run the application and you can see the hightchart graph rendered in UI.

There are a lot of useful client side functionalities provided by this graph component like - zooming , highlighting specific graphs etc. Try it out an you will be amazed by how powerful this tool is.

Thursday, May 19, 2011

Video Streaming in ASP.NET using Silverlight

This article is about how to use Silverlight to stream videos in ASP.Net application.

I used Visual Studio 2010 express edition and Silverlight 4.0 (ASP.NET 4.0) for this example. In below example we will just focus on a simple video streaming example. We will look at how to implement progress bar, stop/start buttons etc in another post.

So, let us look at how to create an ASP.NET web application with video streaming.

1 Create a new Silverlight application from Visual studio 2010. Visual studio creates a test web application to test the Silverlight application. So you will have two projects in the solution.

2 In MainPage.xaml ,drag and drop the media element from toolbor. Or include the below XAML in the page

<MediaElement Height="153" HorizontalAlignment="Left" Margin="24,150,0,0" Name="mediaElement1" VerticalAlignment="Top" Width="462" AutoPlay="true" />

3. We have to now provide the video file path for the media element to play . For this test, I copied a video clip to a folder named “Video” in the test web application. Note that I did not copy the file to the Silverlight project folder, but it was placed inside the test web application.

4. Get the URL for the video file. (For my test it was http://localhost:[portnumber]/Video/WindowsMedia.wmv")

5.Set the path of the video file in the MediaElement.

<MediaElement Height="153" HorizontalAlignment="Left" Margin="24,150,0,0" Name="mediaElement1" VerticalAlignment="Top" Width="462" Source="http://localhost:[portnumber]/Video/WindowsMedia.wmv" AutoPlay="False" / >

That’s it ! Now run the application and you can see the video getting rendered in the web site.

We will look into how to implement progress bar , start/stop buttons etc in another post. Till then, happy coding!

Tuesday, May 17, 2011

ASP.NET and Json

JSON (Javascript Object Notation) is a language independent open standard for representing data. It is human readable and light weight compared to XML. JSON can be used to serialize objects and transmit data.

So - how do you convert .net objects to JSON and pass to javascript function. I could not find a good/simple example on this, which lead me to write the below example.

As always – lets go directly to example and see JSON and .net at work .

1) Create an ASP.Net application. Create a class which we will pass to javascript (client side) as JSON
public class ChartEx
public string name { get; set; }
public List<int> data{ get; set; }

2) In the page load of default.aspx ,create an instance of the object and fill data
ChartEx oEx = new ChartEx(); = new List(); = "Revenue";;;;;

3) Create a public property for the page.

public string Series1 { get; set; }

4) Serialize the object using Javascript serializer (in namespace Sytem.Web.Script.Serialization) And set serialized data to the public property.

JavaScriptSerializer oSerializer = new JavaScriptSerializer();
string strData = oSerializer.Serialize(oEx);
Series1 = strData;

5) Access the public property from ASPX page JS function inside script block
function ShowAlert()
var sdata =<%=Series1 %> ;

6) And call the js function in Load event of the page as given below.
<body onload="ShowAlert();">

Run the application and we can see that the .net object is serialized to a JSON object which can be now be used by a JS function. Isn’t that awesome (and easy)?

Monday, May 2, 2011

jQuery Basics

I wanted to learn jquery for long time, but kept postponing since it is possible to do most of the normal client functions that I do (like validation, showing alerts, pop up etc) using classic javascript itself. But when it comes to complex functions (like fading out/fading in controls or animation), doing it in javascript becomes difficult. And you have to worry about browser compatability too.

Thats the reason why I started to learn jQuery.... and it was pretty easy and really helpful.

Given below are the steps that I followed in creating a simple example.

1) The first thing to do is to download the jquery Js file from (When I downloaded the file the version was "jquery-1.5.1.min.js")

2) Create an html file and include the download js file in the html file

<script src="Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>

Ok... now we are ready to start using jQuery. Elements are accessed in jQuery as $("#controlId")... the same code in javascript would be "document.getElementById("controlId").

3) Let us set a value in textbox using jQuery

a) First Create a textbox and button control in html as given below

<input type="text" id="txtBox1" value="test" />

<input type="button" value="Set Value" onclick="SetValue();" />

b) Set text "Hello World" in text box using jQuery as given below

function SetValue() {
$("#txtBox1").val("Hello world")

Wasn't that easy. Let us look at some other simple functions of jQuery.

Fade Out

function FadeOut() {

Fade In

function FadeIn() {

Let us now see how to animate a div

Include a div element in html
<div id="divAnimate" class="ui-dialog" style="display:none;border:1px solid gray;width:0px;">
<div class="ui-widget-header" style="width:300px;">
Just a box

Include 2 buttons to invoke 'hide' and 'display' animations

<div class="codeBlock">
<input type="button" value="Animate-Display" onclick="Animate_Display();" />
<input type="button" value="Animate-Hide" onclick="Animate_Hide();" />
</div >

Include script for "hide" and "display" functions

function Animate_Display() {
$("#divAnimate").css({ "display": "block", "overflow": "auto" });
$("#divAnimate").animate({ width: "300px",height:"300px" }, 1000);
function Animate_Hide() {
$("#divAnimate").animate({ width: "0px", height: "0px" }, 1000, function() {
function Animation_Complete() {
$("#divAnimate").css({ "display": "none", "overflow": "auto" });

Monday, April 18, 2011

Consuming ReST Service

Today let us review how to consume the ReST service that was created in previous post.

Given below are 3 ways to consume the service

1) By using XMLDocument

XmlDocument oDoc = new XmlDocument();

2) Using Http Request

HttpWebRequest oRequest = (HttpWebRequest)WebRequest.Create("http://localhost:49492/UserService.svc/users/World");
HttpWebResponse webResponse = (HttpWebResponse)oRequest.GetResponse();
Stream receiveStream = webResponse.GetResponseStream();
StreamReader oReader = new StreamReader(receiveStream);

3) Using Channel Factory

ChannelFactory factory = new ChannelFactory(new WebHttpBinding(), new EndpointAddress("http://localhost:49492/UserService.svc"));
factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
IUserService proxy = factory.CreateChannel();

int i = proxy.PutUserAccount("world", "newval");

Monday, April 4, 2011

ReST Application using WCF

This article is about creating a simple ReST(Representational State Transfer) application using WCF. Using ReST model of communication, web services can be invoked without the WSDL.

Let us go through an example on how to develop a ReST application

1) Create a WCF application in VS 2008
(File -> New project-> Select "WCF Service Application" (Under Visual C#, Web))
Visual Studio will create service file (Service1.svc and IService1.cs)

2) Add reference to "System.ServiceModel.Web" ( This is required for "WebGet" Attribute that is used in interface method definition )

Let us reuse IService.cs for our example.

3) Create a new method definition in IService1 as given below

[WebGet(UriTemplate = "users/{username}")]
string GetFullName(string username);

4) Implement the interface method in Service1.svc as given below

public string GetFullName(string username)
return "Hello " + username;

5)In web.config make below 2 changes

 a) Remove the existing endpoint and add the new endpoint

<endpoint address="" behaviorconfiguration="webHttp" binding="webHttpBinding" contract="RestTestApp.IService1">
<dns value="localhost">

 b) Include endpoint behavior for webHttp. This should be inside tag

<behavior name="webHttp">

6)The development of ReST application is complete! Run the application.

Navigate to -
http://localhost:{Port if using Development server}/UserService.svc/users/test

This will return an xml

With ReST model , we are now able to access the service without passing the parameters in XML (SOAP). The service can be accessed and executed using a simple http webrequest.

We will look at how to consume this ReST application in later articles.

Till then, happy coding.

Friday, April 1, 2011

Callback Feature in ASP.NET

The callback feature in ASP.NET helps to display content in webpage in an asynchronous way.

Lets go straight to an example and get it working.

1)Create a web application in VS 2008

2)In Page Load of "Default.aspx.cs" , enter the following code

/*Client function to Receive Server Data*/
string strReceiveServerData = "function ReceiveServerData(arg,context){RecieveServerDate2(arg);}";

/*Get Callback Reference*/
string strReceiveCallReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", strReceiveServerData);

/*Client function to Call Server... the reference of "Receive server data" function is added here*/
string strCallTheServer = "function CallServer(arg,context){" + strReceiveCallReference + ";}";

/*Register the script*/
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", strCallTheServer, true);

3) Inherit interface “ICallbackEventHandler” in page

public partial class AsyncServerCall : System.Web.UI.Page,ICallbackEventHandler

4) Add method code for interface "ICallbackEventHandler" in "Default.aspx.cs"

#region ICallbackEventHandler Members

string strVar = "";
public string GetCallbackResult()
return strVar;

public void RaiseCallbackEvent(string eventArgument)
strVar = "Hello World," + eventArgument;


5) Add below Javascript to aspx page. Make sure you add "script" tags.

function RecieveServerDate2(arg) {

6) And the final step... call the javascript function to make server call in body onload

<body onload=" CallServer('Guys', '');" >

Run it! And you will get an alert “Hello World, Guys”. Wasn’t the callback easy in ASP.NET?

Thursday, March 31, 2011

Generics and LINQ

Generics is a feature that is very useful in ASP.NET. If generic collection is used to store data then quering data from the collection becomes really easy.
Given below is a simple example for creating a generic collection and quering from it using LINQ.

1) Create an object collection
a) Define the object "Employee"

public class Employee
public Employee(int iID, string strName, string strAddress, int iAge)
ID = iID;
Name = strName;
Address = strAddress;
Age = iAge;
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public int Age { get; set; }

b)Add objects to collection

public List GetEmployees()

List<Employee> lstEmps = new List<Employee>();

lstEmps.Add(new Employee(1, "Emp 1", "212 Street1", 34));
lstEmps.Add(new Employee(2, "Emp 2", "543 Street2", 31));
lstEmps.Add(new Employee(3, "Emp 3", "3332 Street2", 27));
lstEmps.Add(new Employee(4, "Emp 4", "1011 Street2", 40));
lstEmps.Add(new Employee(5, "Emp 5", "3214 Street4", 33));
lstEmps.Add(new Employee(6, "Emp 6", "5543 Street1", 35));

return lstEmps;

2) Query collection using LINQ

List<employee> EmpList =GetEmployees();

/**LINQ Examples**/

//Select employees with age > 30
List<employee> emps1 = (from x in EmpList where x.Age > 30 select x).ToList();

//Select employees with name starting with "Emp"
List<employee> emps2 = (from x in EmpList where x.Name.StartsWith("Emp") select x).ToList();

//Select employee with address "212 Street1"
List<employee> emps3 = (from x in EmpList where x.Address == "212 Street1" select x).ToList();

Delete Duplicate Rows from SQL Server Table

This example is about deleting duplicate rows in SQL server table. In this example duplicate records are deleted from the table based on rank.

/*Create temp table*/
create table #tmp(id int,name1 varchar(20),cre_date datetime)

/*Insert rows with duplicate data in it*/
insert into #tmp values(1,'name1','2011-03-30 9:00 am')
insert into #tmp values(1,'name1','2011-03-30 9:20 am')
insert into #tmp values(2,'name2','2011-03-30 9:30 am')
insert into #tmp values(3,'name3','2011-03-30 9:40 am')
insert into #tmp values(3,'name3','2011-03-30 9:50 am')
insert into #tmp values(3,'name3','2011-03-30 9:55 am')

/*Delete the rows that are duplicate*/
with t as (
Select id,name1,row_number() over (partition by id,name1 order by cre_date) rnk from #tmp )
delete from t where rnk>1