Tuesday, 6 December 2011

Page.PreviousPage Method in Asp.net

At times there becomes a need to transfer data from one page to another page in ASP.NET and for doing this, there are various ways through which we can transfer data from one page to another page. For transferring the data we need to store the data either on the client side or on the server side.

Client Side Storage Mechanism:-
  1. Cookies
  2. Query String
  3. Hidden Field (View State)
  4. Cache
Server Side Storage Mechanism:-
  1. Session
  2. Application
We can easily transfer data through a query string but the drawback of using this concept is that the string is visible in the address bar and your site can be easily hacked. This means we cannot transfer sensitive data such as passwords or any other data. And the 2nd limitation is that we can transfer data maximum up to 255 characters and not more than that.

There is one more approach that can be used for transferring data that is the  PostBackUrl property. This property can be set on a Button when you need to transfer data from one page to another page. The value of this property should be the transferred page. Let's suppose that we have 2 pages
  1. Survey.aspx
  2. SurveyReceipt.aspx
And we need to transfer data from survey.aspx to surveyReceipt.aspx. In this case we set the PostBackUrl of the button control on survey.aspx to SurveyReceipt.aspx.

Following is the design of Survey.aspx
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Survey.aspx.cs" Inherits="_Default" %>

<!DOCTYPE
html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html
xmlns="http://www.w3.org/1999/xhtml">
<head
runat="server">
    <title>Untitled Page</title>
    <style type="text/css">
        .style1
        {
            height: 46px;
        }
    </style>
</head>
<
body>
    <form id="form1" runat="server">

    <div>
        <table style="width: 100%; color: #0E0E6C">
                        <tr>
                            <td align="left" valign="top" colspan="2" style="background-color: Maroon; color: White;">
                              <span style="font-size: 18pt; font-family: Verdana; font-style: normal;">&nbsp;Help
                                    us to help you!</span>
                                <br />
                                Personal Info&nbsp;
                            </td>
                        </tr>
                        <tr>
                            <td align="right" valign="top">
                                Name:</td>
                            <td>
                                <input id="txtName" type="text" name="txtName" runat="server" enableviewstate="true" />
                            </td>
                        </tr>
                        <tr>
                            <td align="right" valign="top" class="style1">
                                Gender:</td>
                            <td class="style1">
                                <input id="Radio1" name="optGender" type="radio" value="Female" runat="server" enableviewstate="true" />Female
                                <br />
                                <input id="Radio2" name="optGender" type="radio" value="Male" runat="server" enableviewstate="true" />Male
                            </td>
                        </tr>
                        <tr>
                            <td align="right" valign="top">
                                Mountain Bike Rider?</td>
                            <td>
                                <input id="chkMBR" checked="checked" name="chkMBR" type="checkbox" runat="server"
                                    enableviewstate="true" />
                            </td>
                        </tr>
                        <tr>
                            <td align="right" valign="top">
                                Road Rider?</td>
                            <td>
                                <input id="chkRR" checked="checked" name="chkRR" type="checkbox" runat="server" enableviewstate="true" />
                            </td>
                        </tr>
                        <tr>
                            <td align="right" valign="top">
                                Favorite Trails from&nbsp;<br />
                                around the world:</td>
                            <td>
                                <textarea id="txtTrails" cols="50" name="txtTrails" rows="3" runat="server" enableviewstate="true"></textarea>
                            </td>
                        </tr>
                    </table>
                    <hr />
                    <asp:Table ID="tblOuter" runat="server" ForeColor="#0E0E6C" Width="100%">
                        <asp:TableRow ID="outerR1" runat="server">
                            <asp:TableCell ID="outerR1C1" runat="server" ColumnSpan="2">
                                <asp:Panel ID="pnlActivity" runat="server" Width="100px">
                                    Recent and Planned Activity</asp:Panel>
                            </asp:TableCell>
                        </asp:TableRow>
                        <asp:TableRow ID="outerR2" runat="server">
                            <asp:TableCell ID="outerR2C1" runat="server" VerticalAlign="Middle" Width="1%" Wrap="False">Rides</asp:TableCell>
                            <asp:TableCell ID="outerR2C2" runat="server">
                                <asp:Table ID="tblInner" runat="server" GridLines="None" Width="100%">
                                    <asp:TableRow ID="innerR1" runat="server">
                                        <asp:TableCell ID="innerR1C1" runat="server" Wrap="false" Width="1%">
                                            <asp:Literal ID="itlLast" runat="server" Text="Last Trip>>>"></asp:Literal>
                                        </asp:TableCell>
                                        <asp:TableCell ID="innerR1C2" runat="server">
                                            <asp:Calendar ID="calLast" runat="server" TodayDayStyle-BackColor="Maroon"></asp:Calendar>
                                        </asp:TableCell>
                                    </asp:TableRow>
                                    <asp:TableRow ID="innerR2" runat="server">
                                        <asp:TableCell ID="innerR2C1" runat="server" Wrap="false" Width="1%">
                                            <asp:Literal ID="ltlNext" runat="server" Text="Next Trip>>>"></asp:Literal>
                                        </asp:TableCell>
                                        <asp:TableCell ID="innerR2C2" runat="server">
                                            <asp:Calendar ID="calNext" runat="server" TodayDayStyle-BackColor="Maroon"></asp:Calendar>|
                                        </asp:TableCell>
                                    </asp:TableRow>
                                </asp:Table>
                            </asp:TableCell>
                        </asp:TableRow>
                        <asp:TableRow ID="outerR3" runat="server">
                            <asp:TableCell ID="outerR3C1" runat="server" HorizontalAlign="Left" VerticalAlign="Top"
                                Width="1%" Wrap="False">Your Ability:</asp:TableCell>
                            <asp:TableCell ID="outerR3C2" runat="server">
                                <asp:DropDownList ID="ddAbility" runat="server">
                                    <asp:ListItem Text="Beginner"></asp:ListItem>
                                    <asp:ListItem Text="Competent"></asp:ListItem>
                                    <asp:ListItem Text="Expert"></asp:ListItem>
                                </asp:DropDownList>

