Friday, January 11, 2013

An Intro to MEF – Part 1

 

I’m a big fan of MEF (Managed Extensibility Framework). I think it is very easy to use and offers a lot of advantages when developing an application.  MEF was developed to be a framework to allow for extensibility in your applications.  Parts of Visual Studio (including the Entity Framework Designer) run on MEF as does the Extension Manager.  That being said, it also works very well as a Dependency Injection container. My goal is not to compare MEF to other containers (ie. Unity, Windsor Castle, NInject, etc) but to show you how to use MEF as a DI container.

As usual, you can view/download the code on GitHub.

For Part 1 we will create a simple console application that will log a message.  However, we will use MEF as a DI container to supply the ILogger implementation.  Remember, this is meant to be a very simple example.  It is definitely not meant to demonstrate how MEF should be used.

Monday, June 25, 2012

EF Entity Name Scrubbing - Part 1

Recently I've been working with a database that has some unusual naming conventions on its tables.  The naming convention consists of [(schema)_(tableName)] where 'schema' is used in place of an actual database schema.  An example is HR_Contact.  I'm not going to go into why it was done but rather what issues this presents when using the Entity Framework designer.

Here is the database that we will be working with:



As you can see, we have two HR_ tables and two IT_ tables.  When using the Entity Framework Designer several issues arise:

1. The Entities are imported with these names
2. Navigation Properties and References are created using these names
3. The Pluralization service can have issues figuring out what the appropriate pluralization would be

When you are dealing with such a small number of tables, this may not be a big deal.  But if you're dealing with 25, 50, even 75+ tables this can prove to be a real PITA.  This was such a problem that the owner of the database decided against using EF as it was too time consuming to rename everything.  Following you will see how to create an EF Designer Plugin that will do all of the scrubbing for you.

// NOTE : Before we get started, be sure that you have the Visual Studio SDK installed.  I'll be using Visual Studio 2012 RC so I'll be installing the SDK from here.

Let's begin by creating a new C# Project called EFEntityNameScrubberExtension:


Delete the default Class1.cs file and add the following assembly references:

  1. Microsoft.Data.Entity.Design.Extensibility
  2. System.Data.Entity.Design
  3. System.ComponentModel.Composition
Now create a new class called EFEntityNameScrubber and inherit from IModelGenerationExtension.  Additionally we will add two attributes to the class that will expose EFEntityNameScrubber as an IModelGenerationExtension plugin for MEF.  Your class should look like the following:

Next we will create a new VSIX Project called EFEntityNameVsix:


When the project is created a wizard will be displayed.  On the Metadata tab enter your name in the Author text box:



Under the "Install Targets" tab, add the Visual Studio versions that you will support.


Finally, under the "Assets" tab, add the EFEntityNameScrubberExtension project as a MefComponent:


Now that we have our VSIX project created and configured, set it as the Startup Project and add a few break points into the EntityNameScrubber class methods.  Once you hit F5 an Experimental Instance of Visual Studio will start up.  This can take a few minutes if it is the first time that you have used the Experimental Instance (EI).

