Nuget 1.6 is released along with breaking changes

First for some back ground. I’ve found the development story of creating nuget packages to be a bit rough. This is the development story I’ve come up with. In the root of my solutions that will build nuget packages I place Nuget.exe the command line executable. (I commit this to hg and keep it in solution)

Following that any project that needs to build itself as a package, I create a nugget.cmd in the project root. This is an example of what my nugget.cmd would look like:

_ SOLUTION_\Nuget.exe pack _ PROJECT_\myProj.csproj -Configuration Release -Verbose -OutputDirectory .\bin\

This works very well as I can right click the project from the solution explorer and Open Command Prompt then just run nugget.cmd. I believe Open Command Prompt  comes from the PowerCommands for VS VSIX extension.

Enter today, I updated the Nuget.exe to 1.6 using “Nuget.exe update” went to run my nugget.cmd and was presented with:

Unknown option: ‘-Configuration’

The migration path to this is to update your build scripts to behave as:

Nuget.exe pack _ PROJECT_\myProj.csproj  -Build -Verbose -OutputDirectory .\bin\ -Properties Configuration=Release

Another breaking change that I encountered is if you use the replacement tokens with nuget such that your nuspec file contains

<id>$id$</id>
<version>$version$</version>
<authors>$author$</authors>
<owners>$author$</owners>

The $version$ property will no longer properly read your AssemblyInfo version attribute. After upgrading to 1.6 and building my project it would just result in 1.0 instead of the correct version. I had to set the specific version in the nuspec file to overcome this. I opened issue #1777 on Codeplex for nuget about this as this seems like a bug.

BloggingContext.ApplicationInstance.CompleteRequest();

Advertisements

Donut Output Caching in ASP.NET MVC 3

Came across this today, Donut Output Caching in ASP.NET MVC 3. This project seems to solve all of the problems that you would encounter with ASP.NET built in OutputCache if you attempted to use it with MVC3. The builtin output cache is very unhelpful for real world MVC applications.

PM> Install-Package MvcDonutCaching

BloggingContext.ApplicationInstance.CompleteRequest();

Lync sign in error – personal certificate

So today I sat down at my chair at work and saw I was signed out from Lync. We use office365 (it is hotness) here at work, and was rather perplexed with the error message “Cannot sign in to Lync There was a problem acquiring a personal certificate required to sign in. If the problem continues, contact your support team.”

Called microsoft, and the answer was an extremely strange one but very trivial.

Click the gear to open options, on the personal tab, click advanced, set it to manual.

In the internal/external host addresses enter: sipdir.online.lync.com:443

Connect, all should go well.

Click the drop down next to the gear, file, sign out.

Click the gear, personal, advanced, set it back to automatic.

Sign in and the problem for me atleast was resolved.

Hopefully I’ll save some of you out there on the interwebs the 20 minute support phone call with Microsoft and just fix it yourselves. As to why this occurred, my only guess is Microsoft updated some SSL certificate or host IP that didn’t perk through properly for everyone where connecting to the server directly caused the SSL to refresh…. or something. I always love the or something answers.

BloggingContext.ApplicationInstance.CompleteRequest();

Elmah.MVC nuget

I figured since I haven’t been writing much I’m better off posting microblog posts instead of nothing. I came across this package today, Elmah.MVC by @alexbeletsky.

This made things so trivial to setup with Elmah. This is how I will configure all of my future MVC3 applications with Elmah as it takes literally 1 minute now.

(assuming the Nuget package manager console)

PM> Install-Package elmah.xml

PM> Install-Package Elmah.MVC

Uncomment the authorize attribute

[Authorize(Roles = "Admin")]
public class ElmahController : Controller {

Done.

I find only the XML version of elmah to be worthwhile. However at some point I might try out the Sql Server Compact edition. I require that my error logging solution not depend on external resources like an external sql server database because if the database goes down you lose even your error logging capability which defeats the purpose.

BloggingContext.ApplicationInstance.CompleteRequest();

Cassette for javascript and css minifying and combining

It’s been another long time since I’ve updated my blog. However this project definitely deserves a shout out. Cassette is the best CSS & Javascript minifier/combiner I’ve ever seen. Almost every other project has felt extremely lacking to me in one way or another but with Cassette it doesn’t.

After seeing the wide assortment of choices it’s finally clear Cassette is king. I hope work can be done to improve Cassette to end the high level of fragmentation among the projects. The wiki is a little bit confusing and documentation very sparse. For new users you want to start with the documentation following the migration to 0.6. This discusses the current version of Cassette and not outdated documentation that is not relevant to Cassette any longer.

Exa-Mastery stage of software development patterns

One of the bloggers I make efforts to follow Steve Smith on the The 4 Stages of Learning Design Patterns. I’ve had the opportunity to meet Steve at previous DevConnections and he’s an all around good guy and from us speaking and all I’ve read through his blog posts I find our software development and architecture mentality to be very similar.

To sumarize Steve’s article he defines that are 4 stages to understanding software patterns.