How to populate DataGridView, GridView with SQL statement in C#

When we do the development, we always want to make the code simple and error free if possible. In C#, GridView for web based application and DataGridView for windows form based application are different in using and behavior. It looks like Microsoft has two different teams to develop GridView and DataGridView separately.  This is why I wrote this article to share the coding for each control. Here I am using MS Visual Studio 2005.

I. Populate GridView control for web based application with SQL statement

Let us put GridView1 control on the web form from Toolbox. The coding is straight forward and is like the following:

protected void Page_Load(object sender, EventArgs e)
{

string strSQLconnection = "Data Source=dbServer;Initial Catalog=testDB;Integrated Security=True";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("select * from table1", sqlConnection);
sqlConnection.Open();

SqlDataReader reader = sqlCommand.ExecuteReader();
       
GridView1.DataSource = reader;
GridView1.DataBind();
}

You run the code and you can see the result. But when you see the data binding for DataGridView in the following section, it is quite different.

II. Populate DataGridView control with SQL statement for Window form based application

When I used the DataGridView control in C# in MS Visual Studio 2005, I found DataGridView control is not friendly to use. Windows form-based DataGridView control is different from web based GridView control. DataGridView doesn't have DataBind() method.  It took me a few days to figure out.
The logic is like this
  1. Create data set from SQL statement or stored procedure
  2. Create a table to hold this data set
  3. Create a BindingSource and bind this table with this BindingSource
  4. Then bind this BindingSource with GridView control.

This looks trivial. But I found it is very efficient and error free.

Let us put DataGridView control and BindingSource control on the windows form from Toolbox. Let us name DataGridView control as dbGridView, BindingSource control as dbBindSource. Let us apply the following code:

private void Form1_Load(object sender, EventArgs e)
{
string strCon = "Data Source=dbServer;Initial Catalog=testDB;Integrated Security=True";
string strSQL = "select * from table1";

SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

// Populate a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
dbBindSource.DataSource = table;

// Resize the DataGridView columns to fit the newly loaded content.
dbGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
// you can make it grid readonly.
dbGridView.ReadOnly = true; 
// finally bind the data to the grid
dbGridView.DataSource = dbBindSource;
}

Now we compile it and run it. You can see the data in the grid.

Monday, 5 December 2011

Globalization and localization in ASP.NET

Introduction

In this article, we will discuss the internationalization of web application using ASP.NET 2.0 and SQL Server 2005. Through the given solution, we can achieve the scenario below:
1. Display content in localization for these users who haven't set prefered language.
2. Change language and culture immediately after selection.
3. Store settings in database to remember the prefered language

<formulas></formulas>

(Diagram 1)

















