Monday, November 01, 2004

If you're like me in your GDI+ adventures you've run across the Image.GetThumbnailImage(...) method and been disappointed with its results.  This method opts for performance over quality when rendering your thumbnail image and as a result your thumbnails can look discolored or distorted.  I wanted to have a routine that provided a high performance alternative but would render a better quality image.

The way I implemented this at first was to iterate through the pixels of the source image, performing averages of pixel color over an area of pixels, and writing that resultant pixel to the output (thumbnail) image.  I wrote this a couple of years ago and it did the trick nicely and for a small number of small pictures it was more than adequate; with larger pictures, on the other hand, the performance degradation was noticeable.  I've attached the code for your viewing pleasure:

public static Bitmap CreateThumbnail(Bitmap source, int thumbWi, int thumbHi, IProgress progressCallback) {
   if ( thumbWi > source.Width || thumbHi > source.Height ) return null;

   Bitmap ret = new Bitmap(thumbWi, thumbHi);
  
   float xScale = (float)thumbWi / ((float)source.Width - 1);
   float yScale = (float)thumbHi / ((float)source.Height - 1);

   for ( int i = 0; i < thumbHi; i++ ) {
      for ( int j = 0; j < thumbWi; j++ ) {
         int x1 = (int)( j / xScale );
         int x2 = (int)( ( ( j + 1 ) / xScale ) - 1 );
         int y1 = (int)( i / yScale );
         int y2 = (int)( ( ( i + 1 ) / yScale ) - 1 );
         float r = 0, g = 0, b = 0;
         for ( int x = x1; x <= x2; x++ )
            for ( int y = y1; y <= y2; y++ ) {
               int c = source.GetPixel(x, y).ToArgb();
               r += ( c & 0xff0000 ) / 0xff01;
               g += ( c & 0xff00 ) / 256;
               b += ( c & 0xff );
            }

         int numPixels = ( x2 - x1 + 1 ) * ( y2 - y1 + 1 );
         ret.SetPixel(j, i, Color.FromArgb((int)( r/numPixels ), (int)( g/numPixels ), (int)( b/numPixels )));
      }

      if ( null != progressCallback ) progressCallback.Report(i / thumbHi * 100);
   }

   return ret;
}


Recently, however, it became important to have a faster algorithm to generate image thumbnails.  To meet these new demands, I produced the following code which results in as good a thumbnail as my previous code but MUCH faster - though not quite as fast as the GetThumbnailImage(...) method.  Here is its code:

public static Bitmap CreateThumbnail(Bitmap source, int thumbWi, int thumbHi) {
   // return the source image if it's smaller than the designated thumbnail
   if ( source.Width < thumbWi && source.Height < thumbHi ) return source;

   System.Drawing.Bitmap ret = null;
   try {
      int wi, hi;

      // maintain the aspect ratio despite the thumbnail size parameters
      if ( source.Width > source.Height ) {
         wi = thumbWi;
         hi = (int)(source.Height * ((decimal)thumbWi / source.Width));
      }
      else {
         hi = thumbHi;
         wi = (int)(source.Width * ((decimal)thumbHi / source.Height));
      }

      // original code that creates lousy thumbnails
      // System.Drawing.Image ret = source.GetThumbnailImage(wi,hi,null,IntPtr.Zero);
      ret = new Bitmap(wi, hi);
      using ( Graphics g = Graphics.FromImage(ret) ) {
         g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
         g.FillRectangle(Brushes.White, 0, 0, wi, hi);
         g.DrawImage(source, 0, 0, wi, hi);
      }
   }
   catch {
      ret = null;
   }

   return ret;
}


Enjoy!...and happy thumbnailing!

Monday, November 01, 2004 9:05:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [7]  |  Trackback

In developing pages and controls in ASP.NET I've come across situations in which I need to bind against properties that are not implemented on the default interface of the object in question.  For the most part, this is really never an issue.  Typically you have an object (be it a user-defined class instance, or something more data-centric such as a DataSet or a DataReader) and you want to bind against it.  Your syntax might frequently resemble the following:

<%# DataBinder.Eval(Container.DataItem, "UserName") %>