  • Stage 0: I don’t know this pattern
  • Stage 1: I sort of know this pattern and can talk about it, maybe I can use it somewhere
  • Stage 2: I know this pattern, I think it’s awesome, I’m going to use it EVERYWHERE.
  • Stage 3: Understanding that too much of anything, even good things can be bad. That there are optimal usages of a given pattern and less fitting ways to use them.

This put my brain on the track of well what’s next? What’s past that last level of knowledge?

The next level comes from having obtained the experience to be a functioning Enterprise Architect. Having already obtained the knowledge and understanding of the application of said pattern(s) the next level comes from balancing the appropriate level of adoption of the pattern by your software team.

Successful usage of patterns at the exa-mastery level will result in:

    • improved code schematic cohesion

there’s nothing harder to digest than every project doing everything differently

    • design stays true to DRY YAGNI and KISS

if you’re continually violating these you’re failing as an architect because no matter how awesome you think your systems and frameworks if they aren’t built with these principles in mind you’re lieing to yourself and your team and your business. Writing software is hard, when you expect others to use your patterns they need to be simple in usage regardless of whether they are ungodly complex or trivially simple under the seams.

    •  pattern usage that is easy to understand

this is directly drives off my last point, the pattern doesn’t need to be easy the usage does. A perfect example of this is MVC and the conventions around the rather elaborate MVC software pattern, by following the conventions you can work even if you don’t understand why. This is an important requirement to have success that implementing your pattern can be done by your most junior dev to your most senior architect.

    • reducing code churn

good patterns hinge on DRY, or Don’t Repeat Yourself. Making this statement would have the corollary, good usage of software patterns lowers code churn. When software is built on top of repeatable success the lines of code that change should reduce because the amount of iterations to reach success should also reduce. Your pattern should be replacing the need to repeatedly do more work than neccessary. If your pattern is substantially increasing the work done for developers you need to have serious considerations on the usage.

    • patterns will have as few external moving parts as possible.

is another aspect of keeping it simple but discrete enough to merit it’s own line, the more pieces you have to manually connect the harder it is to stay successful with a pattern. A perfect example of this is shown by many ORMs. You create a class file that defines your object, you create an xml mapping file that relates your class to the database table, you have to remember to have the xml file set correctly in the project so when you goto deploy that it’s still there and can be accessed correctly. The more disjoint pieces you make your team responsible for to use your patterns you exponentially increase the amount of failure. I can’t tell you how many times I saw people ready to pull their hair out in NHibernate forums and other discussion forums on why their mapping isn’t working and it comes down a hbm file being set to the wrong resource type.

BloggingContext.ApplicationInstance.CompleteRequest();

Converting a string value that is a literal hexadecimal to its ASCII char

It’s been a while since I’ve posted to my blog and have stuff I definitely want to get in but haven’t got around to yet. Regardless I encountered a strange encoding last week that I couldn’t figure out coming from Feedburner’s web service. I would receive messages back there were similar to:

document.write(“/x3cdiv ….

Where /x3cdiv is supposed to actually be <div

With assistance of stackoverflow I was pointed to that the special characters were encoded to the hexadecimal value of their ASCII char.

This left me with the question, how is it possible to convert “3c” to ‘<‘? I went to google and really had no luck in finding the correct way to convert this. With alot of effort I was able to find the code to handle this conversion buried in a completely unrelated post dealing with file processing.

To hopefully make life easier on someone else here’s how simple the code is to convert the hexidecimal  value of “3c” to ‘<‘

public static  char ConvertHexToASCII(string hex)
{
  if (hex == null) throw new ArgumentNullException(hex);
  return (char)Convert.ToByte(hex, 16);
}

BloggingContext.ApplicationInstance.CompleteRequest();

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

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

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();

Making text proper case in SSIS 2008 with a script component

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.