Aug 7 2010

Mapping String Enum with Spaces in Fluent NHibernate

Category: FluentNHibernate | Nhibernate | .NetAdam Aldrich @ 07:18

By default Fluent NHibernate will map Enums as strings. So if you have an Enum like this:

public enum CreditCardType
{
    Visa,
    American Express,
    MasterCard,
    Discover
}

You are going to have issues because you can’t use spaces for “American Express”. The good news is that there is a way to get around this without changing your data. In your Enum replaces spaces with underscores (_). So our new Enum looks like this:

public enum CreditCardType
{
    Visa,
    American_Express,
    MasterCard,
    Discover
}

FluentNHibernate has created a GenericEnumMapper that gets used by default. However you can override it for this instance by creating a new class like this:

public class CreditCardTypeMapping : GenericEnumMapper<CreditCardType>
{
    public override object GetInstance(object code)
    {
        var value = (string)code;
 
        if (string.IsNullOrEmpty(value))
            return StringToObject(value);

        return StringToObject(value.Replace(" ", "_"));
    }

    public override object GetValue(object code)
    {
        return (code == null) ? string.Empty : code.ToString().Replace('_', ' ');
    }
}

All I’m doing here is replacing any spaces(“ “) with underscores(“_”) during the translation. You still need to tell FluentNHibernate how to use this so in your mapping file map your enum value like this:

Map(x => x.credit_card_type).CustomType<CreditCardTypeMapping>();

That is it. You should be able to use your Enum type with spaces now.

Bookmark and Share DotnetKicks dotnetshoutout

Tags:

Jul 23 2010

Blog Update

Category: Adam Aldrich @ 08:45

I updated my blog from DasBlog to BlogEngine.Net. I needed to upgrade to ASP.Net 4.0 and I wasn’t having much success with DasBlog. If you find any problems please let me know. I setup redirects for the RSS feed so that shouldn’t be affected.

Bookmark and Share DotnetKicks dotnetshoutout

Tags:

Jul 20 2010

IronRuby on Rails Setup Using Local Rails Gems

Category: .Net | IronRuby | RailsAdam Aldrich @ 18:29

Recently I was trying to install IronRuby on Rails but had a few snags so I thought I would mention how I got around them for anyone that might have the same problems. First off you can follow the official install documentation http://ironruby.net/Documentation/Real_Ruby_Applications/Rails. For the most part I was able to follow the instructions without any issues however I started getting an error when trying to install rails:

SocketError: An established connection was aborted by the software in your host machine (http://gems.rubyforge.org/gems/rails-2.3.8.gem)

They mention that you can use a proxy if you have an error. They don’t say exactly which error but I assume this is the one. I turned my firewall off but still got the error. The only thing I can figure is that I’m running inside a VM and that might cause some issues. Either way I couldn’t get the “igem install rails” command to work so I had to take a manual install route.

  • Download the rails gem version you are looking for, at the time of this writing it was 2.3.8.
  • From the Command Prompt navigate to the directory where you downloaded the file and try to install it locally “igem install ./rails-2.3.8.gem”
  • You will likely get an error that another package dependency is needed. If you look at the rubyforge page it shows which dependencies are required for rails to install.

rails_gem_download

  • You can repeat step 1-3 to download and manually install each of these if needed. For me I had to install “activesupport, activerecord, and actionpack”. Actionpack required Rack version 1.1.0. That was an older version that the one you get when you just install using “igem install rack”. Long story short just make sure you download the correct version for the one you get an error saying it needs as a dependency. If you feel like you are getting lost just run the “igem install ./rails-2.3.8.gem” and it will tell you what you are missing.
  • Once the rails install passes you are good to go. You should be able to follow the rest of the official tutorial.
Bookmark and Share DotnetKicks dotnetshoutout

Tags: , ,

Jul 9 2010

Hosting Multiple Websites using 1 Discount ASP.Net Account

Category: .Net | DiscountASP.NetAdam Aldrich @ 06:37

I have spent the last couple of days trying to use my DiscountASP.Net Account with multiple websites. For instance lets say I owned sites www.site1.com, www.site2.com and www.site3.com and I wanted them all to be hosted on DiscountASP.Net under the same account but use their own domain names. Here is what I ended up having to do to get it to work.

1. Publish each site to it’s own location.  Lets say we have a Site1, Site2 and Site3 folder under the root that we want to deploy the corresponding domains. You need to make sure you go into the DiscountASP.Net Control Panel->Tools & Utilities->Web Application Tool and set each location as a Application.

2. Get the Unlimited Subdomain Addon from DiscountASP.Net. You can view their addons here https://my.discountasp.net/addons/ At the time of this posting it is $5 a month. All this really does is give you a Static IP Address that you can use to point your other domain names too.

3. Setup DNS Records. I use Godaddy but most all the domain hosting companies allow you to modify your DNS Records. What you need to do is create 2 A Records. 1 for www and one for the root. This will point anyone that types in www.site1.com and site1.com to your DiscountASP.Net site. Just point them to the IP Address given to you in the DiscountASP.Net Control Panel under Tools & Utilities->DNS Manager.

4. IIS 7 URL Rewriting. This works with IIS 7 I’m not sure about 6 but if it doesn’t work you could use ASP.Net Routing to accomplish the same thing. I just find it easier to use IIS 7. All we want to do is route the requests to the appropriate Site Application location (The ones you created in Step 1 /Site, /Site2 and /Site3). Create a blank website and deploy it to the root location. In it’s web.config you need to add an entry for each of your sites that fits this format. Make sure you start the <system.webServer> after <configSections>

   1: <system.webServer>
   2:       <rewrite>
   3:         <rules>
   4:           <rule name="Rewrite to Site1" stopProcessing="true">
   5:             <match url="(.*)" />
   6:             <conditions>
   7:               <add input="{HTTP_HOST}" pattern="^www.site1.com$" />
   8:             </conditions>
   9:             <action type="Rewrite" url="Site1/{R:1}" />
  10:           </rule>
  11:           <rule name="Rewrite to Site2" stopProcessing="true">
  12:             <match url="(.*)" />
  13:             <conditions>
  14:               <add input="{HTTP_HOST}" pattern="^www.site2.com$" />
  15:             </conditions>
  16:             <action type="Rewrite" url="Site2/{R:1}" />
  17:           </rule>
  18:           <rule name="Rewrite to Site3” stopProcessing="true">
  19:             <match url="(.*)" />
  20:             <conditions>
  21:               <add input="{HTTP_HOST}" pattern="^www.site3.com$" />
  22:             </conditions>
  23:             <action type="Rewrite" url="Site3/{R:1}" />
  24:           </rule>
  25:         </rules>
  26:       </rewrite>
  27:     </system.webServer> 

You can also use the IIS Manager to accomplish the same thing but I think it is easier to just use code.

Think of the process in this manner. Someone navigates to www.site1.com that gets routed to the IP Address of your DiscountASP.Net account. The IIS Url Rewrite tool then looks at the request and sees that it is a www.site1.com address. It will then forward that request to the /Site1 directory on your Account. The cool thing about IIS Url Rewriting is that the address bar still says www.site1.com instead of www.site1.com/Site1 if you use a redirect it would not look as good.

Hope this helps someone trying to do the same thing.

Bookmark and Share DotnetKicks dotnetshoutout

Tags: ,

Apr 15 2010

Intro to NHibernate Presentation for Huntsville .Net User Group

Category: .Net | Demos | NhibernateAdam Aldrich @ 00:26

I had a great time presenting to the Huntsville .Net User Group last night. I think the presentation went really well. It was a very nice group of people. The thing I enjoyed the most was the dialog and conversation from the audience. I love talking with my fellow developers about writing software and finding out how they are solving problems with different approaches. Thanks again to everyone who attended I hope you found it useful. I enjoy feedback both good and bad :) so please feel free to e-mail me with any comments/questions.

You can download all my slides and code here

Also if you don’t have resharper to run the tests you can use TestDriven.Net which is a free utility to run/debug your unit tests. I was using Machine Specifications as my BDD framework. You will have to run a setup file to get TestDriven.Net to work with MSpec there is a good blog article here that explains how to do it. If your interested in it more you can get the source code via github here.

Thanks again for attending the presentation.

Bookmark and Share DotnetKicks dotnetshoutout

