Search This Blog

Saturday, March 13, 2010

Working with Delegates in C#

In this article I'll discuss what delegates are with lucid code examples.
Delegates in C# are like functions pointers in C/C++. A multi cast delegate can refer to several methods. A delegate can be used to invoke a method, the call to which can only be resolved or determined at runtime. This article discusses what delegates are and how they can be used in C# with lucid code examples.

Friday, March 12, 2010

Understanding Connection Pooling in .NET

Connection Pooling can increase the database performance to a huge extent. This article discusses what Connection Pooling actually is, how it can boost the performance of database access and how we can create a Connection Pool in .NET and add and remove connections to it.

Connecting to the database is resource intensive and a relatively slow operation in an application but the most crucial of them all. A Connection Pool is a container of open and reusable connections. A Connection Pool is released from the memory when
the last connection to the database is closed. The basic advantage of using Connection Pooling is an improvement of performance and scalability while the main disadvantage is that one or more database connections, even if they are currently not being used, are kept open. The Data Providers in ADO.NET have Connection Pooling turned on by default; if you need to turn it off, specify Pooling = false in the connection string being used. Connection Pooling gives you an idle, open, reusable connection instead of opening a new one every time a connection request to the database is made. When the connection is closed or disposed, it is returned to the pool and remains idle until a request for a new connection comes in. If we use Connection Pooling efficiently, opening and closing of connections to the database becomes less resource expensive. This article discusses what Connection Pooling is all about and how Connection Pooling can be used efficiently to boost the performance and scalability of applications.

Working with Images Using .NET

In this code snippet I will examine how to work with images using Visual Studio .NET 2003 and SQL Server 2000 database.

Some applications, be it desktop or web, require working with images.  Aptly speaking, the good paradigm is banking applications.  Withdrawal of an amount of money from a bank account requires signature verification of the account holder.  Normally, specimen signatures of customers are archived as images in such applications.

Working with Images Using .NET


In this code snippet I will examine how to work with images using Visual Studio .NET 2003 and SQL Server 2000 database.


Some applications, be it desktop or web, require working with images.  Aptly speaking, the good paradigm is banking applications.  Withdrawal of an amount of money from a bank account requires signature verification of the account holder.  Normally, specimen signatures of customers are archived as images in such applications.

There can be a couple of ways to work around to store images.  One is typically to tag each image with a unique identifier and save the image at a physical location accessible by the application. Store that unique identifier and the physical absolute/relative path in a database table.  Now, when the application looks in for a given identifier from database table then the path against the identifier can be pulled from the table and uses that path in any image control to display the image.

Multithreading with an Example of .NET Application

In this article I will discuss the basics of multithreading and how it could be effective over a single thread application. It also includes the advantages and disadvantages of multithreading. The article includes the complete .NET project for creating a simple multithreaded application.

Threads are also known as lightweight processes.  However, if we go into depth then we would know that a thread is not actually a process; rather it provides ways for executing different parts of a program.  Now let us discuss what it actually means by multithreading.  Multithreading (as the name suggests multi+threading) is nothing but an efficient execution of multiple threads at a time to enhance the performance of the application.  For example, we are doing a file copy operation with a status bar on UI indicating the completion percentage.  Here we need to keep track of how much file size is copied and at the same time we also need to advance the progress bar accordingly.  This can not be done efficiently in a single thread and you have to use multiple threads.
The above example shows just one instance where we are forced to use multithreading.  However, when we are not forced we can also use this for the betterment of the application performance. And of course, all this depends on how effectively the thread is implemented in an application.  Most of the developers do not use multithreaded applications and continue with a single thread.  However, the efficient use of threads can give birth to a highly powerful application.

Thursday, March 11, 2010

Localization in ASP.NET 2.0 (advanced)

This article will cover some more of the Visual Studio 2005 enhancements for making Resources easier to include in your project, as well as showing the various ways that Resources can be included through code within your applications.

In the previous article, the Visual Studio .NET 2005 features for easily Localizing a web site were explored without using any code.

