Subscribe

RSS Feed (xml)

Change the Permissions Given to ASP.NET Code

ASP.NET code doesn't run under the IIS authenticated user or the anonymous IUSR_[ServerName] account. Part of the reason is that this account usually won't have sufficient privileges for ASP.NET code, which needs to be able to create and delete temporary files to manage the Web page compilation process.


By default, ASP.NET pages run using the local ASPNET account, which has a carefully limited set of privileges. If you need your ASP.NET code to perform something that is not allowed by default for the local account (writing to the server hard drive or the event log, for example), you can explicitly grant these rights to the ASPNET process. You can also change the setting by editing the machine.config file and modifying the <processModel> tag. You can set the userName and password attributes to any arbitrary user, or you can make use of the built-in local ASPNET process (set userName to Machine and password to AutoGenerate) or local system account (set userName to System and password to AutoGenerate). Because the local system has full rights to the computer, using this account is never recommended except for testing purposes. The ASP.NET account settings are global, and all Web applications will share the account that you specify.


You can also change the account used to execute certain applications or specific code by using impersonation. For example, to configure a single Web application to run under a different user account, add the <identity> tag to the Web.config file, as shown here:




<configuration>
<system.web>
<!-- Other settings omitted. -->

<identity impersonate="true" name="domain\user" password="pwd"/>

</system.web>
</configuration>

You can also instruct the Web application to use the identity that was authenticated by IIS, which will be the anonymous IUSR_[ServerName] account if you aren't using Windows authentication. Simply add the <identity> tag without supplying any user credentials:



<identity impersonate="true"/>

Remember, for this type of impersonation to work, the user account will require read/write access to the Temporary ASP.NET Files directory where the compiled ASP.NET files are stored. This directory is located under the path C:\[WindowsDirectory]\Microsoft.NET\Framework\[version]\Temporary ASP.NET Files.


Finally, you can also use impersonation programmatically, to change the account used to execute a particular section of code. The following code snippet shows a brief example that works in conjunction with Windows authentication. Provided IIS has authenticated the user, that user identity will be assumed when the WindowsIdentity.Impersonate method is used. To use this code, you must import the System.Security.Principal namespace.




if (User.GetType() == typeof(WindowsPrincipal)) {

WindowsIdentity id = (WindowsIdentity)User.Identity;
WindowsImpersonationContext impersonate = id.Impersonate();

// (Now perform tasks under the impersonated ID.)

// Revert to the original ID as shown below.
impersonate.Undo();
} else {

// User is not Windows authenticated.
// Throw an error to or take other steps.
}

ASP.Net Enabling Web Site Debugging

The "unable to start debugging" error signals that Visual Studio .NET was able to compile the Web application but can't execute it in debug mode. Unfortunately, this problem can arise for different reasons, including the following:




  • IIS, the Windows component that hosts Web applications, is not installed or is installed incorrectly.




  • The user running Visual Studio .NET is not a member of the Debugger Users group for the Web server.




  • The user running Visual Studio .NET doesn't have permissions to debug the ASP.NET process. For example, if the ASP.NET process is running under the local system account, the user must have Administrator privileges to debug it.




  • The Web server is running a version of Windows that doesn't support debugging, such as Microsoft Windows NT and Windows XP Home Edition. (Windows 2000, Windows XP Professional, Windows XP Server, and Windows Server 2003 all support debugging.)




  • The Web application doesn't have a Web.config file, or the Web.config file doesn't enable debugging.




  • You're running Visual Studio .NET, and you haven't enabled Integrated Windows authentication for the virtual directory.




The first step that you should take when diagnosing why you can't debug a Web application is to check that IIS is installed on the Web server. To do so, open http://localhost/localstart.asp in your browser. (localhost is an alias for the current computer.) If the test page doesn't appear, IIS is not installed or is not enabled. You can also attempt to start your Web application without debugging by selecting Debug | Start Without Debugging from the Visual Studio .NET main menu. If this test is successful, IIS is correctly installed.


