Using GridView, Entity Framework, LINQ, and an ObjectDataSource to implement a GridView that sorts and filters.

June 19, 2009

Wednesday, June 17, 2009
Using GridView, Entity Framework, LINQ, and an ObjectDataSource to implement a GridView that sorts and filters.

I went in search of an elegant and flexible way to implement a GridView that supports sorting (and the ability to add custom paging if I need it later, though I won’t cover that here) and uses a Data Access Layer (DAL). The filtering I am looking for is the ability to add any number of controls on the page and have them filter the results that are shown in the GridView. Based on the values of these user controls, I want to be able to do a begins with, or a range, or choose from a list of values, etc. I don’t want to be limited to just one value.

I am a believer that like SQL, you don’t want your LINQ queries all over the place. I believe a Data Access Layer (DAL) is a good place to put all your LINQ queries.

At the present time, this means that the ObjectDataSource is probably the best choice because it can call the DAL to do the query and not embed it in the EntityDataSource or LinqDataSource.

It is possible to get pretty good filtering and little to no code to do this using the Dynamic Data Future, but even then I using the DynamicFilter I found it difficult to modify the query to do things like ranges, or a begins with search for example. If you decide to go down that road, you might also want to check out the following post on how to do this in your own project. It makes searching based on a DropDownList or an AutoComplete field very easy. I wanted more flexibility than that. You can also get much of that same functionality from VS 2008 SP1 (yes the SP1 is required to get this functionality since SP1 is essentially a feature release, not a bug fix release).

The hard part of this is writing the DAL method, but is actually much easier than it used to be now that we have LINQ. In this case, I am using LINQ to Entities to query the Entity Framework.

Here is my DAL:

public class DAL
{
private MyEntities ctx = new MyEntities();

public IQueryable GetPerson(string firstName, string lastName, bool hasChildren, int? age, string sortExpr)
{
// set a default sort order
if (string.IsNullOrEmpty(sortExpr))
{
sortExpr = “FName”;
}

var people = from p in ctx.Person
select new
{
ID = p.ID,
FName = p.FName,
LName = p.LName,
Age = p.Age,
NumChildren = p.NumChildren
};

if (hasChildren)
people = people.Where(p => p.NumChildren > 0);

if (!string.IsNullOrEmpty(firstName))
people = people.Where(p => p.firstName.StartsWith(firstName));

if (!string.IsNullOrEmpty(lastName))
people = people.Where(p => p.firstName.StartsWith(lastName));

if (!age.HasValue)
people = people.Where(p => p.Age > age);

var sortedPeople = people.OrderBy(sortExpr)
.Select(“new(ID, FName, LName, Age, NumChildren)”);

return sortedPeople;
}
}

You may notice that the .OrderBy() method gives you a compiler error or is not in your Intellisense. You need to download it from Microsoft. Click here to download. In the zip file, look for the Dynamics.cs file. You can include it in your project or you can build the project that comes with and include the assembly it builds in your project. It is one file, so I like putting it in my project as source code.

This Dynamic class works very in scenarios like this because it actually supports the same syntax as the ObjectDataSource uses which is . If the sort direction is Ascending, then no direction is specifed by the ObjectDataSource. For example the syntax for sorting my FName in Ascending order, the sortExpression would be “FName” or “FName Descending” if you wanted to sort in Descending order.

You may also notice that I use Lambda expressions to do the additional where statements. Be sure to use the value returned by the Where() method since the Where() call doesn’t change (or even query the database). All the Where() does is adds another condition to the existing where clause in the generated sql. Each time Where() is called, the statement is ANDed to the existing where clause. The code is very optimized. I am quite impressed with the code generation.

For related details on sorting with the ObjectDataSource, check out my other post.

Below is the aspx code. The most important thing you get right is the SelectParameters/ControlParameters. The ControlID property needs to match the ID of the Controls you are using for Filtering. The Name property needs to match the parameter names in the DAL method you specified in the ObjectDataSource SelectMethod property.

First Name starts with:
Last Name Starts with:
Has Children:

Posted by Brent V at 2:41 PM 0 comments Links to this post
Labels: .Net, ADO.NET Entity Framework, LINQ, Programming
Monday, June 15, 2009
The GridView ‘GridView1′ fired event Sorting which wasn’t handled.

If you get the error:

The GridView ‘GridView1′ fired event Sorting which wasn’t handled.

You are likely using an ObjectDataSource and then set AllowSorting to true or you are binding to directly your GridView in Page_Load using something like this.

It means you using a GridView that has AllowSorting=”true” equal to true and for some reason nothing has told it what will handle the sorting. The easiest way to avoid this is to use a DataSource control such as an EntityDataSource, SqlDataSource, or LinqDataSource control. The ObjectDataSource will not help you out of the box though. Some extra stuff is required. I’ll show you that later.

This page entry is broken up into to sections. One if you are binding directly to the GridView in your page load and thus have no DataSource assigned to the GridView. Another if you have are using an ObjectDataSource.

In both sections I assume you are using LINQ to access the database, but you could use anything to talk to the database. The logic that needs to be implemented is still the same. I also assume you have an object that encapsulates your database access (a Database Access Layer (DAL)).

