Sunday, February 20, 2011

AutoEventWireup attribute in ASP.NET

AutoEventWireup attribute in ASP.NET

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

The ASP.NET page framework supports an automatic way to associate page events and methods. If the AutoEventWireup attribute of the Page directive is set to true, the page framework calls page events automatically, specifically the Page_Init and Page_Load methods. In that case, no explicit Handles clause or delegate is needed.

AutoEventWireup is an attribute in Page directive.
AutoEventWireup is a Boolean attribute that indicates whether the ASP.NET pages events are auto-wired.
AutoEventWireup will have a value true or false. By default it is true.
There is no event or method associated with Page_Load. Those events whose inline event is not there but that should be executed, for that purposed AutoEventWireup="true".

Disadvantages of AutoEventWireup attribute

AutoEventWireup uses fixed naming convention for the events. Page events handlers have specific predictable names. This limits your flexibility in how you name event handlers.
If you do set AutoEventWireup to true, Visual Studio will generate code to bind the events and the page framework will automatically call events based on their names. This can result in the same event code being called twice when the page runs. As a consequence, you should always leave AutoEventWireup set to false when working in Visual Studio.
Another disadvantage is that performance is adversely affected, because ASP.NET searches for methods at run-time. For a Web site with high traffic volumes, the impact on performance could be significant.
AutoEventWireup="true" target is for page events only. In case of AutoEventWireup method are not case sensitive. (Page_Load or page_load both will work).

If AutoEventWireup="false" but still you want to executed Page event (Page_Load). In this you have to explicitly code for it.

< form id="form1" runat="server" onload="Page_Load">

Monday, February 14, 2011

Forms Authentication in Asp .net

Introduction:

Security is one of the most important component of any application. Security is even more important when you are making a web application which is exposed to million of users. Asp.net provides classes and methods that ensure that the application is secure from outside attacks. In this article we will investigate the Forms authentication in Asp.net which provides a powerful way of securing applications.
Setting the forums authentication

First you need to set up the forms authentication in the web.config file. If you see in the web.config file there will be a tag like this:

< authentication mode="Windows" />

By default it is set to the Windows authentication mode in order to change this to forms authentication you will just need to change the windows to forms as I have shown below:


Now you have set your application to use the features of the forms authentication instead of the windows authentication.

Storing username and password in the Web.config file:

If you have very few users that needs to use the application than you can set the username and passwords in the web.config file.

< authentication mode="Forms">
< forms loginUrl="Login.aspx">
< credentials>
< user name="Joe" password="Smith" />
< /credentials>
< /forms>
< /authentication>


You will see some new tags and attributes above lets explain all of them:

The tag forms has an attribute loginUrl which is the url of the page the users will be redirected if they try to access an authorized page. In this case we have given the url as Login.aspx which means that if some user is trying to access some page and he is not signed in he will be redirected to the Login.aspx page.

Later we have the credentials tag which has attributes username and password. The username and password is simply the username and password for a particular user. All the usernames and passwords that are present in the web.config files < credentials> tag will be authorized to user the pages.

You can have multiple user name and password stored in a single web.config file. As you can see in the code below I have stored 2 username and their passwords:

< authentication mode="Forms">
< forms loginUrl="Login.aspx">
< credentials>
< user name="Joe" password="Smith" />
< user name="azam" password="hello" />
< /credentials>
< /forms>
< /authentication>


Now you got the username and passwords stored in the web.config file and now you want to authenticate the user depending on the credentials present in the web.config file. Let's set one more thing up which is the authorization tags in the web.config file.

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


The deny users = "?" means that all the other users whose name is not present in the web.config file must not be able to access the pages.

Lets make a simple login screen that lets the user enter his credentials:

Suppose you are too lazy to change your page name from WebForm1 to Login.aspx. Now if you run the page you will see an error that there is no Login.aspx page. You will be surprised that what is asp.net looking for Login.aspx page. The reason is that because you told the Asp.net that the login page will be named Login.aspx remember:

< forms loginUrl="Login.aspx">

Now if you change the name of your page to Login.aspx it will work fine. You can also change the loginUrl = WebForm1.aspx to make it work but making a Login.aspx page sounds much better.

Now we need to implement the button click code:

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

if(FormsAuthentication.Authenticate(txtUserName.Text,txtPassword.Text))

{

FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,false);

}

else

{

Label3.Text = "you are not authorized to view the page";

}

}


