Welcome to the amazing dot net programming

Author: Vijaya Kumar
Contact:

    

  

Get updates by e-mail

HP Computer Museum

 

 

 

 

free website submission search engine seo optimization

 

Powered by Blogger

November 17, 2006

Read Assembly Information Using Reflection

Reflection is ability to find information about types contained in an assembly at run time. Prior to .NET languages like C++ provided such ability in a limited sense. .NET provides a whole new set of APIs to introspect assemblies and objects. All the APIs related to reflection are located under System.Reflection namespace. .NET reflection is a powerful mechanism which not only allows you to inspect type information but also allows you to invoke methods on those types at runtime. Certain reflection APIs also allow creating of assembly in memory dynamically and use it in your code. In this article we will examine the basic and most commonly used features of reflection. Reflection APIs can be used to develop applications like class browsers, add-ons for development IDEs and inelegant editors.

Getting started

The first thing you should do while using reflection classes is to include System.Reflection namespace.

using System.Reflection;


Loading an assembly

Before obtaining any information about types contained in an assembly we must first load the assembly.

Assembly myassembly = Assembly.LoadFrom("employee.dll");

This statement loads an assembly called employee.dll. You can substitute your own path here. Assembly class has a static method called LoadFrom that loads the specified assembly in memory. The method returns an instance of assembly class itself.


obtaining details about types from the assembly

The next step is to obtain a list of various types contained in the assembly.

Types mytypes[] = myassembly.GetTypes();

Type mytype=myassembly.GetType("Company.Employee");

There are two methods to get type information . The method GetTypes returns an array of System.Type objects. The method GetType returns a type object having details of specified object. Note that in our example Company is the namespace. In case your assembly do not contain any namespace you will simply write the type name.


Obtaining type details

The Type class has following properties that gives details about the type under consideration :
  • Name : Gives name of the type
  • FullName : Give fully qualified name of the type
  • Namespace : Gives namespace name
  • IsClass
  • IsInterface
  • IsAbstract
  • IsCOMObject : Indicates if the type is a COM object
  • IsEnum
  • IsSealed
  • IsPublic

All the property names are self-explanatory and need no separate explanation.


obtaining details about methods, properties and fields

Each type may have fields (member variables), properties and methods. The details about each of these types are obtained by following methods of the Type object.
  • GetMembers() : Gives array of MemberInfo objects
  • GetFields() : Gives array of FieldInfo objects
  • GetProperties() : Gives array of PropertyInfo objects
  • GetMethods() : Gives array of MethodInfo objects

Note that you can also get information about specific method, property or field using GetMethod("mymethod"), GetProperty("myprop") or GetField("myfield") methods.

MethodInfo[] mymethods= mytype.GetMethods();

MethodInfo mymethod = mytype.GetMethod("GetSalary");

Following paragraphs list commonly used properties and methods of above objects. The property and method names are self explanatory.


Properties and methods of MethodInfo Object
  • Name
  • IsPrivate
  • IsPublic
  • IsStatic
  • IsConstructor
  • ReturnType
  • GetParameters()
  • Invoke()

Properties and methods of PropertyInfo Object
  • Name
  • CanRead
  • CanWrite
  • PropertyType
  • GetValue()
  • SetValue()

Properties and methods of FieldInfo Object
  • Name
  • FieldType
  • IsPublic
  • IsPrivate
  • IsStatic
  • GetValue()
  • SetValue()

Invoking a method on a type

We have seen how to get information about various types from an assembly. Reflection also allows us to create instances of these types and invoke methods on them. Following code fragment shows just that.

Assembly a=Assembly.LoadFrom("employee.dll");
Type t=a.GetType("Company.Employee");
MethodInfo getsalary=t.GetMethod("DisplayMsg");
object obj=Activator.CreateInstance(t);
object[] p=new object[1];
p[0]="Hello bipin";
getsalary.Invoke(obj,p);

Assembly a=Assembly.LoadFrom("employee.dll");
Type t=a.GetType("Company.Employee");
MethodInfo getsalary=t.GetMethod("GetSalary");
object obj=Activator.CreateInstance(t);
object[] p=new object[1];
p[0]="bipin";
object retval=getsalary.Invoke(obj,BindingFlags.DefaultBinding, null,p,null);
Console.WriteLine(retval);