If you installed IIS after you installed Visual Studio .NET or the .NET Framework, you might need to "repair" the .NET Framework by using the original setup CD or DVD. To start this process, type the following command at the command line (or in the Run window), using the Visual Studio .NET DVD. (It's split into two lines below because of page constraints, but it should be entered on a single line.)



<DVD Drive>:\wcu\dotNetFramework\dotnetfx.exe /t:c:\temp
/c:"msiexec.exe /fvecms c:\temp\netfx.msi"

If you're using the CD version of Visual Studio .NET, use the following command line with the Windows Component Update disc:



<CD Drive>:\dotNetFramework\dotnetfx.exe /t:c:\temp
/c:"msiexec.exe /fvecms c:\temp\netfx.msi"

If IIS is properly installed, the next step is to validate your Web application's Web.config file. The Web.config file should follow the structure shown here:



<configuration>
<system.web>
<compilation defaultLanguage="c#"
debug="true" >

<!-- Other settings omitted. -->

</system.web>
</configuration>

By default, Visual Studio .NET adds the compilation tag to the automatically generated Web.config file with the debug attribute set to true.


The next step is to verify the IIS configuration. Problems will occur if you fail to create the required virtual application directory or if you try to run a Web application after you've removed or modified the virtual directory. To correct these problems, modify the virtual directory settings in IIS Manager by selecting Control Panel | Administrative Tools | Internet Information Services from the Start menu. Verify that the virtual application directory exists and that it's configured as a Web application. (You can see virtual directory settings by right- clicking the directory and choosing Properties.) For example, in the screen shot shown in the below figure, the virtual directory exists but is not configured as a Web application. To resolve this problem, you simply need to click the Create button in the Application Settings section.


ff.JPG


One other IIS configuration problem that can occur in Visual Studio .NET is a failure to authenticate. Visual Studio .NET attempts to access the local Web server using Integrated Windows authentication, even if you have anonymous authentication enabled for the virtual directory. This means that your virtual directory must allow both anonymous and Integrated Windows authentication. To allow both authentication methods, follow these steps:




  1. In IIS Manager, right-click the virtual directory for your application and choose Properties. (Alternatively, you can configure authentication for all directories if you right-click the Web Sites folder and choose Properties.)




  2. Select the Directory Security tab.




  3. In the Anonymous access and authentication control section, click the Edit button.




  4. In the Authentication Methods dialog box, under Authenticated access, select Integrated Windows authentication, as shown in below figure.




  5. Click OK to apply your changes.




fig.JPG

ASP.NET Web Service Creation

To illustrate creating a Web service, this simple example takes a string and returns a


message.To do this, you type in the following code and save it as code01vb.asmx


<%@ WebService Language="vb" Class="codevb" %>


Imports System.Web.Services


Imports System.Text


Public Class code01vb


<WebMethod()> _


Public Function GreetCustomer(ByVal person as String) As String


Dim output As StringBuilder = New StringBuilder()


output.Append("Welcome to Cook Center Mr/Mrs.")


output.Append(Person)


output.Append(" , Hope you are enjoying our examples!!" )


GreetCustomer = output.ToString()


End Function


End Class


Now, you save this file in some Web directory.This is all that is required to create a Web


service! To see how it works, open the file in a Web browser. Microsoft provides a default


test page feature in the .NET Framework for its Web services. In that page, you will see


a GreetCustomer function. Click it, and it will take you to another page.There, you


enter some text and press Invoke. A new window opens with the output in XML


format.



In this class, you create a Web method called GreetCustomer. By adding the <WebMethod()> attribute to a method


within a .ASMX file, you create a Web service. Here, the Key attribute is <WebMethod>.


This WebMethod attribute indicates to the .NET Framework that the specified method


should be made accessible via standard Internet protocols.These Web service methods


should be defined as public, which indicates that they can be accessible from outside


parent class.This Web method has various attributes. This example uses the description


attribute.The following properties are defined for the WebMethod attribute:




  • BufferResponse-Specifies whether the response for this Web method should be buffered. By default, it is set to True.



  • CacheDuration-This specifies the number of seconds the Web method response is stored in cache.



  • Description-Specifies the user-friendly description of the publicWeb method.



  • EnableSession-Specifies whether session state is enabled for the Web method. Default setting is false.



  • MessageName-Specifies an alias name for a Web method.This MessageName attribute allows you to provide different names for overloaded methods.



  • TransactionOption-Specifies the Enterprise service transaction support for the Web method.


ASP.NET Stack Collection

First, you create a new object of type


System.Collections.Stack called myStack .You


then add items to the stack by using the Push method and passing in the object you



want to add to the top of the stack.You can then retrieve items from the top of the stack .


(remember a stack is last-in-first-out, or LIFO) by using the Pop method.The item is


returned as type of object, so if you need to convert it into a string, as in the following


example, you simply call the ToString() method. Otherwise, you'll need to cast it to


the type of object that you need.


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


'Make sure System.Collections is imported


Sub Page_Load(sender As Object, e As EventArgs)


Dim myStack As New Stack()


myStack.Push("One")


myStack.Push("Two")


myStack.Push("Three")


While myStack.Count > 0


Response.Write(myStack.Pop().ToString() & "<br>")


End While


End Sub


For more info see:


Stack class-http://msdn.microsoft.com/library/en-us/cpref/html/


frlrfSystemCollectionsStackClassTopic.asp

ASP.NET Queue Collection

Create a new object of type


System.Collections.Queue called myQueue. Add items to


the queue by using the EnQueue method and passing in the object you want to add to


the queue.You can then retrieve items from the front of the queue (remember a queue


is first-in-first-out, or FIFO) by using the DeQueue method.The item is returned as type


of object, so if you need to convert it into a string as in the following example, you simply


call the ToString() method. Otherwise, you'll need to cast it to the type of object


that you need.


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


'Make sure System.Collections is imported


Sub Page_Load(sender As Object, e As EventArgs)


Dim myQueue As New Queue()


myQueue.Enqueue("One")


myQueue.Enqueue("Two")


myQueue.Enqueue("Three")


While myQueue.Count > 0


Response.Write(myQueue.Dequeue().ToString() & "<br>")


End While


End Sub

ASP.NETHashTable Collection

You create a new object of type


System.Collections.HashTable called myHash.


Then, you add keys to the hash table by using the add method and passing in the


name and value of each key.You can then retrieve the values of each key by using


myHash("KeyName").The value is returned as type of object, so if you need to convert it


into a string, as in the following example, you simply call the ToString() method.


Otherwise, you'll need to cast it to the type of object that you need.


The ASPX page is as follows:


<%@Import namespace="System.Collections"%>


<%@Import namespace="System.Drawing"%>


<HTML>


<body>


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


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


</form>


</body>


</HTML>


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


Sub Page_Load(sender As Object, e As EventArgs)


Dim myHash As New Hashtable()


myHash.Add("Red", "#FF0000")


myHash.Add("Green", "#00FF00")


myHash.Add("Blue", "#0000FF")


MyLabel.BackColor=ColorTranslator.FromHtml(myHash("Blue").ToString())


MyLabel.ForeColor=ColorTranslator.FromHtml(myHash("Red").ToString())


End Sub

ASP.NET Creating Custom Collection

A custom collection class allows the use of the


For Each syntax (foreach in C#) to


loop through a set of custom typed items.The custom collection class must internally


keep references to the items with an array or other type of collection (ArrayList,


HashTable).The .NET Framework then requires the following two interfaces to be


implemented in order to support the For Each syntax:




  • System.Collections.IEnumerable



  • Function GetEnumerator() As IEnumerator



  • System.Collections.IEnumerator



  • Sub Reset()



  • Function MoveNext() As Boolean



  • ReadOnly Property Current As Object



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


Sub Page_Load()


Dim _customCollection As CustomCollection


Dim _customItem As CustomItem


Dim _index As Integer


_customCollection = New CustomCollection(10)


For Each _customItem In _customCollection


_index = _customItem.Index


Next


End Sub


Custom Collection defined in CustomCollection.vb


Public Class CustomCollection


Implements IEnumerable, IEnumerator


Private customItems() As CustomItem


Private currentIndex As Integer = -1


Public Sub New(ByVal Count As Integer)


Dim index As Integer


ReDim customItems(Count - 1)


For index = 0 To Count - 1


customItems(index) = New CustomItem(index)


Next


End Sub


#Region "Implementation of IEnumerable"


Public Function GetEnumerator() As Ienumerator


Implements IEnumerable.GetEnumerator


Return CType(Me, IEnumerator)


End Function


#End Region


#Region "Implementation of IEnumerator"


Public Sub Reset() Implements IEnumerator.Reset


currentIndex = -1


End Sub


Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext


If currentIndex < customItems.Length - 1 Then


currentIndex = currentIndex + 1


Return True


Else


Return False


End If


End Function


Public ReadOnly Property Current() As Object


Implements IEnumerator.Current


Get


Return customItems(currentIndex)


End Get


End Property


#End Region


End Class


Custom Item defined in CustomItem.vb


Public Class CustomItem


Private _index As Integer


Public ReadOnly Property Index() As Integer


Get


Return _index


End Get


End Property


Public Sub New(ByVal Index As Integer)


_index = Index


End Sub


End Class



This implementation uses a simple array of the CustomItem type and offers nothing


beyond the For Each support. It can be easily extended to support additional array or


ArrayList methods, such as Count/Length and Item.The base collection type can also


be changed to ArrayList or HashTable for further functionality.


This implementation of the CustomItem type is no more than a contrived example


with a single property of Index. It should be extended to include the various properties



and methods relevant to the actual custom item.The construction of the item, or set of




items, can also come from an external data store.

How to Declare Collections in ASP.NET

The .NET Framework includes a number of commonly used collections.They are found in the


System.Collections namespace, and can hold any object type, which means they


can hold any type, because in .NET, all types inherit from object.This example demonstrates


this using a simple array list.


Sub Page_Load (Sender As Object, E As EventArgs)


Dim al As New ArrayList(5)


al.Add("one")


al.Add(2)


al.Add(False)


al.Add(New System.Object())



Response.Write("Successfully added " & al.Count & _




" different types of objects to an ArrayList.")


End Sub



Declaring and using collections in .NET is very straightforward. Later in this chapter,


you'll learn how to use some of the different collections included in the framework, as


well as how to create your own strongly typed collections.

Load User Controls Programmatically

User controls are self-contained groups of controls. Like Web forms, user controls consist of a layout portion that defines the contained controls (.ascx file) and a code-behind portion with the event-handling logic (.cs file). User controls allow you to reuse common interface elements on multiple pages and build complex interfaces out of smaller building blocks. One useful characteristic of user controls is that they can be loaded programmatically, which allows you to create a highly configurable interface that you can tailor dynamically according to the user. You simply load the control, configure its properties, and then add it to another container control.


The basic solution could be implemented in a more object-oriented way by creating a custom user control that encapsulates the dynamic graphic. The user control could allow the page to set the text, font, colors, and so on through various properties. Here's an example of what the custom control would look like:




using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;

public class DynamicGraphicControl : System.Web.UI.UserControl {

// (Designer code omitted.)

private string imageText = "";
public string ImageText {
get {
return imageText;
}
set {
imageText = value;
}
}

private Font textFont;
public Font TextFont {
get {
return textFont;
}
set {
textFont = value;
}
}

private Size imageSize;
public Size ImageSize {
get {
return imageSize;
}
set {
imageSize = value;
}
}

private Color foreColor;
public Color ForeColor {
get {
return foreColor;
}
set {
foreColor = value;
}
}

private Color backColor;
public Color BackColor {
get {
return backColor;
}
set {
backColor = value;
}
}

private Color borderColor;
public Color BorderColor {
get {
return borderColor;
}
set {
borderColor = value;
}
}

private void Page_Load(object sender, System.EventArgs e) {

if (ImageText == "")
return;

// Create an in-memory bitmap where you will draw the image.
Bitmap bitmap = new Bitmap(ImageSize.Width, ImageSize.Height);

// Get the graphics context for the bitmap.
Graphics graphics = Graphics.FromImage(bitmap);

// Set the background color and rendering quality.
// This color will become the border
graphics.Clear(BorderColor);
graphics.SmoothingMode = SmoothingMode.AntiAlias;

// Paint a rectangle.
graphics.FillRectangle(new SolidBrush(BackColor), 5, 5,
ImageSize.Width - 10, ImageSize.Height - 10);

// Set the alignment for the text.
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;

// Paint the text.
graphics.DrawString(ImageText, TextFont, new SolidBrush(ForeColor),
new Rectangle(0, 0, ImageSize.Width, ImageSize.Height),
stringFormat);

// Render the image to the HTML output stream.
bitmap.Save(Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Gif);

graphics.Dispose();
bitmap.Dispose();
}
}

The Web form loads this user control in the Page.Load event handler. The user control is placed in a Panel control container. The LoadControl method returns a generic Control object, which the code casts to the appropriate user control class.




using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Drawing;

public class DynamicControlTest : System.Web.UI.Page {

protected System.Web.UI.WebControls.Panel pnl;

// (Designer code omitted.)

private void Page_Load(object sender, System.EventArgs e) {

// Load the control.
DynamicGraphicControl ctrl;
ctrl = (DynamicGraphicControl)
Page.LoadControl("DynamicGraphicControl.ascx");

// Configure the control properties.
ctrl.ImageText = "This is a new banner test";
ctrl.ImageSize = new Size(300, 200);
ctrl.TextFont = new Font("Verdana", 24, FontStyle.Bold);
ctrl.BackColor = Color.Olive;
ctrl.ForeColor = Color.LightYellow;
ctrl.BorderColor = Color.OrangeRed;

// Add the control to the page.
pnl.Controls.Add(ctrl);
}
}

In Visual Studio .NET, the user control class is always available because classes are compiled into a single .dll assembly. If the user control is not a part of the project, however, you won't have the required user control class and you won't be able to access any of the user control's properties or methods. To remedy this problem, you can define a base class or an interface that defines the basic functionality you need to be able to access in any of your custom user controls.




Technorati :

Dynamically Render an Image

You can draw dynamic graphics using the same GDI+ code in a Web application that you'd use in a Windows-based application. The only difference is how you render the final graphic. There are basically two approaches that you can use.




  • You can stream the binary contents of the image directly to the OutputStream property of the HttpResponse object. This is a good approach if you need to generate a wide range of images and don't want to clutter the server hard drive with image files that won't be used again. It's also the best choice if you need to create dynamic images that are tailored to match user input.




  • You can save the image to the Web server's file system and use an HTML <img> tag to display the created image. This is a good choice if you need to create a graphic that will be reused because it will avoid the overhead of continuously re-creating the graphic.




This post explores both approaches. First we'll consider how to dynamically create an image without saving it to a file. In this example, the goal is to create a simple banner


You'll notice that the only user-supplied value in this example is the banner text itself, which is supplied through the query string. The font, colors, and dimensions are hard-coded (although they could easily be set based on other query string parameters or Web.config defaults).


Here's the full page code:




using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;

public class DynamicGraphic : System.Web.UI.Page {

// (Designer code omitted.)

private void Page_Load(object sender, System.EventArgs e) {

// Get the text from the query string.
// If no text is supplied, choose a default.
string text = "";
if (Request.QueryString["image"] == null) {

Response.Redirect(Request.Url + "?image=" +
Server.UrlEncode("This is a test image"));
}
else {
text = Server.UrlDecode(Request.QueryString["image"]);
}

// Create an in-memory bitmap where you will draw the image.
// The Bitmap is 300 pixels wide and 200 pixels high.
int width = 300, height = 200;
Bitmap bitmap = new Bitmap(width, height);

// Get the graphics context for the bitmap.
Graphics graphics = Graphics.FromImage(bitmap);

// Set the background color and rendering quality.
// This color will become the border
graphics.Clear(Color.OrangeRed);
graphics.SmoothingMode = SmoothingMode.AntiAlias;

// Paint a rectangle.
graphics.FillRectangle(new SolidBrush(Color.Olive), 5, 5,
width - 10, height - 10);

// Choose a font and alignment for the text.
Font fontBanner = new Font("Verdana", 24, FontStyle.Bold);
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;

// Paint the text.
graphics.DrawString(text, fontBanner, new
SolidBrush(Color.LightYellow), new Rectangle(0, 0, width, height),
stringFormat);

// Render the image to the HTML output stream.
bitmap.Save(Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Gif);

graphics.Dispose();
bitmap.Dispose();
}
}
}

When you save an image to the response stream, you replace any other output. Therefore, you can't use this technique with a page that also includes Web controls or static HTML content. Thus, if you want to use a page that combines dynamically generated images and Web controls, you need to wrap the dynamically generated image in a control or write the image to the hard drive before displaying it.


If you want to save the file to the hard drive, you move the image generation code into a separate method, which we'll call GenerateBanner. Then, in the Page.Load event handler, you begin by checking to see whether the file already exists by using the static File.Exists method. If the file doesn't exist, you generate it in memory by calling GenerateBanner and save it using the Bitmap.Save method. Otherwise, you simply load the image directly.


The following code shows the basic approach you must take:




using System;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;

public class DynamicGraphic : System.Web.UI.Page {

protected System.Web.UI.WebControls.Image imageControl;

// (Designer code omitted.)

private Bitmap GenerateBanner() {

// Create the image using the same code as in the previous example.
// (Code omitted.)
}

private void Page_Load(object sender, System.EventArgs e) {

// Set the filename based on the image text.
// We assume this only includes characters that are
// legal for a filename.
string fileName = Request.QueryString["image"] + ".gif";

Bitmap bitmap = null;

// Check if an image with this text already exists.
if (File.Exists(fileName)) {

// Load the existing image.
try {
bitmap = new Bitmap(fileName);
}catch {
bitmap = GenerateBanner();
}
}
else {
bitmap = GenerateBanner();

// Save the image.
bitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Gif);
}

// Display the image by setting an Image property.
imageControl.ImageUrl = fileName;
}
}



