Monday, October 26, 2009

C# Object oriented programming concepts

Object oriented programming is a successful paradigm shift from procedural world. Representing a real world entity through an object and encapsulating data and behavior together in an object are some of basics of OOPS world. Object oriented has showered us with many benefits esp. code re usability through inheritance and abstraction.  At the same time, we are pushed into complex world filled with classes, contracts, objects and relationships between them. Polymorphism, encapsulation, messaging, abstraction are OOPS concepts.

There are three kinds of relationships between objects

Association:  Simple relationship which relates two objects. Customer object is related to sales object. 

Aggregation: It is containment or composition model. Example: page class encompasses controls on the page.

Inheritance:  Defining specialized derived classes from preexisting generalized classes. It shows more of a parent-child relationship like vehicle -> car


Abstract classes and Interfaces:


A class can implement more than one interface but can only inherit from one abstract class. Since C# doesn't support multiple inheritance, interfaces are used to implement multiple inheritances. All elements in interfaces are public by default.

An abstract class can contain non-abstract methods. i.e methods with code in it.
An interface cannot contain non-abstract methods. Abstract classes SHOULD have atleast one method abstract and interfaces have all abstract methods.

Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.

An abstract class defines the core identity of a class and there it is used for objects of the same type.

An abstract class can contain non-static member variables.
An interface cannot contain non-static member variables.

A derived class uses the keyword "Extends" for an abstract class.
A subclass uses the keyword "Implements" for an interface.

If the subclass extends an abstract class, it cannot extend any other class.
If the subclass implements an interface, it can implement any number of other interfaces.

If the various implementations only share method signatures then it is better to use interfaces ( Multiple behaviors for different conditions)

Abstract classes provide a simple and easy way to version our components. By updating the base class, all the inheriting classes are automatically updated with the change. In an interface, creation of additional functions will have an effect on its child classes due to the necessary implementations of interface methods in classes. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.

Say there are two classes, bird and airplane, and both of them have methods called fly. It would be ridiculous for an airplane to inherit from the bird class just because it has fly() method. Rather, the fly() method should be defined as an interface and both bird and airplanes should implement that interface. If we want to provide common, implemented functionality among all implementations of component.

In VB.Net language, abstract classes are created using "MustInherit" keyword. In C#, we have "Abstract" keyword. Abstract class is designed to act as a base class. You cannot create a object of abstract class.

Shadowing:

When two elements in a program have same name, one of them can hide and shadow the other one. So in such cases the element which shadowed the main element is referenced.

Differences between overriding and shadowing:

  • Overriding redefines only the implementation while shadowing redefines the whole element.

Sealed classes:

The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class. In .Net Framework, string is a sealed class.

Virtual keyword: (Overridable)
They signify  that method and property can be overridden.

Static/Shared:

  • If you want an object to be shared between multiple instances you will use a static/shared class.
  • Static classes cannot be instantiated. By default, an object is created on the first method call to that object.
  • Static classes cannot be inherited. 
  • Static classes can have only static members.
  • Static classes can have only static constructor

Structures and classes:

  • Structures are value types and classes are reference types. So structures use stack and classes use heap. 
  • Structure members cannot be declared as protected, but class member can be.
  • You cannot define inheritance in structures.
  • Structures do not require constructors while classes require.
  • Objects created from classes are terminated using garbage collector while structures are not destroyed GC



Thursday, October 22, 2009

ASP.Net Instrumentation - Tracing

Tracing in ASP.NET 3.5:

Tracing is a way to monitor the execution of your ASP.NET application. You can record exception details and program flow in a way that doesn’t affect the program’s output. In ASP.NET 3.5, there is rich support for tracing. The destination for trace output can be configured with TraceListeners like the EventLogTraceListener.

ASP.NET 3.5 Improvements for Tracing:

  • ASP.NET Tracing has increased precision from 6 digits to 18 digits for highly accurate profiling.

  • Trace forwarding between the ASP.NET page-specific Trace class and standard Base Class Library’s (BCL) System.Diagnostics.Trace used by non-Web developers.

First, we will explore ASP. Net’s tracing facilities first, and then learn how to bridge the gap and see some new features in 3.5 that make debugging even easier.