where this code will evaluate (via Reflection) the item being bound (identified by Container.DataItem) and extract the value contained within the UserName property/column/etc.  This is all well and good and usually all that you need.  However, only properties (and methods) on the default interface are sought.  That is, if your object (Container.DataItem) implements and interface and maps to the interface methods directly rather than implementing them generically by name, the runtime will not be able to resolve to them.

For example, suppose you have an IUser interface defined and implemented within a User class:

public interface IUser {
   string UserName { get; set; }
}

public sealed class User : IUser {
   private string _userName;

   public string UserName {
      get { return _userName; }
      set { _userName = value; }
   }
}


In this scenario, your databinding would work perfectly.  Yes, UserName maps to the IUser.UserName property implicitly, but is also defined on the default interface for User.  Suppose, however, that the implementation were explicit:

public sealed class User : IUser {
   private string _userName;

   string IUser.UserName {
      get { return _userName; }
      set { _userName = value; }
   }
}


Now, the databinding would fail because there is no property called UserName on the default interface of the User class.  In this circumstance, it is important to take matters into our own hands and perform the casting on the ASP.NET page/control ourselves.  This may also require that we fully qualify the interface name (using the proper namespace) or use an <%@ Import namespace="..." %>directive.

<%@ Import namespace="..." %>

<%# ((IUser)Container.DataItem).UserName %>


There, works like a charm.  Note, that depending on the content of the property, you might be best served by enclosing the operation in a Server.HtmlEncode() function call to prevent any misuse, XSS (Cross Site Scripting), or HTML/Script injection.

Monday, November 01, 2004 3:25:00 AM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Thursday, October 28, 2004

I'm liking this.  I found a new tool called PostXING, by Christopher Frazier while reading through a blog post by Darren Neimke.  It's pretty slick.  I especially like the fact that there is a Design View, HTML view, and a Preview option.  It's been a pain to perform syntax hilighting in the past - I've resorted to manual highlighting as well as some other strategies.

This product is very nice.  Its ability to post pictures is very handy as well as there is no such support natively in .Text.  While I have no immediate need for the cross site posting, I can see that to be a very handy feature and may end up using it in the not-so-distant future.

There are a couple of loose ends:

  • Font sizes on the FTP settings tab are a bit too large that they wrap
  • The auto-resizing of the controls on the Syntax Highlighting form needs addressing
  • I'm unclear on the Url textbox and what it's purpose is
  • Post vs. Post & Publish?

Aside from these minor issues, I really enjoy it.  Thanks Christopher for a job well done!

BTW: This post was made courtesy of the PostXING product :-)

Thursday, October 28, 2004 4:19:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Tuesday, October 26, 2004

[Updated 10/29/2004 with item #6]

I figured that for my 100th post I'd put something out there that I hope to get lots of feedback on.

Each day as I'm coding I invariably stumble across a language feature that just doesn't sit right with me.  That, or I get to thinking, I wish the BCL's supported X function or Y capability.  While I'm not coding, however, I tend to forget these items until I once again go crashing headfirst up against it.

I've given this some thought, but will probably be amending it a bit here in the next few days as I expect I'll encounter a few more.  So, without further ado, here's my .NET wish list (NOTE: I'm not addressing several issues that I know will be fixed within Whidbey such as scoped accessors on properties, etc):

1. CONSTANTS

I really wish I could declare globals (public constants) at the namespace level without having to resort to an enumeration or a class when the values aren't conceptually enumerated or non-integers.  I'd love the ability to create public and/or internal constants like this:

namespace SomeNamespace {
   internal const int MaxIdLength = 15;
  
   public class Employee {
      public const int MaxNameLength = MaxIdLength;
      // ... class code here ...
   }
}


1a. DEFINES

Along the same lines as constants, having the ability to perform a #define would be very powerful.  Where a constant can potentially be exposed outside the library as a value, a #define only has applicability to the compiler preprocessor.

#define S_RES_APPLICATION_TITLE 10001

namespace SomeNamespace {

   internal sealed class Res {
      internal static string GetString(int id) {
         // return the designated resource value
      }
   }
 
   internal sealed class EntryPoint {
      public static void Main() {
         System.Windows.Forms.MessageBox.Show(Res.GetString(S_RES_APPLICATION_TITLE));
      }
   }
  
}


Now there might be some issues of type safety here that would need to be addressed, but this capability would be extremely enabling and powerful...hearkening to what C++ developers can already do.

2. TRY..CATCH..FINALLY VARIABLES