(Diagram 2)
We use ASP.Net 2.0 Culture-sensetive formating and global resource settings here. This article isn't to discuss all about the internationalization in ASP.Net 2.0, but give one solution to bring the example how to implement that. However, I sugguest you'd better have a read about the relative information of ASP.NET 2.0 internationalization and localization before continuing.

ASP.NET 2.0 Internationalizing concepts:


(Diagram 3)

1. Create database and web project

(Diagram 4)

Only two tables, one is for user's information, the other is language or culture information.
After creating the database, then we can setup a new web project in VS2005/VWD2005.
2. Display localization content
ASP.Net 2.0 can render the localized HTML for special browsers. It checks the "Accept-Language" HTTP header to identify the browser settings. To perform the localization, we can simply add the attributes for @Page or add globalization section in web.config file.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Culture="auto" UICulture="auto" %>
Or
<!--// Web.config section under system.web-->
<globalization culture="auto" uiCulture="auto"/>
The differences between "Culture" and "UICulture" are Culture controls the formatting of dates, numbers, and currency whereas UICulture is for resource loading.
3. Change the UICulture when select specified language.
As in Diagram 2, when we select the language in dropdownlist control, the page's calendar, currency, and static text are going to be converted to corresponding localization. When ASP.NET web server receives one request, it will start one thread to handle the process, and the thread's culture and UICulture decide which culture of resource files will be loaded. Before this, we will come to set the resources for ASP.NET.
Right-click the web project, choose "App_GlobalResources" under "Add ASP.NET folder". And add a new resource file under that folder names "Resource.resx". To input the text is very easy, and no need to talk more here. Let's take a look at how to use the Global Resources on ASP.NET pages.
(1) On .aspx files, we can set the resource expression though the property toolbox.
(Diagram 5)
(Diagram 6)
This will add the explicit expression like:
<asp:Label ID="lbName" runat="server" Text="<%$ Resources:Resource, LoginUser %>"></asp:Label>
(2) Also we can use programmatic access in behind code by GetGlobalResourceObject() static method in HttpContext or though the default Resources namespace directly.
HttpContext.GetGlobalResourceObject("Resource", "LoginUser")
Or
Resources.Resource.LoginUser
By now, we can introduce the important properties of CurrentThread. They are Thread.CurrentThread.CurrentCulture and Thread.CurrentThread.CurrentUICulture. If we set these two properties for current thread then we can get our needed culture resources files. And the best practice to evaluate is to override the page's InitializeCulture method. To make this happen, we should make the page reload to init again because the dropdownlist selected changed event occurs after this mehod. Coding likes below:
protected void ddlCulture_SelectedIndexChanged(object sender, EventArgs e){
Session["PreferedCulture"] = this.ddlCulture.SelectedValue;
Server.Transfer(Request.Url.LocalPath);
}
protected string CurrentCulture{
get{
if(null != Session["PreferedCulture"]){
return Session["PreferedCulture"].ToString();
}
return String.Empty;
}
}
protected override void InitializeCulture(){
if(!String.IsNullOrEmpty(CurrentCulture)){
try{
Thread.CurrentThread.CurrentCulture = new CultureInfo(CurrentCulture);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}
catch{throw;}
}
}
4. Make application UICulture change.
After section 3, we can change the page's culture with our need. But if you add one hyperlink to another page and visit it, you'll find that's not your want. On the second page, all settings are kept in the old culture. Although two pages use the same thread, they have the different culture info, and we haven't changed it artificially. I guess when the page2 class initializes, it initializes the culture with the default settings.
To solve this and make the whole application or website can use the same culture info, we add one Parent class file to every .ASPX file. And invoke the InitializeCulture method in it, every other page inherits this base class.
 

Saturday, 3 December 2011

Difference between .NET framework 3.5 and 4.0

.Net Framework 4.0 comes up with some of major changes as compare to previous versions of .Net Framework 3.5 and 2.0


