0% found this document useful (0 votes)
103 views14 pages

Part 55 - Cross Page Postback Part 56 - Cross Page Postback Strongly Typed Reference

The document discusses different techniques for passing data between web forms in ASP.NET, including context handler object, query strings, and session state. It provides code examples for using context handler object and query strings to transfer data from one form to another. Session state modes such as InProc, StateServer, and SQLServer are also summarized, along with code samples for configuring StateServer session state in web.config.

Uploaded by

lal kapda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views14 pages

Part 55 - Cross Page Postback Part 56 - Cross Page Postback Strongly Typed Reference

The document discusses different techniques for passing data between web forms in ASP.NET, including context handler object, query strings, and session state. It provides code examples for using context handler object and query strings to transfer data from one form to another. Session state modes such as InProc, StateServer, and SQLServer are also summarized, along with code samples for configuring StateServer session state in web.config.

Uploaded by

lal kapda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Part 55 - Cross page postback

Part 56 - Cross page postback strongly typed reference


Part 57 - Opening new window using javascript in asp.net 

Different techniques to move data from one webform to another 


1. Cross Page Postback: Discussed in Part 55 and Part 56
2. Context.Handler object - Will be discuss in this video session.

The following concepts will be discussed in the subsequent sessions


3. Query strings 
4. Cookies
5. Session state
6. Application state 

In general, the members of one Web form are unavailable from a subsequently
displayed Web form. However, when navigating between Web forms using the Transfer or
Execute method, data can be retrieve from the previous Web form using Context.Handler
object.

Points to remember Context.Handler object


1. Context.Handler returns WebForm1 as the previous page, only the first time when you
land on WebForm2 from WebForm1. If there is a button on WebForm2, and if you click the
button, the page will postback, and Context.Handler will return WebForm2 instead of
WebForm1.
2. For the Context.Handler to return WebForm1 as the previous page, you should have
landed on WebForm2, using Server.Transfer or Server.Execute method from WebForm1.
3. The control values from the previous page, can be accessed using FindControl() method
or using public properties. The problem with FindControl() method is that, if you mis-spell the
ControlID, we could get a runtime NullRefernceException. Using public properties, instead of
FindControl() method, can eliminate runtime NullRefernceExceptions.

WebForm1.aspx HTML source:


<div style="font-family: Arial">
<table>
    <tr>
        <td colspan="2">
            <h1>
                This is WebForm1</h1>
        </td>
    </tr>
    <tr>
        <td>
            <b>Name</b>
        </td>
        <td>
            :<asp:TextBox ID="txtName" runat="server">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <b>Email</b>
        </td>
        <td>
            :<asp:TextBox ID="txtEmail" runat="server">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td colspan="2"> 
            <asp:Button ID="Button1" runat="server" 
            Text="Go to WebForm2" onclick="Button1_Click" />
        </td>
    </tr>
</table>
</div>

WebForm1.aspx.cs Code:
protected void Button1_Click(object sender, EventArgs e)
{
    Server.Transfer("~/WebForm2.aspx");
}

public string Name
{
    get
  {
        return txtName.Text;
  }
}

public string Email
{
    get
  {
        return txtEmail.Text;
  }
}

WebForm2.aspx HTML source:


<div style="font-family: Arial">
<table>
    <tr>
        <td colspan="2">
            <h1>This is WebForm2</h1>
        </td>
    </tr>
    <tr>
        <td>
            <b>Name</b>
        </td>
        <td>
            :<asp:Label ID="lblName" runat="server">
            </asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            <b>Email</b>
        </td>
        <td>
            :<asp:Label ID="lblEmail" runat="server">
            </asp:Label>
        </td>
    </tr>
</table>
</div>

