Corey Coogan

Python, .Net, C#, ASP.NET MVC, Architecture and Design

  • Subscribe

  • Archives

  • Blog Stats

    • 71,079 hits
  • Meta

Archive for the ‘C#’ Category

Using NHibernate from a Batch Program

Posted by coreycoogan on September 17, 2010


I use Batch Programs, aka Batch Jobs, all the time for tasks that aren’t necessarily time-critical. In most organizations, there are many of these things running on servers all over the place.   I recently had to write a batch job that did a bunch of database updates using NHibernate.  The job updates two tables in a foreach loop.  Within each loop, an NH transaction is started, committed or rolled back and disposed of.  I usually don’t write all my code into the default program.cs file, but opt for writing some service to do the heavy lifting.  I recently wrote one that had ran into some problems.

I wrote the service as I usually would.  I setup my constructor to take everything it would need and made a StructureMap registry to bootstrap all my dependencies so I could work with the existing components.

Here’s my original batch service constructor:

public ProfileUpdateService(
ISession session, //for managing transactions
IProfileRepository repo //for getting/saving
)
{
    //set private vars
}

My StructureMap registry was pretty basic.  It takes an ISessionFactory instance in the constructor and uses it to setup the ISession resolution.  The repository happens with a scanner’s default conventions:

For<ISession>()
   .Use(() => _sessionFactory.OpenSession()); //use the lambda to ensure my factory is configured when this is actually accessed

Here’s what my original code looked like (sort of):

var records = _repo.GetAll();

if(!records .Any())
    return;

try
{

    foreach (var record in records)
    {

        try
        {
           
            _transaction = _session.BeginTransaction();
           
            var otherRecord = _repo.GetOtherThing(record.Something);
 
            //do some processing first then save
            _repo.DoFirstThing(record);
            
           //do some processing first, then save
            _repo.DoSecondThing(otherRecord);

            _transaction.Commit();
        }
        catch(Exception ex)
        {
            //log it
            //rollback
            _transaction.Rollback();
        }
        finally
        {
            if(_transaction != null)
                _transaction.Dispose();
        }
    }
    
}
finally
{
    _session.Dispose();
}

During testing, some edge cases emerged that caused an exception while committing my changes.  Since my use of NHibernate has followed the Session/Request pattern in web and WCF environments, I never really had to deal with exceptions and their impact on the NHibernate Session.  But this case was different.  There was no single Request to contain my Unit of Work and I soon found out that the exception being thrown was hosing up my Session.  RTFM, right Corey?

Here’s what the NH reference doc has to say about it:

If the ISession throws an exception you should immediately rollback the transaction, call ISession.Close()
and discard the ISession instance. Certain methods of ISession will not leave the session in a consistent state.

I had to make some obvious changes.  My batch service needs to be able to create an instance of an ISession and since my repository class takes an ISession in its constructor, I need to be able to create a new IProfileRepository instance as well.  Since I wanted to maintain testability, I used the mighty Func<> as a factory.

Here’s what my constructor looks like now:

public ProfileUpdateService(
ISessionFactory sessionFactory,
Func<ISession,IProfileRepository> repoFactory
)
{
    //set private vars
}

Now I had to change StructureMap to know how to resolve those dependencies.  Using the Lambda in the Use() method gives me deferred execution, so I don’t have to worry about premature invocation of my ISessionFactory.

For<ISessionFactory>()
                .Use(() => _factory);

For<Func<ISession, IProfileRepository>>()
                .Use((session) => new ProfileRepository(session));

Finally, I had to restructure the code to better handle the exceptions.  When one happens, I want to close and dispose of the ISession instance being used.  I would also want to use a new Repository object since the current one will be using the damaged ISession object.  To handle this, I relied on properties and lazy initialization.  (note: this code may not be the most efficient, but it’s a batch job after all, so give me a break)

//use the lazy initialized repo
var records = ProfileRepository.GetAll();

if(!records .Any())
    return;