Following are list of Major Changes in .Net 4.0



  • ControlRenderingCompatabilityVersion Setting in the Web.config File 
  • ClientIDMode Changes 
  • HtmlEncode and UrlEncode Now Encode Single Quotation Marks 
  • ASP.NET Page (.aspx) Parser is Stricter 
  • Browser Definition Files Updated 
  • System.Web.Mobile.dll Removed from Root Web Configuration File 
  • ASP.NET Request Validation 
  • Default Hashing Algorithm Is Now HMACSHA256 
  • Configuration Errors Related to New ASP.NET 4 Root Configuration 
  • ASP.NET 4 Child Applications Fail to Start When Under ASP.NET 2.0 or ASP.NET 3.5 Applications 
  • ASP.NET 4 Web Sites Fail to Start on Computers Where SharePoint Is Installed 
  • The HttpRequest.FilePath Property No Longer Includes PathInfo Values 
  • ASP.NET 2.0 Applications Might Generate HttpException Errors that Reference eurl.axd 
  • Event Handlers Might Not Be Not Raised in a Default Document in IIS 7 or IIS 7.5 Integrated Mode Changes to the ASP.NET Code Access Security (CAS) Implementation 
  • MembershipUser and Other Types in the System.Web.Security Namespace Have Been Moved 
  • Output Caching Changes to Vary * HTTP Header 
  • System.Web.Security Types for Passport are Obsolete 
  • The MenuItem.PopOutImageUrl Property Fails to Render an Image in ASP.NET 4 

Friday, 2 December 2011

ASP .NET - The TextBox Control

The TextBox control is used to create a text box where the user can input text.
The example below demonstrates some of the attributes you may use with the TextBox control:

<html>
<body>

<form runat="server">


A basic TextBox:

<asp:TextBox id="tb1" runat="server" />
<br /><br />

A password TextBox:

<asp:TextBox id="tb2" TextMode="password" runat="server" />
<br /><br />

A TextBox with text:

<asp:TextBox id="tb4" Text="Hello World!" runat="server" />
<br /><br />

A multiline TextBox:

<asp:TextBox id="tb3" TextMode="multiline" runat="server" />
<br /><br />

A TextBox with height:

<asp:TextBox id="tb6" rows="5" TextMode="multiline"
runat="server" />
<br /><br />

A TextBox with width:

<asp:TextBox id="tb5" columns="30" runat="server" />

</form>


</body>

</html> 

Add a Script

The contents and settings of a TextBox control may be changed by server scripts when a form is submitted. A form can be submitted by clicking on a button or when a user changes the value in the TextBox control.
In the following example we declare one TextBox control, one Button control, and one Label control in an .aspx file. When the submit button is triggered, the submit subroutine is executed. The submit subroutine writes a text to the Label control:
Example:

<script runat="server">
Sub submit(sender As Object, e As EventArgs)
lbl1.Text="Hello " & txt1.Text
End Sub
</script>

<html>
<body>

<form runat="server">
Enter your name:
<asp:TextBox id="txt1" runat="server" />
<asp:Button OnClick="submit" Text="Submit" runat="server" />
<p><asp:Label id="lbl1" runat="server" /></p>
</form>

</body>
</html> 

 


Web Forms in ASP.NET

In ASP.NET Web forms, it is essential to write all the server controls within the <form> tag and runat="server" attribute must be included in it. This attribute shows that the form is to be processed on the server. Also it indicates that the controls enclosed in the <form> tag can be accessed by server scripts.

For instance:
<form runat="server">

...HTML + server controls

</form>
If you don't specify the action attribute, it will be ignored as the form is always submitted to the page itself. If method attribute is left out, by default it will be set to method="post". Other attributes like name and if are also automatically assigned by ASP.NET if you don't mention them. Important point to keep in mind here is that an .aspx page can have only one <form runat="server"> control.
If you leave out name, method, action and ID attribute, the .aspx page will look as follows if you view the source:
 <form name="_form1" method="post" action="index.aspx" id="_form1">

...some code

</form>

Submitting a Form

A button is used mostly to submit a form. The format of the Button server control is as follows in ASP.NET:
<asp:Button id="id" text="label" OnClick="sub" runat="server"/>
Here the id attribute sets a unique name for the button and the text attribute assigns a label to the button. The onClick event handler sets a named subroutine to execute.
In the following example we declare a Button control in an .aspx file. A button click runs a subroutine which changes the text on the button:
<script runat="server">
Sub submit(Source As Object, e As EventArgs)

button1.Text="You clicked me!"

End Sub

</
script>
<
html>
<
body>
<
form id="Form1" runat="server">
<
asp:Button id="button1" Text="Click me!" runat="server"
OnClick
="submit" />
</
form>
</
body>
</
html>

Try it yourself 

<script  runat="server">
Sub submit(Source As Object, e As EventArgs)
   button1.Text="You clicked me!"
End Sub
</script>


<html>
<body>

<form runat="server">
<asp:Button id="button1" Text="Click me!" runat="server" OnClick="submit" />
</form>

</body>
</html>