WebForm2.aspx.cs Code:
//On postback Context.Handler returns WebForm2
if (!IsPostBack)
{
    Page lastpage = (Page)Context.Handler;
    if (lastpage is WebForm1)
  {
        //Use FindControl() if public properties does not exist on the 
        //previous page(WebForm1). FindControl() may cause 
        //NullRefernceExceptions due to mis-spelled conrol Id's

        //lblName.Text = ((TextBox)lastpage.FindControl("txtName")).Text;
        //lblEmail.Text = ((TextBox)lastpage.FindControl("txtEmail")).Text;
                    
        //Using public properties can eliminate NullRefernceExceptions 
        lblName.Text = ((WebForm1)lastpage).Name;
        lblEmail.Text = ((WebForm1)lastpage).Email;
  }

Points to remember about query strings


1. Querystrings are name/value collection pairs
2. Using querystrings, is a very comman way to send data from one webform to another.
3. Query strings are appended to the page URL.
4. ?(Question Mark), indicates the beginning of a query string and it's value.
5. It is possible to use more than one query string. The first query string is specified using
the ?(question mark). Subsequent query strings can be appended to the URL using the
&(ampersand) symbol.
6. There is a limit on the Query string length. Hence, Query strings cannot be used to send
very long data.
7. Query strings are visible to the user, hence should not be used to send sensitive
information, unless encrypted.
8. To read the query string value, use Request object's QueryString property.
9. &(ampersand) is used to concatenate query strings, so if you want to send &, as value for
the query string there are 2 ways, as shown below
Using Server.UrlEncode() method
Response.Redirect("WebForm2.aspx?UserName=" + Server.UrlEncode(txtName.Text) + 
    "&UserEmail=" + Server.UrlEncode(txtEmail.Text));

Or
&(ampersand) is encoded as %26, so use, Replace() function to replace & with %26
Response.Redirect("WebForm2.aspx?UserName=" + txtName.Text.Replace("&", "%26") +
    "&UserEmail=" + txtEmail.Text.Replace("&", "%26")); 

WebForm1.aspx HTML: We want to send Name and Email, that user enters on
WebForm1.aspx to WebForm2.aspx using query strings.
<div style="font-family: Arial">
<table>
    <tr>
        <td colspan="2">
            <h1>
                This is WebForm1</h1>
        </td>
    </tr>
    <tr>
        <td>
            <b>Name</b>
        </td>
        <td>
            :<asp:TextBox ID="txtName" runat="server">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <b>Email</b>
        </td>
        <td>
            :<asp:TextBox ID="txtEmail" runat="server">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td colspan="2"> 
            <asp:Button ID="btnSendData" runat="server" 
            Text="Go to WebForm2" onclick="btnSendData_Click" />
        </td>
    </tr>
</table>
</div>

WebForm1.aspx.cs
protected void btnSendData_Click(object sender, EventArgs e)
{
    //Using Server.UrlEncode to encode &(ampersand)
    //Response.Redirect("WebForm2.aspx?UserName=" + Server.UrlEncode(txtName.Text)

    //    "&UserEmail=" + Server.UrlEncode(txtEmail.Text));
            
    //Using String.Replace() function to replace &(ampersand) with %26 
    Response.Redirect("WebForm2.aspx?UserName=" + txtName.Text.Replace("&", "%26")
+
        "&UserEmail=" + txtEmail.Text.Replace("&", "%26"));
}

WebForm2.aspx HTML:
<div style="font-family: Arial">
<table>
    <tr>
        <td colspan="2">
            <h1>This is WebForm2</h1>
        </td>
    </tr>
    <tr>
        <td>
            <b>Name</b>
        </td>
        <td>
            :<asp:Label ID="lblName" runat="server">
            </asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            <b>Email</b>
        </td>
        <td>
            :<asp:Label ID="lblEmail" runat="server">
            </asp:Label>
        </td>
    </tr>
</table>
</div>

WebForm2.aspx.cs Code:
protected void Page_Load(object sender, EventArgs e)
{
    // Read the QueryString values 
    lblName.Text = Request.QueryString["UserName"];
    lblEmail.Text = Request.QueryString["UserEmail"];

StateServer asp.net session state mode management - Part 65


Suggested Videos
Part 62 - Asp.net session state
Part 63 - Cookie less sessions in asp.net
Part 64 - Inporc asp.net session state mode management 

In this video, we will discuss about the asp.net session state mode -
StateServer.Asp.net session state mode can have any of the following 4 values. Asp.net
session state mode is set in web.config file.
1. Off - Disables session state for the entire application.
2. InProc - Discussed in Part 64
3. StateServer - Will be discussed in this session.

The following session state modes will be discussed in a later video session.
4. SQLServer
5. Custom 

When the session state mode is set to StateServer, the session state variables are
stored in a process, called as asp.net state service. This process is different from the asp.net
worker process. The asp.net state service can be present on a web server or a dedicated
machine. 

Steps to follow, to configure asp.net web application to use StateServer:


1. Start the ASP.NET state Service. To start the asp.net state service
    a) Click Start > Type Run > Press Enter
    b) In the run window, type services.msc and click OK.
    c) In the services window, right click on ASP.NET State Service and select Start.
2. In web.config set sessionState mode="StateServer"
3. Set stateConnectionString="tcpip=StateServer:42424"
    Example: <sessionState mode="StateServer"  
