Online Earning Sources (Without Investment)

If you want to post, send your post on dotnetglobe@gmail.com .Put 'Title' as 'Subject'

Pages

Monday, November 3, 2008

Form validation is vastly improved in ASP.NET

One essential task in Web programming is the validation of values entered into forms by users. Classic ASP provides little support in this area, leaving developers to devise their own validation mechanisms. Luckily, ASP.NET has improved this situation considerably. For starters, its event-based, UI control-centric WebForms programming model greatly simplifies the task of implementing your own validation. But ASP.NET goes even further, providing direct support for validation through a set of server controls that all but eliminate the need to implement your own validations. In this article, I'll introduce and demonstrate the validation server controls shipped with ASP.NET.

Validation control hierarchy
The ASP.NET validation server controls live under the System.Web.UI.WebControls namespace, together with Web sever controls such as TextBox and Label. ASP.NET provides six concrete validation controls, shown in green in Figure A.

Figure A
ASP.NET validation controls


The ValidationSummary control doesn’t actually perform validation. Instead, it provides a way to summarize the error messages from the other validation controls within the page. For the remainder of the article, when I refer to validation controls, I’m referring to those controls that actually perform validations—all of the validation controls except ValidationSummary.

Validation controls are derived directly or indirectly from the abstract BaseValidater class, which in turn derives from the Label control. At first, it seems odd that validation controls would derive from Label, but we'll see why shortly.

Validation
A validation control works by evaluating the value of an input server control on the page to see whether it meets certain criteria. The input control to evaluate is specified through the validation control’s ControlToValidate attribute. You can programmatically cause a validation control to perform its evaluation by calling its Validate method, which sets the validation control’s IsValid property to true if validation succeeds and false if it fails. You can cause all of the validation controls on a page to validate their input controls by calling the Page.Validate method.

The Page.IsValid property is set to true if validation succeeds for all validation controls within the page; otherwise, it's false. The Page.Validate method is automatically invoked when a button control whose CausesValidation property is set to true is clicked. CausesValidation is set to false by default for a reset or clear button. The button click event is suppressed if IsValid is false for any validation control on the page.

If the target browser supports ECMAScript 1.2 (JScript) and a Document Object Model (DOM) compatible with Internet Explorer 4 or later, validation controls render client-side scripting to perform validation on the client without a round trip to the server. This provides more timely feedback to the user. To support downlevel browsers and to guard against a user attempting to bypass validation, validation is still performed on the server when the page is posted to it. Client-side validation can be disabled for a validation control by setting its EnableClientScript property to false. You can disable client-side validation for all validation controls within the page by specifying the attribute ClientTarget=”downlevel” in the @Page directive.

When validation fails, the Text property of the validation control is displayed in-line within the page at the validation control’s location, just like a label. If the Text property is not set, the ErrorMessage property is displayed instead. The ErrorMessage property is also displayed in the ValidationSummary control when validation fails. Nothing is displayed in the ValidationSummary if no ErrorMessage is set for a validation control. One strategy involves setting a brief message or error indicator as the Text property and a longer explanation as the ErrorMessage property.

Different validation controls test different criteria:
  • · RequiredFieldValidator—Validation succeeds if any value has been entered in the input control.
  • · RangeValidator—Validation succeeds if the input control’s value falls within the range specified by the MaximumValue and MinimumValue properties. The Type property specifies the data type to which MaximumValue, MinimumValue, and the input control’s value are converted before performing the range comparison.
  • · RegularExpressionValidator—Validation succeeds if the input control’s value matches the regular expression specified in the ValidationExpression property.
  • · CompareValidator—This control can perform several types of evaluation through its Operator property. The DataTypeCheck operator simply determines whether the input control’s value can be converted to a data type specified by the Type property. Relational operators, such as Equal or GreaterThan, compare the input control’s value with either a static value, specified by the ValueToCompare property, or with the value of another control, specified by the ControlToCompare property.
  • · CustomValidator—This control enables you to perform your own unique validation by handling the CustomValidator.ServerValidate event, fired when CustomValidator.Validate is called. The event handler can evaluate whatever you want and set the IsValid property of the ServerValidateEventArgs event argument to set the state of the validation control. A ServerValidate event handler can be specified through the OnServerValidate property. Specifying a client-side script function through the ClientValidationFunction property enables client-side validation.

Validation in action
Listing A shows NewBabyBoomer.aspx. This is a sign-up page to create a new account at an imaginary Web site providing information to members of the baby boom generation, those born between 1946 and 1964. This page is typical of many sign-up pages. The user is asked to choose a username and a password and to enter the password again as confirmation. The page also asks the user to enter the year in which he or she was born.

The Label, TextBox input control and validation controls for each field are arranged within a Web server Table control. The Table control is followed by a button control and a ValidationSummary control. Button_Click, the OnClick event handler for the button control, is contained in a block at the top of the aspx file. Figure B shows the initial NewBabyBoomer page.

Figure B
Baby boomer sign-up page


All fields in the NewBabyBoomer page are required. As a result, each input control is validated by two validation controls. A RequiredFieldValidator ensures that some value is entered in the input control. A second validation control then evaluates the value.

If you're dealing with optional fields, you can use validation controls, such as RegularExpressionValidator, CompareValidator, and RangeValidator. With those controls, validation succeeds if the target input control has no value, so you can make a field optional but still apply validation when the user chooses to enter value.

In NewBabyBoomer, a RegularExpressionValidator validates the Username field to ensure that the username is at least six alphanumeric characters long. The regular expression “\w{6,}” is specified through the ValidationExpression property. A RegularExpressionValidator likewise validates the Password field, though the ValidationExpression is set to “.{6,}” to allow the password to contain any character, so long as the length is at least six characters.

A RangeValidator validates the Year Born field to ensure that the input control’s value is an integer within the range 1946 to 1964. Validation fails if the value falls outside the range or if the value is not convertible to an integer. Finally, a CompareValidator specifying the Equal operator validates the Confirm field to ensure that it matches the Password field.

Figure C shows the output of the validation controls and the ValidationSummary control when invalid input is entered. The Button_Click event handler is called when the Create Account button is clicked and all fields are valid. The Page.IsValid property is checked within the event handler in case the page was posted back from a downlevel browser. Figure D shows the confirmation page after a successful account creation.

Figure C
Validation control output


Figure D
Validation confirmation


Conclusion
The new validation controls available in ASP.NET provide the necessary functionality for any Web development effort. This is a great improvement over the basic ASP technology. I hope this article has provided the groundwork for employing the validation controls in your next development project.

Dealing with ASP.NET's view state

One of the more exciting features of ASP.NET is the view state concept. It allows you to save Web Form properties across different server requests. While this simplifies maintaining data on a Web page, it does have disadvantages. This week, I examine view state, as well as enhancements to the feature in ASP.NET 2.0.

Maintaining state

The basic idea behind the view state feature is that when a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. This is easily demonstrated with an example as the C# Web Form in Listing A shows. Listing B offers the equivalent VB.NET code.

It is a basic Web Form that accepts user input in a text field and displays the contents of the field in a label when the button is selected. If you test the form, you'll notice the contents of the text field are maintained between button clicks. In part, this is accomplished with the view state feature, which is a default feature of ASP.NET Web Forms. You will see the view state field if you view the page source when it is opened in a browser as the following demonstrates:

"dDwtMjA1MzM3NDEyNzt0PDtsPGk8Mj47PjtsPHQ8O2w8aTw3Pjs+O2w8dDxwPHA8bDxUZXh0Oz47bDxkZDs
+Pjs+Ozs+Oz4+Oz4+Oz6Tt+UvLyB2DGSLR/NhrjKwZrP7BQ==" />

As you can see, the view state information is not stored as clear text. By default, a machine-specific authentication code is calculated on the data and appended to the view state string. The resulting text is then Base64 encoded but not encrypted.

Weekly .NET tips in your inbox
TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET.
Automatically sign up today!

You can use a higher level of security via the Page class' EnableViewStateMac property. When used, the view state MAC is an encrypted version of the page's view state. When you set the EnableViewStateMac attribute to true, the regular encoded and encrypted view state are compared to verify that it has not been tampered with on the client.

You may choose to disable the view state feature by setting the EnableViewState property of the ASP.NET Page class to false. This may be accomplished in the page control directive like the following line accomplishes:

<%@ Page language="vb" EnableViewState="false" %>

Or, you may choose to enable or disable the feature in code as the VB.NET sample in Listing C demonstrates.

In addition to disabling or enabling the entire page, most data controls such as the TextBox, DataGrid, and Repeater controls provide an EnableViewState property that allows granular control over what is stored in view state.

An interesting aspect of the hidden field is that even if EnableViewState is false, there may be a hidden view state field rendered with the page that is used by ASP.NET to detect postback.

In the simple examples presented so far, using view state is overkill. This is due to the fact that once the page is loaded and populated via the view state, the page proceeds to read information from the Page's Request object and uses those values to override most of the settings for the controls on the page. This doesn't mean view state is unnecessary; it just points out that you should use it with care. Another way to utilize the view state feature is via coding.

Using code

You may programmatically access a page's view state along the same lines as working with a user's session—like working with dictionary object. The StateBag class implements the view state and manages the information that ASP.NET pages and embedded controls persist across successive posts of the same page instance. Listing D adds a Label control to the first example to illustrate storing values in view state. The value stored in the view state object is retrieved during the loading of the page and displayed in the Label control.

A good way to illustrate disabling the view state is by setting the EnableViewState property to false in this example. If set to false, you'll notice the additional Label control is always empty when the code runs. Also, you'll notice the system does not produce an error if view state is used when it has been disabled—it just doesn't work. Also, the contents of values stored in the ViewState object are valid only during the life of its container page.

Use view state with care

Most developers advise not to use the view state feature unless it is absolutely necessary, so turn it off for any control that doesn't need it. The reason is simple: storing large amounts of data in a hidden field requires that field be transferred during server calls and it takes time. If you don't believe it can't get out of control, load up a page with lots of data (with view state enabled) and take a look at its source—the size of that hidden view state field is a bit overwhelming, isn't it?

ASP.NET 2.0

With the release of ASP.NET 2.0, Microsoft recognized the need to overhaul some aspects of the view state feature. This includes the following:

  • A change in the serialization format used to store view state data, which results in more efficient data retrieval and parsing via a smaller footprint.
  • View state is partitioned into two categories: view state and control state. It addresses the problem of view state being an all or nothing feature for controls in ASP.NET 1.1. Control state is another type of hidden state reserved exclusively for controls to maintain their core behavioral functionality.

Working with it

View state is a key element of the ASP.NET architecture. It allows you to easily persist data between server roundtrips, and it is utilized by the postback architecture. It does consume valuable resources, so you should use it when appropriate.

Maintaining state in ASP.NET: Know your options

Maintaining state is a problem that all Web developers face regardless of the platform. ASP.NET adds four options on top of the standard approaches on the Web. Tony Patton drills down on these options.

—————————————————————————————————————

Developing robust solutions with ASP.NET requires a thorough understanding of the platform. An important part of most Web applications is maintaining data or state between pages. Here’s a look at ASP.NET’s four ways to maintain data.

The state of things

A quick review of state as it applies to a Web page helps with the concepts in this article. A good description is the current state of a page which includes the current value of all variables and controls on the page for the current user and session.

It is worth mentioning that the Web is inherently stateless since the HTTP protocol is stateless. The Web server treats every HTTP page request as an independent request. By default, everything on a page is lost when/if you go to another page.

Developers’ skills are used to maintain the state of all or a portion of a Web page. In the past, cookies or the query string were often used to achieve this goal. A development platform like ASP.NET provides other ways to maintain state.

Different approaches to state

ASP.NET provides four ways to maintain state within a Web application. The following list provides an overview of each approach:

  • Application state: A data repository available to all classes in an ASP.NET application. The data is stored in memory on the computer. It is available to all users and sessions for the application.
  • Control state: This approach provides the ability to save the state of a specific control on a page; this is especially true for data controls like DataGrid and GridView, where control state is used to store behavioral data. The control state is used to provide paging and sorting functionality in the GridView control. It cannot be modified or directory accessed.
  • Session state: A data repository available on a user by user basis; that is, it stores data for individual users. By default, session state is enabled.
  • View state: This approach stores the state of all controls on a page. It is applicable to only that page, so every page maintains its own view state. It is enabled by default for all ASP.NET pages.

While control state does not provide programmatic access, you can work with the other states, as I explain below.

Application state
Utilizing application state within a site is as simple as using the Application keyword and assigning or accessing one of its values. The Application object — as well as the ViewState and Session objects used for view and session state — is a Dictionary object. With that said, entries are assigned index values as well as data values. The following C# snippet assigns a value to the Application state variable ApplicationName:

Application["ApplicationName"] = "TechRepublic.com Example";

Application state variables live within the application, so they are accessible to all users. Problems may arise when/if two users attempt to write data to the same Application entry. This may be avoided by locking the object when a data change is made. Also, Application state values are cleared during server reboot and do not carry over to other processors or servers in a cluster or farm environment.

Session state
A session begins when a user accesses a Web application. It ends when they leave the application or a certain amount of time has passed with no site activity. The Session state object can be used to maintain values during a user’s session.

The values in the Session object are only applicable to a certain user and may not be accessed by other users. Like the Application object, the Session object is Dictionary, with values accessed according to their index values. The following VB.NET snippet stores a value in the Session variable called UserName:

Session("UserName") = "Tony Patton"

Session state may be enabled on a page by page basis with the EnableSessionState attribute of the Page directive. Also, it may be configured for a site via the web.config file. There are a variety of options available when using session state, such as signaling whether cookies are used, storing data in a database, and the length of the timeout.

View state
By default, all pages have view state enabled. The actual data is stored in a hidden field on the form — take a look at a page’s source, and you’ll quickly find the field hosting the data. The data is not encrypted, so it does present security risks; however, it is Base64 encoded, which doesn’t make it easily read by the naked eye.

Like session state, view state may be disabled on the page level via the EnableViewState attribute of the page directive. Likewise, most individual controls have the same property available. It may be disabled for the entire site in the web.config file.

Like the other state objects, the Dictionary approach is used, as the following C# snippet demonstrates:

ViewState["CurrentCount"] = 2;

This entry is maintained for the life of the page; it is gone when the page is no longer loaded. The size of the hidden field used to maintain view state can become large, so disable it whenever it is not needed.

Choosing the right method

The interesting aspect of the many available ASP.NET features is when to use one over another. The choice often depends on the development team’s preferences, but there are some guidelines for using one of the options for maintaining state.

If you’re worried about bandwidth or server resources, you should remember that session and application states utilize server resources, and view state uses bandwidth to carry that hidden field at all times. With security, the biggest hole is view state; it is available by viewing the page source. All of the states are accessible via your favorite language, but you should keep scope in mind with each approach and choose the one that best fits the situation.

Also, don’t forget the older methods of cookies and the query string — they are still viable in certain situations.

Export large data from Gridview and Datareader to an Excel file using C#

protected void btnExportFromDatagrid_Click(object sender, EventArgs e)
{
ExportGridToExcel(grdStudentMarks, "StudentMarks.xls");
}
public void ExportGridToExcel(GridView grdGridView, string fileName)
{
Response.Clear();
Response.AddHeader("content-disposition",
string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.ContentType = "application/vnd.xls";

StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
grdGridView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}


Overiding VerifyRenderingInServerForm Method
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */

}

Read HTML from aspx pages

protected string GetHtmlString()
{
string sHtml = "";
HttpWebRequest request;
HttpWebResponse response = null;
Stream stream = null;
request = (HttpWebRequest)WebRequest.Create("http://www.google.com/");
response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream, System.Text.Encoding.Default);
sHtml = sr.ReadToEnd();
if (stream != null) stream.Close();
if (response != null) response.Close();
return sHtml;
}

Reading HTML from any URL Programmatically

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

using (Stream stream = request.GetResponse().GetResponseStream())

{

using (StreamReader reader = new StreamReader(stream))

{

string response = reader.ReadToEnd();

return response;

}
}

itworld