Here, we first obtained type of employee class. We then created an instance of it using Activator.CreateInstance() method. There are two forms of Invoke() method :
  • If your method is not returning any value then you may use following form Invoke ( obj , obj[])
  • If your method is returning some value and you want to trap it use following form : obj = Invoke ( obj , bindingflag, binder , parameters, cultureflag )

For both the forms you pass instance of object on which the method will be called and array of objects that contains method parameters.

The second method shown here is with most commonly used values for BindingFlags, Binder and Culture.

November 16, 2006

Microsoft, Wake Up and Smell Defeat!

in ipod Market :), it's just for fun only.

Assemblies in .NET

Assemblies Overview

Assemblies are a fundamental part of programming with the .NET Framework. An assembly performs the following functions:

  • It contains code that the common language runtime executes. Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. Note that each assembly can have only one entry point (that is, DllMain, WinMain, or Main).
  • It forms a security boundary. An assembly is the unit at which permissions are requested and granted.
  • It forms a type boundary. Every type's identity includes the name of the assembly in which it resides. A type called MyType loaded in the scope of one assembly is not the same as a type called MyType loaded in the scope of another assembly.
  • It forms a reference scope boundary. The assembly's manifest contains assembly metadata that is used for resolving types and satisfying resource requests. It specifies the types and resources that are exposed outside the assembly. The manifest also enumerates other assemblies on which it depends.
  • It forms a version boundary. The assembly is the smallest versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit. The assembly's manifest describes the version dependencies you specify for any dependent assemblies.
  • It forms a deployment unit. When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes, can be retrieved on demand. This allows applications to be kept simple and thin when first downloaded.
  • It is the unit at which side-by-side execution is supported.

Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in portable executable (PE) files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed.

There are several ways to create assemblies. You can use development tools, such as Visual Studio .NET, that you have used in the past to create .dll or .exe files. You can use tools provided in the .NET Framework SDK to create assemblies with modules created in other development environments. You can also use common language runtime APIs, such as Reflection.Emit, to create dynamic assemblies.


Assembly Benefits

Assemblies are designed to simplify application deployment and to solve versioning problems that can occur with component-based applications.

End users and developers are familiar with versioning and deployment issues that arise from today's component-based systems. Some end users have experienced the frustration of installing a new application on their computer, only to find that an existing application has suddenly stopped working. Many developers have spent countless hours trying to keep all necessary registry entries consistent in order to activate a COM class.

Many deployment problems have been solved by the use of assemblies in the .NET Framework. Because they are self- describing components that have no dependencies on registry entries, assemblies enable zero- impact application installation. They also simplify uninstalling and replicating applications.

Versioning Problems

An End to DLL Conflicts

To solve versioning problems, as well as the remaining problems that lead to DLL conflicts, the runtime uses assemblies to do the following:

  • Enable developers to specify version rules between different software components.
  • Provide the infrastructure to enforce versioning rules.
  • Provide the infrastructure to allow multiple versions of a component to be run simultaneously (called side-by-side execution).

Assembly Names

An assembly
's name is stored in metadata and has a significant impact on the assembly's scope and use by an application. A strong-named assembly has a fully qualified name that includes the assembly's name, culture, public key, and version number. The runtime uses this information to locate the assembly and differentiate it from other assemblies with the same name. For example, a strong-named assembly called myTypes could have the following fully qualified name:

"myTypes, Version=1.0.1234.0, Culture="en-US", PublicKeyToken = b77a5c561934e089c

In this example, the fully qualified name indicates that the myTypes assembly has a strong name with a public key token, has the culture value for US English, and has a version number of 1.0.1234.0.

Code that requests types in an assembly must use a fully qualified assembly name. This is called fully qualified binding. Partial binding, which specifies only an assembly name, is not permitted when referencing assemblies in the .NET Framework.

All assembly references to assemblies that make up the .NET Framework also must contain a fully qualified name of the assembly. For example, to reference the System.Data .NET Framework assembly for version 1.0 would include:

System.data, version=1.0.3300.0, Culture=neutral, PublicKeyToken = b77a5c561934e089

Note that the version corresponds to the version number of all .NET Framework assemblies that shipped with .NET Framework version 1.0. For .NET Framework assemblies, the culture value is always neutral, and the public key is the same as shown in the above example.


