Ang3lFir3 – Life as a Code Poet

March 18, 2009

Fluent NHibernate new style mappings – powerful semantics

Filed under: C#, Fluent NHibernate, NHibernate, ORM, Uncategorized — Tags: , , , , , , — ang3lfir3 @ 5:56 pm

So today I updated to the latest build of Fluent NHibernate.  As any of you who might have done the same have discovered there are some breaking changes. I wasn’t sure I liked the new class based conventions at first, especially since it wasn’t clear at first how to tackle altering my mappings. Then it dawned on me how powerful the conventions would end up being while also promoting DRY.

as @jagregory said :

“brevity was sacrificed for power in this case.”

This can be seen in the example below which is a self referencing Parent Child relationship.

The description of the relationship is:

Categories can have one or none parents.

Categories can have many or no children.

The parent Category is always found in a property called “Parent”.

The children are always found in a property called “Children”.

Before

Original Mapping:

public class CategoryMap : ClassMap<Category>
{
  public CategoryMap()
  {
    Id(x => x.Id);
    Map(x => x.Name);
    References(x => x.Parent).TheColumnIs("parent_id").Cascade.All();
    HasManyToMany(x => x.Products).Inverse();
    HasMany(x => x.Children).WithKeyColumn("parent_id").Cascade.All().Inverse();
  }
}

**Note:  These aren’t exactly “Conventions” but it turned out that ‘WithKeyColumn’ got dropped and I had to look for a better way. The new style conventions offered that even over older convention styles.

After

The new style Convention Mappings :

The Convention classes below create a convention that reads like:

“For a HasMany when the child type matches the type of the root and the name of the property is ‘Children’  then use the column ‘parent_id’ as the KeyColumn. For a Reference when the child type matches the type of the root and the name of the property is ‘Parent’ then set its reference ColumnName to ‘parent_id’ “

public class SelfReferencingHasManyConvention : IHasManyConvention
{
  public bool Accept(IOneToManyPart target)
  {
     return target.Member.ReflectedType == target.EntityType && target.Member.Name == "Children";
  }

  public void Apply(IOneToManyPart target)
  {
     target.KeyColumnNames.Clear();
     target.KeyColumnNames.Add("parent_id");
  }
}
public class SelfReferencingReferenceConvention : IReferenceConvention
{
  public bool Accept(IManyToOnePart target)
  {
    return target.Property.ReflectedType == target.EntityType && target.Property.Name == "Parent";
  }

  public void Apply(IManyToOnePart target)
  {
     target.ColumnName("parent_id");
  }
}

The Mapping after the convention :

Clean and clear, the conventions themselves are not cluttering the Mapping. More importantly the conventions help me stay DRY.

public class CategoryMap : ClassMap<Category>
{
  public CategoryMap()
  {
    Id(x => x.Id);
    Map(x => x.Name);
    References(x => x.Parent).Cascade.All();
    HasManyToMany(x => x.Products).Inverse();
    HasMany(x => x.Children).Cascade.All().Inverse();
  }
}

Adding Mappings to my Persistence Model

You can see that adding the conventions was pretty easy and straight forward. This applies to the fact that I am using the PersistenceModel approach.

public class DataModel : PersistenceModel
{
  public DataModel()
  {
     AddMapping(new ProductMap());
     AddMapping(new CategoryMap());
     ConventionFinder.AddFromAssemblyOf<DataModel>();
   }
}

kick it on DotNetKicks.com

July 28, 2008

Specification Pattern and Lambdas

Filed under: .NET, Microsoft, Patterns, technology, web development — Tags: , , , , , — ang3lfir3 @ 9:51 pm

While working on my current project I decided that I had a need to use the Specification Pattern . After finding a clean implementation by Jeff Perrin I set to work creating the specifications that I needed. I quickly realized that we were going to end up having a ton of specifications and sometimes they would only apply to very special cases. Other times they would be very broad cases and they needed to be even more composable than even the fluid interface implemented in Jeff’s implementation wasn’t going to be enough. It after all still required me to create a concrete implementation for each specification, no matter how minuscule it might be.