stateConnectionString="tcpip=localhost:42424"  
              timeout="20"></sessionState> 

Advantages of using StateServer session state mode:


1. ASP.NET worker process independent. Survives worker process restart. 
2. Can be used with web farms and web gardens.
3. State server offers more scalability than InProc.

Dis-advantages of using StateServer session state mode:


1. StateServer is slower than InProc
2. Complex objects, need to be serialized and deserialized
3. If the StateServer, is on a dedicated machine, and if the server goes down all the sessions
are lost.
Note: 
Web Garden - Web application deployed on a server with multiple processors
Web Farm - Web application deployed on multiple server 

. Off - Disables session state for the entire application.


2. InProc - Discussed in Part 64
3. StateServer - Discussed in Part 65
4. SQLServer - Will be discussed in this session.
5. Custom - Enables you to build your own Session State provider. For example, Oracle. 

When the session state mode is set to SQLServer, the session state variables are stored
in a SQLServer database.

Steps to follow, to configure asp.net web application to use SQLServer:


1. Create the ASPState database using aspnet_regsql.exe tool. There are several versions
of this tool. I am running .NET version 4.0, on a 64 bit operating system. So I will use the
version that is present in C:\Windows\Microsoft.NET\Framework64\v4.0.30319.
   a) click Start > Type Run > Press Enter
   b) Type cmd > Press Enter
   c) In the command prompt type - cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
   d) Press Enter
   e) Type - aspnet_regsql.exe -S SQLServerName -E -ssadd -sstype p
   f) Press Enter. At this point you should have ASPState Database added.
   g) For help running this tool, please refer to the following MSDN article 
        http://msdn.microsoft.com/en-us/library/ms229862(v=vs.100).aspx

2. Set the Session state mode=SQLServer and sqlConnectionString


    If you want to use windows authentication
      <sessionState mode="SQLServer" 
      sqlConnectionString="data source=SQLServerName; integrated security=SSPI"
      timeout="20"></sessionState>
  
    If you want to use sql serevr authentication
     <sessionState mode="SQLServer" 
     sqlConnectionString="data source=SQLServerName; user id=sa; password=pass"
     timeout="20"></sessionState> 

Note: If you use integrated security(windows authentication), you might get an error
stating "Failed to login to session state SQL server for user 'IIS APPPOOL\ASP.NET v4.0'.".
To resolve this error
a) click Start > Type Run > Press Enter
b) Type inetmgr > Press Enter
c) Expand IIIS and Click on Application Pools.
d) Right click on ASP.NET v4.0 and select Advanced settings
e) Change Process Model > Identity to LocalSystem and Click OK

Advantages of using SQLServer session state mode:


1. SQLServer is the most reliable option. Survives worker process recycling and SQL Server
restarts.
2. Can be used with web farms and web gardens.
3. More scalable than State server and InProc session state modes.

Dis-advantages of using StateServer session state mode:


1. Slower than StateServer and InProc session state modes
2. Complex objects, need to be serialized and deserialized

Note: 
Web Garden - Web application deployed on a server with multiple processors
Web Farm - Web application deployed on multiple server 
Suggested Videos
Part 64 - Inporc asp.net session state mode management
Part 65 - StateServer asp.net session state mode management
Part 66 - SQLServer asp.net session state mode management 

Part - 67

1. Application State variables are available across all pages and across all sessions.
Application State variables are like multi-user global data.

2. Application State variables are stored on the web server.

3. Application State variables are cleared, only when the process hosting the application
is restarted, that is when the application ends. 

4. Application State variables are not shared across a Web Farm or a Web Garden. 

5. Application state variables are not thread safe. Lock and Unlock methods of the
application class must be used to protect against race conditions, deadlocks, and access
violations.
Application.Lock();
Application["GlobalVariable"] = (int)Application["GlobalVariable"] + 1;
Application.UnLock();

Please Note: In this example, we are using application state variables to send data from one
web form to another. If the requirement, is just to send data from webform to another, you
should consider other alternatives.

6. Use application state variables only, when the variables need to have global access
and when you need them for entire time, during the life time of an application. Cache
object, can be used, as an alternative, if you need to have global access for a certain
duration. 
Forms authentication using user names list in web.config - Part 90
Suggested Videos
Part 87 - Windows authentication
Part 88 - Windows authentication and authorization
Part 89 - Windows authentication and folder level authorization 

Anonymous authentication is fine for web sites that contain public informationthat
every one can see. We discussed about Anonymous authentication in
Part 85 - Anonymous authentication
Part 86 - Anonymous authentication and impersonation

