this.Blog.Find(entry => entry.IsHelpful);
 Wednesday, June 10, 2009
WCF and IDisposable

If you’re like me (and apparently many other people), when you start using (no pun intended) WCF by creating a client channel, it’s only a matter of time before you realize that you’re probably doing it wrong. 

Problem number one is that if you don’t explicitly close the connection, it’s only a matter of time before the connection starts faulting.  So you say to yourself, “Aha!  I need to close the damn connection.  And since I’m a good .Net programmer, I see the IChannelListener interface extends the IDisposable interface so I can just wrap my call in a ‘using’ statement which will explicitly clean up all my resources no matter what happens during the method execution.”

And then an exception happens.  Even though you wrap your call in the using statement, you see this weird exception about the channel being in the faulted state (or something like that).  Wait – I wrapped my call in the using statement.  This should work!  So you fire up Google Bing and quickly learn the WCF team made the decision to implement IDisposable wrong uniquely. 

In order to get a WCF client to work as expected, you need to workaround the decision made by the WCF team and wrap all your WCF calls in blocks similar to this one:

  1: var channelFactory = new ChannelFactory(binding, endpointAddress);
  2: 
  3: var proxy = channelFactory.CreateChannel<ICustomerService>();
  4: IClientChannel clientChannel = (IClientChannel)proxy;
  5: bool isSuccessful = false;
  6: try
  7: {
  8:   proxy.AddCustomer(customer);
  9:   clientChannel.Close();
 10:   isSuccessful = true;
 11: }
 12: finally
 13: {
 14:   if ( !isSuccessful )
 15:   {
 16:     clientChannel.Abort();
 17:   }
 18: }

As you can see here, you must explicitly call Close() on the client channel unless an Exception is thrown, in which case you need to call the Abort() method.

This code doesn’t just emit a code smell of violating the DRY principle, it absolutely reeks of it.  Steve Smith (and others) have come up with extension/utility methods aimed at simplifying the call and removing the repetitive boiler plate code from the above example.  Inspired by these solutions, I’d thought I’d throw out my own answer to this problem:

  1: public class WcfClient<TInterface>
  2: {
  3:   public WcfClient(Uri uri) : this(uri, new NetTcpBinding(SecurityMode.None))
  4:   {
  5:     Uri = uri;
  6:   }
  7:   
  8:   public WcfClient(Uri uri, Binding binding) 
  9:   {
 10:     this.Uri = uri;
 11:     this.Binding = binding;
 12:   }
 13:   
 14:   public Uri Uri
 15:   {
 16:     get;
 17:     private set;
 18:   }
 19:   
 20:   public Binding Binding 
 21:   {
 22:     get
 23:     private set;
 24:   }
 25: 
 26:   public void Using(Action<TInterface> serviceAction)
 27:   {
 28:     TInterface proxy = CreateChannelFactory().CreateChannel();
 29:     IClientChannel clientChannel = (IClientChannel)proxy;
 30:     bool isSuccessful = false;
 31:     try
 32:     {
 33:       serviceAction(proxy);
 34:       clientChannel.Close();
 35:       isSuccessful = true;
 36:     }
 37:     finally
 38:     {
 39:       if ( !isSuccessful )
 40:       {
 41:         clientChannel.Abort();
 42:       }
 43:     }
 44:   }
 45: 
 46:   public TResult Using<TResult>(Func<TInterface, TResult> serviceAction)
 47:   {
 48:     TResult result;
 49:     TInterface proxy = CreateChannelFactory().CreateChannel();
 50:     IClientChannel clientChannel = (IClientChannel)proxy;
 51:     bool isSuccessful = false;
 52:     try
 53:     {
 54:       result = serviceAction(proxy);
 55:       clientChannel.Close();
 56:       isSuccessful = true;
 57:     }
 58:     finally
 59:     {
 60:       if ( !isSuccessful )
 61:       {
 62:         clientChannel.Abort();
 63:       }
 64:     }
 65: 
 66:     return result;
 67:   }
 68:   
 69:   private ChannelFactory CreateChannelFactory()
 70:   {
 71:     var endpoint = new EndpointAddress(Uri);
 72:     return new ChannelFactory(Binding, endpoint);
 73:   }
 74: }

The two Using() methods offer an overloaded way to invoke a method on the service proxy.  In the first version, you can invoke an Action call which doesn’t expect a returned value.  In the second version, the TResult generic type determines the type of value expected from the invocation of the proxy object.  The return value will flow through from the proxy call execution to the caller.  Think of these two methods as being akin to the differences between a Sub or a Function in VB (my God, did I just admit to knowing VB?!?!?!).

The WcfClient code is responsible for creating the client proxy and returns the proxy back to the calling code.  As the caller, here is how you would execute the methods:

  1: string wcfUri = ConfigurationManager.AppSettings["wcfUri"];
  2: 
  3: var wcfClient = new WcfClient<ICustomerService>(wcfUri);
  4: 
  5: wcfClient.Using(proxy => proxy.AddCustomer(new Customer()));
  6: 
  7: // ...
  8: 
  9: Customer[] customers = wcfClient.Using(proxy => proxy.GetCustomers());

The nice thing about this solution is that we take care of the exception handling and correctly clean up our resources in one place, and that logic is completely shielded from the calling code.  Plus, we can account for situations where a return value is expected versus when one is not.


Kick it on DotNetKicks.com
Tuesday, June 09, 2009 11:02:10 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | C# | WCF

 Sunday, February 01, 2009
More Love For Lambda Expressions

When I first jumped into C# programming, one of the biggest points of confusion for me was in understanding delegates.  You see, Java had no real similar concept.  So the idea of function pointers didn’t really register with me.  I saw some really weird syntax for event handlers that looked like this:

   1: myButton.Clicked += MyButton_Clicked;
   2:  
   3: // ...
   4:  
   5: private MyButton_Clicked(object sender, EventArgs e) 
   6: {
   7:     // do something
   8: }

Eventually, I caught on that because the function called MyButton_Clicked satisfied the signature required by the OnClick event, it could be added as an event handler to the event.

Aha!  Delegates are nothing more than “interfaces” at the method (as opposed to class) level.  So even though I understood what delegates were, I still didn’t see a widespread use for them outside event handlers.  Sure, I saw examples where they were used, but they all seemed very contrived to me. 

Enter in lambda expressions

Lambda expressions were introduced in C# 3.0.  I’ve said it before, while lambda expressions are new to .Net, they are not even close to being a new concept in programming languages.  They have been around forever.  Basically, it’s a terse syntax for defining anonymous delegates.  In .Net, they were really a simpler way to interact with LINQ.  Now you no longer had to go through the ceremony of creating an explicit method just to satisfy the compiler.  This “inline” function call was especially useful in simple delegate calls, as in a Predicate:

   1: var myList = new List<Person>();
   2: // ...
   3: Person chris = myList.Find(person => person.FirstName == "Chris");

I don’t know why, but I really latched on to lambda expressions in a  way I never did with delegates.  Which is actually a little weird, since I’ve heard numerous complaints that the lambda expression syntax is too confusing for the average developer. 

Changing the way I code

Now, lambda expressions have really changed the way I approach programming.  I’ll give an example from Miado.  I wanted to add support to Miado for creating typed DataSet objects (in addition to regular DataSet objects).  I added support for a querying for a DataSet using generics, where the generic type had to be a class derived from DataSet:

   1: public virtual T QueryForDataSet<T>() where T : DataSet

I wanted to have one common method that handles creating both types of DataSets (the ol’ DRY – i.e. “Don’t Repeat Yourself”).  Here’s the rub - when using a DataAdapter to fill the DataSet, the method actually is just a little different from using a regular DataSet versus a typed one.  It’s not that different, but enough to make you have to handle it two different ways.  Previously, I probably would’ve created a template method or maybe handled it through an interface.  But to use interfaces would require an interface to define the method and two separate classes to implement the varying implementations.  That’s a lot of work to accomplish this seemingly simple task.

Hmm … if I could just pass in the method  that I want to call, I can solve this problem much easier.  Enter in my good friend Action<T> to the rescue! 

Action<T>