Technorati :

Add Controls to Web Form Dynamically

You can use a technique to add Web controls to a Web page that's similar to the way you would add Windows controls to a form, but there are some differences, including the following:




  • Dynamically added controls will exist only until the next postback. If you need them, you must re-create them when the page is returned. This requirement doesn't prevent you from writing code that handles their events, however.




  • Dynamically added controls aren't as easy to position. Typically, you'll use literal controls containing HTML code (such as the line break <br>) to separate more than one dynamically created control.




  • Dynamically created controls should be placed in a container control (such as a Panel or a LiteralControl) rather than directly on the page itself, which makes it easier to position them.




  • If you want to interact with the control later, you should give it a unique ID. You can use this ID to retrieve the control from the Controls collection of its container.




The best place to generate new controls is in the Page.Load event handler, which ensures that the control will be created each time the page is served. In addition, if you're adding an input control that uses view state, the view state information will be restored to the control after the Page.Load event fires. That means a dynamically generated text box will retain its text over multiple postbacks, just like a text box that's defined in the .aspx file. Similarly, because the Page.Load event always fires before any other events take place, you can re- create a control that raises server-side events and its event-handling code will be triggered immediately after the Page.Load event. For example, this technique allows you to dynamically generate a button that can respond to user clicks.


The following example demonstrates all these concepts. It generates three dynamic server controls (two buttons and a text box) and positions them using literal controls that act as separators. The buttons are connected to distinct event handlers. The text box is given a unique identifier so that its text can be retrieved later, in response to the button clicks.