Assembly Contents

In general, a static assembly can consist of four elements:

  • The assembly manifest, which contains assembly metadata.
  • Type metadata.
  • Microsoft intermediate language (MSIL) code that implements the types.
  • A set of resources.
Only the assembly manifest is required, but either types or resources are needed to give the assembly any meaningful functionality.

There are several ways to group these elements in an assembly. You can group all elements in a single physical file, which is shown in the following illustration.





Assembly Location

An assembly's location determines whether the common language runtime can locate it when referenced, and can also determine whether the assembly can be shared with other assemblies. You can deploy an assembly in the following locations:

  • The application's directory or subdirectories.
This is the most common location for deploying an assembly. The subdirectories of an application's root directory can be based on language or culture. If an assembly has information in the culture attribute, it must be in a subdirectory under the application directory with that culture's name.

  • The global assembly cache.
This is a machine-wide code cache that is installed wherever the common language runtime is installed. In most cases, if you intend to share an assembly with multiple applications, you should deploy it into the global assembly cache.

  • On an FTTP server.
An assembly deployed on an FTTP server must have a strong name; you point to the assembly in the codebase section of the application's configuration file.

Types of Assemblies

  • Private
  • Public / Shared
  • Satellite
A private assembly is normally used by a single application, and is stored in the application's directory.

A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime.

Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language.


Public / Shared Assemblies - Installing an Assembly into the Global Assembly Cache

if we want to make any public / shared assemblies, it must be strong named and deployed in Global Assembly Cache (GAC). below the find the steps to add the assembly into GAC.

Global Assembly Cache

Each computer where the common language runtime is installed has a machine - wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer.

You should share assemblies by installing them into the global assembly cache only when you need to. As a general guideline, keep assembly dependencies private, and locate assemblies in the application directory unless sharing an assembly is explicitly required. In addition, it is not necessary to install assemblies into the global assembly cache to make them accessible to COM interop or unmanaged code.

Note There are scenarios where you explicitly do not want to install an assembly into the global assembly cache. If you place one of the assemblies that make up an application in the global assembly cache, you can no longer replicate or install the application by using the xcopy command to copy the application directory. You must move the assembly in the global assembly cache as well.

There are several ways to deploy an assembly into the global assembly cache:

  • Use an installer designed to work with the global assembly cache. This is the preferred option for installing assemblies into the global assembly cache.
  • Use a developer tool called the Global Assembly Cache tool (Gacutil.exe), provided by the .NET Framework SDK.
  • Use Windows Explorer to drag assemblies into the cache.

Note In deployment scenarios, use Windows Installer 2.0 to install assemblies into the global assembly cache. Use Windows Explorer or the Global Assembly Cache tool only in development scenarios, because they do not provide assembly reference counting and other features provided when using the Windows Installer.

Administrators often protect the WINNT directory using an access control list (ACL) to control write and execute access. Because the global assembly cache is installed in the WINNT directory, it inherits that directory's ACL. It is recommended that only users with Administrator privileges be allowed to delete files from the global assembly cache.

Assemblies deployed in the global assembly cache must have a strong name. When an assembly is added to the global assembly cache, integrity checks are performed on all files that make up the assembly. The cache performs these integrity checks to ensure that an assembly has not been tampered with, for example, when a file has changed but the manifest does not reflect the change.

Creating and Using Strong-Named Assemblies

A strong name consists of the assembly's identity — its simple text name, version number, and culture information (if provided) — plus a public key and a digital signature. It is generated from an assembly file using the corresponding private key. (The assembly file contains the assembly manifest, which contains the names and hashes of all the files that make up the assembly.)

Remember that once you give an assembly a strong name, all assemblies that reference that assembly also have to have strong names, so that the security of the strongly named assembly is not compromised.

Note Once an assembly is created, you cannot sign it with a strong name. You can sign an assembly with a strong name only when you create it.

Strong Name Tool (Sn.exe)

The Strong Name tool helps sign assemblies with strong names. Sn.exe provides options for key management, signature generation, and signature verification.

sn [-quiet][option [parameter(s)]]

Examples

The following command creates a new, random key pair and stores it in keyPair.snk.

sn -k keyPair.snk

Signing an Assembly with a Strong Name