This article will cover some more of the Visual Studio 2005 enhancements for making Resources easier to include in your project, as well as showing the various ways that Resources can be included through code within your applications.

In Visual Studio 2005 Web Site's there is the concept of a "Resources" folder living on the root of your web site. In this folder you can place, surprisingly enough, resources. Unlike the Resources discussed in the Previous Article, any Resources placed in the Resources folder have scope across the whole Application, in that they can be accessed from any Web Form or Code, whereas the Resources stored in "LocalResources" folders are only associated with a specific .aspx.

Visual Studio 2005 not only supports the use of the Resources folder, it's embraced and encouraged, this is done by offering Developers Strongly Typed access right in to their Resource files through the Resources Namespace, for example if there is a .resx in the Resources folder called "Bob" and within Bob.resx there is a Resource String called "Alice" with a value of Cake, in your .aspx all you need to do to access the Resource String "Alice" (with full intellisense of course) is type: -

string AlicesFavFood = Resources.Bob.Alice.ToString();

Oh, ResGen is Dead, RIP ResGen.

Now you've picked yourself up off the floor after that moment of enthusiastic bouncing let's continue.

The above happens without the need to recompile, all that you the developer needs to do, is Save the .resx file and you instantly get all the Intellisense within your application.

Intellisense on your Resources is really usful, especially if you're no the person that put together the Resource files, this allows you to quickly get hold of the right Resources within your applications. However. And it's a Big However. To me, it's very rare that I will know the name a of Resource for my controls before I come to actually write the controls them selves, this leaves us in somewhat of a Chicken and Egg situation.

I see this functionality being useful mainly where you have General resources, such as you might have on an e-commerce site, strings such as "Price", "Shopping Basket" and "Checkout" might be strings you regularly use in many different e-commerce applications, I see having a Resource file that you drop in to each of your projects with General Resources being used with the Intellisense, otherwise I think it may be an otherwise unused piece of Visual Studio 2005 functionality.

Accessing resources in code can be achieved in a variety of ways, mainly depending on the source of the Resource. Along with the meta Resources discussed in the previous article it's also possible to explicitly include Text from Resource Files stored in the LocalResources folder as so: -

Or in Code Beside/Behind you can access the LocalResources of a page by using the GetPageResourceObject() method of the Page.

string LocalResource = (string)GetPageResourceObject("LabelResource1.Text");

It's also possible to Localize static content, i.e. just basic strings that don't need to have Server Side access.

Some Default Content

Using Application level resources is possible through the Resources member as shown above, but it can also be accessed programatically in pages via the GetAppResourceObject() method, as so: -

string ApplicationResource = (string)GetAppResourceObject("Bob", "Alice");

As well as the Programatic access, it's possible to retreive the Application level Resources declaritavly like this: -

So there you have some more of the new features in ASP.NET 2.0, everything about Localization in ASP.NET 2.0 is so much easier. The next articles in this series will discuss .Resource files in ASP.NET 2.0 and Database stored Resources.

Happy Dotnetting... :)

How to do a language switch in a master page.

As the rap song goes: “There’s no champagne in the champagne room...”, there is no page in MasterPage. It derives from UserControl. As such it does not support the InitializeCulture() method for us to override as described in this post. Newbies love master pages, even though half the time they do not understand them, so here is a solution, compounding the misuse, but here it goes.

Don't try to access controls in InitializeCulture()

InitializeCulture() is an empty protected virtual method in the Page class. So it is empty in the inherited class too that the IDE generates. When overriding it there is no need to call the base method.

What is noteworthy is the fact that is IS VERY EARLY ON, in the page lifecycle. Way before any controls exist. So most postback handlers that depend on controls are worthless for setting the culure in the thread, BECAUSE THEY ARE ALL LATE.

So how do we do a dropdown or a listbox to switch languages? Isn’t the dropdown a server control? Here is the magic that keeps so many people, that are enamored with localization, stumped.