try
{

    foreach (var record in records)
    {

        try
        {
          
            _transaction = Session.BeginTransaction();
           
            var otherRecord = ProfileRepository.GetOtherThing(record.Something);
 
            //do some processing first then save
            ProfileRepository.DoFirstThing(record);
            
           //do some processing first, then save
            ProfileRepository.DoSecondThing(otherRecord);

            _transaction.Commit();

        }
        catch(Exception ex)
        {
            //log it
            //rollback
            _transaction.Rollback();
            
            _session.Dispose();
            _session = null;
            _profileRepository = null;
        }
        finally
        {
            if(_transaction != null)
                _transaction.Dispose();
        }
    }
   
}
finally
{
    _session.Dispose();
}


//Using lazy initialization so I don't have to worry about these being destroyed
IProfileRepository ProfileRepository 
{
    get
    {
        if (_profileRepository == null)
            _profileRepository = _profileRepositoryFactory(Session);

        return _profileRepository;
    }
}

ISession Session
{
    get
    {
        if (_session == null)
            _session = _sessionFactory.OpenSession();

        return _session;
    }
}   

This really isn’t rocket science, but it’s a different way of thinking for those of us using NHibernate from the Web.

Posted in C#, IoC, NHibernate, StructureMap | Tagged: , , , , | Leave a Comment »

Initializing NHProf in MSTest

Posted by coreycoogan on September 4, 2010


Alternate title for this post could be Running initialization code before an MSTest Test Run

I’m not at all a fan of MSTest for various reasons. My preference is NUnit, however xUnit, mbUnit or any other framework is just as well. There are often cases when a client wants to use MSTest, usually for its Visual Studio integration. This is a compelling argument for a shop new TDD or unit testing, that wants the least amount of friction and doesn’t want to invest in TestDriven.Net or R#.

Integration tests written with MSTest are a great place to profile your NHibernate data access and catch any gotchas early in the development cycle. When the client is willing to pay for it, there’s no better tool than Ayende’s NHProf for this. NHProf can be easily initialized in code, but this should be done only once per test run, as you would bootstrap NHibernate itself only once. This led me on a search in MSTest for how to initialize once per test run. There’s widely known attributes for executing setup code when a test class fires and also whenever a test fires, but the answer to my requirement was found in the lesser known [AssemblyInitialize] attribute.

Just throw that attribute on a static void method that takes a TestContext argument and it will execute once before each test run. The class that houses the initialization method must also be decorated with the [TestClass] attribute.

[TestClass]
    public class AssemblyInit
    {
   
        [AssemblyInitialize]
        public static void Init(TestContext testContext)
        {
             HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
        }
    }

Posted in Architecture and Design, C#, NHibernate, TDD | Tagged: , , | Leave a Comment »

The Singleton and Composition/Testability

Posted by coreycoogan on September 3, 2010


I read this post from Kellabyte which got me thinking about solutions I’ve used in the past.  There’s ways to live with Singletons, at least from a composition and testability standpoint.  This can come in especially handy when working with a legacy code base.

The first thing, is that your property/method that returns the instance of the Singleton should return an interface, not a concrete.

public static ILog Instance
{
     get{ return _logger;}
}

I assume when talking about composition, we are all using an IoC container of some kind.  My favorite is StructureMap.  Most containers have the ability to configure a type resolution through a factory method.

In SM, it might look like this:

ForSingletonOf<ILog>()
.Use(() => Logger.Instance)

Now any requests from your container that require an ILog instance can come from the Singleton in production, but resolve to a mock or anything else in test scenarios.

//example of Dependency Injection via constructor
public class SoSomethingService(ISomethingRepository repo, ILog logger)
{
//set to instance vars
}

Posted in C#, Design Patterns, IoC, StructureMap | Tagged: , | 1 Comment »

Using StructureMap to Configure Applications and Components

Posted by coreycoogan on May 24, 2010


By now it’s probably a pretty safe assumption that any developer who’s worth their salt has at least heard of Inversion of Control (IoC) or Dependency Injection (DI), if not used it at least once. IoC as an architectural concept has many benefits, including testability and helping with Open/Closed Principle compliance. The specifics of DI have been discussed many times over, so consult your friendly neighborhood Google for more on the topic. What I’d like to talk about is the tooling that helps developers achieve IoC in their own systems. The tool is known as a Container and there are many good options to choose from in the .NET space. Top picks include Castle, StructureMap (SM), AutoFac, Ninject and even the very sad entry from Microsoft – Unity.

Why StructureMap?