For this example, let’s assume you have used the ADO.NET Entity Data Model in Visual Studio to create your entities. In this example we have one entity called Person. It has 3 properties: ID, FName, LName.
Data Access Layer
Below is a solution if you are using an LINQ to Entities, though it would be virtually identical to LINQ to SQL. A similar solution could be used for SQL, though in that case you would translate the requests to SQL statements.

public class DAL
{
private MyEntities ctx = new MyEntities();

public IQueryable GetPerson(string sortExpression)
{
// set a default sort order for when the page is first rendered
if (string.IsNullOrEmpty(sortExpression))
{
sortExpression = “FName Descending”;
}

var people = from p in ctx.Person
select p;

var sortedPeople = people.OrderBy(sortExpression)
.Select(“new(ID, FName, LName)”);

return sortedPeople;
}}

You may notice that the .OrderBy() method gives you a compiler error or is not in your Intellisense. You need to download it from Microsoft. Click here to download. In the zip file, look for the Dynamics.cs file. You can include it in your project or you can build the project that comes with and include the assembly it builds in your project. It is one file, so I like putting it in my project as source code.

This Dynamic class works very in scenarios like this because it actually supports the same syntax as the ObjectDataSource uses which is . If the sort direction is Ascending, then no direction is specifed by the ObjectDataSource. For example the syntax for sorting my FName in Ascending order, the sortExpression would be “FName” or “FName Descending” if you wanted to sort in Descending order.

The GridView sortingEvent also uses very similar syntax. In either case, this saves us from writing a bunch of if-else or switches for each column and sort direction. The choice is yours. This is just so easy, and it is clean.

Binding ObjectDataSource to GridView

This is by far easier of the two methods. I highly recommend using a DataSource such as the ObjectDataSource. The code is much simpler.

To make the ObjectDataSource sort all you have to do is set the DataSourceID property on the GridView to the ID of your ObjectDataSource.

You do have to tell the ObjectDataSource some things about your Data Access Layer though. You need to tell it the type for your Data Access Layer, the method to call, and what the parameter name is for sortExpression the GridView will pass you.

Here is my ObjectDataSource that I defined for the Data Access Layer we defined above.

Binding Directly to GridView in Page Load

If you want to work a little harder you can implement the logic using the GridView and no ObjectDataSource. If you are bind directly to your GridView in your page load, all you to do to stop this error message is handle the Sorting event on your GridView. While this stops the error message, it doesn’t give you sorting when a column header is clicked. You need to put some logic in the Sorting event for it to do something useful.

You are likely binding your DAL to your GridView using something like this or maybe conditionally if it isn’t a postback:

protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = new DAL().GetPerson(“”);
GridView1.DataBind();
}

The GridView does NOT set the SortDirection property in this event handler unless an DataSource object is set. This means that Sorting event ALWAYS will have a e.SortDirection equal to SortingDirection.Ascending. This is a bug in my mind, but I think Microsoft just says it is by design (or bad design if you ask me). For more explanation on this please see here for the response from Microsoft.

As a recommended workaround, we need to track the SortDirection ourselves. In order to do something useful, we need to also track the column that was clicked so that we know when to reset the sort direction to the default direction.

Here is the code to handle the sorting event for GridView. Be sure to wire it up to your GridView.

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{

// get values from viewstate
String sortExpression = ViewState["_GridView1LastSortExpression_"] as string;
String sortDirection = ViewState["_GridView1LastSortDirection_"] as string;

// on first time header clicked ( including different header), sort ASCENDING
if (e.SortExpression != sortExpression)
{
sortExpression = e.SortExpression;
sortDirection = “Ascending”;
}
// on second time header clicked, toggle sort
else
{
if (sortDirection == “Ascending”)
{
sortExpression = e.SortExpression;
sortDirection = “Descending”;
}
// Descending
else
{
sortExpression = e.SortExpression;
sortDirection = “Ascending”;
}
}

// save state for next time
ViewState["_GridView1LastSortDirection_"] = sortDirection;
ViewState["_GridView1LastSortExpression_"] = sortExpression;

// NOTE: Depending on the syntax you require for your sortExpression parameter
// to your method, you may need to convert the sort expression to that syntax.
GridView1.DataSource = new DAL().GetPerson(sortExpression + ” ” + sortDirection);
GridView1.DataBind();
}

Posted by Brent V at 12:44 PM 0 comments Links to this post
Labels: .Net, ADO.NET Entity Framework, LINQ, Programming
Thursday, May 14, 2009
ADO.NET Entity Data Model Designer doesn’t open model when double-clicking

I understand that the ADO.NET Entity Data Model Designer is still in its infancy, but I have to wonder how this bug was missed. If you open a model in the ADO.NET Entity Data Model Designer by double-click on it or right-clicking and choosing Open the model opens fine. Close it and try the same thing again. The model will not open.

Luckily the workaround is not too much of a pain. Do the following to get the designer to open the model again.

1. Close the model.
2. Right-click on the Model.edmx (or similarly named file) in the Solution Explorer in Visual Studio 2008.
3. Choose Open With…
4. In the windows that comes up, choose XML Editor and click the OK button. Actually you can also use the Source Code (Text) Editor. You really just need an editor that can read xml, so most of them will work. The key is to open it in something other than the ADO.NET Entity Data Model Designer.
5. Close Model.
6. Double-click on the Model.edmx (or similarly named file) to open it as you usually would.