This is the part where I thought to my self that since i was really only creating implementations for a single method that I could just write a LambdaSpecification and be able to use this for all the special cases I had.

Below is the LambdaSpecification Code:


using System;
using System.Linq.Expressions;

namespace Specification
{
    public class LambdaSpecification<T> : Specification<T>
    {
        private Func<T,bool> _expression;

        public LambdaSpecification(Func<T,bool> expression)
        {
             if(expression ==null) throw new ArgumentNullException(“expression”);
              _expression = expression;
        }

        public override bool IsSatisfiedBy(T obj)
        {
            return _expression(obj);
        }
    }
}

And the Tests:


[Test]
public void LambdaSpecification_CanExecuteSimpleLambda()
{
    var p = new Person() {Name = "Eric"};
    var spec = new LambdaSpecification<Person>(x => x.Name == "Eric");

        Assert.IsTrue(spec.IsSatisfiedBy(p));
}

[Test]
public void LambdaSpecification_CanExecuteComplexLambda()
{
    var p = new Person() {Name = “Eric”, Age = 28};
    var spec = new LambdaSpecification<Person>(x => x.Name == “Eric” &&
                                                                        new IsLegalDrinkingAgeSpecification().IsSatisfiedBy(x));

    Assert.IsTrue(spec.IsSatisfiedBy(p));
}

//Might Not be needed but I wanted to be sure
[Test]
public void LambdaSpecification_CanExecuteLambda_AndUseAndSpecification()
{
    var p = new Person() {Name = “Eric”, Age = 28};
    var spec = new LambdaSpecification<Person>(x => x.Name == “Eric” );

    Assert.IsTrue(spec.And(new IsLegalDrinkingAgeSpecification()).IsSatisfiedBy(p));
}

Comments are welcome and encouraged, especially if you see a reason why I shouldn’t be doing this. Or, if you have any ways to make this better, I would love to hear them. This is the first time I have ever used a lambda as a parameter in my own code and so far i am liking it.

Thanks to Jeff Perrin again for his post on creating a clean implementation of the specification pattern.

**EDIT: Thanks to Greg Beech for his input. I’ve updated the code to reflect his suggestions.

kick it on DotNetKicks.com

May 30, 2008

ASP.Net MVC , Visual Web Developer 2008 Express SP1 Beta

After reading ScotGu’s Blog post in regards to the recent drop of ASP.Net MVC Preview 3 I discovered that the express Edition of VWD (Visual Web Developer) 2008 should now have support for MVC projects with the improvements tht came from VSD SP1 Beta. Exciting I know! Actual support in Express editions of VS products.

I really want to give a big thank you to Phil Haack, Scott Hanselman, Scott Guthrie and the rest of the ASP.Net MVC team. The bit of screen shot below really shows the level of improvement coming from MSFT development teams. Additions like this were things we couldn’t have dreamed of before in Express additions and now… they are available to everyone to share in the MVC goodness. This particular team are definitely raising the bar on excellence and creating a new standard I hope other teams follow.

 

May 20, 2008

Dear Twitter, Scale or Die

Filed under: Argh, twitter, web development — ang3lfir3 @ 5:27 pm

As many of you may know twitter is a microblogging service (wow i hate that term) that enables users to have an interactive delayed conversation in 140 char increments. Each day the issue of scalability becomes increasingly worse. This pain stems from the rise in users and traffic from a number of applications using it’s API. From desktop apps to analytical web apps twitter is finding it ever harder to keep up.

The result of the current increase in twittages (twitter outages.. and yes i made that word up) is that users are begining to look for alternatives. Scott Koon aka LazyCoder wrote about it earlier today sighting FriendFeed as a possible alternative. And I can’t remember who it was who mentioned Pownce as another alternative (ironically via twitter)[Edit : I now know it was KeithElder ]. Other options like Jaiku exist and may take over the space.