I’ve had to use Unity at a current gig because it was approved and didn’t require .NET 3.5, but I’ll say right off that Unity is a very simple Container that lacks the features that make working with a Container fun. Granted, we’re using version 1.1, so I can’t speak to some of the enhancements found in 2.0.

I’ve blogged about Castle in the past, which I was using because it came standard in the S#arpArchitecture. Castle is a very good Container, but it has its downfalls. The biggest, in my opinion, is that its fluency is not very intuitive. Despite how many times I’ve used it, I can’t configure an application without looking at a previous example. It just doesn’t seem to flow and feels a bit clunky. It’s still a great tool, so I don’t want to take anything away from all the hard work that has gone into it.

Then there’s StructureMap. What can I say – SM rocks and I actually have fun using it. The fluent DSL flows easily and it is capable of doing everything I’ve ever really wanted it to. Some of my favorite, and most used features, include the default convention, the ease of adding custom conventions, registering open generics and showing what’s been configured. If you haven’t worked with it, have a look and play around with it. Like anything, it will take a bit to learn the ins and outs, but after that it’s pure joy. (NOTE: some of the doc I’m linking to is a bit out of date – the only downside to SM, however, there is plenty on CodeBetter)

Define Components

It is common practice to break different layers into separate components/assemblies/VisualStudio.Net Projects, such as Core, Data, Infrastructure, etc. It is also very common to have components shared throughout the enterprise, such as Inventory, SalesProcessing, Products, etc. This is what I’m referring to as components. Since each component may have its own unique DI requirements, configuring applications to initialize each of those components, as well as itself, can become challenging and when done incorrectly can make applications brittle.

Configuring the Application

The application, in the context of this post, refers to the actual executable – web site, Windows Form, WPF, Console, Windows Service, WCF. When using an IoC Container, the application should always have the responsibility of configuring and initializing the Container. It’s not uncommon to see some developers configuring a Container at the component level because that’s where the knowledge of the component’s dependencies exists. How would the application know about special conventions or nuances that the Container should be handling? The problem with this is the case where the application wants to leverage the Container and swap out one dependency for another.

Equally as painful is the practice of configuring all the components directly from the application. Once a developer gets everything working, the configuration is typically copied/pasted to other applications that use the same components. Now when something changes, someone has the joy of [hopefully] finding all the occurrences of the code in question and pasting a new version on top of it.

Configuring Components

So we don’t want the components to configure themselves in the Container and we don’t want to copy/paste the component configuration in all the consuming applications. How do we do it then? Well I’m glad you asked. The answer is found in StructureMap’s Registry facility.

A Registry in SM is a custom class, derived from the StructureMap.Configuration.DSL.Registry class. This is where the nuts and bolts of an SM configuration should exist. A component can have one or more registries, broken down into any sized unit that makes sense. Maybe the Inventory application has a registry for some common domain services and another for specific communication mechanisms that may vary depending on the type of application.

Here’s an example of a simple component Registry that has a couple specific needs and then relies on scanning and default conventions for the rest.


public class ProfileRegistry : Registry
{
	public ProfileRegistry()
	{
	    ForSingletonOf<IProfileValidator>()
		.Use<ProfileValidator>();

	    Scan(scanner =>
		     {
			 scanner.AssemblyContainingType<IProfileRepository>();

			 //use the default convention
			 scanner.WithDefaultConventions();

		     });
	}
}

Initializing the Application

Now that our components have their own default configurations broken into one or more Registry classes, we need to get that into our Container. As previously mentioned, it is the responsibility of the application to configure and initialize the Container. This is something we generally want to happen only once. This can be accomplished by putting the code to handle the initialization of SM, NHibernate, Logging, whatever, in a BootStrapper that gets called at the application’s entry point. This can be the Global.Application_Start in a web application or inside the Program class of a console or WinForm application.

Initializing Component Registries

So how does the BootStrapper initialize SM with each component registry? With StructureMap, there are actually three common techniques.

By Type

This technique is pretty straight forward and probably suits the majority of cases. In this example, we know what the Registries are and simply add them by type to SM’s configuration during initialization.


public static class Bootstrapper
{
	public static void Initialize()
	{

		ObjectFactory.Initialize(cfg =>
		{
		    cfg.AddRegistry<ProfileRegistry>();
		});

	}
}

By Instance