The full code is shown here:




using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public class DynamicControls : System.Web.UI.Page {

protected System.Web.UI.WebControls.Label lblMessage;
protected System.Web.UI.WebControls.Panel pnl;

// (Designer code omitted.)

private void Page_Load(object sender, System.EventArgs e) {

// Create a dynamic button.
Button dynamicButton = new Button();
dynamicButton.Text = "Dynamic Button A";

// Connect an event handler.
dynamicButton.Click += new EventHandler(cmdDynamicA_Click);

// Add the button to a Panel.
pnl.Controls.Add(dynamicButton);

// Add a line break separator.
pnl.Controls.Add(new LiteralControl("<br>"));

// Create a second dynamic button.
dynamicButton = new Button();
dynamicButton.Text = "Dynamic Button B";
dynamicButton.Click += new EventHandler(cmdDynamicB_Click);
pnl.Controls.Add(dynamicButton);

// Add a line break separator.
pnl.Controls.Add(new LiteralControl("<br><br>"));

// Create a dynamic textbox.
TextBox dynamicText = new TextBox();
pnl.Controls.Add(dynamicText);

// Assign a unique ID so the textbox can be retrieved
// from the control collection later.
dynamicText.ID = "DynamicText";
}

private void cmdDynamicA_Click(object sender, System.EventArgs e) {

lblMessage.Text = "Clicked A";
GetText();
}

private void cmdDynamicB_Click(object sender, System.EventArgs e) {

lblMessage.Text = "Clicked B";
GetText();
}

private void GetText(){
lblMessage.Text += "<br><br>";

foreach (Control ctrl in pnl.Controls){
if (ctrl.ID == "DynamicText"){
lblMessage.Text += "TextBox contains: " +
((TextBox)ctrl).Text;
}
}
}
}

If you need to dynamically create complex layouts that include some prebuilt control "groups," you might prefer to use user controls and load them dynamically into a page.




Technorati :

Perform Selective Input Validation

The ASP.NET validation controls are an ideal solution for quickly validating forms. They work well as long as you want to validate an entire page at a time. If you want to validate only part of a form, or you want to make a programmatic decision about whether to validate a control (perhaps based on the validation success or value of another control), you'll need to use selective validation.


The first step in selective validation is to disable the EnableClientScript property of every validation control on your page. Otherwise, validation will be performed at the client through JavaScript, the page won't be posted back if it contains invalid values, and your event handling code won't be executed. Once you've made this change, you can validate the page one control at a time using the BaseValidator.Validate method, or you can validate the entire page using the Page.Validate method.