There are two ways to sign an assembly with a strong name:

  • Using the Assembly Linker (Al.exe) provided by the .NET Framework SDK.
  • Using assembly attributes to insert the strong name information in your code. You can use either the AssemblyKeyFileAttribute or the AssemblyKeyNameAttribute, depending on where the key file to be used is located.
You must have a cryptographic key pair to sign an assembly with a strong name.

To create and sign an assembly with a strong name using the Assembly Linker

At the command prompt, type the following command:

al /out:[assembly name] [module name] /keyfile:[file name]

In this command, assembly name is the name of the assembly to sign with a strong name, module name is the name of the code module used to create the assembly, and file name is the name of the container or file that contains the key pair.

The following example signs the assembly MyAssembly.dll with a strong name using the key file sgKey.snk.

al /out:MyAssembly.dll MyModule.netmodule /keyfile:sgKey.snk


To sign an assembly with a strong name using attributes

In a code module, add the AssemblyKeyFileAttribute or the AssemblyKeyNameAttribute, specifying the name of the file or container that contains the key pair to use when signing the assembly with a strong name.

The following code example uses the AssemblyKeyFileAttribute with a key file called sgKey.snk.

[Visual Basic]
Assembly:AssemblyKeyFileAttribute("sgKey.snk")
[C#]
[assembly:AssemblyKeyFileAttribute(@"..\..\sgKey.snk")]

You can also delay sign an assembly when compiling. After adding the file, compile the assembly once to take the changes.

When signing an assembly with a strong name, the Assembly Linker (Al.exe) looks for the key file relative to the current directory and to the output directory. When using command-line compilers, you can simply copy the key to the current directory containing your code modules.


To install a strong-named assembly into the global assembly cache

At the command prompt, type the following command:

gacutil -I [assembly name]

In this command, assembly name is the name of the assembly to install in the global assembly cache.

The following example installs an assembly with the file name hello.dll into the global assembly cache.

gacutil -i hello.dll


To remove an assembly from the global assembly cache

At the command prompt, type the following command:

gacutil -u [assembly name]

In this command, assembly name is the name of the assembly to remove from the global assembly cache.

The following example removes an assembly named hello.dll from the global assembly cache.

gacutil -u hello

The .NET Framework SDK also provides a Windows shell extension called the Assembly Cache Viewer (Shfusion.dll), which you can use to remove assemblies from the global assembly cache.


To view a list of the assemblies in the global assembly cache

At the command prompt, type the following command:

gacutil -l

The .NET Framework SDK also provides a Windows shell extension called the Assembly Cache Viewer (Shfusion.dll), which you can use to view the contents of global assembly cache.

November 13, 2006

3-D desktop

Using Forms Authentication with SQL Server in ASP.NET 1.1

Most of the Web applications we have to provide the authentication to check the use credentials to logon to the secured pages in the site. By default IIS provides the windows authentication which doesn't need to write any single line of code instead of some settings in IIS. We can use Forms authentication in ASP.NET to verify the user credentials in order to access the secured pages. But for Forms authentication, we have to write little bit of code, below i have added the setps to setup the forms
authentication.

Step 1. Create a Web Application with a Logon Page
Step 2. Configure the Web Application for Forms Authentication
Step 3. Develop Functions to Generate a Hash and Salt value
Step 4. Create a User Account Database
Step 5. Use ADO.NET to Store Account Details in the Database
Step 6. Authenticate User Credentials against the Database
Step 7. Test the ApplicationAdditional Resources

Web applications that use Forms authentication often store user credentials (user names and passwords) together with associated role or group lists in MicrosoftSQL Server.

This How To describes how to securely look up user names and validate passwords against SQL Server. There are two key concepts for storing user credentials securely:

Storing password digests. For security reasons, passwords should not be stored in clear text or encrypted format in the database. This How To describes how to create and store a one-way hash of a user's password rather than the password itself. This approach is preferred to storing a clear text or encrypted version of the user's password, for two reasons. First, it helps to prevent an attacker who gains access to our user store from obtaining the user passwords. In addition, this approach helps you to avoid the key-management issues associated with encryption techniques.

Using a salt value when creating the hash helps to slow an attacker who is attempting to perform a dictionary attack (where an attacker attempts to decipher the key used for hashing). This approach gives you additional time to detect and react to the compromise.
Important: The one drawback of not storing passwords in the database is that if a user forgets a password, it cannot be recovered. As a result, your application should use password hints and store them alongside the password digest within the database.

Validating user input. Where user input is passed to SQL commands, for example as string literals in comparison or pattern matching statements, great care should be taken to validate the input, to ensure that the resulting commands do not contain syntax errors and also to ensure that a hacker cannot cause your application to run arbitrary SQL commands. Validating the supplied user name during a logon process is particularly vital as your application's security model is entirely dependent on being able to correctly and securely authenticate users.

Step 1. Create a Web Application with a Logon Page

Start Visual Studio .NET and create a new C# ASP.NET Web application called FormsAuthSQL.

Use Solution Explorer to rename WebForm1.aspx to Logon.aspx

Add the controls to Logon.aspx to create a simple logon form.

Your Web page should resemble the one illustrated in Figure 1.


Figure 1. Logon page Web form

Step 2. Configure the Web Application for Forms Authentication

Use Solution Explorer to open Web.config.

Locate the <authentication> element and change the mode attribute to Forms. Add the following <forms> element as a child of the <authentication> element and set the loginUrl, name, timeout, and path attributes as follows.


<authentication mode="Forms">

<forms loginUrl="logon.aspx" name="sqlAuthCookie" timeout="60" path="/">

</forms>

</authentication>


Add the following <authorization> element beneath the <authentication> element. This will allow only authenticated users to access the application. The previously established loginUrl attribute of the <authentication> element will redirect unauthenticated requests to the logon.aspx page.


<authorization>

<deny users="?" />

<allow users="*" />

</authorization>

Step 3. Develop Functions to Generate a Hash and Salt value

This procedure adds two utility methods to your Web application; one to generate a random salt value, and one to create a hash based on a supplied password and salt value.

To develop functions to generate a hash and salt value

Open Logon.aspx.cs and add the following using statements to the top of the file beneath the existing using statements.

using System.Security.Cryptography;
using System.Web.Security;

Add the following static method to the WebForm1 class to generate a random salt value and return it as a Base 64 encoded string.


private static string CreateSalt(int size)
{
// Generate a cryptographic random number using the cryptographic
// service provider
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
// Return a Base64 string representation of the random number
return Convert.ToBase64String(buff);
}

Add the following static method to generate a hash value based on a supplied password and salt value.

private static string CreatePasswordHash(string pwd, string salt)
{
string saltAndPwd = String.Concat(pwd, salt);
string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile( saltAndPwd, "SHA1");
hashedPwd = String.Concat(hashedPwd, salt);
return hashedPwd;
}

Step 4. Create a User Account Database

Run the the table Users script in SQL query analyzer to create the table.

CREATE TABLE [Users] (
[UserName] [varchar] (20) NOT NULL ,
[PasswordHash] [varchar] (40) NOT NULL ,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[UserName]
) ON [PRIMARY]
) ON [PRIMARY]