Action<T> is a delegate method.  It takes in an instance of the generic T type defined in its signature and has no return value.  So it’s a callback method that performs some action (and thus cleverly named).  I love this delegate.  It’s really great for implementing simple one line functions via a lambda expression.  The syntax becomes very terse without having to build up all the ceremony just to satisfy the compiler.

Implementation

Actually, Action is overloaded so you can pass in multiple arguments.  In my case, I am using two arguments to the method (i.e. Action<T,U>).  Here is the way I implemented it:

   1: private T QueryForDataSetUsingCustomDataAdapterFillFunction<T>(
   2:             Action<DbDataAdapter, T> adapterFillFunction) where T : DataSet
   3: {
   4:     T ds = CreateEmptyDataSet<T>();
   5:  
   6:     using ( DbConnection conn = this.Database.CreateConnection() )
   7:     {
   8:         conn.Open();
   9:  
  10:         using ( DbCommand cmd = conn.CreateCommand() )
  11:         {
  12:             cmd.CommandText = this.CommandText;
  13:             cmd.CommandType = this.CommandType;
  14:  
  15:             if ( this.Parameters != null )
  16:             {
  17:                 cmd.Parameters.AddEnumeration(this.Parameters);
  18:             }
  19:  
  20:             using ( DbDataAdapter adapter = this.Database.CreateDataAdapter() )
  21:             {
  22:                 adapter.SelectCommand = cmd;
  23:                 adapterFillFunction(adapter, ds);
  24:             }
  25:         }
  26:     }
  27:  
  28:     return ds;
  29: }
  30:  
  31: public virtual DataSet QueryForDataSet()
  32: {
  33:     return QueryForDataSetUsingCustomDataAdapterFillFunction<DataSet>(
  34:             (adapter, ds) => adapter.Fill(ds));
  35: }
  36:  
  37: public virtual T QueryForDataSet<T>() where T : DataSet
  38: {
  39:     return QueryForDataSetUsingCustomDataAdapterFillFunction<T>(
  40:             (adapter, ds) => adapter.Fill(ds, ds.Tables[0].TableName));
  41: }

Basically, I made it so that the common method takes in a function that, given a DataAdapter and a DataSet, does some work on those objects.  So the two public methods pass in a different implementation of the Fill() method on the DataAdapter.  Like I said before, it’s kind of like using interfaces for methods.  The common method (in line 23) calls the Action method to perform its specific function by passing back the current DataAdapter and DataSet.

Conclusion

Again, lambda expressions have changed the way I approach programming.  Once you get a handle on the syntax, it’s a great tool to have in your toolbox!


Kick it on DotNetKicks.com
Sunday, February 01, 2009 3:46:49 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  .Net | C# | Miado

 Wednesday, January 28, 2009
Atlanta Alt.Net User Group Meeting
agile_book

Tonight we are going to have another meeting of the Atlanta alt.net user group.  We are meeting at Manuel’s Tavern again, but we are supposed to be in a different room this time.  I know the last meeting at Manuel’s was a little hard to find (if you weren’t there, last time they put us in a side room off another room that was holding a meeting, which had closed its outer doors to the rest of the restaurant). 

This week were are going to be in the “Eagle’s Nest” room, which is located on the other side of the restaurant off the main dining area on its southern side.  Look for the small stairs in the corner of the room.

We are going to be discussing the book, “Agile Estimating and Planning” by Mike Cohn.  If you haven’t read the book, it’s no big deal.  We will be discussing lots of other things, too.  

Hope to see you there!


Kick it on DotNetKicks.com
Wednesday, January 28, 2009 10:01:32 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | alt.net | User Groups

 Monday, January 12, 2009
Minimizing Accessibility And Testing Internal Classes in C#
Effective_Java

There is a great book on the Java programming language called Effective Java by Joshua Bloch.  Even if you don’t use Java as your primary coding language, this book contains innumerable software engineering tips and design patterns that will help you improve in no matter what language you code.  It’s a great reference guide that I continuously go back to, even though I haven’t done much Java coding in the last few years.  The fact that I bought the second edition when it came out despite the fact I no longer really do Java should tell you something.  Josh, if you’re reading this post, you can contact me to see how you can send me the referral fees.

The first item in the “Classes And Interfaces” section of the book is: “Minimize the accessibility of classes and interfaces”. The idea is to not just think of encapsulation in terms of class internals, but to also take it to the next level - meaning up to your API in general.  As Bloch says,

"The single most important factor that distinguishes a well-designed module from a poorly designed one is the degree to which the module hides its internal data and other implementation details from other modules.  A well-designed module hides all of its implementation details, cleanly separating its API from its implementation.  Modules then communicate only through their APIs and are oblivious to each others’ inner workings."

It’s a principle I strive for in all my software design.  By making your API strong and weakening your implementations, you are effectively decoupling your module from the rest of the system.  This decoupling allows you to easily develop, test, and refactor your module in isolation without affecting the rest of the system.  It’s a concept that falls right in line with “The Open/Closed Principle”.  This principal states you should make your software modules “open” for extension, but “closed” for modification.

One of the easiest ways to accomplish encapsulation in an object-oriented language is through the use of access modifiers (e.g. public, protected, internal, private).  Anything you declare as public is open to the whole world.  Therefore, Bloch says that when design your software, “make each class or member as inaccessible as possible.”

I am the author of an open-source project called Miado.  It’s an API that sits on top of ADO.Net and attempts to simplify data access and remove the repetitive, error-prone, boiler plate code we write over and over again in our data access modules.  In building my API, I’ve tried to adhere to good OO design principles.  I’m a big fan of coding to interfaces, using dependency injection, unit testing, and mocking.  Therefore, I’ve exposed most of the API as interfaces rather than concrete classes.  Since I want to abide by the tenants I’ve talked about already, I’ve restricted the corresponding class implementations of these interfaces.  They are declared as “internal”, which in C# terms means they are only exposed to classes in the same assembly in which they are defined.  Since no external assembly can reference my implementations, the “black box” of my interface is upheld, yet allows the consumer to override their own implementations (even if it is only in a mock).

Now this is all well and good, but there’s one more thing of which you need to be aware.  Remember that when you mark a class as “internal” in C#, only classes in that same assembly can reference that class.  Like I said, I’m a big fan of unit testing.  How do you test a class in a test assembly when you can’t even see it???  You could move your test classes to the declaring class assembly, but that’s really just a bad idea.  It adds extra overhead to an assembly and provides no real value to its consumer.  It’s just extra noise taking up space.  And jumping through hoops to remove those test classes as part of a build step reeks of wasted effort.

Java has a nice way to get around this gotcha.  In Java, “protected” scope is somewhat similar to “internal” scope in C#, with one important distinction.  Protected accessibility in Java allows any subclass to access that member, as well as any other class in the same “package” (a close cousin to a “namespace” in C#).  So when you write your unit tests in Java, you merely have to declare your unit test class as belonging to the same package as the class being tested, which then allows you to access any of that class’s internal state and behavior, even if it gets deployed as a separate jar file.  Unfortunately, C# has no similar “namespace” accessibility modifier.

But .Net does have some aces up its sleeve.  There is a way to declare another assembly as a sort of “friend” assembly so that it can see the original’s internal members.  In the original assembly (the one being tested), add the following line to your AssemblyInfo.cs class:

   1:  // let the unit tests see internals of this assembly
   2:  [assembly: InternalsVisibleTo("Miado.Test")]

Now, this is not something I would regularly do (it defeats the whole purpose of hiding implementation details in the first place!), but it does get around the problem of being able to unit test internal code modules.  Simply adding this one line to your assembly can allow you to improve your API immensely.  Now you don’t have to sacrifice the accessibility of your modules just to make them easier to unit test!
Kick it on DotNetKicks.com
Monday, January 12, 2009 4:46:33 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | C# | Java | Miado

 Tuesday, October 21, 2008
WSCF Moved to Open Source on CodePlex

Thinktecture has announced that their popular Web Service Contract First tool (WSCF) has been made available as an open source project hosted on CodePlex.

