Saturday, June 27, 2009

Understanding Delegates

In this article we will deal with Delegates in C#. I tried my best to keep this article very simple so that people could understand the basics of delegates.

In simple words when you invoke something on Delegates it Delegates( means hand over) to some one. Delegates acts like a bridge between a method that is invoked and a person responding.

Perhaps you can recall from high-school days that sound travels with Particles. Sound emitted at Point A(Source) reaches Point B (Receiver) with the help of medium. An example of a medium is an interface to travel sound from Point A to Point B. Similary, Delegates are interfaces to pass functionality from one object to another object. You guys may me wondering why I am teaching physics, medium was a perfect example for a Delegate.

It looks like a method Overriding but Delegates concept is much more robust and powerfull than method overriding.


A delegate in C# allows you to pass methods of one class to objects of other classes that can call those methods. You can pass method Play (method name) in Class A, wrapped in a delegate, to class B and Class B will be able to call method Play in class A.
Delegates in C# are objects which points towards a function which matches its signature. Delegates are reference type used to encapsulate a method with a specific signature.
A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to function pointers in C++; however, delegates are type-safe and secure.
You can pass both static and instance methods.
A delegate represents a class.
A delegate is type-safe.
You can combine multiple delegates into a single delegate.
You can use delegates both for static and instance methods.
You can define delegates inside or outside of classes.
You can use delegates in asynchronous-style programming.
Delegates are often used in event-based programming, such as publish/subscribe.
The delegate declaration takes the form:

[attributes] [modifiers] delegate result-type identifier ([formal-parameters]);attributes (Optional)The allowed modifiers are new and the four access modifiers. result-typeThe result type, which matches the return type of the method.

identifierThe delegate name.

formal-parameters (Optional)Parameter list. If a parameter is a pointer, the delegate must be declared with the unsafe modifier. Delegates are the basis for events.

Functionality of Delegates can be accomplished in four steps.

1 Declare a delegate object with a signature that exactly matches the method signature that you are trying to encapsulate.

2. Define all the methods whose signatures match the signature of the delegate object that you have defined in step 1.

3. Create delegate object and plug in the methods that you want to encapsulate.

4. Call the encapsulated methods through the delegate object.

Gathering all my posts in one place

hey guys i thought i should gather all my posts to one place so from now on i'll post everything here and also trying to recollect the things that i posted to different websites

Tuesday, June 23, 2009

Globalization and Localization

There are many tutorials which explain you about localization / globalization concept. In this article I just tryed to explain every single point from the developer/programmer point of view.Let me brief you about Resource files.
"aspx.resx" (resource) files: Resource files are xml files, which stores string, file paths (image), which are required to translate in to other languages.
"App_GlobalResources": You can keep files which need to be accessed throughout the application. So in our application I have kept "TextDirect" & "EmailFormat" which required to access in maximum pages. In short common strings.
"App_LocalResources": Local resources are associated with the single web pages, In this folder I have kept lables and strings which are specific to particualt aspx page it self.Note: Since I am showing this in english and arabic. So every aspx page will have two different resource files.For Example:I have "Registration.aspx" page, for this page I had made files as follows:
Registration.aspx.ar.resx (for arabic content to be stored).
Registration.aspx.resx (for english content to be stored).The above files are local, now letus consider files which can be accessed globally as.
MulResource.resx
MulResource.ar.resxThese files are used for storing "EmailFormat" & "TextDirection" which is common for most of the pages.To create a resource file manually:Make sure that your Web site has a folder in which to store the resource file by doing one of the following:If you are creating a global resource file, you must have a folder named App_GlobalResources. To create the folder, in Solution Explorer, right-click the name of your Web site, click Add Folder, and then click App_GlobalResources Folder. There can only be one of these folders in an application, and it must be located at the root of the application.If you are creating a local resource file, you must have a folder named App_LocalResources. To create the folder, in Solution Explorer, right-click the name of your Web site, click Add Folder, and then click App_LocalResources Folder. There can be many of these folders in an application, and they can be located at any level in the application.To create a resource file, right-click the App_GlobalResources or App_LocalResources folder, and then click Add New Item.Global resource files must be in the App_GlobalResources folder. If you try to create a .resx file outside of this folder, Visual Web Developer prompts you to create it in the folder.Glbalization:It is process by which you can develope application / program so that it can be used by the various regions/cultures. Let us consider that you have made a product called as "Shopping Cart" and you want to sell it to different regions, since it is online say arabic people should able to read the info in Arabic & English people should read it in English. To achive this we have to use something called as localizationLocalization:It is process of using specific regional/cultural info so that your program uses local language.Culture:Every region has different language and language is depend on different geographical location.For example: "ar-EG" ar is the code for arabic language & EG means this language is spoken in Egypt country/region so "ar-EG" sets for Arabic-Egyption. Similarly "en-US" stands for English-United State.Note: In IE the user can change the culture by going to Internet Options->General->Languages. For this to work, we need to set both the Culture and the UICulture to auto and enableClientBasedCulture = trueSetting Page Culture:You can set the page culture by two ways:

Setting culture by programmatically.protected override void InitializeCulture(){//string culture = Request.Form["ddSelLanguage"];string culture = Session["Language"].ToString();if (string.IsNullOrEmpty(culture))culture = "Auto";//Use thisUICulture = culture;Culture = culture;//OR Thisif (culture != "Auto"){System.Globalization.CultureInfo MyCltr = new System.Globalization.CultureInfo(culture);System.Threading.Thread.CurrentThread.CurrentCulture = MyCltr;System.Threading.Thread.CurrentThread.CurrentUICulture = MyCltr;}base.InitializeCulture();} Code:In "Default.aspx" file I have a drop-down by which user can select specific language, i have Arabic and English languages and by default "Auto" is set. I have used Auto-postback property of the drop-down & even you can make use of submit button for the same.Once you got the selected language you can hold that value in the session as explained in the above code.
Session["Language"] = Request.Form["ddSelLanguage"];While overriding the InitializeCulture() method you can assign this to the culture variable.In this application i have tryed to explain with two different forms:
User registration form.
Send Email (In which I have also explained that how can we make use of built-in asp.net validation controls).And on both the pages i have shown as we can switch on different pages by making use of .Now let us have a look at "Registration.aspx" page code.
@ Page Language="C#" AutoEventWireup="true" CodeFile="Registration.aspx.cs" Inherits="Registration" meta:resourcekey="RegResource" %>This code is preety much similar with the code which get generated normally for any aspx page, only difference is that:meta:resourcekey="RegResource" Here I want to explain in little depth, the concept of storing values like key-value pair and accessing values in the aspx page. Forexample if you refer to "Registration.aspx.resx" & "Registration.aspx.ar.resx" pages you will notice thatA resourceKey "RegResource.Title" has value "Registration" similarly in the other language. "RegResource.Title" has value, which is directly accessed as shown above.' xmlns="http://www.w3.org/1999/xhtml">In the above tag it should have runat="server" attribute or it will give you error use literal runat="server" .As i have already explained you about the global & local resources, in the above we have used dir='$ Resources:MulResource, TextDirection %>' attribute, now let us go little in dept for this, many of you must be aware of "DIR" attribute, it is nothing but the direction or the text in the page by default it is LTR (left to write) to have arabic type of appearance of the page we have to use it as "RTL". In short this act as common for all the pages either LTR or RTL so i have two global resource files as:
MulResource.resx
MulResource.ar.resxIn which you will find "TextDirection" ResourceKey and it's value associated with it, which is used in the above code.I think so far so clear?Now let us see how we can access the value of different labels in our project.For example: On the registratio page i have label called as "lblFirstName" and it's values are stored in the corrosponding resource files viz.
Registration.aspx.resx
Registration.aspx.ar.resxHere is code to make use of the same.

ASP.NET

Working in Nic
Working in Nic Edit Maskfunction mask(str,textbox,loc,delim){var locs = loc.split(',');for (var i = 0; i <= locs.length; i++){for (var k = 0; k <= str.length; k++){if (k == locs[i]){if (str.substring(k, k+1) != delim){str = str.substring(0,k) + delim + str.substring(k,str.length)}}}}textbox.value = str}

Steps of Collection Class
class Leaf {private int intAge;private String strName;// Default Constructor public Leaf() {}// gets and sets the age valuepublic int Age {get {return intAge;}set {intAge = value;}}// gets and sets the strName variablepublic string Name {get {return strName;}set {strName = value;}}}

Object Oriented Programming
An object-oriented programming language (also called an OO language) is one that allows or encourages, to some degree, object-oriented programming techniques such as encapsulation, inheritance, modularity, and polymorphism

Working in ListView Control
ListView control is a new control added into ASP.NET 3.5. It enables you to display data in a format specified by you using templates and styles. It is useful for data in any repeating structure just like DataList and Repeater controls. However, unlike those controls ListView control enable you to edit, insert, delete, sort, paginate data without any extra effortStep 1stFirst create a new .aspx page and go to design view. Go to Data tab of the Toolbox and drag ListView control to your page. Now again go to the Data tab and drag LinqDataSource control to the page. Now configure the LinqDataSource control as described in Make sure that you have selected Enable Delete, Enable Insert and Enable Update checkbox from the smart tag of the LinqDataSource control as displayed in the picture belowStep 2ndNow open the smart tag of the ListView control and choose the Data Source as the LinqDataSource as displayed in the picture below.Step 3rdNow click on Configure ListView … from the smart tag of the Listview. Select Tiled from Layout, Professional from Style and Enable Editing, Enable Inserting, Enable Deleting and Enable Paging from the Options as displayed in the picture below. In the Enable Paging dropdown you may select Next/Previous pager or Numeric pagerStep 4thNow Save your files and press F5 to run. You should see an Insert form in your browsers. Just enter few records, try editing, deleting records. Once the number of records will exceed the PageSize of the DataPagers (that will be automatically inserted into ListView when you will select Enable Paging from the Configure ListView dialogue box) First, Previous, Next and Last button at the bottom will be enabled automatically.Hope you enjoyed playing with ListView and LinqDataSource control. Do let me know if you have any comments or suggestions. Thanks and Happy Coding !!!

Hello

Hello