Windows authentication is used for intranet web applications, where the users are part
of a windows domain-based network. We discussed about Windows authentication in Parts
87, 88 and 89. 

In this video we will discuss about


1. When to use Forms Authentication
2. How to enable Forms Authentication

When to use Forms Authentication?


Forms authentication is used for internet web applications. The advantage of Forms
authentication is that users do not have to be member of a domain-based network to have
access to your application. Many internet web sites like Gmail.com, Amazon.com,
facebook.com etc uses forms authentication. To access these applications we do not have
to be member of their domain-based network. 

How to enable Forms Authentication?


Create an asp.net web application project. Add a webform with name Welcome.aspx, and
Login.aspx. Add a new folder with name "Registration", to the project. Add Register.aspx
web form to the "Registration" folder.

Welcome.aspx HTML:
<h1>Welcome Page</h1>

Login.aspx HTML:
<div style="font-family:Arial">
<table style="border: 1px solid black">
    <tr>
        <td colspan="2">
            <b>Login</b>
        </td>
    </tr>
    <tr>
        <td>
            User Name
        </td>    
        <td>
            :<asp:TextBox ID="txtUserName" runat="server">
            </asp:TextBox>
        </td>    
    </tr>
    <tr>
        <td>
            Password
        </td>    
        <td>
            :<asp:TextBox ID="txtPassword" TextMode="Password" runat="server">
            </asp:TextBox>
        </td>    
    </tr>
    <tr>
        <td>
                    
        </td>    
        <td>
            <asp:Button ID="btnLogin" runat="server" Text="Login" />
        </td>    
    </tr>
</table>
<br />
<a href="Registration/Register.aspx">Click here to register</a> 
if you do not have a user name and password.
</div>

Register.aspx HTML:
<h1>Registration Page</h1>

If you run the application now, we will be able to navigate to any page, just by changing
the name of the page in the address bar. We are not logged in, but we are still able to
access all the pages in the application. 

Let us enable forms authentication now. To enable forms authentication, set


authentication element's mode attribute to forms in web.config file of the application. 
<authentication mode="Forms">
   <forms loginUrl="Login.aspx" timeout="30" 
          defaultUrl="Welcome.aspx" protection="All">
    <credentials passwordFormat="Clear">
      <user name="venkat" password="venkat"/>
      <user name="pragim" password="pragim"/>
      <user name="prasad" password="prasad"/>
    </credentials>
  </forms>
</authentication>

<authorization>
  <deny users="?" />
</authorization>
The description of the attributes
loginUrl - The URL of the login Page

timeout - Specifies the number of minutes the authentication cookie persists on the clients’s
computer. The default is 30 minutes.
  
defaultUrl - The url the user will be redirected after authentication

Protection - Specifies the protection for authentication cookie stored on the clients’s
computer. The default is All, which performs encryption and data validation. Other possible
settings are Encryption, Validation, and None.

Double click the login button on the Login.aspx page. Copy and paste the following code
in the button click event handler.
// Authenticate againts the list stored in web.config
if (FormsAuthentication.Authenticate(txtUserName.Text, txtPassword.Text))
{
    // Create the authentication cookie and redirect the user to welcome page
    FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,
chkBoxRememberMe.Checked);
}
else
{
    lblMessage.Text = "Invalid UserName and/or password";
}

Run the application. Try to navigate to Welcome.aspx or Registration/Register.aspx pages,


you will be redirected to Login page. After you login, you will be able to access these pages. 

There are 2 problems with this application at the moment.


1. It is not a good practise to store user names and passwords in web.config file. If you want
to create the user names and passwords dynamically, you need to change the web.config
file. If you change the web.config file at run time, the application restarts and all the session
data will be lost, if stored inside the worker process. In a later video session, we will discuss
about storing user names and passwords in a database table.

2. At the moment, users are not able to access Register.aspx page, if they are not logged in.
If a user does not have user name and password, he should be able to register himself using
Register.aspx page. In a later video session, we will discuss about this. 

Forms authentication in asp.net and user registration - Part 91


Suggested Videos
Part 88 - Windows authentication and authorization
Part 89 - Windows authentication and folder level authorization
Part 90 - Forms authentication using user names list in web.config 

In this code sample, we have used validation controls and ADO.NET. If you have not
watched the videos on validation controls and ADO.NET, I would strongly encourage you to
do so, before continuing with this session.

Please watch Part - 90, before proceeding. In Part - 90, we have discussed the basics of
Forms authentication. One of the problems, with the example in Part 90, is that, we are not
able to navigate to Registration/Register.aspx page if we are not logged in.