I love using WSCF to build web service proxy interfaces for traditional asmx web services.  It is a fantastic tool that greatly improves upon the traditional “Add a Web Reference” functionality in Visual Studio.  The one thing I was always frustrated about it was the (lack of) speed of its development, and the timeliness of keeping up with .NET releases.  Hopefully, the open source community will rise to the challenge and improve upon an already solid product.


Kick it on DotNetKicks.com
Tuesday, October 21, 2008 8:00:12 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Open Source | Visual Studio | Web Services

 Wednesday, September 24, 2008
Favor Composition Over Inheritance

I've come across all kinds of architectures in my time.  Some have been good, some bad (yet somehow the bad vastly outnumber the good).  Even on some of the good architectures I've seen, a common problem I've found is the abuse of object inheritance. 

It's tempting to create an inheritance hierarchy to quickly get all the functionality provided by a common base class.  Through one little symbol or keyword, you can easily extend your object to get all the functionality provided by some other class.  However, be aware this kind of modeling comes with a price, and many times it's a price more steep than you should be willing to pay. 

Which is why a lot of people much smarter than me - Josh Bloch, Venkat Subramaniam, Andy Hunt, Dave Thomas, Robert "Uncle Bob" Martin, and Steve McConnell - have all argued that using composition instead of inheritance creates a much more Agile object model.  There are many reasons why Agile developers feel this way.

Conceptually

"Is-a" vs. "Has-a"

In inheritance modeling, class inheritance should only be used to represent true "subtype" relationships.  Every subclass should be a subtype of the class it is extending.  Object B should only extend Object A if a logical "is-a" relationship exists.  In other words, you need to ask yourself, "Is every B really an A?"  If you cannot truthfully answer yes to this question, there is no reason for B to extend A other than simple convenience.  And convenience is not a good reason for creating an inheritance hierarchy. 

Steve McConnell explains further in his seminal book Code Complete,

"If the derived class isn't going to adhere completely to the same interface contract defined by the base class, inheritance is not the right implementation technique."

Rather, you are better served modeling a "has-a" relationship between the two classes, where A is a private instance in the implementation details of B.  B may depend on the services provided by A, but is not a logical subtype of it.  By "wrapping" the reference to A, you will have a more conceptually accurate and flexible implementation.

It's all about the context!

A consumer of an object should be able to intuitively decipher its purpose from its public API.  When you force an inheritance hierarchy of two objects that don't have an "is-a" relationship, you have created an subclass object that contains methods, properties, fields, etc. from two different contexts.  By combining these contexts, you have created a confusing API that causes the consumer of it to have to actively track down the meaning behind methods exposed from the two contexts.

For example, suppose I have an Account object that extends TransactionCoordinator.  The two objects have two different contexts, and the design of their individual APIs most likely reflect that fact.  As a consumer of the Account object, when I see methods such as Start(), Commit(), Rollback() that have been inherited from the base class representing a different context, I am confused.  Intuitively, an Account is not a TransactionCoordinator, and I would have to know that inheritance relationship even exists to understand why I am seeing these methods.  Normally, I wouldn't expect to see them there.  What do these methods mean?  What do they do?  If I'm lucky, I can look at the API documentation (if it exists) on the Account object and it will detail each method and its functionality and implications when called from the subclass.  More likely, I will have to open the Account object up, see that it extends the TransactionCoordinator, and go there to research what each method actually does.  And only then can I have the ability to decide if that behavior is something I want to invoke on my subclass.

Here’s the lesson - don't make consumers of your API work any harder than they have to.

Liskov's Substitution Principle

Barbara Liskov wrote one of most ground-breaking papers on object-oriented programming in 1998.  In this paper, Liskov proposed that you shouldn't inherit from a base class unless the derived class truly "is-a" more specific version of the base class.  In what became known as the "Liskov Substitution Principle", Liskov argued that any derived class must be able to be completely substituted for its base class interface without any knowledge of the calling class.  In other words, subclasses must only change the implementation and not the meaning or intent of the base class interface. 

Say you have an abstract base Account object.  Callers that reference the base class API should not have to know or care which whether a CheckingAccount or SavingsAccount derived class actually provides the implementation.  To take the example further, suppose there is a CalculateInterest() method declared on the Account object.  In normal implementations it calculates the interest due to the consumer.  Suppose you introduce a BankLoanAccount which changes the implementation to calculate the interest for the bank.  This class violates the LSP since it changes the meaning of the implementation of the CalculateInterest() method, so now the caller cannot freely call the method on the base class reference.

Single Responsibility Principle

I'm a firm believer in the Single Responsibility Principle.  Classes should have one responsibility, and one responsibility only.  Think of it as the old Henry Ford assembly line - classes should do their one thing and do it well.  There is no reason for them to know the inner details or the workings in the classes in which it interacts.  This leads to smaller, more focused classes.  And small, purposeful classes are A GOOD THING. 

Single responsibility creates classes that are highly cohesive, while limiting coupling to external dependencies.  High cohesion and low coupling is an admirable goal in any software architecture.

Planning for change

By limiting classes to one responsibility, you are also creating a class that has only one reason to change.  As a developer who believes in Agile methodologies, I know change is going to come.  Limiting the reasons for classes to change, as well as the surface area in which that change will be felt, will go a long way towards making those changes easier to implement.

Technical

Introduces Dependencies

Anytime you inherit from a class, you are explicitly creating a dependency on that super class.  The code to the super class may change over time.  Each time it does change, it can potentially directly or indirectly break some or all of its subclasses, even though the code in subclasses may not have changed at all.  Most likely, the subclasses had no idea the change even occurred at all.  And unless you have planned for this contingency in your unit test (you are writing unit tests, right???), you may not even find this breaking change until after the code is deployed.  And if you are writing unit tests, that's just more (seemingly avoidable) unit tests you need to write to handle these cases.

This creates a lot more work for the API producer.  All subclasses now will have to be designed (and tested) to evolve in conjunction with their super classes.  That's more code and more unit tests you now have to write and maintain.

Fragile classes

Due to rules we must live with when choosing a static, compiled language, we limit ourselves in the structuring of our API.  Anytime we define a method signature in any class, this signature causes a ripple effect up and down the inheritance hierarchy.  That's both good and bad.  Each base class automatically inherits the new functionality, but guess what - it may not want to do so.  Or worse yet, it can break existing functionality in the subclass.

For example, introducing or changing a method signature in the base class will flow down to every class that derives from it.  What if that subclass already has a method defined in that class with the same name?  This will cause either: a compilation error if the method cannot be overridden; or worse yet unexpected behavior at runtime if the method can be overridden as the subclass implementation is now unknowingly invoked.  Or, what about if the subclass has the same method name but a different signature?  You will be forced to change your API in one of the classes just to get them to compile.  The same problems manifest itself as methods are introduced in base classes, but at least you are a probably little more aware of the potentially breaking changes.

Think this is a far-fetched example?  I don't.  Imagine common method names like Execute(), Activate(), Register(), or IsAvailable(), Open(), Load(), or Save().  All of these are all methods names that are prolific in our object models, and could easily have much different signatures as well as potentially meaning very different things in different contexts.

What if the behavior introduced in a base class implementation is not desired in the subclass?  Sorry, your S.O.L.  Good and bad, you get everything that comes down from the base.

Refactoring

Due to all the problems with carrying "API baggage", classes with deep hierarchies are much harder to refactor.  Are you completely comfortable with the API provided by your super class?  Because anytime you extend it, any flaws/issues/concerns you have with it are propagated down to the subclasses.  Not only that, the flaws now become further spread across your object model through the expanded surface area of all of its own and now its subclasses consumers.  Composition is much more flexible.  It has the advantage of masking, improving, or changing the API to encapsulate the existing concerns.

Not only that, but now you have tied yourself to this mis-matched inheritance hierarchy, and it will be much harder to introduce a new base class if a new valid one ever presents itself.

Summary

Inheritances is one of the most powerful and most abused concepts in object-oriented programming languages today.  True, inheritance is an easy and useful way to provide quick code reusability across your object model.  But the drawbacks of doing so far outweigh the short-term gains achieved.  Oftentimes the reusability gained comes as the expense of code extensibility, maintainability, and testability.  In the long run, ironically both producers and consumers of the API will have to do more work to maintain the fragile inheritance hierarchy.  Favor composition over inheritance to limit fragile inheritance hierarchies and create a much more flexible and powerful API.


