Tuesday 27 December 2011

Implementing .NET Passport Authentication in Web Applications

Implementing .NET Passport Authentication in Web Applications 

In this article, i am going to explain how you can implement .NET Passport Authentication in Web applications using ASP.NET. Basically we are going to see what are steps that are required to implement .NET Passport Authentication.

.NET Passport

    .NET Passport allows users to create a single sign-in name and password to access any site that has implemented the Passport single sign-in (SSI) service. By implementing the Passport SSI, you won't have to implement your own user-authentication mechanism. Users authenticate with the SSI, which passes their identities to your site securely. Although Passport authenticates users, it doesn't grant or deny access to individual sites i.e. .NET Passport does only authentication not authroziation . Passport simply tells a participating site who the user is. Each site must implement its own access-control mechanisms based on the user's Passport User ID (PUID). Here is how .NET Passport Authentication works,

    First user requests any page from his web server. Since user is not authenticated, web server redirect its request for authentication with Sign-In logo. When user presses Sign-In button, request will go to Passport server for Sign-In page. Once the Sign-In page comes to browser, user will enter his authentication details like Passport ID and Password. When user credentials are submitted, Credentials are validated in Passport server. Then Cookies are created in server and response is send to the browser with encrypted querystring. Now both cookies and querystring is having details about authentication. Once user is authenticate, he will be taken to page which is requested first.

Steps To Implement .NET Passport Authentication

   Here the steps that are required to implement passport authentication in your system,
1. Download the Microsoft .NET Passport SDK from the following Microsoft Site  and install it in your web server.
2. Register your application in .NET Service Manager. Go to Service Manager Site , this is where you need to create application for your website. You will be prompted for contact information and other details. After that you will be  prompted for Application details. The following table describes about mandatory fields that are required for registering your application.
Field Name
Sample Value
Description
Preproduction Application Name ExtremeExperts This is how .NET Passport will describe your application.
Web Site Title ExtremeExperts The common name of your .NET Passport site. This is the name by which we will refer to your site on the .NET Passport pages, including our site directory.
Domain Name ExtremeExperts This will be the host name your browser will use to browse to your Web site.
Default Return URL http://extremeexperts/login.aspx
The default location to which Users will be redirected in the event of an error or when you do not specify a ru parameter. For SCT Matrix, it should point to your Login.asp in Web general folder
Cobrand Image URL
http://extremeexperts/images/header.jpg This is an image file that will be displayed above the standard .NET Passport logon prompt when someone logs on from your site.
Cobrand Instruction Text
ExtremeExperts Web Site The instruction text that will appear at the top of the .NET Passport Credential dialog box and can be viewed in Internet Explorer 6.0 and later. This is a UTF-8 encoded string.
Expire Cookie URL
http://extremeexperts/Signout.aspx The location of the page that will delete all the cookies set by Microsoft® .NET Passport for your site.
Logout URL http://extremeexperts/login.aspx The location to which we will send your customers if they sign out of .NET Passport by clicking the .NET Passport Sign Out button on your site.

3. Get the SiteID and Application key after registering your application with .NET Services Manager.Return to the .NET My Services Manager "Manage My Applications" page, select the application you just created from the drop-down list box and click Submit. Select the Download a key option and click Continue to download the executable that will install your key on your local machine. Save the file to a secure location on your machine. In my case the file was named partner33943_1.exe. To install the key you must run the application with the /addkey option.
             For example: partner33943_1.exe /addkey
   After installing the key you need to make the key current. This is done with the /makecurrent option along with a time-out option for any previous keys.
            For example: partner33943_1.exe /makecurrent /t 0
   The application's key is now installed. Configure your Site in Passport Administration Utility. This tool came along with .NET Passport SDK. Then configure  Secure Level in Passport Administration depending upon your secure level. If it is basic level, then configure it as 0. If your site is SSL Enabled then configure it as 10.
4. Create a .NET Passport in the pre-production environment. The .NET Passport you created in step 1 was a .NET Passport created in the production environment. The pre-production environment is a completely separate set of accounts. Therefore, to log on to your development site you will need a pre-production account. Development has to happen in this enviornment only. Once it is done then you have request a compliance review for your site. The .NET Services compliance team will review your site and verify that you have met all of its functionality, UI, and other requirements. After your site has been approved, you are ready to launch your live site 

Enable Passport Authentication in Web.Config

   In ASP.NET, Passport Authentication works very similar to Forms(cookies) Authentication. To enable Passport authentication you need to specify it in the authentication section of your web.config file
<configuration>
    <system.web>
          <authentication mode="Passport">
                 <passport redirectUrl="login.aspx" />
           </authentication>
           < authorization>
                  < deny users="?" />
            </authorization>
         </system.web>
</configuration>
  Basically here you need to set your application authentication type to Passport and you are not allowing any unauthenticated users to access any pages in your website. By doing this, if any unauthenticated users try to access this website, he will redirected to the page which is mentioned in redirectUrl. Once you specify authentication as passport, Identity of user property of the page will return PassportIdentity which managed version of Passport Manager.

Implementing Passport Authentication using ASP.NET

    The .NET Framework provides .NET Passport Manager functionality with two main classes: the System.Web.Security.PassportAuthenticationModule class and the System.Web.Security.PassportIdentity class. You can think of the PassportAuthenticationModule as the inner workings of .NET Passport, about which you do not need to worry. It is simply a plug-in that allows Microsoft ASP.NET applications to perform .NET Passport authentication. The PassportIdentity class is where all the functionality is provided that you will use in your code. It exposes many of the same methods that were available with the PassportManager COM object for use in ASP pages, but now it is done completely in managed code.
   Once you have set the authentication mode to Passport, you will be able to access the PassportIdentity class, which is accessed via the IIdentity interface that it implements. You can get an interface pointer to it from the User property of the current ASP.NET page context. The following code is used to get an instance of a PassportIdentity object
