INTRODUCTION
Before we get in the learning details I would like to share a story with you all, It was 2009, very harsh times for all IT people in the world. The whole world is in its worst recession ever and its even worse for IT people all over the world. It was hard to keep the job we have and even harder for people to get an interview for a job. But, I luckily managed to get an interview with one of the IT companies here in VA. I thought I was lucky and intelligent enough to get an interview scheduled, but Later I decided was all wrong.
The only question I was asked is what is difference between AJAX an JavaScript. I was a big fool back then, i didn't know the difference but I tried to come up with an answer but I was totally wrong and like you all are guessing I didn't get through the Interview. But the good thing is that I got fired up and thought I wanted to know all about AJAX.
I wanted to share my experiences with you all the easy processes I found over the course of learning AJAX. This course is divided into 10 Parts which will discuss everything in detail. Please leave comments or suggestions about these posts.
Without any further delay lets Jump into Part 1
HISTORY
In the early days of web applications and desktop applications that used internet (Web 1.0 times) for data processing the user has to wait for the server's response and the web page used to flash once before it displayed the result. For example, if the user is filling in a registration form for his flight, after filling in his/her information he/she needs to wait till the application talks to the server and get a result for him/her. Which was good for few year until Google really took the idea of Web 1.0 to Web 2.0 (a whole new leap forward in the web technology).
This is where AJAX came into picture and changed the way how we see the Web. Very good example for AJAX at its best is Google Maps and Google's Instant Search which gives you search results while you were typing.
What actually happens is that Google get the "text_changed" event on the search box and uses AJAX to get the results for the user instantly. Since we know what the result would look like if we use AJAX, lets get into the tricks and great things AJAX can do for us and for our applications (either web or desktop).
The only and very important object that should be understood to learn AJAX is XMLHttpRequest. This is a simple javascript object which can be instantiated as below
var request = new XMLHttpRequest();
This is a very simple javascript object, but the AJAX capabilities comes into picture on where and how we use this object. Usually when a user is filling a form and click on a submit button the data is taken from the form and then sent to the server to process, once we get some result from the server the screen flashes and goes to the next page. This is where AJAX comes into picture. Instead we sending the data directly to the server, the data is sent to the javascript object and then to the server. while javascript talks to the server and gets a result for the user the screen doesn't flash and the process is more seamless, which can be called as Web 2.0. With out the user intervention, javascript code talks to the server and gets the data which can be shown directly to the user or can also be used to do some further processing by some javascript code on the client machine. Everything is done without the user noticing any kind of flash screens etc. That is the power of XMLHttpRequest.
Adding some spices
Once you have the XMLHttpRequest do its magic we can do basic stuff like
-- Get form data (raw data from the server)
-- Change values on the data that we got from the server
-- Parse HTML and XML (see next chapter)
we will talk about the third point later in the next chapter, and to be able to do first and second we have to make ourselves familiar with "getElementById()" method. This method can be used to get or set values.
Which can be used as below
//Get the value of nameTextBox and save it to "name" variable
//here nameTextBox is the id property of a textbox
var name = document.getElementById("nameTextBox").value;
//Set some values from the response to the controls, here response is an array
document.getElementById("nameTextBox").value = response[0];
document.getElementById("phoneTextBox").value = response[1];
Once you have a clear understanding on XMLHttpRequest, the rest of the code is just raw javascript.
STAY TUNED....
for .NET Beginners
Wednesday, October 6, 2010
Monday, July 27, 2009
Everything Combo Box
Hi Everyone,
This post is exclusively for Combo Box Control, that we use a lot either in our web or window based applications. We all know the purpose of this control, what and how we can use the control depending on our requirement. But there are always a few very basic things that we are important and simple at the same time.
Combo Box control is almost like a list control that shows list of options or data that you can view or can select from , but the main advantage over list control is, Combo Box will show only one selected value and holds the list that is shown on a button click. A very helpful tool to provide various options to the user and also can save lot of work space and also hold rich features that server our purpose.
It wont be hard to find a solution but i just thought why not keep everything in one post from the basic usage to data binding.
This post will be updated constantly with new tips or tricks that we can get from this Combo Box control. Every Tip or Trick will be in a form of FAQ. you have a question and an answer for that question.
I guess this approach will be a straight forward and very helpful way for many Developers.
Lets start basic and then go deep into the usuage.
NOTE: The code shown in this post will be in C#.
1. How to Use a Combo Box Control in C# (Web/Windows Application)
Combo Box Control comes with the default controls for every ASP.NET or C# or VB.NET or Silverlight or WPF etc.. Projects.
When ever you create a new project in VS, this control is present in the ToolBox Window of the application. You can always drag drop the control to the Application Window (Work Area), which will be the easiest way to do. But you can also do the same using code, like below:
In ASP.NET:
This post is exclusively for Combo Box Control, that we use a lot either in our web or window based applications. We all know the purpose of this control, what and how we can use the control depending on our requirement. But there are always a few very basic things that we are important and simple at the same time.
Combo Box control is almost like a list control that shows list of options or data that you can view or can select from , but the main advantage over list control is, Combo Box will show only one selected value and holds the list that is shown on a button click. A very helpful tool to provide various options to the user and also can save lot of work space and also hold rich features that server our purpose.
It wont be hard to find a solution but i just thought why not keep everything in one post from the basic usage to data binding.
This post will be updated constantly with new tips or tricks that we can get from this Combo Box control. Every Tip or Trick will be in a form of FAQ. you have a question and an answer for that question.
I guess this approach will be a straight forward and very helpful way for many Developers.
Lets start basic and then go deep into the usuage.
NOTE: The code shown in this post will be in C#.
1. How to Use a Combo Box Control in C# (Web/Windows Application)
Combo Box Control comes with the default controls for every ASP.NET or C# or VB.NET or Silverlight or WPF etc.. Projects.
When ever you create a new project in VS, this control is present in the ToolBox Window of the application. You can always drag drop the control to the Application Window (Work Area), which will be the easiest way to do. But you can also do the same using code, like below:
In ASP.NET:
Monday, July 20, 2009
Pie Chart in Silverlight with WCF - (Part Final of Many)
Please see the previous post...
Lets put in the code that actually draws the pie chart in the chart control.
To show the data in our Pie Chart, we need the WCF to service reference in our Silverlight project, to do that right click on the refereces folder in the Silverlight project “PieChart” and click on “Add Service Reference”.
Below is the window, that adds service reference to our silverlight project.