Kick it on DotNetKicks.com
Wednesday, September 24, 2008 10:30:23 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Back To Basics

 Monday, September 22, 2008
Atlanta ALT.Net Meetup

The Atlanta ALT.Net user group is meeting again this Wednesday, September 24 at the Thinking Man Tavern in Decatur.  If you plan on attending, the organizers are asking people to RSVP in order to get an accurate head count. 

We are going to spend some time talking about ASP.Net MVC, but I imagine it will be open to discussion on all topics.  Hope to see you there!


View Larger Map


Kick it on DotNetKicks.com
Monday, September 22, 2008 10:26:11 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | alt.net

 Saturday, August 09, 2008
Isolated Storage

In my last post, I showed how to write stuff out to a temporary directory.  After I wrote the post, I started thinking about how people could misconstrue the meaning of it.  The post was intended to show how to dump stuff easily to a random directory on the file system.  The code that drove me to write that particular example came from a unit test that was using the temporary directory as a repository for the output of the XmlSerializer.  In other words, I really was not doing anything meaningful with the data.

To clear things up, I thought I would write a post that showed how use a unknown storage directory as a meaningful repository for application data.  What constitutes meaningful data?  I don't know, it's your app!!!  But common possibilities include application settings, user-specific data, etc...  I'm thinking of things that might be otherwise be stored in the registry.  Yeah, don't do that anymore.  I don't know about you, but the just the word "registry" causes me to shudder.

.Net has introduced a new concept called "Isolated Storage" to hold this type of information.  Isolated storage is an unspecified location on the file system that is hidden away from the application.  Even though the location is unknown, the application is guaranteed to have full permissions to it, even if it is running in a restricted security mode.  As it name implies, the location is "isolated" so that any data written to it does not affect other applications or anything else on the file system.  So as far as security goes, you're limited to only hurting yourself by maliciously or ignorantly (mis)using this repository.

Here's a code sample of how you would use it to store data:

// get the location specific to this user/assembly
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly();
// create a file to write the data to 
using ( var outStream = new IsolatedStorageFileStream("foo.txt", FileMode.Create, isf) ) 
{
    using ( var sw = new StreamWriter(outStream) ) 
    {
    	// write out the text
        sw.Write("Random text");
        sw.Close();
    }
}

And here is how you can retrieve it:

IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly();
// open the file
using ( var inStream = new IsolatedStorageFileStream("foo.txt", FileMode.Open, isf) ) 
{
    string[] files = isf.GetFileNames("foo.txt");
    if ( files.length > 0 )
    {
        StringBuilder sb = new StringBuilder();
        foreach ( var file in files )
        {
            using ( var sr = new StreamReader(inStream) )
            {
                sb.AppendLine(sr.ReadLine());
            }
        }
    }
}

This method is a much more "enterprise-y" way to access data in your applications.


Kick it on DotNetKicks.com
Saturday, August 09, 2008 3:45:26 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | C#

 Friday, August 08, 2008
Using Temp directories in .Net

Have you ever found the need to use a temporary directory on the file system in your code?  This issue came up with me recently (and bit me in the ass), so I thought I would share some experiences on how I overcame the problem. 

At the root of the problem is that you need some sort of permanent storage, but nothing that is stringent enough to require it reside in some "known" directory where it can be accessed at a later time.  You don't really care where you store a file, but you need to store it somewhere. 

I recently came across a piece of code in a unit test that serialized a class using the XmlSerializer.  The person who wrote the test must have wanted to see what the class looked like in serialized form.  The code was written so that the xml version of the class was dumped to the file system.  However, when the test was written, the file was hard-coded to the C:\Temp directory. 

As part of my task, I was incorporating the unit tests on this component into the continuous build.  Guess what happened when the test was moved the build server?  FAIL!!!  No C:\Temp directory on that machine means lots of red on the build server and the IT director screaming WTF?!?!?

The lesson is, never make assumptions when accessing the file system.  In this case, the test was counting on the directory both existing and the user having permissions to it.  Obviously, that's not a good idea.

There are other ways to get to a valid "temporary" directory in .Net.  The following code sample shows how you can try a few known places in .Net that should work as "temporary" directories.

/// <summary>
/// Get a valid "temporary" directory on the machine that is running this code 
/// </summary>
/// <returns>a temporary directory</returns>
private string GetTemporaryDirectory() 
{ 
    // try this first 
    string dir = Path.GetTempPath(); 
    if ( String.IsNullOrEmpty(dir) || !Directory.Exists(dir) ) 
    { 
        // see if the "TEMP" environment variable is set 
        dir = Environment.GetEnvironmentVariable("TEMP"); 
        if ( String.IsNullOrEmpty(dir) || !Directory.Exists(dir) ) 
        { 
            // hmmm ... let's create one in "My Documents" 
            string myDocsDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 
            if ( String.IsNullOrEmpty(myDocsDir) || !Directory.Exists(myDocsDir) ) 
            { 
                // no "My Documents" directory??? 
                throw new Exception( 
                    "Cannot determine a valid temporary directory on this system. " + 
                    "Please set a valid directory for the \"TEMP\" environment variable."); 
            } 
            dir = String.Format("{0}\\Temp", myDocsDir); 
            if ( !Directory.Exists(dir) ) 
            { 
                Log.Info("Creating new Temp directory in {0}", myDocsDir); 
                Directory.CreateDirectory(dir); 
            }  
        } 
    } 
    if ( dir.EndsWith("\\") ) 
    { 
        // cut the last char off 
        dir = dir.Substring(0, dir.Length - 1); 
    } 
    return dir; 
}

The code example above tries to use the .Net libraries to query the file system for some well-known directories that can be used for temporary files.  If a valid one is not found, it will try to create a "Temp" directory in the current user's "My Documents" directory.  At worst, the user should have access to this directory, and the build should not break based on a hard-coded assumption.


Kick it on DotNetKicks.com
Friday, August 08, 2008 12:46:30 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | C#

 Tuesday, July 29, 2008
Is MS-Linux next???

Take a look at this little announcement that came out of OSCON last week...

http://port25.technet.com/archive/2008/07/25/oscon2008.aspx

Amazingly, Microsoft has agreed to join the Apache Software Foundation as a platinum sponsor.  Oh, in case you weren't aware, Microsoft has this little product called "IIS" that kind of directly competes against the open-source Apache web server.

Paradoxically, IIS would die to get the market share enjoyed by Apache, yet is neither free as in beer nor as in speech.  A fact that I imagine probably makes for a tough sell for the Microsoft marketing department.

The cynics are saying this is a bold move by Microsoft to help ease the sting caused by the PR fiasco known as "Windows Vista."

"Hey, look at us, you might think we suck and are inherently evil, but suddenly we love open source (well, not anything that is GPL'ed - but I guess that's just common sense)." 

I honestly don't know what to make of it.  I guess in the grand scheme of things, the $100,000 ponied up to join Apache can't even be considered a drop in the bucket for Microsoft.  As they said on TWiT this last weekend, "That just gets them on the mailing list."

Maybe it's like Sun-Tzu said (and later echoed by Michael Coreleone in Godfather II), "Keep your friends close, but your enemies even closer."


Kick it on DotNetKicks.com
Tuesday, July 29, 2008 10:01:31 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  .Net | Apache | IIS | Open Source

 Sunday, July 20, 2008
Atlanta alt.net user group meetup

The first(?) meeting of the Atlanta alt.net user group is going to take place this Wednesday at the Thinking Man's Tavern in Decatur (which is conveniently located fairly close to my house).  I have already RSVP''d.  If you want to come, sign up soon.  The web signup page says there are only 2 spots left.  Hope to see you there!


Kick it on DotNetKicks.com
Sunday, July 20, 2008 7:07:43 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  .Net | alt.net

 Saturday, July 19, 2008
Don't call virtual methods in a constructor

I ran into a piece of code today similar to this:

public class Base
{
    public Base()
    {
        this.Initialize();
    }

    protected virtual void Initialize()
    {
        Debug.WriteLine("Base.Initialize()");
    }
}