We simply used the FormsAuthentication.Authenticate() method and supplied it with the username and password. These username and password will be checked against the web.config file. If the username and password are present inside the web.config file than the user will be authorized and will be taken to the originally requested Url. If the person is not authorized than a message will be printed that "You are not authorized to view the page".

Cookie Expiration:

You can also expire the cookies that you make in your application. Setting the time for the cookie expiration is not difficult at all. Lets see the following code and see what it does:

Lets first make a simple cookie that will hold the user's username and than set its expiration time in days:

HttpCookie myCookie = new HttpCookie("UserName");

myCookie.Value("UserName") = txtName.Text;

myCookie.Expires = DateTime.Now.AddDays(1);

Response.Cookies.Add(myCookie);


As we can see in the code sample above that making and setting the expiration time for the cookie is not difficult at all. You can also use FormsAuthentication Ticket to assign the expiration time of the cookie.

This method is good if you dont want the user to be logged on all the times. Its also safe from the security point of view cause it will expire in 1 day.

Database Authentication:

If you have a larger system you will be better off using the Database to keep the UserNames and passwords. You can use a simple SQL Stored procedure which returns 1 or 0 for success and failure depending on the username and password supplied. A simple database validation method can be written as follows:

private bool IsUserAuthenticated(string username,string password)
{

// Make database connection

* /*// set up the Sql Server Stored procedure

* CREATE PROC [GetUserID]

* @PersonID int OUTPUT,

* @UserName nvarchar(50),

* @Password nvarchar(50)

*

* AS

*

* SELECT @PersonID = PersonID WHERE UserName = @UserName AND Password = @Password;

*

*/// exeucte the command



}
// return false;// else // return true; // if(personID > 0 ) // Attach the parameters, should also have output parameters to return a value




Signing out a user Securely:
Let's see how we can implement a simple signout method. The logic behing the sign out is to expire the user cookie.

FormsAuthentication.SignOut();

Response.Cookies["UserName"].Value = null;

// The date can be anything which has already passed

Response.Cookies["UserName"].Expires = new System.DateTime(1999,10,12);

Response.Redirect("Whateverpage.aspx");


As you can see the code above is pretty simple and straight forward. The FormsAuthentication class provides a signout method which can be used to signout users.

Later we assign null to the cookie and expired the cookies date by assigning it a date which has already passed. After signout the user I simply redirected the user to another page.

Client side Validation

Don't leave all the things for your business logic and then for the database to decide. Do all the validation before you send the data to the business layers and the database layers. For this you can always use RequiredFieldValidators to check that if the required fields are not left blank.

ASP.net Tips

1.Smart navigation

Smart navigation is a little-known Internet Explorer feature that enables the individual controls on your Web forms to maintain focus between postback, as well as allows you to suppress that flicker that occurs as you load the new page.
To turn on this little-known feature, simply set the smartNavigation property of your ASPX page to True. You can also apply the property to all project pages, by adding the tag to the following location within your Web.config file:

< configuration>
< system.web>
< pages smartNavigation="true"/>
< /system.web>
< /configuration>

Note that smart navigation works on only Internet Explorer 5 and above; however, ASP.NET will automatically detect this and serve up the ?smart? code only if the target browser supports it.

Also, I?d personally advise that you test it against any third-party menu controls or scripts you may have running: it is prone to falling over on particularly advanced pages.


2.Stopping Your User from Right-Clicking


Want to prevent your user from performing any of the other commands available by right-clicking on a Web page in Internet Explorer? It?s not foolproof, but this neat little HTML edit usually does the trick.

Just alter the opening < body> tag of your HTML to the following:

< BODY oncontextmenu="return false" >
When the menu is requested, the oncontextmenu event runs, and we instantly cancel it using JavaScript. This is especially potent as a method for stopping the user from viewing your source, when used in conjunction with a menu-less browser window. Great stuff!

3.Creating Images Dynamically

Ask any ASP developer who has ever tried to dynamically create his own images and he?ll tell you it?s a nightmare. In fact, it?s more than a nightmare. It?s practically hell. The only true solution? Reverting to an expensive, dodgy, third-party control to do the work for you.

With ASP.NET, however, you can develop your own dynamic images with ease. Simply create an image object and use the new GDI+ features to add objects to that image, such as text, rectangles, and ellipses. After that, you can simply stream straight back down to the client.

