Siraj ’s heaven.

Imagination is more important than knowledge. -Albert Einstein

Archive for the ‘Asp.net’ Category

Localization in ASP.NET 2.0

Posted by sirajq on April 2, 2008

When you are developing a web site for international users, one questions instantly come to our mind which is how our web site going to support multiple language, currencies, date etc.? Thanks to ASP.Net 2.0, it made our task of making localized application simple and easier. Localization  is the process of designing and developing a software product that function for multiple cultures having different language currencies, date and time. Asp.Net 2.0 has a incredibly good features to support localizaion. These are features are self explanatory and easy to use.   A .Net web forms page have two culture values , Culture and UICulture. Culture is used to determine culture dependent function such as Date, Currency. So it is used for date formatting ,number formatting. UICulture values is used to determine which language the resources should load that is which UI string the resource should use. The two culture settings do not need to have same values. It may be different depending on the application. I will give you brief idea of developing application that support localization.  For example, we want to develop a website which should support english and french language. Functionality of the web site will be same only difference will be the language in which information will be displayed on the pages of web site.

Setting Culture and UICulture

1. Through Web.Config


<configuration>
<system.web>
<globalization fileEncoding=”utf-8″ requestEncoding=”utf-8″ responseEncoding=”utf-8″ culture=”en-US” uiCulture=”frFR” />
</system.web></configuration>
2. In Code-inline (aspx) Page

<%@ Page UICulture=”fr” Culture=”en-US” ….%>

3. In Code-Behind (aspx.cs) Page

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture (“fr-FR”);
Thread.CurrentThread.CurrentUICulture=new CultureInfo(“fr-FR”);

 Resources:

ASP.NET wont automatically translate the contents in one language to another language by using Culture. For this we need to put our language specific labels, messages, title in resources file and ASP.Net will load this information from resource file depending on the setting of UICulture and key provided to Resource Manager object. Each entry in the resource file will have a resource key which help us to identify and read the message from the resource fileResources represents embedded data such as strings or images, which can be retrieved during runtime and displayed in the user interface. Resource Management is a feature of .NET framework which is used to extract localized element from source code and to store them with a string key as resources . At runtime, ResourceManager class instance is used to resolve key to the original resource or localized version. Resources can be stored as an independent file or part of an assembly.  ResourceWriter and resgen.exe can be used to create .resources file. To include .resources file inside an assembly use related compiler switch or Al.exe.

Create Resource Text Files:

In resource.en-US.txt
Test = Hello there, friend!In resource.fr-FR.txt
Test = Bonjour là, ami!

Generate .resources file:

Goto VisualStudio.Net command prompt and use resgen command utility to generate .resources file resgen resource.en-US.txt
resgen resource.fr-FR.txtThis commands will create .resources file.

In TestGlobalization.aspx Page

<asp:RadioButtonList id=”RadioButtonList1″ style=”Z-INDEX: 101; LEFT:144px; POSITION: absolute; TOP: 144px” runat=”server”
AutoPostBack=”True”>
<asp:ListItem Value=”en-US” Selected=”True”>English</asp:ListItem>
<asp:ListItem Value=”fr-FR”>French</asp:ListItem>
</asp:RadioButtonList>

In TestGlobalization.aspx.cs Page, on Page_Load Event

CultureInfo objCI = new CultureInfo ( RadioButtonList1 .SelectedValue .ToString ()) ;
Thread.CurrentThread.CurrentCulture = objCI;
Thread.CurrentThread.CurrentUICulture = objCI;
ResourceManager rm = ResourceManager .CreateFileBasedResourceManager (“resource”, Server.MapPath(“resources”) + Path.DirectorySeparatorChar, null);
Response.Write( rm.GetString(“Test”));



You can read details explaination of localization in Asp.Net 2.0 at   following links


http://www.ondotnet.com/pub/a/dotnet/2005/08/08/localizingaspnet20.html?page=1

 

 http://aspalliance.com/821
http://www.codeproject.com/KB/aspnet/localizationByVivekTakur.aspx

Posted in Asp.net | Leave a Comment »

Web Form Page Processing

Posted by sirajq on March 30, 2008

In general, the life cycle for a Web Forms page is similar to that of any Web process that runs on the server. Certain characteristics of Web processing — information passed via HTTP protocol, the stateless nature of Web pages, and so on — apply to Web Forms pages just as they do to most Web applications.However, the ASP.NET page framework performs many Web application services for you. For example, the ASP.NET page framework captures information posted with the Web Forms page, extracts the relevant values, and makes the information accessible via object properties.It is important to understand the sequence of events that occurs when a Web Forms page is processed. This knowledge will help you program your Web Forms pages and Web applications more effectively.