public class Derived : Base
{
    public Derived() : base() {}

    protected override void Initialize()
    {
        base.Initialize();
    }
}

public class FurtherDerived : Derived
{
    public FurtherDerived() : base() {}

    protected override void Initialize()
    {
        Debug.WriteLine("FurtherDerived.Initialize()");
    }
}

public class Tester
{
    public static void Main(string[] args)
    {
        Base myBase = new Base();

        Derived myDerived = new Derived();

        FurtherDerived myFurtherDerived = new FurtherDerived();

        Console.ReadLine();
    }
}

See any problems here?  Even though the compiler lets you call virtual methods from a base constructor, it's generally a "bad idea".  That's because the constructor in the derived classes defers its construction up to its base classes before it executes its own constructor (even if we don't explicitly call the base constructor like in the example).  Yet the call to a virtual function in the base class constructor is executed in the derived class implementation.  This can cause subtle, unexpected problems.

In the example above, things "happen" to go well.  It actually runs just fine.  It outputs the following as you'd probably expect:

Base.Initialize()
Base.Initialize()
FurtherDerived.Initialize()

But that's only because we didn't do anything significant in the derived constructors.  What happens if we change the FurtherDerived class:

public class FurtherDerived : Derived
{
    StringBuilder _sb;

    public FurtherDerived() : base()
    {
        _sb = new StringBuilder();
    }

    protected override void Initialize()
    {
       _sb.Append("FurtherDerived.Initialize()");
       Debug.WriteLine(_sb.ToString());
    }
}

Guess what happens when we run this code? FAIL!!! The dreaded, "Object reference not set to a reference of an object". Since the Initialize() method in the FurtherDerived class is called from the Base constructor, we are trying to access the _sb class level parameter before it's ever initialized.  We are calling a method on an class we know has not been fully constructed.  That ain't good.

The lesson is - never call a virtual method from a constructor.  At best, you are introducing a bug waiting to happen.  At worst, you've already done so.


Kick it on DotNetKicks.com
Friday, July 18, 2008 11:57:17 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Back To Basics | C#

 Monday, July 07, 2008
Presenting at MS Pros User Group Tonight

I will be presenting at the Atlanta Microsoft Professionals User Group meeting tonight with Alan Stevens.  The topic is Inversion Of Control, including a comparison of four of the leading .Net IoC Containers.  The meeting starts around 6pm, with our talk scheduled to begin around 7:30pm.

Location
Microsoft
1125 Sanctuary Pkwy
3rd Floor
Alpharetta, GA



View Larger Map


Kick it on DotNetKicks.com
Monday, July 07, 2008 7:11:58 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  .Net

 Friday, May 30, 2008
New release of Miado

This new release contains significant changes.  First and foremost, all the implementation classes have had their public scope removed, so you will now have to program exclusively against the interfaces.  I have also moved the IMiadoDao interface to IMiadoRepository in order to encourage composition and not force an inheritance hierarchy.  Combined with that change, I also moved the functionality from SimpleSql into IMiadoRepository, as well as making that interface the point where you access an IDbStatement, making the IMiadoRepository the main worker module of Miado.   Another change is that you need to use the MiadoRepositoryFactory to create an instance of the IMiadoRepository.

Enough with the talk, let's see some code...

public AdddressDao 
{
private static readonly string INSERT_ADDRESS_SQL =
"insert into Address(Address1, Address2, City, State, ZipCode) " +
"values(@Addr1, @Addr2, @City, @State, @ZipCode)";

private static readonly string SELECT_ADDRESS_SQL =
"select AddressId, Address1, Address2, City, " +
"State, ZipCode " +
"from Address ";

private static readonly string SELECT_ADDRESS_BY_ID =
SELECT_ADDRESS_SQL + "where AddressId = @Id ";

private static readonly string SELECT_ADDRESS_BY_ZIP_CODE =
SELECT_ADDRESS_SQL + "where ZipCode = @ZipCode ";

private static readonly string SELECT_COUNT_BY_STATE =
"select count(*) from Address where State = @State ";

// uses MiadoRepositoryFactory.CreateMiadoRepository()
public AddressDao()
: this(MiadoRepositoryFactory.CreateMiadoRepository(
SqlClientFactory.Instance,
ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString)) {}

public AdddressDao(IMiadoRepository repository)
{
this.MiadoRepository = repository;
}

protected IMiadoRepository MiadoRepository
{
get;
set;
}

public void SaveAddress(Address addr)
{
// uses SQL right in IMiadoRepository
this.MiadoRepository
.ExecuteNonQuery(INSERT_ADDRESS_SQL,
addr.Address1,
addr.Address2,
addr.City,
addr.State,
addr.ZipCode)
}

public ICollection<Address> FindAddressesByZipCode(string zipCode)
{
// build IDbStatement and do the mapping in a lambda expression
ICollection<Address> addresses =
this.MiadoRepository
.CreateDbStatement(SELECT_ADDRESS_BY_ZIP_CODE)
.AddParameter("ZipCode", zipCode)
.QueryForResults<Address>(
row => new Address()
{
AddressId = row.GetValue<int>("AddressId"),
Address1 = row.GetValue<string>("Address1"),
Address2 = row.GetValue<string>("Address2"),
City = row.GetValue<string>("City"),
State = row.GetValue<string>("State"),
ZipCode = row.GetValue<string>("ZipCode")
});
return addresses;
}

public Address LoadAddress(int addrId)
{
// uses delegate method to do the mapping
return
this.MiadoRepository
.CreateDbStatement(SELECT_ADDRESS_BY_ID)
.AddParameter("Id", addrId)
.QueryForOne<Address>(CreateAddress);
}

public int FindCountByState(string state)
{
return
this.MiadoRepository
.CreateDbStatement(SELECT_COUNT_BY_STATE)
.AddParameter("State", state)
.QueryForOne<int>(row => row.GetValue<int>(0));
}

private static Address CreateAddress(IResultSetRow row)
{
return
new Address()
{
AddressId = row.GetValue<int>("AddressId"),
Address1 = row.GetValue<string>("Address1"),
Address2 = row.GetValue<string>("Address2"),
City = row.GetValue<string>("City"),
State = row.GetValue<string>("State"),
ZipCode = row.GetValue<string>("ZipCode")
};
}

}

Kick it on DotNetKicks.com
Friday, May 30, 2008 10:57:03 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | C# | Miado

 Wednesday, May 21, 2008
Using LINQ to generate a random confirmation number

Igor Ostrovsky recently published a great blog post about 7 tricks for using LINQ to simplify your programs.  Posts like this really make me re-evaluate how I am writing my code in C# 3.0.  For example, I had written a piece of code for my current project that generates a random confirmation number for a reservation system.  After reading Igor's post, I built off one of his examples and refactored my code to use LINQ to build my confirmation number.  I must admit, the refactored code is much more elegant:

private static readonly char[] AVAILABLE_CHARS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890123456789".ToCharArray();

private static string GenerateConfirmationNumber(int length)
{
int lastIndex = AVAILABLE_CHARS.length - 1;
Random rand = new Random();
var confNbr =
Enumerable.Repeat<int>(0, length) // loop N times
.Select<int, int>(loopNbr => rand.Next(0, lastIndex)) // get a random index
.Select<int, char>(index => AVAILABLE_CHARS[index]) // pull a char
.ToArray(); // project the results to a char[]
return new String(confNbr);
}

I think it's important to remember that LINQ is much, much more than just LINQ-to-SQL (which is what most people immediately think of when you refer to LINQ).  In fact, none of the examples in Igor's post have anything to do with SQL.  Take a look at his post (and other LINQ examples online) and hopefully it will give you ideas on how to code using more of a dynamic language type syntax.


Kick it on DotNetKicks.com
Wednesday, May 21, 2008 9:42:57 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | C# | Linq

 Wednesday, May 14, 2008
C# Extension Methods

In my last post, I showed an example of how you can create an extension method on an existing class in javascript.  Well, C# 3.0 has now added the exact same functionality.  And it just so happens that today I needed to create one, so I thought I would post an example of how it's done in C#.

public static class StringExtensions 
{
public static byte[] ToByteArray(this string s)
{
return ASCIIEncoding.UTF8.GetBytes(s);
}
}

Extension methods act like static methods on existing classes, and as such they can only be declared in static classes. To mark a method as an extension method, you must preface the declaration of the first parameter in the method signature with the keyword "this". The compiler will then add the method to the type of class declared in the first parameter. Any other parameters declared after the first one will become the signature to the extension method.

Now we can call the extension method we added to the String class:

public class Program 
{
public static void Main(string[] args)
{
string myString = "Foo";
byte[] bytes = myString.ToByteArray();
}
}

The other cool thing is that Visual Studio provides full Intellisense on all extension methods!  So in the example I provided, ToByteArray() is now offered up as a potential method anytime I reference a string.


Kick it on DotNetKicks.com
Wednesday, May 14, 2008 12:43:26 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | C#

 Monday, May 12, 2008
Visual Studio 2008 and .Net 3.5 SP1 Beta Released

Microsoft announced today the release of the first public beta of Service Pack 1 for Visual Studio 2008 and the 3.5 version of the .Net framework.  Rather than an extended re-hash of what's included in the release, I'll defer to the experts:

Some of the highlights for me are:

  • Rails-like "Scaffolding" support via ASP.Net Dynamic Data (I need to play around with this and see if there's a need to get Miado to work with this)
  • ASP.Net AJAX script combining to reduce the number of requests to the server
  • ASP.Net AJAX back button support!
  • Improved Javascript intellisense and formatting
  • Support for ADO.Net Data Services (the project formerly known as Astoria), which aids in the creation of a data access layer using REST-ful web services

Since this is a *beta* version of a service pack, at this point I personally wouldn't install this in anything but a VM.


Kick it on DotNetKicks.com
Monday, May 12, 2008 4:45:45 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Visual Studio

 Saturday, May 03, 2008
Sort and Remove Unused Usings in Visual Studio 2008

When I first starting developing in .Net, I had been a Java programmer for many years.  I remember when I first started the transition, a long-time VB developer told me how much I was going to *love* Visual Studio.  It was as if programming Java in Eclipse was akin to living in the stone age and he had suddenly granted me the programming gift equivalent to fire.  "Here you go ... but use this power wisely.  With great power, comes great responsibility."  Hey, it's not like I was using vi on an terminal emulator!  (by the way, have you seen any old school guys program in vi (and still choose to do it)?  It's *scary* how fast they are.)

Anyway, it's 2004 and I start my era as a .Net developer using Visual Studio.  Dare I say, I actually begin to *miss* some things that were in Eclipse.

Example - In Java, you have "import" statements at the top of every class you write.  They are very similar to "using" declarations at the top of a C# class.  They basically tell the compiler what packages (i.e. namespaces in .Net) you need to compile the class.  Whereas in .Net you only can include an entire namespace, in Java you have the ability to import an entire package:

import java.util.*;

or individual classes within a package without having to import the entire package:

import java.util.Calendar;
import java.util.Date;
import java.util.List;

Flash back to circa 2002 or so.  I was working on a J2EE project with a team of developers.  Another developer and I were working on a couple of the same files.  After he checked a file in and I was going to work on it, I would do a diff on the file to see what he had changed.  I noticed every time he checked a file in, along with the changes he had made, he would rearrange the import statements.  Now, the usual ordering of imports in a java class are that all the java.* classes go first, then the javax.*, followed by any org.*, and finally your application classes last.  The project we were working on was for the state of Georgia, so some of our application packages started with gov.*.  Well, he would always move those imports above the java.* packages.  I would move them back to the bottom (where they actually belonged).  When he checked it back in, they would be right back at the top.  I thought to myself, "Man, this guy must be really anal to go through the effort of expanding out and ordering all the imports statements that way.  I wonder why."

One day I finally asked him about it.  "Why do you re-order the imports statements every time you check a file in and put the gov ones first?"  He looked at me with a puzzled look.  "Huh?"  Then he realized what was happening.  "Oh, I just hit Ctrl-Shift-O every time before I save a file to organize the imports."  And he showed it to me.  In Eclipse, you could use that keyboard shortcut (or access it through the menu) to automatically figure out your individual class imports and arrange them via a configuration of your choice (since he hadn't set up the gov ones in any order, it defaulted them to be first alphabetically).

Wow!  Pretty cool!  This was 6 years ago mind you.  So I got in the habit every time I saved a file: Ctrl-Shift-O, Ctrl-S ... Ctrl-Shift-O, Ctrl-S ... Ctrl-Shift-O, Ctrl-S.  I quickly became a "creature of habit".

Back to starting out in Visual Studio in 2004 ...  Let's see, I'd like to organize my using declarations.  Ok, Ctrl-Shift-O doesn't do that.  Hmm ... I wonder where that setting *is* in Visual Studio ...  Looks of looking, lots of googling ... Nothing.  Well, damn.  That kinda sucks.  You mean I actually have to manage this myself?!?!?  I think to myself, "Am I the only one out there who is wanting this sort of thing???"

Time passes, I am surviving by organizing my usings by hand (barely).  The more and more .Net blogs I read, I start hearing about people using and loving ReSharper.  Last year, after going solo and starting my own company, I finally decided to pull the trigger and buy myself a copy.  And boy, was I glad I did!  Along with a bunch of other great things, I notice that it let's you sort and remove unused usings.  "There it is, there it is!!!"  Ctrl-Alt-O!  Organize and remove usings!

Last year, Visual Studio 2008 comes out, but damn - ReSharper is not quite ready for it.  Well, work still needs to get done so I need to carry on, albeit without ReSharper for the time being.  I am playing around with Visual Studio 2008, and I notice a new menu option under Edit->Intellisense.  Whoa, what's this?  "Organize Usings".  I click on it, and lo and behold, there it is - three options: 1) Remove Unused Usings; 2) Sort Usings; 3) Remove and Sort.  Finally!!!

There is no native keyboard shortcut mapped to the "Remove and Sort".  Well, we can change that easily enough:

 

There, I've mapped Ctrl-Alt-O to Remove and Sort.  I'm back baby!  Ctrl-Alt-O, Ctrl-S!  Let's see it in action ...

Before:

And after:

The bottom line is - yes, Visual Studio is a great IDE.  But don't fool yourselves .Net developers.  Eclipse, IntelliJ, and even NetBeans (my preferred IDE for working in Ruby) are all very strong IDEs that in reality actually do some things (gasp!) *better* than Visual Studio.


Kick it on DotNetKicks.com
Saturday, May 03, 2008 2:52:09 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Eclipse | Java | ReSharper | Visual Studio

 Wednesday, April 30, 2008
Using Miado with Powershell

One of the nice things about Miado is that it wraps a lot of tedious, repetitive ADO.Net code and therefore greatly reduces the amount of code you actually do need to write. 

Here's a quick example.  One of the tasks I had to do at my last last gig was upload a set of prices from a CSV file every month.  I wrote a PowerShell script to use Miado to do the DB inserts:

  1. function BuildSql()   
  2. {   
  3.   # build the SQL   
  4.   $sb = New-Object System.Text.StringBuilder   
  5.   $sb.Append("insert into VendorPrice(VendorID, FixedPrice, VariablePrice, ");   
  6.   $sb.Append("CreationDate, LastUpdatedDate) ");   
  7.   $sb.Append("values(@VendorID, @FixedPrice, @VariablePrice, ");   
  8.   $sb.Append("current_timestamp, current_timestamp)");   
  9.     
  10.   return $sb.ToString();   
  11. }   
  12.   
  13. [Reflection.Assembly]::LoadFile("C:\dev\VS2008\Miado\src\Miado\bin\Release\Miado.dll")   
  14.   
  15. # setup the configuration   
  16. $connString = "Data Source=.\SQLEXPRESS;Initial Catalog=MyDatabase;User Id=user;Password=passw0rd"  
  17. $dbProvider = System.Data.SqlClient.SqlClientFactory::Instance;
  18. $repository = Miado.MiadoRepositoryFactory::CreateMiadoRepository($dbProvider, $connString);
  19.   
  20. $sql = BuildSql;   
  21.   
  22. foreach ( $row in Import-Csv prices.csv | Select VendorID, FixedPrice, VariablePrice )    
  23. {  
  24.   $repository.ExecuteNonQuery($sql.ToString(), $row.VendorID, $row.FixedPrice, $row.VariablePrice);     
  25. }  

As you can see, the script iterates over each row in the CSV file and inserts a record for each row.  There's no need to write all the code necessary to create the DbConnection and DbCommand objects, nor do you have to dynamically create DbParameter objects for each row.  Just pass the SQL and the variables (in order of replacement) into the IMiadoRepository.ExecuteNonQuery() call and Miado takes care of all the ugly details.  One line for each insert - that's it!

Edit: This post was updated to reflect the changes in the 0.7.10530.1


Kick it on DotNetKicks.com
Wednesday, April 30, 2008 11:38:38 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Miado | Powershell

 Wednesday, April 16, 2008
It's funny because it's true!

I just received this from Scott Hanselman's twitter feed (where he is attending the Microsoft MVP conference):

twitter: shanselman: "The UpdatePanel is like crack." - #mvp08

:-)


Kick it on DotNetKicks.com
Wednesday, April 16, 2008 12:37:53 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Ajax | ASP.Net | Conferences | Humor

 Monday, April 14, 2008
New Release of Miado out on CodePlex

I have uploaded a new version of Miado out on CodePlex.  I am still calling this a beta.  There are a few features I would like to add before I officially proclaim a 1.0 version (ability to use SqlServer-type syntax with an ODBC provider and integrated caching with the IDbStatement are two at the top of my list).

For this latest version, I have moved the DbProvider and vendor specific stuff to the Miado.Configuration namespace.  I have added an IParameterParser interface which is used in the SimpleSql class to determine the parameter name declarations in a SQL statement based on whether you are using the ODBC-type syntax or newer syntax for variable declaration. For example,

MyParam = ?
vs.
MyParam = @MyParam

This week I am going to try and come up with a good set of DAOs that use the AdventureWorks DB so people can see samples of how the API should be used.


Kick it on DotNetKicks.com
Monday, April 14, 2008 6:52:06 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Miado

 Thursday, April 10, 2008
Starting out with ASP.Net Ajax and the Ajax Control Toolkit

So only javascript gurus can make slick Ajax-enabled web pages, right? Wrong! Want to know the dirty little secret?  It's actually really easy!

If you are not using Ajax already on your ASP.Net pages, here's a great place to start.  It's always bothered me how on something as simple as paging and sorting on a GridView caused a full postback. Wrap that sucker in an UpdatePanel and you’ve instantly Ajax-enabled your page! By including the declaration ChildrenAsTriggers="true" (or not declaring it at all – it’s the default option), any postback event triggered in the UpdatePanel will automatically cause the page to partially re-render its contents. That’s it! No javascript needed. Well, actually there’s a ton of javascript involved – just none of it written by you. ;-)