Tags: , ,

Mar 13 2010

NHibernate Error “illegal access to loading collection”

Category: NhibernateAdam Aldrich @ 12:29

I ran into this error today “illegal access to loading collection”. I couldn’t figure out what was causing it because my code has been working fine for 7+ months then all of a sudden I get this error when loading 1 specific record. It turns out there are several reasons you can get this error. My reason ended up being an orphaned record in the many to many linker table. Here are the details.

I had a class with a many to many mapping inside of it. The class was lazy loaded so I knew that it couldn’t be anything trying to access the collection before it finished loading. So I have an Employee and a Manager. An Employee can have many Managers and a Manager can have many Employees. They are joined with an EmployeeManagerLinker table which will have an EmployeeID and a ManagerID. It looks like this:

Here is the mapping file for the Manager:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true">
    <class name="Manager" lazy="true" table="Managers" >
        <id name="ManagerID" column="ManagerID" type="Int64" unsaved-value="-1">
            <generator class="native" />
        </id>
        <set name="Employees" table="EmployeeManagerLinker" lazy="true" cascade="all" >
            <key column="ManagerID" />
            <many-to-many column="EmployeeID" class="Employee" lazy="proxy"/>
        </set>
    </class>
</hibernate-mapping>

If you notice the collection of Employees is set to lazy load. The data in the database had an EmployeeId in the linker table that had no corresponding record in the Employee table, ie. an orphaned record. This was causing the illegal access to loading collection error. I corrected the data and everything started working fine. If you don’t have the option to correct the data you can also add the not-found="ignore" attribute which will tell NHibernate not to throw an error when you have an orphaned record. I advise against this however because it causes NHibernate to fetch all the many to many records one by one without lazy loading them. If you really must though it would look like this:

<set name="Employees" table="EmployeeManagerLinker" lazy="true" cascade="all" not-found="ignore" >

As I stated there are other reasons you would see this error. If you were not lazy loading and you tried to do something like access the collection before NHibernate had finished loading it you would also see this error.

Bookmark and Share DotnetKicks dotnetshoutout

Tags:

Mar 11 2010

Getting started with NDepend

Category: .Net | NDependAdam Aldrich @ 17:12

NDepend is a commercial tool that helps you analyze your solution for dependencies, problem areas, places that need refactoring, the list goes on and on. I like to use it to find those dark and dingy places of your code that everyone pretends doesn’t exist. It can also be used to keep a running analysis on your code base to make sure certain rules are met.

One thing that I had a problem with initially was where in the world to get started. This thing shows you SO much information it can be intimidating. So I thought that I would show a simple how to get started and which things I used most frequently when I was learning the tool.

I am using NDepend v3 which was recently released. It has substantial improvements over v2. I plan to write a post later to highlight some of the new enhancements.

First thing is to install the Visual Studio Add-in so NDepend can hook into your solution and make it easier to analyze. You should get this screen when you start VisualNDepend.exe for the first time. If you don’t see it you can go to Tools->Options

image

Make sure you don’t have Studio already open and Click the Install for the version of studio you want. You will get a confirmation that the add-in is installed.

Now open up the solution you want to analyze. You should now have an NDepend Menu option. From it choose the Attach existing NDepend Project to current VS Solution.

image

By default it will add all projects in your solution to the NDepend project. Choose the projects you don’t want to include. I almost always just include them all.

image

Your solution will reload itself and you should now have a different menu structure for NDepend. You should also see a webpage open with a report for your solution. This report is huge. It has everything you ever wanted to know about your solution. If you are a one of those people that likes to know every nook and cranny in your solution then you just got it.

Here are some of the things I find most useful when getting started. You can access most of them from the NDepend menu.

  • Dependency Graph
  • CQL Query Editor
  • Unit Test Coverage
  • Integration with Build Process

Dependency Graph

The Dependency Graph shows you each library and which libraries it depends on. This is extremely useful to me because it shows the coupling between my projects. By default the box sizes are sized based on the number of lines of code but you can easily change it. I like to look at the Afferent coupling. Definition from NDepend is “The number of types outside this assembly that depend on types within this assembly. High afferent coupling indicates that the concerned assemblies have many responsibilities.”

