Tuesday, February 5, 2013

IIS7 - Troubleshooting Failed Requests Using Tracing i


Introduction

Request-based tracing provides a way to determine what exactly is happening with your requests and why, provided that you can reproduce the problem that you are experiencing. Problems like poor performance on some requests, or authentication-related failures on other requests, or the server 500 error from ASP or ASP.NET can often be difficult to troubleshoot--unless you have captured the trace of the problem when it occurs.
Failed-request tracing is designed to buffer the trace events for a request and only flush them to disk if the request "fails," where you provide the definition of "failure". If you want to know why you're getting 404.2 error messages or request start hanging, use failed-request tracing.
The tasks that are illustrated in this article include:
  • Enabling the failed-request tracing module
  • Configuring failed-request tracing log-file semantics
  • Defining the URL for which to keep failed request traces, including failure definitions and areas to trace
  • Generating the failure condition and viewing the resulting trace

Prerequisites

INSTALL IIS

You must install IIS 7 or above before you can perform the tasks in this article. Browse to http://localhost/ to see if IIS is installed. If IIS is not installed, see Installing IIS on Windows Server 2008 for installation instructions. When installing IIS, make sure that you also install the following:
  • ASP.NET (under World Wide Web Services - Application Development Features - ASP.NET)
  • Tracing (under World Wide Web Services - Health and Diagnostics - Tracing)

LOG IN AS ADMINISTRATOR

Ensure that the account that you use to log in is the administrator account or is in the Administrators group.
Note: Being in the Administrators group does not grant you complete administrator user rights by default. You must run applications as Administrator, which you can do by right-clicking on the application icon and selecting Run as administrator.

MAKE A BACKUP

You must make a backup of the configuration before doing the following tasks.
To make a backup of the configuration:
  1. Click Start -> All Programs -> Accessories.
  2. Right-click Command Prompt, and then click Run as administrator.
3. In a command prompt, run the following command:


%windir%\system32\inetsrv\appcmd add backup cleanInstall

CREATE SAMPLE CONTENT

  1. Delete everything in the %systemdrive%\inetpub\wwwroot folder.
  2. In the command prompt, navigate to the test.asp file in inetpub\wwwroot.
  3. In the test.asp file, enter the following code:
<h2>Failed Request Tracing Lab</h2><br>
<br>Today's date is <% response.write(Date()) %>

DISABLE ASP

ASP must be disabled for this task. ASP is disabled only as an example and for the purposes of the tasks in this article.
To disable ASP:
  1. Open IIS Manager.
  2. Double-click ISAPI and CGI Restrictions.
3. Select Active Server Pages. In the Actions pane, click Deny to disable ASP.

Enable Failed-Request Tracing

After you enable failed-request tracing, you need to configure where the log files will reside. In this task, you will enable failed-request tracing for the Default Web Site and specify where to put the log files. You will then configure the failure for which to generate failure logs.

STEP 1 : ENABLE FAILED-REQUEST TRACING FOR THE SITE AND CONFIGURE THE LOG FILE DIRECTORY

  1. Open a command prompt with administrator user rights.
  2. Launch inetmgr.
  3. In the Connections pane, expand the machine name, expand Sites, and then click Default Web Site.
  4. In the Actions pane, under Configure, click Failed Request Tracing….
5. In the Edit Web Site Failed Request Tracing Settings dialog box, configure the following:
  • Select the Enable check box.
  • Keep the defaults for the other settings.
6. Click OK.
Failed-request tracing logging is now enabled for the Default Web Site. Check the %windir%\system32\inetsrv\config\applicationHost.config file to confirm that the configuration looks as follows:
<system.applicationHost>
<sites>
<!-- site & app defaults -->
<site name="Default Web Site" id="1">
<!-- other site configuration -->
<traceFailedRequestsLogging enabled="true" />
</site>
</sites>
</system.applicationHost>

STEP 2 : CONFIGURE YOUR FAILURE DEFINITIONS

In this step, you will configure the failure definitions for your URL, including what areas to trace. You will troubleshoot a 404.2 that is returned by IIS for any requests to extensions that have not yet been enabled. This will help you determine which particular extensions you will need to enable.
  1. Open a command prompt with administrator user rights.
  2. Launch inetmgr.
  3. In the Connections pane, expand the machine name, expand Sites, and then click Default Web Site.
  4. Double-click Failed Request Tracing Rules.