First off, you need a couple of resources to get started. If you are using the 3.5 version of the framework, ASP.Net Ajax is already included by default. If you are using .Net 2.0, you will need to download the ASP.Net Ajax Extensions 1.0 (could they make it *any* more confusing?).

I am using the Ajax Control Toolkit to perform the animations during the partial post-back. The Ajax Control Toolkit has a nice set of tools to use to help you build rich web UIs, and as Clark Howard would say, "Hey, it's free!!!!" In the example below, I am using the UpdatePanelAnimationExtender to declaratively set a FadeOut animation to occur on the div container surrounding the UpdatePanel as the page posts back, and a FadeIn animation as it re-renders.

OK, so I lied. I am actually using a little javascript to dynamically show a spinning loading image centered on the grid during the postback.  But, again, the ASP.Net Ajax library to the rescue!  It makes our life a lot easier by providing all sorts of nice javascript shortcuts that are cross-browser compatible (like the Sys.UI.DomElement.getBounds() call I’m using).

Oh, you need to check out this site that will generate a custom loading image for you. Make sure you select a transparent background when you build your image.

Here is the code:

<!-- loading image is hidden by default -->
<img id="imgLoading" src="images/ajax-loader.gif" alt="Loading..." width="30" height="30"
style="display: none;" />
<div id="container">
<asp:UpdatePanel ID="updPnl" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:GridView ID="gvw" runat="server" CssClass="grid"
HeaderStyle-CssClass="header" AutoGenerateColumns="false" RowStyle-CssClass="odd"
AllowPaging="true" AllowSorting="true" AlternatingRowStyle-CssClass="even">
<Columns>
<asp:BoundField SortExpression="ID" HeaderText="ID" DataField="ID" />
<asp:BoundField SortExpression="Name" HeaderText="Name" DataField="Name" />
<asp:BoundField SortExpression="BirthDate"
HeaderText="Date Of Birth" DataField="BirthDate" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<ajaxToolkit:UpdatePanelAnimationExtender ID="animator" runat="server" TargetControlID="updPnl">
<Animations>
<OnUpdating>
<Sequence>
<!-- shows the loading image in the center of our grid -->
<ScriptAction Script="showInProcessImage($get('imgLoading'), $get('container'));" />
<Parallel duration=".10" Fps="30">
<FadeOut AnimationTarget="container" minimumOpacity="0" />
</Parallel>
</Sequence>
</OnUpdating>
<OnUpdated>
<Sequence>
<Parallel duration=".25" Fps="30">
<FadeIn AnimationTarget="container" minimumOpacity="0" />
</Parallel>
<!-- hides the loading image -->
<ScriptAction Script="hideInProcessImage($get('imgLoading'));" />
</Sequence>
</OnUpdated>
</Animations>
</ajaxToolkit:UpdatePanelAnimationExtender>