-- create stored procedure to register user details

CREATE PROCEDURE RegisterUser
@userName varchar(20),
@passwordHash varchar(40)
AS
INSERT INTO Users VALUES(@userName, @passwordHash)
GO

-- create stored procedure to retrieve user details
CREATE PROCEDURE LookupUser
@userName varchar(20)
AS

SELECT PasswordHash FROM UsersWHERE UserName = @userName
GO

Step 5. Use ADO.NET to Store Account Details in the Database

This procedure modifies the Web application code to store the supplied user name, generated password hash and salt value in the database.

To use ADO.NET to store account details in the database

Return to Visual Studio .NET and double-click the Register button on the Web form to create a button click event handler. Add the following code to the method.

int saltSize = 5;
string salt = CreateSalt(saltSize);
string passwordHash = CreatePasswordHash(txtPassword.Text,salt);

try
{
StoreAccountDetails(
txtUserName.Text, passwordHash);
}
catch(Exception ex)
{
lblMessage.Text = ex.Message;
}

Add the following using statement at the top of the file, beneath the existing using statements.

using System.Data.SqlClient;

Add the StoreAccountDetails utility method using the following code. This code uses ADO.NET to connect to the UserAccounts database and stores the supplied username, password hash and salt value in the Users table.

private void StoreAccountDetails( string userName, string passwordHash )
{
// See "How To Use DPAPI (Machine Store) from ASP.NET" for information
// about securely storing connection strings.

SqlConnection conn = new SqlConnection( "Server=(local);" + "Integrated Security=SSPI;" + "database=UserAccounts");

SqlCommand cmd = new SqlCommand("RegisterUser", conn );

cmd.CommandType = CommandType.StoredProcedure;
SqlParameter sqlParam = null;
//Usage of Sql parameters also helps avoid SQL Injection attacks. sqlParam = cmd.Parameters.Add("@userName", SqlDbType.VarChar, 20);
sqlParam.Value = userName;
sqlParam = cmd.Parameters.Add("@passwordHash ", SqlDbType.VarChar, 40);
sqlParam.Value = passwordHash;

try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch( Exception ex )
{
// Code to check for primary key violation (duplicate account name)
// or other database errors omitted for clarity
throw new Exception("Exception adding account. " + ex.Message);
}
finally
{
conn.Close();
}
}

Step 6. Authenticate User Credentials Against the Database

This procedure develops ADO.NET code to look up the supplied user name in the database and validate the supplied password, by matching password hashes.

To authenticate user credentials against the database

private bool VerifyPassword(string suppliedUserName, string suppliedPassword )
{
bool passwordMatch = false;
// Get the salt and pwd from the database based on the user name.
// See "How To: Use DPAPI (Machine Store) from ASP.NET," "How To:
// Use DPAPI (User Store) from Enterprise Services," and "How To:
// Create a DPAPI Library" for more information about how to use
// DPAPI to securely store connection strings.

SqlConnection conn = new SqlConnection( "Server=(local);" + "Integrated Security=SSPI;" + "database=UserAccounts");

SqlCommand cmd = new SqlCommand( "LookupUser", conn );
cmd.CommandType = CommandType.StoredProcedure;
//Usage of Sql parameters also helps avoid SQL Injection attacks. SqlParameter sqlParam = cmd.Parameters.Add("@userName", SqlDbType.VarChar, 20);
sqlParam.Value = suppliedUserName;

try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader(); reader.Read();
// Advance to the one and only row
// Return output parameters from returned data stream
string dbPasswordHash = reader.GetString(0);
int saltSize = 5;
string salt = dbPasswordHash.Substring(dbPasswordHash.Length - saltSize);
reader.Close();
// Now take the password supplied by the user
// and generate the hash.
string hashedPasswordAndSalt = CreatePasswordHash(suppliedPassword, salt);
// Now verify them.
passwordMatch = hashedPasswordAndSalt.Equals(dbPasswordHash);
}
catch (Exception ex)
{
throw new Exception("Execption verifying password. " + ex.Message);
}
finally
{
conn.Close();
}
return passwordMatch;
}

Step 7. Test the Application

This procedure tests the application. You will register a user, which results in the user name, password hash and salt value being added to the Users table in the UserAccounts database. You will then log on the same user to ensure the correct operation of the password verification routines.

To test the application

Return to the Logon form and double-click the Logon button to create a button click event handler.

Add the following code to the Logon button click event handler to call the VerifyPassword method and display a message based on whether or not the supplied user name and password are valid.

bool passwordVerified = false;
try
{
passwordVerified = VerifyPassword(txtUserName.Text,txtPassword.Text);
}
catch(Exception ex)
{
lblMessage.Text = ex.Message;
return;
}
if (passwordVerified == true )
{
// The user is authenticated
// At this point, an authentication ticket is normally created
// This can subsequently be used to generate a GenericPrincipal
// object for .NET authorization purposes
// For details, see "How To: Use Forms authentication with
// GenericPrincipal objects
lblMessage.Text = "Logon successful: User is authenticated";
}
else
{
lblMessage.Text = "Invalid username or password";
}

On the Build menu, click Build Solution.

In Solution Explorer, right-click logon.aspx, and then click View in Browser.

Enter a user name and password, and then click Register.

Use SQL Server Enterprise Manager to view the contents of the Users table. You should see a new row for the new user name together with a generated password hash.

Return to the Logon Web page, re-enter the password, and then click Logon. You should see the message "Logon successful: User is authenticated."

Now enter an invalid password (leaving the user name the same). You should see the message "Invalid username or password."

Google
 
Web dotnetlibrary.blogspot.com