To solve this issue, add another web.config file to the "Registration" folder, and specify the
authorization element to allow all users.
<authorization>
  <allow users="*"/>
</authorization>

At this point, without logging into the application, users should be able to navigate to
Registration/Register.aspx page. 

Copy and paste the following HTML in Register.aspx page.


<div style="font-family:Arial">
<table style="border: 1px solid black">
    <tr>
        <td colspan="2">
            <b>User Registration</b>
        </td>
    </tr>
    <tr>
        <td>
            User Name
        </td>    
        <td>
            :<asp:TextBox ID="txtUserName" runat="server">
            </asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorusername" 
            runat="server" ErrorMessage="User Name required" Text="*"
            ControlToValidate="txtUserName" ForeColor="Red">
            </asp:RequiredFieldValidator>
        </td>    
    </tr>
    <tr>
        <td>
            Password
        </td>    
        <td>
            :<asp:TextBox ID="txtPassword" TextMode="Password" runat="server">
            </asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorPassword" 
            runat="server" ErrorMessage="Password required" Text="*"
            ControlToValidate="txtPassword" ForeColor="Red">
            </asp:RequiredFieldValidator>
        </td>    
    </tr>
    <tr>
        <td>
            Confirm Password
        </td>    
        <td>
            :<asp:TextBox ID="txtConfirmPassword" TextMode="Password" runat="server">
            </asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorConfirmPassword" 
            runat="server" ErrorMessage="Confirm Password required" Text="*"
            ControlToValidate="txtConfirmPassword" ForeColor="Red" 
            Display="Dynamic"></asp:RequiredFieldValidator>
            <asp:CompareValidator ID="CompareValidatorPassword" runat="server" 
            ErrorMessage="Password and Confirm Password must match"
            ControlToValidate="txtConfirmPassword" ForeColor="Red" 
            ControlToCompare="txtPassword" Display="Dynamic"
            Type="String" Operator="Equal" Text="*">
            </asp:CompareValidator>
        </td>    
    </tr>
    <tr>
        <td>
            Email
        </td>    
        <td>
            :<asp:TextBox ID="txtEmail" runat="server">
            </asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail" 
            runat="server" ErrorMessage="Email required" Text="*"
            ControlToValidate="txtEmail" ForeColor="Red"
            Display="Dynamic"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail" 
            runat="server" ErrorMessage="Invalid Email" ControlToValidate="txtEmail"
            ForeColor="Red" Display="Dynamic" Text="*"
            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
            </asp:RegularExpressionValidator>
        </td>    
    </tr>
    <tr>
        <td>
          
        </td>    
        <td>
            <asp:Button ID="btnRegister" runat="server" Text="Register" 
            onclick="btnRegister_Click"/>
        </td>    
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblMessage" runat="server" ForeColor="Red">
            </asp:Label>
        </td>    
    </tr>
    <tr>
        <td colspan="2">
            <asp:ValidationSummary ID="ValidationSummary1" ForeColor="Red" runat="server"
/>
        </td>    
    </tr>
</table>
</div>

Copy and Paste the following code in the "Register" button click event.
// If the Page has no validation errors
if (Page.IsValid)
{
    // Read the connection string from web.config.
    // ConfigurationManager class is in System.Configuration namespace
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    // SqlConnection is in System.Data.SqlClient namespace
    using (SqlConnection con = new SqlConnection(CS))
  {
        SqlCommand cmd = new SqlCommand("spRegisterUser", con);
        cmd.CommandType = CommandType.StoredProcedure;

        SqlParameter username = new SqlParameter("@UserName", txtUserName.Text);


        // FormsAuthentication calss is in System.Web.Security namespace
        string encryptedPassword = FormsAuthentication.
            HashPasswordForStoringInConfigFile(txtPassword.Text, "SHA1");
        SqlParameter password = new SqlParameter("@Password", encryptedPassword);
        SqlParameter email = new SqlParameter("@Email", txtEmail.Text);

        cmd.Parameters.Add(username);
        cmd.Parameters.Add(password);
        cmd.Parameters.Add(email);

        con.Open();
        int ReturnCode = (int)cmd.ExecuteScalar();
        if (ReturnCode == -1)
    {
            lblMessage.Text = "User Name already in use, please choose another user name";
    }
        else
    {
            Response.Redirect("~/Login.aspx");
    }
  }
}

Run the application. Fill in the required details, and click "Register" button. The user
should be added to the database. In the next video session, we will discuss about,
authenticating with the credentials we stored in the database. 

You might also like