dotNetChris @ Marisic.Net

April 4, 2010

Definitive guide to object pooling with C# in .NET 3.5

Filed under: Architecture, Programming — dotnetchris @ 12:12 am

Recently I had considerations of needing to implement an object pool in my application and I know concurrency issues are one of the most insidious and complex issues to overcome correctly in programming regardless of language. Understanding this I knew I’d be better offer finding a very defined example that handles the concurrency issues of an object pool and defer to a source that has more experience with concurrency and use their information as a starting point for my specific needs. Normally this works great however in this situation I found very little relevant information on Google for this problem. It’s possible my Google-fu just wasn’t on point for finding the most relevant articles but almost all information I found had the very threading issues I was concerned about as part of their example (ie they just ignored it or weren’t aware of it).

This lead me to query the knowledge base of developers on StackOverflow which didn’t add much to my equation at the start however I instituted a bounty over this question and got one of the most complete answers I’ve ever seen in response to a question that addresses basically every single need required of an object pool correctly. Read over all of the great information I got on this topic at C# Object Pooling Pattern implementation

March 15, 2010

Creating a common generic and extensible NHiberate Repository version 2

This is a follow up to my original post on this topic Creating a common generic and extensible NHiberate Repository and further progression of it taking advantage of DetachedCriterias and Future queries.

I’m going to start with my interface as a jumping off point.

public interface IRepository<T>
{
    /// <summary>
    /// Adds the specified <see cref="T"/>.
    /// </summary>
    /// <param name="obj">The obj.</param>
    void Add(T obj);

    /// <summary>
    /// Deletes the specified <see cref="T"/>.
    /// </summary>
    /// <param name="obj">The obj.</param>
    void Delete(T obj);

    /// <summary>
    /// Defers the detached crteria execution which will return a result set that is an  <see cref="IEnumerable{T}"/>.
    /// </summary>
    /// <param name="detachedCriteria">The detached criteria.</param>
    /// <returns></returns>
    IEnumerable<T> FutureList(DetachedCriteria detachedCriteria);

    /// <summary>
    /// Executes the detached crteria immediately returning a single item <see cref="T"/>
    /// This will also cause the execution of any defered queries to be executed.
    /// </summary>
    /// <param name="detachedCriteria">The detached criteria.</param>
    /// <returns></returns>
    T FutureSingle(DetachedCriteria detachedCriteria);

    /// <summary>
    /// Gets the specified <see cref="T"/>.
    /// </summary>
    /// <typeparam name="U"></typeparam>
    /// <param name="id">The id.</param>
    /// <returns></returns>
    T Get<U>(U id);

    /// <summary>
    /// Executes the detached crteria immediately returning a result set that is an  <see cref="IList{T}"/>.
    /// This will also cause the execution of any defered queries to be executed.
    /// </summary>
    /// <param name="detachedCriteria">The detached criteria.</param>
    /// <returns></returns>
    IList<T> QueryList(DetachedCriteria detachedCriteria);

    /// <summary>
    /// Executes the detached crteria immediately returning a single item <see cref="T"/>
    /// </summary>
    /// <param name="detachedCriteria">The detached criteria.</param>
    /// <returns></returns>
    T QuerySingle(DetachedCriteria detachedCriteria);

    /// <summary>
    /// Inserts or updates the specified <see cref="T"/>.
    /// </summary>
    /// <param name="obj">The obj.</param>
    void SaveOrUpdate(T obj);

    /// <summary>
    /// Updates the specified <see cref="T"/>.
    /// </summary>
    /// <param name="obj">The obj.</param>
    void Update(T obj);
}

I think my interface is very well defined and with the XMLDoc comments easy to follow what will be implemented. The most notable changes from my original post is the removal of the GetAll and GetRange methods that returned an ICriteria, these always felt like a kludge to me as they clearly bleed concern by allowing the raw ICriteria to be exposed however back then I didn’t have the tools and knowledge available to create a better solution.

The new methods are related to the DetachedCriterias QuerySingle, QueryList and to the Future based queries FutureSingle and FutureList. Future is a newer construct in NHibernate that allows you to specify a query that you want NHibernate to understand and know at some point in the Future it will need this execution so you can batch more than 1 query together and reduce the number of calls to a database. This is a great bonus as the database is usually always the biggest slow down in an application.

On to the actual implementation of the interface

public class Repository<T> : IRepository<T>
{
    private readonly IBusinessConversation _conversation;

    public Repository(IBusinessConversation conversation)
    {
        _conversation = conversation;
    }

    IList<T> IRepository<T>.QueryList(DetachedCriteria detachedCriteria)
    {
        return detachedCriteria.GetExecutableCriteria(_conversation.Session).List<T>();
    }

    T IRepository<T>.QuerySingle(DetachedCriteria detachedCriteria)
    {
        return detachedCriteria.GetExecutableCriteria(_conversation.Session).UniqueResult<T>();
    }

    T IRepository<T>.FutureSingle(DetachedCriteria detachedCriteria)
    {
        return detachedCriteria.GetExecutableCriteria(_conversation.Session).FutureValue<T>().Value;
    }