image

CQL Query Editor

CQL is a query language for your code. It can allow you to find out almost anything you need to know about your code. Number of Methods with X number of lines, Number of Constructors with X number of parameters, etc. It also allows you to setup constraints. For instance one I like to use is that I generally never want a method with more than 5 parameters. I feel like if a method takes more than 5 parameters it is too complex and should be broken up. If I wanted to find all those methods I would simply issue this query

SELECT METHODS WHERE NbParameters > 5

image

If you want to see all the possible things you can do with CQL here is NDepend’s great intro. It really is a simple to use language. To make things even easier the editor has intellisense built in that easily shows you what you can do.

Unit Test Coverage

NDepend can use your unit tests coverage reports. This will allow you to use CQL to query all Methods, Types, Namespaces, and Assemblies for Percentage of Coverage, Number of Lines Covered, Number of Lines not Covered and Percentage of Branches covered (NCover only). You can import coverage files from NCover 2.0, 3.0 and Visual Studio Team System. Unfortunately the only free version of NCover is an older 1.x version so you will have to purchase the newer versions if you want to enable this feature with NCover.

Integration with Build Process

NDepend can output an analysis report when you run your build. If you are using a Continuous Integration process such as Cruise Control.Net you can integrate NDepend with it. This will let you output a report showing information from NDepend’s analysis directly in your CI report. One of the really cool features is that you can customize the report to show exactly what you want. From the NDepend menu go to NDepend Project>Edit Project Properties

image

Now select the Report Tab. You can select what you want outputted in the report.

image 

Conclusion

I hope this has shown some of the features you would find useful when getting started with NDepend. As I mentioned this tool does wayyyy more than I have shown. I personally find this tool very useful. In greenfield projects it helps you to keep your code clean as you develop. In brownfield projects I use it to find existing problem areas. I have been using it on a 10 year old product that has been developed on by lots of different developers throughout the lifespan. So by using a tool such as NDepend you can easily start to identify dependencies and code that doesn’t meet your standards.

The version 3 has great Studio integration. In this post after the initial Visual Studio plug-in install, we never had to directly open the VisualNDepend.exe directly. I love that I can do everything from inside Visual Studio while looking at my solution. Visit their website for some great screencast tutorials and more information on all the features it can provide you.

Bookmark and Share DotnetKicks dotnetshoutout

Tags: ,

Feb 20 2010

Specification Pattern and Linq

Category: .Net | Linq | NhibernateAdam Aldrich @ 23:03

Note: This post assumes you know the basics of the Specification Pattern. It would be too much to cover in it’s entirety in this post. I’ll leave that to others that can explain it better than me. The basics are that you turn business logic into boolean logic. You can chain several Specifications together and at the end the is_specified_by method is called and returns a bool that determines if the current object meets the specified criteria.

If you want to just download the source code then feel free to here

I have been using DDD with Stub Repositories on a project recently. Everything was going great, all my unit tests passed, my domain logic for my specifications was working as I wanted with an in memory collection…and then I tried to create a repository using NHibernate. The big question was how do I get NHibernate to take my specification logic and turn it into an NHibernate query?

In order to execute a Linq query you use Where. So I started with

result = session.Linq<Employee>().Where(specification.is_satisfied_by());

My initial thinking was that the Where would take the specification and execute the is_satisfied_by method with the employee object and it would be returned if it evaluated true. Nope my query just returned all the Employees. It executed the specification but the query itself didn’t have any where logic in it. Let’s take a look at the Linq.Where clause

image

So we can basically pass it 2 types of things:

  1. Func<T,bool>
  2. Expression<Func<T,bool>>

Func<T,bool> is any Function that takes a Type (T) and returns a bool. Expression<Func<T,bool>> on the surface may sound like the same thing but it is not. Expression is a placeholder for an expression tree. This means that Func<T,bool> is turned into an piece of expression data and passed on to the NHibernate Linq provider. Why would we want to do that you might ask? The expression is still in the raw data form, it will get passed to the NHibernate Linq provider where it can be translated into a NHibernate compatible form. Think of the Expression Tree as the generic form that all Linq providers can use to translate into something else. That took me awhile to understand but it makes sense when you think about it. Here is what the Expression Tree looks like:

image

 

You can see that we are calling x=>x.Name.Equals("Adam Aldrich") Which is a type Func<Employee,Boolean>

This is nasty looking stuff. I show so you can see what will get passed to the Linq Provider is not just a function it is an Expression Tree.

 

 

 

 

 

 

 

 

 

 

 

 

So the point is if we can write our specification pattern to return Expression<Func<T,bool>> then it can be passed to any Linq Provider! We can pass this to NHibernate, Linq to Sql, Entity Framework, etc. so we are building a reusable Specification Library.

Ok, so hopefully I have explained why we need to pass in Expression<Func<T,bool>> so lets figure out how to make our specification pattern actually work.

This is our ISpecification Interface.

public interface ISpecification<T>
{
    bool is_satisfied_by(T condition);
    Expression<Func<T, bool>> is_satisfied_by(); 
    ISpecification<T> And(ISpecification<T> other);
    ISpecification<T> Or(ISpecification<T> other);
    ISpecification<T> Not();
}

The only thing I am doing here that is different than the normal specification pattern is the Expression<Func<T,bool>> is_satisfied_by(). This will be used to pass to our Where method on the Linq provider. I don’t want to show all the code but I do need to show how you implement the basic Binary/Unary Specifications (And, Or, Not).

Here is what the basic Specifications would look like:

public class OrSpecification<T> : BinarySpecification<T>
{
    public OrSpecification(ISpecification<T> left, ISpecification<T> right) : base(left,right){}

    public override bool is_satisfied_by(T condition)
    {
        return left_side.is_satisfied_by(condition) || right_side.is_satisfied_by(condition);
    }

    public override Expression<Func<T, bool>> is_satisfied_by()
    {
        var body = Expression.OrElse(left_side.is_satisfied_by().Body, right_side.is_satisfied_by().Body);
        var lambda = Expression.Lambda<Func<T,bool>>(body, left_side.is_satisfied_by().Parameters);

        return lambda;
    }
}
public class AndSpecification<T> : BinarySpecification<T> 
{
    public AndSpecification(ISpecification<T> left, ISpecification<T> right) : base(left,right){}

    public override bool is_satisfied_by(T condition)
    {
        return left_side.is_satisfied_by(condition) && right_side.is_satisfied_by(condition);
    }

    public override Expression<Func<T, bool>> is_satisfied_by()
    {
        var body = Expression.AndAlso(left_side.is_satisfied_by().Body, right_side.is_satisfied_by().Body);
        var lambda = Expression.Lambda<Func<T,bool>>(body, left_side.is_satisfied_by().Parameters);

        return lambda;
    }
}
public class NotSpecification<T> : Specification<T>
{
    readonly ISpecification<T> to_negate;

    public NotSpecification(ISpecification<T> to_negate)
    {
        this.to_negate = to_negate;
    }

    public override bool is_satisfied_by(T condition)
    {
        return !to_negate.is_satisfied_by(condition);
    }

    public override Expression<Func<T, bool>> is_satisfied_by()
    {
        var body = Expression.Not(to_negate.is_satisfied_by().Body);
        var lambda = Expression.Lambda<Func<T,bool>>(body, to_negate.is_satisfied_by().Parameters);

        return lambda;
    }
}

The key pieces to look at are the Expression<Func<T, bool>> is_satisfied_by() methods. Lets look at the Not.

var body = Expression.Not(to_negate.is_satisfied_by().Body);
var lambda = Expression.Lambda<Func<T,bool>>(body, to_negate.is_satisfied_by().Parameters);

Expression.Not is the expression version of the bitwise ! (Not) operator. We are passing it the Body of the Expression which if you look at the expression tree I showed earlier is just really the guts of our specification wrapped up into an expression.

Expression.Lambda just takes our body after it has been negated and wraps it back up into a lambda expression which will get passed to Linq. Lets look at the before and after to show you that all we are doing is modifying the expression tree before it is sent to Linq.

Before:

After:

image image

You can see how the x=>False is now x=>Not(False). And and Or are similar.

