Friday, July 8, 2011

ASP.NET Routing

ASP.NET routing enables you to use URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users.

Let's take an example to understand how it works.
I have created a demo project with two aspx screens. Project structure is like:


Step 1: Add following code in web.config to enable routing in your project:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule,
System.Web.Routing, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"
/>
</modules>
<handlers>
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*"
path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
/>

</handlers>
</system.webServer>
</configuration&gt;

Step 2: Create a function in Global.asax which registers all the route mappings:

Using System.Web.Routing;
private static void RegisterRoutes()
{
//Maps Screen1.aspx to FirstScreen in URL.
RouteTable.Routes.MapPageRoute("MainScreen", "FirstScreen",
"~/Screen1.aspx");

//Maps Screen2.aspx to SecondScreen/{ScreenName} in URL.
RouteTable.Routes.MapPageRoute("SecondaryScreen", "SecondScreen/{ScreenName}",
"~/Screen2.aspx");
}

MapPageRoute function provides a way to define routes for web forms.
It takes 3 parameters:
  1. RouteName - Unique Name for each Route.
  2. RouteURL - New URL, which will be displayed in the browser.
  3. PhysicalFile - aspx page URL.

Step 3: Call this function in Application_Start() in Global.asax:
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}

Step 4: Add 1 textbox and button on Screen1.aspx:
<h2>
Screen Name to be displayed in URL
</h2>
<asp:TextBox runat="server" ID="txtScreenName" />

<asp:Button ID="Button1" runat="server" Text="Next Screen"
OnClick=
"Button1_Click" />



Also, add following code on Screen1.aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("SecondScreen/" + Server.UrlEncode(txtScreenName.Text.Trim()));
}


The URLEncode method applies URL encoding rules, including escape characters, to a specified string.
URLEncode converts characters as follows:
  • Spaces ( ) are converted to plus signs (+).
  • Non-alphanumeric characters are escaped to their hexadecimal representation.
This will redirect the screen to Screen2.aspx and the URL displayed in the browser will be somewhat like :
Something/SecondScreen/ValueEnteredInTextBox


This URL was getting created on the basis of value entered in the textbox at runtime. Suppose we want to hardcode a url, in that case we will simply write:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("~/FirstScreen");
}

We have already defined the mapping for FirstScreen in above mentioned Global.asax file.
Read More..

Thursday, October 21, 2010

Inheritance

As we all know, inheritance is just the hierarchical relationship between various classes.
Class from which another class is inheriting some methods is base class and the other one is known as derived class.

For ex:
Class AA
{ }

Class BB : AA
{ }

Here, AA is your base class and B is your derived class.

Now a very basic question:
When we create an object of derived class, which constructor gets called?
1. Of Base Class
2. Of Derived Class
3. Both
4. None

Let's try to figure it with this example:

class AA
{
public AA()
{
Console.WriteLine("In AA");
}
}

class BB : AA
{
public BB()
{
Console.WriteLine("In BB");
}
}

class CC : BB
{
public CC()
{
Console.WriteLine("In CC");
}
}

Here, class CC is inheriting class BB and class BB is inheriting class AA.

class Program
{
static void Main(string[] args)
{
CC c = new CC();
}
}

I just created an object of CC in another class.
Now which constructor will be called?

Here is the output :


In case of inheritance, derived class always calls base class constructor first and then its own constructor.
Here, object of CC called the constructor of BB and similarly BB calls its base class constructor i.e., AA.
so, the sequence of execution is:
AA constructor -> BB constructor -> CC constructor

Read More..

Const Keyword

Const is a keyword which can be use to declare fields. We can initialize Const variable only at the time of declaration and cant modify it at runtime.
We cant make a Const field as static.
Const fields are compile-time constants.

For ex:
I have a class which contains two const variables.
class TestConst
{
public const int a = 10;
public const int b = 7;
}

I have another class, where i have created an object of TestConst class.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(TestConst.a);
Console.WriteLine(TestConst.b);
Console.ReadLine();
}
}

We cant access a const variable through object of class. We can always access a const variable with class name only.
Like : ClassName.ConstVariableName
Read More..

ReadOnly Modifier

ReadOnly is a modifier which can be use to declare fields. We can initialize readonly variable either at the time of declaration or through constructor.

ReadOnly fields can be used for runtime constants as we can declare value through constructors.

For ex:
I have a class which contains two readonly variables.
class TestReadOnly
{
public readonly int a = 10;
public readonly int b;

public TestReadOnly()
{
b = 15;
}

public TestReadOnly(int newB)
{
b = newB;
}
}

I have another class, where i have created an object of TestReadOnly class.
class Program
{
static void Main(string[] args)
{
TestReadOnly test = new TestReadOnly();
Console.WriteLine(test.a);
Console.WriteLine(test.b);
test = new TestReadOnly(20);
Console.WriteLine(test.b);
Console.ReadLine();
}
}

Whenever, I want to reassign the value to a readonly variable, I have to call the parametrized constructor of the class and pass the new value.
Read More..

Monday, October 11, 2010

BENEFITS OF XMLDATADOCUMENT OVER XMLDOCUMENT

Recently I came across a requirement, where I need to fetch the data from GridView and convert it to XML.
I had a predefined format of XML, in which I need to save the data :
<root>
<rec>
<amount />
<remark />
</rec>
<rec>
<amount />
<remark />
</rec>
</root>
Also, I have a checkbox in the first column of GridView. I have to fetch records for which checkbox is checked.