    IEnumerable<T> IRepository<T>.FutureList(DetachedCriteria detachedCriteria)
    {
        return detachedCriteria.GetExecutableCriteria(_conversation.Session).Future<T>();
    }

    T IRepository<T>.Get<U>(U id)
    {
        return _conversation.Session.Get<T>(id);
    }

    void IRepository<T>.SaveOrUpdate(T obj)
    {
        _conversation.Session.SaveOrUpdate(obj);
    }

    void IRepository<T>.Add(T obj)
    {
        _conversation.Session.Save(obj);
    }

    void IRepository<T>.Update(T obj)
    {
        _conversation.Session.Update(obj);
    }

    void IRepository<T>.Delete(T businessObj)
    {
        _conversation.Session.Delete(businessObj);
    }
}

The one that might be confusing is the _conversation dependency this relates to another post Implementing NHibernate Long Conversation with no HttpModules or AOP build time weaving. You can take a look at this if you haven’t and are curious however it’s not needed to understand my code here as you can really view _conversation to be the raw NHibernate ISession and understand what is going on here.

This class houses the generic CRUD operations that are made generic to allow you to handle any custom object easily. The methods that are once again of interest are the ones I discussed as new additions to my Repository. The beauty of all them regardless is in their simplicity that they can all be written in 1 concise line yet offer immense flexibility.

With the QuerySingle and QueryList methods these allow you to take in a DetachedCriteria and get back either a single object or a IList collection which should be pretty self explanatory from both the code and method names.

The FutureList and FutureSingle are not so much as obvious. As I stated before these allow you to make these happen in the future. In my implementation only the FutureList will really allow you to relegate multiple events into the future but it also makes the most sense since individual lookups are frequently done by indexed columns that should be quick even done in multiple seperate calls. For each call you make to FutureList it will have NHibernate queue up the specified DetachedQuery and wait for one of the following either code causes any of IEnumerables returned to be enumerated which will fire off 1 mulit-query to get all of the result sets or you call FutureSingle.

FutureSingle is some what of a more unusual animal because a regular object doesn’t have the lazy access method that IEnumerables do either it exists, or it doesn’t. There is no transient stage as there is with IEnumerables. To overcome this fact the developers of NHibernate created this transient stage by wrapping object with a generic interface for IFutureValue<T> this gives a construct to have a 3rd stage that you need to call .Value to invoke the actual execution which will process all future queries. In my repository I actually call .Value immediately on a DetachedCriteria being passed into this, why? Because I’d need to return a IFutureValue<T> instead of just T as the result from the method. This in my opinion would be just as much of a kludge as returning ICriteria was from my previous implementation as it bleeds NHibernate understanding logic outside of the repository. This purely a subjective point and if you disagree with my sentiment you could easily return IFutureValue<T> and have a wider range of flexibility with the Future support.

Now on to actual usage of this in a real world scenario. I am going to be taking advantage of a framework I recently learned about called NHibernate Lambda Expressions this allows you to write Criteria and DetachedCriteria queries without the need to rely on magic strings. The point of this post won’t be to cover the usage of this as it should be mostly understandable for my example.

 public class DataProvider : IDataProvider
{
 private readonly IRepository<Person> _personRepository;

 public DataProvider(IRepository<Person> personRepository)
    {
        _personRepository = personRepository;
    }

    public IList<Person> GetPersons(State state)
    {
        var query = DetachedCriteria.For<Person>()
            .CreateCriteria<Person>(x => x.PrimaryZip)
            .CreateCriteria<Zip>(x => x.State)
            .Add<State>(x => x.StateCode == state.StateCode);

        return _personRepository.FutureList(query);
    }

    public Person GetPerson(Guid personID)
    {
        return _personRepository.Get(personID);
    }
}

If you look at my GetPersons method you should see I have a somewhat deep object graph that is realistic, I have a collection of Persons in my database where I assign them a zip code object that contains among other things the zip code and the state that zip code lives in. I create a DetachedCriteria that lets me find all persons that exist in a state and I pass that down to my generic IRepository by delegation instead of inheritance. Many examples similar to my post use inheritance where you will inherit from Repository<Person> instead of having a delegate inside of a non generic class I feel this is the wrong way because it then limits you to having 1 repository per data object instead of being able to drop multiple IRepositorys inside of a single DataProvider.

Taking this a step further I can even remove the need to ever create a physical implementation of Repository<Person> through the use of an inversion of control / dependency injection framework in this case specifically StructureMap. In literally 1 line I can create an infinite amount of IRepositories for any application I need.

For(typeof (IRepository<>)).LifecycleIs(new HybridLifecycle()).Use(typeof (Repository<>));

This instructs StructureMap that anytime I need a IRepository<Person> or any other data object that it’s to give it a usage of Repository
completely absolving me of the responsibility of defining a Repository<Person> combining the functionality I’ve outlined in this post it offers a broad range of usage that allows you to interact with NHibernate without ever needing to write a single line of code again except the specific DetachedCriterias which will need written in one shape or form irregardless because they will have custom sql be the end result of them and to just wire up Methods to allow access to the underlying CRUD methods. You could actually expose the generic methods themselves however I feel that is exposing too much logic to be available to an API and prefer to shroud my generic repositories in the classes I call DataProviders as it also lets me group repositories in meaningful ways.