But covering the graphics features in depth would require at least another two books, and, unfortunately, we don?t have that much room. So, I?m going to share a sample that demonstrates creating a small ?Drawing? button, alongside a little blue-and-yellow bullet point.It?s the sort of personalized graphic you?ll find on sites such as Amazon.com.

Here?s the code:

Bitmap objBitmap = new Bitmap(120, 30);
Graphics objGraphics = Graphics.FromImage(objBitmap);
objGraphics.FillRectangle(new SolidBrush(Color.LightBlue), 0, 0, 120, 30);
objGraphics.FillEllipse(new SolidBrush(Color.Blue), 3, 9, 10, 10);
objGraphics.FillEllipse(new SolidBrush(Color.Yellow), 4, 10, 8, 8);
objGraphics.DrawString("Drawing", new Font("Tahoma", 8), new SolidBrush(Color.Green), 16, 8);
Response.Clear();
Response.ContentType = "image/jpeg";
objBitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
objGraphics.Dispose();
objBitmap.Dispose();

You can put it inside any event you want.

4.Clear All The Textbox Values (Reset Function)

In Classic ASP, to clear all the textboxes in a form, to start over, we just had to use a simple html 'Reset' button in the form. Sometimes that works in ASP.Net;sometimes it doesn't.

Here are a couple of ways to do this, iterating through the ASP.Net TextBox controls in a form --
Just create a Reset type subroutine - in that routine, use the following code:
in C# - it would be:

Control myForm = Page.FindControl("Form1");
foreach (Control ctl in myForm.Controls)
if(ctl.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox"))
((TextBox)ctl).Text = "";

This will clear EVERYTHING from the textboxes - even if you had them pre-populated with data. A VERY simple way to just reset it to the condition at Page_Load time, just do this in the Reset SubRoutine:

Server.Transfer("YourPageName.aspx");

5.Pressing Enter key


Sometimes, you will notice, that, in an ASP.Net form, depending on the circumstances, pressing the 'Enter' key to submit the form does not work.

To force this to happen for a particular button on your page, just put this in the Page_Load routine:

Page.RegisterHiddenField("__EVENTTARGET", "button1")

Then, change 'button1' to the ID of your particular button. Understand, of course, if your cursor is inside of a MultiLine textbox, the default action of the enter key is to create a new line in the textbox, so, if this basically works anywhere outside of that scenario.

6.ASP.Net Server Controls Not Showing on pages


It's possible that ASP.Net is not registered correctly on your system.Try running aspnet_regiis from the command prompt.

Here's the default location:

C:\WINNT\Microsoft.NET\Framework\<< ASP.Net Version#>>\aspnet_regiis.exe -i

Windows Server 2003, you must use aspnet_regiis -i -enable. This is because of the "Web Service Extensions" feature in IIS 6

7.Where To Store Database Connection

Let's say you have a database connection (or several) that you will be using over and over. Yes, you can manually copy/type it in on every ASP.Net page - BUT - an easier way is to store it in the Web.Config file (formerly config.web) and then refer to it in the code.

In Web.Config, you would add a key to the AppSettings Section:

< appSettings>
< add key="MyDBConnection" value="server=YourServer;uid=Username;pwd=Password;database=DBName" />
< /appSettings>

for OleDb - use Absolute Path - Not Server.MapPath:
< add key="NWOleDB" value= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Inetpub\wwwroot\data\northwind.mdb;" />

Then, in your ASP.Net application - just refer to it like this:

SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings("MyDBConnection"));

8.Focusing on a certain control:

If you ever noticed by going to google that google automatically focuses on the textbox when you visit the page. This is very useful feature which lets the developer to quickly fill the form. Let's see how we can focus on a textbox control on the page load.

In the example we will just have a single TextBox on the form which will be named "TextBox1".

Just type this code in the Body of the Html.

< body onload="document.forms[0]['TextBox1'].focus();" MS_POSITIONING="GridLayout">




Now if you load the page you will see that the focus is set on the TextBox control.

Wednesday, February 9, 2011

How to uncheck checkboxlist

place this code inside eventHandler that you want to uncheck checkboxlist

foreach (ListItem li in cblMulti.Items)
{
li.Selected = false;
}

Tuesday, February 8, 2011

Add a Row Number to the GridView

Here’s a simple way to add a Row Number to the GridView. Just add the following tags to your section of your GridView