There is a Http collection called the “form data set”  which is passed in every request. It is a name value collection. The keys are the name attributes of the html elements in the form tag. The values depend on the element. For a dropdown that value is the selected value (if no value, then the selected text, if none then the first item) These are what is known as “successful control” rules. At the time of submission the browser gathers up these values and submits the collection along with the request.

Notice no aspnet so far. The aspnet representation of that collection is the HttpRequest.Form property. Its type isSystem.Collections.Specialized.NameValueCollection and thenicest thing is, IT HAS NOTHING TO DO WITH SERVER CONTROLS. How do we know? Just try retrieving the values from a regular html form element without runat=server and you will know; all without the aspnet runtime doing anything more than reading the browser request.

So we get it for free, and we get it right away and we get it every time.This is the key concept. Plus the collection items map to form elements. So we can grab values out of it inside the InitializeCulture() method and never wait for the full controls to be built. The HttpRequest is exposed as the Request property of the page class.

the server control
<asp:DropDownList runat="server" ID="ddl" AutoPostBack="true" />

renders as the html element, with both the name and value attributes the same(provided not declared in a template like a user control or a master page)
<select name="ddl" id="ddl">

Here is a sample of that code.   Here is a video demo

EVERY PAGE NEEDS THE THREAD SET DE NOVO, because the thread dies at the end of the page lifecycle. So it becomes a pain to do this code over and over again. We can inherit from our own page class that overrides this method and never have to see it from code behind. The problem is that OO intimidateas the hell out of newbies. Also the class would be too closely coupled with the form element under question and I myself have a paranoia of coupling business logic. User controls and master pages do not support the InitializeCulture() method.
So System.Globalization is really in the way of code globalization! ;)
Here is a solution how to do a language switch dropdown in a master page with globalized code.

Happy Dotnetting... :)

Wednesday, March 10, 2010

Localization in ASP.NET 2.0


In this article, I am going to present the new localization feature provided by .NET framework 2.0. Throughout the article, the new tools provided by Visual Studio 2005 to support localization will be highlighted and used to show you how easy it is to localize your web applications with ASP.NET 2.0.


A few years ago we started hearing new terms in economics about globalization and integration of international markets.  This made many large business companies begin thinking of how to attract markets from all over the world and not only from domestic markets.  The first idea that might come to the company is to have a Multilanguage website; clients from a set of targeted countries can localize their website to their own native language.

ASP.NET 2.0 comes with a rich environment that makes localization of web applications a very easy task to perform.  There are two main kinds of localization in ASP.NET 2.0: implicit localization and explicit localization, each of which will be discussed in more detail throughout this article.

Preliminary Steps

When you think of localizing a web application, some preliminary steps should be taken into account.  Those steps can be summarized in two main points:

Globalization: The main strategy of the web application is set in this step.  The web application architect shall ask the following questions: How many countries or languages are targeted in the application?  What sections are to be localized?  Etc.  In addition, gathering of resources for all the predetermined languages should be collected before any implementation starts.

Localization: The actual localization and implementation through code is done in this step.  The resources needed are supplied to the web application and then it is the developer's role to allow the application being worked on to support all the predetermined languages required by their application.

Localization and Visual Studio 2005

Visual Studio 2005 now ships with a new resource editor that allows you to easily add/remove/update any resource key in any ASP.NET resource file (.resx).

In addition, Visual Studio 2005 makes generating resource files an easy step to do by just going to Toolsà Generate Local Resource while your WebForm is in the Design view.

Moreover, Visual Studio 2005 provides two ways of localizing a web application.  The first is using Local Resources; a local resource is a resource file attached to a WebForm.  Or you could use   Global Resources in which you can combine all common resource keys used by several ASP.NET web forms into a single resource file.

The above tools and concepts will be revisited throughout this article while creating and manipulating resource files.

Working with Local Resources

In this section we are going to show how easy it is to generate a local resource file for any ASP.NET web form.  By local resource we mean that a single resource file is in a many to 1 relationship with the ASP.NET web form.  In other words, if you have a Label server control and you want to show some text in this label for each culture available in the web application, then you place a resource key in an accompanying resource file for a specific culture.  At run time, the resource key will be looked up in the culture-specific resource file, evaluated and replaced with the proper text translation.  You can have several resource files for the same ASP.NET web form, each representing a specific culture.