I can use either XMLDocument or XMLDataDocument for the same.

1. Using XMLDocument:XmlDocument xmlDoc = new XmlDocument();
XmlElement root = xmlDoc.CreateElement("root"); xmlDoc.AppendChild(root);
foreach (GridViewRow Row in grdTest.Rows)
{
CheckBox chkTopUpRequest = (CheckBox)Row.FindControl("chkRequest");
if (null != chkTopUpRequest && chkTopUpRequest.Checked)
{
XmlElement rec = xmlDoc.CreateElement("rec");
root.AppendChild(rec);
XmlElement topupid = xmlDoc.CreateElement("topupid");
topupid.InnerText = grdTopUpRequest.DataKeys[Row.RowIndex].Value.ToString();
rec.AppendChild(topupid);
XmlElement amount = xmlDoc.CreateElement("amount");
TextBox txtAmount = (TextBox)Row.FindControl("txtAmount");
amount.InnerText = txtAmount.Text.Trim();
rec.AppendChild(amount);
XmlElement remarks = xmlDoc.CreateElement("remarks");
TextBox txtRemarks = (TextBox)Row.FindControl("txtRemarks");
remarks.InnerText = txtRemarks.Text.Trim();
rec.AppendChild(remarks);
}
}
2. Using XMLDataDocument :

DataSet dataSet = new DataSet("root");
DataTable dataTable = new DataTable("rec");
dataTable.Columns.AddRange(new DataColumn[]
{
new DataColumn("topupid"),
new DataColumn("amount"),
new DataColumn("remarks")
});

foreach (GridViewRow Row in grdTest.Rows)
{
CheckBox chkTopUpRequest = (CheckBox)Row.FindControl("chkRequest");
if (null != chkTopUpRequest && chkTopUpRequest.Checked)
{
TextBox txtAmount = (TextBox)Row.FindControl("txtAmount");
TextBox txtRemarks = (TextBox)Row.FindControl("txtRemarks");
dataTable.Rows.Add(grdTopUpRequest.DataKeys[Row.RowIndex].Value.ToString(),
txtAmount.Text.Trim(),
txtRemarks.Text.Trim());
}
}
dataSet.Tables.Add(dataTable);
XmlDataDocument xmlDataDoc = new XmlDataDocument(dataSet);


XMLDocument is an in-memory (cache) tree representation of an XML document and enables the navigation and editing of this document.

The XmlDataDocument class extends XmlDocument and allows structured data to be stored, retrieved, and manipulated through a relational DataSet. This class allows components to mix XML and relational views of the underlying data.

Read More..

Friday, October 8, 2010

HANDLING KEYPRESS EVENT OF TEXTBOX INSIDE GRIDVIEW

I have a GridView, in which my first column is Template Field which contains textbox.

<asp:gridview id="grdTest" runat="server" autogeneratecolumns="false" datakeynames="TestID">
<columns>
<asp:templatefield HeaderText="Amount">
<itemtemplate>
<asp:TextBox ID="txtAmount" runat="server" Text='' />
</itemtemplate>
<asp:boundfield datafield="Name" headertext="Name" />
</asp:TemplateField>
</columns>
</asp:GridView>

Now, I want that user can only enter integer value in txtAmount textbox. I want to handle this client side only. So, I used jquery and handled KeyPress event of textbox. By doing so, user can only enter digits. If user will press any non-numeric key it will not get entered.

<script type="text/javascript">
$(document).ready(function () {
$("#<%=grdTest.ClientID %> INPUT[id$='txtAmount']").keypress(
function IsNumericHandler(e) {
var unicode = e.charCode ? e.charCode : e.keyCode

//if the key isn't the backspace key (which we should allow)
if (unicode != 8) {
//if not a number
if (unicode <> 57)
//disable key press
return false;
}
});
});
</script>

Read More..

Thursday, October 7, 2010

SELECT ALL \ DESELECT FUNCTIONALITY FOR CHECKBOX INSIDE GRIDVIEW

I have a GridView, in which my first column is Template Field which contains checkbox.

<asp:gridview id="grdTest" runat="server" autogeneratecolumns="false" datakeynames="TestID">
<columns>
<asp:templatefield>
<headertemplate>
<asp:checkbox id="ChkAll" runat="server" />
</headertemplate>
<itemtemplate>
<asp:checkbox id="chkRequest" runat="server" />
</itemtemplate>
<asp:boundfield datafield="Name" headertext="Name" />
</asp:TemplateField>
</columns>
</asp:GridView>

Now, I want on click of ChkAll checkbox (which is in header of grid) all the checkboxes in the first row gets selected. Also, when I deselect any checkbox in first row, ChkAll checkbox gets deselected.

I did this using jquery :

<script type="text/javascript">
$(document).ready(function () {
//To Select/Deselect all checkboxes on click of ChkAll checkbox.
var chkBox = $("input[id$='ChkAll']");
chkBox.click(
function () {
$("#<%=grdTest.ClientID %> INPUT[type='checkbox']")
.attr('checked', chkBox.is(':checked'));
});

// To deselect CheckAll when a GridView CheckBox is unchecked.
$("#<%=grdTest.ClientID %> INPUT[type='checkbox']").click(
function (e) {
if (!$(this)[0].checked) {
chkBox.attr("checked", false);
}
});
});
</script>
Read More..