I am of the firm belief that if a variable is declared within the try block its scope should extend to both the catch and the finally blocks.  As it stands, in order to use a variable in the various blocks you must declare it outside the try..catch..finally.  In other words, if I declare a SqlConnection within a try I can't Dispose() of it in the finally...I must declare it before the try.  This can lead to poor code.  First of all, the object's scope now extends beyond its intended usage, a bad practice as far as I'm concerned.  This would be ideal:

public string GetName(int id) {
   try {
      SqlConnection cn = new SqlConnection("...");
      // get the name and return it
   }
   finally {
      if ( null != cn ) cn.Dispose();
   }
}


There might very well be some technical reasons behind why this is so danged difficult, but I believe it would lead to much clearer code and the developer's intentions would be more easily maintained.

3.  SCOPED INHERITANCE

I get fed up with having to scope my base classes the same as the deriving classes (or vice versa).  Oftentimes, I am wanting to declare a base class to be internal to my assembly, but have a public class that derives from it.  I am using the base class internally for private functionality and object organization, but I don't need it exposed.  Yes, I know I can probably use an internal interface and a private class to accomplish something similar, but that's not what I want to do.

If in fact I do have to expose the base class (which I might be amenable to), I'd at least like to have it internally abstract and publically sealed.

Ideally:

internal abstract Base {
   // ... some methods here ...
}

// here sealed would be implied by virtue of the fact that the
// abstract base class is not publically exposed

public class Derived : Base {
   // ... implementation ...
}


Willing to Accept:

public sealed internal abstract Base {   // or something like that
   // ... some methods here ...
}


Or even:

internal abstract Base {
   // ... some methods here ...
}

public sealed class Derived : internal Base {
   // ... implementation ...
}


4.  STRING.ZERO()

In an effort to provide more out of the box security, I believe the String class should provide a .Zero() method.  This method would be a void method, but when called would zero out/blank out the contents within the string.  I'd imagine that internally it would call SecureZeroMemory().

Yes, we could probably accomplish this using unsafe methods, but that's not a recommended/supported route.  Instead support for this should be built into the framework.

string pwd = txtPassword.Text;
// of course this would have been acquired encrypted and/or securely
// ... use the password variable to login, access a resource, etc
// now that we're done with it, clear it out
pwd.Zero();

This could potentially have further reaching impacts; it could adversely affect parameters, etc, but would provide a nice mechanism to blank out information that you don't want dangling in memory when you're done with it.

5. INDEXERS

It's pretty darned convenient to be able to add an indexer to your class.  It would be very powerful to have this functionality extended to support indexers on properties rather than just on this.  This capability would enable a more flexible and powerful mechanism for indexing into collections internal to your classes without having to write accessors that don't exhibit an indexing mechanism via [].

public sealed class Quote {

   private QuoteLineItem[] _lineItems;
  
   public QuoteLineItem LineItem[int i] {
      get { return _lineItems[i]; }
   }
}


6. NOITEMSTEMPLATE

This is pretty esoteric, but since day 1 that I got into .NET development this one has bugged me and I just remembered it today.  The ASP.NET Data(Grid|List) and Repeater controls have some niceties and are pretty powerful controls.  Each of these controls allows you to define templates for how records are rendered in the browser via the <itemTemplate>.  But what if your controls is being bound to a data source that doesn't have any records?

In this case you have to perform custom server logic and then determine the proper course of action or your content is going to look horrible in the browser.  I think there should be a <noItemsTemplate> that allows you to specify what should render on the browser in the even no items were bound.  This would return control back to the UI designers to lay out the page as they see fit.

<asp:Repeater id=rpt runat=server>
   <noItemsTemplate>
      We're sorry, there are no employees that match your query.
   </noItemsTemplate>
   ...
</asp:Repeater>

Tuesday, October 26, 2004 5:34:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  |  Trackback

Ok, I'm impressed.  I'm a PC guy.  I grew up a PC guy, I'll probably stay one for a long time.  However, I've been thinking about investing in a Mac lately, partly for the experience and partly because there is much to be learned about that whole world.  I don't know if it's mere coincidence or if the stars are just lining up, but I find it really intriguing that I stumbled upon this link while contemplating looking at a new Mac.

I like it - a lot.