To generate a local resource file in Visual Studio 2005, start by creating a new website.  Open the default.aspx page and add few controls, including the following:

Label Server Control, with an ID of lblName

TextBox Server Control, with an ID of txtName

Button Server Control with an Id of btnSubmit

The figure below shows what the default.aspx page looks like.

Make sure your default.aspx page is in the design view.  Then go to Tools à click on the Generate Local Resource command.

You will notice two changes to your web application and ASP.NET page.  First of all, a new "system" folder has been added in the web application’s root folder called App_LocalResources.  The App_LocalResources folder has been newly added to the ASP.NET 2.0 web application. This folder holds all the resource files for all the ASP.NET web forms.  The ASP.NET runtime uses the .NET framework, ResourceManager, to perform resource key lookups.  The ResourceManager will look at the App_LocalResources folder at all times.  This means that any resource file located outside this folder will be ignored.

You can easily add a new resource file to that folder to represent any additional language for your web application by simply copying the default resource file of an ASP.NET form and pasting it with a new name.  For instance, if you have the default.aspx.resx resource file, which represents the English language, then you have English set as the default language of your machine.  Now you want to add the Arabic-Lebanese language for your web application.  You simply copy the default.aspx.resx and rename it to  This way you have added support for a new language.  The only thing left to do is to change the values of every resource key inside the resource file added.

Next, open the source view of the default.aspx page and you will notice new tags have been added to the controls that require localization.

Listing 1

<form id="form1"runat="server">
<asp:Label ID="lblName"runat="server"meta:resourcekey="lblNameResource1">asp:Label>
<asp:TextBox ID="txtName"runat="server"meta:resourcekey="txtNameResource1">asp:TextBox><br/>
<br />
<asp:Button ID="btnSubmit"runat="server" Text="Submit"meta:resourcekey="btnSubmitResource1" />div>

As you can see, a “meta:” tag has been added to every server control together with a resource key that corresponds to the resource key entry in the default.aspx.resx resource file.

The snapshot of the default.aspx.resx is shown below.

Figure 2

For each server control a single resource key has been added with multiple properties of .Text and .ToolTip.

As mentioned above, at runtime the resource key will be evaluated and the corresponding text in the resource file will be displayed.

Now we can add the Text and ToolTip values for every control in the resource file.  However, before we can run this page and see how it is being localized automatically, we have to specify the Culture and UICulture properties in the Page directive.  This way, the ASP.NET runtime will know the culture used and apply the specific resource file for that chosen culture.

To do so, add the following to the Page directive:

Listing 2

Culture="auto:en-US" UICulture="auto"

We have set the Culture to be auto and have a default value of en-US and the UICulture set to auto.  Having an auto property means that the request will automatically detect the culture specified on the client browser.

Run the application and you will see that the server mainly controls the Label and that the Button Text property will be evaluated based on the culture and the resource file of that culture.

To support an additional culture, copy the original resource file as mentioned above and add your translation for the entire resource key and test it in your browser.  To test your application with other cultures, refer to the following: Setting a Preferred Language in Internet Explorer.

Working with Global Resources

As mentioned above, the Local Resources are in a many to 1 relationship with ASP.NET web forms.  In some cases, your ASP.NET web forms in an application might share a set of resource keys.  Instead of having redundant data in your resource files, ASP.NET 2.0 introduces the App_GlobalResources folder which lets you place all the global resources, i.e. resources shared by some ASP.NET web forms, in one location.

To create a new global resource, right click your web application root, add an ASP.NET Folder and choose App_GlobalResources.  Then right click this folder and add a new Resource file.  The structure of this resource file is the same as the structure of the resource files placed inside the App_LocalResources.  However, the name of this file can be any meaningful name and is not limited to the name of the ASP.NET web form.  This file, as mentioned above, will hold shared resource keys for several ASP.NET web forms.