SM also offers the ability to add a registry to the SM configuration as an instance. This comes in very handy when you have a Registry that requires an instance of some type for its own configuration.

A real-life example of this is when using an NHibernate Session/Call pattern in a StructureMap enabled WCF service (details available in this post). In this case, I want the Wcf.NHibernate registry to tell SM how it should resolve an ISession. In order for this to happen, the Registry will need an initialized ISessionFactory instance, which will be passed to it by the application’s BootStrapper. Once the registry is instantiated, just add it to the SM’s configuration.


public static class Bootstrapper
{
	public static void Initialize()
	{
		ObjectFactory.Initialize(cfg =>
		{
		    cfg.AddRegistry<ProfileRegistry>();

			//get the sessionfactory from another method
		    ISessionFactory sessionFactory = InitFactory();

		    //create the WCF NH Registry
		    var nhWcfRegistry = new WcfNHibernateRegistry(sessionFactory);

			//add the Registry as an instance
		    cfg.AddRegistry(nhWcfRegistry);
		});
	}
}

By Scanning

Last but least, SM Registries can be added to the configuration via scanning. I really like SM’s ability to scan the types specified and apply common and custom conventions for type registration. I won’t go into details here, as the documentation is pretty good in this area.

During a scan, SM can be told to look for all Registry implementations and automatically add them to the configuration using the IAssemblyScanner.LookForRegistries() method. This can come in handy if you are scanning your components from your application. If you have a large number of components, it may be tempting to scan all the application’s assemblies and find registries, but be warned that this can make for a very long startup when you consider the number of types in your third party assemblies, like Log4Net, NHibernate, Castle, etc. Of course, you can always apply a convention to limit which components get scanned, but it’s definitely something to be aware of. Just put some thought into your use of IAssemblyScanner.AssembliesFromApplicationBaseDirectory() and IAssemblyScanner. AssembliesFromPath(path:string).


Scan(scanner =>
{
	 //include this
	scanner.TheCallingAssembly();

	//include the Data component
	scanner.AssemblyContainingType<IProfileRepository>();

	//include all the registries
	scanner.LookForRegistries();

});

Conclusion

Using Dependency Injection/IoC is a great way to build loosely coupled, composeable applications. An IoC Container is a tool that is used to tell your application how it should compose your types by defining the “what” and the “how” of your application’s dependency resolution. StructureMap is one of many available choices of IoC Containers for .NET, but its rich feature set and intuitive fluent DSL have put it at the top of my list.

Many examples and tutorials for StructureMap show how to configure a trivial application where all the types exist within the application or from application specific components. When dealing with components that are shared across the enterprise, it is important to give every consuming application a way to configure SM with their default configuration without copying the code into every application’s startup and without putting the configuration decisions solely in the hands of the component. This can be achieved through the use of the StructureMap Registry, which can be defined as coarse or granular as required at the co

Posted in Alt.Net, Architecture and Design, ASP.NET MVC, C#, IoC, NHibernate, StructureMap, TDD, Uncategorized | Tagged: , , , , , | 2 Comments »

ReSharper Coupon Code and Extended Trial

Posted by coreycoogan on February 21, 2010


