Wednesday, 17 June 2009

A Catch-All C# Logger

Create a Logs folder in the root of your website add this little snippy snappy snoo to your Global.asax file. This will catch all exceptions in your Asp.Net site and create a log file for you.

    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs

        Exception ex = Server.GetLastError( ).GetBaseException( );

        string logFormat = DateTime.Now.ToShortDateString( ).ToString( )
            + " " + DateTime.Now.ToLongTimeString( ).ToString( );

        StringBuilder sb = new StringBuilder( );
        sb.Append( DateTime.Now.Year.ToString( ) );
        sb.Append( DateTime.Now.Month.ToString( ) );
        sb.Append( DateTime.Now.Day.ToString( ) );
        sb.Append( "_" );
        sb.Append( DateTime.Now.Hour.ToString( ) );
        sb.Append( DateTime.Now.Minute.ToString( ) );
        sb.Append( DateTime.Now.Second.ToString( ) );
        sb.Append( DateTime.Now.Millisecond.ToString( ) );
        
        string fullPath = Server.MapPath(
            VirtualPathUtility.ToAbsolute("~/Logs/") ) + sb.ToString( );

        System.IO.StreamWriter sw = new System.IO.StreamWriter( fullPath, true );
        sw.WriteLine( "Logged: " + logFormat );
        sw.WriteLine( "Request: " + Request.Url.OriginalString );
        sw.WriteLine( "Form: " + Request.Form.ToString( ) );
        sw.WriteLine( "Exception Message: " + ex.Message );
        sw.WriteLine( "Target Site: " + ex.TargetSite );
        sw.Write( "Stack Trace: " + ex.StackTrace.Trim( ) );
        sw.Flush( );
        sw.Close( );        
    }

I'm not claiming credit for this code snippet, so if your reading this and discover I've copied some code from your blog, then you're probably right. The problem is I'm trying to keep little code snippets safe so I can refer back to them (hence, me adding this to my blog notepad) but I can't find the original source. If you are the source of this C# code then send me your link to original post and I'll credit you.

Friday, 29 May 2009

Transact Sql String Manipulation...Extract a section of a delimited string

I've been doing some reading on Microsoft forums and I came across quite a lot of posts with questions about string manipulation using various Transact-Sql string manip. functions. It prompted me to start a post...

One of the questions was about extracting a portion of a string. Here's an example of how to extract a sub string from a string that has consistent seperation of parts. The following Sql will extract and print the third part (number 6717) from the string assigned to the @data variable.

declare @data varchar(100); set @data = 'Asl/UKE/6717/08'; declare @firstpass varchar(100); set @firstpass = left(@data, len(@data) - charindex('/', reverse(@data))); print right( @firstpass, charindex('/', reverse(@firstpass))-1);

The above was tested on Sql Server 2005

Thursday, 28 May 2009

Second param of SUBSTRING( ) is not a zero-based index value...

I came across a problem the other day.....A developer had produced some sql for me that used the SUBSTRING function. I needed everything before a full stop (period):

e.g. I needed 1234 from 1234.efgdhyt

He programmed the method like this:

SUBSTRING( value, 0, CHARINDEX(’.', value ) – 1)

which gave me 123

Note: Using SUBSTRING you must access the first character index using 1 not 0(zero), so the correct statement would be:

SUBSTRING( value, 1, CHARINDEX(’.', value ) – 1)

Monday, 23 February 2009

Implementing the State Design Pattern in C#

How to program state values in your C# code.

This article has moved....

Implement The State Design Pattern in C# and other cool articles can be found at cscoffee.blogspot.com

Asp.Net Data Caching - Clone Objects for Asp.Net Cache

The importance of object cloning to protect data in the Asp.Net cache.

This article has moved....

Cloning Objects for the Asp.Net Cache and other cool articles can be found at cscoffee.blogspot.com

The State Design Pattern in C#

A page of useful resources for The State Software Design Pattern

About The State Design Pattern

The motivation for the State Design Pattern is to reduce code complexity by eliminating the need for complex conditional statements....

    if ( _state is this ) then
      // do something
    else
    if ( _state is this or _state is that ) then
      // do this other thing
    else
    if ( _state is this and _state is that ) then
      // do something else
    .
    ....etc.

Don't pass the Context to the State

In Design Pattern, Elements of Reusable Object-Oriented Software (Gamma, Helm, Johnson, Vlissides) they write that the context obj. defines the interface of interest to the client. They also write that the context object can be passed through to the current state obj. so the state can access the context if necessary. This could be ok, but, you may want to seperate out concerns here. The context interface is defined for a client (presumably some presentation object) so we might not want the state to have access to the same interface, and at the same time, we may wish to expose other details to the state, details we don't want provide the client with. I written an article about this pattern and provided a good practical example. Take a look at Implementing The State Design Pattern in C#

Articles about The State Design Pattern

Books

  • Design Patterns: Elements of Reusable Object-Oriented Software, by Erich Gamma, Richard Helm, Ralph Johnson, John Vissides
  • Refactoring To Patterns, by Joshua Kerievsky