To have the same resource file available for several languages, you need to follow the same steps mentioned while discussing the local resources.  The default global resource file is named resource.resx and the French version is written as

Add a new Label Server control to the default.aspx page as:

Listing 3

<asp:Label ID="lblwelcome" runat="server"/>

Inside the resource.resx and files add one resource key called “welcome.”


Key: welcome

Value: Welcome to our website


Key: welcome

Value: Bienvenue à notre site Web

To link the global resource to the above label, we need to do the following:

Right click on the label in Design view, click on properties and then choose Expressions.  A pop-up window is then opened for you so choose from the Bindable properties, Text property and form the Expression Type, Resources.  In the Expression Properties you set the ClassKey to be resource.resx and the ResourceKey to be welcome.

You can see now how the label server control looks.

Listing 4

<asp:Label ID="lblwelcome"runat="server" Text="<%$ Resources:resource, welcome%>">asp:Label>

Instead of having implicit localization as the case of local resources, the explicit localization in global localization is done by evaluating an expression and giving this expression the original resource name and the resource key in that resource file.

Now, run your application in a browser and try to change the default culture of your browser from English to French and see how the text inside the label changes as specified in the two resource files mentioned above.

CurrentCulture and CurrentUICulture

Before going on with this article, let us stop and discuss the two main properties of concern, mainly the CurrentCulture and CurrentUICulture.

CurrentCulture and CurrentUICulture are both of the type CultureInfo which belongs to the System.Globalization.

CurrentCulture and CurrentUICulture are both properties of the current thread represented by System.Threading.Thread.CurrentThread.CurrentCulture and System.Threading.Thread.CurrentThread.CurrentUICulture

CurrentCulture is used mainly to format the Dates, Currencies, etc.  For that reason, it should be set as specific and not left as neutral.  For instance, you need to set the CurrentCulture as:

Listing 5

System.Threading.Thread.CurrentThread.CurrentCulture= newCultureInfo("ar-LB");

We have set the current culture to be a specific culture, Arabic - Lebanese.  So make sure to always be specific in specifying the CurrentCulture.

CurrentUICulture is mainly used for language/text translations.  The ResourceManager is based upon the CurrentUICulture.  It does not matter whether the culture set here is specific or neutral.  For instance, either ar or ar-lb works fine with the CurrentUICulture.

Listing 6

System.Threading.Thread.CurrentThread.CurrentCulture= newCultureInfo("ar");

Programmatically Setting Culture and UICulture

In the above discussion, we have seen that the Culture and UICulture properties inside the Page directive were set to "auto."  In this section we will learn how to set both properties programmatically inside our VB.NET or C# code.

Create a new ASP.NET web form and add the following code:

Listing 7

<asp:DropDownList ID="ddlLanguage"runat="server" AutoPostBack="True">
<asp:ListItem Selected="True"Value="auto">Autoasp:ListItem>
<asp:ListItemValue="en-US">English (US)asp:ListItem>
<asp:ListItemValue="en-GB">English (UK)asp:ListItem>

This DropDownList lists a few options to change the default culture.  One of the methods of the Page class is called InitializeCulture().  This method is being executed in the early stages of the page creation.  It is the responsibility of this method to set the Culture and UICulture of the current request.  We will override this method to build our own logic in setting the above two mentioned properties based on the selection from the DropDownList.

Copy this code and paste it inside your code behind class.

Listing 8

protected override void InitializeCulture()
  string lang =Request["DropDownList1"];

  if ((lang != null))
    if (lang != "")
      Thread.CurrentThread.CurrentUICulture =new CultureInfo(lang);
      Thread.CurrentThread.CurrentCulture =CultureInfo.CreateSpecificCulture

In this piece of code, we are first getting the selection from the language DropDownList.  Notice that we did not use the DropDownList properties to access the selected option; this is done on purpose, since the first time the page is visited the DropDownList will not be created.  We use the Request object to access the form's controls.

The CurrentUICulture property is set to the language selected.

