Subscribe

RSS Feed (xml)

You can stream the binary data returned by SQL Server directly using the

You can stream the binary data returned by SQL Server directly using the


Response.BinaryWrite


method. Do this after retrieving the data from the database.


In <script runat="server" /> block or codebehind:


Sub Page_Load(sender As Object, e As EventArgs)


Dim connectionString as String = "Your connection string"


Dim objConnection as New SqlConnection(connectionString)


Dim commandText as String = "SELECT Image FROM imageTable"


Dim objCommand as New SqlCommand(commandText, objConnection)


Dim objReader as SqlDataReader


Try


objConnection.Open()


objReader = objCommand.ExecuteReader()


If objReader.Read() Then


Response.ContentType = "image/jpeg"


Response.BinaryWrite( CType(objReader("Image"), Byte()) )


End If


Catch exc as Exception


Response.Write( exc.ToString() )


Finally


If Not objConnection Is Nothing Then


If objConnection.State = ConnectionState.Open Then


objConnection.Close()


End If



End If




If Not objReader Is Nothing Then


objReader.Close()


End If


End Try


End Sub


Comments


This code will display the contents of the first record in the imageTable. In the example


code, the Image field in the SQL Server contains the binary data that is written out with


the Response.BinaryWrite method.


Response.ContentType should be set to the appropriate MIME-type of the image


that you are trying to display.This can be stored in the database as well and retrieved


along with the image data.




Technorati :

Inserting an Image into SQL Server

You must properly set up the SQL Server database table to accept images, as well as provide


a way on your Web Form to upload an image and send it to the SQL Server.


The table that will store the image must utilize the


image data type on a column that


will store the image. In the following examples, the name of this column is called Image.


In the .ASPX file:


<form enctype="multipart/form-data" runat="server">


<input id="ImageFile" runat="server" type="file" /><p />


<asp:button runat="server" id="UploadButton" OnClick="UploadImage" />


</form>


In <script runat="server" /> block or codebehind:


Sub UploadImage(sender As Object, e As EventArgs)


Dim connectionString As String = "Enter your Connection String"


Dim imageStream As Stream = ImageFile.PostedFile.InputStream


Dim byteData(ImageFile.PostedFile.ContentLength) As Byte


Dim objConn As New SqlClient.SqlConnection(ConnectionString)


Dim cmdText As String = "INSERT INTO sql_images(Image) VALUES(@image)"


Dim objCommand As New SqlClient.SqlCommand(cmdText, objConn)


Dim objParam As New SqlClient.SqlParameter("@image", SqlDbType.Image)


imageStream.Read(byteData, 0, imageFile.PostedFile.ContentLength)


objParam.Value = byteData


objCommand.Parameters.Add(objParam)


Try


objConn.Open()


objCommand.ExecuteNonQuery()


Catch exc as System.Exception


ErrorLabel.Text = exc.ToString()


Finally


objConn.Close()


imageStream.Close()


End Try


End Sub


Note that you must include the System.Data namespace for this code to compile.



Comments




The <form> tag has an additional attribute called enctype.This attribute allows binary


data to be passed through the form (which is needed for the image).


In the code, the submitted image file is broken into a byte array (imgdata) and then


used as the value of the SqlParameter that is passed in as the image (imgparam, @image).

Executing a Stored Procedure with No Results Returned

' Set up the connection / command


Dim connectionString as String = "server=.;database=Northwind;


Trusted_Connection=true"


Dim connection As New SqlConnection(connectionString)


Dim command As New SqlCommand("IncrementDownloads", connection)


command.CommandType = CommandType.StoredProcedure


' Execute, but don't return any results


connection.Open()


command.ExecuteNonQuery()


connection.Close()


Comments


There are many cases, especially when using stored procedures, where it is unnecessary


to return a result set from the database. In those cases, the


SqlCommand provides a simple


ExecuteNonQuery() method that can be used to run the results on the database.This


method doesn't return a result set-if one is returned it's simply ignored.


This technique is also useful when executing non-SELECT SQL scripts, such as


UPDATE, INSERT, and DELETE, where returning a result set serves no purpose.


When working with a datareader, make sure to close the connection. Unlike a


dataset, the connection stays open until you close it.

Using a Tool to Create a Data Access Layer

There are quite a few data access code generators available for .NET, with widely varying


costs and feature sets.This example demonstrates LLBLGen, an open source data tier


generator that supports a wide array of options for the created files. It generates stored


procedures for insert, update, select, and delete for the tables selected, and then creates


VB or C# classes to call these procedures. It is available at


http://www.sd.nl/


software/.This section uses version 1.2, released in November 2002.


To use LLBLGen, simply start the program and provide the connection information


for your database, as below figure shows.


textbox.JPG


Next, choose the tables and views for which you want to generate data access classes, as shown in below figure


new1.JPG


Now, choose the options you want for your .NET classes, including naming conventions,


namespaces, language, and method of storing the connection string. Below figure shows the available options.


new2.JPG


Do the same thing for the SQL procedures-pick which ones you want to generate, choose a common name prefix for them, and pick other options as described in below figure.


new3.JPG


Finally, generate the code! Choose the output paths for the .NET source files and the T-SQL script file, and watch as it generates your code for you.Below figure concludes this example, showing how a successful code generation should end.