Now I just have to consider a few things...mostly $ and would I be willing to purchase the software needed to be effective with it?...gotta think for a bit.

Tuesday, October 26, 2004 3:09:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Monday, October 25, 2004

[Amendments made 10/26 - in blue]

Tonight I got to thinking.  I know, dangerous.

Anyway, my thoughts were revolving around the SqlCommand object and its companion the SqlConnection. These thoughts might also have been directed at their friends - the OleDb, Oracle, and Odbc variations, but I'll focus on the objects I use most.  Many of us developers want to write good, friendly, performant code, right?  Why, then, do so many of us fall back to the simple conveniences?  Take for example the following code:

public string DoSomething() {
   string sql = "SELECT Something FROM SOMEWHERE WHERE Anything = NothingAtAll";
   string cnStr = "Data Source=.;Initial Catalog=DB;Integrated Security=SSPI";
   using ( SqlCommand cm = new SqlCommand(sql, new SqlConnection(cnStr)) ) {
      cm.Connection.Open();
      cm.CommandType = CommandType.Text;
      return (string)cm.ExecuteScalar();
   }
}

What's wrong with the code?  Anything?  Well, for starters it's not friendly code.

I've seen code like this far too often; heck, I've even written something similar on occasion and invariably it comes back to bite me.  So, what's the issue?  Well this code is not friendly because it doesn't play nicely with the connection pool.  The connection that is passed into the SqlCommand's constructor is never closed.  It's hanging around long after the function returns waiting for the garbage collector to come around and clean it up so that the underlying connection can be returned to the pool.  This is definite madness - of all the resources you don't want to tie up any longer than necessary, database connections are some of the biggest.

You can write a real quick test harness to see how the connections are not being returned to the pool.  I've attached a simple one here (if you want the C# source, click here).  To effectively see the example, open your Performance Monitor, add a counter (SQLServer:General Statistics - User Connections).  I like to select the counter and make the line thicker so it stands out more.  Run the example and watch how the connections grows in increments of 15 (a number I arbitrarily chose in the example) for each new connection.  However, when you clean up your connection (that is close/dispose of it) you only gain one connection; it gets reused on each subsequent request indicative of the fact that it's being drawn from the pool.

So, I guess the real question is how do we properly clean up our connection?  We cannot always take the easy road and effectively and reliably insert a cm.Connection.Close() call before the end of our using block because if an exception is thrown preventing the code from reaching that line then we have a dangling connection still.  There are a few ways I can think of doing this, but to me the best most readable and elegant is this (best is a relative term that I may have misused):

public string DoSomething() {
   string sql = "SELECT Something FROM SOMEWHERE WHERE Anything = NothingAtAll";
   string cnStr = "Data Source=.;Initial Catalog=DB;Integrated Security=SSPI";

   using ( SqlConnection cn = new SqlConnection(cnStr) )
   using ( SqlCommand cm = new SqlCommand(sql, cn) ) {
      cn.Open();
      cm.CommandType = CommandType.Text;
      return (string)cm.ExecuteScalar();
   }
}


ASIDE:

One niceties of the C-family of languages is that if you have a block construct (e.g. an if(){...}) you can omit the braces if the block's execution path is a single statement or another block.  Therefore, you can place two, three, n using/fixed/checked/etc blocks in immediate succession and they are semantically nested.  A bonus is the editor will not indent them.  Personally, I don't like the syntactic appearance of

using () {
   using () {
   }
}

especially with all the other braces floating around.  Rather, I prefer the brevity and elegance of

using ()
using () {
}

Ok, enough of a soapbox.


In fact, there are a variety of means to ensure that the connection closes down that I failed to mention in the original post.  One is the case where your function returns a SqlDataReader -- though not always a preferred tactic especially if you don't have control over how the DataReader will be used.  In this case you cannot dispose of the SqlConnection (via using() or finally) or the connection will shut down prior to the DataReader being accessed.  Fortunately, you can pass a parameter to the SqlCommand.ExecuteReader() method of CommandBehavior.CloseConnection which will take care of the connection once the connection is gone.  Again, if you're using this strategy of returning a SqlDataReader your architecture might very well be flawed - consider instead calling back via a delegate which would effectively lend the reader to a function.  This gives you much better lifetime management on your connections and can help keep you in control.