And the javascript:

<script language="javascript" type="text/javascript">

// show the image in the center of the container
function showInProcessImage(img, container) {
// get the bounds of both the container and the image
var containerBounds = Sys.UI.DomElement.getBounds(container);
var imgBounds = Sys.UI.DomElement.getBounds(img);

// figure out where to position the element (the center of the container)
var x = containerBounds.x +
Math.round(containerBounds.width / 2) - Math.round(imgBounds.width / 2);
var y = containerBounds.y +
Math.round(containerBounds.height / 2) - Math.round(imgBounds.height / 2);

// set the position of the in progress image
Sys.UI.DomElement.setLocation(img, x, y);

// finally un-hide it
img.style.display = '';
}

// hide the image
function hideInProcessImage(img) {
img.style.display = 'none';
}

</script>

I've left out the details of actually handling the paging and sorting events on the GridView.  I assume you are doing that already (or know how to do it).

One more thing to keep in mind - even though you are partially rendering the screen, you are still hitting the server (and your code-behind page).  On your partial post-backs, don't perform any extra work in the code-behind that's not going to be rendered in the update panel (e.g. hitting the DB, populating drop-down lists, setting headings, etc.). And don’t be fooled into thinking that Ajax-enabled web apps take a significant burden off the server.  If they are designed to be too "chatty", they can even make things worse!


Kick it on DotNetKicks.com
Thursday, April 10, 2008 9:42:23 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Ajax | Ajax Control Toolkit | ASP.Net

 Monday, April 07, 2008
Miado API Documentation

I have published the API documentation for Miado.  The IDbStatement and SimpleSql objects are the two main components of the API and both contain examples of how it should be used.

I have to give a shout out to the Sandcastle Help File Builder project on CodePlex.  It made my life 1000x better in using Sandcastle to generate the API documentation.


Kick it on DotNetKicks.com
Monday, April 07, 2008 7:07:02 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | API | Miado | Sandcastle

 Sunday, April 06, 2008
Miado is out on CodePlex

I have been refining some data access code that I have used on a bunch of my projects to the point where I've made it fairly generic.  I decided to publish it as a project on CodePlex.  I just put the initial release out today.  If you are interested, please take a moment to check it out and give me any feedback.  Keep in mind, I wrote this specifically for those people who have (or want) to use straight SQL and ADO.Net in their data access layer.  So if you want to use LINQ, Nhibernate, Subsonic, etc... they are absolutely great tools, but they try to hide/remove the SQL from your code, whereas this project just makes it much easier for those who use SQL.