< Columns>
< asp:TemplateField HeaderText="RowNumber">
< ItemTemplate>
<%# Container.DataItemIndex + 1 %>
< /ItemTemplate>
< /asp:TemplateField>
...
< /Columns>

and you will get the following output

How to populate a DropDownList with Culture-specific Month names

DateTimeFormatInfo.MonthNames is a useful property to fetch the culture-specific full names of the month. This property gets a string array containing the names of the month. Remember to add a reference to the System.Globalization namespace.

Here’s how to use this property and populate a DropDownList with month names:

string[] names = DateTimeFormatInfo.CurrentInfo.MonthNames;
DropDownList1.DataSource = names;
DropDownList1.DataBind();

Sunday, February 6, 2011

Reset values of all controls using ASP.NET 2.0

Using ASP.NET
Step 1: Drag and drop a few controls like textboxes, radio buttons, checkboxes etc. on to the form
Step 2: Add a button to the form and rename its Text property as “Clear all controls using ASP.NET”. Rename its id property to be “btnClearASP”.
Step 3: Double click the button. In its click event, call a method that will clear the content of the controls on a Page.

Button click event

protected void btnClearASP_Click(object sender, EventArgs e)
{
ResetFormControlValues(this);
}


Write code for this method

private void ResetFormControlValues(Control parent)
{
foreach (Control c in parent.Controls)
{
if (c.Controls.Count > 0)
{
ResetFormControlValues(c);
}
else
{
switch(c.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
((TextBox)c).Text = "";
break;
case "System.Web.UI.WebControls.CheckBox":
((CheckBox)c).Checked = false;
break;
case "System.Web.UI.WebControls.RadioButton":
((RadioButton)c).Checked = false;
break;

}
}
}
}

Thursday, February 3, 2011

Improve Performance Of Website

1. Maintain the position of the scrollbar on postbacks: In ASP.NET 1.1 it was a pain to maintain the position of the scrollbar when doing a postback operation. This was especially true when you had a grid on the page and went to edit a specific row. Instead of staying on the desired row, the page would reload and you'd be placed back at the top and have to scroll down.

2. Set the default focus to a control when the page loads: This is another extremely simple thing that can be done without resorting to writing JavaScript. If you only have a single textbox (or two) on a page why should the user have to click in the textbox to start typing? Shouldn't the cursor already be blinking in the textbox so they can type away? Using the DefaultFocus property of the HtmlForm control you can easily do this.

3. Set the default button that is triggered when the user hits the enter key:
This was a major pain point in ASP.NET 1.1 and required some JavaScript to be written to ensure that when the user hit the enter key that the appropriate button on the form triggered a "click" event on the server-side. Fortunately, you can now use the HtmlForm control's DefaultButton property to set which button should be clicked when the user hits enter. This property is also available on the Panel control in cases where different buttons should be triggered as a user moves into different Panels on a page.

4. Validation groups: You may have a page that has multiple controls and multiple buttons. When one of the buttons is clicked you want specific validator controls to be evaluated rather than all of the validators defined on the page. With ASP.NET 1.1 there wasn't a great way to handle this without resorting to some hack code. ASP.NET 2.0 adds a ValidationGroup property to all validator controls and buttons (Button, LinkButton, etc.) that easily solves the problem. If you have a TextBox at the top of a page that has a RequiredFieldValidator next to it and a Button control, you can fire that one validator when the button is clicked by setting the ValidationGroup property on the button and on the RequiredFieldValidator to the same value. Any other validators not in the defined ValidationGroup will be ignored when the button is clicked.

Folders in ASP.NET

There are seven new folders introduced in ASP.NET 2.0 :

\App_Browsers folder – Holds browser definitions(.brower) files which identify the browser and their capabilities.

\App_Code folder – Contains source code (.cs, .vb) files which are automatically compiled when placed in this folder. Additionally placing web service files generates a proxy class(out of .wsdl) and a typed dataset (out of .xsd).

\App_Data folder – Contains data store files like .mdf (Sql Express files), .mdb, XML files etc. This folder also stores the local db to maintain membership and role information.

\App_GlobalResources folder – Contains assembly resource files (.resx) which when placed in this folder are compiled automatically. In earlier versions, we were required to manually use the resgen.exe tool to compile resource files. These files can be accessed globally in the application.

\App_LocalResources folder – Contains assembly resource files (.resx) which can be used by a specific page or control.

\App_Themes folder – This folder contains .css and .skin files that define the appearance of web pages and controls.

