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:

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.

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.

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.

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.

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.

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.

Introduction to LINQ - Part1 (2 of many)

Person Class
The Person class is the example business object we will be using with our LINQ queries. There is only a FirstName, LastName, and Age property for the Person class. The code for this class is shown below.

Figure 1.0
public class Person
{
private int _age = 0;
private string _firstName = "";
private string _lastName = "";

public int Age
{
get
{
return _age;
}
set
{
_age = value;
}
}

public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}

public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}

public Person(string firstName, string lastName, int age)
{
_firstName = firstName;
_lastName = lastName;
_age = age;
}
}

Main Application Code
Since this application is only meant for demonstration purposes I have placed the Person class declaration directly in the main application code for the console application. This is obviously not the way a real application would be written but in this case it reduces complexity and allows us to focus on the LINQ queries themselves.
The first thing we are going to is instantiate a few instances of the Person class. I have used four people here but feel free to play around with it as much as you want. The code for the Person instantiation is below.

Figure 1.1
Person jake = new Person("Jake", "Weakley", 27);
Person bruce = new Person("Bruce", "Campbell", 40);
Person jimmy = new Person("Jimmy", "Dean", 55);
Person brother = new Person("Jimbo", "Weakley", 29);

After instantiating your instances of the People class we will then create a new instance of a generic List class typed as a collection of Person objects and add the people we created into the collection.

Figure 1.2
List people = new List();

people.Add(jake);
people.Add(bruce);
people.Add(jimmy);
people.Add(brother);

After the setup is complete we can get into writing the LINQ queries.

LINQ: Projection, Filtering, and Sugar
Those of you familiar with writing standard CRUD SQL queries should find the LINQ query syntax fairly easy to grasp after a few runs at it. LINQ is basically like writing a SQL SELECT statement backwards. Using LINQ to SELECT data from a collection is called projection. The WHERE part of the query (called the predicate) is where filtering of that data will occur. To help you wrap your head around it a bit more let us look at a simple example.
We will say, for instance, that we have a table of Person data. This table has 30 rows but we want to only retrieve the rows where Age > 30. We would write the SQL query something like what I have done below.
Figure 1.3

SELECT LastName, FirstName, Age
FROM Person
WHERE Age > 30


The same data would be retrieved using a LINQ query something like the one found below.

Figure 1.4

from p in people
where p.Age > 30
select p;

The two queries are very similar except that in Figure 1.3 the query would be run against a database. In the Figure 1.4 query, we will run the results against an enumerable collection of objects. By now you are probably wondering about what is returned as a result from these queries. Well, lets take a look.

Even though these queries are written to select the exact same data they yield very different results. It should be fairly obvious that the query in Figure 1.3 returns some rows of data either in the query editor window or in some kind of dataset in the data layer of an application. The difference between the return value of the Figure 1.3 query and the Figure 1.4 query is that the LINQ query, in its current state, returns exactly nothing. That’s right, nothing. Why does it return nothing? Let’s find out.

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.

Introduction to LINQ - Part1 (1 of many)

Introduction
.NET 3.5 has brought many new features into the world of .NET programming and put at the hands of developers some very powerful tools such as; full support for client and server based ASP .NET AJAX, WCF support, and the ability to target your development to a specific version of the .NET framework, just to name a few. This article will be focusing on one of the biggest enhancement to the .NET framework with version 3.5: LINQ.
What is LINQ?
LINQ is an acronym for Language Integrated Query. It is a component of the .NET framework and adds querying capabilities to the language. It was fully integrated into in the .NET framework 3.5 in November of 2007. LINQ enables developers to project and filter data in any type of enumerable data structure, including objects built from relation databases and XML. Using LINQ you can retrieve data from any of these data structures in the exact format needed without adding all of your filtering and formatting conditions inside a foreach loop, for instance.

Do I Need Special Software to use LINQ?
Yes and no. LINQ is fully integrated with Visual Studio 2008 and Visual Studio 2010, so if you are already using Visual Studio 2008 or 2010 then you don’t need to do anything except maybe add a reference to System.Data.Linq if you are going to be using a LINQ-to-SQL data layer. If you are using Visual Studio 2005 you can install the community preview 2006 which was released about 6 or 7 months before .NET 3.5 and Visual Studio 2008 was released. The CTP is old but still useful if you haven’t moved over to Visual Studio 2008 yet. The CTP can be found here:

http://www.microsoft.com/downloads/details.aspx?familyid=1e902c21-340c-4d13-9f04-70eb5e3dceea&displaylang=en

so enough with the history lesson, let’s get down to business.

How do I use LINQ in my Code?
First let me mention that the code examples and accompanying project associated with this article were created using Visual Studio 2008 and C#. Configuring Visual Studio 2005 to use LINQ is beyond the scope of this article, but the LINQ queries and syntax will be the same regardless of the environment in which they are used. This article also assumes you have some very basic knowledge of .NET, OOP, and Visual Studio in general. With that out of the way, let’s get into the code.
First open and unzip the project source code (IntroductionToLINQ_ExampleProject.zip) into a folder on your hard drive and open up IntroductionToLINQ.sln. The only code file of interest in this solution is Program.cs.

Introduction to LINQ - Part1 Continued...
Final 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.