Once the EI has started, create a new Console Application and add an Entity Data Model.  Choose the "Generate from Database" option and click Next.  Select the Sandbox database (or any database with the table prefix that we will try to create.  For now, simply add a single table to the model:












































When you click "Finish", the break point within the OnAfterModelGenerated method should be hit:









In Part 2 we will dig into the meat of the extension!

You can download the source on GitHub here.

Saturday, June 23, 2012

GetCustomAttributes Sucks

Ok so maybe the title of this post is a little harsh.  I don't really have anything against the MemberInfo.GetCustomAttributes.  I just don't like writing code like the following:


I'd prefer to do something like this:


Here is the source for the GetAttribute extension method:


You can download the full source (with tests) on GitHub here.

Saturday, June 2, 2012

Getting back to life

For those of you (aka most of you) who don't know me, I've spent the last 3 years working on a side project that really could have been amazing. IMO it failed for one primary reason: it was simply too big to be undertaken by a single developer. Now this could be viewed in a different light. If my business partner and I subscribed to a more agile methodology maybe we would have gotten something out. Maybe.

At the end of the day I'm writing this blog post for one reason... to celebrate my getting back to life! I effectively let my life go to hell. My social life was non-existent. My health went to crap. So...thank you jebus! I'm back!

Saturday, September 10, 2011

Intro to Expressions

I've been doing a lot of work with Expressions recently and completely love working with them. I feel that they allow your code to be more powerful as well as more expressive. It seems to me that many developers don't use Expressions in their code though. Maybe that is because Expressions can seem daunting. If this is the case I figured some of you might like a walk through of how you can use Expressions in your daily development.

What will we be building today? How about the beginnings a validation-helper for ensuring that a field, property, or argument is not null? How often have you written the following code?



Now this code is all good and well. But at some point we might change the name of the parameter but forget to update the string that represents the name of the parameter. Instead we can use an Expression which will dynamically get the name of the member which guarantees that the argument name provided to the ArgumentNullException constructor is always correct. So instead of using a string to represent the argument name, let's use an Expression:


Nice and simple! Now for some Expression basics.

Expression Basics

As seen on msdn the System.Linq.Expression namespace can be explained as follows:
The System.Linq.Expressions namespace contains classes, interfaces and enumerations that enable language-level code expressions to be represented as objects in the form of expression trees.

The abstract class Expression provides the root of a class hierarchy used to model expression trees.

The classes in this namespace that derive from Expression, for example MemberExpression and ParameterExpression, are used to represent nodes in an expression tree. The Expression class contains static (Shared in Visual Basic) factory methods to create expression tree nodes of the various types.

The enumeration type ExpressionType specifies the unique node types.

I think that's enough of that for now. Let's dive into some code.

Following is what our method might look like without utilizing Expressions.



As we will be passing properties, fields, and method parameters into our IsNotNull method, we will be dealing exclusively with Expressions of type MemberExpression.
The best tool in the Expression toolbox is the ExpressionVisitor. In a nutshell an ExpressionVisitor handles the navigation and of an ExpressionTree (which we will talk about in more detail in my next post).

To handle extracting the MemberExpressions from our ExpressionTree we will create an ExpressionVisitor and override the VisitMember method. The VisitMember method will simply add the MemberExpression to a SortedList instance. The reason for using a SortedList is that a single Expression Tree can contain many Expressions. In some scenarios the order of which the Expressions are extracted can be very important.Here is our CustomExpressionVisitor implementation:


Now that we have a method of extracting a MemberExpression, we can implement our IsNotNull(Expression>) method. This method must do the following:
  1. Extract the MemberExpression
  2. Extract the value of the property, field, or argument from the MemberExpression
  3. Check if the value is null
  4. If null, throw an ArgumentNullException

Here is the finished code for the Validate class:


And finally here is an example of how to invoke IsNotNull:


Source code can be downloaded from github here.
























Tuesday, February 15, 2011

Visual Studio Light Switch

As is typical for me I went to MSDN and saw a quick blurb about Visual Studio Light Switch. I had never heard of it before and so was interested to see what it was all about. Basically, it is a new platform for easily and quickly creating professional-quality business applications for the desktop, the web, and the cloud. I think it looks to be absolutely amazing! I'm not sure where they are going with it but I could definitely see Light Switch being a much more powerful (and much more professional-looking) replacement for ASP.NET Dynamic Data.

I have used Dynamic Data several times and have found it to be invaluable. That being said, it doesn't offer some of the integration with SharePoint and Office. Additionally, the look and feel of the Light Switch apps is really outstanding. Plus, you can use your Light Switch app on the web or on the desktop! That's just awesome!

If you haven't seen anything on Light Switch check out the website and click on "Watch Videos about Light Switch".

I really suggest watching the keynote video (50+ minutes) if you want to see some really powerful stuff!

Monday, February 14, 2011

Asshole Driven Development

Shai Raiten had a great blog post about A-s-shole Development.

"Driven development (ADD) – Any team where the biggest jerk makes all the big decisions is asshole driven development. All wisdom, logic or process goes out the window when Mr. Asshole is in the room, doing whatever idiotic, selfish thing he thinks is best. There may rules and processes, but Mr. A breaks them and people follow anyway."

I've worked with people like this before and almost fell out of my seat laughing when I saw this!