Twitter is becoming old news. Their scaling issues are like cancer, spreading fast and consuming them entirely. This much is true…. Twitter MUST scale … or DIE…

 

March 26, 2008

Developing InfoPath 2007 Solution == Most Painful experience in my life

The title says it all!!! Well almost. For the last few days I have been banging my head on InfoPath 2007 as a platform for developing a solution. There are great many painful experiences in InfoPath 2007 as a development platform that I was already expecting (it is after all an Office product thus making it inherantly painful)¹ but I wasn’t expecting to have it just randomly crash VS any time I write a little code.

What I am trying to do, and hopefully someone smarter than me can tell me how, is to incorporate a custom dll into an InfoPath 2007 Template project in VS2005 AND be able to use that dll to do work on the Template (the library contains validation functions specific to US and I need it to be reusable). Now you might be thinking life was easy here, but let me through in a few wrenches…

We aren’t using the forms on machines that are NOT connected to our network. The Templates are published to machines that are in the field. No SharePoint,  No Forms Server, just templates and a mdb with the values for the drop down menus in it. Yup… each template comes with its very own personal copy of the database that contains nothing more than tables with values and labels for drop down lists. At a later date the data in the .xml files will be uploaded to a Database after being collected.

 Hopefully I have made it clear how these templates are being used (not my idea so i can’t provide any justifications)

So how does one use InfoPath 2007 to publish a template containing custom validation routines (complex enough that they need to be written in C#) that use a shared library and access fields on the form? WITHOUT THE WHOLE THING EXPLODING!!!! There are no examples that I can find anywhere of even developing with InfoPath in this sort of manner. I am not finding anything related to my issues on the team blog either.

Maybe I am missing something or simply just don’t get it…. what ever the case… hopefully someone can explain this to me…. cuz right now… I’m drowning.

HELP!!!

1) office applications in general always seem to have the goofiest API’s and worst documentation. If I just want to do something once and not become an expert in <Office_application_X_Development /> the pain is almost unbearable. It should be easy guys…. no really it should!

March 21, 2008

ASP.Net MVC Code on CodePlex

Filed under: .NET, ASP.Net MVC, Microsoft, technology, web development — ang3lfir3 @ 1:29 pm

Scott Hanselman just announced here that the ASP.Net MVC code was available on Codeplex.

Now you can download and mess with the ASP.NET MVC code all you want… more importantly you can become seriously familiar with its internals and offer suggests to the MVC team for everything from refactorings to spelling corrections in comments (if you really want to).

So … read Scott’s post and download the bits…. and get moving!!! The best part is you can build ASP.NET MVC yourself and have anything your heart desires in your own personal build!!! no more excuses about it not being in the framework :p

March 19, 2008

Time for a Theme Change.

Filed under: Argh, Blogging, technology — ang3lfir3 @ 11:48 am

I decided I HAD to change my theme today when I realized I was contributing to the one thing I dislike most on other blogs.   I realized that the dates for my entries were difficult to find and only located at the bottom of the post. That doesn’t make them very useful especially when often times what I might be commenting about could be information that changes in days/weeks/months. I find this a lot when I am looking for information regarding a topic. I will start googling and looking through blog entries of known bloggers like Scott Hanselman and Ayende Rahien only to find that on details for each entry the dates are only listed at the bottom of the entry, which could be a considerable distance to scroll. Leaving me to realize later that the information I was reading was out of date and potentially no longer accurate and that any links I followed may be stale.

I really like blog themes like Phil Haack’s and Jean-Paul Boodhoo’s where the dates are clearly displayed above each entry even in the detail view.

So I changed my theme to one that lists the complete date clearly. Anyone who manages to stumble along here should have a better idea now of when entries where made and what the potential validity of that information is.

March 12, 2008

ASP.Net MVC Framework, Give Me Rescues!