Unfortunately, you will need to do this every time you close the model and then want to re-open it. It is better than the other workaround of restarting Visual Studio 2008.
Posted by Brent V at 11:49 AM 4 comments Links to this post
Labels: .Net, ADO.NET Entity Framework, Programming
ADO.NET Entity Data Model Designer missing delete functionality

I understand that the ADO.NET Entity Data Model Designer is still in its infancy, but to not delete an object all the way is a BIG missing feature in my opinion.

If you delete an object as I describe below, you may get the following error:

Error 1 Error 3013: Problem in Mapping Fragment starting at line 241: Missing table mapping: Foreign key constraint ‘FK_TestTable1_MyTable’ from table TestTable1 (MyTableID) to table MyTable(ID): no mapping specified for the table TestTable1.
C:\MyWebSite\DataModel\Model.edmx 242 15 DataModel

For simplicity in explanation, let’s assume you have two tables in your model. They are called TestTable1 and MyTable. There is a foreign key / association inTestTable1 that points to MyTable. There is also a reverse association from MyTable to TestTable1.

I decided that I didn’t want TestTable1 in the model anymore. I select the object and delete it. That only deletes it from the viewable portion of the model. It is still in the underlying xml.

You can try to update the model from the database, but it doesn’t show TestTable1 as a table that you can add again. This is because it is still defined in the underlying xml.

Luckily the workaround is pretty easy and painless, but not necessarily obvious at first glance. Do the following to remove the references to TestTable1 and fix the problem.

1. Right-click on the Model.edmx (or similarly named file) in the Solution Explorer in Visual Studio 2008.
2. Choose Open With…
3. In the windows that comes up, choose XML Editor and click the OK button.
4. If you are prompted to close the model because it is already open, click the Yes button.
5. Now, search for your table name. In my case TestTable1. Delete all tags (and inner-Xml) that you find.
6. Save your changes.
7. Right-click on the Model.edmx (or similarly named file) in the Solution Explorer in Visual Studio 2008.
8. Choose Open With…
9. In the windows that comes up, choose ADO.NET Entity Data Model Designer and click the OK button.
10. Rebuild your solution. That should take care of the error.

Another workaround is to actually delete the table from your database. This may or may not be what you want to do. If you do indeed want to delete it from the database also, then you are in luck. You can update the underlying xml by updating the model from the database (right-click on the designer surface).

If you want to see a read-only visual representation of the underlying xml look for a Model Browser tab while you are in the ADO.NET Entity Data Model Designer. Mine is right next to my Solution Explorer on the right side of my screen. If it isn’t there check the different dockable areas. The Model Browser only shows when you are in the ADO.NET Entity Data Model Designer, so be sure that is your active window. It would be nice if you could edit through the Model Browser. Oh well, your choices for now are direct xml editing or modifying your database and synching it.
Posted by Brent V at 11:39 AM 0 comments Links to this post
Labels: .Net, ADO.NET Entity Framework, Programming
Wednesday, May 13, 2009
Making Linq to Entities do a case-insensitive string comparison.

Linq to Entities by default is case-sensitive for string comparisons. Even for SQL Server, which is case insensitive string comparisons are case-sensitive.

Below are two examples. The first example shows a case-insensitive example, and the second one, shows a case-sensitive example.

// This is NOT case-sensitive
using (MyModel ctx = new MyModel())
{
Reviewer reviewer = ctx.Reviewer.First(r => r.FirstName.Equals(“Brent”, StringComparison.CurrentCultureIgnoreCase));
}

// This IS case-sensitive
using (MyModel ctx = new MyModel())
{
Reviewer reviewer = ctx.Reviewer.First(r => r.FirstName == “Brent”);
}

BTW, don’t use the .toLower() method as this translates into a similar call in SQL which then will usually cause your indexes to not be used.
Posted by Brent V at 4:37 PM 0 comments Links to this post
Labels: .Net, ADO.NET Entity Framework, LINQ, Programming
Tuesday, April 28, 2009
AJAX ReorderList breaks when using EntityDataSource entity that has a Navigation Property

After some digging, I figured out the reason why the ReorderList from the AJAX Control Toolkit stopped working for me. When I use the ReorderList with the SqlDataSource it works fine. When I use it with the EntityDataSource it works also. Well sort of. It works fine if the object that you are binding to do not have a Navigation Property in ADO.NET Entity Data Model.

If the object does, you will not receive an error when you reorder items in the ReorderList, but it will not work either. The reason is that the control is not completely robust / completed. If figured this out by changing my reference to the the AjaxControlToolkit.dll that is in the source code version of the Ajax Control Toolkit Sample Application. This allowed me to step through the code. There I saw code that “swallowed” the exception and thus never reported it to the calling method. This is why there is no error, but it is not working either.

Here is the InnerException that I found when I stepped through the ReorderList code:

“Error while setting property ‘ICAContract’: ‘This property descriptor does not support the SetValue method.’.”

