Thursday, November 29, 2007

Authenticating Users with ASP.NET AJAX



ASP.NET 2.0 provides built-in membership management capabilities that allow applications to log users into and out of a Web site with minimal coding. Simply run the aspnet_regsql.exe tool to add Microsoft's membership database into your chosen database server (otherwise, a SQL Server 2005 Express database will be used), add a few lines of configuration code in web.config to point to your database, drag on a few controls such as the Login and CreateUserWizard controls, and you're ready to go!

However, each time a user logs in to your application, a postback operation occurs which, in some situations, may not be desirable. In cases where you'd like to log users into a Web site without performing a complete postback of a page, you can use the ASP.NET AJAX authentication service instead.

The authentication service consists of a service that lives on the Web server that accesses membership information from the database, as well as a client-side class named AuthenticationService (located in the Sys.Services namespace) that is built into the ASP.NET AJAX script library. The AuthenticationService class knows how to call the membership service using the XmlHttpRequest object behind the scenes.
To use the AuthenticationService class to log users in or out of a Web site, you must first enable the authentication service on the server. This is done by adding code into web.config as shown below.


NOTE: instead of '<' symbol i have used '[' and for '>' I have used ']' symbol.


[system.web.extensions]
[scripting]
[webServices]
[authenticationService enabled="true" /]
[/webServices]
[/scripting]
[/system.web.extensions]

This code enables calls to a file named _AppService.axd to be made behind the scenes and allows membership credentials to be passed and validated. _AppService.axd doesn't actually exist as a physical file; it's really an alias for an HttpHandler named ScriptResourceHandler that's responsible for handling log-in and log-out functionality within ASP.NET AJAX applications. ScriptResourceHandler is configured automatically when you create an ASP.NET AJAX-enabled Web site in Visual Studio .NET 2005, as shown in the following code:

[httpHandlers]
...
[add verb="*" path="*_AppService.axd" validate="false"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions,
Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/]
...
[/httpHandlers]

Once you've enabled the ASP.NET AJAX authentication service in web.config you can use the client-side AuthenticationService class to log users into a Web site using an asynchronous postback operation. The AuthenticationService exposes login() and logout() methods, as well as several different properties.

1 defaultFailedCallback : Gets or sets the default failure callback method.
2 defaultLoginCompletedCallback: Gets or sets the default login callback method.
3 defaultLogoutCompletedCallback: Gets or sets the default logout callback method.
4 isLoggedIn : Used to determine if the user is currently logged into the application or not.
5 path : Gets or sets the authentication service path.
6 timeout : Gets or sets the authentication service time-out value.

The AuthenticationService's login() method performs an asynchronous postback operation that calls the ScriptHandlerFactory HttpHandler mentioned earlier to log a user into a Web site. The overall process still involves setting a cookie containing the ASP.NET membership authentication ticket in it as with standard ASP.NET applications, but the cookie is set without reloading the entire page. The login() method accepts several different parameters, as shown here:

1 userName The user name to authenticate.
2 password User password to use while authenticating.
3 isPersistent Determines if the issued authentication ticket should be persistent across
browser sessions. The default is false.
4 customInfo Reserved by Microsoft for future use. Defaults to null.
5 redirectUrl The URL to redirect the browser to on successful authentication. If null, no
redirect occurs. The default is null.
6 loginCompletedCallback The method to call when the login has finished successfully. The
default is null.
7 failedCallback The method to call if the login fails. The default is null.
8 userContext User context information that you are passing to the callback methods.

You can see that login() takes quite a few parameters, although several of them are optional. The key parameters are userName, password and loginCompletedCallback.


the AuthenticationService's login() method to attempt to log a user into a Web site. The code first calls the AuthenticationService class's login() method and passes in the user name, password, log-in completed callback handler and failure handler.

If the log-in attempt completes successfully, the method named OnLoginCompleted() is called. You know if the user successfully logged in or not by checking the isValid parameter. If the log-in attempt fails due to the service being unavailable or other circumstances, the OnLoginFailure() method is called, letting the user know that they're not able to log in at this time.

To log a user out of a Web site, you can call the AuthenticationService's logout() method. Be aware that this method will cause a full-page postback operation to occur to ensure that the authentication cookie is properly removed from the user's browser. This is standard behavior, so don't waste any time trying to figure out why an asynchronous postback isn't occurring. Parameters that the logout() method accepts are shown here:

1 redirectUrl The URL to redirect the browser to on successful logout. The default is null.
2 logoutCompletedCallback The method that is called when the logout has finished. The default
is null.
3 failedCallback The method that is called if the logout has failed. The default is null.
4 userContext User context information that you are passing to the callback methods.


Calling the logout() method to remove the authentication cookie from the users browser and log them out of a Web site. It defines a log-out completed callback method, as well as a failure callback method.


ASP.NET 2.0 membership management

Membership and Role Manager Providers - ASP.NET 2.0 now includes built-in support for membership (user name/password credential storage) and role management services out of the box. Because all of these services are provider-driven, they can be easily swapped out and replaced with your own custom implementation.


Login Controls - The new login controls provide the building blocks to add authentication and authorization-based UI to your site, such as login forms, create user forms, password retrieval, and custom UI for logged in users or roles. These controls use the built-in membership and role services in ASP.NET 2.0 to interact with the user and role information defined for your site.

Monday, November 26, 2007

Introduction to .NET 3.0 for Architects


Check this site to know .NET 3.0 Architecture

ASP.NET 2.0 New Features

Click this link to see the features

ASP.NET Tips

Tip: Do not use the AutoPostBack attribute on the DropDownList control to simply redirect to another page.
There are probably cases when this might make sense, but for the most part it is overkill. Using the autopostback for a redirect requires extra roundtrip to the server. First the autopostback returns to the server and processes everything up to the event handling the postback. Next a Response.Redirect is issued which goes back to the client requesting the client use another page. So you end up with two separate requests + processing just to get a user to another page.
Using the onchange event of the select element, we can do this all on the client. In the sample below, I am simply redirecting to the current page with an updated querystring element. Your logic will vary, but in the case below, I am avoiding the zero index.
0) { window.location = window.location.pathname + '?t=' + this[this.selectedIndex].value;}" />

Tip: Never use the ASP.Net Label control.
Ever is a strong word, but except for some quick and dirty style hacks you should never ever use this control. Any text is rendered inside a span control which is usually unnecessary and complicates any CSS styling you may be trying to use. In most cases, you can replace the Label with a Literal and achieve the same results.

Tip: Use the ASP.Net Repeater instead of DataList, DataGrid, and DataView controls
The Repeater is the single most powerful control shipped in ASP.NET. It is versatile and lightweight. There are times (especially prototyping) when the other databound controls make sense to use, but they generate a lot of extra markup and generally complicate the page with all of their events and styling. Using the Repeater, you may write a little more code up front, but you will be rewarded in the long run.

Tip: Understand how to effectively use caching.
By now, most ASP.NET developers know about the Cache. Most examples show the virtue of caching for hours at a time. Very little data that is worth the effort to display on a web page requires caching for this long. The main reasons for caching are performance related. Memory in ASP.NET is still a very limited resource. Do not waste it by caching anything more than a couple of minutes unless it is very expensive to regenerate.

Tip: Always set a memory threshold for your AppPool.
A related tip would be to first understand the total memory available on your box: how many sites are there, is SQL running locally? Is there anything else on this box which will consistently use Memory?
In most cases, you should never set the available memory for an AppPool above 800mb's unless you can also set the 3/gb switch (then you can use about 1200mb). Allowing memory to go unchecked or set about 800mb can bring even a moderately sized site to it's knees once too much memory is used.

Tip: Use AppOffline.htm for updates
If you are making any changes to files in your bin directory, always use the AppOffline.htm file. It is very likely that while you uploading (or copy & pasting) your updates, users will see an error message. It is much better to show them one that you purposely created and can explain the situation vs. the built in ASP.NET error pages (or even your own customError page). In addition, this will help prevent the locking .dll issue that is not supposed to exist anyway.

Tip: Always check Page.IsValid in your button's EventHandler.
Just because you are using ASP.Net validation controls, do not assume the page could not be submitted with invalid data.
Also, just because you hide a control, do not assume buttons/textboxes/etc on it are not submit-able. It is perfectly fine to hide a control that a user should not access, but with very little code (or using a third party tool) users can easily make an HttpPost with any data they choose.

Tip: When redirects are permanent, use a 301 status code.
This use to be a little more manual, but with ASP.NET 2.0, it is even easier:
Response.RedirectLocation = "http://site.com/newlink.aspx";Response.End();

Tip: To create fully qualified URLs, use the new VirtualPath class.
string relativePath = "~/somefolder/test/123.aspx"Uri newUri = new Uri(Request.Url, VirtualPathUtility.ToAbsolute(relativePath));
Again, please add any other suggestions below. I am looking forward to reading them.