The Life Cycle of a Web Forms Page

You might find it helpful to understand some fundamental characteristics of how Web Forms pages work in Web applications before you examine the details of what goes on inside a page when it is processed.

Round Trips

One of the most important things to understand is the division of labor in a Web Forms page. The browser presents the user with a form, and the user interacts with the form, causing the form to post back to the server. However, since all processing that interacts with server components must occur on the server, this means that for each action that requires processing, the form must be posted to the server, processed, and returned to the browser. This sequence of events is referred to as a round trip.

Note   You can create client script in Web Forms, which is useful for user input validation and for some types of UI programming. Client script does not interact with server components.Imagine a business scenario: A user enters an order and you want to confirm sufficient inventory for the order, so your application posts the page to the server at an appropriate point in the user’s order-entry process. A server process examines the order, performs an inventory lookup, perhaps takes some action defined in business logic (such as modifying the page to indicate an error), and then returns the page to the browser for the user to continue.

Round Trip

 Web Page Life Cycle

In Web Forms, most user actions — such as clicking a button — result in a round trip. For that reason, the events available in ASP.NET server controls are usually limited to click-type events. Most server controls expose a click event, one that requires an explicit user gesture. By the same token, server controls do not expose high-frequency events such as onmouseover, because each time such an event is raised, another round trip to the server would occur, which would considerably affect response time in the form.

Recreating the Page (View State and State Management)

In any Web scenario, pages are recreated with every round trip. As soon as the server finishes processing and sending the page to the browser, it discards the page information. By freeing server resources after each request, a Web application can scale to support hundreds or thousands of simultaneous users. The next time the page is posted, the server starts over in creating and processing it, and for this reason, Web pages are said to be stateless — the values of a page’s variables and controls are not preserved on the server.Note   The server can be configured to cache page information to optimize the pages, but for purposes of application programming, it is clearest to think of them as being disposed of as soon as the server has finished processing them.In a traditional Web application, the only information that the server has about a form is the information that the user has added to the controls on the form, because that information is sent to the server when the form is posted. Other information, such as variable values and property settings, is discarded.ASP.NET works around these limitations in the following ways:

·                     It saves page and control properties between round trips. This is referred to as saving the view state of the control.

·                     It provides state management facilities so you can save your own variable and application-specific or session-specific information between round trips.

·                     It can detect when a form is requested for the first time versus when the form is posted, which allows you to program accordingly. You may want a different behavior during a page postback versus an initial request.

 Benefits of an Event-Driven Model versus a Linear Processing Model

If you have experience using Active Server Pages (ASP), you recognize that ASP is a linear processing model. An ASP page is processed in a top-to-bottom sequence. Each line of ASP code and static HTML is processed in sequence as it appears in the file. User actions cause the page to be posted to the server in a round trip. Since this action causes a round trip, the server must recreate the page. After the page is recreated, it is processed in the same top-to-bottom sequence as before, and therefore the page is not exhibiting truly event-driven behavior. To create an event-driven experience, you need to explicitly design it. In addition, you have to explicitly maintain page and control state at the most basic level. This model limits the richness of the user interfaces that can be assembled, and it increases the complexity of the code needed to support it.In comparison, an event-driven model, as in a traditional Visual Basic application, contains programmable elements that are initialized and displayed on the form. Users interact with the elements, which cause events to be raised that in turn call event handlers. This model supports true event-driven behavior, which, by design, greatly extends the richness of the user interfaces that can be assembled, and it reduces the complexity of the code needed to support it. ASP.NET replaces the linear processing model of ASP by emulating the behavior of an event-driven model. The ASP.NET page framework is provided to implicitly make the associations of an event to an event handler for you. Using the page framework allows you to easily create a user interface that reacts to user actions.In addition, this same framework eases the implementation of page and control state management. For example, ASP.NET allows you to set up event handlers in server code for events that are passed from the browser. Assume the user is interacting with a Web Forms page that contains one button server control. The user clicks the button control and an event is raised that is transmitted via an HTTP post to the server where the ASP.NET page framework interprets the posted information and associates the raised event with an appropriate event handler. This event handler can be a default handler supplied by ASP.NET or it can be your custom implementation. The framework automatically calls the appropriate event handler for the button as part of the framework’s normal processing. As a result, you no longer need to explicitly design event-like behavior into a linear processing model. 

 Stages in Web Forms Processing