The CurrentCulture, as mentioned above, should always be set to a specific culture.  Keeping that in mind, we have to use the static method of CultureInfo object, CreateSpecificCulture().   This takes as an input a parameter specifying the culture and returns a CultureInfo instance having a specific culture set.

Once a culture is chosen from the DropDownList, the current Culture and UICulture will be set accordingly.


We have presented the new localization features in ASP.NET 2.0.  Visual Studio 2005 has been improved to give a better experience in many aspects, mainly the Localization of web applications.  Two new features in ASP.NET 2.0 Localization, Implicit and Explicit localization, have been discussed.  A distinction between CurrentCulture and CurrentUICulture was given showing the similarities/differences and the effect of each of them.  Finally, a programmatic way of setting the CurrentCulture and CurrentUICulture was shown.

Hope you enjoyed this article.

Happy Dot Netting!!

Thursday, March 04, 2010

Understanding ASP.NET View State continued...

The Role of View State

View state's purpose in life is simple: it's there to persist state across postbacks. (For an ASP.NET Web page, its state is the property values of the controls that make up its control hierarchy.) This begs the question, "What sort of state needs to be persisted?" To answer that question, let's start by looking at what state doesn't need to be persisted across postbacks. Recall that in the instantiation stage of the page life cycle, the control hierarchy is created and those properties that are specified in the declarative syntax are assigned. Since these declarative properties are automatically reassigned on each postback when the control hierarchy is constructed, there's no need to store these property values in the view state.
For example, imagine we have a Label Web control in the HTML portion with the following declarative syntax:

  Text="Hello, World!">
When the control hierarchy is built in the instantiation stage, the Label's Text property will be set to "Hello, World!" and its Font property will have its Name property set to Verdana. Since these properties will be set each and every page visit during the instantiation stage, there's no need to persist this information in the view state.

Understanding ASP.NET View State continued...

Stage 0 - Instantiation

The life cycle of the ASP.NET page begins with instantiation of the class that represents the requested ASP.NET Web page, but how is this class created? Where is it stored?
ASP.NET Web pages, as you know, are made up of both an HTML portion and a code portion, with the HTML portion containing HTML markup and Web control syntax. The ASP.NET engine converts the HTML portion from its free-form text representation into a series of programmatically-created Web controls.
When an ASP.NET Web page is visited for the first time after a change has been made to the HTML markup or Web control syntax in the .aspx page, the ASP.NET engine auto-generates a class. If you created your ASP.NET Web page using the code-behind technique, this autogenerated class is derived from the page's associated code-behind class (note that the code-behind class must be derived itself, either directly or indirectly, from the System.Web.UI.Page class); if you created your page with an in-line, server-side "script" block, the class derives directly from System.Web.UI.Page. In either case, this autogenerated class, along with a compiled instance of the class, is stored in the WINDOWS\Microsoft.NET\Framework\version\Temporary ASP.NET Files folder, in part so that it doesn't need to be recreated for each page request.

Understanding ASP.NET View State


Microsoft® ASP.NET view state, in a nutshell, is the technique used by an ASP.NET Web page to persist changes to the state of a Web Form across postbacks. In my experiences as a trainer and consultant, view state has caused the most confusion among ASP.NET developers. When creating custom server controls or doing more advanced page techniques, not having a solid grasp of what view state is and how it works can come back to bite you. Web designers who are focused on creating low-bandwidth, streamlined pages oftentimes find themselves frustrated with view state, as well. The view state of a page is, by default, placed in a hidden form field named __VIEWSTATE. This hidden form field can easily get very large, on the order of tens of kilobytes. Not only does the __VIEWSTATE form field cause slower downloads, but, whenever the user posts back the Web page, the contents of this hidden form field must be posted back in the HTTP request, thereby lengthening the request time, as well.
This article aims to be an in-depth examination of the ASP.NET view state. We'll look at exactly what view state is storing, and how the view state is serialized to the hidden form field and deserialized back on postback. We'll also discuss techniques for reducing the bandwidth required by the view state.