Dim Passport as System.Web.Security.PassportIdentity
Passport = Page.User.Identity
 
    Now the Passport variable can be used to access the .NET Passport-specific functionality provided by the PassportIdentity class. One of the key things you will need to implement when you perform .NET Passport authentication is the sign-in and sign-out buttons that should be displayed somewhere in the upper-right portion of your page. The HTML for the images along with a corresponding hyperlink to the .NET Passport authentication servers is returned by the LogoTag method of the PassportIdentity object. The following code demonstrates how you might use the LogoTag method in an ASP.NET page
ltlSignin.Text = Passport.LogoTag(strURL,2000, False, Nothing, 1033, Page.Request.IsSecureConnection, Page.Request.ServerVariables("SERVER_NAME"),0 ,False)
   The first parameter to the LogoTag2 method is the return URL. This is where the user will be redirected after a successful .NET Passport sign-in. In most situations the return URL should be the current page so that the user is returned to where the user was before signing in. You can, however, specify a different return URL if you prefer, or no URL at all, which tells .NET Passport Manager to pull the default return URL from the registry that you set with the Passport Administration utility; if it is not there, the .NET Passport servers will use the default return URL indicated during the configuration of your .NET My Services application when you created the site ID. For more details about other parameters, you can refer SDK Documentation.
    Your code will probably also want to detect if a user has signed in or not. The IsAuthenticated property of the PassportIdentity class can be used to detect a user's sign-in status. Once a user is signed in, the .NET Passport profile information will be available through the Items collection. Developers should be aware that most of the profile information is optional information. So, for instance, if you are accessing the FirstName item from the profile, it may not exist for all users.
    The Passport User ID (PUID) will always be available for a .NET Passport-authenticated user and is accessible via the Name or HexPUID properties of the PassportIdentity class. You should use the PUID as the index for storing user-specific information at your site. For the Favorites Service, we store the hierarchical favorites list for each user, so we use the PUID as the user identifier
    Signing in and accessing the .NET Passport profile information is only part of your responsibilities as a .NET Passport site developer. The other key item you must deal with is signing out. The LogoTag2 method will still handle creating the image and anchor for linking appropriately to the .NET Passport servers for performing a sign-out, but you must create a page that will handle the last portion of the sign-out. The .NET Passport servers will deal with expiring the .NET Passport ticket used for validating your sign-in, but it is up to the site developer to delete the HTTP cookies that carry the ticket information. Your sign-out page must also return an image that can be used to indicate a successful sign-out to the user. The following code deletes the .NET Passport cookies and returns the appropriate GIF image to perform a successful sign-out
<%
        Response.ContentType = "image/gif"
        Response.Expires = -1
        Response.AddHeader("P3P", "CP=TST") 
        Dim Cookie1 As New HttpCookie("MSPProf","") 
        Cookie1.Expires = Now()
        Response.Cookies.Add(Cookie1) 
        Dim Cookie2 as New HttpCookie("MSPAuth","") 
        Cookie2.Expires = Now()
        Response.Cookies.Add(Cookie2) 
        Dim Cookie3 as New HttpCookie("MSPSecAuth","") 
        Cookie3.Expires = Now()
        Response.Cookies.Add(Cookie3) 
        Dim Cookie4 as New HttpCookie("MSPProfC","") 
        Cookie4.Expires = Now()
        Response.Cookies.Add(Cookie4) 
        Dim Cookie5 as New HttpCookie("MSPConsent","") 
        Cookie5.Expires = Now()
        Response.Cookies.Add(Cookie5)
        Response.WriteFile("images/signoutcheckmark.gif") %>

Conclusion

     If you are implementing a site that will eventually go into production, you will need to take special care to follow the UI guidelines indicated in the .NET Passport SDK documentation. This article just gave an basic idea about how to implement Passport Authentication in Web applications. There is one more important thing which i didnt cover in this article is Co-branding stuff. For more details about that and for any other clarification refer .NET Passport SDK

Monday 26 December 2011

Security concept With window authen

SP.NET 3.5 Windows-Based Authentication