The ASP.NET page framework processes Web Forms pages in distinct stages. During each stage of Web Forms processing, events may be raised, and any event handler that corresponds to the event runs. These methods provide you with entry points — hooks — that allow you to update the contents of the Web Forms page.The table below lists the most common stages of page processing, the events raised when they occur, and typical uses at each stage. These stages are repeated each time the form is requested or posted. The Page.IsPostBack property allows you to test whether the page is being processed for the first time.

Note   There are several more stages of Web Forms page processing than are listed in the following table. However, they are not used for most page processing scenarios. Instead, they are primarily used by server controls on the Web Forms page to initialize and render themselves. If you intend to write your own ASP.NET server controls, you need to understand more about these stages.  

Stage Meaning Typical uses
ASP.NET Page Framework Initialization The page’s Page_Init event is raised, and the page and control view state are restored. During this event, the ASP.NET page framework restores the control properties and postback data.
User Code Initialization The page’s Page_Load event is raised. Read and restore values stored previously: ·                     Using the Page.IsPostBack property, check whether this is the first time the page is being processed. ·                     If this is the first time the page is being processed, perform initial data binding. ·                     Otherwise, restore control values. ·                     Read and update control properties.
Validation The Validate method of any validator Web server controls is invoked to perform the control’s specified validation. (There is no user hook at this stage. You can test the outcome of validation in an event handler.)
Event Handling If the page was called in response to a form event, the corresponding event handler in the page is called during this stage. Perform your application-specific processing: ·                     Handle the specific event raised. Note   Events are not raised in a particular order, except that cached control events — as specified by the control’s AutoPostBack property — are always processed before the posting event.·                     If the page contains Types of Validation for ASP.NET server Controls, check the IsValid property for the page and for individual validation controls.

 ·                     Manually save the state of page variables that you are maintaining yourself.

·                     Check the IsValid property of the page or of individual validation controls.

 ·                     Manually save the state of controls dynamically added to the page.

Cleanup The Page_Unload event is called because the page has finished rendering and is ready to be discarded. Perform final cleanup work: ·                     Closing files. ·                     Closing database connections.

 ·                     Discarding objects.

Note   It is important that expensive resources, such as database connections, be explicitly closed. Otherwise, they will remain open until the next garbage collection occurs. On a heavily loaded server, many open resources can adversely affect performance.

Posted in Asp.net | Leave a Comment »

State Management

Posted by sirajq on March 28, 2008

State management is the process by which you maintain state and page information over multiple requests for the same or different pages. As is true for any HTTP-based technology, Web Forms pages are stateless, which means that they do not automatically indicate whether the requests in a sequence are all from the same client or even whether a single browser instance is still actively viewing a page or site. Furthermore, pages are destroyed and recreated with each round trip to the server; therefore page information will not exist beyond the life cycle of a single page.
ASP.NET provides multiple ways to maintain state between server round trips. Choosing among the options for state management available in ASP.NET will depend heavily upon your application, and it should be based on the following criteria:

  • How much information do you need to store?
  • Does the client accept persistent or in-memory cookies?
  • Do you want to store the information on the client or server?
  • Is the information sensitive?
  • What sorts of performance criteria do you have for your application?
  • ASP.NET supports various client-side and server-side options for state management.

Client-side options are:

  • The ViewState property
  • Hidden fields
  • Cookies
  • Query strings

Server-side options are:

  • Application state
  • Session state
  • Database Client-Side State Management Options

Storing page information using client-side options doesn’t use server resources. These options tend to have minimal security but fast server performance because the demand on server resources is modest. However, because you must send information to the client for it to be stored, there is a practical limit on how much information you can store this way.

View State

Web Forms pages provide the ViewState property as a built-in structure for automatically retaining values between multiple requests for the same page. View state is maintained as a hidden field in the page.

You can use view state to store your own page-specific values across round trips when the page posts back to itself. For example, if your application is maintaining user-specific information — that is, information used in the page but not necessarily part of any control — you can store it in view state.

The advantages of using view state are:

  • No server resources required. The view state is contained in a structure within the page code.
  • Simple implementation.
  • Automatic retention of page and control state.
  • Enhanced security features. The values in view state are hashed, compressed, and encoded for Unicode implementations, thus representing a higher state of security than hidden fields have.The disadvantages of using the view state are:
  • Performance. Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it.
  • Security. The view state is stored in a hidden field on the page. Although view state stores data in a hashed format, it can be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue

Hidden Fields

You can store page-specific information in a hidden field on your page as a way of maintaining the state of your page.

If you use hidden fields, it is best to store only small amounts of frequently changed data on the client. ASP.NET provides the HtmlInputHidden control, which offers hidden field functionality. For more information on HtmlInputHidden see ASP.NET server Controls by Function.

Note If you use hidden fields you must submit your pages to the server using the HTTP POST method rather than requesting the page via the page URL (the HTTP GET method).

The advantages of using hidden fields are:

  • No server resources are required. The hidden field is stored and read from the page.
  • Broad support. Almost all browsers and client devices support forms with hidden fields.
  • Simple implementation. :

The disadvantages of using hidden fields are

  • Security. The hidden field can be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue.
  • Limited storage structure. The hidden field does not support rich structures. Hidden fields offer a single value field in which to place information. To store multiple values, you must implement delimited strings and the code to parse those strings.
  • Performance. Because hidden fields are stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it.

Cookies

Cookies are useful for storing small amounts of frequently changed information on the client. The information is sent with the request to the server.

The advantages of using cookies are:

  • No server resources are required. The cookie is stored on the client and read by the server after a post.
  • Simplicity. The cookie is a lightweight, text-based structure with simple key-value pairs.
  • Configurable expiration. The cookie can expire when the browser session ends, or it can exist indefinitely on the client computer, subject to the expiration rules on the client.

The disadvantages of using cookies are:

  • Limited size. Most browsers place a 4096-byte limit on the size of a cookie, although the support for 8192-byte cookie size is becoming common in the new browser and client-device versions available today.
  • User-configured refusal. Some users disable their browser or client device’s ability to receive cookies, thereby limiting this functionality.
  • Security. Cookies are subject to tampering. Users can manipulate cookies on their computer, which can potentially represent a security compromise or cause the application dependent on the cookie to fail. For more information see Introduction to Web Application Security.
  • Durability. The durability of the cookie on a client computer is subject to cookie expiration processes on the client and user intervention.

Note Cookies are often used for personalization, where content is customized for a known user. In most of these cases, identification is the issue rather than authentication, so it is enough to merely store the user name, account name, or a unique user ID (such as a GUID) in a cookie and use it to access the user personalization infrastructure of a site.
For details about creating and reading cookies, see HttpResponse.Cookies Property and HttpRequest.Cookies Property.

Query Strings

A query string is information appended to the end of a page’s URL. For more information, see Introduction to Web Forms State Management.

You can use a query string to submit data back to your page or to another page through the URL. Query strings provide a simple but limited way of maintaining some state information. For example, they are an easy way to pass information from one page to another, such as passing a product number to another page where it will be processed.
<b> Note : </b>  Query strings are a viable option only when a page is requested via its URL.

You cannot read a query string from a page that has been submitted to the server.

The advantages of using query strings are:

  • No server resources required. The query string is contained in the HTTP request for a specific URL.
  • Broad support. Almost all browsers and client devices support passing values in a query string.
  • Simple implementation. ASP.NET provides full support for the query string method, including methods of reading query strings using the HttpRequest.Params property.

The disadvantages of using query strings are:

  • Security. The information in the query string is directly visible to the user via the browser user interface. The query values are exposed to the Internet via the URL so in some cases security may be an issue.
  • Limited capacity. Most browsers and client devices impose a 255-character limit on URL length.

Client-Side Method State Management Summary

The following table summarizes client-side state management options and when you should consider using them.
Method Use when View state You need to store small amounts of information for a page that will post back to itself. Use of the ViewState property provides functionality with basic security.

Hidden fields You need to store small amounts of information for a page that will post back to itself or another page, and security is not an issue.

Note You can use a hidden field only on pages that are submitted to the server.
Cookies

You need to store small amounts of information on the client and security is not an issue.
Query string You are transferring small amounts of information from one page to another and security is not an issue. Note You can use query strings only if you are requesting the same page, or another page via a link.

Server-Side State Management Options

Server-side options for storing page information tend to have higher security than client-side options, but they can use more Web server resources, which may lead to scalability issues when the size of the information store is large. ASP.NET provides several options to implement server-side state management.

Management.
Session State