UPDATE 6/1/2010:  I recently got an email from David Ridgway stating that the offer discussed in this post is no longer valid.  Sorry :(

I’ve been using the trial version of R#, but recently expired.  I’ve grown quite used to it and thought it to be a worthwhile business expense.  Because I’m cheap and figure there’s always a better deal, I immediately started searching for a promo code when I saw the “Coupon Code” field on the checkout form.

That brought me to David Ridgway’s blog, where he has a post about how to get 10% off and an extended 60 day trial license key.  The blog says to email him and he’ll send the info.

If you’re like me, this sounds a bit fishy and I was apprehensive to try, but the blog looked legit so I gave it a shot.  To my surprise, I received a response within 10 minutes at 1:30 AM.  The details were there and they are right on.

If you are thinking about buying or trying ReSharper 4.5, definitely send David an email and ask him for the scoop.  You’ll save some cash or get the longer trial (or both).

http://web2asp.net/2009/01/resharper-extended-trial-period-and.html

Posted in C#, Visual Studio | Tagged: , , , , | Leave a Comment »

Showing Strong Named Internal Classes to Rhino Mocks

Posted by coreycoogan on December 5, 2009


Other possible titles include:

Rhino Mocks 3.5 Public Key, Rhino Mocks 3.6 Public Key, Rhino Mocks Strong Named Mocking

When you design your code to be testable with a mocking framework like Rhino Mocks, you typically end up marking otherwise private classes as Internal.  This allows you to share your internal classes with test project[s].  To do this, you have to use the InternalVisibleTo assembly attribute in the AssemblyInfo class that you want to share.

[assembly: InternalsVisibleTo(“S2sol.ProjectA.TestProject”)]

This attribute is essentially doing what it says, “Make my stuff that is marked internal visible to the specified class”.  When the project under test is strongly named, for whatever reason, it is also required that you put the public key (not the public key token) of the test project in there with the assembly name.  This to ensure that the internals that are being exposed are only exposed to an assembly that is known.

Rhino Mocks uses Castle’s Dynamic Proxy for mocking.  It creates classes at runtime to act as proxies, or interceptors, whenever you create a mock or stub using MockRepository.Create…  This means that the project under test must verify the dynamic proxy class via the InternalVisibleTo attribute, which means we’ll need the PublicKey for the dynamic assembly. 

I found this somewhere on the web over a year ago and took it for granted until I needed it again today.  After I hunted in some of my old code and found it, seemed like a great post that will surely help someone else out there.  So when you are in this scenario, using Rhino 3.5/3.6, add this to the AssemblyInfo of the component you want to test and you will be good to go:

NOTE: breaks in the public key are intentional for rendering.  It works like this or if the key is one line.

  
//required for Rhino Mocks  
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=00240000048000009"+     
"40000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f" +   
"3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cd" +    
"cf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74" +     
"c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]  

Posted in Alt.Net, C#, Rhino Mocks, TDD | Tagged: , , , , , , | Leave a Comment »

Partial Methods on Partial Classes

Posted by coreycoogan on June 9, 2009


Here’s something I learned recently while reading Professional ASP.NET 1.0 – not only are there partial classes, but also partial methods.

I can’t believe this feature has been around as long as partial classes and I haven’t heard about it until now [UPDATE 7/10/2009: Thanks to Scott Mitchell's Comment, where he pointed out that this actually came with the 3.5 Framework].  I must have read 25 blog posts and articles when partial classes were being introduced talking about how cool they were and none of them ever mentioned the awesomeness of partial methods.

Until now, when I wanted to define a method on one side of a generated class and let it be implemented on another, I would create a base class and add a virtual method to be overridden, such as the example below.  Partial methods are private, so this approach still has merit when true inheritance is required.

Old Way

//My generated class
public partial class DataMapper : DataMapperBase
{
     public void Map()
     {
          //foreach loop or something

         //now do custom mapping
         MapCustom();
     }
}

//my custom partial class
public partial class DataMapper
{
     protected override void MapCustom()
     {
         //do custom mapping
     }
}

//generated base class
public abstract class DataMapperBase
{
     protected virtual void MapCustom(){}
}

As I said, this works, but it’s ugly. Now here’s what it looks like with partial methods:

With Partial Methods

//My generated class
public partial class DataMapper
{
     public void Map()
     {
          //foreach loop or something

         //now do custom mapping
         MapCustom();
     }

     //define the partial method
     partial void MapCustom();
}

//my custom partial class
public partial class DataMapper
{
     //implement the partial method
     partial void MapCustom()
     {
         //do custom mapping
     }
}

How do partial methods work you ask? If a partial method gets implemented by any of the other partials, it’s compiled and all is good. If it is not implemented, the compiler removes the method definition, as well as all calls to it, as though it was never there. More details are available on the MSDN site.

There are some limitations, so here’s the rules (from MSDN):

  • Partial method declarations must begin with the contextual keyword partial and the method must return void.
  • Partial methods can have ref but not out parameters.
  • Partial methods are implicitly private, and therefore they cannot be virtual.
  • Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.
  • Partial methods can have static and unsafe modifiers.
  • Partial methods can be generic. Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one. Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one.
  • You can make a delegate to a partial method that has been defined and implemented, but not to a partial method that has only been defined.

Posted in C# | Tagged: , | 2 Comments »

 
Follow

Get every new post delivered to your Inbox.