at System.Web.UI.WebControls.EntityDataSourceUtil.SetAllPropertiesWithVerification(EntityDataSourceWrapper entityWrapper, Dictionary`2 changedProperties, Boolean overwrite)
at System.Web.UI.WebControls.EntityDataSourceView.InstantiateEntityFromViewState(EntityDataSourceWrapper entityWrapper, IDictionary mergedKeysAndOldValues)
at System.Web.UI.WebControls.EntityDataSourceView.ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues)
at System.Web.UI.DataSourceView.Update(IDictionary keys, IDictionary values, IDictionary oldValues, DataSourceViewOperationCallback callback)

Here is the code from ReorderList.cs file.

try{…}
catch (Exception ex)
{
System.Diagnostics.Debug.Fail(ex.ToString());
//TODO WHY ARE SWALLOWING THIS EXCEPTION!!!
}

I have to conclude that ReorderList needs to handle error properly, and that potentially the ADO.NET Entity Framework may need some more work. I can’t confirm that, but I do know that I have had to implement several work arounds as noted in these blog entries, and that the experience has been buggy at best.

* AJAX ReorderList Example for Adding and Editing Items using the EntityDataSource

* AJAX ReorderList Example for Adding and Editing Items using the SqlDataSource

Posted by Brent V at 4:43 PM 0 comments Links to this post
Labels: .Net, ADO.NET Entity Framework, AJAX, Programming
Monday, April 27, 2009
AJAX ReorderList Example for Adding and Editing Items using the EntityDataSource

This blog entry is very similar to my entry AJAX ReorderList Example for Adding and Editing Items using the SqlDataSource. I highly recommend you read it first to understand the fixes and enhancements I made, since it is the same logic for the EntityDataSource I show here. The functionality is the same, but the difference is that this example show how to use the EntityDataSource (part of the ADO.NET Entity Framework) instead of the SqlDataSource.

The code is very similar to what I did for the SqlDataSource. However, there is some changes that needed to be done as well. The biggest one is that the ReorderList when used with the EntityDataSource requires a DataBind() call after all commands except Edit and Update, and requires special logic for the Update command.

The big change is that there is now a RequiresReorderListDataBind Boolean that I added. This flag is set to true on the initial page load, and then set based on the command that is executed. In turn, when the control is rendered, if RequiresReorderListDataBind is true then DataBind() is called in the PreRender event. You could also call the DataBind() in the appropriate command events such as OnInsertCommand, OnDeleteCommand. However, the Update command needs to call the UpdateItem() and then call DataBind() earlier in the cycle so we put it in the OnItemCommand event. Also, you can’t but the DataBind() call in OnItemCommand for the Insert and Delete. For this reason, I have the logic in the particular events that I do. I wanted to put everything in the OnItemCommand event, but it didn’t work. :(

This example assumes you have a table in your database. Here is the SQL you can use to create one.

CREATE TABLE [dbo].[TestTable1](
[intID] [int] IDENTITY(1,1) NOT NULL,
[strName] [varchar](50) NOT NULL,
[strLink] [varchar](50) NOT NULL,
[intOrder] [int] NOT NULL,
CONSTRAINT [PK_TestTable1] PRIMARY KEY CLUSTERED
(
[intID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

You will need to add a ADO.NET Entity Data Model (just like you add any other file to your web site). Select the database and table you created above. I called my Model MyModel and my entities MyEntities.

Here is the contents of the .aspx file.

OrderedList AJAX

.ajaxOrderedList li
{
list-style:none;
}

 
<asp:HyperLink ID="HyperLink1" runat="server" Text='’ NavigateUrl=” />

<asp:Panel ID="dragHandle" runat="server"
style="height: 20px; width: 20px; border: solid 1px black; background-color: Red; cursor: pointer;"
Visible="”>
 

 

<asp:TextBox ID="txtName" runat="server" Text='’>

<asp:TextBox ID="txtLink" runat="server" Text='’>

<asp:TextBox ID="txtName" runat="server" Text='’/>
<asp:TextBox ID="txtLink" runat="server" Text='’ />
<asp:TextBox ID="txtOrder" runat="server" Text='’ />

Here is the code-behind (.cs) file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class EntityDataSourceTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label3.Text = DateTime.Now.ToLongTimeString();
if (!IsPostBack)
{
ShowDragHandle = true;
RequiresReorderListDataBind = false;
}
}

protected void ReorderList1_ItemReorder(object sender, AjaxControlToolkit.ReorderListItemReorderEventArgs e)
{
ShowDragHandle = true;
}

protected Boolean ShowDragHandle { get; set; }

protected void ReorderList1_ItemCommand(object sender, AjaxControlToolkit.ReorderListCommandEventArgs e)
{

switch (e.CommandName)
{
case “Edit”:
ShowDragHandle = false;
RequiresReorderListDataBind = false;
break;

case “Update”:
ShowDragHandle = true;
ReorderList1.UpdateItem(ReorderList1.EditItemIndex);
ReorderList1.DataBind();
RequiresReorderListDataBind = false;
break;

// Cancel, Insert, Delete, and any unknown case
default:
ShowDragHandle = true;
RequiresReorderListDataBind = true;
break;
}
}

private Boolean RequiresReorderListDataBind { get; set; }
protected void ReorderList1_PreRender(object sender, EventArgs e)
{
if (RequiresReorderListDataBind)
{
ReorderList1.DataBind();
}
}
}

Tips

* Be sure to set the ContextType property of the EntityDataSource as described here.

* There are fewer issues when using a SqlDataSource as described here.

* Be sure to set the OrderBy property of your EntityDataSource. An example is “it.intOrder ASC”.

Indexer in C#

June 18, 2009

Indexers In C#

C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C# community. Defining a C# indexer is much like defining properties. We can say that an indexer is a member that enables an object to be indexed in the same way as an array.

this [argument list]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}

Where the modifier can be private, public, protected or internal. The return type can be any valid C# types. The ‘this’ is a special keyword in C# to indicate the object of the current class. The formal-argument-list specifies the parameters of the indexer. The formal parameter list of an indexer corresponds to that of a method, except that at least one parameter must be specified, and that the ref and out parameter modifiers are not permitted. Remember that indexers in C# must have at least one parameter. Other wise the compiler will generate a compilation error.

The following program shows a C# indexer in action

// C#: INDEXER
// Author: rajeshvs@msn.com

using System;
using System.Collections;

class MyClass
{
private string []data = new string[5];
public string this [int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
}

class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc[0] = “Rajesh”;
mc[1] = “A3-126″;
mc[2] = “Snehadara”;
mc[3] = “Irla”;
mc[4] = “Mumbai”;
Console.WriteLine(“{0},{1},{2},{3},{4}”,mc[0],mc[1],mc[2],mc[3],mc[4]);
}
}

The indexers in C# can be overloaded just like member functions. The formal parameter list of an indexer defines the signature of the indexer. Specifically, the signature of an indexer consists of the number and types of its formal parameters. The element type is not part of an indexer’s signature, nor is the names of the formal parameters. The signature of an indexer must differ from the signatures of all other indexers declared in the same class. C# do not have the concept of static indexers. If we declare an indexer static, the compiler will show a compilation time error.

Indexers & Inheritance

Just like any other class members, indexers can also participate in inheritance. A base class indexer is inherited to the derived class.

//C#: Indexer : Inheritance
//Author: rajeshvs@msn.com
using System;
class Base
{
public int this[int indxer]
{
get
{
Console.Write(“Base GET”);
return 10;
}
set
{
Console.Write(“Base SET”);
}
}
}

class Derived : Base
{

}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1[0] = 10;
Console.WriteLine(d1[0]);//Displays ‘Base SET Base GET 10′
}
}

Indexers & Polymorphism

A Base class indexer can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.

//C#: Indexer : Polymorphism
//Author: rajeshvs@msn.com

using System;

class Base
{
public virtual int this[int index]
{
get
{
Console.Write(“Base GET”);
return 10;
}
set
{
Console.Write(“Base SET”);
}
}
}

class Derived : Base
{
public override int this[int index]
{
get
{
Console.Write(“Derived GET”);
return 10;
}
set
{
Console.Write(“Derived SET”);
}
}
}

class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1[0]= 10;
Console.WriteLine(b1[0]);//Displays ‘Derived SET Derived GET 10′
}
}

Abstract Indexers

An indexer inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract indexer in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors.

If the abstract class contains only set accessor, we can implement only set in the derived class.

The following program shows an abstract indexer in action.

//C#: Indexer : Abstract
//Author: rajeshvs@msn.com

using System;

abstract class Abstract
{
public abstract int this[int index]
{
get;
set;
}
}

class Concrete : Abstract
{
public override int this[int index]
{
get
{
Console.Write(” GET”);
return 10;
}
set
{
Console.Write(” SET”);
}
}
}

class MyClient
{
public static void Main()
{
Concrete c1 = new Concrete();
c1[0] = 10;
Console.WriteLine(c1[0]);//Displays ‘SET GET 10′
}
}

Indexers & Properties

1. An index is identified by it’s signature. But a property is identified it’s name.
2. An indexer is always an instance member, but a property can be static also.
3. An indexer is accessed through an element access. But a property is through a member access.

Conclusion

The indexer is one of the key concepts of C# and are very interesting aspects of the language. I’ve given you enough information to use indexer in your code and shown you some examples. The feedback is always welcome. Feel free to contact me for any questions or comments you may have about this article at .

New in Visual Studio 2008

June 16, 2009

ntroduction

Visual Studio 2008 code name “Orcas” Beta 2 has just hit the road and, since it is Beta 2, this means Visual Studio 2008 is feature complete and is ready for RTM. Below, we would find a brief introduction of some of the new features introduced with VS 2008 and .NET 3.5 Beta 2.

A quick list of some of the new features are:

* Multi-Targeting support
* Web Designer and CSS support
* ASP.NET AJAX and JavaScript support
* Project Designer
* Data
* LINQ � Language Integrated Query

The features listed and explained in this paper are not complete and this document intends to give you a forehand to start off with VS 2008.
1. Multi-Targeting Support

Earlier, each Visual Studio release only supported a specific version of the .NET Framework. For example, VS 2003 only works with .NET 1.1, and VS 2005 only works with .NET 2.0.

One of the major changes with the VS 2008 release is to support what Microsoft calls “Multi-Targeting”. This means that Visual Studio will now support targeting multiple versions of the .NET Framework, and developers will be able to take advantage of the new features that Visual Studio provides without having to migrate their existing projects and deployed applications to use a new version of the .NET Framework.

Now when we open an existing project or create a new one with VS 2008, we can pick which version of the .NET Framework to work with. The IDE will update its compilers and feature-set to match the chosen .NET Framework.

Features, controls, projects, item-templates, and references that do not work with the selected version of the Framework will be made unavailable or will be hidden.

Unfortunately, support has not been included to work with Framework versions 1.1 and earlier. The present release supports 2.0/3.0 and 3.5 .NET Frameworks.

Microsoft plans to continue multi-targeting support in all future releases of Visual Studio.
Creating a New Project with Visual Studio 2008 that Targets .NET 2.0 Framework Library

The screenshots below depict the creation of a new web application targeting .NET 2.0 Framework. Choose File->New Project. As we see in the snapshot below in the top-right of the new project dialog, there is now a dropdown that allows us to choose which versions of the .NET Framework we want to target when we create the new project. The templates available are filtered depending on the version of the Framework chosen from the dropdown:
Can I Upgrade an Existing Project to .NET 3.5?

When we open a solution created using an older version of Visual Studio and Framework, VS 2008 would ask if migration is required. If we opt to migrate, then a migration wizard would start. If we wish to upgrade our project to target a newer version of the Framework at a later point of time, we can pull up the project properties page and choose the Target Framework. The required assemblies are automatically referenced. The snapshot below shows the properties page with the option Target Framework marked.
2. Web Designer, Editing and CSS Support

One feature that web developers will discover with VS 2008 is its drastically improved HTML designer, and the extensive CSS support made available.

The snapshots below depict some of the new web designer features in-built into VS 2008.
Split View Editing

In addition to the existing views, Design view and Code view, VS 2008 brings along the Split view which allows us to view both the HTML source and the Design View at the same-time, and easily make changes in any of the views. As shown in the image below, as we select a tag in code view, the corresponding elements/controls are selected in design view.
CSS Style Manager

VS 2008 introduces a new tool inside the IDE called “Manage Styles”. This shows all of the CSS style sheets for the page.

It can be used when we are in any of the views – design, code and split views. Manage Styles tool can be activated by choosing Format -> CSS Styles -> Manage Styles from the menu. A snapshot of the same would look like the following:

Create a new style using the new style dialog window as show in the snapshot below.

Now, the style manager would show .labelcaption style as well in the CSS styles list. However, if we observe that the body element has a circle around it but the .labelcaption does not have one, this is because the style is not in use yet.

We will not select all the labels below and apply our new style .labelcaption.

We can choose to modify the existing style through GUI using “Modify style…” menu option in the dropdown menu as shown above or choose to hand edit the code by choosing the option “Go To Code”.
CSS Source View Intellisense

The designer is equipped with the ability to select an element or control in design-view, and graphically select a rule from the CSS list to apply to it.

We will also find when in source mode that we now have intellisense support for specifying CSS class rules. The CSS Intellisense is supported in both regular ASP.NET pages as well as when working with pages based on master pages.
Code Editing Enhancements

Below is a non-exhaustive list of a few new code editing improvements. There are many more about which I don’t know yet.
Transparent Intellisense Mode

While using VS 2005/2003 we often find ourselves escaping out of intellisense in order to better see the code around, and then go back and complete what we were doing.

VS 2008 provides a new feature which allows us to quickly make the intellisense drop-down list semi-transparent. Just hold down the “Ctrl” key while the intellisense drop-down is visible and we will be able to switch it into a transparent mode that enables us to look at the code beneath without having to escape out of Intellisense. The screenshot below depicts the same.
Organize C# Using Statements

One of the small, but a nice new feature in VS 2008 is support for better organizing using statements in C#. We can now select a list of using statements, right-click, and then select the “Organize Usings” sub-menu. When we use this command the IDE will analyze what types are used in the code file, and will automatically remove those namespaces that are declared but not required. A small and handy feature for code refactoring.
3. ASP.NET AJAX and JavaScript Support
JavaScript Intellisense

One new feature that developers will find with VS 2008 is its built-in support for JavaScript Intellisense. This makes using JavaScript and building AJAX applications significantly easier. A double click on HTML control in design mode would automatically create a click event to the button and would create the basic skeleton of the JavaScript function. As we see in the depicted image below, JavaScript Intellisense is inbuilt now. Other JavaScript Intellisense features include Intellisense for external JavaScript libraries and adding Intellisense hints to JavaScript functions.
JavaScript Debugging

One new JavaScript feature in VS 2008 is the much-improved support for JavaScript debugging. This makes debugging AJAX applications significantly easier. JavaScript debugging was made available in VS 2005 itself. However, we had to run the web application first to set the breakpoint or use the “debugger” JavaScript statement.

VS 2008 makes this much better by adding new support that allows us to set client-side JavaScript breakpoints directly within your server-side .aspx and .master source files.

We can now set both client-side JavaScript breakpoints and VB/C# server-side breakpoints at the same time on the same page and use a single debugger to step through both the server-side and client-side code in a single debug session. This feature is extremely useful for AJAX applications. The breakpoints are fully supported in external JavaScript libraries as well.
4. Few Other Features and Enhancements

Below is a list of few other enhancements and new features included in Microsoft Visual Studio 2008.
Project Designer

Windows Presentation Foundation (WPF) applications have been added to Visual Studio 2008. There are four WPF project types:

* WinFX Windows Application
* WinFX Web Browser Application
* WinFX Custom Control Library
* WinFX Service Library

When a WPF project is loaded in the IDE, the user interface of the Project Designer pages lets us specify properties specific to WPF applications.
Data

Microsoft Visual Studio 2008 Beta 2 includes the following new features to incorporate data into applications:

* The Object Relational Designer (O/R Designer) assists developers in creating and editing the objects (LINQ to SQL entities) that map between an application and a remote database
* Hierarchical update capabilities in Dataset Designer, providing generated code that includes the save logic required to maintain referential integrity between related tables
* Local database caching incorporates an SQL Server Compact 3.5 database into an application and configures it to periodically synchronize the data with a remote database on a server. Local database caching enables applications to reduce the number of round trips between the application and a database server

LINQ � Language Integrated Query

LINQ is a new feature in VS 2008 that broadens great querying capabilities into the language syntax. LINQ introduces patterns for querying and updating data. A set of new assemblies are provided that enable the use of LINQ with collections, SQL databases, and XML documents.
Visual Studio 2008 Debugger

The Visual Studio 2008 debugger has been enhanced with the following features:

* Remote debugging support on Windows Vista
* Improved support for debugging multithreaded applications
* Debugging support for LINQ programming
* Debugging support for Windows Communications Foundation
* Support for script debugging, including client-side script files generated from server-side script now appear in Solution Explorer

Reporting

Visual Studio 2008 provides several new reporting features and improvements such as:

* New Report Projects: Visual Studio 2008 includes two new project templates for creating reporting applications. When we create a new Reports Application project, Visual Studio provides a report (.rdlc) and a form with a ReportViewer control bound to the report.
* Report Wizard: Visual Studio 2008 introduces a Report Wizard, which guides us through the steps to create a basic report. After we complete the wizard, we can enhance the report by using Report Designer.
* Expression Editor Enhancement: The Expression Editor now provides expressions that we can use directly or customize as required.
* PDF Compression: The ReportViewer controls can now compress reports that are rendered or exported to the PDF format.
Note: This article is taken from CodeProject

Using Windows APIs from C#

June 9, 2009

Introduction

This article shows how to control other windows and trigger events for their controls using Windows APIs.

In this sample, I simply get a handle for the Calculator window using the FindWindow API, get a handle for the Calculator buttons using FindWindowEx, and trigger the Button Click event for any required buttons, using the SendMessage API.
Background

The main idea I want to demonstrate here is that any form/dialog in Windows must have a window handle; with this handle and using the windows related APIs, you can control the form/dialog and trigger events for its controls.

Here’s the code. I think it is well commented and needs no more explanation:
Collapse

int hwnd=0;
IntPtr hwndChild=IntPtr.Zero;

//Get a handle for the Calculator Application main window

hwnd=FindWindow(null,”Calculator”);
if(hwnd == 0)
{
if(MessageBox.Show(“Couldn’t find the calculator” +
” application. Do you want to start it?”,
“TestWinAPI”,
MessageBoxButtons.YesNo)== DialogResult.Yes)
{
System.Diagnostics.Process.Start(“Calc”);
}
}
else
{

//Get a handle for the “1″ button

hwndChild = FindWindowEx((IntPtr)hwnd,IntPtr.Zero,”Button”,”1″);

//send BN_CLICKED message

SendMessage((int)hwndChild,BN_CLICKED,0,IntPtr.Zero);

//Get a handle for the “+” button

hwndChild = FindWindowEx((IntPtr)hwnd,IntPtr.Zero,”Button”,”+”);

//send BN_CLICKED message

SendMessage((int)hwndChild,BN_CLICKED,0,IntPtr.Zero);

//Get a handle for the “2″ button

hwndChild = FindWindowEx((IntPtr)hwnd,IntPtr.Zero,”Button”,”2″);

//send BN_CLICKED message

SendMessage((int)hwndChild,BN_CLICKED,0,IntPtr.Zero);

//Get a handle for the “=” button

hwndChild = FindWindowEx((IntPtr)hwnd,IntPtr.Zero,”Button”,”=”);

//send BN_CLICKED message

SendMessage((int)hwndChild,BN_CLICKED,0,IntPtr.Zero);

}

Points of interest

I think controlling windows in other processes can be very helpful in many situations like:

1. Ensuring that a main application is running before starting a dependant application.
2. Automating some tasks.

WCF

June 8, 2009

Overview
[ Back To Top ]

User Interfaces in any software application are an extremely important aspect of any programming model. Designing effective user interfaces gives measurable benefits to the users of the software to whom it’s intended. The objective of Windows Presentation Foundation (WPF) is to provide developers with an effective tool to design and develop attractive, effective user interfaces. WPF helps to create dynamic, data driven presentation systems. It also provides a common programming model for browser based and standalone applications. The objective of this article is to provide an introduction of WPF to the readers who are new to this technology and to present its important features.
What is Windows Presentation Foundation?
[ Back To Top ]

Windows Presentation Foundation, code name Avalon, is a graphical subsystem feature of the .NET Framework 3.0 and comes as a built in package with Microsoft Windows Vista operating system. WPF can also be installed with other popular Windows operating systems like Windows XP SP2 and Windows Server 2003. The objective is to present a steady programming model for applications with isolation between User Interfaces and Business Logic layers. A WPF application is mostly web based but it can also be implemented on a desktop environment. The visual aspects of Windows based programming that expects rich graphics, controls design and development, are well handled by WPF. Many application services like User Interface, fixed documents, adaptive documents, 2D and 3D drawings, animation, audio, video etc. work together in unison under WPF. Microsoft Silverlight that is based on XAML and JScript is a web based subset of WPF. Silverlight helps develop web and mobile applications with codes similar to .NET applications and the applications are similar to Flash.

WPF allows developers to create applications that are friendly and rich in quality to the target users. Developers can use WPF in building applications similar to building applications on Win32 and DHTML based applications and content. Unlike being a typical tool for only developing enhanced graphics, WPF takes care of all forms of presentations like User Interface, media, vector graphics, and documents that can be looked as a novelty in the Windows platform.
WPF and XAML
[ Back To Top ]

WPF reduces the amount of procedural code in application specifications and enables increased collaboration amongst various team members in the development team and in turn, rationalizes the development process. XAML is the new technology from Microsoft that drives this union between design and implementation. XAML is a declarative mark up language based on XML and is used in initializing structured values and objects. The acronym stands for Extensible Application Markup Language. XAML is designed as an enhanced method of developing application user interfaces and is used extensively in the .NET Framework 3.0 technologies, mostly in WPF. XAML helps create graphically rich visual User Interfaces (similar to the ones created by Adobe Flash, UIML etc.) when used in WPF. WPF supports various features like 2D and 3D objects, animations, rotations, and various other effects.

The XAML advantage to WPF goes to its declarative nature that allows developers to describe the behavior and integration of components without using procedural programming. This helps a developer to create a working application even without much knowledge of procedural programming. This case however is rare where an entire application is developed on XAML, but in practical scenarios, XAML enables the designers to more effectively contribute during any application’s development. XAML, however, is not specific to WPF or .NET and the standard is in use by other technologies too.

How WPF works
[ Back To Top ]

This section provides a brief description of the architecture of WPF which spreads across both managed code and native code components. The managed code only provides the publicly exposed API. The major code portions of WPF are the PresentationFramework, PresentationCore, and milcore. The composition engine of WPF is a native component and is known as MIL (Media Integration Layer) and resides in the milcore.dll. Milcore is written in unmanaged code and the interfacing is done with DirectX at this level for providing support for 2D and 3D surfaces. WPF displays are done through the DirectX engine. The composition engine in WPF is highly performance sensitive and demands forsaking of several CLR advantages for enhancing performance. PresentationCore (presentationcore.dll) implements the core services for WPF and the PresentationFramework (presentationframework.dll) is responsible for the presentation features of the end users. The major WPF subsystems are as follows; Object, Threading.DispatcherObject, Windows.DependancyObject, Windows.Media.Visual, Windows.UIElement, Windows.FrameworkElement, Windows.Controls.Control. Details of the WPF architecture are beyond the scope of this article.
Features
[ Back To Top ]

This section provides some salient features of the WPF.

1. WPF offers all graphics as Direct3D applications. Direct 3D applications are supported by Microsoft Windows Operating Systems and are part of Microsoft’s DirectX API. This is primarily used to render three dimensional graphics in performance savvy applications (e.g. games).

2. Interoperability with Win32 is supported by WPF. Windows Presentation Foundation can be used internally to Win32 pre-existing code through hosting and at the same time, Win32 code can be used inside WPF. ElementHost and WindowsFormsHost classes can be used to enable interoperability of WPF with Windows Forms.

3. WPF provides a built-in set of brushes, pens and geometries and also provides shape primitives for 2D graphics. The WPF 3D features are just a subset of the Direct3D feature set. Additionally, WPF provides better integration with User Interfaces, documents and media. This way it provides 3D UI, media and documents.

4. WPF supports all the standard image formats and video formats like WMV, MPEG and AVI. WPF also supports time based animations, Open Type Font features and Text rendering.

5. WPF supports time based animations. These animation effects can be defined object wise and can be directly accessed from XAML markup. Animations can also be activated by external events like user action. WPF comes with a set of built-in effects that may be used readily by the designers.

6. Developers with the help of WPF can write image codecs for their specific image file formats. This happens due to the fact that Windows Imaging Component codecs and APIs can be locally used by WPF.

7. WPF supports XML Paper Specification documents. It also supports reading and writing of paginated documents.

8. WPF offers many built-in controls like button, list box etc. There is a significant aspect to be considered for WPF and that is the logical separation of a control from its appearance. The visual appearance of any control can be changed by modifying the corresponding control template. A control may have any other control or layout and this enables excellent control on the composition.

9. WPF offers some useful, built-in effects such as bitmap effects, special effects like dropshadows and blurring, etc. Other special effects can also be easily implemented by WPF.

10. Binding and manipulation of application data is supported by WPF through its built-in set of data services. Data templates for controlling data presentation are also provided by WPF.
Suggested Readings
[ Back To Top ]

I would like to suggest interested readers to browse through these links to get started on WPF.

Get Started Using Windows Presentation Foundation

Windows Presentation Foundation Tutorials

Windows Presentation Foundation Resource Sites

Windows Presentation Foundation Video Training

Windows Presentation Foundation Slide Show

WPF Tutorials on ASP Alliance

WCF and WPF Downloads

Review: Essential Windows Presentation Foundation

Review: Programming WPF
Conclusion
[ Back To Top ]

Windows Presentation Foundation is an essential change from how Windows allowed the working of interactive applications earlier. In this article we have introduced WPF to the beginners and illustrated its salient features. However, there are loads of things to learn about WPF to effectively use this new technology from Microsoft. It is recommended for beginners who are new to this technology to read more on WPF before getting started apart from this article, and in this regard, few tutorials links are also provided as references. WPF from Microsoft aims to stand tall amidst various competitions and criticisms in the creative development community and we expect greater offerings from Microsoft in this area in the near future.


Follow

Get every new post delivered to your Inbox.