var body = Expression.OrElse(left_side.is_satisfied_by().Body, right_side.is_satisfied_by().Body);
var lambda = Expression.Lambda<Func<T,bool>>(body, left_side.is_satisfied_by().Parameters);
var body = Expression.AndAlso(left_side.is_satisfied_by().Body, right_side.is_satisfied_by().Body);
var lambda = Expression.Lambda<Func<T,bool>>(body, left_side.is_satisfied_by().Parameters);

There are a few differences. Since these are Binary operations we need a left and right to compare. We also use the OrElse and the AndElse. There is also an Expression.And and an Expression.Or but those are bitwise operators, we need the conditional operators respectively (&&) and (||) so we use OrElse and AndElse. Also notice we are only using the parameter from the left_side. Our left_side and right_side should be of the same type T so this should not be a problem.

Putting it all together we can use our specification pattern like this:

specification = new AnonymousSpecification<Employee>(x => x.Name.Equals("Adam Aldrich"))
                   .Or(new AnonymousSpecification<Employee>(x => x.Age.Equals(4)));
            
results = session.Linq<Employee>().Where(specification.is_satisfied_by());

Here is what the query looks like

image

specification = new AnonymousSpecification<Employee>(x => x.Name.Equals("Adam Aldrich"))
                .And(new AnonymousSpecification<Employee>(x => x.Age.Equals(27)));
results = session.Linq<Employee>().Where(specification.is_satisfied_by());
image 
specification = new NotSpecification<Employee>(
                new AnonymousSpecification<Employee>(x => x.Name.Equals("Adam Aldrich")));
results = session.Linq<Employee>().Where(specification.is_satisfied_by());
image 

Summary

Whew! that was a lot. I hope it made sense. The biggest thing I hope you take away from this is how you can use the Specification pattern to keep query logic inside the domain. Then take that specification and feed it into Linq to NHibernate (or any Linq provider for that matter). I also hope you take away that Expression<Func<T,bool>> is a generic way to pass a query around between Linq providers. I only implemented a few operators (And,Or,Not) but you can see how you could easily build others (GreaterThan, LessThan) into the library. Also you can wrap all this up into a nice Internal DSL to make it much easier to use, I’ll save that for a later post.

I have attached the source code along with tests so you can see more details about what is going on.

Bookmark and Share DotnetKicks dotnetshoutout

Tags: , ,

Feb 11 2010

Vrome Vimperator like extension to Chrome

Category: Chrome | ProductivityAdam Aldrich @ 09:11

I have been using Vimperator for firefox. It is an addon that lets you use Vim commands to navigate the web. JP Boodhoo has a nice screencast that will help you get started with it if your interested. Jeff Barnes recently told me about Vrome which is supposed to be similar to Vimperator but for Google’s Chrome browser. Another cool thing is that the source is available at Github if you want to download it. I didn’t have any issues installing the extension for Windows but Mac kept giving me a “Chrome Extensions are not enabled” error. Here is how I got around it.

Installation for Mac:

1. You will have to download the development version of Chrome because the current Mac Chrome version doesn’t support extensions, you can get it here

2. After installation you can install the Vrome extension from here

3. Now you can use Vim commands inside of chrome.

So far most of the ones from Vimperator seem to work in Vrome. These are the ones I have tested and use most of the time.

Key Action
j Scroll Down
h Scroll Right
k Scroll Up
l Scroll Left
o Open Link
t Tab Open Link
d Close Current Tab
gt Next Tab
gT Previous Tab
r Reload
H Go Back
L Go Forward
f Follow Link, Highlights all links with numbers.
Bookmark and Share DotnetKicks dotnetshoutout

Tags: ,

Jan 29 2010

Merging a local Git branch over your master

Category: gitAdam Aldrich @ 11:28

I had a scenario the other day where I wanted to take all the content from a branch and merge it into the master. Normally this is not an issue I would issue these commands:

git checkout master
git merge mybranch

However I had a lot of merging issues and I didn’t exactly feel like running mergetool on all of them. In this case I knew that everything in my current branch should be what I want in my master. So I issued these commands:

git checkout master
git reset --hard mybranch

This will tell git to reset the master branch using the branch you specified. My master now looks like the mybranch branch.

Bookmark and Share DotnetKicks dotnetshoutout

Tags: