Hash password in ASP.NET a Simple way

We all know that storing password in plain text is not a professional or should I say Ethical approach by any means. If you are a student then still follow the line. Passwords can be stored in two ways either using Encryption or by Hashing. Encryption normally allows conversion to original text as you know be Decryption which still is not just as per my opinion. We would like to have a system that stores password in a one-way mode and if forgotten a new password should be sent to the user, without knowing the old password. Fortunately, it’s very easy to hash passwords in ASP.NET (and C# and Visual Basic in general).

So how to do it?

Microsoft has provided a very simple method of FormsAuthentication class that cn Hash the password with SHA-1, well SHA-1 is recommended by most security experts, so I will use this.

public static string PasswordHasher(string Password)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(Password, System.Web.Configuration.FormsAuthPasswordFormat.SHA1);
}

The above method will take a password that you enter and run it through the encryption function provided using the SHA1 format. You’ll get back a string with the generated hash of your password. Well that’s it we can also use SALT with this to make it more secure but lets keep it simple for now.

Free ASP.NET 4 and VS 2010 Beta Hosting


MaximumASP

MaximumASP is offering a free hosting account so you can get started with ASP.NET 4 and Visual Studio 2010.

On this account you can test ASP.NET 4 applications in a hosting environment and try out the new publishing features with Visual Studio 2010 and the Microsoft Web Deployment Tool.

  • Windows Server 2008 R2 / IIS 7.5
  • .NET Framework 4 Beta 2
  • 1GB disk space
  • 50 MB SQL Server 2008 database
  • MS Deploy Access
  • FTP over SSL Access

The environment on which your apps will be running is a slimmed down version of our robust MaxESP platform. Experience some of the platform’s features such as instant scaling, application aware load-balancing, and the IIS Remote Manager. If you like what you see during the ASP.NET 4 beta, sign up for a full account. We would love to have you.

http://aspnet4beta.maximumasp.com/

MCTS 70-562, ASP.NET 3.5 Application Development

In this post I would be covering some Tips, Study material, Registration process and Discount options about this exam that is MCTS 70-562. This certification exam measures your ability to develop applications using ASP.NET in a development environment that uses Microsoft Visual Studio 2008 and Microsoft .NET Framework 3.5. I started studying for this exam right after I passed the MCTS 70-536 Application Development Foundation. I passed the 70-536 with 884/1000.

The test had 50 questions in total covering different topics from User controls, Mobile controls, Debugging and troubleshooting, Server controls etc. With some detailed study and experience in the industry I managed to pass this with 1000/1000 yes that’s 100%.

Registering for the Exam:

You can register for this exam by following this link http://www.register.prometric.com/
After selecting the country you will be given registered test centers in Pakistan. If you don’t have an account create one and complete the registration form. If you don’t have the Credit Card its better to call the test center and they may help you in this regard.

Remember Passport is a must for candidates from Pakistan

Discount Vouchers:

Testing fee is 50USD but thanks to discount vouchers scheme I got 10% for first exam and for second got 20% discount. Microsoft offers promotions periodically for different exams, previously it was Second Shot offer running but at the time of writing you can benefit from the Discount Vouchers. You can get 15, 20, 25% discount depending upon your choice of exam, more at http://www.prometric.com/microsoft/careeroffer.htm

Study Materials

To preMCTS 70-562pare for this exam the best recommended book is MCTS Self-Paced Training Kit (Exam 70-562): Microsoft .NET Framework 3.5 – ASP.NET.This book comprises of  16 chapters in total starting from Introduction to ASP.NET 3.5, Server controls, Performing validations, Site navigation, State management, ADO.NET, XML, LINQ, Services, Monitoring, Troubleshooting, ASP.NET mobile applications and finally Deploying, Configuring and Caching applications. Each chapter may consist of 2 or more lessons and after every lesson there are some practice questions available as well.

As a reference book I also studied Programming Microsoft ASP.NET 3.5 by Dino Esposito.

Audience Profile
Candidates for this exam use Microsoft Visual Studio in a team-based, medium-sized to large development environment. Candidates should have a minimum of two to three years of experience developing Web-based applications by using Microsoft ASP.NET. Candidates should also have a minimum of one year of experience with the following:

* Database access by using Microsoft ADO.NET classes in the Microsoft .NET Framework
* Web services
* State management
* ASP.NET configuration
* Monitoring Web applications
* Debugging
* Application and page life-cycle management
* Security aspects such as Forms Authentication and membership and roles
* ECMAScript (JavaScript, Microsoft JScript)
* Internet Information Server (IIS)

Candidates should be very familiar with Visual Studio 2005 or later and the .NET Framework classes that are related to ASP.NET and ADO.NET. In addition, candidates should have a good grasp of ASP.NET AJAX.

Skills Measured

Skills Being MeasuredThis exam measures your ability to accomplish the technical tasks listed below.The percentages indicate the relative weight of each major topic area on the exam. Configuring and Deploying Web Applications (10 percent)

  • Configure providers. May include but is not limited to: personalization, membership, data sources, site map, resource, security

  • Configure authentication, authorization, and impersonation. May include but is not limited to: Forms Authentication, Windows Authentication

  • Configure projects, solutions, and reference assemblies. May include but is not limited to: local assemblies, shared assemblies (GAC), Web application projects, solutions

  • Configure session state by using Microsoft SQL Server, State Server, or InProc. May include but is not limited to: setting the timeout; cookieless sessions

  • Publish Web applications. May include but is not limited to: FTP, File System, or HTTP from Visual Studio

  • Configure application pools.

  • Compile an application by using Visual Studio or command-line tools. May include but is not limited to: aspnet_compiler.exe, Just-In-Time (JIT) compiling, aspnet_merge.exe

Consuming and Creating Server Controls (20 percent)

  • Implement data-bound controls. May include but is not limited to: DataGrid, DataList, Repeater, ListView, GridView, FormView, DetailsView, TreeView, DataPager

  • Load user controls dynamically.

  • Create and consume custom controls. May include but is not limited to: registering controls on a page, creating templated controls

  • Implement client-side validation and server-side validation. May include but is not limited to: RequiredFieldValidator, CompareValidator, RegularExpressionValidator, CustomValidator, RangeValidator

  • Consume standard controls. May include but is not limited to: Button, TextBox, DropDownList, RadioButton, CheckBox, HyperLink, Wizard, MultiView

Working with Data and Services (17 percent)

  • Read and write XML data. May include but is not limited to: XmlDocument, XPathNavigator, XPathNodeIterator, XPathDocument, XmlReader, XmlWriter, XmlDataDocument, XmlNamespaceManager

  • Manipulate data by using DataSet and DataReader objects.

  • Call a Windows Communication Foundation (WCF) service or a Web service from an ASP.NET Web page. May include but is not limited to: App_WebReferences; configuration

  • Implement a DataSource control. May include but is not limited to: LinqDataSource, ObjectDataSource, XmlDataSource, SqlDataSource

  • Bind controls to data by using data binding syntax.

Troubleshooting and Debugging Web Applications (16 percent)

  • Configure debugging and custom errors. May include but is not limited to: ,

  • Set up an environment to perform remote debugging.

  • Debug unhandled exceptions when using ASP.NET AJAX. May include but is not limited to: client-side Sys.Debug methods; attaching a debugger to Windows Internet Explorer

  • Implement tracing of a Web application. May include but is not limited to: Trace.axd, Trace=True on @Page directive,

  • Debug deployment issues. May include but is not limited to: aspnet_regiis.exe; creating an IIS Web application; setting the .NET Framework version

  • Monitor Web applications. May include but is not limited to: health monitoring by using WebEvent, performance counters

Working with ASP.NET AJAX and Client-Side Scripting (15 percent)

  • Implement Web Forms by using ASP.NET AJAX. May include but is not limited to: EnablePartialRendering, Triggers, ChildrenAsTriggers, Scripts, Services, UpdateProgress, Timer, ScriptManagerProxy

  • Interact with the ASP.NET AJAX client-side library. May include but is not limited to: JavaScript Object Notation (JSON) objects; handling ASP.NET AJAX events

  • Consume services from client scripts.

  • Create and register client script. May include but is not limited to: inline, included .js file, embedded JavaScript resource, created from server code