Click on “Discover” and it will find our WCF service, and make sure you have the method on the right under “Operations”. Click on OK to add the WCF as Service reference to our Silverlight Project.
You can give any name to your service reference like anything related, but as this is just one Service reference I am just going by default name “ServiceReference1”.
So now make the following changes to your MainPage.xaml
Now build your project, goto Build\Build Solution, and run the program, go to
Debug\Start Without Debugging (Ctrl+F5)
It runs the program and you will get an output like below

Click on Generate Button and the final output will be below

To See all parts for Pie Chart in Silverlight with WCF, please click on the link to the right that says it.
You can download the final version of the project and full version of the post in a word document in the final part of this post.
Please do comment or leave any suggestions or questions below, I will reply immediately. You may also leave any requests for new posts.
Thank you, See you soon with a new post.
Lets put in the code that actually draws the pie chart in the chart control.
To show the data in our Pie Chart, we need the WCF to service reference in our Silverlight project, to do that right click on the refereces folder in the Silverlight project “PieChart” and click on “Add Service Reference”.
Below is the window, that adds service reference to our silverlight project.
Click on “Discover” and it will find our WCF service, and make sure you have the method on the right under “Operations”. Click on OK to add the WCF as Service reference to our Silverlight Project.
You can give any name to your service reference like anything related, but as this is just one Service reference I am just going by default name “ServiceReference1”.
So now make the following changes to your MainPage.xaml
Now build your project, goto Build\Build Solution, and run the program, go to
Debug\Start Without Debugging (Ctrl+F5)
It runs the program and you will get an output like below
Click on Generate Button and the final output will be below
To See all parts for Pie Chart in Silverlight with WCF, please click on the link to the right that says it.
You can download the final version of the project and full version of the post in a word document in the final part of this post.
Please do comment or leave any suggestions or questions below, I will reply immediately. You may also leave any requests for new posts.
Thank you, See you soon with a new post.
Pie Chart in Silverlight with WCF - (Part 3 of Many)
So Lets start creating a web service and calling the web service in our siverlight application. We use LINQ to SQL to access data from the database. As we just said the data is will be on the server side we need to create a web service on the server side project that Visual studio created for us “PieChart.Web”. Follow the below steps to create a web service.
1. Right click on “PieChart.Web” project and click on Add Item to add a new “LINQ to SQL” file.

You can give any name to the file, but I am just going with the default name “DataClasses1.dbml”.
Click on OK, this adds “DataClasses1.dbml” file to our Web project and also opens a window where you were asked to select the database and its tables that we wanted to use for our project.

Make sure the window is named “DataClasses1.dbml” and one the left it should say “Server Explorer” . In case if you cant see this window , you can always click on “Server Explorer” link in the center of the screen.
2. Once you have the server explorer window on the left, right click on “ Data Connections” and select Add Connection. This opens the following window where you can select the type of database