5. Click Finish.
6. In the Actions pane, click Add....
7. In the Add Failed Request Tracing Rule wizard, on the Specify Content to Trace page, select All content (*). ClickNext.
8. On the Define Trace Conditions page, select the Status code(s) check box and enter 404.2 as the status code to trace.
9. Click Next.
10. On the Select Trace Providers page, under Providers, select the WWW Server check box. Under Areas, select theSecurity check box and clear all other check boxes. The problem that you are generating causes a security error trace event to be thrown. In general, authentication and authorization (including ISAPI restriction list issues) problems can be diagnosed by using the WWW Server – Security area configuration for tracing. However, because the FREB.xsl style sheet helps highlight errors and warnings, you can still use the default configuration to log all events in all areas and providers.
Under Verbosity, select Verbose.
11. Click Finish. You should see the following definition for the Default Web Site:
IIS Manager writes the configuration to the %windir%\system32\inetsrv\config\applicationHost.config file by using a <location> tag. The configuration should look as follows:
<location path="Default Web Site">
<system.webServer>
<tracing>
<traceFailedRequests>
<add path="*">
<traceAreas>
<add provider="WWW Server" areas="Security" verbosity="Verbose" />
</traceAreas>
<failureDefinitions statusCodes="404.2" />
</add>
</traceFailedRequests>
</tracing>
</system.webServer>
</location>

Test and View the Failure Request Log File

In this task, you will generate a failed request and view the resulting trace log. You already configured IIS to capture trace logs for http://localhost/*.asp requests that fail with an HTTP response code of 404.2. Now verify that it works.

STEP 1 : GENERATE AN ERROR AND THE FAILURE REQUEST LOG FILE

  1. Open a new Internet Explorer window.
  2. Type in the following address: http://localhost/test.asp.
  3. You should see the following:

STEP 2 : VIEW THE FAILURE REQUEST LOG FILE

  1. Now that you have generated a failed request, open a command prompt with administrator user rights and navigate to %systemdrive%\inetpub\logs\FailedReqLogFiles\W3SVC1.
  2. Run start to start an Internet Explorer window from the directory.
3. Notice a few things here: When IIS writes the failed request log file, it writes one file per failed request. A freb.xsl style sheet is also written, one per directory. This helps when you view the resulting failure request log files (such as fr000001.xml above).
4. Right-click the log file for the 404.2 error, and click Open With -> Internet Explorer. If this is the first time that you are opening a Failed Request Tracing file, you must add about:internet to the list of trusted sites, since Internet Explorer's Enhanced Security Configuration is enabled by default. If this is the case, you will see the following:
5. In the Internet Explorer dialog box, click Add… to add about:internet to the list of trusted sites. This allows the XSL to work. You will see the following after adding about:internet to the list of trusted sites:
A summary of the failed request is logged at the top, with the Errors & Warnings table identifying any events that are WARNING, ERROR, or CRITICAL ERROR in severity. In this example, the WARNING severity level is due to ISAPI RESTRICTION. The image that you tried to load was %windir%\system32\inetsrv\asp.dll.
6. Open the raw XML file directly by using a text editor, and look at the contents of each event.

Summary

You have completed two tasks: configured failed request tracing to capture traces for * if IIS returns it with a 404.2 status code; and verified that IIS captured the trace for your request. You also verified that the freb*.xml log file did not contain any other requests for the requests that you made because the requests did not have a 404.2 return code. When you consult the failure log file, you determined that the cause of the failure was that the extension was disabled for that request. You can try other non-HTML pages (like gifs or jpgs) and note that the log file does NOT add these traces. You can also easily change this to be 404, or capture the failure if the request takes longer than 30 seconds by setting the timeTaken field in your failureDefinitions.

Monday, January 28, 2013

VS - VS 2010 Database Project: An Introduction


Visual Studio 2010 has a new Database Project. The scripts in this new Database project define your database just like the files in your code projects define your application.
The prior Database project (the one under the "Other Projects" node in VS 2003/2005/2008 as detailed in this prior post), was simply a storage container for your database scripts.
The new Database project is alive. Like the old Database project, it retains your database scripts, but it also has Intellisense, build-time validation, and automatic deployment features. It allows you to keep the definition of the database in your scripts and ensure that the scripts are deployed to your development database.
This is the first in a series of posts on using the new Database project. This post provides the steps for adding a Database Project to any solution in either VB or C#.
1. Right-click on your solution and select Add | New Project. Or select File | New Project from the main menu.
The Add New Project dialog is then displayed.
image
2. Open the Database node in the Installed Templates panel on the left and select SQL Server.
3. Select SQL Server 2008 Database Project from the middle panel, enter a name for the project, and click OK.
NOTE: If you have SQL Server 2005, you can select the SQL Server 2005 Database Project instead.
Visual Studio then creates the new project and adds it to your Solution Explorer:
image
4. Use the Database project to write the scripts for a new database or manage the scripts for an existing database.
For example, use the Tables node to manage your table scripts and the Programmability | Stored Procedures node to manage your stored procedure scripts:
image

Wednesday, January 23, 2013

SQL - Last Access date of Databases

To know the last accessed date of Database run the following query



SELECT DatabaseName, MAX(LastAccessDate) LastAccessDate
FROM
    (SELECT
        DB_NAME(database_id) DatabaseName
        , last_user_seek
        , last_user_scan
        , last_user_lookup
        , last_user_update
    FROM sys.dm_db_index_usage_stats) AS PivotTable