Targeting Mobile Devices (5 percent)

  • Access device capabilities. May include but is not limited to: working with emulators

  • Control device-specific rendering. May include but is not limited to: DeviceSpecific control; device filters; control templates

  • Add mobile Web controls to a Web page. May include but is not limited to: StyleSheet controls; List controls; Container controls

  • Implement control adapters. May include but is not limited to: App_Browsers; rendering by using ChtmlTextWriter or XhtmlTextWriter

Programming Web Applications (17 percent)

  • Customize the layout and appearance of a Web page. May include but is not limited to: CSS, Themes and Skins, Master Pages, and Web Parts, App_Themes, StyleSheetTheme

  • Work with ASP.NET intrinsic objects. May include but is not limited to: Request, Server, Application, Session, Response, HttpContext

  • Implement globalization and accessibility. May include but is not limited to: resource files, culture settings, RegionInfo, App_GlobalResources, App_LocalResources, TabIndex, AlternateText , GenerateEmptyAlternateText, AccessKey, Label.AssociatedControlID

  • Implement business objects and utility classes. May include but is not limited to: App_Code , external assemblies

  • Implement session state, view state, control state, cookies, cache, or application state.

  • Handle events and control page flow. May include but is not limited to: page events, control events, application events, and session events, cross-page posting; Response.Redirect, Server.Transfer, IsPostBack, setting AutoEventWireup

  • Implement the Generic Handler.

JQuery and ASP.NET page methods

What?

jQuery is a lightwight javascript library loaded with really amazing features and UI richness that cannot be ignored instantly. It provides fast and easy way of HTML DOM traversing and manipulation, event handling, client side animations, etc.You can perform routine javascript tasks with jQuery but the difference is that jQuery is easy to use and give too much flexibility to the developers.

The definition mentioned in jQuery official Web Site

“jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript”

From Scott Gu

“One of the characteristics of jQuery commands is that they can be “chained” together – so that the result of one command can feed into another.  jQuery also includes a built-in set of animation APIs that can be used as commands.  The combination allows you to do some really cool things with only a few keystrokes.”

Features of jQuery

Here are the famous features of jQuery.

Effects and animations
DOM element selections functions
DOM traversal and modification
Events
CSS manipulation
Ajax
Extensibility
Utilities – such as browser version and the each function.
JavaScript Plugins

As mentioned in the above features jQuery is used in web application to handle events, validation, adding effects and animation, client side processing and many more.

Compatible languages

jQuery can be used almost with any web development languages ranging from ASP, ASP.NET,PHP, CGI,Servlets, CGI etc. Ofcourse you can create some appealing and interactive webcontent by blending it with plain HTML.

Using with ASP.NET and Visual Studio

Being a Microsoft shill I would like to write more specifically about using it with ASP.NET and Visual Studio. To start building ASP.NET download the latest jQuery version 1.3.2 at the time of writing from here (common script file for all languages) and place it in a new folder say scripts under the root of your web application. Folder part is optional but a good practice in terms of managing resources like images, CSS, script files etc.

Note: The download page has another link for Visual Studio which you should prefer as it contains intellisence support for writing javascripts. Here is a link to it jQuery for VisualStudio

Before doing any magic with jQuery we need to make sure that we start adding events etc. as soon as the DOM is ready by doing

$(document).ready(function() {
// do stuff when DOM is ready
});

Although we can append our script within the head tag like

<head runat=”server”>
<title></title>
<script src=”scripts/jquery-1.3.2-vsdoc2.js” type=”text/javascript”></script>

<script type=”text/javascript”>
$(document).ready(function(){
alert(“Welcome to jQuery”);
});

</script>
</head>

but again for clear understanding I will place my full example script in another file say Default.js and reference it in head tag.

For this example I will update a div with the result returned from a page method named HelloQuery in default.aspx code behind file which will take a name from the ASP textbox control and display Hello + name in Result div.

Secondly a div DateDiv will be updated with server time by calling GetDate pageMethod.

Writing a page method is easy just add [WebMethod] attribute found in System.Web.Services on top of standard static method like