\App_WebReferences folder – Replaces the previously used Web References folder. This folder contains the .disco, .wsdl, .xsd files that get generated when accessing remote web services.

Dynamically Adding Meta Tags in ASP.NET

Custom Adding Title Tag :
Me.Header.Title = "Title Of Page Here"

Custom Adding Meta Tag :
Dim metaDescription As New HtmlMeta()
metaDescription.Name = "description"
metaDescription.Content = "A description of the page here."
Me.Header.Controls.Add(metaDescription)

Custom Adding Style :
Dim styles As New HtmlGenericControl("style")
styles.Attributes.Add("type", "text/css")
styles.InnerText = "p { font-weight: bold; }"
Me.Header.Controls.Add(styles)

Dim style As New Style()
style.ForeColor = System.Drawing.Color.Navy
style.BackColor = System.Drawing.Color.LightGray
Me.Header.StyleSheet.CreateStyleRule(style, Nothing, "body")

Custom Adding Css Style:
Dim cssLink As New HtmlLink()
cssLink.Href = "styles.css"
cssLink.Attributes.Add("rel", "Stylesheet")
cssLink.Attributes.Add("type", "text/css")
Me.Header.Controls.Add(cssLink)

Custom Adding Java Script:
Dim javaScript As New HtmlGenericControl("script")
javaScript.Attributes.Add("type", "text/javascript")
javaScript.InnerText = "alert('Hello World!');"
Me.Header.Controls.Add(javaScript)

All the above code should be used within page Page_Load event

Tuesday, February 1, 2011

Execute Commands Methods: How to use it?

We have 4 types of Exceute methods, through which we can excecute the quries angainst Database.
1). ExecuteNonQuery(()
2). ExecuteReader()
3). ExecuteScalar()
4). ExceuteXmlReader()


1). ExecuteNonQuery(()
Explanation: Executes a command but does not return any value or output
usage conditions: UPDATE, INSERT, DELETE statements

using System;
using System.Data;
public class exampleone
{
publis static void main(string[] args)
{
string source="server=(local);" +
"integrated security=SSPI;"+
"databs=dbNAME";

string select="UPDATE table set name='newname' where name='raj'";

SqlConnection conn = new SqlConection(source);
conn.Open();
SqlCommand cmd = new SqlCommand(select,conn);
int rowsreturn = cmd.ExecuteNonQuery();
Response.Write(rowsreturn);
conn.Close();
}
}

2). ExecuteReader()
Explanation: Executes a command and returns a typed data reader object.
usage conditions: Display Data

using System;
using System.Data;
public class exampletwo
{
publis static void main(string[] args)
{
string source="server=(local);" +
"integrated security=SSPI;"+
"databs=dbNAME";

string select="SELECT * from Tablename";

SqlConnection conn = new SqlConection(source);
conn.Open();
SqlCommand cmd = new SqlCommand(select,conn);
SqlDataReader reader = cmd.ExecuteReader();
while(dr.Read())
{
Response.write(dr[0].ToString());
}

}
}


3). ExecuteScalar()
Explanation: Executes a command and returns a single result.
usage conditions: count of records, time etc.

using System;
using System.Data;
public class exampletwo
{
publis static void main(string[] args)
{
string source="server=(local);" +
"integrated security=SSPI;"+
"databs=dbNAME";

string select="SELECT count(*) from Tablename";

SqlConnection conn = new SqlConection(source);
conn.Open();
SqlCommand cmd = new SqlCommand(select,conn);
object o = cmd.ExecuteScalar();
Response.write(o);

}
}


4). ExecuteXmlReader()
Explanation: Executes a command and returns a XmlReader Object.

using System;
using System.Data;
using System.Xml
public class exampletwo
{
publis static void main(string[] args)
{
string source="server=(local);" +
"integrated security=SSPI;"+
"databs=dbNAME";

string select="SELECT name,address from Tablename FOR XML AUTO ";

SqlConnection conn = new SqlConection(source);
conn.Open();
SqlCommand cmd = new SqlCommand(select,conn);
XmlReader xr = cmd.ExecuteXmlReader();
xr.read();
do
{
s = xr.ReadOuterXml();
if(s!=="")
Response.Write(s);
} while (s!="");
conn.Close();
}
}

Ajax CalendarExtender displaying at wrong position in Chrome

< script type ="text/javascript" language ="javascript">     function onCalendarShown(sender, args)...