by Yogendra Pratap Singh(assistant Professor)
This article looks at Windows-based ASP.NET authentication, one of several different types of authentication measures ASP.NET 3.5 provides to use within your applications. ASP.NET has several ways of performing Windows-based authentication and we'll look at all of them: Integrated Windows authentication, Basic authentication, and Digest authentication. You'll also see in this article that if you are running your ASP.NET 3.5 pages on IIS 7 and Windows Vista, some of the authentication options will be configured with slightly different steps than in IIS 5.0 and 6.0 on Windows Server 2003 or Windows XP.
In ASP.NET terms, authentication is the process that determines the identity of a user. After a user has been authenticated, a developer can determine if the identified user has authorization to proceed. It is impossible to give an entity authorization if no authentication process has been applied. You should never authorize access to resources you mean to be secure if you have not applied an authentication process to the requests for the resources.
Authorization is the process of determining whether an authenticated user is permitted access to any part of an application, access to specific points of an application, or access only to specified datasets that the application provides. Authenticating and authorizing users and groups enable you to customize a site based on user types or preferences.
The different authentication modes are established through settings that can be applied to the application's web.config file or in conjunction with the application server's Internet Information Services (IIS) instance.
ASP.NET is configured through a series of .config files on the application server. These are XML-based files that enable you to easily change how ASP.NET behaves. This is an ideal way to work with the configuration settings you require. ASP.NET configuration files are applied in a hierarchal manner. The .NET Framework provides a server-level configuration file called the machine.config file, which can be found at C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG. The folder contains the machine.config file. This file provides ASP.NET application settings at a server-level, meaning that the settings are applied to each and every ASP.NET application that resides on the particular server.
A web.config file is another XML-based configuration file that resides in the root of the Web application. The settings applied in the web.config file override the same settings applied in the higher-level machine.config file.
You can even nest the web.config files so that the main application web.config file is located in the root directory of your application, but additional web.config files reside in some of the application's subdirectories (see Figure 1). The web.config files contained in any of the subdirectories supersede the root directory's web.config file. Therefore, any settings applied through a subdirectory's web.config file change whatever was set in the application's main web.config file.
Figure 1
Figure 1 In many cases, you can use the web.config file to apply the authentication and authorization mechanics you want in your applications. You also can work with IIS to apply settings directly to your applications.
IIS is the Web server that handles all the incoming HTTP requests that come to into the server. You must modify IIS to perform as you want. IIS hands a request to the ASP.NET engine only if the page has a specific file extension (for example, .aspx). This article will work with IIS 7.0 as well.

The <authentication> Node

You use the <authentication> node in the application's web.config file to set the type of authentication your ASP.NET application requires:
<system.web>
   <authentication mode="Windows|Forms|Passport|None">


   </authentication>
</system.web>
The <authentication> node uses the mode attribute to set the form of authentication that is to be used. Options include Windows, Forms, Passport, and None. Each option is explained in the following table.
Provider Description
Windows Windows authentication is used together with IIS authentication. Authentication is performed by IIS in the following ways: basic, digest, or Integrated Windows Authentication. When IIS authentication is complete, ASP.NET uses the authenticated identity to authorize access. This is the default setting.
Forms Requests that are not authenticated are redirected to an HTML form using HTTP client-side redirection. The user provides his login information and submits the form. If the application authenticates the request, the system issues a form that contains the credentials or a key for reacquiring the identity.
Passport A centralized authentication service provided by Microsoft that offers single login and core profile services for member sites. This mode of authentication was de-emphasized by Microsoft at the end of 2004.
None No authentication mode is in place with this setting.
As you can see, a couple of methods are at your disposal for building an authentication/authorization model for your ASP.NET applications. This article examines the Windows mode of authentication. In the book, Professional ASP.NET 3.5 (Wrox, 2008, ISBN: 978-0-470-18757-9), Chapter 21, "Security," examines Forms authentication in detail.

Windows-Based Authentication

Windows-based authentication is handled between the Windows server where the ASP.NET application resides and the client machine. In a Windows-based authentication model, the requests go directly to IIS to provide the authentication process. This type of authentication is quite useful in an intranet environment where you can let the server deal completely with the authentication process — especially in environments where users are already logged onto a network. In this scenario, you simply grab and utilize the credentials that are already in place for the authorization process.
IIS first takes the user's credentials from the domain login. If this process fails, IIS displays a pop-up dialog box so the user can enter or re-enter his login information. To set up your ASP.NET application to work with Windows-based authentication, begin by creating some users and groups.

Creating Users

You use aspects of Windows-based authentication to allow specific users who have provided a domain login to access your application or parts of your application. Because it can use this type of authentication, ASP.NET makes it quite easy to work with applications that are deployed in an intranet environment. If a user has logged onto a local computer as a domain user, he will not need to be authenticated again when accessing a network computer in that domain.
The following steps show you how to create a user. It is important to note that you must have sufficient rights to be authorized to create users on a server. If you are authorized, the steps to create users are as follows:
  1. Within your Windows XP or Windows Server 2003 server, choose Start-->Control Panel-->Administrative Tools-->Computer Management. If you are using Windows Vista, choose Start-->Control Panel-->System and Maintenance-->Administrative Tools-->Computer Management. Either one opens the Computer Management utility. It manages and controls resources on the local Web server. You can accomplish many things using this utility, but the focus here is on the creation of users.
  2. Expand the System Tools node.
  3. Expand the Local Users and Groups node.
  4. Select the Users folder. You see something similar to the results shown in Figure 2.

    Figure 2
    Figure 2
  1. Right-click the Users folder and select New User. The New User dialog appears, as shown in Figure 3.

    Figure 3
    Figure 3
  1. Give the user a name, password, and description stating that this is a test user. In this example, the user is called Bubbles.
  2. Clear the check box that requires the user to change his password at the next login.
  3. Click the Create button. Your test user is created and presented in the Users folder of the Computer Management utility, as shown in Figure 4.

    Figure 4
    Figure 4
Now create a page to work with this user.

Authenticating and Authorizing a User

Now create an application that enables the user to enter it. You work with the application's web.config file to control which users are allowed to access the site and which users are not allowed.
Add the section presented in Listing 1 to your web.config file.
Listing 1: Denying all users through the web.config file
<system.web>
   <authentication mode="Windows" />
   <authorization>
      <deny users="*" />
   </authorization>
</system.web>
In this example, the web.config file is configuring the application to employ Windows-based authentication using the <authentication> element's mode attribute. In addition, the <authorization> element is used to define specifics about the users or groups who are permitted access to the application. In this case, the <deny> element specifies that all users (even if they are authenticated) are denied access to the application. Not permitting specific users with the <allow> element does not make much sense, but for this example, leave it as it is. The results are illustrated in Figure 5.
Figure 5
Figure 5 Any end user — authenticated or not — who tries to access the site sees a large "Access is denied" statement in his browser window, which is just what you want for those not allowed to access your application!
In most instances, however, you want to allow at least some users to access your application. Use the <allow> element in the web.config file to allow a specific user. Here is the syntax:
<allow users="Domain\Username" />
Listing 2 shows how the user is permitted access.
Listing 2: Allowing a single user through the web.config file
<system.web>
   <authentication mode="Windows" />
   <authorization>
      <allow users="REUTERS-EVJEN\Bubbles" />
      <deny users="*" />
   </authorization>
</system.web>
Even though all users (even authenticated ones) are denied access through the use of the <deny> element, the definitions defined in the <allow> element take precedence. In this example, a single user—Bubbles—is allowed.
Now, if you are logged on to the client machine as the user Bubbles and run the page in the browser, you get access to the application.

Looking Closely at the <allow> and <deny> Nodes

The <allow> and <deny> nodes enable you to work not only with specific users, but also with groups. The elements support the attributes defined in the following table.
Attribute Description
Users Enables you to specify users by their domain and/or name.
Roles Enables you to specify access groups that are allowed or denied access.
Verbs Enables you to specify the HTTP transmission method that is allowed or denied access.
When using any of these attributes, you can specify all users with the use of the asterisk (*):
<allow roles="*" />
In this example, all roles are allowed access to the application. Another symbol you can use with these attributes is the question mark (?), which represents all anonymous users. For example, if you want to block all anonymous users from your application, use the following construction:
<deny users="?" />
When using users, roles, or verbs attributes with the <allow> or <deny> elements, you can specify multiple entries by separating the values with a comma. If you are going to allow more than one user, you can either separate these users into different elements, as shown here:
<allow users="MyDomain\User1" />
<allow users="MyDomain\User2" />
or you can use the following:
<allow users="MyDomain\User1, MyDomain\User2" />
Use the same construction when defining multiple roles and verbs.

Authenticating and Authorizing a Group

You can define groups of individuals allowed or denied access to your application or the application's resources. Your server can contain a number of different groups, each of which can have any number of users belonging to it. It is also possible for a single user to belong to multiple groups. Pull up the Computer Management utility to access the list of the groups defined on the server you are working with. Simply click the Groups folder in the Computer Management utility, and the list of groups is displayed, as illustrated in Figure 6.
Figure 6
Figure 6 Right-click in the Groups folder to select New Group. The New Group dialog displays (see Figure 7).
Figure 7
Figure 7 To create a group, give it a name and description; then click the Add button and select the users whom you want to be a part of the group. After a group is created, you can allow it access to your application like this:
<allow roles="MyGroup" />
You can use the roles attribute in either the <allow> or <deny> element to work with a group that you have created or with a specific group that already exists.

Authenticating and Authorizing an HTTP Transmission Method

In addition to authenticating and authorizing specific users or groups of users, you can also authorize or deny requests that come via a specific HTTP transmission protocol. This is done using the verb attribute in the <allow> and <deny> elements.
<deny verbs="GET, DEBUG" />
In this example, requests that come in using the HTTP GET or HTTP DEBUG protocols are denied access to the site. Possible values for the verbs attribute include POST, GET, HEAD, and DEBUG.

Integrated Windows Authentication

So far, you have been using the default Integrated Windows authentication mode for the authentication/authorization process. This is fine if you are working with an intranet application and each of the clients is using Windows, the only system that the authentication method supports. This system of authentication also requires the client to be using Microsoft's Internet Explorer, which might not always be possible.
Integrated Windows authentication was previously known as NTLM or Windows NT Challenge/Response authentication. This authentication model has the client prove its identity by sending a hash of its credentials to the server that is hosting the ASP.NET application. Along with Microsoft's Active Directory, a client can also use Kerberos if it is using Microsoft's Internet Explorer 5 or higher.

Basic Authentication

Another option is to use Basic authentication, which also requires a username and password from the client for authentication. The big plus about Basic authentication is that it is part of the HTTP specification and therefore is supported by most browsers. The negative aspect of Basic authentication is that it passes the username and password to the server as clear text, meaning that the username and password are quite visible to prying eyes. For this reason, it is important to use Basic authentication along with SSL (Secure Sockets Layer).
If you are using IIS 5 or 6 to implement Basic authentication for your application, you must pull up IIS and open the Properties dialog for the Web site you are working with. Select the Directory Security tab and click the Edit button in the Anonymous Access and Authentication Control box. The Authentication Methods dialog box opens.
Uncheck the Integrated Windows Authentication check box at the bottom and check the Basic Authentication check box above it (see Figure 8). When you do, you are warned that this method transmits usernames and passwords as clear text.
Figure 8
Figure 8 End by clicking OK in the dialog. Now your application uses Basic authentication instead of Integrated Windows authentication.
If you are using Windows Vista, it is not easy to find the option to enable Basic authentication. Instead, you first have to enable IIS 7 to use Basic authentication by selecting Start-->Control Panel-->Programs-->Programs and Features-->Turn Windows features on or off. From the provided dialog box, navigate to the Internet Information Services section and expand until you arrive at World Wide Web Services-->Security. From here, check the Basic Authentication option and press OK to install. This option is presented in Figure 9.
Figure 9
Figure 9 Once this option is installed, you can then return to the Internet Information Services (IIS) Manager and select the Authentication option in the IIS section for the virtual directory you are focusing on. From there, highlight the Basic Authentication option and select Enable from the Actions pane. This is illustrated in Figure 10.
Figure 10
Figure 10

Digest Authentication

Digest authentication is the final mode you explore in this article. The model alleviates the Basic authentication problem of passing the client's credentials as clear text. Instead, Digest authentication uses an algorithm to encrypt the client's credentials before they are sent to the application server.
To use Digest authentication, you are required to have a Windows domain controller. One of the main issues that arises with Digest authentication is that it is not supported on all platforms and requires browsers that conform to the HTTP 1.1 specification. Digest authentication, however, not only works well with firewalls, but it is also compatible with proxy servers.
You can select Digest authentication as the choice for your application in the same Authentication Methods dialog — simply select the Digest Authentication check box from the properties dialog if you are using IIS 5 or 6. If you are using IIS 7, you need to install Digest Authentication just as you installed Basic Authentication. Once installed, you will find this option and will be able to enable it from the Authentication section within the IIS Manager.
This excerpt is from Chapter 21, "Security," of the upcoming Professional ASP.NET 3.5: in C# and VB (Wrox, Feb-2008, ISBN: 978-0-470-18757-9). Bill Evjen (St. Louis, MO) is one of the most active proponents of the .NET technologies. He has been involved with .NET since 2000 and has founded the International .NET Association, representing more than 500,000 members worldwide. In addition to working in the .NET world, Bill is a Technical Director serving in the office of the Chief Scientist for the international news and financial services company Reuters. Bill is the lead co-author of the upcoming (Feb-2008) Professional ASP.NET 3.5: in C# and VB and the best-selling ASP.NET 2.0 book, Professional ASP.NET 2.0. Other related articles of interest by Bill and his co-authors, Scott Hanselman and Devin Rader, include Manipulating ASP.NET Pages and Server Controls with JavaScript, Connecting to Oracle or Access from ASP.NET 2.0, Using the ASP.NET 2.0 SQL Server Cache Dependency, and ASP.NET 2.0 FileUpload Server Control.

Tuesday 13 December 2011

Narayana Murthy is the Non-Executive Chairman and Chief Mentor of Infosys Technologies Limited

Born: August 20, 1946
Achievement: One of the founders of Infosys Technologies Limited; Chosen as the World Entrepreneur of the Year - 2003 by Ernst and Young

Narayana Murthy is the Non-Executive Chairman and Chief Mentor of Infosys Technologies Limited. He is a living legend and an epitome of the fact that honesty, transparency, and moral integrity are not at variance with business acumen. He set new standards in corporate governance and morality when he stepped down as the Executive Chairman of Infosys at the age of 60.

Born on August 20, 1946, N.R. Narayana Murthy is a B.E. Electrical from University of Mysore (1967) and M.Tech from IIT Kanpur (1969). Narayan Murthy began his career with Patni Computer Systems in Pune. In 1981, Narayana Murthy founded Infosys with six other software professionals. In 1987, Infosys opened its first international office in U.S.A.

With the liberalization of Indian economy in 1990s, Infosys grew rapidly. In 1993, the company came up with its IPO. In 1995, Infosys set up development centers across cities in India and in 1996, it set up its first office in Europe in Milton Keynes, UK. In 1999, Infosys became the first Indian company to be listed on NASDAQ. Today (in 2006), Infosys has a turnover of more than $ 2billion and has employee strength of over 50,000. In 2002, Infosys was ranked No. 1 in the "Best Employers in India 2002" survey conducted by Hewitt and in the Business World's survey of "India's Most Respected Company." Conducted in the same year.

Along with the growth of Infosys, Narayana Moorthy too has grown in stature. He has received many honors and awards. In June 2000, Asiaweek magazine featured him in a list of Asia's 50 Most Powerful People. In 2001, Narayana Murthy was named by TIME/CNN as one of the 25 most influential global executives. He was the first recipient of the Indo-French Forum Medal (2003) and was voted the World Entrepreneur of the Year - 2003 by Ernst and Young. The Economist ranked Narayana Murthy eighth on the list of the 15 most admired global leaders (2005) and Narayan Murthy also topped the Economic Times Corporate Dossier list of India's most powerful CEOs for two consecutive years - 2004 and 2005.

day to prevent in calender

if (e.Day.Date < DateTime.Now)
        {

            e.Day.IsSelectable = false;
        }

day highlight in calender

  if (e.Day.DayNumberText == "20")
        {

            e.Cell.Controls.Add(new LiteralControl("<p>GITM</p>"));
            e.Cell.BorderColor = System.Drawing.Color.Blue;
            e.Cell.BorderWidth = 1;
            e.Cell.BorderStyle = BorderStyle.Groove;
            e.Cell.BackColor = System.Drawing.Color.LightGoldenrodYellow;
        }

<January 2012>
SuMoTuWeThFrSa
25262728293031
1234567
891011121314
151617181920GITM21
22232425262728
2930311234

Monday 12 December 2011

Delete Duplicate rows from the table.


Delete Duplicate rows from the table.
Suppose there is a table called "EmployeeTable" which have some duplicate records.
There is a three way to delete the duplicate rows.

First way to delete duplicate rows :


Select distinct * into Emp_Temp_Table from EmployeeTable

In the above line we are inserting all the distinct row of the "EmployeeTable" to another table "Emp_Temp_Table" (Emp_Temp_Table will create automatically when you use the above query.)
Actuall the above query create clone of EmployeeTable and insert all the distinct row inside the Clone Table (Emp_Temp_Table).


drop table EmployeeTable

sp_rename 'Emp_Temp_Table',EmployeeTable'

Then Delete the orginal table and rename the clone table with the name of orginal table.


Second way to delete duplicate rows :

Select distinct * into Emp_Temp_Table from EmployeeTable

Truncate table EmployeeTable

insert into EmployeeTable select * from Emp_Temp_Table

drop table Emp_Temp_Table


Third way to delete duplicate rows :

Populate the new Primary Key


Alter table EmployeeTable add NewPK int NULL
Go
Declare @intCounter int
Set @intCounter = 0
Update EmployeeTable
SET @intCounter = NewPK = @intCounter + 1

Select name,RecCount=count(*), PktoKeep = max(NewPK)
Into #dupes
From EmployeeTable
Group by name
Having count(*) > 1
Order by count(*) desc

Wednesday 30 November 2011

cookies concept in asp.net

o write a cookie by creating an instance of the HttpCookie object

  1. Create an object of type HttpCookie and assign it a name.
  2. Assign values to cookie's subkeys and set any cookie properties.
  3. Add the cookie to the Cookies collection.
    The following code example shows an instance of the HttpCookie object named myCookie, which represents a cookie named UserSettings.
    HttpCookie myCookie = new HttpCookie("UserSettings");
    myCookie["Font"] = "Arial";
    myCookie["Color"] = "Blue";
    myCookie.Expires = DateTime.Now.AddDays(1d);
    Response.Cookies.Add(myCookie);
    Read a string from the Cookies collection using the cookie's name as the key.
     
    if (Request.Cookies["UserSettings"] != null)
    {
        string userSettings;
        if (Request.Cookies["UserSettings"]["Font"] != null)
        { userSettings = Request.Cookies["UserSettings"]["Font"]; }
    }
     

Wednesday 16 November 2011

girdview values delete by combo box in asp.net

HTML clipboard
asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="SqlDataSource1" AllowPaging ="true" DataKeyNames ="Roll">
            <Columns>
                <asp:TemplateField HeaderText="ROLL">
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" Text='<%# Eval("Roll") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            </Columns>
        </asp:GridView>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:goelConnectionString %>"
            SelectCommand="SELECT * FROM [stu]"></asp:SqlDataSource>
  
    </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
        style="width: 74px" Text="DELETE" />
    </form>
 
 
protected void Button1_Click(object sender, EventArgs e)
{

        bool atLeastOneRowDeleted = false;
     foreach (GridViewRow row in GridView1.Rows)

    CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
    if (cb != null && cb.Checked)
{
        atLeastOneRowDeleted = true;
        // First, get the ProductID for the selected row
    int productID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value); // "Delete" the row
   

    SqlConnection sq = new SqlConnection("data source=MCQL;initial catalog=goel;user id=sa;password=lko.123");
    sq.Open();
    SqlCommand cmd = new SqlCommand("delete from stu where Roll='" + productID.ToString() + "'", sq);
    cmd.ExecuteNonQuery();
    Label1.Text += string.Format("This would have deleted ProductID {0}<br />", productID);
}
        // Show the Label if at least one row was deleted...
Label1 .Visible = atLeastOneRowDeleted;
   
    }

checkbox added in gridview

. right click on your DataGrid -->Property Builder -->Columns --> Template Column --> Apply --> Ok.
2. Right click again --> EidtTemplate --> choose Column you add --> drag CheckBox control from Toolbox and drop it in ItemTemplate field and if you need CheckBox in edit mode put another CheckBox control in EditItemTemplate field --> End Template Editing.

Code on the button:

  1. private void btn_Delete_Click(object sender, System.EventArgs e)
  2. {
  3. for(int i=0;i<dg_EditProduct.Items.Count;i++)
  4. {
  5. CheckBox chk = new CheckBox();
  6. chk = (CheckBox)dg_EditProduct.Items[i].FindControl("chk_Delete");
  7. if(chk.Checked)
  8. {
  9. DataTable myTable;
  10. myTable=(DataTable)Session["ProductTable"];
  11. int ID_Delete = Convert.ToInt32( myTable.Rows[i]["ProductID"]);
  12. Str_Conn = ConfigurationSettings.AppSettings["Fashion"];
  13. MyConn = new SqlConnection(Str_Conn);
  14. //Command to delete Product
  15. // SqlCommand cmd_DeleteProduct = new SqlCommand("dbo.DeleteProduct",MyConn);
  16. SqlCommand cmd_DeleteProduct = new SqlCommand("DeleteProduct",MyConn);
  17. cmd_DeleteProduct.CommandType = CommandType.StoredProcedure;
  18. SqlParameter ProductID_Delete = cmd_DeleteProduct.Parameters.Add("@ProductID",SqlDbType.Int);
  19. ProductID_Delete.Value = ID_Delete ;
  20. MyConn.Open();
  21. dg_EditProduct.DataSource = myTable;
  22. cmd_DeleteProduct.ExecuteNonQuery();
  23. MyConn.Close();
  24. }
  25. }
  26. BindData(); // it is the function you use to bind data to datagrid on page load
  27. }

Monday 14 November 2011

GRID VIEW HANDLING CONCEPT


Your project or website must be ASP.NET AJAX enabled website. Because we are going to add the GridView in an UpdatePanel. So your GridView control will be look smart without unnecessary postbacks. You need to create a Customer Table with 6 columns for Customer Code[Code], Name[Name], Gender[Gender], City[City], State[State] and Customer Type[Type], with your desired data types. Then create a class file in your App_Code folder and create a Default.aspx along with code-behind file Default.aspx.cs.

Step 1. Create Class File ‘CustomersCls.cs’

We need to create a class file to do database manipulations such as select, insert, delete and update data in the Customer Table. So we add a class file as ‘CustomersCls.cs’ in App_Code section. Let us write five methods in the class file as follows
public void Insert(string CustomerName, string Gender, string City, string State, string CustomerType)
{
    // Write your own Insert statement blocks
}

public DataTable Fetch()
{
  // Write your own Fetch statement blocks, this method should return a DataTable
}

public DataTable FetchCustomerType()
{
  // Write your own Fetch statement blocks to fetch Customer Type from its master table and this method should return a DataTable
}

public void Update(int CustomerCode, string CustomerName, string Gender, string City,  string CustomerType)
{
  // Write your own Update statement blocks.
}

public void Delete(int CustomerCode)
{
  // Write your own Delete statement blocks.
}
Step 2: Make Design File ‘Default.aspx’

In the Default.aspx page, add an UpdatePanel control. Inside the UpdatePanel, add a GridView, set AutoGenerateColumns as False. Change the ShowFooter Flag to True and set the DataKeyNames your column name for Customer Code and Customer Type, in our case it is Code and Type. Then click on the Smart Navigation Tag of the GridView control, choose Add New Column and add 5 BoundField columns with DataField values as Name, Gender, City, State and Type, plus 2 CommandField columns with one for Edit/Update and another for Delete functions. Now your GridView control is ready. But as first step, we need to add some new records into the database. For that we need to place the controls in the Footer row. So we have to convert all these BoundField columns as TemplateField columns. To do this again, click on the Smart Navigation Tag on the GridView choose Edit Columns, the Field’s property window will open. Select column by column from Name to Customer Type, include also Edit column, and select ‘Convert this field into a TemplateField’. Now all the BoundField columns will be converted to TemplateField columns except the Delete column.
Column[0] – Name

Right click on the GridView control, select Edit Template, choose column[0] – Name, you can view a label placed in the ItemTemplate section and a TextBox placed in the EditItemTemplate section. Add another Texbox in the FooterTemplate section and name it as txtNewName.

Column[1] - Gender

Now again select Edit Template, choose column[1] - Gender, replace the TextBox with a DropDownList, name it as cmbGender, add Male and Female as their ListItem values. On the Edit DataBindings of the cmbGender, add Eval("Gender") to its selectedvalue. Add another DropDownList in the FooterTemplate section and name it as cmbNewGender.

Column[2] –City & Column[3] - State

Add Texboxes in both column’s FooterTemplate section and name it as txtNewCity and txtNewState respectively.

Column[4] - Type

In this column’s EditItemTemplate section, replace the TextBox with a DropDownList, name it as cmbType. Also add another DropDownList in the FooterTemplate section and name it as cmbNewType. Both these DropDownList’s we are going to fill with dynamic data from database. So specify both DropDownList’s DataTextField and DataValueField as Type.

Column[5] - Edit

Just add a link button into the FooterTemplate section, specify its CommandName property as ‘AddNew’.

For your persual, we have provided the complete source code of the GridView control below. The State column in our sample is read-only. So you cannot find TextBox for that column in the EditItemTemplate section.
http://www.aspdotnetcodes.com/Images/collapse.jpgClick here to view Source Code of the GridView Control [Show full code..]
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Code, Type" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand" ShowFooter="True" OnRowDeleting="GridView1_RowDeleting">
<Columns>

<asp:TemplateField HeaderText="Name" SortExpression="Name"> <EditItemTemplate>
  <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewName" runat="server"></asp:TextBox> </FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Gender">
<EditItemTemplate>
  <asp:DropDownList ID="cmbGender" runat="server" SelectedValue='<%# Eval("Gender") %>'>
    <asp:ListItem Value="Male" Text="Male"></asp:ListItem>
    <asp:ListItem Value="Female" Text="Female"></asp:ListItem>
  </asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
  <asp:Label ID="Label2" runat="server" Text='<%# Eval("Gender") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
  <asp:DropDownList ID="cmbNewGender" runat="server" >
    <asp:ListItem Selected="True" Text="Male" Value="Male"></asp:ListItem>
    <asp:ListItem Text="Female" Value="Female"></asp:ListItem> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="City">
<EditItemTemplate>
  <asp:TextBox ID="txtCity" runat="server" Text='<%# Bind("City") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewCity" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label3" runat="server" Text='<%# Bind("City") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="State" SortExpression="State">
<EditItemTemplate>
  <asp:Label ID="Label1" runat="server" Text='<%# Eval("State") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewState" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label4" runat="server" Text='<%# Bind("State") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Type">
<EditItemTemplate>
  <asp:DropDownList ID="cmbType" runat="server" DataTextField="Type" DataValueField="Type"> </asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
  <asp:Label ID="Label5" runat="server" Text='<%# Eval("Type") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
  <asp:DropDownList ID="cmbNewType" runat="server" DataTextField="Type" DataValueField="Type"> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />

</Columns>
</asp:GridView>


Step 3: Make Code-behind File ‘Default.aspx.cs’

Now we are going to do the code-behind part of this page. Les us explain you event by event coding on each methods. In the code-behind page, create an instance for the Customer class as follows
CustomersCls customer=new CustomersCls();