Page level Tracing:

ASP.NET tracing can be enabled on a page-by-page basis by adding “Trace=true” to the Page directive in any ASP.NET page:

<%@ Page Language="C#" Trace="true" TraceMode = "SortByCategory" Inherits  = "System.Web.UI.Page" CodeFile="Default.aspx.cs" %>

Additionally, you can add the TraceMode attribute that sets SortByCategory or the default, SortByTime. You can use SortByTime to see the methods that take up the most CPU time for your application. You can enable tracing programmatically using the Trace.IsEnabled property.

Application Tracing:

You can enable tracing for the entire application by adding tracing settings in web.config. In below example, pageOutput=”false” and requestLimit=”20” are used, so trace information is stored for 20 requests, but not displayed on the page because pageOutput attribute is set to false.

<configuration>
    <appSettings/>
    <connectionStrings/>
    <system.web>
        <compilation debug="false" />
        <authentication mode="Windows" />
      <trace enabled ="true" pageOutput ="false" requestLimit ="20" traceMode ="SortByTime " />       
    </system.web>
</configuration>

The page-level settings take precedence over settings in Web.config, so if enabled=”false” is set in Web.config but trace=”true” is set on the page, tracing occurs.

Viewing Trace Data:

Tracing can be viewed for multiple page requests at the application level by requesting a special page called trace.axd. When ASP.NET detects an HTTP request for trace.axd, that request is handled by the TraceHandler rather than by a page.

Create a website and a page, and in the Page_Load event, call Trace.Write(). Enable tracing in Web.config as shown below

<system.web>
        <compilation debug="false" />
        <authentication mode="Windows" />
      <trace enabled ="true" pageOutput ="true"  />       
    </system.web>

protected void Page_Load(object sender, EventArgs e)
    {
        System.Diagnostics.Trace.Write("This is Page_Load method!");

    }


When you run the page, you can see a great deal of trace information in the browser because we have set PageOutput=true as shown below


Trace Information

The message from Trace.write appears after Begin Load and before End Load. Eleven different sections in Trace provide a great deal of information.

Request Details: This section includes the ASP.NET Session ID, the character encoding of the request and response, and the HTTP conversation’s returned status code.

TraceInformation: This section includes all the Trace.write methods called during the lifetime of the HTTP request and a great deal of information about timing. The timing information located here is valuable when profiling and searching for methods in your application that take too long to execute.


Trace Information

Control Tree: Control tree presents an HTML representation of the ASP.NET Control Tree. Shows each control’s ID, run time type, the number of bytes it took to be rendered, and the bytes it requires in View State and Control State.

Session State:  Lists all the keys for a particular user’s session, their types and their values.

Application State: Lists all the keys in the current application’s Application object and their type and values.

Request Cookies: Lists all the cookies passed in during the page is requested

Response Cookies: Lists all the cookies that were passed back during the page’s response.

Headers Collection: Shows all the headers that might be passed in during the request from the browser, including Accept-Encoding, indicating whether the browser supports the compressed HTTP responses and Accept languages.

Form Collection: Displays a complete dump of the Form Collection and all its keys and values.

QueryString Collection: Displays a dump of the Querystring collection and all its contained keys and values

Server Variables: A complete dump of name-value pairs of everything that the web server knows about the application

Trace.axd:

    Page output of tracing shows only the data collected for the current page request. However, if you want to collect detailed information for all the requests then we need to use Trace.axd.  We can invoke Trace.axd tool for the application using the following URL http://localhost/application-name/trace.axd. Simply replace page name in URL with Trace.axd. That is, in our case. We should use following URL (Address bar) for our application as shown below.


Application Trace

Trace.axd displays all the tracing information for all requests up to a present limit. Above figure shows that three requests have been made to this application and the right side of the header indicates “Remaining:7” That means that there is seven more requests remaining before tracing stops for this application. After that final request, tracing data is not saved until an application recycle or until you click “Clear Current Trace” from the Trace.axd page. The request limit can be raised in Web.config by setting requestLimit to a higher value as shown below

<trace enabled ="true" requestLimit ="20" pageOutput ="true"/>

Trace forwarding:

ASP.NET 3.5 introduced new attribute to Web.config <trace> element that allows you to route messages emitted by ASP.NET tracing to System.Diagnostics.Trace:writeToDiagnosticsTrace.

<trace enabled ="true" requestLimit ="20" writeToDiagnosticsTrace ="true " pageOutput ="true"/>

When you set writeToDiagnosticsTrace to true, all calls to System.Web.UI.Page.Trace.Write(the ASP.NET TraceContent) also go to System.Diagnostics.Trace.Write, enabling you to use all the standard TraceListeners. The simple writeToDiagnosticsTrace setting connects the ASP.NET tracing functionality with the rest of the base class library.

New Trace Listeners in ASP.NET 3.5:

The new ASP.NET 3.5 WebPageTraceListener derives from System.Diagnostics.TraceListener and automatically forwards tracing information from any component calls to System.Diagnostics.Trace.Write. This enables you to write your components using the most generic trace provider and to see its tracing output in the context of your ASP.NET application

The WebPageTraceListener is added to the web.config as shown below

<system.diagnostics>
    <trace autoflush ="false" indentsize ="4">
      <listeners>
        <add name="webListeners"
             type="System.Web.WebPageTraceListener, System.Web" />
         </listeners>
    </trace>
  </system.diagnostics>

XmlWriterTraceListener:

XmlWriterTraceListener derives from TextWriterTraceListener and writes out a strongly typed XML file. The XML created is not well formed. Specifically, it doesn’t have root node. It’s just collection of peer nodes.

DelimitedListTraceListener:

DelimitedListTraceListener derives from TextWriterTraceListener. It writes out comma-separated values (CSV) files.

Membership provider and Login controls explained in ASP.NET 3.5

New Security Features in ASP.NET 3.5

Security is an important attribute of any ASP.NET application. The authentication and authorization of users and resistance against the malicious attacks are important tasks in web applications.  In ASP.NET 1.x introduced new authentication service called Forms-based authentication which involves authenticating users and redirecting unauthenticated users again to Login page. It also performs necessary cookie management. This kind of authentication was fine in many ways, but it required developers to build every element including Login page User Interface and create necessary tables to manage user accounts.
                
        ASP.NET 3.5 introduced a new membership and role management service that provides both authentication and authorization services and management of users who access your application with out building any tables or writing any code. To achieve this Microsoft implements extensible provider based security model in ASP.NET 3.5

Security Model:

ASP.NET 3.5 provides two providers in new security model

  • Membership Provider
  • Role Provider

                 The extensible Membership provider framework can register and authenticate new users. Membership provider uses Microsoft SQL Server as the back-end data store. Role providers are used to manage user roles like creating new roles for users. This Provider based framework also includes new API that allows for programmatic access to both membership and role management services.

Membership Provider:
                           
                                  The provider model in ASP.NET 3.5 provides pluggable architecture for developers to plug their own implementations for creating custom membership providers. The provider model begins with the abstract class ProviderBase. Inheriting from ProviderBase are the MembershipProvider and RoleProvider abstract classes. These classes add additional properties and methods to define the interface for their custom needs. Below listings should give you a concrete idea.


MembershipProvider abstract class Listing


RoleProvider abstract class Listing
                                  
ASP.NET 3.5 ships with two membership providers: the SqlMembership provider and the AccessMembership provider. As name implies, Sqlmembership provider stores membership information in a SQL Server database. Similarly, AccessMembership provider stores membership information in Access database. You can also create custom membership provider using any OLEDB DataSource or XML data source. But you need to implement all the methods and properties of the abstract MembershipProvider class.


:

.
SqlMembership Provider:
Unlike the Microsoft Access Provider, before you can use the SQL Provider you must create the necessary database tables and stored procedures. You can automatically create all of the required SQL Server database objects by executing the aspnet_regsql tool from the command line. This tool, by default, creates a new database named aspnetdb on your local instance of SQL Server. Let’s see how to configure aspnetdb using aspnet_regsql tool in below series of listings.
When we run aspnet_regsql from command prompt the following wizard opens up to configure aspnetdb database

Click Next



Choose Configure SQL Server for application services to create new database to membership information and click next



Specify the server name and authentication mode for membership database and click next



Summary of settings which you have specified and once you are done, click next



Database has been created and you can now configure the provider for membership. Click finish to end the wizard.

After you create the new database, you'll want to make sure the database can be accessed by your ASP.NET application. You can find default membership provider settings for the server by looking at the machine.config file


<membership>
      <providers>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="LocalSqlServer"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression="" />
      </providers>
    </membership>
Machine.config filesettings for sqlmembership provider

Configuring Membership Provider Properties:

The SqlMembershipProvider support several provider specific attributes:
  • ApplicationName: If you need to host multiple applications on the same Web server, you can use this property to isolate the users who are associated with the different applications.
  • ConnectionStringName: The name of a database connection string defined in the connectionStrings section of the Web configuration file.
  • Description: A description of the provider definition.
  • EnablePasswordReset: When true, users can reset their password to a randomly generated password.
  • EnablePasswordRetrieval: When true, user passwords can be retrieved from the Membership provider.
  • PasswordFormat: This property has three possible values: Clear, Encrypted, and Hashed. When passwords are hashed, the original passwords cannot be retrieved from the Membership Provider.
  • RequiresQuestionAndAnswer: When true, the user must answer a password retrieval question before the user password can be reset or retrieved.
  • RequiresUniqueEmail: When true, a unique e-mail address must be associated with each user.
You can use these Membership Provider attributes to control how membership information is stored and retrieved from the database. The values of these attributes can be changed in your application's Web configuration file. For example:
By default, the machine.config file configures membership and roles to work with a SQL Server Express database file in the App_Data directory. Looking back at the configuration listing above, we see the connectionStringName property is “LocalSqlServer”. If you locate the connectionStrings section of machine.config you’ll find the following:
<connectionStrings>
    <add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
  </connectionStrings>
ConnectionStrings section of machine.config file
One you’ve configured a database for the provider to use, you can modify the web.config file for your application to redefine the LocalSqlServer connection string to point to the new database.
<connectionStrings>
  <remove name="LocalSqlServer"/>
  <add name="LocalSqlServer"
       connectionString="server=.;database=aspnetdb;integrated security=sspi;"/>   
</connectionStrings>


Testing the Settings Using Web Site Administration Tool:

You can also test above created settings with the ASP.NET Configuration tool. You can open the Web Site Administration Tool by selecting ASP.NET Configuration from under the Website menu. You can also navigate directly to the Web Site Administration Tool by requesting the special page WebAdmin.axd. For example, if your application is located in a virtual directory named MyWebApp on your local machine, you can open the Website Administration Tool for your application by entering the following URL in your Web browser.
http://localhost/MyWebApp/WebAdmin.axd

Web site Administration Tool is opened when you run the above URL in IE as shown below


Click different provider for each feature link. We are referring sqlmembershipProvider as AspNetSqlProvider becoz it is named in machine.config. refer to machine.config listing above



Click Test link if you want to test AspNetSqlMembershipProvider and once test is successful click back to return from web site administration tool.


Login Controls:

ASP.NET 3.5 contains a new set of security-related controls, known collectively as the Login controls. By taking advantage of the Login controls, you can create standard registration, login, and password recovery pages without writing any code. By default, login controls integrate with ASP.NET membership and forms authentication to help automate user authentication for your Web site. The Login control, for example, will ultimately call the ValidateUser method of the current membership provider when a user enters their username and password and clicks the Login button. There is no need to write any code if the built-in controls provide all the functionality you need. All of the controls allow customization various levels of customization through styles and templates. You can find the controls in the Visual Studio toolbox under the “Login” category.
Behind the scenes, the Login controls take full advantage of the Provider Model. If the SqlMembershipProvider is enabled, the configured SQL Server database is used by the controls.
Before using any of the Login controls, you should enable Forms Authentication for your application. You can enable Forms Authentication by modifying your application's Web configuration file, or by using the Web Site Administration Tool.
Different Login and Password server Controls:

  • CreateUserWizard server control
  • Login server Control
  • LoginStatus Server Control
  • LoginName Server Control
  • ChangePassword Server Control
  • PasswordRecovery Server Control
  • LoginView Server Control

                                                      CreateUserWizard server control enables you to plug registered users into your data store for later retrieval. LoginStatus Server control enables users to click a link to log in or log out of a site. LoginName server control enables you to display the username of the authenticated user. PasswordRecovery control enables to retrieve password for the user. ChangePassword as the name implies allows changing the password for the user. Login server control provides Login mechanism for application.




Login Server Control:
The Login server Control display standard login interface for user authentication. The Login control can be used as a standalone control on a main or home page, or you can use it on a dedicated login page.
If you use the Login control with ASP.NET membership, you do not need to write code to perform authentication. However, if you want to create your own authentication logic, you can handle the Login control's Authenticate event and add custom authentication code.
Create an ASP.NET Web application that uses ASP.NET membership. Create an ASP.NET Web page in your application named Login.aspx. By default, ASP.NET forms authentication is configured to work with a page named Login.aspx. You can change the default login page name in the Web.config file for your application using the LoginUrl property.

Following example shows the markup for a Login control:
<asp:Login ID="Login1" runat="server" DestinationPageUrl="~/MembersHome.aspx"> </asp:Login>


Login Control on Default page listing
When you submit your username and password by using the Login control, your credentials are automatically validated by the configured Membership Provider.
Login Control properties:
  • FailureText: used to control the content and appearance of the text that is displayed when a login attempt fails.
  • CreateUserUrl: used to create links to registration page to create user
  • PasswordRecoveryUrl: used to create links to password recovery page
  • VisibleWhenLoggedIn: This property enables you to automatically hide the Login control when the user is already authenticated
  • DestinationPageUrl: This property sets the name of the page that the user will be redirected to after logging in. If you do not specify a value for the DestinationPageUrl property, the user will be redirected to the originally requested URL after being authenticated.
CreateUserWizard Control:
The CreateUserWizard control enables you to create a standard user registration page. You can use the CreateUserWizard control to allow users to create a new user entry in the membership system. The exact appearance of the interface generated by the CreateUserWizard depends on the settings of your application's Membership Provider. For example, the text boxes for a password question and answer appear only when the default Membership Provider's requiresQuestionAndAnswer attribute has the value true.


CreateUserWizard Output listing

  1. Create or edit an ASP.NET Web page.
  2. Place a CreateUserWizard control on the page using the following syntax:
<asp:CreateUserWizard ID="CreateUserWizard1" Runat="server"> </asp:CreateUserWizard>
  1. Set the ContinueDestinationPageUrl to the URL of the page that users will visit after completing registration, such as your home page
                                                       One of the interesting things that you can do with the CreateUserWizard control is to automatically send a registration e-mail message after the user has completed all of the registration steps.

ChangePassword Control:

The ChangePassword control enables users to change their passwords. The control displays text boxes for entering the original password and entering a new password 


ChangePassword control Output listing
Like the CreateUserWizard and PasswordRecovery controls, the ChangePassword control includes a MailDefinition property. When values are assigned to the MailDefinition property, the ChangePassword control automatically sends an e-mail message to the user when a password is successfully changed.
LoginName and LoginStatus Controls:
The LoginName and LoginStatus controls enable you to display information about the current authentication status of a user. After a user has logged onto your application, the LoginName control displays the user's registered username. If a user has not been authenticated with Forms Authentication, the LoginName control displays absolutely nothing.
<asp:LoginName ID="LoginName1" Runat="server" />

The LoginStatus, on the other hand, enables a user to log in or log off your Web application. The control displays one of two links. If the user is not authenticated, a link to the Login.aspx page is displayed. If the user has already been authenticated, a link that enables the user to log off is displayed. Here's how you declare the LoginStatus control.
<asp:LoginStatus ID="LoginStatus1" Runat="server" />

LoginView Control:

The LoginView control enables you to display different content depending on the role of the current user. For example, many Web sites display different information on their home page, depending on whether the user is a new user or a registered user. New users might get an overview of the purpose of the Web site, while registered users can view information that is customized for them.

                                      The ASP.NET 3.5 framework includes significant new security features which make the life of developer a lot easier. The new Web Site Administration Tool enables you to create and manage users entirely through a Web form interface. The new Login controls enable you to build standard Web site security pages without writing a single line of code. Finally, the Membership API provides you with a powerful set of methods for manipulating membership information through code.