[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToShortDateString();
}
}

Default.aspx

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title></title>
<script src=”scripts/jquery-1.3.2-vsdoc2.js” type=”text/javascript”></script>
<script src=”scripts/Default.js” type=”text/javascript”></script>
</head>
<body>

<form id=”form1″ runat=”server”>
<div>
<h2> Calling ASP.NET Page Method with jQuery </h2>
<p>Enter your name:</p>

<asp:TextBox ID=”txtName” runat=”server”></asp:TextBox>
<input id=”btnSubmit” value=”Say Hello” type=”button”  />

<div id=”Result” style=”padding:20px 20px 20px 0; color:Navy; font-size:22px”></div>

<div id=”DateDiv” style=”padding:20px 20px 20px 0; color:Navy; font-size:22px”>Click Me for Time</div>

</div>
</form>
</body>
</html>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

[WebMethod]
public static string HelloQuery(string name)
{
return “Hello ” + name;
}

[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToShortDateString();
}
}

Default.js

$(document).ready(function() {
$(“#btnSubmit”).click(function() {
$.ajax({
type: “POST”,
url: “Default.aspx/HelloQuery”,
data: “{‘name’: ‘” + $(‘#txtName’).val() + “‘}”, // “{‘name is the parameter name passed to HelloQuery page method
contentType: “application/json; charset=utf-8″,
dataType: “json”,
success: function(msg) {
// Replace the div’s content with the page method’s return.
$(“#Result”).text(msg.d);

}
});
event.preventDefault();
});
});

$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$(“#DateDiv”).click(function() {
$.ajax({
type: “POST”,
url: “Default.aspx/GetDate”,
data: “{}”,
contentType: “application/json; charset=utf-8″,
dataType: “json”,
success: function(msg) {
// Replace the div’s content with the page method’s return.
$(“#DateDiv”).html(msg.d);
}
});
});
});

Download sample project

From Where I can get jQuery Library?

The jQuery library is freely available on jQuery official web site (www.jquery.com). Detail documentation, tutorials are also available to learn about jQuery.

Conclusion

PageMethods provides a solution for the limitations of the standard way of handling pages, URLs and parameters.
The usual way to proceed is not structured. With PageMethods, the code of your pages is simpler, cleaner and more reliable. The approach is based on strict page inputs and declarative parameter binding. With PageMethods, each page exposes a set of methods that represent the different ways to call the page.
All you have to do to start benefiting from sharp URLs is to add methods to your pages, and mark these methods with attributes provided by PageMethods.

This project of 3 files mainly the Default.aspx, Default.aspx.cs and Default.js. This is just a limited demo of functionality offered by jQuery and ASP.NET but to start with its good.

Two features in ASP.NET4 I liked most

ASP.NET 4 introduces a number of features that improve core ASP.NET services such as output caching and session-state storage. We all are waiting for the final releases but still there are lots of improvements and enhancements.
While reading the whitepaper I found 2 features that I liked the most, doesn’t mean rest are not exciting but these two will bring goodness to my existing projects instantly and that are:

1. Extensible Output Caching

Since ASP.NET 1.0 was released, output caching has enabled developers to store the generated output of pages, controls, and HTTP responses in memory. On subsequent Web requests, ASP.NET can serve content more quickly by retrieving the generated output from memory instead of regenerating the output from scratch. However, this approach has a limitation — generated content always has to be stored in memory, and on servers that are experiencing heavy traffic, the memory consumed by output caching can compete with memory demands from other portions of a Web application.

ASP.NET 4 adds an extensibility point to output caching that enables you to configure one or more custom output-cache providers. Output-cache providers can use any storage mechanism to persist HTML content. This makes it possible to create custom output-cache providers for diverse persistence mechanisms, which can include local or remote disks, cloud storage, and distributed cache engines.

You create a custom output-cache provider as a class that derives from the new System.Web.Caching.OutputCacheProvider type. You can then configure the provider in the Web.config file by using the new providers subsection of the outputCache element, as shown in the following example:

<caching>
<outputCache defaultProvider=”AspNetInternalProvider”>
<providers>
<add name=”DiskCache”
type=”Test.OutputCacheEx.DiskOutputCacheProvider, DiskCacheProvider”/>
</providers>
</outputCache>
</caching>

By default in ASP.NET 4, all HTTP responses, rendered pages, and controls use the in-memory output cache, as shown in the previous example, where the defaultProvider attribute is set to AspNetInternalProvider. You can change the default output-cache provider used for a Web application by specifying a different provider name for defaultProvider.

In addition, you can select different output-cache providers per control and per request. The easiest way to choose a different output-cache provider for different Web user controls is to do so declaratively by using the new providerName attribute in a page or control directive, as shown in the following example:

<%@ OutputCache Duration=”60″ VaryByParam=”None” providerName=”DiskCache” %>

Specifying a different output cache provider for an HTTP request requires a little more work. Instead of declaratively specifying the provider, you instead override the new GetOuputCacheProviderName method in the Global.asax file to programmatically specify which provider to use for a specific request. The following example shows how to do this.

public override string GetOutputCacheProviderName(HttpContext context)
{
if (context.Request.Path.EndsWith(“Advanced.aspx”))
return “DiskCache”;
else
return base.GetOutputCacheProviderName(context);
}

With the addition of output-cache provider extensibility to ASP.NET 4, you can now pursue more aggressive and more intelligent output-caching strategies for your Web sites. For example, it is now possible to cache the “Top 10″ pages of a site in memory, while caching pages that get lower traffic on disk. Alternatively, you can cache every vary-by combination for a rendered page, but use a distributed cache so that the memory consumption is offloaded from front-end Web servers.

2. Auto-Start Web Applications

Some Web applications need to load large amounts of data or perform expensive initialization processing before serving the first request. In earlier versions of ASP.NET, for these situations you had to devise custom approaches to “wake up” an ASP.NET application and then run initialization code during the Application_Load method in the Global.asax file.

A new scalability feature named auto-start that directly addresses this scenario is available when ASP.NET 4 runs on IIS 7.5 on Windows Server 2008 R2. The auto-start feature provides a controlled approach for starting up an application pool, initializing an ASP.NET application, and then accepting HTTP requests.

To use the auto-start feature, an IIS administrator sets an application pool in IIS 7.5 to be automatically started by using the following configuration in the applicationHost.config file:

<applicationPools>
<add name=”MyApplicationPool” startMode=”AlwaysRunning” />
</applicationPools>

Because a single application pool can contain multiple applications, you specify individual applications to be automatically started by using the following configuration in the applicationHost.config file:

<sites>
<site name=”MySite” id=”1″>
<application path=”/”
serviceAutoStartEnabled=”true”
serviceAutoStartProvider=”PrewarmMyCache” >
<!– Additional content –>
</application>
</site>
</sites>

<!– Additional content –>

<serviceAutoStartProviders>
<add name=”PrewarmMyCache”
type=”MyNamespace.CustomInitialization, MyLibrary” />
</serviceAutoStartProviders>

When an IIS 7.5 server is cold-started or when an individual application pool is recycled, IIS 7.5 uses the information in the applicationHost.config file to determine which Web applications need to be automatically started. For each application that is marked for auto-start, IIS7.5 sends a request to ASP.NET 4 to start the application in a state during which the application temporarily does not accept HTTP requests. When it is in this state, ASP.NET instantiates the type defined by the serviceAutoStartProvider attribute (as shown in the previous example) and calls into its public entry point.

You create a managed auto-start type with the necessary entry point by implementing the IProcessHostPreloadClient interface, as shown in the following example:

public class CustomInitialization : System.Web.Hosting.IProcessHostPreloadClient
{
public void Preload(string[] parameters)
{
// Perform initialization.
}
}

After your initialization code runs in the Preload method and the method returns, the ASP.NET application is ready to process requests.

With the addition of auto-start to IIS .5 and ASP.NET 4, you now have a well-defined approach for performing expensive application initialization prior to processing the first HTTP request. For example, you can use the new auto-start feature to initialize an application and then signal a load-balancer that the application was initialized and ready to accept HTTP traffic.

Don’t forget to read the full Whitepaper at http://tinyurl.com/cqojv6