kick it on DotNetKicks.com

Shout it

BloggingContext.ApplicationInstance.CompleteRequest();

January 28, 2010

Making text proper case in SSIS 2008 with a script component

Filed under: Sql Server — Tags: , — dotnetchris @ 1:59 pm

Drop a new script component on your dataflow task and wire up the input to it. Select the input column that you want to be proper cased. Also set an output column that you will want the correctly cased text to flow from (or you could set it up to alter your input column if you wanted)

After that edit your script so the script editor opens up, the first thing you need to do is right click on the references folder on the right and goto add reference and under the .NET tab pick Microsoft.VisualBasic. Then your code should look similar to

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using Microsoft.VisualBasic;
using System.Globalization;

[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        Row.Name = Strings.StrConv(Row.County, VbStrConv.ProperCase,CultureInfo.CurrentCulture.LCID);
    }
}

This should do it, the properties you need to use Row.Name and Row.County those are all dependent on the columns you specify for your input and output mapping.

January 12, 2010

Why can’t I a have string? aka Nullable<string>

Filed under: Uncategorized — dotnetchris @ 8:40 pm

It’s not often that I write a post to rant about something that is by design and not actually a bug or just hard to accomplish end but something that really bothers me is the fact I can’t declare a string nullable.

The number one response to that is ”surely you jest as string is already nullable. Which obviously it is, however it’s also created to behave as a primitive type. This being the case makes it the only primitive type you can’t declare as nullable. Once again people usually will re-iterate, ‘exactly, it’s already nullable.’

If string is nullable, why can’t I preform .GetValueOrDefault()?

This is one of the most useful methods available as it easily let you establish frameworks around your primitive types without ever once needing to worry about triggering a null reference exception. It also clearly defines all objects that you expect to be able to be uninitialized and null. This is why I hate that strings cannot be nullable, it’s impossible to tell the intent of the string. Is null an accepted value because it could imply string.Empty? This always has to be handled by convention and validation there’s no way to clearly define this, whereas if you could declare string? this would definitively tell you that null is an expected value and acceptable.

To further my proof is the static method on the string class, string.IsNullOrEmpty(string). This method was placed here because the C# team clearly knew that strings being complex objects treated as reference types is very ambiguous and knew to expose a standardization on how to check this. Why would none of the other classes provide a type.IsDefault(type) method? So in my conclusion I should be able to do string? and sadly I can’t and I guess would have very little regress other than perhaps downloading mono and probably needing to alter the source code for itself.

December 18, 2009

Implementing NHibernate Long Conversation with no HttpModules or AOP build time weaving

This post has been almost a year coming and it’s finally here. I still haven’t been posting much even being in the full swing of development, I just usually end up drained between work and overtime when I have years worth of development plans for my company that they would love to have all of them tomorrow. Fortunately my current employer is definitely is the best environment I’ve ever been in aside from that they give me all the tools I need to complete job they give me basically full reign on system architecture that I finally get to develop and put into production code I’ve worked off and on for over a year now. Also they have very realistic expectations that I’m not rushed to make poor decisions to push a product out the door that’s poorly designed. Now getting back on track.

It all started with Conversation Per Business Transaction using PostSharp and IoC written almost a year ago from today. This post at the time was definitely one of my largest successes in my development career however even though I solved the problem I wanted I still was not happy with the solution (probably because with PostSharp atleast back then my solution would take 5 minutes+ to build) still it was somewhat fragile for how I had to decorate classes with my [BusinessConversation] attributes that a nested method call would cause all hell to break loose.

To start I’m going to show you my final product, this is one of my model classes in the Model-View-Presenter software pattern

public class NotificationModel : INotificationModel
{
    private readonly INotificationProvider _NotificationProvider;

    public NotificationModel(INotificationProvider NotificationProvider)
    {
        _NotificationProvider = NotificationProvider;
    }

    [ConversationPersistance(ConversationCommitMode.Rollback)]
    public void AddButRollBack(NotifyRun notifyRun)
    {
        _NotificationProvider.Add(notifyRun);
    }

    public void Add(NotifyRun notifyRun)
    {
        _NotificationProvider.Add(notifyRun);
    }
}

As you can see on the AddAndRollBack method I do decorate the method with a custom attribute which does make my model somewhat aware of my implementation of my repository but I feel this is an acceptable pollution as it is reasonable to expect any method in the MVP pattern to know whether it’s role is to get data, save data or cancel an action. As you can see though the other method has no decoration and doesn’t require any decoration for the default action you configure.

Next I’m going to start with my inversion of control container, I use StructureMap however I believe this should also be able to be acheived using most other major DI frameworks.

