Friday, October 2, 2009
Advanced Site Functionality in ASP.NET
In this tutorial you will learn advanced site functionality, Enhanced Page Framework, To create the Web.Sitemap file, Tracking Traffic with Site Counters and Going Mobile.
Enhanced Page Framework
The advanced functionalities offered by ASP.NET include site navigation and site counters. The built in navigation has three components:
1. Site Structure which is a programming interface that lists the hierarchical structure of the Website. The site map object exposes this interface using the components provided by the Site Map Provider. The default data store is usually a root level xml file named app.sitemap.
2. Site Navigation is a control that names each node defined in the site map and associates it with a URL.
3. Site Structure Display is a component that renders the site navigation user interface in an intelligent fashion and maps user friendly URLs to appropriate .aspx files.
The Site Map is a container for the hierarchical collection of nodes representing pages in an application. The default representation of a site map is Web.sitemap. This is an xml file.
To create the Web.Sitemap file:
1. Right click on the Website root folder and select Add New item…
2. Select a XmlFile and name it Web.sitemap
3. Open the file and add the following code to it.
Click here to view sample code
4. Open the Default.aspx file and enter the following code to the page.
Click here to view sample code
5. Press F5 to execute the program. The output will look as under:
Let us examine what we have done in the above code. We have used a Panel control to define a header and put a label in it and we have added a BulletedList control to display the contents of the SiteMap.
Click here to view sample code
Then we have used a TreeView control to display the same information in a different format.
Click here to view sample code
Finally we have used a Menu control to display the same information.
< asp:Menu runat="server" DataSourceID="ExForSysSiteMap" / >
Another type of control that can be used to display the same information is the SiteMapPath control. This control displays a navigation path and shows the current user the place he is in and displays links to the Home page. The entire control can be deployed and bound to a data source without writing a single line of code. The SiteMapPath is customizable. The links will appear as: Home > Courses > Web Application Development. The user can navigate back and forth at higher or lower levels of the hierarchy using the SiteMapPath controls navigation features.
Tracking Traffic with Site Counters
Another advanced control provided by ASP.NET 2.0 for site enhancement is the Site Counter. This is extremely useful in monitoring visitor activity. The two types of site activity normally performed by visitors are Impression and ClickThrough. Impression is a viewing of some specific content while ClickThrough is a user’s click to see a specific content. The site counters provide means to track these activities and collects the read and write related activities to a database via an ad hoc provider. Counter data can be collected using page view counters and server counters such as Hyperlink and AdRotator.
For counters to work, the site counter service must be enabled in the configuration file in the site counters section. A database must be set up before they are used and finally the provider must be set up and connected to the related database using the Web Administration tool.
A hyperlink control configured to track clicks would be coded as under:
< asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="http://www.exforsys.com" Text="Visit us at ExForSys for the best tutorials" counterclicks="true" counterName="Exforsys.com" >< / asp:HyperLink >
Apart from accessing the counters declaratively it is possible to access the counters programmatically also. The Static members of the Site counter class can be used for reading and writing data in the site counters. The GetRows method returns a DataSet object filled with the site counter table.
Site counter providers include the AccessDataSource provider and the SQLDataSource Provider. ADO.NET classes are used to read and write onto the tables. Site counter tables are named aspnet_SiteCounters by default.
Going Mobile
ASP.NET 1.x used the Microsoft Mobile Toolkit to code for mobile devices. In ASP.NET 2.0 all controls have a mobile interface. The infrastructure of the server control are now built on a control adapter architecture. There is an adapater for each device and the number of adapters can be added. Since the controls are derived from the adapters no special action is required to be performed. The adapter renders the control intelligently to the device.
The following code is a sample of the code for a nokia device.
< asp:Label id="MyLabel" runat="server" Text="Welcome ExForSys.com" Nokia:Text="Time to upgrade your Nokia phone!" cssClass="StandardStyleClass" Nokia:cssClass="SpecialNokiaStyleClass" / >
The Mechanisms help developers override the built in rendering for mobile devices and provide automatic support with standard controls. However there are some controls which are specifically built for mobile devices. For instance the PhoneLink and Pager controls are exclusively for mobile devices.
It is clear that the direction of development of Web application development is the creation of a seamless, supportive, codeless environment that helps rapid application development and ease of deployment.
General Coding Guidline for .Net
General Coding Guidline for .Net
Importance of coding standards is increasing day by day because of the fact the people work more in teams than as a single coder. The code written by one person may be read by many, including to client for whom the code is written for. This demands the code to be more readable and consistent. By strictly following a coding standard, we can increase the readability of the code by many bounds.
Every group or individual follow their own coding standards. Microsoft provides its own coding standards.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconeventusageguidelines.asp
My style of coding is much like the standards set by Microsoft, however I beg to differ with the software giant in some areas. In this article I am discussing only the some basic concepts, but people who are interested I would suggest them to read the guidelines suggested by MS in link above.
Always remember that coding standards aren’t rules. They are mere suggestions.
1. Naming Conventions
Following a consistent naming pattern is one of the fundamental elements to increase the readability of code. One important aspect in this area is that NEVER use acronym (unless of course that acronym is widely known) or any other short form for variable name.
Note: Use meaningful, descriptive words to name variables etc.
For Example:
String stringAddr; // This is Wrong
String stringAddress; // This is Correct
Microsoft advocates on not using Hungarian notation and prepending datatype to the variable name. Incidentally this is one of areas where I would differ with MS. By attaching the datatype to variable name would allow much more understandability as you write long codes.
For Example:
String stringName;
int intAge;
Note: Never use special characters like “_” in names.
Just like Microsoft I would suggest you to use pascalCase for all local variables and function parameters. As for all global variables, Function name, class name etc, I would suggest you to use CamelCase. However, for constant variables, especially global constants, I would advice you to use full caps. Ex: Const int INTVALUE;
Note: Always make sure to select a name that won’t confuse you with a keyword
General rule for naming namespaces is to use the company name followed by the project name and optional feature or module name.
[CompanyName].[Project].[Module].[subsection]
For Example:
CalpineTechnologies.ProjectCalpine.Accounting
While using exception, we need mostly use ‘e’ as the exception object. However event handlers in Visual Studio .NET tend to use an "e" parameter for the event parameter to the call. To avoid a conflict, its better will use "ex" as a standard variable name for an Exception object.
The naming conventions can be summarized as follows
• Always append datatype to variable name.
• Use pascalCase for local variables.
• Use pascalCase for parameters.
• Use CamelCase for Global Variables;
• Use CamelCase for Class Name, Function Name, Property Names etc.
• Always use meaningful, descriptive names.
• Never use special characters like “_”.
2. Comments
• All Methods Should use XML document comments.
• All other comments in the code should use // style (two slash) instead of “/*”.(of course, VB.Net coders use “’”)
3. Exception Handling
• Never do try catch and do nothing.
For Example , below code is wrong coding practice.
Try
{
// your code
}
catch
{
return;
}
• Always give a friendly message to the user. For your use, you can log the actually error along with all possible details.
• Always use specific exception and not generic
• No need to use exception in all your methods. Use exception where there is possibility for an exception to raise. For example, writing to a file.
4. Some General Practices
• Always place an open curly bracket “{“on a new line. However, in case a block with single line code, you can use it same line.
Example: Both below examples are good styles
public String StringName
{
get{return stringFirstName}
set{string FirstName=value;}
}
public String StringName
{
get
{
return stringFirstName;
}
set
{
stringFirstName=value;
}
}
• Avoid methods with over 25 lines. But it doesn’t mean you should split a 26 lines code into 2. The idea behind this is to keep each function simple.
• Avoid using methods with over 5 arguments. If you need to pass more than 5 arguments, use structures for passing multiple arguments. This increase readability.
• Avoid Files with over 500 lines. Always try keep each file less than 500 lines of code. Of course , this is excluding machine generated code.
• Do not provide public or protected variables. It’s better to use properties. It would restrict the values, range of values passed onto a variable.
• Avoid using multiple namespaces in same file. A single file should contain a single namespace.
• Use String.Empty instead of “”
For Example
string stringAddress=””; // This is wrong
string stringAddress=String.Empty; // This is correct
• When building a long string, always use StringBuilder. This is because string is immutable, and when you use “+” to built string , its infact destroying and creating new string.
Importance of coding standards is increasing day by day because of the fact the people work more in teams than as a single coder. The code written by one person may be read by many, including to client for whom the code is written for. This demands the code to be more readable and consistent. By strictly following a coding standard, we can increase the readability of the code by many bounds.
Every group or individual follow their own coding standards. Microsoft provides its own coding standards.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconeventusageguidelines.asp
My style of coding is much like the standards set by Microsoft, however I beg to differ with the software giant in some areas. In this article I am discussing only the some basic concepts, but people who are interested I would suggest them to read the guidelines suggested by MS in link above.
Always remember that coding standards aren’t rules. They are mere suggestions.
1. Naming Conventions
Following a consistent naming pattern is one of the fundamental elements to increase the readability of code. One important aspect in this area is that NEVER use acronym (unless of course that acronym is widely known) or any other short form for variable name.
Note: Use meaningful, descriptive words to name variables etc.
For Example:
String stringAddr; // This is Wrong
String stringAddress; // This is Correct
Microsoft advocates on not using Hungarian notation and prepending datatype to the variable name. Incidentally this is one of areas where I would differ with MS. By attaching the datatype to variable name would allow much more understandability as you write long codes.
For Example:
String stringName;
int intAge;
Note: Never use special characters like “_” in names.
Just like Microsoft I would suggest you to use pascalCase for all local variables and function parameters. As for all global variables, Function name, class name etc, I would suggest you to use CamelCase. However, for constant variables, especially global constants, I would advice you to use full caps. Ex: Const int INTVALUE;
Note: Always make sure to select a name that won’t confuse you with a keyword
General rule for naming namespaces is to use the company name followed by the project name and optional feature or module name.
[CompanyName].[Project].[Module].[subsection]
For Example:
CalpineTechnologies.ProjectCalpine.Accounting
While using exception, we need mostly use ‘e’ as the exception object. However event handlers in Visual Studio .NET tend to use an "e" parameter for the event parameter to the call. To avoid a conflict, its better will use "ex" as a standard variable name for an Exception object.
The naming conventions can be summarized as follows
• Always append datatype to variable name.
• Use pascalCase for local variables.
• Use pascalCase for parameters.
• Use CamelCase for Global Variables;
• Use CamelCase for Class Name, Function Name, Property Names etc.
• Always use meaningful, descriptive names.
• Never use special characters like “_”.
2. Comments
• All Methods Should use XML document comments.
• All other comments in the code should use // style (two slash) instead of “/*”.(of course, VB.Net coders use “’”)
3. Exception Handling
• Never do try catch and do nothing.
For Example , below code is wrong coding practice.
Try
{
// your code
}
catch
{
return;
}
• Always give a friendly message to the user. For your use, you can log the actually error along with all possible details.
• Always use specific exception and not generic
• No need to use exception in all your methods. Use exception where there is possibility for an exception to raise. For example, writing to a file.
4. Some General Practices
• Always place an open curly bracket “{“on a new line. However, in case a block with single line code, you can use it same line.
Example: Both below examples are good styles
public String StringName
{
get{return stringFirstName}
set{string FirstName=value;}
}
public String StringName
{
get
{
return stringFirstName;
}
set
{
stringFirstName=value;
}
}
• Avoid methods with over 25 lines. But it doesn’t mean you should split a 26 lines code into 2. The idea behind this is to keep each function simple.
• Avoid using methods with over 5 arguments. If you need to pass more than 5 arguments, use structures for passing multiple arguments. This increase readability.
• Avoid Files with over 500 lines. Always try keep each file less than 500 lines of code. Of course , this is excluding machine generated code.
• Do not provide public or protected variables. It’s better to use properties. It would restrict the values, range of values passed onto a variable.
• Avoid using multiple namespaces in same file. A single file should contain a single namespace.
• Use String.Empty instead of “”
For Example
string stringAddress=””; // This is wrong
string stringAddress=String.Empty; // This is correct
• When building a long string, always use StringBuilder. This is because string is immutable, and when you use “+” to built string , its infact destroying and creating new string.
Handle Enter Key in ASP.NET
This is the One of the common requests in ASP.NET is to submit a form when visitor hit an Enter key. That could be a case if, for example you want to make Login Screen. It is expected that user just hit enter when he insert a password instead to of forcing him to use a mouse to click login button. If you want to make search function on your web site, it is frequently required to give a possiblity to hit enter after you insert a search terms instead of mouse click on a Search button.
Here is sample
In classic HTML or ASP pages, it is not hard to submit forms using the enter key. Programmer use a [input' type="submit"> to make a default button. If web site visitor click on that button or press enter key, the form will be submitted.
Off course, you can have a more than one form on your page and individual submit button for every form.
You don't want to submit a form with Enter key?
Rarely, you will need to disable an Enter key and avoid to submit form. If you want to prevent it completely, you need to use OnKeyDown handler on tag of your page. The javascript code should be:
if (window.event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
}
ASP.NET problems with Enter key
If you try to use Enter key in ASP.NET, according to your browser's type, you can get really weird results. Try to place one ASP.NET textbox and a button to the web form. Write a code on a OnClick event of a button. That could be something simple, like:
Response.Write("The button was clicked!");
Now start debuging and write something to textbox. If you press enter while focus is on textbox, form will submit, but your code for button's click event will not be executed.
Stop the debuging and place one simple HTML textbox to the form. You will not write anything in this textbox, so you can make it invisible. Just place this HTML code somewhere inside of your form tag.
input't style="visibility: hidden; position: absolute;" type="text">
Start debuging again. You cannot see the second textbox, and everything looks like before. Try again to write something in visible textbox. If you press enter now, form will submit, and also your code for button's click event will be executed. This is extremelly different behavior, and you did nothing except you placed one inivisible HTML textbox on web form. :)
Maybe it is not elegant, but placing invisible textbox could be simple solution for you if you have only one button on your web form. But, what if you have a different situation? What if you have a few buttons with only one textbox, more than one text box with only one button, or many text boxes and many buttons on form?
Different browsers has a different behaviors in these cases. if you have more buttons, only first button will be "clicked" every time. So, we need some other approach to get an universal solution.
How to make a default button in ASP.NET
We need to specify exactly what button will be "cliked" when visitor press Enter key, according to what textbox currently has a focus. The solution could be to add onkeydown attribute to textbox control:
TextBox1.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('"+Button1.UniqueID+"').click();return false;}} else {return true}; ");
This line of code will cause that button Button1 will be "clicked" when visitor press Enter key and cursor is placed in TextBox1 textbox. On this way you can "connect" as many text boxes and buttons as you want.
Easy solution for default button
There is a free component that allows you to assign a button to the "enter-pressed" client side event of input controls. If you type some text in textbox and press Enter, the form will postback, and the serverside click event of your button is fired.You don't need to write any code You only need to use control's "DefaultButton" property. It you are a beginner programmer this could be a life saver. More about MetaBuilders DefaultButtons Control you can find at http://www.metabuilders.com/Tools/DefaultButtons.aspx
Default buttons in ASP.NET 2.0
ASP.NET 2.0 makes this problems easier and introduce a concept of a "default button". New defaultbutton attribute can be used with [form] or control. What button will be "clicked" depends of where acutally cursor is and what button is choosen as a default button for form or a panel.
Here is sample HTML code that contains one form and one panel control:
[asp:textboxx id="textbox1" runat="server">
[asp:textboxx id="textbox2" runat="server">
[asp:buttonx id="button1" text="Button1" runat="server">
[asp:panelx defaultbutton="button2" runat="server">
[asp:textboxx id="textbox3" runat="server">
[asp:buttonx id="button2" runat="server">
[/asp:panel>
[/form>
Here is sample
In classic HTML or ASP pages, it is not hard to submit forms using the enter key. Programmer use a [input' type="submit"> to make a default button. If web site visitor click on that button or press enter key, the form will be submitted.
Off course, you can have a more than one form on your page and individual submit button for every form.
You don't want to submit a form with Enter key?
Rarely, you will need to disable an Enter key and avoid to submit form. If you want to prevent it completely, you need to use OnKeyDown handler on tag of your page. The javascript code should be:
if (window.event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
}
ASP.NET problems with Enter key
If you try to use Enter key in ASP.NET, according to your browser's type, you can get really weird results. Try to place one ASP.NET textbox and a button to the web form. Write a code on a OnClick event of a button. That could be something simple, like:
Response.Write("The button was clicked!");
Now start debuging and write something to textbox. If you press enter while focus is on textbox, form will submit, but your code for button's click event will not be executed.
Stop the debuging and place one simple HTML textbox to the form. You will not write anything in this textbox, so you can make it invisible. Just place this HTML code somewhere inside of your form tag.
input't style="visibility: hidden; position: absolute;" type="text">
Start debuging again. You cannot see the second textbox, and everything looks like before. Try again to write something in visible textbox. If you press enter now, form will submit, and also your code for button's click event will be executed. This is extremelly different behavior, and you did nothing except you placed one inivisible HTML textbox on web form. :)
Maybe it is not elegant, but placing invisible textbox could be simple solution for you if you have only one button on your web form. But, what if you have a different situation? What if you have a few buttons with only one textbox, more than one text box with only one button, or many text boxes and many buttons on form?
Different browsers has a different behaviors in these cases. if you have more buttons, only first button will be "clicked" every time. So, we need some other approach to get an universal solution.
How to make a default button in ASP.NET
We need to specify exactly what button will be "cliked" when visitor press Enter key, according to what textbox currently has a focus. The solution could be to add onkeydown attribute to textbox control:
TextBox1.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('"+Button1.UniqueID+"').click();return false;}} else {return true}; ");
This line of code will cause that button Button1 will be "clicked" when visitor press Enter key and cursor is placed in TextBox1 textbox. On this way you can "connect" as many text boxes and buttons as you want.
Easy solution for default button
There is a free component that allows you to assign a button to the "enter-pressed" client side event of input controls. If you type some text in textbox and press Enter, the form will postback, and the serverside click event of your button is fired.You don't need to write any code You only need to use control's "DefaultButton" property. It you are a beginner programmer this could be a life saver. More about MetaBuilders DefaultButtons Control you can find at http://www.metabuilders.com/Tools/DefaultButtons.aspx
Default buttons in ASP.NET 2.0
ASP.NET 2.0 makes this problems easier and introduce a concept of a "default button". New defaultbutton attribute can be used with [form] or
Here is sample HTML code that contains one form and one panel control:
[asp:textboxx id="textbox1" runat="server">
[asp:textboxx id="textbox2" runat="server">
[asp:buttonx id="button1" text="Button1" runat="server">
[asp:panelx defaultbutton="button2" runat="server">
[asp:textboxx id="textbox3" runat="server">
[asp:buttonx id="button2" runat="server">
[/asp:panel>
[/form>
Subscribe to:
Posts (Atom)