new4.JPG

Using Microsoft’s Data Access Application

The first step is to reference the data, SQLClient, and data access application block


namespaces. Add the following statements to the top of your data access client


source file:


<%@ Page Language="VB" ClassName="Recipe1001vb" %>


<%@ import Namespace="System.Data" %>


<%@ import Namespace="System.Data.SqlClient" %>


<%@ import Namespace="Microsoft.ApplicationBlocks.Data" %>


<script runat="server">



Next, you have to place the following code inside a method. Page_Load will do fine for




this example:


Sub Page_Load(sender As Object, e As EventArgs)


Dim dataSet As DataSet


'parameter value variables


Dim beginningDate As string = "1/1/1996"


Dim endingDate As string = "12/31/1996"


Try


Dim connectionString As string = _


"Integrated Security=yes;Initial Catalog=Northwind;Data Source=(local)"


Dim arParams(1) As SqlParameter


arParams(0) = New SqlParameter("@Beginning_Date", beginningDate)


arParams(1) = New SqlParameter("@Ending_Date", endingDate)


dataSet = SqlHelper.ExecuteDataset(connectionString, _


CommandType.StoredProcedure, "Employee Sales by Country", arParams)


'bind dataSet to a WebControl and call Page.DataBind()


Catch exception As Exception


'An error occurred - were your connection string,


'stored procedure name and parameters correct?


'you could display the error via a WebControl or throw an exception here


End Try


End Sub 'Page_Load


Comments


This is a simple example-it barely scratches the surface of data access application


block functionality.There's support for performing transactional updates and fetching


XML as well as data-readers and caching parameters for multiple calls to a given stored


procedure.


The SqlHelper object manages just about everything for you. In order to achieve the


same result in ADO.NET, you would need SqlConnection, SqlCommand, and


SqlDataAdapter objects in addition to what you've declared here. Connection management


is improved as well because the SqlConnection is created internally to the object.


There is no need you for to close the connection-the object handles closing the connection


as it goes out of scope.


Finally, take the opportunity to examine the source code for the application block.


There are many examples of best practices in the source code that you might want to


apply to your own projects!

Connecting to an ODBC Datasource

Dim connectString As string = "DSN=myDSN;Uid=user;Pwd=pass"

Dim myConn As Microsoft.Data.Odbc.OdbcConnection = _

New Microsoft.Data.Odbc.OdbcConnection( connectString )

Try

myConn.Open()

'do something and then be sure to close the connection...
 
Finally

If Not myConn Is Nothing Then

myConn.Close()

End If

End Try

Comments

According to Carsten Thomsen, author of Database Programming in C#:

The OdbcConnection class, which uses the Platform Invoke feature, is roughly twice as fast for

standard applications than the OleDbConnection.The latter uses COM, which is chatty, and

hence has more server round-trips. So unless your application is shipping large amounts of data

(hundreds of thousands of rows or more) per data request, you should at least consider using

the OdbcConnection class. SqlConnection is roughly 20 percent faster than

OdbcConnection.



Technorati :

Connecting to MySQL Database

You can use the OleDB provider that ships with the .NET Framework. In this case, your


code would look something like this:


Dim connectString As string = _


"Provider=MySQLProv;Data Source=mydb;User Id=user;Password=pass"


Dim myConn As System.Data.OleDb.OleDbConnection = _


New System.Data.OleDb.OleDbConnection( connectString )


Try


myConn.Open()