Click on Continue , which opens a new window that asks us to select the database from our database server. Which looks like this,

Select the Server Name from the list and select the database from the bottom list. Click on OK that shows the database in the “Server Explorer” window to our left.
After it shows your database in the server explorer window, you select the database and go down to select the necessary database (in our case it is ExpensesDatabase) and drag the table from the left to the right window. Which will look like below.

3. As the data is at the server side and the calls are made from the client side we need to make the talking searlizable so click on the white part of the window and in the properties window select the below selected option.
Below is how your window should look after you make the connection searlizable.

4. Now that we added the database to our project, we have to add a web service that contacts the database and sends data to us. So right click on the web project “PieChart.Web” and select Add item to add “Silverlight Enabled WCF Service”. You can give any name you want to name the service but in this case I am just going with the default name.

Click on Add to add a WCF Service to your project.
5. Right after you added the WCF Service it gives you a default code that helps you to work further on it. The default code window looks like this

6. Please copy and paste the following code in the appropriate position so that we will be ready to call our web service and use the data in our PieChart.
Code:
public ExpenseTable[] GetExpense()
{
DataClasses1DataContext expenseCTX = new DataClasses1DataContext();
var expense = from exp in expenseCTX.ExpenseTables
select exp;
return expense.ToArray();
}
And after adding the above code the Service1.svc file looks like this.

7. Now that we have our WCF Done and Database done, its time to design a simple UI, with just a Button “Generate” and a Pie Chart Control to display the data.
Follow is the code that we have to put in the MainPage.XAML file in order to get the UI done.
In Silverlight the button control can be found by default but the Pie chart control is a special user control that can be only found by adding a reference to the .dll file in our Silverlight project.
Add “System.Window.Controls.Data.dll” and “System.Window.Controls.DataVisualization.dll”.
Right click on the “PieChart\References” and select Add reference and go to “Browse” tab and browse to the following path,
C:\Program Files\Microsoft SDKs\Silverlight\v2.0\Toolkit\Jul09\Bin\System.windows.Controls.DataVisualization.dll
If you don’t see jul09 or toolkit folder, don’t panic or feel bad about it, just download the jul09 Silverlight Toolkit.
Add the following code in the “MainPage.xml” in the between the columns. StackPanel is one of the Silverlight control that stacks various other controls that are put in the , in our case we put in a Button Control and a Chart Control in the stack panel.
This is how the above code looks when you run the program,

Checkout the Address, it shows the test project “PieChart.Web” that was created by Visual Studio.
And also look at the stack panel , how it stacked the controls up, a button and a chart control.
Next Part Continues...
To See all parts for Pie Chart in Silverlight with WCF, please click on the link to the right that says it.
You can download the final version of the project and full version of the post in a word document in the final part of this post.
Please do comment or leave any suggestions or questions below, I will reply immediately. You may also leave any requests for new posts.
1. Right click on “PieChart.Web” project and click on Add Item to add a new “LINQ to SQL” file.
You can give any name to the file, but I am just going with the default name “DataClasses1.dbml”.
Click on OK, this adds “DataClasses1.dbml” file to our Web project and also opens a window where you were asked to select the database and its tables that we wanted to use for our project.
Make sure the window is named “DataClasses1.dbml” and one the left it should say “Server Explorer” . In case if you cant see this window , you can always click on “Server Explorer” link in the center of the screen.
2. Once you have the server explorer window on the left, right click on “ Data Connections” and select Add Connection. This opens the following window where you can select the type of database
Click on Continue , which opens a new window that asks us to select the database from our database server. Which looks like this,
Select the Server Name from the list and select the database from the bottom list. Click on OK that shows the database in the “Server Explorer” window to our left.
After it shows your database in the server explorer window, you select the database and go down to select the necessary database (in our case it is ExpensesDatabase) and drag the table from the left to the right window. Which will look like below.
3. As the data is at the server side and the calls are made from the client side we need to make the talking searlizable so click on the white part of the window and in the properties window select the below selected option.
Below is how your window should look after you make the connection searlizable.
4. Now that we added the database to our project, we have to add a web service that contacts the database and sends data to us. So right click on the web project “PieChart.Web” and select Add item to add “Silverlight Enabled WCF Service”. You can give any name you want to name the service but in this case I am just going with the default name.
Click on Add to add a WCF Service to your project.
5. Right after you added the WCF Service it gives you a default code that helps you to work further on it. The default code window looks like this
6. Please copy and paste the following code in the appropriate position so that we will be ready to call our web service and use the data in our PieChart.
Code:
public ExpenseTable[] GetExpense()
{
DataClasses1DataContext expenseCTX = new DataClasses1DataContext();
var expense = from exp in expenseCTX.ExpenseTables
select exp;
return expense.ToArray();
}
And after adding the above code the Service1.svc file looks like this.
7. Now that we have our WCF Done and Database done, its time to design a simple UI, with just a Button “Generate” and a Pie Chart Control to display the data.
Follow is the code that we have to put in the MainPage.XAML file in order to get the UI done.
In Silverlight the button control can be found by default but the Pie chart control is a special user control that can be only found by adding a reference to the .dll file in our Silverlight project.
Add “System.Window.Controls.Data.dll” and “System.Window.Controls.DataVisualization.dll”.
Right click on the “PieChart\References” and select Add reference and go to “Browse” tab and browse to the following path,
C:\Program Files\Microsoft SDKs\Silverlight\v2.0\Toolkit\Jul09\Bin\System.windows.Controls.DataVisualization.dll
If you don’t see jul09 or toolkit folder, don’t panic or feel bad about it, just download the jul09 Silverlight Toolkit.
Add the following code in the “MainPage.xml” in the between the
This is how the above code looks when you run the program,
Checkout the Address, it shows the test project “PieChart.Web” that was created by Visual Studio.
And also look at the stack panel , how it stacked the controls up, a button and a chart control.
Next Part Continues...
To See all parts for Pie Chart in Silverlight with WCF, please click on the link to the right that says it.
You can download the final version of the project and full version of the post in a word document in the final part of this post.
Please do comment or leave any suggestions or questions below, I will reply immediately. You may also leave any requests for new posts.
Sunday, July 19, 2009
Pie Chart in Silverlight with WCF - (Part 2 of Many)
Implementation:
Open Microsoft Visual Studio 2008, go to FILE MENU and select CREATE\NEW PROJECT. Select “SilverlightApplication” on the right and make sure you window looks like below. And also make sure all the highlted fields are same and you can give any name to the project , but as we are doing a Pie Chart I named it as PieChart.