private sealed class StructureMapRegistry : Registry
{
    public StructureMapRegistry()
    {
    //Configure default persisance mode
        ForRequestedType<ConversationCommitMode>().TheDefault.IsThis(ConversationCommitMode.Commit);

    //Castle DynamicProxy
        ForRequestedType<ProxyGenerator>().TheDefaultIsConcreteType<ProxyGenerator>()
      .CacheBy(InstanceScope.Singleton);

    //Castle DynamicProxy IInterceptor 
        ForRequestedType<ConversationInterceptor>().TheDefaultIsConcreteType<ConversationInterceptor>()
      .CacheBy(InstanceScope.Singleton);

     //Configuration wrapper of NH, this could be configured inline here but it's rather verbose
        ForRequestedType<INHibernateSessionManager>().TheDefaultIsConcreteType<NHibernateSessionManager>()
      .CacheBy(InstanceScope.Singleton);

    //This is a lightweight wrapper of the NH ISession that supports lazy access with the session
        ForRequestedType<IBusinessConversation>().TheDefaultIsConcreteType<LazyBusinessConversation>()
      .CacheBy(InstanceScope.HybridHttpSession);

    //This is my NH repository
        ForRequestedType<INotificationProvider>().TheDefaultIsConcreteType<NotificationProvider>()
      .CacheBy(InstanceScope.Hybrid);

    //This is a model class in the MVP pattern  that uses the above NH Provider
        ForRequestedType<INotificationModel>().TheDefaultIsConcreteType<NotificationModel>().CacheBy(InstanceScope.Hybrid)
            .EnrichWith((ctx, model) =>
      ctx.GetInstance<ProxyGenerator>().CreateInterfaceProxyWithTarget(model, ctx.GetInstance<ConversationInterceptor>()));

    //Set rules for what properties are injected on ObjectFactory.BuildUp(this)
        SetAllProperties(policy => policy.NameMatches(name => name.EndsWith("Provider") || name.EndsWith("Model")));
    }
}

I’m not going to explain my NotificationProvider class as it’s irrelevant to this post, it’s a class entirely derived from Creating a common generic and extensible NHiberate Repository, the SetAllProperties is just a StructureMap convention, ConversationCommitMode lets you inject your default configuration to the conversation, and the SessionManager also is unrelated to this post it’s just a wrapper class for boostrapping my NH session factory with Fluent NHibernate. The ProxyGenerator is a class in Castle DynamicProxy, I just use the version that’s already included with my NH. So now I’ll start with my Conversation class that has changed since my previous post. The biggest change is the client no longer needs to be aware of starting the session, connecting or disconnecting the session in anyway. The only need to care about what happens with the ISession after it is consumed.

public interface IBusinessConversation
{
    bool IsInTransaction { get; }
    bool IsNull { get; }
    ISession Session { get; }

    void Abort();
    void Commit();
    void CommitAndFlush();
    void End();
    void Rollback();
}

Part of the reason behind my BusinessConversation class is that I can implement the Null object pattern and lazy loading of the ISession itself so the session is delayed creation until one of my Repositories actually goes to use it and after it exists it’s only connected in instances that actually need it, not on every single page request! Onto the actual implementation.


public sealed class LazyBusinessConversation : IBusinessConversation
{
  private readonly INHibernateSessionManager _sessionManager;
  private ISession _session;

  public LazyBusinessConversation(INHibernateSessionManager sessionManager)
  {
    _sessionManager = sessionManager;
  }

  #region IBusinessConversation Members

  /// <summary>
  /// Rollback and do not commit the current transaction
  /// </summary>
  public void Rollback()
  {
    Rollback(_session);
  }

  /// <summary>
  /// Gets a value indicating whether this instance is in transaction.
  /// </summary>
  /// <value>
  ///   <c>true</c> if this instance is in transaction; otherwise, <c>false</c>.
  /// </value>
  public bool IsInTransaction
  {
    get { return _session.Is().Not.Null && _session.Is().InTransaction; }
  }

  /// <summary>
  /// Gets a value indicating whether this instance is null.
  /// </summary>
  /// <value><c>true</c> if this instance is null; otherwise, <c>false</c>.</value>
  public bool IsNull
  {
    get { return _session.Is().Null; }
  }

  /// <summary>
  /// Aborts this instance.
  /// </summary>
  public void Abort()
  {
    Abort(ref _session);
  }

  /// <summary>
  /// Commits the open transaction the session. Does not flush the session
  /// </summary>
  public void Commit()
  {
    Commit(_session, false);
  }

  /// <summary>
  /// Commits any open transaction in the session and
  /// flushes all pending changes to the database
  /// </summary>
  public void CommitAndFlush()
  {
    Commit(_session, true);
  }

  /// <summary>
  /// Ends this instance committing and flushing all data in session.
  /// </summary>
  public void End()
  {
    End(ref _session);
  }

  public ISession Session
  {
    get
    {
      if (!IsInTransaction)
      {
        Resume(_sessionManager, ref _session);
      }

      return _session;
    }
  }

  #endregion

  #region Class Methods

  private static void Abort(ref ISession session)
  {
    if (session.Is().NullOrClosed) return;

    Rollback(session);
    TerminateSession(ref session);
  }

  private static void Commit(ISession session, bool flush)
  {
    if (session == null)
      throw new ArgumentNullException("session");

    if (session.Is().InTransaction)
      session.Transaction.Commit();

    if (flush)
      session.Flush();

    session.Disconnect();
  }

  private static void End(ref ISession session)
  {
    if (session.Is().NullOrClosed) return;

    Reconnect(session);

    Commit(session, true);

    TerminateSession(ref session);
  }

  private static void Reconnect(ISession session)
  {
    if (session == null)
      throw new ArgumentNullException("session");

    if (session.IsConnected) return;

    session.Reconnect();
  }

  private static void Resume(INHibernateSessionManager sessionManager, ref ISession session)
  {
    if (session.Is().NullOrClosed)
      session = sessionManager.GetSession();

    if (session.Is().Null)
      throw new AccessViolationException("Session could not be created");

    Reconnect(session);

    if (session.Is().Not.InTransaction)
      session.Transaction.Begin();
  }

  private static void Rollback(ISession session)
  {
    if (session == null)
      throw new ArgumentNullException("session");

    if (session.Is().InTransaction)
      session.Transaction.Rollback();
  }

  private static void TerminateSession(ref ISession session)
  {
    session.Close();
    session.Dispose();

    /// Safety net incase conversation is reused
    /// this will guarantee a new session is created
    session = null;
  }

  #endregion
}

Sorry, long block of code I know, before I get into the specifics of it the majority of this class is pretty simple I inject my SessionFactory to the Conversation so I can new sessions when I need them. Other than that the majority of the methods do exactly what they are named and just complete the session or transaction in 1 way or another. Also I’m sure you noticed I call session.Is() this is an extension method that allows me to fluently check session state instead of having to do if(session != null && session.IsInTransaction) etc. Where all of the work really occurs is ISession { get }

IsInTransaction will always return false the first time .Session is accessed during a page request because either the session will be null or it will be disconnected. So the first time it’s accessed it calls Resume. Inside Resume I check to see if it exists, if not, new a session. If it already existed it needs to be reconnected. This handles all of the lazy loading (or lazy reconnection) this is a big advantage over pretty much every solution I’ve seen for the Long Conversation pattern is that they are based on instantiating a session for every user, connecting it at the start of every page request and committing it at the end of every page request regardless of whether or not they need the session at all! Also many of these patterns rely on HttpModules which makes testing so much harder!

At some point this class could probably use some refactoring to split out the methods that actually reattach the session, currently I have a few them with static methods and ref pointers so that you couldn’t call Resume(_sessionManager, Session) from inside the class easily and cause all kinds of unnecessary recursion. Of course as I type this I realize an explicitly defined Session { get } would go a long way for that, I also might consider wrapping my static methods into a class of their own and actually injecting that into the conversation. Now that you can see what my conversation class does we’ll take a look at what’s going on with

ForRequestedType<INotificationModel>().TheDefaultIsConcreteType<NotificationModel>().CacheBy(InstanceScope.Hybrid)
  .EnrichWith(
  (ctx, model) =>
  ctx.GetInstance<ProxyGenerator>().CreateInterfaceProxyWithTarget(model, ctx.GetInstance<ConversationInterceptor>()));

Per the StructureMap documentation

EnrichWith() — Registers a Func that runs against the new object after creation and gives you the option of returning a different object than the original object

So what happens here is you’re intercepting StructureMap giving you an instance of the NotificationModel and doing something with it. In this case what we’re going to do with it is use Castle DynamicProxy to actually create an entirely new NotificationModel that will wrap all of our methods with what we do in the ConversationInterceptor!

public class ConversationInterceptor : IInterceptor
{
  private readonly ConversationCommitMode _conversationCommitMode;

  public ConversationInterceptor(ConversationCommitMode conversationCommitMode)
  {
    _conversationCommitMode = conversationCommitMode;
  }

  private ConversationCommitMode GetConversationMode(ICustomAttributeProvider methodInfo)
  {
    var attribute = methodInfo.GetCustomAttributes(typeof (ConversationPersistanceAttribute), true);

    return attribute == null || attribute.Length == 0
           ? _conversationCommitMode
           : ((ConversationPersistanceAttribute) attribute[0]).ConversationMode;
  }

  #region IInterceptor Members

  public void Intercept(IInvocation invocation)
  {
    invocation.Proceed();

    var conversation = ObjectFactory.GetInstance<IBusinessConversation>();

    if (conversation.IsNull) return;

    switch (GetConversationMode(invocation.Method))
    {
      case ConversationCommitMode.CommitAndFlush:
        conversation.CommitAndFlush();
        break;
      case ConversationCommitMode.Rollback:
        conversation.Rollback();
        break;
      case ConversationCommitMode.Abort:
        conversation.Abort();
        break;
      case ConversationCommitMode.Commit:
      default:
        conversation.Commit();
        break;
    }
  }

  #endregion
}

So what happens after the ProxyGenerator creates our new class is instead of directly calling each method in the Model it will execute the code in Intercept(IInvocation) which for our case will first immediately run the method because we only need to do more AFTER it completes. Now as it runs the method it will call down to the Provider which will then use the lazyBusinessConversation.Sesssion property which will activate our session, run it’s NH commands and start to trace the call chain back after it finishes the execution of the original method call for any of the Model methods it returns back to the Intercept method.

The first thing we’ll check is if the session is null because if it is (meaning we didn’t touch it in our method) we don’t need to do anything else! I’ll explain why this will be very useful in a minute. Assuming we did an NH operation we’re going to check to see if I have our custom attribute added to the method like I do for AddAndRollBack in the model. If it’s there it will return that otherwise it will return the default commit operation that we injected into our IoC container. The switch statement is self explanatory. If we didn’t actually interact with NH on our round trip but the session was created before it still calls conversation.Commit() but looking above you can see it verifies it has an open transaction otherwise it will do nothing, this covers our lazy connection handling without having to embed that logic inside the interceptor.

Now the reason why I handle the null checking as some of you may have wondered, why would the session ever be null when the model is basically just a wrapper around the NH provider classes, the flexibility my solution offers is if you move the .EnrichWith() method in our StructureMap registry off of the Model classes you can put them on either your View or Presenter classes so that the session will be connected for basically the full page life cycle so you should get full support from lazy loading! Also since alot of methods in your views or presenters will have nothing to do talking to NH it will skip all of the work with NH on those requests! This is where I would Enrich my classes outside of my test project.

I would really like to thank Sam over on the StructureMap forums for his very insightful post that gave me the knowledge I needed to see how to solve the Long Transaction pattern using the castle dynamic proxy framework!

Right now none of this code is in my StructuredWeb SVN currently but I will merge all my current work back into SW soon!

kick it on DotNetKicks.com

Shout it

BloggingContext.ApplicationInstance.CompleteRequest();

November 10, 2009

Great Blog on URL Rewriting with URLRewriter.net

Filed under: Uncategorized — dotnetchris @ 3:54 pm

It’s been a while since I posted anything and I came across this great post on Run Tings Proper, Advanced url rewriting for the rest of us – how to create a custom transform in UrlRewriter.net.

This is a great post that really sumarizes the most common needs in URL rewriting and how to handle it with URLRewriter.net (does anyone else find it ironic this website is php, of course I suppose it could be php in asp.net) while I didn’t try out what was on here yet or download the demo it definitely all looks right. At some point I wanted to implement an URL rewriting scheme in my applications and this post will be a great help when I actually start on that.

September 1, 2009

Using jQuery to create a scrolling sidebar

Filed under: Uncategorized — dotnetchris @ 1:45 pm

The easiest way to start this post is with an image explaining the concept.

layout

So now as you can see we have a basic site layout a 2 column with a fixed header and footer. For this example I’m dealing with a fixed header & footer for simplicity but you’ll see you can easily handle dynamic sizing also. The content column is a dynamic size column that can contain a large amount of text that if you scroll down past the fold of the page you will lose track of the sidebar. So the goal I was seeking was a way to have the sidebar follow the scroll bar in an aesthetically pleasing manner.

At first I attempted a fixed width layout but then ran into all of the browser compatibility issues so I turned to jQuery. The first thing we need to achieve is to make the sidebar track the scrollbar.

<script type="text/javascript">
$(window).scroll(function() {
    $('#sidebarPage1').animate(
        { top: $(window).scrollTop() + 'px' }
    );
});
</script>

This will achieve the tracking we desire however it is a very jerky and unpleasant effect so lets see what we can do to tune it up.

<script type="text/javascript">
$(window).scroll(function() {
    $('#sidebarPage1').animate(
        { top: $(window).scrollTop() + 'px' },
        { queue: false, duration: 500, easing: 'easeInOutSine' }
    );
});
</script>

This will produce a much nicer effect. The queue parameter we included is to allow jQuery to create a series of events that happen in a certain order to create animation. We don’t want our animation waiting for anything so we set queue: false to make it run immediately. The duration parameter is how long in milliseconds the animation to take, so setting 500 is one half of a second. This lowers the amount of jumping the sidebar does significantly. Lastly the easing parameter allows us to setup an easing algorithmthat influences how the animation handles the start and ends of the effects. If you look at the easing plugin’s site you can play around with the different options that are built into jQuery natively. I chose the easeInOutSine as it seemed to produce a very nice animation where it spends more of the animation time at the start and end where jerkiness can be more easily noticed, but this was just a personal preference.

Now the real fun, polishing this and fixing the “quirks” this code creates. If you make your browser view port very small you can actually scroll the sidebar off the entire screen because of the footer taking up space at the bottom and the sidebar is already offset from the top because it’s below the header. The first is to get it to stop scrolling off the page. This will involve doing some math to calculate limits on the scrolling.

<script type="text/javascript">
    $(window).scroll(function() {
        var dynamicSidebarHeight = $('.sidebar').height();

        if ($(window).height() > dynamicSidebarHeight) {
            var fixedFooterOffset = 150;
            var scrollTo = $(window).scrollTop()
            var calculatedMaxTop = $('#footer').offset().top - dynamicSidebarHeight - fixedFooterOffset;
            var fixedHeaderOffset = 150;

            if (scrollTo > calculatedMaxTop) {
                scrollTo = calculatedMaxTop;
            }

            $('#sidebarPage1')
            .animate(
                { top: scrollTo + 'px' },
                { queue: false, duration: 500, easing: 'easeInOutSine' }
            );
        }
    });
</script>

To explain what each of these variables mean:

  • dynamicSidebarHeight – this is the jQuery calculated height at run time of the sidebar
  • fixedFooterOffset and fixedHeaderOffset – are the height in pixels of the static headers and footers, which for this example are said to be 150px.
  • calculatedMaxTop – This is the equation to know the farthest down the sidebar’s top can be set to that it won’t crash into the footer.

The first check is make sure the browser viewport is atleast as big as the sidebar. If it’s smaller than the sidebar scrolling is pointless because you will never be able to see the bottom of the sidebar because when you’d scroll down to see the rest of the sidebar it will move off screen. After that we calculate the Max value for the Top of the sidebar which is the based off the location of the top of the footer which is what calling .offset().top returns, let’s say 2000px for this example. We’ll assume the sidebar height is 500px and we have our fixed footer height of 150px.

So top of footer is at 2000px we subtract the height of the bar 500px and the height of the footer 150px so in this example the furthest you could set the top of the sidebar would be 1350px since if the top of the sidebar is 1350px, the next 500px is the sidebar and the next 150px is the footer. So we want to check if scrollTo is > than this value and if it is we want it to set it to the maximum length we would allow.

The final part is to handle once we scroll past the page fold the sidebar is now 150px offset from the top of the window due to the header being at the top that has scrolled up off the screen so it would look alot better if the bar stays stuck at the top edge. This is the reason I have the unused fixedHeaderOffset so far which accounts for the height of the header. The final code we will have is this

<script type="text/javascript">
    $(window).scroll(function() {
        var dynamicSidebarHeight = $('#sidebar').height();

        if ($(window).height() > dynamicSidebarHeight) {
            var fixedFooterOffset = 150;
            var scrollTo = $(window).scrollTop()
            var calculatedMaxTop = $('#footer').offset().top - dynamicSidebarHeight - fixedFooterOffset;
            var fixedHeaderOffset = 150;

            if (scrollTo > calculatedMaxTop) {
                scrollTo = calculatedMaxTop;
            }
            else if (scrollTo < fixedHeaderOffset) {
                scrollTo = 0;
            }
            else
            {
                scrollTo -= fixedHeaderOffset - 18; //18 is for a top margin
            }

            $('#sidebarPage1')
            .animate(
                { top: scrollTo + 'px' },
                { queue: false, duration: 500, easing: 'easeInOutSine' }
            );
        }
    });
</script>

So far we’ve asserted that the viewport is larger than the sidebar, we now cannot scroll the sidebar under the footer or off the page. To make handle the calculation of where to have it in relation to the top of the page we add

else if (scrollTo < fixedHeaderOffset) {
    scrollTo = 0;
}
else
{
    scrollTo -= fixedHeaderOffset - 18; //18 is for a top margin
}

To our if statement. The first case is we’ve scrolled back up to the top of the page and want the sidebar to sit under the header so scrollTo is < the height of the header. At this point we set scrollTo to 0 (I have a position: relative wrapper around my content and sidebar columns) if you don't have a position: relative tag around the sidebar you would set this to the fixedHeaderOffset and probably some margin say 18px.

Now we have the case where we're scrolling the bar down and we want it to be at the top of the viewport this is the else case. So the condition for this is scrollTo is shorter than the maximum allowed value AND scrollTo is further down than the header. Since the position of scrollTo includes the height of the header we need to subtract that off of the value of scrollTo and then subtract a little more so the sidebar sits 18px below the top of the page. If you don't have the position: relative container around the sidebar this would most likely just be the offset from the top of the page so scrollTo – 18px.

Unfortunately I don't have a demo for this but this should be very easy to test. I'll throw up a zip file with the html in it to let you test it out.

August 4, 2009

More Team Foundation Server Voodoo

Filed under: Team Foundation Server — Tags: , , — dotnetchris @ 8:28 pm

After finally getting TFS installed I went to create my first project under it and was greeted with a new lovely error message:

TF30004: The New Team Project Wizard encountered an unexpected error while initializing the Microsoft.ProjectCreationWizard.Reporting plug-in.

Explanation
TF30171: The Microsoft.ProjectCreationWizard.Reporting plug-in used to create the new team project could not be initialized and returned the following error: TF30224: Failed to retrieve projects from the report server. Please check that the SQL Server Reporting Services Web and Windows services are running and you have sufficient privileges for creating a project..

After alot of googling and reading the primary solution came down to reinstall Visual Studio 2008 SP1 again which I put off figuring there had to be a less voodoo solution to this but eventually broke down and tried it. Surprisingly that fixed THIS problem and then immediately I was confronted with ANOTHER problem.

Trying to view the created project on Windows Sharepoint the first thing that shows up is:

An error has occurred during report processing. (rsProcessingAborted)
Cannot create a connection to data source ‘TfsOlapReportDS’. (rsErrorOpeningConnection)
For more information about this error navigate to the report server on the local server machine, or enable remote errors

More google hoop jumping which buried deep down in this post on How do I fix the TfsOlapReportDS user problem? I saw a comment from MattPil29

I had the same problem which was not solved by the “Allow log on locally” fix until I removed the same account from “Deny log on locally” !!!!

So I fixed that with:

NTRIGHTS -u TFSSERVICE -r SeDenyInteractiveLogonRight

Finally I have a successfully created Team Foundation Server project!

August 3, 2009

Flash CS4 Publish to Gif file sucks

Filed under: Uncategorized — dotnetchris @ 8:19 pm

So today I had to convert a swf flash movie I made for an advertisement to an animated gif file so it could be added to an email newsletter and when I’d publish it using Flash CS4 it was just epic… fail. The fading/transparency effects would flicker massively, shift between colors that didn’t even exist in the movie then when text would appear it just turned into a giant blob of black smear in my image.

How very useful…. NOT.

Luckily I found a program that just saved my day E.M. Magic Swf2Gif I also tried a similar product from Aleosoft, Aleo SWF GIF Converter. I’m not sure if this was related to the fact the Aleosoft is a limited functionality trial (watermarks output images) but the resulting quality was substantially lower than E.M. Magic Swf2Gif. So if anyone else has issues with their Flash CS4 Gif publishing looking horrible I recommend taking a look at E.M. Magic Swf2Gif.

July 17, 2009

Team Foundation Dual Server Installation Headaches

Filed under: Uncategorized — Tags: , , , — dotnetchris @ 4:18 pm

Finally I was able to complete the installation of Team Foundation Server (TFS) successfully. I definitely ran into some major headaches along the way.

Firstly, you cannot install TFS on a Domain Controller (DC). This might be a semi-acknowledged limitation but I had no idea of this prior to my first attempt at installation. Working at a small business we only have 2 servers, 1 being the DC. I’m lucky that I was able to have the other server to install it on in the first place and didn’t have to use my local machine.

Since Sql Server was installed on the DC as it’s the more powerful server this requires me to do a dual server setup (Sql Server on one machine and TFS application tier on another.) This isn’t even possible to do using the DVD image or media setup on it’s own. You will need to modify files on the install disk, more on that later.

Another fact I was unaware of is TFS cannot be installed with Sql Server 2008 out of box. The installation needs to have TFS Sp1 slip streamed into the the setup files. I find it rather daunting that I needed to research these options so far in depth to just complete an installation.

First extra steps that need to be done to configure your Sql Server 2008 machine to support TFS.

Change the Sql Server Reporting Services (SSRS) service from using the local system account to a domain account. This account must be configured with the privileges to log on locally, I named the account TFSREPORTS. After creating this account in the active directory you need to configure the rights on it. The easiest way is with the command prompt (start < run < “cmd” ) while still on the server.

NTRIGHTS -u TFSREPORTS +r SeInteractiveLogonRight

While your creating account information you should also create a domain account for TFS to use for it’s service interaction, this requires the Log On as a Service right. I named mined TFSSERVICE. To assign that logon right with NTRIGHTS.

NTRIGHTS -u TFSSERVICE +r SeServiceLogonRight

Now that you have these accounts created you need to either install Sql Server and Reporting Services and when you get to the SSRS configuration the install to designate the TFSREPORTS account to be the account to use. If you already have installed Sql Server + SSRS contrary to the install instructions with TFS you can not just change the account Sql Server Reporting Services using in the services.msc you actually need to use the “Reporting Services Configuration Manager.” By default there is a start menu entry for it under Start < Programs < Microsoft SQL Server 2008 \ Configuration Tools. Open the tool and connect to the server (most likely localhost, unless you’re doing it remotely) under the Service Account tree menu item check Use Another Account supply the account you created in DOMAIN\AccountName form along with the password you created for the account.

Following these steps either updating or your current install or installing new, now it’s time to update Sql Server 2008 to SP1 if it hasn’t already been done so before continuing on to the TFS installation.

At this point you need to dump the files from the TFS dvd image or media onto your hard drive. You will need to slipstream the TFS Sp1 release into your copy of regular TFS. This is included in the TFS documentation or you can view it online How to: Integrate the Installation of Team Foundation Server and Service Pack 1 on devCatharis.

Now you need to modify InstallMedia\AT\msiproperty.ini you need to configure the VSTF_RS_SERVER, VSTF_RS_REPORTS_URI, VSTF_RS_REPORTSERVER_URI. For detail information for setting these values you can view Reporting Services Flexibility (Orcas RTM Only) by Microsoft MVP Sudhir Hasbe.

Now after all of these steps, you SHOULD be ready to install TFS as a dual server installation with Sql Server 2008 on a separate machine and have it complete successfully!

Does anyone else find this basically unacceptable to have to go through this long of a process to just INSTALL your copy of TFS? It sure ruined a few of my days.

BloggingContext.ApplicationInstance.CompleteRequest();

Older Posts »

Blog at WordPress.com.