Sort Collection

I had a need to be able to sort a collection by two different properties within the class. Basically having the collection sorted by one property and then by the 2nd property. I never ended up implementing this in a production application but in all of my testing it did work. You download the code SortCollection.txt (4 KB)

To use it, you add a SortClass to the Comparer. You can add as many as you want. A SortClass is made up of the property name and a direction. So, for example:

public MyCollectionClass SortMyClass(MyCollectionClass myClass)
{
Comparer comparer = new Comparer();
comparer.SortClasses.Add(new SortClass("MyProperty1", SortDirection.Ascending); 
comparer.SortClasses.Add(new SortClass("MyProperty2", SortDirection.Descending); 
myClass.Sort(comparer);      
return myClass;     
}
So after the sort, myClass would be sorted by MyProperty1 (ascending), then by MyProperty2 (descending)

.NET Difference between throw and throw ex

Interesting article on the differences between throw and throw ex.  http://mattgollob.blogspot.com/

The difference is that throw; preserves the original stack trace and throw ex; truncates the stack trace below the method in which the throw ex; call is located. For example, here's some driver code and the generated output:

    1 class Program

    2 {

    3     static void Main(string[] args)

    4     {

    5         ThrowSample ts = new ThrowSample();

    6 

    7         try { ts.ThrowMethod(); }

    8         catch(Exception ex)

    9         {

   10             Trace.WriteLine(

   11                 "Exception caught from ThrowMethod:");

   12             Trace.WriteLine(ex.ToString());

   13         }

   14 

   15         try { ts.ThrowExMethod2(); }

   16         catch (Exception ex)

   17         {

   18             Trace.WriteLine(

   19                 "Exception caught from ThrowExMethod:");

   20             Trace.WriteLine(ex.ToString());

   21         }

   22     }

Output:

Exception caught from ThrowMethod:
System.Exception: DOH!
   at ThrowSample.ThrowSample.ExceptionMethod() in
      C:\ThrowSample\Program.cs:line 55
   at ThrowSample.ThrowSample.ThrowMethod() in
      C:\ThrowSample\Program.cs:line 38
   at ThrowSample.Program.Main(String[] args) in
      C:\ThrowSample\Program.cs:line 14

Exception caught from ThrowExMethod:
System.Exception: DOH!
   at ThrowSample.ThrowSample.ThrowExMethod() in
      C:\ThrowSample\Program.cs:line 48
   at ThrowSample.Program.Main(String[] args) in
      C:\ThrowSample\Program.cs:line 21

Notice how the stack trace from the ThrowMethod() call includes ThrowSample.ThrowSample.ExceptionMethod()? This portion of the stack is conspicuously absent from the ThrowExMethod() stack trace.

Now, we're lucky we've got the PDBs handy so we get line numbers in the exception message. What if we didn't? It certainly would be harder to find the true source of the exception using the stack trace from throw ex;, especially if the ThrowExMethod method was more complicated than it is.

Let's take this one step further, and assume there are several method calls between ThrowExMethod and ExceptionMethod, any or all of which could be throwing their own exceptions. Using the stack trace from throw ex; there'd be no wayy to know where the exception actually came from. See why it's important to understand the difference?

All that being said, using throw ex; isn't always bad. But you should only be using it when you have something to add to the exception that was caught. In which case, you should be throwing a new exception instance, initialized with the caught exception as the inner exception. For example:

    1 public void ThrowExMethod2()

    2 {

    3     try { this.ExceptionMethod(); }

    4     catch (Exception ex)

    5     {

    6         // Log the exception

    7         throw new ApplicationException(

    8             "Uh-oh!", ex);

    9     }

   10 }


Now the stack trace is nicely preserved:


Exception caught from ThrowExMethod:
System.ApplicationException: Uh-oh! ---> System.Exception: DOH!
   at ThrowSample.ThrowSample.ExceptionMethod() in
      C:\ThrowSample\Program.cs:line 65
   at ThrowSample.ThrowSample.ThrowExMethod2() in
      C:\ThrowSample\Program.cs:line 54
--- End of inner exception stack trace ---
   at ThrowSample.ThrowSample.ThrowExMethod2() in
      C:\ThrowSample\Program.cs:line 58
   at ThrowSample.Program.Main(String[] args) in
      C:\ThrowSample\Program.cs:line 21

Visual Studio And Regions

I like to group methods together by scope, meaning that all private methods are group together, and so on. The best way I found to handle this is to define regions for each scope level.

However, I personally, like to see the whole file when I open it. However, C# defaults to collapsing the regions. To change this Open Tools | Options from Visual Studio and select C# under the Text Editor option. Click the Advanced option and uncheck ‘Enter outlining mode when files open’.  You can also do this for vb.net using the vb selection under the Text Editor Properties.


HTTP compression in ASP.NET 2.0

HTTP compression in ASP.NET 2.0 (Original Post: http://www.madskristensen.dk/blog/HTTP+Compression+In+ASPNET+20.aspx)

The new System.IO.Compression namespace in .NET 2.0 makes it easy to implement HTTP compression without having to touch IIS. The best thing about it is that you no longer need any third party compression components, it’s all build directly into .NET Framework.

There are different ways to implement the compression but I think an HttpModule is the right choice for this feature. Let's create one and call it CompressionModule.

The CompressionModule must adhere to the following rules:

  • Support both GZip and Deflate compression
  • Only compress if the browser supports it
  • Simplest possible implementation

These rules are important to make sure that the compression will run smoothly in every situation.

The code

An HttpModule is a class that implements the IHttpModule interface and gives it direct access to the underlying HttpApplication. We have to implement the Init method and attach the Application.BeginRequest event and the event handler that will do the compression.

#region Using

 

using System;

using System.Web;

using System.IO.Compression;

 

#endregion

 

/// <summary>

/// Compresses the output using standard gzip/deflate.

/// </summary>

public class CompressionModule : IHttpModule

{

 

  #region IHttpModule Members

 

  void IHttpModule.Dispose()

  {

    // Nothing to dispose;

  }

 

  void IHttpModule.Init(HttpApplication context)

  {

    context.BeginRequest += new EventHandler(context_BeginRequest);

  }

 

  #endregion

 

  #region Compression

 

  private const string GZIP = "gzip";

  private const string DEFLATE = "deflate";

 

  void context_BeginRequest(object sender, EventArgs e)

  {

    HttpApplication app = sender as HttpApplication;

 

    if (IsEncodingAccepted(GZIP))

    {

      app.Response.Filter = new GZipStream(app.Response.Filter, CompressionMode.Compress);

      SetEncoding(GZIP);

    }

    else if (IsEncodingAccepted(DEFLATE))

    {

      app.Response.Filter = new DeflateStream(app.Response.Filter, CompressionMode.Compress);

      SetEncoding(DEFLATE);

    }

  }

 

  /// <summary>

  /// Checks the request headers to see if the specified

  /// encoding is accepted by the client.

  /// </summary>

  private bool IsEncodingAccepted(string encoding)

  {

    return HttpContext.Current.Request.Headers["Accept-encoding"] != null && HttpContext.Current.Request.Headers["Accept-encoding"].Contains(encoding);

  }

 

  /// <summary>

  /// Adds the specified encoding to the response headers.

  /// </summary>

  /// <param name="encoding"></param>

  private void SetEncoding(string encoding)

  {

    HttpContext.Current.Response.AppendHeader("Content-encoding", encoding);

  }

 

  #endregion

 

}

Implementation

Download the CompressionModule.cs file below and add it to the App_Code folder in the root of your website. Then add these lines to the web.config’s <system.web> section.

 <httpModules>

   <add type="CompressionModule" name="CompressionModule" />

 </httpModules>

 

Download

CompressionModule.zip (0,75 KB)


Some people have too much time on their hands

I ran across this blog post a couple of weeks ago and thought it was quite funny  that someone actually took the time to figure out how to open a beer bottle with a piece of paper. http://www.lockergnome.com/diy/how-to-open-a-beer-bottle-with-a-piece-of-paper/ (external).


Great ASP.NET 2.0 Articles

As I have been migrating to ASP.NET 2.0, I have run across a few really good and helpful articles. Note: All of the links are to external sites.

Scott Gunthrie’s Tips and Tricks Series: http://weblogs.asp.net/scottgu/pages/ASP.NET-2.0-Tips_2C00_-Tricks_2C00_-Recipes-and-Gotchas.aspx\

Great Advanced Master Pages Article that covered a lot of stuff that I had not seen elsewhere: http://odetocode.com/Articles/450.aspx 

Common Gotcha: Slow VS 2005 Web Site Build Performance Because of “Dueling Assembly References:  http://weblogs.asp.net/scottgu/archive/2006/07/30/Common-Gotcha_3A00_-Slow-VS-2005-Web-Site-Build-Performance-Because-of-_1C20_Dueling-Assembly-References_1D20_.aspx

App_Offline.htm and working around the "IE Friendly Errors" feature: http://weblogs.asp.net/scottgu/archive/2006/04/09/App_5F00_Offline.htm-and-working-around-the-_2200_IE-Friendly-Errors_2200_-feature.aspx