Click on OK to start working on our project. As Silverlight is a Client side application, it needs a host to run on the web browser. And below is the window how it looks (I am using Silverlight 3.0)

Make sure you have a good look at the highlighted fields, it will tell you that you need a server side host, like a web application to host the silverlight.
Points to be noticed:
1. Silverlight is a Client side application
2. It needs a server side application(like a web browser) to host the application
Click on OK to start your project.
As we selected the check box in the previous window to host our silverlight application it creates a new PieChart.Web project to our project we just created and below is how it looks in the solution explorer window and also gives us some sample code with the default namespaces and references.

The selected “PieChart.Web” is the host project that is created by Visual Studio to host our Silverlight application. And the PieChartTestPage.aspx is the file that is used to show in the browser.
And MainPage.xaml is the file that is where we do the programming for our PieChart, which is coded in XAML language. So let us just keep the “Piechart.Web” aside for a while and let’s work on MainPage.xaml.
Before we design out Pie Chart we need some data to show in the Pie chart. To draw any Pie chart we need two sets of values one set will be words and the second set will be numbers to relate the text. In Silverlight these set of values are denoted as “IndependentValueBinding” for the set of text and “DependentValueBinding” for the values set. So Lets give the data first in our database (SQL Server), Lets open SQL Sever Management Studio to create a database called “Expences” with a table called “ExpensesTable” with two attributes, Months(for IndependentValueBinding) and Expences (for DependentValueBinding).
Please see this post to create a database in SQLServer “Database Creation” (Caution: only for first timers).
As this post is for Silverlight, we are not discussing SQL Server and creating Tables in SQL Server. For any reference please see the post mentioned above.
Once you are done with creating Database and a Table, lets jump into Visual Studio to use the data for our PieChart.
Note: Silverlight is so fun to play with various builtin controls and animations etc, but when it comes to data binding and using data in our silverlight application we need a web service for the Silverlight Application to invoke data from the database.
The reason behind this is, as we know that Silverlight is a client side application and the data will always be on the server side, so we need a web service to read the server side data in our application.
Next Part Continues...
To See all parts for Pie Chart in Silverlight with WCF, please click on the link to the right that says it.
You can download the final version of the project and final version of the post in a word document in the final part of this post.
Please do comment or leave any suggestions or questions below, I will reply immediately. You may also leave any requests for new posts.
Open Microsoft Visual Studio 2008, go to FILE MENU and select CREATE\NEW PROJECT. Select “SilverlightApplication” on the right and make sure you window looks like below. And also make sure all the highlted fields are same and you can give any name to the project , but as we are doing a Pie Chart I named it as PieChart.
Click on OK to start working on our project. As Silverlight is a Client side application, it needs a host to run on the web browser. And below is the window how it looks (I am using Silverlight 3.0)
Make sure you have a good look at the highlighted fields, it will tell you that you need a server side host, like a web application to host the silverlight.
Points to be noticed:
1. Silverlight is a Client side application
2. It needs a server side application(like a web browser) to host the application
Click on OK to start your project.
As we selected the check box in the previous window to host our silverlight application it creates a new PieChart.Web project to our project we just created and below is how it looks in the solution explorer window and also gives us some sample code with the default namespaces and references.
The selected “PieChart.Web” is the host project that is created by Visual Studio to host our Silverlight application. And the PieChartTestPage.aspx is the file that is used to show in the browser.
And MainPage.xaml is the file that is where we do the programming for our PieChart, which is coded in XAML language. So let us just keep the “Piechart.Web” aside for a while and let’s work on MainPage.xaml.
Before we design out Pie Chart we need some data to show in the Pie chart. To draw any Pie chart we need two sets of values one set will be words and the second set will be numbers to relate the text. In Silverlight these set of values are denoted as “IndependentValueBinding” for the set of text and “DependentValueBinding” for the values set. So Lets give the data first in our database (SQL Server), Lets open SQL Sever Management Studio to create a database called “Expences” with a table called “ExpensesTable” with two attributes, Months(for IndependentValueBinding) and Expences (for DependentValueBinding).
Please see this post to create a database in SQLServer “Database Creation” (Caution: only for first timers).
As this post is for Silverlight, we are not discussing SQL Server and creating Tables in SQL Server. For any reference please see the post mentioned above.
Once you are done with creating Database and a Table, lets jump into Visual Studio to use the data for our PieChart.
Note: Silverlight is so fun to play with various builtin controls and animations etc, but when it comes to data binding and using data in our silverlight application we need a web service for the Silverlight Application to invoke data from the database.
The reason behind this is, as we know that Silverlight is a client side application and the data will always be on the server side, so we need a web service to read the server side data in our application.
Next Part Continues...
To See all parts for Pie Chart in Silverlight with WCF, please click on the link to the right that says it.
You can download the final version of the project and final version of the post in a word document in the final part of this post.
Please do comment or leave any suggestions or questions below, I will reply immediately. You may also leave any requests for new posts.
Pie Chart in Silverlight with WCF - (Part 1 of Many)
Silverlight:
This is a web development tool created by Microsoft to compete with the Adobe Flash player and its plugin. In my view it is almost getting there. To my knowledge we can do anything and everything that we can possibly do in flash (using action script).
Silverlight is quite a recent technology, released in 2007 as Silverlight 1.0 and now in just 2 year we have a very advanced version Silverlight 3.0. For me it used to be touch to program in Silverlight 1.0 where I know I can do great stuff, but the way we had to do is different than it is now. Microsoft also came up with a new suite called “Microsoft Expression” a combination of design and development tool for web designing and development. An Application called “Microsoft Expression Blend” which is a tool that makes our job much easy to develop a Silverlight Application.
Lets stop talking about the history and jump into the project.
Basics:
You can follow me in developing this application even though you don’t have any idea of Visual Studio, Silverlight, Expression Blend, XAML and WCF etc. because each and every step is explained in detail and also screenshots help you to connect the explanation to the project that we are going to do. In case if you are wondering, following are the necessary softwares that you will need to follow me with the project. You don’t have to stop reading the post even though you don’t have any of the below because, it might help you get an idea of how Silverlight and WCF mix together.
List of Softwares:
1. Visual Studio 2008 (Professional or Express Edition)
2. Microsoft Expression Blend (with SP1)
3. Microsoft SQL Server (Professional or Express Edition)
4. Silverlight 2.0 or 3.0 toolkit installed
you can download Silverlight 2.0 Toolkit here
you can download Silverlight 3.0 Toolkit here
You may also have to install Silverlight Tools for Visual Studio 2008 SP1 here
5. Silverlight SDK installed
you may download Silverlight 2.0 SDK here
if you want to upgrade to Silverlight 3.0, you can download Silverlight 3.0 Tools for Visual Studio SP1 here
Visit the following post to follow the whole project.
The Final Completed Version of the project and whole word document of this post can be downloaded from the final post. But i would encourage to follow all posts for this article(from 1 till final of many).
Please leave comments for your support and suggestions about the post and any other posts.
This is a web development tool created by Microsoft to compete with the Adobe Flash player and its plugin. In my view it is almost getting there. To my knowledge we can do anything and everything that we can possibly do in flash (using action script).
Silverlight is quite a recent technology, released in 2007 as Silverlight 1.0 and now in just 2 year we have a very advanced version Silverlight 3.0. For me it used to be touch to program in Silverlight 1.0 where I know I can do great stuff, but the way we had to do is different than it is now. Microsoft also came up with a new suite called “Microsoft Expression” a combination of design and development tool for web designing and development. An Application called “Microsoft Expression Blend” which is a tool that makes our job much easy to develop a Silverlight Application.
Lets stop talking about the history and jump into the project.
Basics:
You can follow me in developing this application even though you don’t have any idea of Visual Studio, Silverlight, Expression Blend, XAML and WCF etc. because each and every step is explained in detail and also screenshots help you to connect the explanation to the project that we are going to do. In case if you are wondering, following are the necessary softwares that you will need to follow me with the project. You don’t have to stop reading the post even though you don’t have any of the below because, it might help you get an idea of how Silverlight and WCF mix together.
List of Softwares:
1. Visual Studio 2008 (Professional or Express Edition)
2. Microsoft Expression Blend (with SP1)
3. Microsoft SQL Server (Professional or Express Edition)
4. Silverlight 2.0 or 3.0 toolkit installed
you can download Silverlight 2.0 Toolkit here
you can download Silverlight 3.0 Toolkit here
You may also have to install Silverlight Tools for Visual Studio 2008 SP1 here
5. Silverlight SDK installed
you may download Silverlight 2.0 SDK here
if you want to upgrade to Silverlight 3.0, you can download Silverlight 3.0 Tools for Visual Studio SP1 here
Visit the following post to follow the whole project.
The Final Completed Version of the project and whole word document of this post can be downloaded from the final post. But i would encourage to follow all posts for this article(from 1 till final of many).
Please leave comments for your support and suggestions about the post and any other posts.
Thursday, July 2, 2009
Introduction to LINQ - Part1 (final of many)
Working with Result from a LINQ Query
Up until now I have been focusing on the LINQ query itself and different ways to achieve the same result should one so desire to use them. But how do we store and enumerate the results? There are many ways to return type safe data in many different forms but I can’t discuss them all in this scope of this article. In this example I will be using what are called Anonymous Types. Below is an example of using an anonymous type to store the results of a LINQ query as well as the foreach loop we will use to enumerate through the results of the query.
Figure 1.8
var overThirty = from p in people
where p.Age > 30
select p;
foreach (Person p in overThirty)
Console.WriteLine(p.FirstName + " " + p.LastName + ", " + p.Age + " years old.");
The variable “overThirty” is called an anonymous type. Anonymous types are used when the type of return value needs to be inferred by the compiler based on the result of the query. The compiler will infer the type to be returned and create accessors and mutators for the properties in the returned object. In the case of the query in Figure 1.8, we can use the Person type as the inferred type because we queried a List object which only contains Person objects.
So what if we query the List but want to return fields that don’t necessarily exist in the Person object? We come up with our own object on the fly, of course.
Figure 1.9
var overThirtyCustom = from p in people
where p.Age > 30
select new
{
FullName = p.FirstName + " " + p.LastName,
Age = p.Age
};
foreach (var p in overThirtyCustom)
Console.WriteLine(p.FullName + ", " + p.Age + " years old.");
The query in Figure 1.9 will not return a Person object, but an object we created on the fly that now contains a new property called FullName. The FullName property is simply a concatenation of the FirstName and LastName properties separated with a comma. This result set can be enumerated in the same way as the one in Figure 1.8 but will now access the FullName property of our custom object.
Conclusion
Well that wraps up the first part in the introduction to LINQ series. I hope anyone reading this has gotten something out of the article and had a chance to learn something, because I surely have. Keep an eye out for part two the Introduction to LINQ series coming soon. Please send any feedback, complaints, flames or any other comments to loch006@gmail.com or mvsaradhi@yahoo.com.
For More information about LINQ, you may consider the following references
Lambda Functions
http://dotnetaddict.dotnetdevelopersjournal.com/lambda.htm
LINQ Wikipedia Page
http://en.wikipedia.org/wiki/Language_Integrated_Query
MSDN .NET Framework 3.5 “What’s New?”
http://msdn.microsoft.com/en-us/library/bb332048.aspx
Delegates and Events in C# .NET
http://www.akadia.com/services/dotnet_delegates_and_events.html
Introduction to LINQ - Part2 will be updated soon, Stay Tuned...
Final Version of the Project can be download at:
Click Here to download
To see all posts on "Introduction to LINQ - Part1" Click on link to your right that says it.
Please do comment the post after you read, Thank you and have a good LINQ.
Up until now I have been focusing on the LINQ query itself and different ways to achieve the same result should one so desire to use them. But how do we store and enumerate the results? There are many ways to return type safe data in many different forms but I can’t discuss them all in this scope of this article. In this example I will be using what are called Anonymous Types. Below is an example of using an anonymous type to store the results of a LINQ query as well as the foreach loop we will use to enumerate through the results of the query.
Figure 1.8
var overThirty = from p in people
where p.Age > 30
select p;
foreach (Person p in overThirty)
Console.WriteLine(p.FirstName + " " + p.LastName + ", " + p.Age + " years old.");
The variable “overThirty” is called an anonymous type. Anonymous types are used when the type of return value needs to be inferred by the compiler based on the result of the query. The compiler will infer the type to be returned and create accessors and mutators for the properties in the returned object. In the case of the query in Figure 1.8, we can use the Person type as the inferred type because we queried a List
So what if we query the List
Figure 1.9
var overThirtyCustom = from p in people
where p.Age > 30
select new
{
FullName = p.FirstName + " " + p.LastName,
Age = p.Age
};
foreach (var p in overThirtyCustom)
Console.WriteLine(p.FullName + ", " + p.Age + " years old.");
The query in Figure 1.9 will not return a Person object, but an object we created on the fly that now contains a new property called FullName. The FullName property is simply a concatenation of the FirstName and LastName properties separated with a comma. This result set can be enumerated in the same way as the one in Figure 1.8 but will now access the FullName property of our custom object.
Conclusion
Well that wraps up the first part in the introduction to LINQ series. I hope anyone reading this has gotten something out of the article and had a chance to learn something, because I surely have. Keep an eye out for part two the Introduction to LINQ series coming soon. Please send any feedback, complaints, flames or any other comments to loch006@gmail.com or mvsaradhi@yahoo.com.
For More information about LINQ, you may consider the following references
Lambda Functions
http://dotnetaddict.dotnetdevelopersjournal.com/lambda.htm
LINQ Wikipedia Page
http://en.wikipedia.org/wiki/Language_Integrated_Query
MSDN .NET Framework 3.5 “What’s New?”
http://msdn.microsoft.com/en-us/library/bb332048.aspx
Delegates and Events in C# .NET
http://www.akadia.com/services/dotnet_delegates_and_events.html
Introduction to LINQ - Part2 will be updated soon, Stay Tuned...
Final Version of the Project can be download at:
Click Here to download
To see all posts on "Introduction to LINQ - Part1" Click on link to your right that says it.
Please do comment the post after you read, Thank you and have a good LINQ.
Introduction to LINQ - Part1 (3 of many)
Deferred Execution
LINQ uses something called deferred execution. This means that the LINQ query in Figure 1.4(from the previous post "Introduction to LINQ - Part1 (2 of many)" will not return anything until you choose to enumerate through the results using something like a foreach loop. Because of this, you can build your LINQ query little by little depending on the business logic. You can limit the amount of rows returned from the datasource as well as the strain on the datasource by narrowing down your selection criteria way before you ever open a connection to the data store. This is working in a disconnected environment at its best.
Not only is execution deferred but the entire query is being built into an expression tree in the background. This allows LINQ to be able to choose, at the endpoint once the expression tree is fully built and the query is complete, the appropriate and most efficient SQL query to execute. This eliminates the need for client side JOINS or any manual optimization we would need to use if concatenating a large SQL query using a StringBuilder, for instance.
Syntactic Sugar
It is very familiar to be able to write LINQ queries using the syntax in Figure 1.4 because most of us have written some kind of SQL query. The ability to write code in such a way that is easier to understand and more familiar, such as in the case with this LINQ query is called Syntactic Sugar.
So you’re on a diet, you say? Maybe you’ve got programmatic diabetes and don’t want any sugar? That is fine too, because there is another way we can write LINQ queries without it. We can also write the same LINQ query from Figure 1.4 using the syntax below.
Figure 1.5
people.Where(p => p.Age > 30);
The result of this query, when enumerated, will yield the same results as the query in Figure 1.4, but without the syntactic sugar. You may find, as I have, in some cases it is easier and more convenient to get results using the method in Figure 1.5, and sometimes the method in 1.4. The choice is completely a matter of preference and up for you to decide. The method in Figure 1.5, however, does need a little explaining if you have never seen the => operator before.
Lambda Functions
The argument for the “Where” method in Figure 1.5 is known as a Lambda function. Lambda functions have been around a lot longer than their use in .NET in the world of mathematics such as calculus, but the use of the technology behind a Lambda function in .NET has been around for quite some time.
A Lambda function is really nothing more than a way to write an inline delegate. A delegate, for those of you that don’t know, is basically a type safe function pointer.
Figure 1.6
public delegate void DoSomethingDelegate();
DoSomethingDelegate doSomething = new DoSomethingDelegate(MyCustomDoSomethingMethod);
In Figure 1.6 above, the “DoSomethingDelegate” type could then be the type set to a property of a class that would accept as a value any method (such as MyCustomDoSomethingMethod) that matched the signature of the DoSomethingDelegate set during declaration.
A Lambda function works the same way in that the argument of the “Where” method is a type of Func where T is the return value of the function and I is the input type. The method is generic and gets typed based on the object calling the “Where” method. In the case of our Person class, the T type would be of type Person and the I (input type) would be a bool. The input type is a bool because we are passing it a standard expression which will either evaluate to true or false.
To illustrate this, we can write the predicate (Where method) filtering in another way using a filter condition we previously created and then passed to the “Where” method of the List class.
Figure 1.7
Func ageFilter = person => person.Age > 30;
var r = people.Where(ageFilter);
Again, you can choose any of the methods in Figure 1.4, 1.5, or 1.7 to perform the operations you need.
Introduction to LINQ - Part1 Continued...
Final Sample Version of the Project can be download from the final post in this series - "Introduction to LINQ - Part1 (final of many)"
To see all posts on "Introduction to LINQ - Part1" Click on link to your right that says it.
Please do comment the post after you read, Thank you and have a good LINQ.
LINQ uses something called deferred execution. This means that the LINQ query in Figure 1.4(from the previous post "Introduction to LINQ - Part1 (2 of many)" will not return anything until you choose to enumerate through the results using something like a foreach loop. Because of this, you can build your LINQ query little by little depending on the business logic. You can limit the amount of rows returned from the datasource as well as the strain on the datasource by narrowing down your selection criteria way before you ever open a connection to the data store. This is working in a disconnected environment at its best.
Not only is execution deferred but the entire query is being built into an expression tree in the background. This allows LINQ to be able to choose, at the endpoint once the expression tree is fully built and the query is complete, the appropriate and most efficient SQL query to execute. This eliminates the need for client side JOINS or any manual optimization we would need to use if concatenating a large SQL query using a StringBuilder, for instance.
Syntactic Sugar
It is very familiar to be able to write LINQ queries using the syntax in Figure 1.4 because most of us have written some kind of SQL query. The ability to write code in such a way that is easier to understand and more familiar, such as in the case with this LINQ query is called Syntactic Sugar.
So you’re on a diet, you say? Maybe you’ve got programmatic diabetes and don’t want any sugar? That is fine too, because there is another way we can write LINQ queries without it. We can also write the same LINQ query from Figure 1.4 using the syntax below.
Figure 1.5
people.Where(p => p.Age > 30);
The result of this query, when enumerated, will yield the same results as the query in Figure 1.4, but without the syntactic sugar. You may find, as I have, in some cases it is easier and more convenient to get results using the method in Figure 1.5, and sometimes the method in 1.4. The choice is completely a matter of preference and up for you to decide. The method in Figure 1.5, however, does need a little explaining if you have never seen the => operator before.
Lambda Functions
The argument for the “Where” method in Figure 1.5 is known as a Lambda function. Lambda functions have been around a lot longer than their use in .NET in the world of mathematics such as calculus, but the use of the technology behind a Lambda function in .NET has been around for quite some time.
A Lambda function is really nothing more than a way to write an inline delegate. A delegate, for those of you that don’t know, is basically a type safe function pointer.
Figure 1.6
public delegate void DoSomethingDelegate();
DoSomethingDelegate doSomething = new DoSomethingDelegate(MyCustomDoSomethingMethod);
In Figure 1.6 above, the “DoSomethingDelegate” type could then be the type set to a property of a class that would accept as a value any method (such as MyCustomDoSomethingMethod) that matched the signature of the DoSomethingDelegate set during declaration.
A Lambda function works the same way in that the argument of the “Where” method is a type of Func
To illustrate this, we can write the predicate (Where method) filtering in another way using a filter condition we previously created and then passed to the “Where” method of the List
Figure 1.7
Func
var r = people.Where(ageFilter);
Again, you can choose any of the methods in Figure 1.4, 1.5, or 1.7 to perform the operations you need.
Introduction to LINQ - Part1 Continued...
Final Sample Version of the Project can be download from the final post in this series - "Introduction to LINQ - Part1 (final of many)"
To see all posts on "Introduction to LINQ - Part1" Click on link to your right that says it.
Please do comment the post after you read, Thank you and have a good LINQ.
Subscribe to:
Posts (Atom)