Here is an example of how to use it to create a collection of custom business objects:

// ideally this declaration would be buried in your base DAO class
// or injected via an IoC container
IDbConfigurable dbConfig = new DbConfiguration(SqlClientFactory.Instance, connString);
IDbStatement dbStmt = new DbStatement(dbConfig);

ICollection<Address> addresses = 
    dbStmt.LoadSql("SELECT AddressId, Address1, Address2, City, State, ZipCode " + 
                   "FROM Address WHERE City = @City")
          .AddParameter("City", "Atlanta")
          .QueryForResults<Address>(
              row => new Address() 
                  {
                      AddressId = row.GetValue<int>("AddressId"), 
                      Address1 = row.GetValue<string>("Address1"),
                      Address2 = row.GetValue<string>("Address2"),
                      City = row.GetValue<string>("City"),
                      State = row.GetValue<string>("State"),
                      ZipCode = row.GetValue<string>("ZipCode")
                  });

Notice how it removes all the usual boiler plate code from a normal ADO.Net implementation.  The only things you really need to do are provide the SQL, set the parameters, and then map the result set to properties on your business object.  I'm using lambda expressions in these examples, but if you want to re-use the result set-to business object mappings, I normally create a method in my DAOs to use as a delegate:

ICollection<Address> addresses = 
dbStmt.LoadSql("SELECT AddressId, Address1, Address2, City, State, ZipCode " +
"FROM Address WHERE City = @City")
.AddParameter("City", "Atlanta")
.QueryForResults<Address>(CreateAddress);
...
private Address CreateAddress(IResultSetRow row)
{
// full details not provided
return new Address() { AddressId = row.AddressId };
}

If you embed the creation of the IDbStatement interface in a base class (or use the one provided in Miado.Integration), you can see how the code reads even more like a Domain-Specific-Language:

// CreateSqlStatment() method is provided in Miado.Integration.MiadoDao
ICollection<Product> products = 
    this.CreateSqlStatement("SELECT ProductId, Name, Description, Color, Quantity " +
                            "FROM Product WHERE Color = @Color and Quantity > @Qty")
        .AddParameter("Color", "Blue")
        .AddParameter("Qty", 20)
        .QueryForResults<Product>(
              row => new Product() 
                  {
                      ProductId = row.GetValue<int>("ProductId"), 
                      Name = row.GetValue<string>("Name"),
                      Description = row.GetValue<string>("Description"),
                      Color = row.GetValue<string>("Color"),
                      Quantity = row.GetValue<int>("Quantity")
                  });

There is also a SimpleSql object that can be used similar to IDbStatement but the syntax is a little more terse since you don't have to map the parameters - they are merely replaced in the order you provide them:

IDbConfigurable dbConfig = new DbConfiguration(SqlClientFactory.Instance, connString);
SimpleSql sql = new SimpleSql(dbConfig);
sql.ExecuteNonQuery("UPDATE Person SET FirstName = @FirstName, " + 
                    "LastName = @LastName " + 
                    "WHERE PersonId = @PersonId", 
                    "John", "Smith", 1001);
// again, I like to embed this in a base class so it reads:
// this.CreateSimpleSql().ExecuteNonQuery(sql, param1, param2);

For this first release, SimpleSql is not supported for ODBC SQL statements (since it uses pattern matching to substitute the SQL parameters).

Here's another example where you can see how easy it is to get a count:

int count = 
    this.CreateSimpleSql()
        .QueryForOne<int>("SELECT count(*) FROM Employee WHERE YearsOfService > @YearsOfSvc",
                           new object[] { 15 },
                           row => row.GetValue<int>(0));

And yes, it supports the creation of DataSets and DataTables:

DataSet ds = 
    this.CreateSimpleSql()
        .QueryForDataSet("SELECT * FROM ProductType WHERE Price > @Price", 10.0);

This is the first code drop, so treat it like a beta release.


Kick it on DotNetKicks.com
Sunday, April 06, 2008 9:35:57 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  .Net | Miado

 Tuesday, April 01, 2008
Atlanta Code Camp Recap
Overall, it was a good time.  Most of the sessions I attended were very informative.  I went to an "Sharepoint for ASP.Net Developers" session and was reminded how much I enjoy working on stuff other than Sharepoint.  ;-)  Shawn Wildermuth gave a couple of great sessions (expectedly) on Silverlight and Expression Blend.  It's hard *not* to be excited about Silverlight.  I just hope it can deliver on its promises.

I am always amazed to find so many people who are willing to give up a full day on Saturday to gather together for a geekfest code camp.  A special thanks goes out to the sponsors and organizers for putting this all together.  I am sure it is an absolute labor of love, because I can't believe how much time they must put into this event to make it so successful.

As an added bonus, I won a free pass to the devscovery conference put on by the folks at Wintellect.  Hoo-ray for me.  The conference looks pretty cool, but since hotel and airfare are *not* included, I am reminded of the Seinfeld episode where Jerry offers George "free" Super Bowl tickets - "So in order to use these, I gotta spend like fifteen-hundred bucks.  This is a bill for fifteen-hundred dollars." :-)


Kick it on DotNetKicks.com
Tuesday, April 01, 2008 1:08:10 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | ASP.Net | Conferences | Silverlight

 Wednesday, March 26, 2008
Changing a control's CSS class name during validation

So I'm converting an ASP.Net prototype that was written entirely in VB Script (don't ask) to C#.  As part of the conversion, I am putting in ASP.Net validation controls on all the input fields in the application.  I was showing off my progress to the graphics designer, and he pointed out that he wanted to dynamically change the CSS class on the input field control that was being validated if it failed validation.  Hmm, I can set the CssClass attribute on the validation control, but I couldn't find anywhere to automatically change the CSS class name on the actual control being validated.

I *could* write custom validators for each input control and change the class name in the javascript validation function, but that seemed like too much work.  So I thought to myself, surely there is some way to add an event listener to the DOM on the validation control to see if it changed it's display attribute.  After some researching, I got it to work.

<head runat="server">
    <title>Test Page</title>
    <style type="text/css">
      .error
      {
        border: solid 1px red;
        background-color: Yellow;
      }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <div>
            <asp:TextBox ID="txtBox" runat="server" />
            <asp:RequiredFieldValidator ID="reqField" runat="server" ControlToValidate="txtBox"
                Display="Dynamic" EnableClientScript="true" ErrorMessage="* Required"
SetFocusOnError="true" />
                <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
        </div>
        <script type="text/javascript" language="javascript">
    function pageLoad() {
        $addHandlers($get('<%= this.reqField.ClientID %>'),
                     { 'DOMAttrModified' : changeTextBoxClass,
'propertychange' : changeTextBoxClass });
    }
    function changeTextBoxClass(eventName) {
        $get('<%= this.txtBox.ClientID %>').className =
            $get('<%= this.reqField.ClientID %>').style.display != 'none' ? 'error' : '';
    }
        </script>
    </form>
</body>
</html>

DOMAttrModified is not supported in IE (shocking!!!) - onpropertychange is the IE equivalent.  Basically, whenever the ASP.Net validators fire and change the "display" attribute on their enclosing <span> tags, I added an event handler that will dynamically set the CSS class on the corresponding input control.  Notice in the example above that I'm using the ASP.Net Ajax library to make my life easier.

Before validation:

image

 

And after the "Submit" button is clicked:

image


Kick it on DotNetKicks.com
Wednesday, March 26, 2008 9:14:38 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Ajax | ASP.Net

 Saturday, March 22, 2008
Reminder! Atlanta Code Camp on 3/29

Just wanted to post a friendly reminder that the Atlanta Code Camp will be taking place at Devry Tech in Decatur next Saturday (3/29).  If you haven't done so already, register for the event to make sure you get a spot.

If you are going, the City of Decatur is sponsoring an electronics recycling event that very same day at Decatur High School.  The high school is just over a mile away from Devry.  I strongly encourage you to bring any outdated, left-over, unused, or otherwise useless old electronic equipment you have lying around for recycling.

Click on the map below for directions from Devry to Decatur HS.


View Larger Map
Kick it on DotNetKicks.com
Saturday, March 22, 2008 12:11:57 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Conferences