`dosomething and then be sure to close the connection...


Finally


If Not myConn Is Nothing Then


myConn.Close()


End If


End Try


Another option is to use the MySQL data provider by eInfoDesigns (which I have only


minimally examined). In which case, your code would look like so:


Dim connectString As string = _


"Data Source=server;Database=mydb;User ID=user;


->Password=pass;Command Logging=false"


Dim myConn As eInfoDesigns.dbProvider.MySqlClient.MySqlConnection = _


New eInfoDesigns.dbProvider.MySqlClient.MySqlConnection( connectString )


Try


myConn.Open()


'do something and then be sure to close the connection...


Finally


If Not myConn Is Nothing Then


myConn.Close()


End If


End Try


Comments


You can access most datasources with the OleDB data provider, although it's not the


most efficient way to do so.You get better performance using a custom data provider


dedicated to that particular datasource. Although Microsoft does not support a custom


MySQL data provider, third-party software vendors are beginning to supply these.




Technorati :

Connecting to a Microsoft Access Database

To connect to a Microsoft Access database, you must include the


System.Data.OleDb


namespace because all the ASP.NET classes that are required to connect to datasources


through an OleDB connection are located in this namespace.The ASPX page looks as


follows:


<html>


<head>


<title>Connecting to a Microsoft Access Database<title>


</head>


<body>


<form runat="server">


<h3>Connecting to a Microsoft Access Database</h3>


<p>


<asp:DataGrid id="dg1" runat="server"></asp:DataGrid>


</p>


<p>


<asp:Literal id="ltlError" runat="server"></asp:Literal>


</p>


</form>



</body>




</html>


Add the following code within the <script> tags:


Public Sub Page_Load(Source As Object, E As EventArgs)


Dim ConnectionString As String


ConnectionString =


"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" & _


Server.MapPath("Northwind.mdb") & ";"


Dim QuerySQL As String


QuerySQL = "SELECT * FROM Shippers"


Dim objConn As New OleDbConnection(ConnectionString)


Dim objCmd As OleDbCommand


objCmd = New OleDbCommand


objCmd.CommandText = QuerySQL


objCmd.Connection = objConn


Try


objConn.Open()


dg1.DataSource = objCmd.ExecuteReader()


dg1.DataBind()


Catch Err As Exception


ltlError.Text = Err.ToString()


Finally


objConn.Close()


End Try


End Sub


Comments


First, you must create a connection string that includes the driver and the source path of


the source database. In this example, this has been assigned to the string type variable


named ConnectionString. Remember that if you are using Microsoft Access 97, the


connection string is going to be as follows:


"Provider=Microsoft.Jet.OleDb.3.75;Data Source=" & _


Server.MapPath("Northwind.mdb") & ";"



Whereas when using Microsoft Access 2000 and XP, the string is as demonstrated in the




code.You must create the Connection and Command objects as well.The Connection


object's constructor is provided with ConnectionString, which contains the connection


string.The Command object's instance is assigned the query and the connection that it


will use to access the datasource.


Having established the basic settings for the Connection and the Command objects,


you enclose the rest of the code within a Try/Catch/Finally block to capture any type


of errors that arise. Afterwards, within the Try/Catch block, you open the connection


and call the ExecuteReader method of the command object.This method executes the


specified query text and returns the results to the DataGrid control that has been


assigned to it.


When you view the page in the browser, you will see all the records from the database


table specified in the query.




Technorati :

Connecting to Oracle

Use the .NET data provider for Oracle, which is in the


System.Data.OracleClient


namespace. This data provider does not come with .NET 1.0, but must be downloaded


separately. Working with Oracle connections is similar to working with SQL Server connections,


as the following code demonstrates:


Dim connectString As string =


"Data Source=Oracle-Test;User ID=user;Password=pass"


Dim myConn As OracleConnection = New OracleConnection( connectString )



Try




myConn.Open()


//do something and then be sure to close the connection...


Finally


If Not myConn Is Nothing Then


myConn.Close()


End Try


Comments


As with the SqlClient data provider, the Oracle data provider offers significant performance


benefits over the OleDB connection method.




Technorati :

Connecting to SQL Server

Use the SQL Server .NET data provider in the


System.Data.SqlClient namespace to


connect to a Microsoft SQL Server 7.0 or 2000 database (for example, the Northwind


sample database).Your connection strings can take advantage of integrated security or


connect using a given SQL login and password.



First, you need to reference the SqlClient namespace. Add the following statement




to the top of your data access client source file to reference the System.Data.SqlClient


namespace:


Imports System.Data.SqlClient


Next, you need to create the connection, use it, and clean up inside a method. For


example, you can place the following in Page_Load:


Dim connectString As string =


"Integrated Security=yes;Initial Catalog=Northwind;Data Source=(local)"


Dim sqlConn As SqlConnection = New SqlConnection( connectString )


Try


sqlConn.Open()


'do something and then be sure to close the connection...


Finally


If Not sqlConn Is Nothing Then


sqlConn.Close()


End If


End Try


Here's an alternative version of an integrated security connection string.This will look


familiar if you build your connection strings using Universal Data Link (.UDL) files.


This VB.NET example explicitly references the Security Support Provider Interface


(SSPI) for the integrated security string and sets the connection string via the


ConnectionString property:


Dim sqlConn As SqlConnection = New SqlConnection()


sqlConn.ConnectionString = "Integrated Security=SSPI;Initial


Catalog=Northwind;Data Source=(local)"


Try


sqlConn.Open()


'do something and then be sure to close the connection...


Finally


If Not sqlConn Is Nothing Then


sqlConn.Close()


End If


End Try


As mentioned, you might also define a connection string that uses a specific SQL Server


logon ID. Using the first example, only the connection string changes:


connectString =


"User ID=user;Password=pass;Initial Catalog=Northwind;Data Source=(local)"


Now, let's say you want to create a connection to a remote database server. In this case,


you need to specify the SQL Server logon ID and password again. Using the


ConnectionString property, the connection string will look similar to this:



sqlConn.ConnectionString = "User ID=user;Password=pass;




Network Library=DBMSSOCN;Data Source=192.168.1.1,1433"


Of course, you have to change the IP address to match your configuration.


Comments


The most important point to remember is this: if you open a connection you must


remember to close it.You cannot rely on ADO.NET's garbage collector to do it for you


in a timely manner. If you neglect to close your connections, you will likely run out of


available connections in short order! The best way to ensure that connections are properly


closed is to wrap their usage in Try/Catch/Finally blocks. Also, in addition to the


techniques you've just seen, SqlConnection can also be created implicitly by certain


ADO.NET objects like the dataset.




Technorati :

Catching Exceptions

In <script runat="server" /> block or codebehind:


Private Sub Page_Load(Source As Object, E As EventArgs)


Dim _Connection As New


SqlConnection("Server=localhost;Database=pubs;uid=sa;pwd=;")


Dim _Command As New SqlCommand("Select * From Authors", _Connection)


Try


'_Connection.Open commented to cause an exception


'_Connection.Open()


DG1.DataSource = _Command.ExecuteReader(CommandBehavior.CloseConnection)


DG1.DataBind()


Catch _Error As Exception


MessageLabel.Text = _Error.Message


Finally


_Connection.Close()


End Try


End Sub


You can also provide multiple Catch statements, as shown here:


Private Sub Page_Load(Source As Object, E As EventArgs)


'Error has been produced in the connection


'string by writing "Server=localhos" (no 't')



Dim _Connection As New




SqlConnection("Server=localhos;Database=pubs;uid=sa;pwd=;")


Dim _Command As New SqlCommand("Select * From Authors", _Connection)


Try


_Connection.Open()


DG1.DataSource = _Command.ExecuteReader(CommandBehavior.CloseConnection)


DG1.DataBind()


Catch _SqlError As SqlException


MessageLabel.Text = _SqlError.Message


Catch _Error As Exception


MessageLabel.Text= _Error.Message


Finally


_Connection.Close()


End Try


End Sub


Comments


The Try/Catch/Finally block is the best approach towards error handling. It provides a


structured error-handling technique that was not available in previous versions of Visual


Basic.The Try block is provided with the code that is to be run.The Catch block is for


catching the exceptions raised by any line of code in the Try block.The Finally block


is executed under both conditions-either when the Try section successfully executes or


when an error occurs and is passed to the Catch block. It is for this reason that the


Close() method of the connection object has been coded in the Finally block, so as to


ensure that under both cases (whether successful or unsuccessful), the connection to the


data store is closed.


Multiple Catch statements can also be provided to capture different types of errors


raised by objects. In the second code listing, the exceptions that would be related to


SqlClient objects are going to be captured by the Catch statement having an object of


the SqlException class. All other exceptions are caught by the second catch statement


provided in the Try block.


The order of the Catch statements is very important. Make sure you put the more


generalized Catch exceptions after the more specific exceptions. For example, in the second


code listing, SqlException is a subclass of Exception, and so is more specific.Thus,


its Catch block occurs above the more generic exception's Catch block. If the order


were reversed, the SqlException Catch block would never be reached, because the


exception block would always catch a SqlException that was thrown.




Technorati :

Handling Page Level Errors

The Page_Error() event, exposed by the Page object, can be used to catch errors on a


page level.The following code demonstrates how you can use this event for page level


error handling.


In <script runat="server" /> block or codebehind:


Private Sub Page_Load(Source As Object, E As EventArgs)


Dim _Connection As New


SqlConnection("Server=localhost;Database=pubs;uid=sa;pwd=;")


Dim _Command As New SqlCommand("Select * From Authors", _Connection)


'_Connection.Open() causes an exception


DG1.DataSource = _Command.ExecuteReader(CommandBehavior.CloseConnection)


DG1.DataBind()


_Connection.Close()


End Sub


Public Sub Page_Error(Source As Object, E As EventArgs)


Response.Write(Server.GetLastError.ToString())


Server.ClearError()


End Sub


Comments


The demonstrated code tries to execute a query without having an open connection to


the datasource.This raises an exception, which is captured by the Page_Error() event of


the Page object itself.Within the Page_Error event, the code displays the error message


by calling the GetLastError method of the Server object.This returns an exception


object that is generated by the error. Note that the data access technique used in this



code is not a good approach for connecting to datasources; it has been adopted here




only for demonstrating the Page_Error event.You should always use the


Try/Catch/Finally statements for interacting with datasources.


Errors can also be handled at the application level using the Application_Error


event found in global.asax.




Technorati :

Raising Exceptions

In


<script runat="server" /> block or codebehind:


Private Sub Page_Load(Source As Object, E As EventArgs)


Dim _Connection As New


SqlConnection("Server=localhost;Database=pubs;uid=sa;pwd=;")


Dim _Command As New SqlCommand("Select * From Authors", _Connection)


Try


_Connection.Open()


DG1.DataSource = _Command.ExecuteReader(CommandBehavior.CloseConnection)


DG1.DataBind()


Catch _Error As Exception


Throw New Exception("Whoops.... You've got an error in the code!")


Finally


_Connection.Close()


End Try


End Sub


The Throw statement here creates a new exception and raises it, replacing the original


exception object.The error message that will appear on the page in this case is the one


that has been provided as an argument to the constructor of the Exception object.


The original error message can also be passed to the Throw statement in order to


show the details.You can achieve this by passing the Exception object as a second argument


to the constructor of the newly raised exception.


Catch _Error As Exception


Throw New Exception("Whoops.... You 've got an error in the code!", _Error)


Your exception message has been replaced by the original one, but your exception message


still appears.Where? Check out the Stack Trace section.


Comments


The Throw statement can be used to explicitly throw an exception or to rethrow a


caught exception.The new exception being raised is provided with a customized statement,


so as to hide error details and display a more simplified error message to the viewer.


You can also pass along the original exception object to the raised exception.This can


be useful because it allows a friendly error message to be displayed to the user, but keeps



the detailed information for debugging purposes.






Technorati :

Enabling Page Level Tracing

In order for page level tracing to be enabled, you need to add the


Trace attribute to the


@ Page directive.


<%@ Page Language="VB" Trace="true"%>



The default value of the Trace attribute is false, which means that it is disabled. In




order to enable it, you simply set its value to true. In <script runat="server" />


block or codebehind:


Private Sub Page_Load(Source As Object, E As EventArgs)


Trace.Write("Page_Load", "Declaring and initializing variables.")


Dim _A As Integer = 10


Dim _B As Integer = 20


Trace.Write("Page_Load", "Applying add operation.")


_A += _B


Trace.Write("Page_Load", "Variable values changed.")


Trace.Write("_A", _A)


Trace.Write("_B", _B)


End Sub


Trace.Write can accept up to three arguments-the first one is the category for the


message, the second is the actual message to display, and the third is the exception


information displayed after the message.The following listing demonstrates all three


arguments:


...


...


Try


'code goes here


Catch _Error As Exception


Trace.Write("Category", "Message", E)


End Try


Comments


In order to display Trace messages from your code, use either the Trace.Write() or the


Trace.Warn() statement.The difference between the two is that Trace.Warn shows the


output text in red, indicating a warning, whereas Trace.Write() shows output in black


text. Both methods accept the same number and type of arguments.


You can also use the Trace.IsEnabled Boolean property to test whether tracing is


enabled prior to performing an expensive operation, such as looping through all values


on the page as part of a Trace output operation.


Note that to access tracing outside of a page, such as in a custom control, you must


refer to the current Web context by using System.Web.HttpContext.Current.Trace()


instead of just Trace() or Page.Trace().




Technorati :

Logging Error Details

Create an object of type


System.Diagnostics.EventLog.Then begin the try/catch


block and enter the code you suspect is causing the error. Create a catch block to run if


an error occurs and assign the exception to the ex variable. Inside the block, create a


new EventLog instance. Set the log to send the error to, and enter your application name


as the source. Finally, write the exception to the event log.


In <script runat="server" /> block or codebehind:


Sub Page_Load(sender As Object, e As EventArgs)


Dim a as Integer=0


Dim myEventLog as System.Diagnostics.EventLog


Try


a=1/a


Catch ex as Exception


myEventLog=new System.Diagnostics.EventLog()


myEventLog.Log="Application"


myEventLog.Source="Recipe0902"


myEventLog.WriteEntry(ex.ToString())



End Try




End Sub


You also can handle errors on an application error by modifying the Application_Error


event handler in the global.asax file. Use Server.GetLastError() to get a reference to


the exception that was thrown.


In the global.asax file:


Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)


Dim myEventLog As System.Diagnostics.EventLog


Dim ex As Exception = Server.GetLastError()


myEventLog = New System.Diagnostics.EventLog()


myEventLog.Log = "Application"


myEventLog.Source = "Recipe0902"


myEventLog.WriteEntry(ex.ToString())


End Sub


Comments


Catching and keeping a log of errors that occur can greatly decrease the amount of time


you spend supporting an application. Note:The ASP.NET account does not have access


to write to the event log by default.To run this example, you need to do one of the


following:


1. Modify the processModel element in machine.config to set ASP.NET to run as


the System account.


2.Add the ASP.NET account to the local Administrators group.


3. Use regedt32 to grant the ASP.NET account write access to the


HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog key.

Configuring a Default Error Page in ASP.NET

In the web.config file, locate the


customErrors section. Set the mode to on and set the


URL for the default redirect.


The web.config file is as follows:


<customErrors mode="On" defaultRedirect="Recipe0901bvb.aspx"/>


In <script runat="server" /> block or codebehind:


Sub Page_Load(sender As Object, e As EventArgs)


Dim a as Integer=1/0


End Sub




The error handler page is as follows:


<html>


<body>


<form id="Recipe0901bvb" method="post" runat="server">


An error has occurred in this application.


</form>


</body>


</html>


Comments


Whenever an unhandled error occurs anywhere in your application, the users are directed


to your custom error screen.This is an important part of creating a professional and


secure Web site. Note that the contents of the web.config file are case sensitive.




Technorati :

Perform Custom Authentication on Each Request

The application event,


Application_AuthenticateRequest, which is defined in


global.asax, is used to perform custom authentication on every request to an application.



It is the perfect place to add custom checks to determine whether the users should be




given access to a particular resource, or to determine which resources the user should be


able to access. In the following example, the list of roles the user belongs to is retrieved


and stored in the HttpContext collection, which is available for the life of each request.


Individual resources can then use the list to determine whether the users should have


access to them.


In global.asax (or its codebehind), do the following:


Sub Application_AuthenticateRequest(ByVal sender As Object sender,


ByVal e As EventArgs)


If Request.IsAuthenticated = True Then


Dim roles() As String


' get this user's roles (left out)


' store roles in Context for the rest of this request


Context.Items.Add("SecurityRoles", roles)


End If


End Sub





Technorati :

Creating a Simple Forms Authentication Logout Page

Place a LinkButton control on the page and assign it the text of


Logout. Place a Literal


control on your page and title it message.This will be populated with a message telling


the users they have logged out and including the code to redirect them to another page.



The ASPX page is as follows:



<p align="center"><asp:LinkButton ID="Logout" Runat="server" OnClick="Logout_




Click">Logout</asp:LinkButton></p>


<p align="center"><asp:Literal ID="Message" Runat="server" /></p>


In <script runat="server" /> block or codebehind:


private void Logout_Click(object sender, System.EventArgs e)


{


System.Web.Security.FormsAuthentication.SignOut();


Message.Text="You have been logged out.";


Message.Text+="<meta http-equiv=\"Refresh\"


content=\"3;URL=http://aspalliance.com\" />";


}


Comments


On the Logout button Click event, do the following:


n Call System.Web.Security.FormsAuthentication.SignOut().This method


forces a log out by removing the authentication ticket and session cookies.


n Add text to the Message literal control to let the users know they have been


logged out.


n Add a Meta tag to the Message literal control to redirect the users to another page.


If you want to send the users back to the login page, you can redirect them to any


page in the application. Forms authentication will force the users to log in first


(assuming the page requires an authenticated user).




Technorati :

Creating a Simple Forms Authentication Login Page

Place two TextBox controls for the username and password on the page. Set the


TextMode property of the password TextBox control to


Password. Add a Button control


to perform the login, and a Label control to provide feedback to the users.


The ASPX page is as follows:


<p align="center">


<table cellpadding="2" cellspacing="0" bgcolor="#fafade">


<tr>


<th colspan="2" bgcolor="#baba99">


Login</th>


</tr>


<tr>


<td>User Name:</td>


<td><asp:TextBox ID="UserName" Runat="server" /></td>


</tr>


<tr>


<td>Password:</td>


<td><asp:TextBox ID="Password" Runat="server"


TextMode="Password" /></td>


</tr>


<tr>


<td colspan="2" align="center"><asp:Button ID="Login"


Text="Login" Runat="server" OnClick="Login_Click"/></td>


</tr>


</table>


<br>


<asp:Label ID="Message" Runat="server" ForeColor="#FF0000"></asp:Label>


</p>



In <script runat="server" /> block or codebehind:




Private Sub Login_Click(sender as Object, e as System.EventArgs)


If UserName.Text="johndoe" AND Password.Text="password" Then


System.Web.Security.FormsAuthentication.RedirectFromLoginPage(


UserName.Text, False)


Else


Message.Text="Invalid Username/Password combination"


End If


End Sub


Comments


On the Login button Click event, you simply add code to verify the user ID and


password are correct.You will most likely want to query a database or check another


source to verify the password instead of hard coding the logins in your code. If the


password is correct, you call System.Web.Security.FormsAuthentication.


RedirectFromLoginPage to send the users to the page they had originally requested.


Pass this function the name of the user who has logged in for use later in your application,


and pass it a boolean of whether to persist the cookie across browser sessions (many


login forms use a check box to determine which value to use for this). If the password is


not correct, you display an error to the users.

Requiring Authentication to Access Files and Folders

Define separate location sections in the web.config file with unique authorization


settings:


1. <location path="file">


2. <location path="folder">


In the web.config file in Web application's root folder:


<?xml version="1.0" encoding="utf-8" ?>


<configuration>


<system.web>


<authentication mode="Forms">


<forms name=".FormsCookie" loginUrl="Login.aspx" />


</authentication>


<authorization>


<allow users="?,*" />


</authorization>


<compilation defaultLanguage="VB" debug="true" />


</system.web>


<location path="SpecialFile.aspx">


<system.web>


<authorization>


<deny users="?" />


<allow users="*" />


</authorization>


</system.web>


</location>


<location path="SpecialFolder">


<system.web>


<authorization>


<deny users="?" />


<allow users="*" />


</authorization>


</system.web>


</location>


</configuration>



Each sub-folder of the Web application can have its own web.config file that specifies its


authorization settings. Individual files however can only have unique authorization settings


specified with the use of the location section. Note that authentication, unlike


authorization, is an application-wide setting that cannot be overridden for files or


folders.

Configuring Windows Authentication

Open the web.config file. Find the authentication tag under


system.web and set the


mode to Windows.This is the default setting if you created the web.config file in Visual


Studio.


The web.config file is as follows:


<system.web>


<authentication mode="Windows">


<system.web>


You must also configure IIS to require authentication.To do this, follow these steps:


1. Open Administrative Tools from either the Start menu or the Control Panel


(depending on the OS).


2. Open Internet Information Services.


3. Branch out the tree to find your Web application folder.


4. Right-click your Web application folder and choose Properties.


5. Click the Director Security tab.


6. Click the Edit button in the Authentication Control section.


7. Uncheck the Anonymous Access box and make sure Integrated Authentication


(Challenge Response) option is checked.


8. If you want to allow the users to type their passwords if IIS Challenge Response


fails, check Basic Authentication.


9. Click both OK buttons and close IIS.


Configuring Forms Authentication

The forms authentication setup process is done in the


<authentication> part of your


web.config file. As with all XML documents, the web.config file's contents are case


sensitive.


Here's the application's web.config file:


<configuration>


<system.web>


<authentication mode="Forms">


<forms name="CookBookForm"


loginUrl="login.aspx"


protection="All"


timeout="30"



path="/" />




</authentication>


</system.web>


</configuration>


Comments


The <forms> tag in web.config provides all the configuration necessary to provide forms


authentication for your application.


This tag includes the following options:


n name-This sets the name of the HTTP cookie that will be sent. If you have multiple


applications on the same server with forms authentication set up, you must


make this value unique in each one of them.


n loginUrl-This sets the location where the users are redirected for login (or any


other action) if they are not authenticated and try to access a secure page.


n protection-This specifies the level of protection to place on the cookie.You


can set this to All, None, Encryption or Validation, the default (and recommended)


is All.


n timeout-This sets the amount of time (in minutes) that a cookie remains valid,


after it was last requested, before it expires.


n path-This sets the path for the cookies to use; default is a backslash.This provides


additional protection because the client browser will not send the cookie if


there is a path mismatch.This value is case-sensitive to some browsers.

Reading and Storing Data in ViewState

The ViewState collection provides an easy way to maintain values on a particular Web


Form across postbacks.This collection is stored as a hidden form field, and thus all data


stored in ViewState is passed to and from the client on every request.You access it using


syntax similar to what you have seen for the Session and Application collections:


ViewState("UserName")="UserNameTextBox.Text"


UserNameLabel.Text = ViewState("UserName")


Comments


By default,Web controls that do not post back values will maintain their state automatically


using ViewState.This can be controlled individually for each control or globally for


each page by setting


EnableViewState to true or false as desired (either for a given


control or in the page directive).The amount of space a control occupies in ViewState


can easily be determined from the control tree section of the trace output.

Reading and Storing Data in Cookies

You can store small pieces of user-specific information in the user's Cookies collection


on the user's local machine, assuming the local browser supports cookies and the user has


not disabled this feature.You can use cookies to hold data for as long as the current


browser window is open, or you can give them an expiration date some time in the


future.The first variety is called an in-memory cookie, because they are never written to


the user's hard drive.The second variety is referred to as a persistent cookie, because


these cookies persist across browser and even machine restarts.


There are several ways to work with cookies in ASP.NET.The simplest uses syntax


very similar to that used for the Application and Session collections:


'write a cookie


Response.Cookies("UserName").Value = UserNameTextBox.Text


'read a cookie


UserNameLabel.Text = Request.Cookies("UserName").Value


In addition, you can give the cookies an expiration date, which will cause them to be


persisted to the user's hard drive.To delete these (and other) cookies, simply set their


expire date to any past date, as shown:


'persist a cookie


Response.Cookies("UserName").Expires =



System.DateTime.Now.AddDays(1) ' persist for 1 day


'delete a cookie


Response.Cookies("UserName").Expires = System.DateTime.Now.AddDays(-1)


Comments


Cookies can be a great place to store small pieces of data that are needed from page to


page.They do not have the overhead of sessions, and they can span multiple user visits


over large time periods.They can also span applications within the same domain (for


example, yahoo.com). Not all users will accept cookies, however. It's best to test for this


by writing a test cookie and attempting to read it back on a subsequent request. Cookies


can store only small amounts of text data, with an upper limit of less than 4KB, which


includes the data and the keys used to extract the data (for example, UserName in the


previous example).

Reading and Writing Values to the Session Object

You can store user-specific information, such as a user's name, in the Session collection.


Because the Session collection is user specific, it should not be written to by multiple


threads concurrently.Therefore, you do not need to use locks around your writes, as you


must with the Application collection . Otherwise, the syntax is similar:


Session("UserName")=UserNameTextBox.Text


UserNameLabel.Text = Session("UserName")


Comments


By default, the Session collection holds data for 20 minutes after the last request to an


application by a particular user.You can adjust this time period in the application's con-


figuration . Because data stored in sessions can grow linearly with the


number of users, and because it persists for quite some time after each user leaves, it can


quickly impede scalability if it is used to store large amounts of data. It should therefore


be used sparingly.

Reading and Writing Values to the Application Object

You can store the name of the server in application state using


Application("ServerName") ="WebFarm1"


.You can retrieve it and display its value by


using MyLabel.Text=Application("ServerName").ToString(). Because it returns the


server name as an object, you need to convert it to a string using the .ToString()


method before assigning it to MyLabel.Text.The ASPX page is as follows:


<html>


<body>


<form id="Recipe0701vb" method="post" runat="server">


<asp:Label ID="MyLabel" Runat="server"/>


</form>


</body>


</html>


In <script runat="server" /> block or codebehind:


Sub Page_Load(sender As Object, e As EventArgs)


Application.Lock()


Application("ServerName")="WebFarm1"


Application.UnLock()


MyLabel.Text=Application("ServerName").ToString()


End Sub


Comments


Application state is useful for storing values that you need to access throughout your


application. Once a value is added to application state, it exists for the life of the application.


Because multiple pages can attempt to write to the Application collection simultaneously,


it must be locked using Application.Lock prior to any writes.The lock is


released using Application.UnLock.The only time locking isn't necessary is in code


that isn't executed by multiple page requests, such as in Application_Start in the


global.asax.

Configuring Sessions in your ASP.NET Application

All of the configuration is provided by the


<sessionState> element in the web.config


file; all you have to do is alter the appropriate attributes.


There are several ways to store session information; these are described next.To disable


Session state, add this to web.config:


<configuration>


<system.web>


<sessionState mode="Off"/>


</system.web>


</configuration>


To enable local storage of Session state, add this to web.config:


<configuration>


<system.web>


<sessionState mode="InProc"


cookieless="true"


timeout="10" />


</system.web>


</configuration>


The InProc setting sets it so that the information is stored locally (the default).


Cookieless can be set to true or false and tells ASP.NET whether to use cookies


when storing session information. Timeout sets the time in minutes that sessions will


expire if they remain unused.


To enable storage of Sessions on a state server add this to web.config:


<configuration>


<system.web>


<sessionState mode="StateServer"


stateConnectionString="tcpip=127.0.0.1:42424" />


</system.web>


</configuration>


This tells ASP.NET to use a state server at the specified address (stateConnectionString).


The state server is found at %SYSTEMROOT%\Microsoft.NET\Framework\version\


aspnet_state.exe.This server then listens on port 42424 over TCP/IP; you can use


this port to store your session information.


To enable storage of Sessions on a SQL Server, add this to web.config:


<configuration>


<system.web>


<sessionState mode="SQLServer"


sqlConnectionString="data source=localhost;user id=sa;


password=securepassword;" />


</system.web>


</configuration>


This method tells ASP.NET to use SQL Server to store the information.To set up a


SQL Server to store session information, you must run the InstallSqlState.sql file located


in %SYSTEMROOT%\Microsoft.NET\Framework\version\ on the SQL Server (there is an


UninstallSqlState.sql file to uninstall it as well).

Configuring Application Error Handling

The web.config file includes a


<customErrors ...> section that controls how the application


responds to errors on its pages. A typical customErrors section follows:


<customErrors mode="RemoteOnly" defaultRedirect="/Maintenance.aspx" >


<error statusCode="404" redirect="/NotFound.aspx" />


</customErrors>


The settings are case-sensitive.The first attribute, mode, can be On, Off, or RemoteOnly.


The first two are self-explanatory; the third redirects errors only for non-local users, so


that a local developer can still debug problems without being routed to the "friendly"


error page.The second attribute, defaultRedirect, specifies the page to which any


request that results in an unhandled exception is sent. If it is not set but custom errors


are on, users will see a generic error message (instead of the detailed exception information).


Optionally, specific redirects can be set up for individual error codes by adding


<error ...> elements within the customErrors element. Each of these can specify a


statusCode, such as 404, that maps to a file not found error code, or 500, for a generic


application error. Each error code can be mapped to its own specific error page by setting


the path to the page in the redirect attribute.


Comments


Setting up friendly default error pages for ASP.NET applications and their common


errors is fairly straightforward. It is useful to have the default error page write to a log


with details of the request or URL that caused the problem. It can also be useful to log


which files users are requesting that are resulting in 404s, and ideally to have the 404


error page automatically redirect users to new locations of old resources.


Note, however, that these error pages handle requests only for resources that the


ASP.NET engine is registered to handle. So a request for a missing .ASPX file would


result in the 404 page being called, but by default a request for a nonexistent .HTM or


.GIF file would not. Additional file types can be associated with the ASP.NET process in


IIS, but this imposes a performance penalty. Note that most of this functionality is also


available within IIS.

Configuring Application Debugging

The web.config file includes a


<compilation ...> section that sets whether debug


mode is set for an ASP.NET application. A typical compilation section follows:


<compilation


defaultLanguage="vb"


debug="true"


/>


Setting debug="true" (which is case-sensitive) enables debug mode for your application.


This means the .PDB file for your assembly will be copied to the application's /bin


folder, which means detailed debug information (stack trace, line numbers, and so on)


will be provided in response to exceptions. Note that there is a significant performance


penalty to application running in debug mode. Individual pages can also be set up to run


in debug mode by setting debug="true" in the individual page directive.

Configuring Application Tracing

The web.config file includes a


<trace ...> section that is used to set up tracing options


for an ASP.NET application. A typical trace section follows:


<trace


enabled="false"


requestLimit="10"


pageOutput="false"


traceMode="SortByTime"


localOnly="true"


/>


This example demonstrates all of the fields available to modify application tracing.The


first field controls whether tracing is enabled.This defaults to false and can be overridden


at the individual page level.The second item, requestLimit, controls how many


requests' trace results should be stored on the server. Once filled, this queue will not


accept new entries until the queue is deleted (which can be done from the trace.axd


page).The third attribute, pageOutput, controls whether trace output should be displayed


on every page in the application.When set to false, trace output is available only from


the trace.axd URL (for example, http://mydomain/myapplication/trace.axd).


Individual pages can override this setting by explicitly setting trace="true" or


trace="false" in their page directive.


The fourth attribute, traceMode, simply controls the ordering of the trace messages in


the Trace Information section of the trace output.The allowable options are SortByTime


(the default) and SortByCategory. Finally, the last attribute, localOnly, enables application


tracing only for requests originating from the local machine when set to true. Note


that these items are case-sensitive.


Comments


Tracing can provide a powerful way to debug applications. By using the trace.axd URL


for trace output, developers can pull important details about a production ASP.NET


application without interfering with current users. However, be careful that you do not


place sensitive information in trace statements or collections that are exposed by the


trace output (Application, Session, Forms, Cookies, QueryString, and so on), because by


default anybody can access the trace.axd URL and access this data. Note that you can


change the name of the trace.axd file by changing its name in the machine.config file.

Archives

Variety in the Web World