The following example uses server-side validation with two validators: a RangeValidator and a RegularExpressionValidator (which validates an e-mail address). If validation fails, the code steps through the collection of validators on the form using the Page.Validators property. Every time the code finds a failed validator, it finds the corresponding control using the Page.FindControl method and then displays the offending value (a trick that's not possible with automatic validation).




using System;
using System.Web;
using System.Web.UI.WebControls;

public class SelectiveValidation : System.Web.UI.Page {

protected System.Web.UI.WebControls.TextBox txtNumber;
protected System.Web.UI.WebControls.TextBox txtEmail;
protected System.Web.UI.WebControls.Label lblCustomSummary;
protected System.Web.UI.WebControls.RegularExpressionValidator
validatorEmail;
protected System.Web.UI.WebControls.RangeValidator validatorNumber;
protected System.Web.UI.WebControls.Button cmdValidate;

// (Designer code omitted.)

private void cmdValidate_Click(object sender, System.EventArgs e) {

// Validate the page.
this.Validate();

if (!Page.IsValid) {

lblCustomSummary.Text = "";
foreach (BaseValidator validator in this.Validators) {

if (!validator.IsValid) {

TextBox invalidControl = (TextBox)
this.FindControl(validator.ControlToValidate);

lblCustomSummary.Text +=
"The page contains the following error: <b>" +
validator.ErrorMessage + "</b>.<br>" +
"The invalid input is: <b>" +
invalidControl.Text + "</b>." + "<br><br>";
}
}

}else {
lblCustomSummary.Text = "Validation succeeded.";
}
}
}

Use Forms Authentication

To prevent users from accessing certain pages unless they have first authenticated themselves with a custom logon page.

Forms authentication is a flexible security model that allows you to prevent unauthenticated users from accessing certain pages. You write the code that performs the authentication, and ASP.NET issues a cookie to authenticated users. Users without the cookie are redirected to a login page when they try to access a secured page.

To implement forms authentication, you must take the following steps:


  • Configure forms authentication using the <authentication> tag in the application's Web.config file.



  • Restrict anonymous users from a specific page or directory using Web.config settings.



  • Create the logon page, and add your authentication logic, which leverages the FormsAuthentication class from the System.Web.Security namespace.
The first step is to configure the Web.config in the root application directory to enable forms authentication, as shown in the following code. You also need to specify your custom login page (where unauthenticated users will be redirected) and a time-out after which the cookie will be removed. The authentication cookie is automatically renewed with each Web request.









<authentication mode="Forms">
<forms loginUrl="login.aspx" timeout="30" />
</authentication>




Next you need to add an authorization rule denying anonymous users. The easiest way to secure pages is to create a subdirectory with its own Web.config file. The Web.config file should refuse access to anonymous users, as shown here:

  


<authorization>
<deny users="?" />
</authorization>





Now ASP.NET will automatically forward unauthenticated requests for pages in this subdirectory to the custom logon page.

Another option is to specifically deny access to specific pages in the current directory by using the <location> tag:

  




<location path="SecurePage.aspx">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>



You can also deny specific users by entering a comma-separated list of user names instead of the wildcard (?) character, which simply means "all anonymous users."

You need to create the logon page. Your logon page can authenticate the user using a hard-coded password (suitable for simple tests), a server-side database, or any other type of custom authentication logic. Once the user has been successfully authenticated, call the static FormsAuthentication.RedirectFromLoginPage method with the username. This method simultaneously sets the forms authentication cookie and redirects the user to the originally requested page.

Here's a rudimentary logon page that simply checks for a specific password when the user clicks a logon button:


using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.Security;

public class LoginPage : System.Web.UI.Page {

protected System.Web.UI.WebControls.Label lblStatus;
protected System.Web.UI.WebControls.Button cmdLogin;
protected System.Web.UI.WebControls.TextBox txtPassword;
protected System.Web.UI.WebControls.TextBox txtName;

// (Designer code omitted.)

private void cmdLogin_Click(object sender, System.EventArgs e){
if (txtPassword.Text.ToLower() == "secret") {
FormsAuthentication.RedirectFromLoginPage(txtName.Text, false);

}else {
lblStatus.Text = "Try again.";
}
}
}

To test this page with the sample code that accompanies the book, request SecurePage.aspx, which is placed in a secured directory. You'll be redirected to login.aspx, and provided you submit the correct password, you'll be returned to SecurePage.aspx.



Technorati :

Using IIS Authentication

To prevent users from accessing certain pages unless they have been authenticated against a Windows user account on the server.

IIS and ASP.NET use a layered security model. When a user requests an ASP.NET Web page over HTTP, the following steps take place:

  1. IIS attempts to authenticate the user. If anonymous access is enabled, IIS automatically logs the user on as the anonymous user (typically the IUSR_[ServerName] account). Otherwise, it requests authentication credentials that it will use to log the user on with another Windows account.

  2. Provided IIS can authenticate the user successfully, it passes the request to ASP.NET with information about the authenticated user. ASP.NET can then use its own security services based on the settings in the Web.config file (for example, denying specific users or groups access to certain pages or directories). In addition, your code can restrict actions programmatically by checking the user information.


  3. If the ASP.NET code accesses any system resources (for example, tries to open a file or connect to a database), the Windows operating system performs its own security checks. Usually, the ASP.NET application code won't actually run under the account of the authenticated user. Thus, these security checks are made against the ASP.NET process account (which is configured using the machine.config file).

The first step to use IIS authentication is to disable anonymous access for the virtual directory. To do so, start IIS Manager (select Settings | Control Panel | Administrative Tools | Internet Information Services from the Start Menu). Then right-click a virtual directory or a subdirectory inside a virtual directory, and choose Properties. Select the Directory Security tab, as shown in below figure.

figure1.JPG

Next, click the Edit button to modify the directory security settings. The window shown below figure will appear. In the bottom half of the window, you can enable one of the Windows authentication methods. However, none of these methods will be used unless you explicitly clear the Anonymous Access check box.

figure2.JPG

You can enable more than one authentication method, in which case the client will use the strongest supported method. If anonymous access is enabled, it's always used. The different authentication methods are described in Table 7. 2.
Table 7.2: Types of Authentication

Mode

Description

Anonymous

The client is not required to submit any information. Users are logged in using the preset anonymous account (typically IUSR_[ServerName]).

Basic

Basic authentication is a part of the HTTP 1.0 standard, and it is supported by almost all browsers and Web servers. When using basic authentication, the browser presents the user with a login box with a user name and password field. This information is then transmitted to IIS, where it is matched with a local Windows user account. Basic authentication should always be combined with SSL because it doesn't encrypt the logon information before transmitting it.

Digest

Digest authentication sends a digest (also known as a cryptographic hash) over the network. Thus, it's much more secure than Basic authentication because intercepted logon information can't be reused. The primary disadvantage is that Digest authentication is supported only by Internet Explorer 5.0 and later versions. Also, your Web server needs to use Active Directory or have access to an Active Directory server.

Integrated

Integrated Windows authentication is the best choice for most intranet scenarios. When using integrated authentication, Internet Explorer sends the logon token for the current user automatically, provided it is on a trusted domain. Integrated authentication is supported only on Internet Explorer 2.0 and later and can't work over proxy servers.

Once you've enabled the appropriate virtual directory security settings, you should make sure that the Web.config file is set to use Windows authentication. In a Visual Studio .NET project, this is the default setting.

<configuration>
<system.web>
<!-- Other settings omitted. -->
<authentication mode="Windows" />
</system.web>
</configuration>

At this point, your virtual directory will require user authentication and your Web application will be able to retrieve the user information. In addition, you can add authorization rules that prevent certain users or groups from accessing Web pages or subdirectories. You do this by adding <allow> and <deny> tags to the <authorization> section of the Web.config file. For example, you can create a subdirectory with the following Web.config file contents:

<configuration>
<system.web>

<authorization>
<deny roles="Guest,Associate" />
<allow users="matthew" />
<deny users="*" />
</authorization>

</system.web>
</configuration>

ASP.NET examines rules in the order they appear and stops when it finds a match. In this example, users in the Guest or Associate groups will automatically be denied. The user matthew will be permitted (unless he's a member of one of the previously forbidden groups). All other users will be denied. In this case, these are local groups and user accounts. If you want to refer to a domain account, use the pathlike syntax [DomainName]\[UserName] instead.

Notice that in this example, the Web.config file doesn't contain an <authentication> section. This omission is because the authentication is configured in the Web.config file in the Web application directory. Subdirectories can set their own authorization rules, but they can't change the mode of authentication.

Another option is to deny access to specific pages using the <location> attribute:

<configuration>  
<system.web>
<!-- Other settings omitted. -->
</system.web>

<location path="SecurePage.aspx">
<system.web>
<authorization>
<deny roles="Guest" />
</authorization>
</system.web>
</location>

</configuration>

Finally, you can write your own authorization logic by examining the user identity in your Web page code using the Page.User property, which provides a WindowsPrincipal object. You can retrieve the user name from the WindowsPrincipal.Identity.Name property, and you can test group membership using the WindowsPrincipal.IsInRole method. The following Web page code demonstrates these techniques:


using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.Security.Principal;

public class WindowsSecurityTest : System.Web.UI.Page {

protected System.Web.UI.WebControls.Label lblMessage;

// (Designer code omitted.)

private void Page_Load(object sender, System.EventArgs e) {

// Get the IIS-authenticated identity.
WindowsIdentity identity = (WindowsIdentity)User.Identity;

// Test if it is an Administrator.
bool isAdmin = User.IsInRole(@"BUILTIN\Administrators");

// Display some information about the identity.
lblMessage.Text = "You have reached the secured page, " +
User.Identity.Name + "." +
"<br><br>Authentication Type: " +
identity.AuthenticationType.ToString() +
"<br>Anonymous: " + identity.IsAnonymous.ToString() +
"<br>Authenticated: " + identity.IsAuthenticated.ToString() +
"<br>Guest: " + identity.IsGuest.ToString() +
"<br>System: " + identity.IsSystem.ToString() +
"<br>Administrator: " + isAdmin.ToString();
}
}

Technorati :

Allow User to Upload File

Because ASP.NET executes on the server, there is no way to access any of the resources on the client computer, including files. However, you can use the System.Web.UI.HtmlControls.HtmlInputFile control to allow a user to upload a file. This control renders itself as the HTML <input type="file"> element, which is displayed as a Browse button and a text box that contains a filename. The user clicks the Browse button and chooses a file. This step takes place automatically and doesn't require any custom code. The user must then click another button (which you must create) to start the actual upload process.


Before you can create a working file upload page, you need to take these steps:




  • You must set the encoding type of the form to multipart/form-data. To make this change, find the <form> tag in your .aspx file and modify it as shown here:




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




  • You need to add the HtmlInputFile control. In Microsoft Visual Studio .NET, you'll find this control under the HTML tab of the Toolbox, with the name File Field. Once you've added this control, you must right-click it and choose Run As Server Control, which creates the required <input type="file" runat="server"> tag.




  • You must add another button that actually starts the file transfer using the specified file by calling the HtmlInputFile.PostedFile.SaveAs method.




Figure 7.3 shows a sample page that allows file uploading. It includes an HtmlInputFile control and uses the following code:




using System;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;

public class UploadPage : System.Web.UI.Page {

protected System.Web.UI.WebControls.Label lblInfo;
protected System.Web.UI.WebControls.Button cmdUpload;
protected System.Web.UI.HtmlControls.HtmlInputFile FileInput;

// (Designer code omitted.)

private void cmdUpload_Click(object sender, System.EventArgs e) {

if (FileInput.PostedFile.FileName == "") {

// No file was submitted.
lblInfo.Text = "No file specified.";

}else {

try {

if (FileInput.PostedFile.ContentLength > 1048576) {

// Forbid files larger than one megabyte.
lblInfo.Text = "File is too large.";

}else {

// The saved file will retain its original filename.
string fileName =
Path.GetFileName(FileInput.PostedFile.FileName);

// The ASP.NET process must have rights for the location
// where it is attempting to save the file, or an
// "access denied" exception will occur.
FileInput.PostedFile.SaveAs(fileName);
lblInfo.Text = "File " + fileName + " uploaded.";
}
}catch (Exception err) {

lblInfo.Text = err.Message;
}
}
}
}


asp1.JPG




The code can check various properties of the submitted file, including its size, before saving it, which allows you to prevent a denial of service attack that tricks an ASP.NET application into filling the hard disk with large files. However, this code doesn't prevent a user from submitting the file in the first place, which can still slow down the server and be used to launch a different type of denial of service attack-one that works by tying up all free ASP.NET worker threads. To prevent this type of attack, use the <httpruntime> tag in the Web.config file to specify a maximum file size. Specify the maximum, in kilobytes, using the maxRequestLength attribute.


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>

<httpRuntime maxRequestLength="4096" />
<!-- Other settings omitted. -->

</system.web>
</configuration>




If you don't specify a maximum length, the default value of 4096 (4 megabytes) will apply. If the user attempts to submit a file that's too large, an exception will be thrown immediately when the page is posted back.



Technorati :

Programmatically Set Control Focus

The ASP.NET Web controls don't provide any way to programmatically set control focus. They do provide a TabIndex property that allows you to set the tab order, but this property applies only to Microsoft Internet Explorer and can't be used to programmatically set the focus to the control of your choice. To overcome this limitation, you need to add a little snippet of JavaScript code.


The following subroutine generalizes this task. It accepts a reference to any control object, retrieves the associated client ID (which is the ID that the JavaScript code must use to refer to the control), and then builds and registers the startup script for setting the focus.



private void SetFocus(Control ctrl) {

// Define a JavaScript statement that will move focus to
// the desired control.
string setFocus = "<script language='javascript'>" +
"document.getElementById('" + ctrl.ClientID +
"').focus();</script>";

// Add the JavaScript code to the page.
this.RegisterStartupScript("SetFocus", setFocus);
}

If you add this subroutine to a Web form, you can call SetFocus as needed. Here's an example that sets the focus when the page first loads:




private void Page_Load(object sender,
System.EventArgs e) {

if (!this.IsPostBack) {
// Move to a specific text box the first time the page loads.
SetFocus(TextBox1);
}
}



Technorati :

Pop-Up Window with JavaScript

Because all ASP.NET code executes on the server, there is no way to show a new window from your C# page code. You can add URL hyperlinks to a page that will automatically open in a new window by setting the target attribute of the anchor tag to _blank, but this still doesn't give you the ability to control the window size or style.


The solution is to use client-side JavaScript code to open the secondary window. The secondary window itself could be an HTML page, an ASP.NET page, an image file, or any other type of resource that can be opened in the client's browser. To open a secondary window, you use the window.open function and specify three parameters. The first parameter is the link for the new page, the second is the frame name of the window, and the third is a comma- separated string of attributes that configure the style and size of the pop-up window. These attributes can include the following:




  • The height and width attributes, which are set to pixel values.




  • The toolbar, menuBar, and scrollbars attributes, which can be set to yes or no depending on whether you want to display these elements.




  • The resizable attribute, which can be set to yes or no depending on whether you want a fixed or resizable window border.




The following example shows how you can configure an ASP.NET Button so that it opens a second ASP.NET page in a pop-up window when clicked. Typically, you would add this code to the Page.Load event handler.



string popupScript = "window.open('PopUp.aspx', " +
"'CustomPopUp', " +
"'width=200, height=200, menubar=yes, resizable=no')";

cmdPopUp.Attributes.Add("onClick", popupScript);

Here's the code you would use to show a pop-up window automatically when the page is displayed. This code would also go in the Page.Load event handler.




string popupScript = "<script language='javascript'>" +
"window.open('PopUp.aspx', " +
"'CustomPopUp', " +
"'width=200, height=200, menubar=yes, resizable=no')" +
"</script>";

Page.RegisterStartupScript("PopupScript", popupScript);



Technorati :

Respond to Client-Side Events with JavaScript

ASP.NET includes a rich programming model. Unfortunately, once a page is rendered to HTML, you can't execute any more .NET code without first triggering a postback to the server. This limitation greatly reduces the effectiveness of validation code and other niceties that can support polished interactive Web pages.


Of course, there's no reason that you can't mingle client-side JavaScript functionality with your .NET code. Although .NET doesn't include any object interface for creating JavaScript, you can manually inject it into the page. One way to do this is simply to set a control attribute. For example, you can create a text box that displays a message box when it loses focus by including the following JavaScript code:




TextBox1.Attributes.Add("onBlur", "alert('The text box has lost focus!');");

The TextBox tag will be rendered to HTML like this:



<input name="TextBox1" type="text" id="TextBox1"
onBlur="alert('The text box has lost focus!');" ... />

In this case, you're using the built-in JavaScript alert function and the JavaScript onBlur event, which fires when a control loses focus. Most HTML elements support a small number of events, and some of the most useful include the following:




  • onFocusOccurs when a control receives focus




  • onBlurOccurs when focus leaves a control




  • onClickOccurs when the user clicks a control




  • onChangeOccurs when the user changes the value of certain controls




  • onMouseOverOccurs when the user moves the mouse pointer over a control




Another approach to adding JavaScript code is to define a JavaScript function in a .NET string variable and then to instruct ASP.NET to insert it into the rendered Web form where it can be used. If you follow this approach, any control can call the function in response to a JavaScript event.


The following example demonstrates this technique with a simple Web page that includes a table and an image. As the user moves the mouse over the cells in the table, two custom JavaScript functions are used, one that highlights the current cell and one that removes the highlight from the previous cell. In addition, the highlighting function changes the image URL depending on which table column is currently selected. If the user hovers the mouse over the first column, an animated GIF of a happy face is shown. If the user hovers the mouse over the second or third column, an animated GIF of a book with a flashing question mark is shown instead.




using System;
using System.Web;
using System.Web.UI.WebControls;

public class JavaScriptTest : System.Web.UI.Page {

protected System.Web.UI.WebControls.Table Table1;
protected System.Web.UI.WebControls.Image Image1;

// (Designer code omitted.)

private void Page_Load(object sender, System.EventArgs e) {

// Define the JavaScript functions.
string highlightScript =
"<script language=JavaScript> " +
"function HighlightCell(cell) {" +
"cell.bgColor = '#C0C0C0';" +
"if (cell.cellIndex == 0)"+
"{document.Form1.Image1.src='happy_animation.gif';}"+
"else {document.Form1.Image1.src='question_animation.gif';}" +
";}" +
"</script>";

string unhighlightScript =
"<script language=JavaScript> " +
"function UnHighlightCell(cell) {" +
"cell.bgColor = '#FFFFFF';" +
"}" +
"</script>";

// Insert the function into the page (it will appear just after
// the <form runat=server> tag.
// Note that each script block is associated with a string name.
// This allows multiple controls to register the same script block,
// while ensuring it will only be rendered in the final page once.
if (!this.IsClientScriptBlockRegistered("Highlight")) {
Page.RegisterClientScriptBlock("Highlight", highlightScript);
}

if (!this.IsClientScriptBlockRegistered("UnHighlight")) {
Page.RegisterClientScriptBlock("UnHighlight", unhighlightScript);
}

// Set the attributes of every cell in the table.
foreach (TableRow row in Table1.Rows) {

foreach (TableCell cell in row.Cells) {

cell.Attributes.Add("onMouseOver", "HighlightCell(this);");
cell.Attributes.Add("onMouseOut", "UnHighlightCell(this);");
}
}
}


image.JPG



Technorati :

Creating Stateful Page Member Variables

ASP.NET provides several state mechanisms, as described in previous post. However, none of these can be used automatically-they all require manual code to serialize and retrieve information. You can add a layer of abstraction by performing this serialization and retrieval once. The rest of your code can then interact directly with the member variables.


In order for this approach to work, you need to read variable values at the start of every postback. The Page.Load event is an ideal choice for this code because it always fires before any other control events. You can use a Page.Load event handler to pre-initialize all your variables. In addition, you need to store all variables before the page is sent to the user, after all processing is complete. In this case, you can respond to the Page.PreRender event, which fires after all event handlers, just before the page is converted to HTML and sent to the client.


The following page shows an example of how you might persist one Page member variable (named memberValue).




using System;
using System.Web;
using System.Web.UI.WebControls;

public class StatefulMembers : System.Web.UI.Page {

// (Designer code omitted.)

private int memberValue = 0;

private void Page_Load(object sender, System.EventArgs e) {

// Reload all member variables.
if (ViewState["memberValue"] != null) {
memberValue = (int)ViewState["memberValue"];
}
}

private void StatefulMembers_PreRender(object sender,
System.EventArgs e) {

// Save all member variables.
ViewState["memberValue"] = memberValue;

// Display value.
lblCurrent.Text = memberValue.ToString();
}

// (Other event handlers can now work with memberValue directly.)
}



Technorati :

Storing Information Between Postbacsk

ASP.NET is a stateless programming model. Every time a postback is triggered, your code loads into memory, executes, and is released from memory. If you want to keep track of information after your code has finished processing, you must use some form of state management.

ASP.NET provides several ways to store information, or state, between requests. The type of state you use determines how long the information will live, where it will be stored, and how secure it will be. The below table lists the various state options provided by ASP.NET. This table doesn't include the Cache object, which provides temporary storage and is described in the previous post. You can also use other, custom, approaches, such as hidden fields or a back-end database.

Table : Types of State Management

Type of State

Allowed Data

Storage Location

Lifetime

Security

View State

All serializable .NET data types.

A hidden field in the current Web page.

Lost when the user navigates to another page.

By default, it's insecure. However, you can use page directives to enforce encryption and hashing to prevent data tampering.

Query String

String data only.

The browser's URL string.

Lost when the user enters a new URL or closes the browser. However, it can be stored in a bookmark.

Clearly visible and easy for the user to modify.

Session State

All serializable .NET data types.

Server memory (can optionally be configured for an external process or database).

Times out after a predefined period (usually 20 minutes, but this period can be altered globally or programmatically).

Secure because data is never transmitted to the client.

Custom Cookies

String data only.

The client's computer (in memory or a small text file, depending on its lifetime settings).

Set by the programmer. Can be used in multiple pages and can persist between visits.

Insecure, and it can be modified by the user.

Application State

All serializable .NET data types.

Server memory.

The lifetime of the application (typically, until the server is rebooted). Unlike other methods, application data is global to all users.

Secure because data is never transmitted to the client.

The syntax for different data-storing methods is similar. Data is stored in a collection object and indexed using a string name.

The below figurehows a Web page that performs a test of several different forms of session state. When the user clicks the Store Data button, a new System.DateTime object is created and stored in page view state, session state, and a custom cookie. When the user clicks the Get Data button, this information is retrieved and displayed. Finally, the Clear Data button removes information from all types of state.

aspform.JPG

Here's the page code:


using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.SessionState;

public class TestState : System.Web.UI.Page {

protected System.Web.UI.WebControls.Button cmdClear;
protected System.Web.UI.WebControls.Button cmdStore;
protected System.Web.UI.WebControls.Button cmdGetData;
protected System.Web.UI.WebControls.Label lblData;

// (Designer code omitted.)

private void cmdStore_Click(object sender, System.EventArgs e) {

// Create a test object.
DateTime now = DateTime.Now;

// Store the object in view state.
ViewState["TestData"] = now;

// Store the object in session state.
Session["TestData"] = now;

// Store the object in a cookie.
// Check if the cookie already exists (named Recipe07-02).
if (Request.Cookies["Recipe07-02"] == null) {

// Create the cookie.
HttpCookie cookie = new HttpCookie("Recipe07-02");

// The cookie can only store string data.
// It can store multiple values, each with a different key.
cookie["TestData"] = now.ToString();

// (You can modify additional Cookie properties to change
//  the expiry date.)

// Attach the cookie to the response.
// It will be submitted with all future requests to this site
// until it expires.
Response.Cookies.Add(cookie);
}
}

private void cmdGetData_Click(object sender, System.EventArgs e) {

lblData.Text = "";

// Check for information in view state.
if (ViewState["TestData"] != null) {

DateTime data = (DateTime)ViewState["TestData"];
lblData.Text += "<b>View state data:</b> " +
data.ToString() + "<br>";

}else {

lblData.Text += "No view state data found.<br>";
}

// Check for information in session state.
if (Session["TestData"] != null) {

DateTime data = (DateTime)Session["TestData"];
lblData.Text += "<b>Session state data:</b> " +
data.ToString() + "<br>";

}else {

lblData.Text += "No session data found.<br>";
}

// Check for information in a custom cookie.
HttpCookie cookie = Request.Cookies["Recipe07-02"];
if (cookie != null) {

string cookieData = (string)cookie["TestData"];
lblData.Text += "<b>Cookie data:</b> " +
cookieData + "<br>";

}else {

lblData.Text += "No cookie data found.<br>";
}
}

private void cmdClear_Click(object sender, System.EventArgs e) {

ViewState["TestData"] = null;
Session["TestData"] = null;
// (You can also use Session.Abandon to clear all session
//  information.)

// To clear a cookie you must replace it with
// a cookie that has an expiration date that has already passed.
HttpCookie cookie = new HttpCookie("Recipe07-02");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
}

One type of state that this page doesn't demonstrate is the query string. The query string requires a page redirect and is ideal for transferring information from one page to another. To set information, you must redirect the user to a new page and add the query string arguments to the end of the URL. You can use the HttpServerUtility.UrlEncode and UrlDecode methods to ensure the string data is URL legal. This method properly escapes any special characters.

DateTime now = DateTime.Now;
string data = Server.UrlEncode(now.ToString());
Response.Redirect("newPage.aspx?TestData=" + data);

To retrieve this information, you can use the HttpResponse.QueryString collection:


// Check for information in the query string.
if (Request.QueryString["TestData"] != null) {

string data = Request.QueryString["TestData"];
data = Server.UrlDecode(data);
lblData.Text += "<b>Found query string data:</b> " + data + "<br>";
}

Redirect the User to Another Page

The easiest way to redirect a user from one Web page to another is to use the HttpResponse.Redirect method and supply a new URL. You can access the current HttpResponse object through the HttpContext object or by using the Reponse property of a Page or a Control object. Here's an example of an event handler that redirects the user in response to a button click:




private void cmdRedirect_Click(object sender, System.EventArgs e) {

Response.Redirect("newpage.aspx");
}

The Redirect method works with relative URLs to resources in the same virtual directory, and with fully qualified URLs. URLs can point to other ASP.NET pages, other types of documents (such as HTML pages or images), and other Web servers.


The Redirect method sends a redirect instruction to the browser. The browser then requests the new page. The result is that the browser has to make two roundtrips to the Web server, and the Web server has to handle an extra request. A more efficient option is available through the HttpServerUtility.Transfer method, which transfers execution to a different ASP.NET page on the same Web server. Here's an example:




private void cmdRedirect_Click(object sender, System.EventArgs e) {

Server.Transfer("newpage.aspx");
}

The Transfer method doesn't require an extra trip to the client, but it won't work if you need to transfer execution to another server or another type of resource other than a Web form (including a classic ASP page).




Technorati :

Variety in the Web World