ASP.NET provides a session state, available as the HttpSessionState class, as a method of storing session-specific information that is visible within the session only. For more information, see Introduction to Web Forms State Management and Session State.
You can store your session-specific values and objects in session state, which is then managed by the server and available to the browser or client device. The ideal data to store in session-state variables is short-lived, sensitive data that is specific to an individual session.

Note If you store a dataset in application state, you have to cast it from Object back to a dataset

The advantages of using session state are:

  • Ease of implementation. The session state facility is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.
  • Session-specific events. Session management events can be raised and used by your application.
  • Durability. Data placed in session-state variables can survive Internet Information Services (IIS) restarts and worker-process restarts without losing session data because the data is stored in another process space.
  • Platform scalability. Session state can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.
  • Session state works with browsers that do not support HTTP cookies, although session state is most commonly used with cookies to provide user identification facilities to a Web application. For more information on using session state without cookies, see ASP.NET Configuration Sections.

The disadvantage of using session state is:

  • Performance. Session state variables stay in memory until they are either removed or replaced, and therefore can degrade server performance. Session state variables containing blocks of information like large datasets can adversely affect Web server performance as server load increases.

Database Support
In some cases, you may wish to use database support to maintain state on your Web site. Typically, database support is used in conjunction with cookies or session state. For example, it is quite common for an e-commerce Web site to maintain state information using a relational database for the following reasons:

  • Security
  • Personalization
  • Consistency
  • Data miningThe following are typical features of a cookie-supported database Web site:
  • Security. The visitor types an account name and password into a site logon page. The site infrastructure queries the database with the logon values to determine if the user has rights to utilize your site. If the database validates the user information, the Web site will distribute a valid cookie containing a unique ID for that user on that client computer. The site grants access to the user.
  • Personalization. With security information in place, your site is able to distinguish each user on your site by reading the cookie on the client computer. Typically, sites have information in the database that describes the preferences of a user (identified by a unique ID). This relationship is known as personalization. The site can research the user’s preferences using the unique ID contained in the cookie, and then place content and information in front of the user that pertains to the user’s specific wishes and reacts to the user’s preferences over time.
  • Consistency. If you have created a commerce Web site, you may wish to keep transactional records of purchases made for goods and services on your site. This information can be reliably saved in your database and referenced by the user’s unique ID. It can be used to determine if a purchase transaction has been completed, and also to determine the course of action should a purchase transaction fail. The information may also be used to inform the user of the status of an order placed using your site.
  • Data mining. Information about your site usage, your visitors, or your product transactions can be reliably stored in your database. For example, your business development department may wish to use this data collected from your site to determine next year’s product line or distribution policy. Your marketing department may wish to examine demographic information about users on your site. Your engineering and support department may wish to look at transactions and note areas where your purchasing process could be improved. Most enterprise-level relational databases such as Microsoft SQL Server contain an expansive toolset for most data mining projects.

By designing the Web site to repeatedly query the database by using the unique ID during each general stage in the above scenario, the site maintains state. In this way, the user perceives that the site is remembering and reacting to him or her personally.

The advantages of using a database to maintain state are:

  • Security. Access to databases is typically very secure, requiring rigorous authentication and authorization.
  • Capacity. You can store as much information as you like in a database.
  • Persistence. Database information can be stored as long as you like, and it is not subject to the availability of the Web server.
  • Robustness and data integrity. Databases include various facilities for maintaining good data, including triggers and referential integrity, transactions, and so on. By keeping information about transactions in a database (rather than in session state, for example), you can recover from errors more readily.
  • Accessibility. The data stored in your database is accessible to a wide variety of information-processing tools.
  • Wide support. There is a large range of database tools available, and many custom configurations are available.

The disadvantages of using a database to maintain state are:

  • Complexity. Using a database to support state management implies more complex hardware and software configurations.
  • Performance. Poor construction of the relational data model can lead to scaling issues. Also, leveraging too many queries to the database can adversely affect server performance.

Server-Side Method State Management Summary

The following table summarizes server-side state management options and when you should consider using them.
Method Use whenApplication state You are storing infrequently changed, global information that is used by many users, and security is not an issue. Do not store large quantities of information in application state.
Session state You are storing short-lived information that is specific to an individual session, and security is an issue. Do not store large quantities of information in session state. Be aware that a session state object will be created and maintained for the lifetime of every session in your application. In applications hosting many users, this can occupy significant server resources and affect scalability.

Database support You are storing large amounts of information, managing transactions, or the information must survive application and session restarts. Data mining is a concern, and security is an issue.

Posted in Asp.net | 1 Comment »