Filed under: ASP.Net MVC, Microsoft, technology, web development — Tags: , , , , — ang3lfir3 @ 2:45 pm

Having played with and loved MonoRail I was overjoyed when I learned about ASP.Net MVC ,(Yay!!! supported MVC Framework!). Now that Preview 2 is out I have been trying to find out as much as I can.

Having just gotten it installed on the laptop yesterday before bed (and having to actually work at work <sad/> ) I haven’t had time to play around too much. I have watched  ScottHa’s Demo at Mix08 and the videos from the ASP.Net site. One thing I didn’t see tho was anything the really and truly resembled the MonoRail idea of Rescues so I decided to see what others had done.

Rescues are a great concept that MonoRail uses to really allow me as the developer in an advanced scenario to make decisions about if I want to display something special to alert users about errors or not. They just feel clean and don’t require me to do a lot of “if/else” or “try/catch” which can dirty up the code real fast especially where catching different types of potential exceptions.

After a few minutes of searching I came across this blog entry . I am hoping this will inspire MSFT to possibly bake this into the framework. It might already actually be there and I just haven’t looked hard enough, but if it’s not I would love to really see it.  The post by Agile Joe does ceratinly show what a great job the guys on the MVC team have done so far to really make the framework very extensible.

I am really loving where ASP.Net MVC is going and certainly can’t wait for it to “go gold”. MVC has always been the way I have wanted to go with development (even in my work environment where webforms and auto-magical databinding are the norm) the seperation of concerns and testability of MVC make it so much more interesting to work with.

 So there you have it… my $.02 on Rescues and ASP.Net MVC

March 11, 2008

Blogging again and this time from Seattle.

Filed under: Seattle, Uncategorized — Tags: , , — ang3lfir3 @ 7:41 pm

After totally abandoning my blog for a few years or something like that (yeah i know I am odd). I decided I would start blogging again. Now that I live in the Seattle area and Commute to Seattle daily (the WSF employees are sadistic….but that is another story) I have some time on the boat every day to spend blogging.

I’ve left my previous job and am now working for the Fred Hutchinson Cancer Research Center. I’ve also droped VB.Net as my main programing language…. sad truth… the tools for C# are just better and more mature. That and C# always gets the kewl stuff first…. so I decided to join em.

So there you have it… thats my life in a nutshell. (at least the parts you need to know about).

August 1, 2006

Sandcastles aren’t just for kiddies anymore!!

Saturday Microsoft released the first CTP of Sandcastle…. and it works!!! So what is sandcastle? Well its a Documentation generation tool that uses reflection and XML comments to create awesome looking CHM documentation you can be proud to distribute with your assemblies.

After a few minutes with a little help from Ashley van Gerven’s Batch File OR Scott Hanselman’s powershell script you can be up and running since the instructions @ http://blogs.msdn.com/sandcastle/archive/2006/07/29/682398.aspx are just crazy. The Sandcastle team does mention on several occations that:

“For this CTP release our focus was on scalability and performance.”

Which is just fine by me (I totally approve actually, good work boys I prefer tools that work well and fast to “pretty” tools)…. Using Ashley van Gerven’s batch script I was producing beautiful MSDN style CHM’s for my assemblies that can easily be integrated into the build process in literally minutes. Even Continuous Integration builds. How cool is that!!!!

I found this entry in the FAQ to be probably one of the most instrumental reasons for me to truely consider integrating Sandcastle into my build cycle.

Is Sandcastle used by Microsoft for their API documentation?
Yes. This CTP version has a new architecture and has reduced the .Net Framework build time from 10 plus hours during VS 2005 ship cycle to 30 minutes. For the current CTP release the focus was on scalability and performance.

Have some fun and give Sandcastle a try even if you are already using similar tools like NDoc I still suggest trying it out…. if not for the meer pleasure of seeing it at work.

Download the CTP  here

Older Posts »

Blog at WordPress.com.