UNPIVOT 
    (LastAccessDate FOR last_user_access IN
        (last_user_seek
        , last_user_scan
        , last_user_lookup
        , last_user_update)
    ) AS UnpivotTable
GROUP BY DatabaseName
HAVING DatabaseName NOT IN ('master', 'tempdb', 'model', 'msdb')
ORDER BY 2

Wednesday, January 16, 2013

OOPS - SOLID Principles of OOD

Dependency Management is an issue that most of us have faced. Whenever we bring up on our screens a nasty batch of tangled legacy code, we are experiencing the results of poor dependency management. Poor dependency managment leads to code that is hard to change, fragile, and non-reusable. Indeed, I talk about several different design smells in the PPP book, all relating to dependency management. On the other hand, when dependencies are well managed, the code remains flexible, robust, and reusable. So dependency management, and therefore these principles, are at the foudation of the -ilities that software developers desire.

The first five principles are principles of class design. They are:
SRPThe Single Responsibility PrincipleA class should have one, and only one, reason to change.
OCPThe Open Closed PrincipleYou should be able to extend a classes behavior, without modifying it.
LSPThe Liskov Substitution PrincipleDerived classes must be substitutable for their base classes.
ISPThe Interface Segregation PrincipleMake fine grained interfaces that are client specific.
DIPThe Dependency Inversion PrincipleDepend on abstractions, not on concretions.

The next six principles are about packages. In this context a package is a binary deliverable like a .jar file, or a dll as opposed to a namespace like a java package or a C++ namespace.

The first three package principles are about package cohesion, they tell us what to put inside packages:

REPThe Release Reuse Equivalency PrincipleThe granule of reuse is the granule of release.
CCPThe Common Closure PrincipleClasses that change together are packaged together.
CRPThe Common Reuse PrincipleClasses that are used together are packaged together.

The last three principles are about the couplings between packages, and talk about metrics that evaluate the package structure of a system.

ADPThe Acyclic Dependencies PrincipleThe dependency graph of packages must have no cycles.
SDPThe Stable Dependencies PrincipleDepend in the direction of stability.
SAPThe Stable Abstractions PrincipleAbstractness increases with stability.

Friday, January 4, 2013

C# - Composition over Inheritance



We had often heard that composition is better than inheritance. Why is it so? First of all how is one different from the other and what are the similarities in them?

Lets say we are writing simulation software for Rocket Launching systems which are to be supplied to different countries. Now these different countries can use them as they want it.
The code for our launching system is below:

public class Launcher{
    
public bool LaunchMissile()
    {
        
Console.WriteLine("Missile launched");
        
return true;
    }
}


public class SufraceToAirMissileLauncher:Launcher{
 }


Now, country A uses this code to launch missile as follows:


static void Main(string[] args)
    {
        
SufraceToAirMissileLauncher staLauncher = new SufraceToAirMissileLauncher();
        
bool isLaunched =   staLauncher.LaunchMissile();    
}


This is how Inheritance is used. The various launchers can reuse the base Launcher class code to launch missile.

The same thing can be achieved by using Composition where base class functionality is encapsulated inside the main concrete class. The code for that is below:


public class SufraceToAirMissileLauncher{
    
private Launcher launcher = new Launcher();
    
public bool LaunchMissile()
    {
        
return launcher.LaunchMissile();
    }
}


The client UI code remains the same.

Now due to our superb code, our patented launching software had become famous and another country B wants to use it. But they had a condition that instead of launching the missile through base class they would want to get an instance of a missile. Now it's up to them what they want to do with it. They might add some nuclear material on it or modify it to increase its range or do whatever they might like. So another Missile object comes into the picture.

public class Missile{
    
private bool isLaunched;
    
public bool IsLaunched
    {
        
get { return isLaunched; }
        
set { isLaunched = value; }
    }
    
public Missile(bool isLaunched)
    {
        IsLaunched = IsLaunched;
    }
}

And the base class function has changed to:


public class Launcher{
    
public Missile LaunchMissile()
    {
        
Console.WriteLine("Missile returned");
        
return new Missile(true);
    }
}

Now it returns a missile instead of launching it. So now if we rely on inheritance, the client code of country A would break since the method signature has changed from what is being used in its UI.

However, if the country A had used composition instead, the code will not break. Only the derived class function would need to accommodate the new changed behavior of the base class. To accommodate this, we need to change our derived class code function "LaunchMissile" as:

public class SufraceToAirMissileLauncher{
    
private Launcher launcher = new Launcher();
    
public bool LaunchMissile()
    {
        
Missile missile = launcher.LaunchMissile();
        
return missile.IsLaunched;
    }
}


Hence, the client code of country A would still work:

static void Main(string[] args)
    {
        
SufraceToAirMissileLauncher staLauncher = new SufraceToAirMissileLauncher();
        
bool isLaunched =   staLauncher.LaunchMissile();   
 }

On the other hand country B which was insisting on getting a missile would still get missile from the base class.

So through this simple example we see how the composition is favored over inheritance to maintain compatibility and where there is a possibility that the functionality might change in future.