Another alternative is to manually control the lifetime of your objects such as the following code.  This avoids having nested using clauses (which compiles down to nested try..finally clauses).  Ultimately (and by itself) this yields better performance than the nested variety at the expense of more code - but that's really just a one-time hit.  Besides, the performance gained by this strategy might very well be swallowed up by how performant your data logic is - IO to the database is going to be a heavier hit generally than the acquiring of the connection in the first place...and that would be the first place to optimize.

SqlConnection cn = null;
SqlCommand cm = null;
try {
   cn = new SqlConnection(cnStr);
   cm = new SqlCommand(sql, cn);
   cn.Open();
   // do work here

}
finally {
   if ( null != cm ) cm.Dispose();
   if ( null != cn ) cn.Dispose();
}


I suppose, therefore, that it's worth remembering to pay special attention to your connections and DISPOSE of them - if nothing else, at least CLOSE THEM....  This can be of utmost importance on an ASP.NET application where you have client request flowing in and you want to maximize the effectiveness the connection pool.

Monday, October 25, 2004 7:54:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  |  Trackback

Rico Mariani provides excellent guidance to developers in writing libraries.  I am something of a library author myself and like to think that I take issues such as these very seriously.  It is all to easy, especially with the proliferation of convenient objects/wrappers and the advancements in modern computing speeds and capacities, to become complacent in writing code and opt out for the easy route or the most convenient construct to accomplish the tasks at hand.  If the developers of yore who had to write an entire program in under 8k saw some of the code today...  ( ! ).

Three of issues that Rico brings up are, I feel, the biggest offenders in lulling programmers into complacency:

Principle #3:  Far too often we, as developers, make multiple passes over arrays or variables when analyzing their contents (not exclusively within the context of parsing).  If our logic is right we should be able to make only one pass with little to no state build up as we go.

Principle #4:  Strings are pretty easy to come by.  Be extremely careful when calling the various string functions as many of them actually create a new string instance on the heap...oh, the power of pointers!  I really like Rico's suggestion to use String.Compare() and to manage offsets rather than creating temp strings.  Also his comment “if you are using String.Substring or String.Split in low level APIs you've probably made a mistake“ is right on.

Principle #5:  when simply walking the contents of a collection (such as an ArrayList) don't use the enumerators (e.g. via foreach), instead rely upon indexes.  It doesn't really affect the readability of your code, and can give a perf boost as well.

When all is said and done, principle #7 is spot on: profile your code.

Though computers today have loads of memory and tons of computing power, let's be judicious and use those resources wisely and not be wasteful.

Anyway, thanks Rico for a great article!

Monday, October 25, 2004 5:17:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Saturday, October 23, 2004

Many developers (especially those involved in OOP at some level) are aware of interface inheritance.  Usually interface inheritance (also frequently referred to as interface implementation) comes in the form of a class providing functionality for an interface, wherein the interface is nothing more than a signature, a set of methods, properties, and/or events.

Interface inheritance provides a mechanism for different classes to be treated in like fashion, despite the fact that they are completely distinct.  By implementing an interface within a class you designate that that class will abide by the interface's contract; clients can expect to be able to invoke the various interface-specified methods.

Take, for example, the IDisposable interface.  If we were to define this interface ourselves, it would resemble the following:

namespace System {
   public interface IDisposable {
      void Dispose();
   }
}


If a class were to implement the interface, it can do so in a variety of manners.  For example, here are two:

using System;

namespace MyNamespace {

   public class MyClass1 : IDisposable {
      // implement the interface by signature (implicitly)
      // this method, though publically available via the class's interface will
      // be mapped at compile time to the IDisposable interface because it matches the
      // method signature in name, type, parameters, and is a public, non-static method.
      public void Dispose() {
         // clean up the object here...
      }
   }
  
  
   public class MyClass2 : IDisposable {
      // implement the interface explicitly
      // this method is not callable via the class's interface directly
      // instead it is only available via an IDisposable reference to the class
      void IDisposable.Dispose() {
         // clean up the object here...
      }
   }

}

