Saturday, March 1, 2008
Wednesday, January 30, 2008
Adding Blank Rows to a DataGrid
In one application I had the requirement to add a blank row after every 10 rows in a DataGrid rather than use paging as shown in FIGURE 1. There is no in-built way to do this with the DataGrid, but it can be easily done by modifying the DataTable that the DataGrid is bound to and by writing some code in the DataGrid's ItemDataBound event. The rest of this article will describe how it is done. To add a blank row every 10 rows seems simple enough to do using a for loop with a counter. I knew that I could not use a for each loop due to me adding new items to the collection within the loop. As it turns out, you cannot use a for loop with a counter as the upper bound of the loop is not re-evaluated on every iteration! This means that the only way to loop through the item collection is to use a while loop with a counter. To keep track of when to add a blank row, another counter is used that is decremented. When this counter reaches 1, a new row is added to the DataTable and is then reset. At the same time, the upper bound is incremented to note the addition of the new row. The code below shows a function that can be used to add blank rows to the first DataTable in any DataSet. As you can see, the row is not actually blank. The first column in the row is given the negative of the counter. When the DataRow is inspected in the ItemDataBound event, the fact that it is a negative value can be used to note that this should be displayed as a blank row in the DataGrid. In this case, the first column in the DataSet that was used was a Primary Key and could not be blank, and I knew that the values from the database would all be positive. When implementing this yourself you can use whatever identifier is suitable for your scenario. After adding the blank rows to the DataTable, the next step is to render the blank rows in the DataGrid. To do this, a few lines in the DataGrid ItemDataBound event are required. The first thing to do is check to see if the item is an Item or Alternating item as this event fires for both the header and the footer of the DataGrid. The underlying DataRow that the ListItem is bound to can then be accessed to check the value in the first column to see if the value it contains denotes that it should be rendered as a blank row. The code below sets the text of the first cell to contain so as to make the blank row visible, and sets the BackColor to White (the rest of the rows are presented in a different color). This code can be easily adapted to allow you to render whatever format of blank row that you want. One alternative use for the idea and code presented here is to create a running total row. As the DataTable is looped through, a running total can be kept and that value inserted into the correct column in the DataTable. Instead of rendering a blank row in the DataGrid, it can be rendered in another format.
Private Function addBlankLines(ByVal ds As DataSet) As DataSet
Dim dr, drBlank As DataRow
Dim count, repeatCount, upperBound As Integer
repeatCount = 10 'used to keep track of when to add a 'blank' row
upperBound = ds.Tables(0).Rows.Count
While count <= upperBound If repeatCount = 1 Then drBlank = ds.Tables(0).NewRow drBlank(0) = -count ds.Tables(0).Rows.InsertAt(drBlank, count + 1) count += 1 upperBound += 1 repeatCount = 10 Else repeatCount -= 1 End If count += 1 End While Return ds End Function
Private Sub dgResults_ItemDataBound(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgResults.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
If CType(CType(e.Item.DataItem, DataRowView).Row.Item(0), Integer) < text = " " backcolor =" System.Drawing.Color.White">
Posted by
Arya
at
12:50 AM
0
comments
Labels: DataGrid
What is the difference between a Web service and a Web application?
The best definition of Web service comes from the W3C: "Web services provide a standard means of interoperating between different software applications, running on a variety of platforms and/or frameworks." The key point in this definition is "interoperate". Web services are all about making heterogeneous applications interoperate. The values of broad interoperability are many: it promotes the network effect and encourages a strong tool and infrastructure marketplace -- both of which dramatically drive your costs down, while improving your time-to-market and productivity.
With the best of intentions, some developers "work around" the Web service specifications. For example, because of perceived performance issues, they might use a virtually empty SOAP message body and pass their real message content in a SOAP attachment. While this message might be sent using SOAP, since you need to manually process the attachment yourself in custom code it certainly is not broadly interoperable and thus can't be considered a Web service -- no 3rd party tools or infrastructure will directly support it so you lose all of the benefits Web services had to offer in the first place. Don't let your application fall into this trap. Follow both the intent and the specifics of the standards (not only SOAP and WSDL, but also WS-I) and you will benefit significantly from the broad interoperability that is the true value of Web services.
Posted by
Arya
at
12:20 AM
0
comments
Dynamic User Interface in ASP.NET Web Applications
Dynamic User Interface in ASP.NET Web Applications
Dynamic User Interface in ASP.NET Web Applications
What is that?
Every developer knows well that to be able to design a proper user interface then we have to have a solid knowledge about every aspect of this user interface before we actually start designing it. Unfortunately, this is not always 100% possible. Situations arise from time to time in which we have no or little idea about what will be the proper user interface for a given application. In web applications things becomes worth as these situations arises more frequently.
The tutorial you are reading now is intended to address this particular problem. This type of user interface construction technique is typically referred to as 'Dynamic Control Creation'. The technique is not that new in desktop applications and is already employed in several development framework many years ago. What we are going to present you in this tutorial is the web based implementation of this technique.
To make your user interface dynamic and responsive to the various situations and modes, several techniques are typically employed. Making irrelevant controls invisible, disabling unused menu items, and moving the frequently used controls to the focus of your user interface are all techniques from that class. Dynamic control creation is another story. The unmatched flexibility and innovation that you can experience with dynamic control creation exceeds in robustness and features any other technique that can be proposed in this class.
City Hall: The 'PlaceHolder' control
At the heart of the process of dynamic control creation in web applications is the PlaceHolder control. This control is a container control in that it can contain other controls inside it. These controls can be dynamically created at run time. It's important here to note that the PlaceHolder control is developed with the intention to host (i.e., to contain) server side controls. Inside the PlcaeHolder control is the Control.Controls collection. This is the collection inside which you add your dynamically created controls. Let's illustrate this by an example:
Simple dynamic control creation. Example 1 (Download)
In this example we will show you how to create a text box inside a PlaceHolder control dynamically. Because this is dynamic control creation you will not draw this text box form the traditional tool box or using the traditional Visual Studio 2005 user interface / form designer.
Create a new web site and on the 'Default.aspx' draw a PlaceHolder control from the tool box. Also add a button so we can write and trigger the code we need. Your form will be similar to figure 1.
| Figure 1 |
Add the following code fragment to the Click event of our button:
| Protected Sub Button1_Click( ByVal sender As Object , ByVal e As System.EventArgs) _ Handles Button1.Click Dim t As TextBox t = New TextBox PlaceHolder1.Controls.Add(t) End Sub |
This code defines and creates an instance of the text box we are attempting to create dynamically. PlaceHolder1.Controls.Add(t) metod actually adds this newly created text box to the Controls collection of the PlaceHolder causing the text box to actually appear on the form. The PlaceHolder itself will not be seen at run time.
Save and run our web site and click the button to see how the dynamically created text box will show regardless that fact it has no existence on the form at design time! See figures 2 and 3 for before and after running respectively.
|
|
Let's examine a more sophisticated example in which the dynamically created controls are a direct representation of an underlying data.
Creation as a data representation technique. Example 2 (Download)
It's frequently desired to have a set of controls dynamically created to represent a given structure of data already available in your web application. The typical case is when you have an SQL or XML data source and you need to have a visual representation of such data. To more focus our tutorial over the problem we are presenting you now (i.e., Dynamic Control Creation) we will skip the database connectivity and data retrieval issues and will assume that all of these issues are already implemented and that the resulting data is loaded and available in a simple array.
We will assume that every record to be dynamically represent in the user interface is represented by an instance of the Record class. Let the Record class be defined as follows:
| Class Record Public ProductName As String ' The product name Public Desc1 As String ' The label of field 1 Public Value1 As String ' The value of field 1 Public Desc2 As String ' The label of field 2 Public Value2 As String ' The value of field 2 End Class |
Here's the code that will initialize the data array. Please give little attention to such code because this case is over simplified for the illustrative purpose. In a real world web application, this array is initialized from a data source like an SQL server or an XML file. Since this is an over simplified scenario, we will not dig deep in this code.
| Dim products(0 To 9) As Record Dim i As Integer 18 For i = 0 To 9 19 products(i) = New Record products(i).ProductName = "Product " & (i + 1) products(i).Desc1 = "Weight of product " & (i + 1) products(i).Desc2 = "Volume of product " & (i + 1) products(i).Value1 = (i + 1) * 10 products(i).Value2 = (i + 1) * 100 25 Next |
Now to the most important part of our example: The dynamic creation of controls. Here's the code that performs the dynamic creation of controls:
| For i = 0 To 9 |
As always, we create an instance from the controls we need to dynamically add to our form. The new practice here is that we are treating them just like any controls created in design time and set their properties with the standard syntax. Finally we add them to the PlaceHolder control as we mentioned previously.
If you are to run our example now, you will get the result illustrated in figure 4 below:
| Figure 4 |
Not that user friendly ..... huh? This is of course an unacceptable user interface by any standard!
Because you are dynamically creating your controls, it's necessary to visualize the resulting output yourself! No more WYSIWYG visual designers! You need to add some formatting tags so that the above messy output is more acceptable.
To solve this dynamic output mess we will opt to use the HTML tag "
" to make sure that every label and every text box is in it's isolated line and that they all will not merge. As well we will use the HTML tag "
" to insert a horizontal line before every record (i.e., every product in our particular case). This all can be achieved by using the Literal control which can represent the "
" and the "
" HTML tags. All you have to do is to add a Literal control to the controls collection of your PlaceHolder every time you need to add a "
" or a "
".
A common mistake is to use the same Literal control every time you need to add a "
" or a "
". If you are to do so, only the first addition will be successful and the rest will be simply ignored as you are adding a control to a collection of controls already containing the control you are adding!
The proper practice is to define a function that returns a new and distinct Literal control every time. See the following function for example:
| Function GetLiteral( ByVal text As String ) |
And now every time we need to add a Literal control we call that function specifying the HTML tag we need to add. After utilizing this technique, then dynamic control creation code should be now like this:
| '---------- " )) PlaceHolder1.Controls.Add(ProductName) PlaceHolder1.Controls.Add(GetLiteral( " " )) PlaceHolder1.Controls.Add(Desc1) PlaceHolder1.Controls.Add(GetLiteral( " " )) PlaceHolder1.Controls.Add(Value1) PlaceHolder1.Controls.Add(GetLiteral( " " )) PlaceHolder1.Controls.Add(Desc2) PlaceHolder1.Controls.Add(GetLiteral( " " )) PlaceHolder1.Controls.Add(Value2) PlaceHolder1.Controls.Add(GetLiteral( " " )) '---------- |
And when you run the web application you will see this tidy output:
| Figure 5 |
For further information
Refer to the online copy of Microsoft Developers Network at http://msdn.microsoft.com or use your own local copy of MSDN.
Posted by
Arya
at
12:08 AM
0
comments
Labels: Place holder
Friday, January 11, 2008
How to Read images from SqlServer in ASP .NET by Das
Introduction
This article is a continuation of my previous article, which talks about Inserting an image to Sql Server. I would recommend to read the above article before continuing this.
Compared to inserting an image, retreiving is very simple. The only new thing that we need to write an image is, we need to use the method BinaryWrite of the Response Object. Also we need to set the appropriate content type. In this article, we will discuss about retrieving images from a Sql Server.
We will be learning the following aspects in this article.
- How to set the Content Type?
- How to use the method, BinaryWrite
Since we already have data in the table, Person, we will add some statements which retrieves all the rows from the table, person. The following code retrieves all rows from the table, Person.
Code to retrieve image from sql server.
| Public Sub Page_Load(sender As Object, e As EventArgs) Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString")) Dim myCommand As New SqlCommand("Select * from Person", myConnection) Try myConnection.Open() Dim myDataReader as SqlDataReader myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection) Do While (myDataReader.Read()) Response.ContentType = myDataReader.Item("PersonImageType") Response.BinaryWrite(myDataReader.Item("PersonImage")) Loop myConnection.Close() Response.Write("Person info successfully retrieved!") Catch SQLexc As SqlException Response.Write("Read Failed : " & SQLexc.ToString()) End Try End Sub |
How it works?
The above example is very very simple. All we are doing is executing a sql statement and looping through all the records. We are displaying only the Image from the table, Person. Before dispalying the image, we first set the contentType. Then we write the image to' the browser using the method, BinaryWrite
Test this ScriptDownload the code
Click here to download the ASPX page
Conclusion
Thus we saw how to retrieve images from a sql server.
Retrieve images,Retrieve images from sql server,Retrieve images from sql in asp.net VB.Net,Retrieving Images to SqlServer in ASP .NET,code for Retrieving images from SQL server vb.net
Posted by
Arya
at
7:35 PM
0
comments
Labels: File handling, SQL Server
How to store images to SqlServer in ASP .NET by Das
Introduction
There will be many occassion, in which we will be urged to store images in the Database. In some applications we may have some sensitive information which cannot be stored in a file system, since if anything is in the file system, then it may be very easy for the users to hack the pictures/images.
In this article, we will discuss about, how we can insert images to a SqlServer 2000.
We will be learning the following aspects in this article.
- Prerequistes for inserting an image file
- Working with the Stream Object
- Finding the Size and Type of the image that is going to be uploaded
- How to use the InputStream method?
Prerequistes for inserting an image file
Two primary things that we need before the upload begins are
# The property enctype of the Form tag should be set to enctype="multipart/form-data"
# We should have a which allows the user to select the necessary image file (which will be inserted into the database)
# Also we need to Import the Namespace, System.IO to deal with the Stream object.
The above three points applies to an ASPX page. Also we need to have the following prerequistes in the SqlServer.
# We should have a Table with atleast one of the field of type Image.
# It will be better, if we have another field of type Varchar to hold the image type.
So, we have a Sql Table with the field type of Image and we have a (HTMLFile control). We also need a Submit button, where user can click after selecting the image. In the OnClick event of the button, we need to read the content of the image file and finally we insert the image to the table. Let us take a look at the OnClick event of the button, which reads the image and inserts into the sql table.
Code in the OnClick event of the Submit button.
| Dim intImageSize As Int64 Dim strImageType As String Dim ImageStream As Stream ' Gets the Size of the Image intImageSize = PersonImage.PostedFile.ContentLength ' Gets the Image Type strImageType = PersonImage.PostedFile.ContentType ' Reads the Image ImageStream = PersonImage.PostedFile.InputStream Dim ImageContent(intImageSize) As Byte Dim intStatus As Integer intStatus = ImageStream.Read(ImageContent, 0, intImageSize) ' Create Instance of Connection and Command Object Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString")) Dim myCommand As New SqlCommand("sp_person_isp", myConnection) ' Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure ' Add Parameters to SPROC Dim prmPersonImage As New SqlParameter("@PersonImage", SqlDbType.Image) prmPersonImage.Value = ImageContent myCommand.Parameters.Add(prmPersonImage) Dim prmPersonImageType As New SqlParameter("@PersonImageType", SqlDbType.VarChar, 255) prmPersonImageType.Value = strImageType myCommand.Parameters.Add(prmPersonImageType) Try myConnection.Open() myCommand.ExecuteNonQuery() myConnection.Close() Response.Write("New person successfully added!") Catch SQLexc As SqlException Response.Write("Insert Failed. Error Details are: " & SQLexc.ToString()) End Try |
How it works?
The Object, PersonImage is the name of the HTMLInputFile control. First we need to get the size of the image that is going to be inserted and that is done by
intImageSize = PersonImage.PostedFile.ContentLength
. Then we retrieve the image type using the property ContenType. Then the most important thing is, we need to get the Image Stream and that is done by
ImageStream = PersonImage.PostedFile.InputStream
. We have an array of Bytes, ImageContent, which is ready to hold the image content. The entire image is read using the method Read of the Stream Object. The method read takes three arguments, viz;
# Target Location that the Image Content to be copied
# Starting position for the purpose of read
# Number of bytes that needs to be read
. And the Read statement is
intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
. Now, we have read the entire image content. Next we need to insert this into a sql table. We are going to use a stored procedure which inserts the image type and the image to a sql table. If you go through the above code listing, then you can see that we use the datatype as SqlDbType.Image. That is it. We have successfully inserted an image to SqlServer.
Sample output of our scenario
The code listing that we saw in the begining of this article is only a part of the ASPX page. I have the complete code listing for you in the download section. You can also download the stored procedure that are needed to create the table and the stored procedure which inserts the data into the table. Following is the output of our scenario:
Fig: Inserting an Image to SqlServer Database.
Download the code
Click here to download the ASPX page
Click here to download the Stored Procedure
Conclusion
Thus we have discussed about how to insert image to a Sql Server. We also have ready to use examples and stored procedures which are available in the Download (above) section.To know how to read images from a SqlServer, read article Retrieving Images from SqlServer in ASP .NET
store images,store images in sql server,store images to sql in asp.net VB.Net,store images in sql server,Inserting Images to SqlServer in ASP .NET,code for inserting images to SQL server vb.net,code for storingimages to SQL server vb.net
Posted by
Arya
at
7:16 PM
0
comments
Labels: File handling, SQL Server
Sunday, January 6, 2008
Web.config and Security
There are two types of XML configuration files used by ASP.NET, they are called machine.config and Web.config. The format of these files and elements that they can contain are the same, however the machine.config file provides the default configuration for all applications and directories, while the Web.config file allows you to modify these defaults for a specific application or virtual directory. The machine.config is a located at: [install drive]:\WINNT\Microsoft.NET\Framework\[ASP.NET Version Number]\CONFIG and there is only one copy of this file per Webserver, whereas there may be dozens of Web.config files for various applications and subdirectories. You can establish the conditions for access to a particular directory or application, by modifying the <system.Web> section in your application’s Web.config file. The conditions you set in the Web.config file will apply to the directory, which contains it, as well as all of its associated sub directories. Within the Web.config file the <system.Web> section establishes the security profile for the application or directories overseen by it. The general syntax for the security section of the Web.config file is illustrated in Listing 13-1: Listing 13-1 General syntax for the security section of the Web.config file
<?xml version=”1.0” encoding=”utf-8” ?>
<configuration>
<location path=”[Path of specific file to which system.Web applies]”>
<system.Web>
<authentication mode=”[Windows/Forms/Passport/None]”>
<forms name=”[name]” loginUrl=”[url]” protection=”[All, None,
Encryption, Validation]” timeout=”[time in minutes]” path=”[path]” >
<credentials passwordFormat=”[Clear, SHA1, MD5]”>
<user name=”[UserName]” password=”[password]”/>
</credentials>
</forms>
<Passport redirecturl=”internal” />
</authentication>
<authorization>
<allow users=”[comma separated list of users]” roles=”[comma
separated list of roles]” verb=”[GET, POST, HEAD]”/>
<deny users=”[comma separated list of users]” roles=”[comma
separated list of roles]” verb=”[GET, POST, HEAD]”/>
</authorization>
<identity impersonate=”[true/false]” name=”[Domain\Username to operate
under]” password=”[password of Domain\UserName]”/>
</identity>
<system.Web>
</location>
</configuration>
Note the use of camel-casing throughout the Web.config and machine. config file where the first letter of the first word is always lower-case and the first letter of the subsequent word is upper-case, as in “configSections”. This is important because the entire file is case sensitive, and errors in case will create application errors.
The default and optional values for these elements are shown in below Default and Optional Values for Security Section of Web.config Element and Default Value Optional Values Comment
<location path=””> Any string that represents If you include a location tag in a valid path to a file then the settings contained in the <system.Web> section following this tag will only apply to the specific file path named in the path property. This tag is optional and should typically only be used for files not supported by ASP.NET.
<authentication mode= Forms, Passport, None The authentication mode cannot
”Windows”> be set at a level below the
application root directory.
<forms name=”.ASPXAUTH”> Any string for storing You can use any string you like
the cookie for the cookie name.
<forms login Url= Any valid absolute or If the mode is set to Forms, and
”login.aspx”> relative URL if the request does not have a
valid cookie, this is the URL to
which the request is directed for a forms-based login.
<forms protection= All, None, Encryption The value within the cookie can ”None”> and Validation by encrypted or sent in plain text. For sites that only use forms authentication to identify a user and not for security purposes, then the default None is just fine.
Element and Default Value Optional Values Comment
<forms path=”/”> Any valid string Specifies the path value of the cookie. Cookies are only visible to the path and server that sets the cookie.
<credentials Clear, MD5 Tells ASP.NET the password
passwordFormat=”sha1”> format used to decrypt the password value of the user attribute.
Note that just setting this value does not automatically encrypt the password value, instead it is
the developers responsibility to add the password value in an encrypted format.
<Passport redirecturl= Any valid URL that The authentication mode must ”internal”
> provides a login equal “Passport” for this to validation apply. When the requested page
requires authentication and the user has not signed on with Passport, then the user will be redirected to the supplied “redirecturl”.
<user name=””> Any valid user name For example use the value as string “jsmith”. <user password=””> Any valid password For example use the value as string “jsmithspassword”.
<allow users=”*”> Any comma-delimited By default the special character * list of users indicates that all users are
allowed; alternatively, ? indicates that anonymous users are allowed
<allow roles= > Any comma-delimited The special character * indicates list of roles that all roles are allowed.
<deny users=””> Any comma-delimited Special characters * for all users list of users and ? for anonymous user can be used. Element and Default Value Optional Values Comment <deny roles=””> Any comma-delimited The special character * for all list of roles roles can be used.
<identity impersonate= True With impersonation set to ”false”> “True”, the usernames and passwords will be compared against valid NT User Groups to determine access based upon
NTFS Access Control Lists.The ASP.NET Configuration System only applies to ASP.NET Resources, which are those items handled by the xspisapi.dll. By default items not handled by
this DLL, such as TXT, HTML, GIF, JPEG, and ASP files, are not secured by the Web.config. To secure these items use the IIS admin tool to register these files, or use the
<location> tag to specify a specific file or directory. Note The following example grants access to Tony, while denying it to Jason and anonymous users:
<?xml version=”1.0” encoding=”utf-8” ?>
<configuration> <system.Web>
<authorization> <allow users=”Tony” />
<deny users=”Jason” />
<deny users=”?” />
</authorization>
<system.Web>
</configuration>
Next we’ll look at how users and roles may refer to multiple entities using a commaseparated
list:
<allow users=”Tony, Jason, DomainName\tcaudill” />
As you can see, the domain account (DomainName\tcaudill) must include both the
domain and user name combination.
Special identities
In addition to identity names, there are two special identities: *, which refers to all identities,
and ?, which refers to the anonymous identity. So, to allow Jason and deny all other
users you could set the configuration section as shown in the following code sample:
<?xml version=”1.0” encoding=”utf-8” ?>
<configuration>
<system.Web>
<authorization>
<allow users=”Jason” />
<deny users=”*” />
</authorization>
<system.Web>
</configuration>
Using request types to limit access
You can also limit access to resources based upon the request type, GET, POST, and HEAD.
The following example lets everyone do a POST, but only Jason can perform a GET request:
<?xml version=”1.0” encoding=”utf-8” ?>
<configuration>
<system.Web>
<authorization>
<allow verb=”GET” users=”Jason” />
<allow verb=”POST” users=”*” />
<deny verb=”GET” users=”*”/>
</authorization>
<system.Web>
</configuration>
When it is determined that a user should be denied, then the default 401 code is
displayed.
Posted by
Arya
at
11:35 PM
0
comments
Labels: ASP.NET 2.0, Security
Understand ADO.NET---ASP.Net
ADO.NET enables datacentric applications to connect to various data sources and retrieve, manipulate, and update data. ADO.NET uses XML to transfer data across applications and data sources. This enables you to use ADO.NET to access data from data sources that expose data via OLE DB or ODBC or from the data sources that providers are available for. The .NET Framework includes SQL Server .NET Data Provider to access Microsoft SQL Server (version 7.0 and later) and OLE DB .NET Data Provider to access database servers that use OLE DB to expose data. In addition, you can also download ODBC .NET Data Provider and Oracle .NET Data Provider from http://msdn.microsoft.com/downloads. In traditional database applications, clients establish a connection to a database and keep the connection open until the application completes execution. Open database connections require system resources. For example, multiple open connections make the database server slow to respond to client calls because most databases can only maintain a small number of concurrent connections. Similarly, applications that require an open database connection are difficult to scale.
One of the advantages of ADO.NET is that it supports disconnected architecture. Using a disconnected architecture, applications connect to a database server only to retrieve or update the data. This enables you to reduce the number of open connections to various database servers. ADO.NET also provides a common data representation that enables you to access data from multiple and various types of data sources and have it appear as one entity.
ADO.NET allows you to use data commands to execute SQL statements or stored procedures from a client application. These data commands enable you to execute SQL statements on a database server easily and quickly. For example, to retrieve a set of rows from a database, you establish a connection to the database, create a data command, specify the SQL SELECT statement to retrieve the required records, and call the execute method of the command. The command object returns the set of rows, which you can process immediately or store in an ADO.NET DataSet for processing at a later time.
An ADO.NET DataSet is a cache of records that you retrieve from a data source, such as a database or an XML file. A DataSet contains records from one or more tables. In addition, a DataSet contains information regarding the relationships between tables. DataSets enable you to process data whenever a user needs to access and process data. You can also use DataSets without a data source to manage data from an application or from an XML file. In addition, DataSets enable you to remain disconnected from the database. Another advantage of DataSets is that components can exchange DataSets. For example, a business object in the middle tier can create and populate a DataSet and then pass it to another component in the application, which then processes the DataSet.
When you create a datacentric application using ADO.NET, data moves between various objects. The data first moves from a data source to a DataSet and then to components, such as controls, in a form. ADO.NET uses XML to transfer data between various components of an application. The ADO.NET data APIs auto-matically create the XML files of the data in a DataSet and send them to other ?components.
The application you create accesses a data source by using a .NET data provider. A .NET data provider enables you to connect to a data source and execute commands to retrieve results and manipulate data. The .NET Framework provides two data providers: OLE DB .NET and SQL Server .NET. You use the OLE DB .NET data provider to connect to and access an OLE DB data source, whereas the SQL Server .NET data provider enables you to connect to and access a SQL Server database. These data providers are an important part of the ADO.NET architecture.
The classes of ADO.NET are defined in the System.Data namespace. This namespace defines classes, such as DataSet and DataTable, which constitute the ADO.NET architecture. Therefore, you add a reference to the System.Data name-space in your application when you want to use ADO.NET. The next section discusses the ADO.NET architecture.
ADO.NET enables data transfer between components, such as data sources, DataSets, and the applications that request data. Together, all of these components constitute the ADO.NET architecture. Figure 5.1 displays the ADO.NET ?architecture.
In addition to the data source, the ADO.NET architecture includes data providers and DataSets.
A data source is a database server for which the .NET Framework provides a data provider or an XML file. To access a data source, you create a connection to the data source using the data providers of ADO.NET. The ADO.NET data providers enable you to establish a connection with a data source and perform other tasks, such as executing SQL commands on data sources. You will learn more about data providers later in this lesson.
The datacentric applications that you create usually need to access data from multiple tables. In addition, you might need to process data from multiple tables as one entity. For example, an organization might need to access the names of all its customers and the quantity of each product supplied to them.
ADO.NET DataSets are designed to store data in disconnected and distributed data environments. ADO.NET DataSets enable you to store data from multiple data sources. The DataSet stores data in a collection of tables. In addition, DataSets store relationships between tables. A DataSet is the data source for the application that requests data. The application can access and manipulate records in the DataSet without having to repeatedly connect to the database.
The functionality of DataSets is defined in the DataSet class. The DataSet class consists of a collection of one or more DataTable objects that represent tables. You will learn about DataSets in Lesson 3.
.NET data providers enable an application to connect to a data source, execute commands, and retrieve results. A .NET data provider consists of the Connection, Command, DataReader, and DataAdapter objects, which you use to perform such tasks as connecting to a database and executing SQL commands. Table 5.1 describes the function of each object.
| Object | Description |
| Connection | This object enables you to establish and manage a connection to a database. |
| Command | This object enables you to execute SQL commands and retrieve results from a database. The Command object also enables you to perform other tasks, such as updating the records of the database. |
| DataReader | This object enables you to read data in a sequential manner. The DataReader retrieves a read-only, forward-only data stream from the database. However, the DataReader object allows you to store only one row of data in memory at any point in time. |
| DataAdapter | This object enables a database and a DataSet to communicate with each other. You use the DataAdapter object to transfer data between a data source and a DataSet. In addition, the DataAdapter object can transfer data between a DataSet and some other applications, such as Microsoft Exchange Server. |
Visual Studio .NET and the .NET Framework include two ADO.NET data providers: an OLE DB .NET data provider and a SQL Server .NET data provider.
The OLE DB .NET data provider enables you to connect to the OLE DB data sources, whereas the SQL Server .NET data provider enables you to connect to SQL Server 7.0 and later databases. The System.Data namespace contains two namespaces: System.Data.OleDb and System.Data.SqlClient. These namespaces contain classes for the OLE DB .NET and SQL Server .NET data providers, respectively. Therefore, to use a data provider in your application, you add a reference to the appropriate namespace. The classes of each data provider contain methods that enable you to perform the following tasks:
-
Create a connection with a database
-
Execute SQL statements or stored procedures on a database
-
Read data rows from a database in forward-only mode
-
Transfer data between a database and a DataSet
-
Display errors and warning messages returned by a database
-
Handle exceptions when a database returns an error or warning
-
Execute Transact-SQL statements on a database
XML is an important component of the ADO.NET architecture. ADO.NET uses XML internally to store and transfer data. You need not explicitly convert data to the XML format or the XML format to data. XML is integrated with ADO.NET as DataSets. The structure of the DataSet, including table definitions, columns, data types, and constraints, is defined by using an XML schema. You can serialize the data within a DataSet as XML. Similarly, you can serialize the structure of the DataSet as an XML schema.
The components of the ADO.NET architecture listed in Table 5.1 enable you to access data and perform operations on data sources easily.
ADO.NET provides many benefits that will help you create datacentric applications. The following sections discuss the benefits of ADO.NET.
Interoperability is one of the key benefits provided by ADO.NET. Because ADO.NET uses XML to exchange data, any component that understands XML can receive data from ADO.NET. For example, you can transfer data between ADO.NET and an application that is running on any platform. The integration of XML and ADO.NET allows ADO.NET to operate easily with the applications that support XML.
Applications created using ADO.NET are easier to manage and scale than applications created using ADO. For example, after developing an application, you might need to change its architecture to improve its speed or increase the number of people who can access the application. Consider the example of an e-commerce site. As the e-commerce site becomes popular, the number of hits on the site increases. If the number of hits increases, you might need to change the architecture of the application and increase the number of tiers. However, increasing the number of tiers in a deployed application is a difficult and time-consuming task. In addition, problems might occur during data exchange or data transfer between the tiers. ADO.NET enables you to easily increase tiers in a deployed application because ADO.NET uses XML to transfer data between tiers. This enables the objects in new tiers to exchange data seamlessly.
ADO.NET simplifies programming for various tasks, such as executing SQL commands. This enables you to increase productivity and minimize the number of errors. For example, you can use the ADO.NET data commands to execute SQL statements or stored procedures. The actual task of building and executing a SQL statement is abstract and performed by ADO.NET. In addition, the ADO.NET data classes enable you to use typed programming to write code. Typed programming allows automatic statement completion. Therefore, it becomes easy to write code. In addition, typed programming increases the safety of the code and reduces the number of compilation errors.
ADO disconnected recordsets use COM marshaling to transfer data between applications. This requires data type conversion in order for COM to recognize the data types, and the conversion diminishes the performance of an application. Alternatively, ADO.NET uses XML to transfer data. Therefore, the requirement to convert the data type does not exist, which increases the performance of an application.
With the increase in data and the change in the business models of organizations, the demand for data has increased rapidly. Consider a Web site that sells sporting goods. When a prospective buyer wants to view product information, the information is available in the Products database. If several prospective customers accessing the Web site simultaneously want to view information about the same product, the demand for data from the Products database increases. ADO.NET enables your applications to scale according to requirements because it uses disconnected architecture. This enables you to reduce the open connections to the database and results in optimum usage of resources.
The features of ADO.NET discussed in the preceding sections provide greater benefits than ADO. The following section explains the basic differences between ADO and ADO.NET.
ADO and ADO.NET have various differences, such as differences in architecture, data representation, and methods of sharing data between applications.
ADO uses a recordset to represent data that is retrieved from tables in memory, whereas ADO.NET uses DataSets. A recordset usually contains data from a single table. To store data from multiple tables, you use a JOIN query. The JOIN query retrieves the data from multiple tables as a single result table. Alternatively, ADO.NET uses a DataSet to represent data in memory. As mentioned earlier, a DataSet can store data from multiple tables and multiple sources. In addition, a DataSet can also contain relationships between tables and the constraints on a table. Therefore, a DataSet can represent the structure of a database.
ADO provides a read-only navigation on recordsets, which allows you to navigate sequentially through the rows of the recordset. However, in ADO.NET, rows are represented as collections. Therefore, you can access records using the primary key index. In addition, you can also filter and sort results.
In ADO.NET, you only connect to a database to retrieve and update records. You can retrieve records from a database, copy them into a DataSet, and then disconnect from the database. Although a recordset can provide disconnected data access in ADO, ADO was primarily designed for connected scenarios.
In ADO.NET, you communicate with the database using a DataAdapter or a DataReader that makes calls to an OLE DB provider or to the APIs provided by the data source.
You use COM marshaling in ADO to transfer a disconnected recordset from one component to another. In ADO.NET, you transfer a DataSet using an XML stream. XML provides the following advantages over COM marshaling when transferring data:
- Richer data types.
COM marshaling can only convert data types that are defined by the COM standard. In an XML-based data transfer, restrictions on data types do not exist. You can use XML-based data transfer to transfer any data that is serializable.
- Bypassing firewalls.
A firewall does not allow system-level requests, such as COM marshaling. Therefore, a recordset cannot bypass a firewall. However, because firewalls allow HTML text to pass and ADO.NET uses XML to transfer DataSets, you can send an ADO.NET DataSet through a firewall.
Posted by
Arya
at
10:40 PM
0
comments
Labels: ASP.NET 2.0
Some thing about Web.Config File in ASP.Net
The Web.Config file is an XML-based configuration file that's used by ASP.NET to set options for your application. Each new project you create has its own Web.Config file. Within a project, you can have multiple Web.Config files in different folders, setting up a hierarchy of what settings to use for each folder.
When you're just getting your feet wet with ASP.NET, you'll normally just use the one default Web.Config file on a per-project basis.
As you've seen in the previous section, you can use the Web.Config file to set application-level settings for state management. You can also set security on directories, set up page-and session-level debugging, and store your own custom configuration information.
The biggest benefit to the Web.Config file is that you have a place to store variable data that might have otherwise been kept in application-level or session-level variables in ASP. For example, database connection information, folder locations, and virtual path information can all be stored in the Web.Config file. With an ASPX page, you can retrieve information from the Web.Config file by using the ConfigurationSettings class.
To see how this works, take a look at the custom AppSettings section in the following Web.Config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="cn" value="Server=Enterprise;UID=NCC1701D;
Pwd=CaptJaneway;Database=Ships"/>
<add key="pics" value="C:\InetPub\storage\"/>
<add key="picsHTTP" value="http://www.picsserver.com/public/"/>
</appSettings>
<system.web>
Each of the values stored can be accessed by retrieving the correct key attribute in code. To do this, you would use the following code:
sqlCn = ConfigurationSettings.AppSettings("cn")
You could also use the GetSettings method to return an array of the items in the AppSettings collection. Storing variable data in the Web.Config file is important for two reasons:
-
You don't need to recompile your application if a setting changes; you simply modify the Web.Config file.
-
You aren't consuming memory using session- or application-level variables.
Posted by
Arya
at
10:34 PM
0
comments
Labels: ASP.NET 2.0
Managing State in ASP.NET Web Applications
The Internet is a stateless application. In a nutshell, that means every call to the server is separate from the next or the previous call. Unlike Windows Forms applications in which you can set global variables and have a bunch of hidden forms open to maintain the state of the data, the Web doesn't afford you that luxury. So, the challenge is to keep track of where the user is in your Web application, and where to take her next. This is done by maintaining state.
State can be maintained in several ways, and some ways are better than others. Where you maintain state can be broken down into two categories: on the client and on the server.
Managing State on the Client
When I say managing state on the client, I mean handling page-level state in the browser. This can be done in the following ways:
-
The Viewstate control
-
Cookies
-
The HTML Hidden control
-
The browser's query string
Using Cookies
The most familiar way to handle state client-side is by using cookies. Cookies are a key-value paring of collection data that are saved on the client's hard drive. When you need to store information about someone's profile, you normally save a cookie that uniquely identifies him on his machine. If he closes the browser and revisits your site, you check for the cookie in a Page_Load event. If it exists, you use it to customize the look and feel of the HTML output. Or, you might simply have a Welcome Back Bob label on your home page, to let the user know he's logged in to your server, or that he's a returning visitor.
Before .NET, cookies were a problem because an end user can decide not to accept cookies on his machine. Because spam emailers and pop-up ads abuse cookies, many people fear them. To get around this, you can modify the Web.Config file to use sessionless cookies, meaning the cookie data is encrypted and passed in the query string of the browser, so no data is actually stored on the end user's machine. To change the cookies option in the Web.Config file, locate the sessionState section of the Web.Config file and modify the cookieless attribute to true, as the following code demonstrates:
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="true"
timeout="20"
/>
To access cookies in code, you access the Cookies property of the Request or Response object, depending on whether you're writing a cookie or reading a cookie. The following code snippet checks for a UserID cookie. If one doesn't exist, the code writes the cookie out.
Dim cookie As HttpCookie = Request.Cookies("UserID")
If cookie Is Nothing Then
Response.Cookies("UserID").Value = "Jason"
Response.Cookies("UserID ").Expires = "January 1, 2010"
Response.Cookies("UserID ").Path = "/"
Else
Response.Write(Request.Cookies("UserID")
End If
When using the Cookies object, you must set the Expires property to actually save the cookie. If you don't set the Expires property, the cookie is deleted when the user's browser session ends.
Note
In ASP, you could simply check the value of a cookie in server-side VBScript by using this syntax:
If Request.Cookies("UserID") = "" Then
This won't work in .NET if the cookie does not exist. You get an error message that says there's no instance of the Cookie object. You must explicitly check whether the HttpCookie object is Nothing, and then get or set the values of the cookie.
Understanding View State
View state is a new way of storing state data if you're coming from an ASP background. Each control and ASPX page has an EnableViewState property, which is set to True by default. When a page is processed that has ViewState enabled, a hidden field named Viewstate is added to the ASPX page and all the page data for the form is preserved in the hidden control. Each time a page is posted back to the server, the contents of the ViewState control are updated so that the correct data is in the fields when the same page is rerendered. This makes it so individual controls on a page don't lose their data each time the page is sent to the server.
Because ViewState is a page-level state management option, the data for each page is simply passed back and forth from the browser to the server inside the page itself. However, this can be problematic for scalability. Because the page data is kept in the hidden control, the page size can grow. For example, if you have a DataGrid control that lists all the authors in the Pubs database, all this information is stored in the page's ViewState control. Each time the page is rendered to the browser, the amount of data sent down the pipe is literally doubled. To avoid this, you can set the EnableViewState property to False for the control, thus eliminating the state data from being kept.
If you want to set ViewState data in code, you can use a key-value pair similar to a Cookies or Session object, as the following code demonstrates:
Viewstate("UserID") = "Bob"
Using the HTML Hidden Control
The HTML Hidden control is an HTML element in the Toolbox. Using hidden fields is a common way to store information in ASP. The concept is the same with the HTML Hidden control—you can set the Value property of the control to store page-specific information.
Using the Query String
Passing data between pages using the query string of the browser is a common way to keep page information safe, while not having to worry about cookies on the client or saving too much data with the ViewState control. When you post a page using HTTP-GET, which is set using the Method=Get attribute on the Form tag in the HTML of your page, you automatically send all the data in the fields through the query string of the browser. When you pass values of a form using HTTP-GET, the initial control ID is separated from the requested page by an ampersand, and the remaining fields are separated by the question mark character. If you were to pass the data to the Success.aspx page using HTTP-GET in the code you wrote for the Login.aspx page, the query string would look something like this:
http://localhost/helloweb_vb?Username=jason@fladotnet&Password=password
Of course, it isn't a wise idea to send secret information in plain text through a query string, so using HTTP-GET with password information isn't recommended.
Managing State on the Server
To manage state on the server side, you use either session state or application state. When developing in ASP, there are long-winded arguments about how, when, and where to store session-level state. This is because IIS can't scale very well if there are too many session variables in memory. For example, assume that you keep 10 session-level variables for each person who hits your site. On average, you have 1,000 hits an hour. That means IIS has to manage 100,000 unique objects in memory to keep track of each browser's session data. This would kill Web servers. In .NET, this is no longer an issue.
Using Session State
Using session-level state enables you to track variable data for a user throughout his visit to your Web site. Using the HttpSessionState class, you can use the same key-value pair syntax for Session objects that you use for ViewState. Each time a browser hits your site, IIS creates a unique session ID for the browser session if you access the Session object in code. If you don't reference the Session object in code, IIS doesn't create a unique ID for the end user's session on your site.
Session information is useful to save data between multiple page calls.we can pass variable values across pages by using session variables. For example, when I visit my bank's Web site, I must enter my username and password every time I visit, which means the bank isn't storing such high-security data in a cookie. But after I log in to the site, each page I navigate knows who I am, so the data is being passed to all pages for my session through the use of session state. To set or retrieve values for session state, you use this syntax:
If Session("UserID") = "Bob" then ...
Reponse.Write(Session("UserID"))
After the browser window is closed or the end user navigates to another site, the session data is lost. When the end user returns to the site, you must create new session information based on the user's current session.
In .NET, the Web.Config file gives you options as to where session-level state can be stored for a site. By default, session state is stored in the same process as IIS. If you need greater scalability, you can store session state in SQL Server or in an out-of-process state server. To change where the state is stored, you modify the mode attribute in the sessionState section of the Web.Config file. If you want to store your Session data in SQL Server, you modify Web.Config to look like this:
<sessionState
mode="SqlServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="false"
timeout="20"
/>
You must also supply the correct authentication information, and run a special SQL script that creates database and temporary tables in SQL Server to hold the state data.
In the Global.asax file, you can also write code in the Session_OnStart and Session_OnEnd events. You could use this to ensure that a session-specific event, such as updating a hit counter in a database, is occurring each time a session begins or ends.
Using Application State
Application-level state is the top level in the state management hierarchy. The first time someone accesses your Web site, the Application object for the site is created. The Application object is alive until the server is rebooted, IIS is restarted, or a new copy of the Web site is deployed. In the Global.asax file, there are Application_OnStart and Application_OnEnd events that you can write code to respond to; they're similar to the Session_OnStart and Session_OnEnd events. The difference is that application-level variables are global for all sessions for your Web site, not for individual users.
Posted by
Arya
at
10:26 PM
0
comments
Labels: Security
.NET Servers and the .Future of .NET
The designers of the .NET Framework put much thought into how distributed computing should work. It seems that .NET is the next killer app, but to make the .NET Framework a widespread success, actual servers must be built using the .NET Framework. Currently, there are no true .NET servers. There are servers that take advantage of the common language runtime and its managed execution environment, but most servers from Microsoft today still run under COM and unmanaged code.
Commerce Server 2002 is positioned as a .NET server for e-commerce, and applications you design with it can be completely written using Visual Basic .NET or C#, but the underlying infrastructure of Commerce Server is still based on COM. Because rewriting server applications is a truly monumental task, the move to completely .NET servers could take several years. Along the way, there'll be servers such as Commerce Server 2002 that are half managed code and half unmanaged code. From a developer's viewpoint that's fine, because you don't want to write ASP and Visual Basic 6 code for server products while the rest of your distributed application development is in a .NET language.
Currently, Microsoft seems to be positioning server products as .NET Enterprise Servers if they can integrate XML Web services into their existing infrastructure. For example, SQL Server 2000 certainly isn't written in managed code, but there are add-ons to SQL Server 2000 that enable you to expose stored procedures as XML Web services. The SQL Server Notification Service is a .NET add-on that allows notification to .NET applications if certain events trigger in SQL. BizTalk server's purpose in life is the orchestration and automation of complex business processes, and it's positioned as a .NET server because of its capability to consume XML Web services. The following Microsoft server products are considered .NET Enterprise Servers because of their capability to at least interact with a distributed environment such as the Internet and have some relationship with the .NET Framework concepts:
-
Internet Security and Acceleration Server
-
Application Center 2000
-
Commerce Server 2000 and Commerce Server 2002
-
BizTalk Server 2000 and BizTalk Server 2002
-
SQL Server 2000
-
Exchange Server 2000
-
Host Integration Server 2000
In my opinion, the fact that a .NET server is truly running under the common language runtime is not a deal breaker. For .NET to get to the next step, it must run on other operating systems, not just the Windows family of desktop and server operating systems. Currently, the Mono project is a grass-roots move to port the .NET Framework class library to the Linux operating system. That means the code you're writing now for Windows will also eventually run under Linux and, hopefully, Unix as well. You can learn more about the Mono project and where it currently is in the development process at http://www.go-mono.org. It would be a huge step forward if .NET were ported to the Macintosh operating system also. Although the Mac is still a small percentage of the overall market in desktop PCs, its incompatibility with Windows creates headaches for application developers. There needs to be consistency across platforms eventually.
Moving into the future with .NET, the sky seems to be the limit. This isn't necessarily because Microsoft is going to think of some great new thing to add to the .NET Framework, even though it most likely will, but it has to do with computing in general and the general infrastructure of our daily lives. As every household and business installs high-speed data access, and as computers become faster and cheaper, the applications you write will have a greater influence on how people look at what computer programs can do. You aren't bound to single servers anymore. Writing truly distributed and scalable applications is very easy because of the groundwork laid out by the .NET Framework. You can begin to look at the code you write not as blocks of modules running on a Windows 2000 Server, but as distributed objects that you can reuse in multiple applications across an enterprise simply by plugging them into an XML Web service. The future of .NET is the concept of a true distributed environment
Posted by
Arya
at
10:23 PM
0
comments
Labels: ASP.NET 2.0
Validation Controls in ASP.NET
Visual Studio .NET comes with built-in validation controls for use in ASPX pages. When you validate a control, you're checking whether a control has data in it and conforms to a specific pattern, (such as an email address), or you're checking the range of data that has been entered.
In ASP, you either had to process the validation on the server and send the page back to the browser if data wasn't correctly entered, or you had to write complex JavaScript to check the validity of control data. ASP.NET has five built-in validation controls in the Toolbox that you can simply drag to a form and associate with a control. Table 5.2 lists the validation controls and gives a description of how you can use each one.
| Control Name | Description |
|---|---|
| RequiredFieldValidator | Forces the user to enter a value into the specified control. |
| CompareValidator | Compares a user's entry against a constant value, or against a property value of another control, using a comparison operator. |
| RangeValidator | Checks that a user's entry is between specified lower and upper boundaries. You can check ranges within pairs of numbers, alphabetic characters, and dates. |
| RegularExpressionValidator | Checks that the entry matches a pattern defined by a regular expression. |
| CustomValidator | Checks the user's entry using validation logic that you write yourself. This type of validation allows you to check for values derived at runtime. |
Each validation control has properties specific to the functionality the control provides. For example, the RequiredFieldValidator has a ControlToValidate property and an ErrorMessage property. The ControlToValidate property takes the ID of a valid control on the form. The RegularExpressionValidator uses the regular expression syntax of .NET to validate the data entered in a control against a regular expression pattern.
Note
Each validation control has a Text property and an ErrorMessage property. The Text property is like the Text property of a Label control—it simply displays text. This could be used to display Required or an * for a RequiredFieldValidator control. The ErrorMessage property displays if an error occurs in the validation.
To test the validation controls, let's add a new Web Form to your solution. Right-click the project name in the Solution Explorer and select Add, Add Web Form from the contextual menu. When the Add New Item dialog pops up, change the name from WebForm2.aspx to Success.aspx, as Figure 5.12 demonstrates.
Figure 5.12. Add New Item dialog box.

You should now see a new ASPX page called Success.aspx is added to your solution, and the Success.aspx page should be in the Web Forms Designer. Double-click Success.aspx to get to the Form_Load event for the page, and add the code in Listing 5.5 to the Page_Load event.
Listing 5.5 Code-Behind for the Page_Load Event of the Success.aspx Page
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Response.Write("You are now logged in
")
End Sub
private void Page_Load(object sender, System.EventArgs e)
{
Response.Write("You are now logged in
");
}
In Listing 5.5, you use the Response object's Write method to render You are now logged in. This page is called from the WebForm1.aspx page if the correct username and password are entered.
To modify the WebForm1.aspx page, you must do the following:
-
Add a new table row above the Log In button. You can add a new row to the table by clicking inside the cell that contains the Log In button, and then right-clicking and selecting Insert, Row Above from the contextual menu. Most of the options you need for manipulating tables and controls can be accessed by right-clicking on the objects in the designer.
-
In the newly added row, drag a Label and TextBox from the Web Forms tab of the Toolbox to line up with the other controls in the table. Change the Text property of the Label control to Re-Enter Password, and change the ID property of the TextBox control to Password2.
-
Change the Text property of the Label control that says UserName: to now say Email Address:.
-
Drag a RequiredFieldValidator control to the form from the Web Form tab of the Toolbox, and place it in the column next to the Username TextBox.
-
From the Web Form tab of the Toolbox, drag a RegularExpressionValidator control and place it next to the RequiredFieldValidator control you just added.
-
From the Web Form tab of the Toolbox, drag a RequiredFieldValidator control to the form and place it in the column next to the Password TextBox.
-
From the Web Form tab of the Toolbox, drag a CompareValidator control to the form and place it in the column next to the Password2 TextBox.
Your WebForm1.aspx should now look like Figure 5.13.
Figure 5.13. WebForm1.aspx after adding new controls and validation controls.

The next step is to set the properties on the validation controls. Follow these steps to do so:
-
Select the RequiredFieldValidator1 control, and change the ControlToValidate property to UserName. Then change the ErrorMessage property to "Email Address Required".
-
Select the RegularExpressionValidator. In the ValidationExpression property, click the ellipses (…) button to get to the Regular Expression Editor dialog box. Scroll down the list until you see the Internet Email Address regular expression. Select it and click the OK button. Change the ErrorMessage property to "Invalid Email Format", and change the ControlToValidate property to Username.
-
Select the RequiredFieldValidator2 control, and change the ControlToValidate property to Password. Then change the ErrorMessage property to "Password Required".
-
Select the CompareValidator1 control, and change the ControlToCompare property to Password. Change the ControlToValidate property to Password2, and change the ErrorMessage property to "Passwords do not match".
When I mentioned regular expressions earlier, you might've gotten a little scared. But you can see that, once again, the Visual Studio .NET team thought of everything. Using the Regular Expression Editor, you can not only easily select a predefined regular expression for common data formats, but you also get a head start on understanding the regular expression syntax.
The next step is to rename the WebForm1.aspx to Login.aspx. To do so, right-click WebForm1.aspx in the Solution Explorer, and select Rename from the contextual menu. You can now change the name to Login.aspx. Make sure that you include the .aspx extension, or you'll get an error.
Now that you've set these properties and renamed your form, your Login.aspx should look like Figure 5.14.
Figure 5.14. Notice also that when you renamed your form, the WebForm1.aspx.vb or WebForm1.aspx.cs code-behind class file was also renamed.

Now, double-click the Log In button, and add the code in Listing 5.6.
Listing 5.6 Code-Behind for the LogIn_Click Event in the Login.aspx Page
Private Sub LogIn_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles LogIn.Click
If UserName.Text = "jason@fladotnet.net" _
And Password.Text = "password" Then
Response.Redirect("Success.aspx")
Else
LogIn.Text = "Invalid Data, please retry"
End If
End Sub
private void LogIn_Click(object sender, System.EventArgs e)
{
if (UserName.Text == "jason@fladotnet.net"
&& Password.Text == "password")
{
Response.Redirect(@"Success.aspx");
}
}
Tip
To make your user interface more friendly, you can set the InitialValue property of the RequiredFieldValidator control to a red asterisk or some other visual clue to the end user that the fields are required. You should also set the TextMode property of the Password and Password2 text boxes to Password so that the data entered into the field is filled with asterisks, and isn't visible to prying eyes.
Now you can build the solution, right-click the Login.aspx page, and select Browse from the contextual menu. After the page is in the browser, test the validation controls. Enter text that isn't an email address, and type different passwords in the Password text box and Password2 text box. When you do so, your form will look something like Figure 5.15.
Figure 5.15. Testing the Login.aspx validation controls.

Tip
You can also press the F5 key to run the application. This starts the application in debug mode. You learn more about debugging on Day 7, "Exceptions, Debugging, and Tracing."
Notice that when you click on the Log In button, the page is never posted to the server. When you place a validation control on a form, ASP.NET automatically adds custom client-side JavaScript when the page is rendered, so the validation occurs on the client and the page isn't posted to the server until the data is correct. Listing 5.7 is the HTML that's rendered to the browser—notice the JavaScript that's been added.
You can see that the HTML output is now vastly different from the output before adding validation controls, and the inserted client-side script was done by ASP.NET.
In the root wwwroot directory of your server, there's a folder named asp_client, which is used in conjunction with this script to make sure that the validation occurs. If you ever add validation to your pages and you get an error about validation files not being found when the page loads in the browser, make sure that the asp_client folder exists in the root of your wwwroot directory or in the actual folder of your Web site in the IIS server.
To see what happens with validation controls in Netscape version 4.79, check out Figure 5.16.
Figure 5.16. Running the validation controls in Netscape 4.79.

When ASP.NET detects that a down-level browser, such as Netscape 4.79, is attempting to access a page that uses validation controls, it simply changes the validation events to occur on the server. You don't need to do anything special to make this happen—it's automatic.
To display a summary of validation errors, you can use the ValidationSummary control on a page. This takes all the validation errors on the page, and places them in a nice bulleted list. Figure 5.17 demonstrates the use of a ValidationSummary control with the ShowMessageBox property set to True.
Figure 5.17. Using a ValidationSummary control.

To validate a page in server-side code, you check the IsValid property of a page. When you check the IsValid property for an entire page, all the validation controls on the page are checked against their respective controls to validate. If they're all okay, processing continues. If there are errors, processing stops and the validation controls or ValidationSummary control will be filled.
You can use this method of server-side validation checking by setting the EnableClientScript property to False for each validation control. In Listing 5.8 the Visual Basic .NET code (used in the Page_Load event) checks the IsValid property to check controls on the page against their validation controls.
Listing 5.8 Using the IsValid Method of the Page Class to Validate a Page
If Page.IsValid Then
If UserName.Text = "jason@fladotnet.net" _
And Password.Text = "password" Then
Response.Redirect("Success.aspx")
Else
LogIn.Text = "Invalid Data, please retry"
End If
End If
No matter what kind of validation you use, Visual Studio .NET makes it so easy to actually implement validation that you should always include it. Here's a user interface tip: Try to validate controls on the client side. There's nothing worse than going to a Web site, filling out a bunch of fields, clicking a Submit button, and then waiting for someone's slow Internet server to refresh the page just to tell you that you forgot to complete the Zipcode field or State field correctly.
Posted by
Arya
at
10:18 PM
0
comments
Labels: Validation