Then create a private method 'FillCustomerInGrid' to retrieve the existing customer list from the database and bind it to the GridView. The CustomersCls class’s Fetch() method is used and it returns the data to a DataTable. On first stage it will return empty rows. So you cannot see any header, data or even footer rows of the GridView control. You can only see an empty space or you see only the EmptyDataText. So you cannot add any new data from the footer row.
private void FillCustomerInGrid()
{
   DataTable dtCustomer= customer.Fetch();

 if (dtCustomer.Rows.Count>0)
 {
    GridView1.DataSource = dtCustomer;
    GridView1.DataBind();
 }
 else
 {
      dtCustomer.Rows.Add(dtCustomer.NewRow());
      GridView1.DataSource = dtCustomer;
      GridView1.DataBind();

      int TotalColumns = GridView1.Rows[0].Cells.Count;
      GridView1.Rows[0].Cells.Clear();
      GridView1.Rows[0].Cells.Add(new TableCell());
      GridView1.Rows[0].Cells[0].ColumnSpan = TotalColumns;
      GridView1.Rows[0].Cells[0].Text = "No Record Found";
  }
}

In this article, we have provided a workaround to fix this problem. Closely look at the method FillCustomerInGrid, there is a conditional statement to check the rows exists in DataTable or not. Now go to the else part of the if statement, see the block of code we provided there. Simply we have added an empty row to the DataTable. Then bind it to the GridView control. To give a professional look to the GridView control, we do little bit more by providing ColumnSpan and set a Text as "No Record Found", this text will be displayed if the GridView is empty without any rows and you can see both the Header and Footer of the GridView control.

Initialize GridView control

In the page load event, we have to call this FillCustomerInGrid method as follows,
protected void Page_Load(object sender, EventArgs e)
{
  If (!IsPostBack)
  {
     FillCustomerInGrid();
   }
}

Fill DropDownList in GridView with dynamic values

In column[4] - Type, there are two DropDownList controls, one in the EditItemTemplate section (cmbType) and another in FooterTemplate (cmbNewType). We have to fill both these DropDownList controls with some dynamic data. If you look at our CustomersCls class, we have a separate method called FetchCustomerType. In the RowDataBound event of the GridView control insert the following code.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
   DropDownList cmbType = (DropDownList)e.Row.FindControl("cmbType");

  if (cmbType != null)
  {
    cmbType.DataSource = customer.FetchCustomerType();
    cmbType.DataBind();
    cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();
   }
 }

if (e.Row.RowType == DataControlRowType.Footer)
{
    DropDownList cmbNewType = (DropDownList)e.Row.FindControl("cmbNewType");
    cmbNewType.DataSource = customer.FetchCustomerType();
    cmbNewType.DataBind();
 }

}


Previously in this article, we have set the DataKeyNames values as Code, Type. If you see in the above code, we use one of the DataKeyNames value as the SelectedValue for the cmbType control, this is to retain the value of the cmbType in EditMode. The index value of Code is 0 and Type is 1. So we use as follows
cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();

So far we have initialized the GridView control with the datatable and also make some values to be filled in the Footer DropDownList cmbNewType. Run the application, you can see the GridView only with the Footer row and data in the cmbNewType control. Let us start to code for adding new records into the database when we click ‘Add New’ linkbutton.

Add New Records from GridView control

Create an event for the GridView’s RowCommand and add the following code in it.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName.Equals("AddNew"))
  {
   TextBox txtNewName=(TextBox)GridView1.FooterRow.FindControl("txtNewName");
   DropDownList cmbNewGender = (DropDownList)GridView1.FooterRow.FindControl("cmbNewGender");
   TextBox txtNewCity = (TextBox)GridView1.FooterRow.FindControl("txtNewCity");
   TextBox txtNewState = (TextBox)GridView1.FooterRow.FindControl("txtNewState");
   DropDownList cmbNewType = (DropDownList)GridView1.FooterRow.FindControl("cmbNewType");

   customer.Insert(txtNewName.Text, cmbNewGender.SelectedValue, txtNewCity.Text, txtNewState.Text, cmbNewType.SelectedValue) ;
      FillCustomerInGrid();
  }
}

In the above code, we are declaring and finding the controls in the GridView’s footer section and use the CustomersCls class insert method to add the new data into the database. Then we are calling the FillCustomerInGrid method to fill the GridView control with the newly inserted values. Now save everything and run your application. Put some test data in the Textboxes and select some values in the DropDownLists and click on the Add New linkbutton. You can see data inserted into the database and listed in the GridView control.
Edit and Update in GridView

In the RowEditing event of the GridView, add the following lines of code. This will switch a specific row of the GridView to Edit Mode.

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
  GridView1.EditIndex = e.NewEditIndex;
  FillCustomerInGrid();
}

After the GridView swithes to Edit Mode, you can view the TextBoxes and DropDownlList controls along with Update and Cancel linkbuttons in the Edit mode. To cancel this action, add the following two lines of code in the GridView’s RowCancelingEdit event.
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
  GridView1.EditIndex = -1;
   FillCustomerInGrid();
}
You can update the data to the customer table, by adding the following lines of code in the GridView’s RowUpdating event.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
  TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
  DropDownList cmbGender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbGender");
  TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity");
  DropDownList cmbType = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbType");

 customer.Update(GridView1.DataKeys[e.RowIndex].Values[0].ToString(),txtName.Text, cmbGender.SelectedValue,txtCity.Text, cmbType.SelectedValue);
  GridView1.EditIndex = -1;
  FillCustomerInGrid();
}