Ok, please forgive the brief lesson.  All OOP developers know and fully understand these precepts.  In my experience, however, it seems that not as many developers are familiar with what I like to term interface aggregation.  Interface aggregation, though not true aggregation, occurs when you define an interface that implements another interface.  Now we know an interface cannot itself provide implementation (otherwise it'd be an abstract class - which is a slightly different beast).  So what happens?  Suppose we have the following:

namespace MyNamespace {
   public interface IAnimal : ICloneable {
      string Name { get; set; }
   }
}

In this case we have an interface (IAnimal) which has one property (Name).  The IAnimal interface also implements the ICloneable interface (which has a method called Clone()).  Therefore, a deriving class must also implement the Clone() method, but does it do it via the IAnimal or the ICloneable interface?

Well, it turns out that my moniker 'Aggregation' is not entirely true...the Clone() method does not actually get aggregated to the IAnimal interface.  We have to implement the interface either implicitly or explicitly via the ICloneable interface as such:

namespace MyNamespace {

   public class Goat : IAnimal {
      private string _name;
     
      // implicit implementation
      string Name {
         get { return _name; }
         set { _name = value; }
      }
     
      object Clone() {
         return this.MemberwiseClone(); // for demo, simply return a shallow copy
      }
   }


   public class Sheep : IAnimal {
      private string _name;
     
      // explicit implementation
      string IAnimal.Name {
         get { return _name; }
         set { _name = value; }
      }
     
      object ICloneable.Clone() {
         return this.MemberwiseClone();   // for demo, simply return a shallow copy
      }
   }
  
}

After seeing this we start to think...so?!  What's the big deal?  Well, here's the kicker.  By having an interface implement another interface, you aggregate your expectations.  After all, isn't an interface a set of expectations?  By defining an interface, I can enforce that a deriving class also implement another interface and ensure that behavior.

The coolest thing about interface aggregation is that while the methods on the inherited interface do not merge with the deriving interface, I can call them via a reference to the deriving interface!  You're not required to cast to the second (or base) interface in order to call the method.  Isn't that cool?!  Taking the above example, while the Clone() method isn't truly a part of IAnimal, I can call it via an IAnimal variable.

namespace MyNamespace {

   public class PetriDish {
      public void Mix() {
         // create the animal
         IAnimal sheep = new Sheep();
         sheep.Name = "Dolly";
        
         // clone it via the IAnimal interface
         Sheep duplicate = (Sheep)sheep.Clone();
      }
   }  

}

Where I have found this to be the most beneficial, in all honesty, is with respect to COM+ (Enterprise Services) components.  Call me crazy, but I am still in love with COM+.  In the traditional COM+ world, your components get pooled and as such, you want to release them back to the pool as quickly as possible after you're done using them.  A convenient way to do this is to call the Dispose() method on a ServicedComponent (which internally calls ServicedComponent.DisposeObject()).

ServicedComponent already implements IDisposable so half of our work is done.

Being the good COM+ programmers that we are, we decide to create a public interface for our COM+ component rather than define methods directly on class...if you want, I can elaborate on this in another post.  In this simple example, we will create a COM+ component that retrieves a customer name from the database; contrived, yes I know, but I'm typing everything in Notepad2 and don't have the luxury of a syntax checker so it's all off the cuff.

COMPONENT CODE

using System;
using System.Data;
using System.Data.SqlClient;
using System.EnterpriseServices;

namespace MyComPlus {

   public interface IDataCustomer : IDisposable {
      string GetName(int custId);
   }
  
  
   [EventTracking()]
   [ClassInterface(ClassInterfaceType.None)]
   [ObjectPooling(true)]
   [JustInTimeActivation(true)]
   [Transaction(TransactionOption.Supported)]
   public class DataCustomer : IDataCustomer {
      string IDataCustomer.GetName(int custId) {
         using ( SqlCommand cm = new SqlCommand("SELECT Name FROM Customers WHERE ID = @ID") ) {
            cm.CommandType = CommandType.Text;
            cm.Parameters.Add("@ID", SqlDbType.Int).Value = custId;
           
            return (string)cm.ExecuteScalar();
         }
      }
   }

}


CLIENT CODE

using System;
using System.EnterpriseServices;
using MyComPlus;


namespace MyClient {

   public class EntryPoint {
      public static void Main() {
         Customer c = new Customer(15);
         Console.WriteLine("Customer Name: ", cust.Name);
      }
   }
  
  
   public class Customer {
      private int _id;
     
      public Customer(int id) {
         _id = id;
      }
     
      public string Name {
         get {
            // create a new Customer via the IDataCustomer interface
            // the using block will automatically invoke the IDisposable.Dispose() method
            // when it finishes, effectively returning the object to the pool
            using ( IDataCustomer customer = new DataCustomer() ) {
               return customer.GetName(_id);
            }
         }
      }
   }
  
}

NOTE:  None of this code has been checked for syntax, spelling, or run through a compiler, so I'm hoping it works as entered.  If not, please let me know and I'll be happy to fix it for you and update the post.

The ability to create an interface is powerful, but it's also fundamental.  The ability for an interface to force a deriving class to implement another interface by deriving from it itself, is extremely enabling and provides a rich object model to your applications.

Saturday, October 23, 2004 9:51:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [3]  |  Trackback
 Sunday, October 17, 2004

In order to provide runtime configuration settings for your applications it's customary to provide a .config file (e.g. web.config, app.exe.config, etc).  Usually, this .config file resides along side your application's .exe file.  The .NET runtime automatically loads the appropriate .config file and examines its contents at runtime as needed.  When developing COM+ applications there are a few other things to be aware of, namely the Activation model used.

COM+ applications can be either Library Applications or Server Applications.  Though there are several important distinctions between the two, the most noticeable difference is that Library Applications are always run in-proc with the calling/host applications.  Library applications, therefore just like any other dll, utilize the host application's .config file for settings.  Server Applications are different, however, in that they are run out-of-proc.  What does this mean?  Well, for starters, a process named dllhost.exe actually provides the application isolation.  dllhost.exe is the host application and is found in the %WINDIR%\System32 folder.  Therefore it is traditional to place your application's configuration settings in a file named dllhost.exe.config within the same folder.

I've cringed everytime I recommended that strategy.  It has pitfalls:

  • all COM+ applications share the same config file.  This has problems.
    • First of all, name clashes can easily occur if you're brave/foolish enough to use and not custom configuration settings.
    • Second, if the application has already started it won't recycle automatically if the .config file changes (a la ASP.NET applications).  You have to actually stop and restart all applications that rely on the new values.
  • it's not a recommended strategy to place files in the %WINDIR%\System32 folder

This issue has been fixed/remedied with COM+ 1.5 (XP and Windows Server 2003).  In the COM+ catalog you can set the Application Root Directory for an application on the Activation tab.  At runtime now, COM+ will look in that folder for two files: application.manifest and application.config.

Your application.manifest file should contain the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" />

Set up your application.config file just as you would for any .config file.

Sunday, October 17, 2004 5:55:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [10]  |  Trackback
 Friday, October 15, 2004

I'm doing a little probe here.  We hear developers constantly talk about their business objects.  Pretty much every discussion revolving around application design mentions them in conjunction with UI objects and Data objects.  What are they?  What is a business object to you and what functionality does one have?

Is a business object...

  • a data container (just a fancy struct)?
  • an object that can "get" an instance of itself from the data store (via static methods)?
  • an object that can "save" itself to the data store?
  • something else?

Where do your business objects live?

  • right along side the UI objects?
  • In a separate library? separate process? separate machine?
  • in the same application but functionally distinct from the UI objects?

How much about the data store do your business objects know and understand?
How do you "get" one? via a data layer? directly?

Suppose you had a "business object" called Customer.  The Customer class is defined within a distinct library; it's physically separate from your UI and your database objects.  How would you design Customer?  How would you distinguish between a "new" Customer and one that had been retrieved from the data store (i.e. an "existing" one)?  Is there any way your data tier can distinguish the two?

For example:  Is there anything you can do to prevent the UI from creating a Customer object that, when saved, wouldn't overwrite an existing Customer from the database?  Is it important to have this level of distinction?

There's no right or wrong answer here, as the answer may be based on context or usage.  I'm just curious what anyone else has to say about these matters.  For the most part we encounter issues such as these (on some level) almost on a daily basis in designing applications.  I have my solutions, but I want to see what feedback I can get before revealing what I think would be an appropriate answer.

Friday, October 15, 2004 10:15:00 AM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [4]  |  Trackback

Over the past weeks, I've had the opportunity to periodically devote my efforts to the design and maintenance of a home-grown website that I use(d) to track defects, issues, tasks, etc for my projects that I develop, among other things.  This project has been a pet project for a long time and was, in fact, one of the very first projects that I ever created using the .NET platform.

Since the time of its inception (back in 2001/2002) I have learned a lot and have wanted to take my new-found intelligence and apply it to my old project.  Unfortunately, the application had grown to a point that it wasn't feasible to simply go in with a small hand broom or a dust-vac and straighten things up a bit...it was going to take some heavy lifting.

I therefore put on the gloves and decided to rip the house down and start from a brand new foundation.  I've blogged about some of these underpinnings periodically over the past months, but I wanted to share some of the insights and inroads I've made toward the completion of the project.

First of all, the application performed extremely well with a small number of users.  Granted the application and its back-end database were on the same server.  Being that the application is an ASP.NET application, I want to be able to accommodate many (100+ simultaneously).  This application (now called DevTracker) is designed to be used by a team of developers and provide the experience that a user would expect from a Windows application.  Well, my original design was not very flexible and would be hindered with more than just a handful of users.  I had no clear separation of UI-logic and data access logic.  Except for just a few objects, the lines were very blurred.

<RANT>

In fact, I think this is one of the dangers with ASP.NET development.  Just like VB made it very easy for non-developers to be productive but at the same time create horrendous, terrible code, ASP.NET makes it very easy to create non-object-oriented websites.  Pre-.NET, the push from Microsoft was the Distributed iNternet Application Architecture (DNA).  This set of principles encouraged the separation and distinction of the logical layers (UI, Business, and Data) using technologies such as MTS and COM.  I, along with many others, subscribed to these principles.  With the advent of .NET (particularly ASP.NET) it seemed to be that the lines became more hazy.  All of the sudden people were recommending bringing DataReaders up to the UI level and binding to them, of dropping Connections and Commands right on their .aspx pages and querying the database directly.  For simple applications this might be fine, but I'd far from recommend it for anything that's gonna have to take a lot of load.

Sure, it used to be done before (even in the DNA days).  People would bind to Recordsets and perform database queries right on their pages, but while the rest of the .NET world was moving forward with nice clean OOP, ASP.NET seemed to be left behind; though I hear things will be changing with v2.0.  It's not as easy in an ASP.NET application to separate the layers - especially when it's so darned convenient to copout and do it the easy way.

I believe that developers feel that they need the raw performance available with DataReaders directly on their pages.  They don't want the perceived overhead of offloading the work to another server (say a COM+ server) when that's the kind of work that an application server does best...probably better than anyone could do on their .aspx pages.  What they don't always realize is that the physical distribution of the network can play a HUGE part in an application's performance.  If the IIS server is the same box as the SQL server, there's no IO on the NIC, so it might make more sense to bind to a DataReader.  However, if the IIS server is separate from the database server which is better? 1) performing a round trip to the database server for each DataReader.Read() call? or 2) having the application server gather all the information from the database right there and return it to the web server in one batch?  People often confuse the issues.  Few objects doesn't necessarily mean better performance.

Anyway, enough of that.

</RANT>

I wanted, in DevTracker, to design an optimal architecture that would cleanly support the physical separation of the application layers while at the same time allowing for optimal performance when located on a single machine.  To accomplish this, as a developer I have to maintain a level of discipline - I can't simply decide to do something the quick and dirty way because in the event of component relocation I don't want the application to break.

Many of the services that are presently tightly coupled within DevTracker really affect the larger whole.  These objects should be available outside the scope of the website, but still within the context of the “application“.  For example, I'm wanting to design a Windows/MSN Messenger plugin that would display a user's set of issues, giving the user direct access to them.  I also want to complete a Windows-based UI that feeds off of the same data.  If all of these objects were directly within the ASP.NET application intertwined on my pages there would be no real way to get to them cleanly.  Instead, by distributing the objects (or at least separating them), I can design interfaces (Web Services?) that expose the objects more naturally.

The best way I can envision to do this, and the obvious choice, is to make the libraries available within COM+.  By leveraging the capabilities of Enterprise Services, I am able to offload much of the horsepower to a second server.  That server therefore acts as a floodgate for all database activity, object JITA/pooling, connection pooling, security, and much more; relieving my IIS web server to do what it does best - serve pages.  So far, this strategy has proven to be beneficial and highly performant.  I'll let you all know what my performance tests yield in comparison.

Friday, October 15, 2004 9:54:00 AM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  |  Trackback