Software Rockstarhttp://www.softwarerockstar.com
Coaching and mentoring on a journey from a Developer to an IT LeaderMon, 22 Apr 2013 15:51:45 +0000en-UShourly1http://wordpress.org/?v=3.4.1Dependency Frameworks and Parameterized Constructorshttp://www.softwarerockstar.com/2012/04/dependency-frameworks-and-parameterized-constructors/
http://www.softwarerockstar.com/2012/04/dependency-frameworks-and-parameterized-constructors/#commentsTue, 24 Apr 2012 01:04:04 +0000SoftwareRockstarhttp://www.softwarerockstar.com/?p=747Most dependency injection frameworks support some kind of object initialization through parameterized constructors. The question is whether or not it’s a good idea to use that feature of DI frameworks.

When we use a DI container such as Unity or Castle Windsor to instantiate a Worker object, we must write some specialized code to pass in the constructor parameter (payLoad in our example). The problem I see with this is that since parameterized constructors can’t be mandated through interface IWorker, the code is only guaranteed to work with the default implementation of IWorker if one is provided. That’s pretty ugly, and pretty much defeats the purpose of using a DI framework. One of the key benefits of using a DI framework is that a new “implementation” can be “injected” into code at any time by only making subtle changes to the configuration.

The above code is not only more concise, but is also more portable. In the event when payLoad needs to be used by more than one Worker method, we can write create an explicit Initialize method to initialize the object. The code can be refactored as follows:

There are some very specialized instances when parameterized constructors need to be used in conjunction with DI frameworks, but those should be exceptions and must be used sparingly with deliberate intent.

Following are 5 easy steps involved in making your app plugin-ready using MEF:

Define an interface for plugins. This is the interface that each plugin must implement.

Define a metadata interface. This interface tells your app out of so many plugins which one is the correct plugin for a given piece of functionality.

Define one or more concrete plugin classes.

Decorate each class with some attributes.

In your app write a few lines of code to invoke MEF, and let the magic happen.

While it may not be very useful in the real world, let’s say that we have an extensible app that can write provided text to Console using different styles. For example input string of “style=warning|This is a warning!” will reproduce text “This is a warning” with red background and white foreground colors. Since our app is extensible we can create new style pluins at any time, place them in appropriate folder, and start using new styles without ever having to recompile our main app.

In order to achieve this, let’s first define an interface that all our plugins must implement:

public interface IStyledConsoleWriter
{
void Write(string text);
}

Since our app is extensible, we can have many plugins that implement IStyledConsoleWriter. How shall the code then know at runtime which plugin to use for which style? That’s super easy with MEF! All we have to do is define a metadata interface that will tell our code which plugin to load:

Once MEF does it’s magic, the _plugins variable will allow us to enumerate through all plugins and use the one suitable for our need. In order for MEF to do it’s magic we need to initialize it like this:

Essentially what we are doing in above code is that we are initializing MEF with plugins that are dynamically loaded from the same folder as our main app. Once the above code executes, our _plugins enumerable is initialized which we can query to find the plugin that we need to use using the metadata properties in IStyledConsoleWriterMetadata.

The above code queries our _plugins enumerable to find a plugin that implements the warning style. Once we find such plugin, we call it’s Write method to write to Console with that style. That’s it!

There is definitely much more you can do with MEF, but hopefully this will get you started quickly. If you would like to dig deep, you can refer to the official MEF documentation.

]]>http://www.softwarerockstar.com/2012/04/mef-easily-creating-plugin-apps/feed/1Finding Distinct Elements In A List(T)http://www.softwarerockstar.com/2011/08/finding-distinct-elements-in-a-listt/
http://www.softwarerockstar.com/2011/08/finding-distinct-elements-in-a-listt/#commentsThu, 04 Aug 2011 05:26:44 +0000SoftwareRockstarhttp://www.softwarerockstar.com/?p=676LINQ provides a Distinct() method, but in order to find distinct elements in a list of some target class, we must first implement the IEqualityComparer<T> interface in our target class. That’s what Distinct() uses in order to compute whether one element is the same as another element. Implementing IEqualityComparer<T>, however, is not so straightforward as it requires us to override Equals() and GetHashCode() methods. Most of the times if all we need to do is just to find non-duplicated elements in a given list, IEqualityComparer<T> route seems like an overkill.

So far so good! Now all we need is a list of distinct elements by, let’s say, FirstName (find all elements that have different first names). We can do that by first grouping our list by FirstName, and then selecting only the first element out of each group as follows:

Easy enough? Now let’s say we need to find out whether or not the list actually contains any duplicates to begin with. We can also do that easily by again grouping and then computing whether or not any of the groups contain more than 1 elements as follows:

]]>http://www.softwarerockstar.com/2011/08/finding-distinct-elements-in-a-listt/feed/2Texticize – String.Format on Steroids!http://www.softwarerockstar.com/2011/07/texticize-string-format-on-steroids/
http://www.softwarerockstar.com/2011/07/texticize-string-format-on-steroids/#commentsFri, 01 Jul 2011 16:42:35 +0000SoftwareRockstarhttp://www.softwarerockstar.com/?p=671I just released a new version of open source Texticize. Texticize is an extensible and intuitive object-to-text template engine for .NET. You can use Texticize to quickly create dynamic e-mails, letters, source code, or any other structured/unstructured text documents using predefined text templates substituting placeholders with properties of CLR objects at run-time.

]]>http://www.softwarerockstar.com/2011/07/texticize-string-format-on-steroids/feed/0Complex Object Mapping Using AutoMapperhttp://www.softwarerockstar.com/2011/05/complex-object-mapping-using-automapper/
http://www.softwarerockstar.com/2011/05/complex-object-mapping-using-automapper/#commentsTue, 31 May 2011 03:39:23 +0000SoftwareRockstarhttp://www.softwarerockstar.com/?p=654AutoMapper is an awesome open source library that allows automatic object-to-object mapping. There are various getting-started blog posts and articles on the web (e.g. Getting Started Guide and AutoMapper on CodeProject) that will get you started with AutoMapper. I was recently challenged with a particular situation using AutoMapper that wasn’t immediately clear and took me a little investigating and some trial and error work, so I will share that with you.

My source object exposed some simple properties as well as a generic List property of another type. My target object had same simple properties, but the generic List property was of an interface type. Following is a simplified illustration of my source and target objects:

Source Object

Target Object

A cool thing about AutoMapper is that when it encounters a target object of an interface, it automatically generates a dynamic proxy class using Castle Dynamic Proxy. This is usually the desired behavior when mapping to a non-existent target class. In my case, however, the target class already existed, and dynamic proxy was just an overhead. I tinkered with AutoMapper mappings to actually map to my existing target rather than generating a proxy:

Essentially what I am doing in my mapping is to first create a map between my source and target Orders objects. Once that’s done, I create a map between my source and target Customer objects but provide a custom map for the Orders property. In my custom map I simply use AutoMapper to map my source Orders property to target Orders property using the map definition I provided earlier (lines 1-2 above). This works out great and I get my expected target object without incurring the overhead of expensive proxies.

]]>http://www.softwarerockstar.com/2011/05/complex-object-mapping-using-automapper/feed/15-minute No-nonsense Intro to Windows Azurehttp://www.softwarerockstar.com/2011/02/why-windows-azure/
http://www.softwarerockstar.com/2011/02/why-windows-azure/#commentsThu, 17 Feb 2011 03:30:05 +0000SoftwareRockstarhttp://www.softwarerockstar.com/?p=639I just came across this excellent introduction to Windows Azure from a developer’s perspective. I hope you will enjoy.

The first version of Entity Framework was introduced with .NET Framework 3.5 SP1 and Visual Studio 2008 SP1. While the intention was great, most of everyone that I know, including my own self who have ever tried using EFv1 for anything except trivial data access have developed a love-and-hate relationship with it. The first version looked great at first, but turned out to be an immature product at best with severe restrictions as well as quite a few bugs.

With .NET 4 Microsoft released a new version of Entity Framework that has addressed many of the issues and made it a much more stable technology. Amongst other things, Microsoft heard developer community at large and provided POCO support in EFv4.

POCO Support – At Last!

The biggest problem with EFv1 was that the domain classes had to be tightly integrated with EF. Essentially these classes were generated from entity models and developers had no control over code generation. This limitation didn’t fly very well with most developers, since we like to keep our domain classes generic enough to where we can easily migrate them to any underlying data access technology. This is especially true since the data access technologies tend to change every so often.

In EFv4 Microsoft has gone to great lengths to support Plain Old CLR Objects (POCO), which is just a fancy name for simple .NET classes with properties that can be used as Data Transfer Objects (DTO) or simply Domain Objects.

POCO classes can be handwritten and easily hooked in to EFv4. Better yet, EFv4 allows us to generate these classes based on our entity models. Also we have complete control over code generation since EFv4 uses T4 templates. Speaking of T4 templates, they can also be used to generate ObjectContext classes for our entity models.

Lazy Loading, Explicit Loading, and Eager Loading

In EFv1 the only way to automatically load related entities was using eager loading. Essentially eager loading is a LINQ technique that allows loading related entities in one shot using the Include method on the LINQ query.

EFv4 allows for lazy loading on POCO’s. The only requirement for this added functionality is that navigation properties on POCO’s be marked as virtual and LazyLoadingEnabled property of ObjectContextOptions be set to true. The way EFv4 does this is very cool. Essentially it generates dynamic proxies overriding the virtual properties on POCO’s and uses those proxies instead of the POCO classes at runtime.

In addition to eager and lazy loading, EFv4 allows explicit loading of related entities. Explicit loading allows us to explicitly load related entities on demand whenever the need arises. Using explicit loading is as easy as calling the LoadProperty method of the ObjectContext using the parent entity as well as the navigation property name as parameters.

Change Tracking

EFv4 supports two different types of change tracking which are as follows:

Snapshot Change Tracking. Using this kind of change tracking is more efficient in most cases but it might require a few additional lines of code. When using snapshot change tracking (default behavior in EFv4), the developer must make explicit call to ObjectContext’s DetectChanges method in order for the EF change tracker to notice any data that has been changed on the entity since it was first retrieved. Also calling the SaveChanges method of the context automatically detects any changes to entities involved.

Real-time Change Tracking. Using real-time change tracking the tracker keeps track of all data changes to entities in real-time. For real-time change tracking to work for POCO’s, all properties of POCO’s should be marked as virtual. Also any navigation properties should have return types of ICollection<T>. Once these two conditions are met, EFv4 automatically generates dynamic proxies and uses them instead of the POCO’s and tracks changes made to data contained within those entities in real time.

Design Techniques

EFv4 allows a couple of different design techniques that ought to satisfy most situations.

Model First. For new projects where that database design is not already set in stone or is non-existent, model-first approach is more natural to most developers and makes a lot of sense. What this entails is that the developer creates an entity model using the Entity Model Designer for the domain objects involved. This model can be easily changed during the design phase or the early development stages. Once the architect/developer is happy with the entity design, he/she can use EFv4 to generate the data model using EFv4’s Data Definition Language (DDL) generation capabilities. Not only that this is a more natural way of designing data access and domain model for a given solution, it’s more agile in that the model can easily be modified using a GUI tool. Also as long as the underlying database is supported by EFv4, the developer need not worry about the exact syntax of the DDL as it can automatically be generated. Once again the generation of DDL can be influenced using T4 templates.

Database First. This technique is more suitable for when a project involves an existing database. In such cases EF can easily generate domain models based on database schema. This design technique is not new to EFv4 as it has been available since the first version of EF and this is probably what most of us are most familiar with.

Code Only. EFv4 introduced another design technique which requires no models to be created. Essentially there are only code classes and EF infers the model from them. Entire database including all required tables can be generated by EF at run-time.

There’s a lot more to EFv4. What I have covered in this article only addresses a bit of POCO support in EFv4 since that has been the number 1 request of the development community since EFv1 was released.

]]>http://www.softwarerockstar.com/2011/01/poco-in-ado-net-entity-framework-4/feed/0Simplify N-tier Development with WCF RIA Serviceshttp://www.softwarerockstar.com/2011/01/simplify-n-tier-development-with-wcf-ria-services/
http://www.softwarerockstar.com/2011/01/simplify-n-tier-development-with-wcf-ria-services/#commentsFri, 14 Jan 2011 18:59:36 +0000SoftwareRockstarhttp://www.softwarerockstar.com/?p=619Last night I was at Dallas .NET User Group meeting where Tony Sneed of DevelopMentor made a presentation on WCF RIA Services called “Turbocharge Silverlight Development with WCF RIA Services“. I had read about this new technology before, but never had the time to play with it.

The presentation turned out to be pretty cool. I think WCF RIA Services provides a very neat way to design n-tier apps without much hassle as it takes care of much of the heavy lifting for you providing very easy data validation, authentication, and role-based security amongst other awesomeness. Also through code projection it automatically allows shared code between UI and the service tier, which makes it easy to write code once and use it cross-tier. While WCF RIA Services can be used with any front-end, e.g. WinForms and ASP.NET, it really shines when combined with a Silverlight front-end. The best part of the technology is automatic batch updates, which is really neat.

]]>http://www.softwarerockstar.com/2011/01/simplify-n-tier-development-with-wcf-ria-services/feed/0An Elegant Way to Implement ReadOnlyDictionary(TKey, TValue) in C#http://www.softwarerockstar.com/2010/10/readonlydictionary-tkey-tvalue/
http://www.softwarerockstar.com/2010/10/readonlydictionary-tkey-tvalue/#commentsSat, 30 Oct 2010 05:23:24 +0000SoftwareRockstarhttp://www.softwarerockstar.com/?p=569While working on creating an application framework for a personal project, I needed a way to expose a Dictionary<TKey, TValue> object from one of my methods. The only caveat being, I wanted the Dictionary object to be read-only.

I knew that there exists a ReadOnlyCollection<T> in the FCL, but to my dismay there is no built-n way of creating a read-only Dictionary in .NET. I searched the web to see how other people are solving this problem, but didn’t find a suitable implementation that I was happy with. Hence I created a nice little ReadOnlyDictionary<TKey, TValue> that essentially allows developers to expose an immutable Dictionary object of specified key and value types.

As you can see the class itself is very concise. This is because it cleverly derives from ReadOnlyCollection<KeyValuePair<TKey, TValue>>, and only adds two methods and an indexer. Also it uses LINQ to Objects to select Dictionary items, and the LINQ query is neatly tucked in a private method where it’s re-used from other public methods.

U.S. Patent and Trademark Office (USPTO) recently granted Microsoft a patent on a “personalized version” of the sudo command with GUI. Sudo is a command that has been in use since 1980′s or even before by Unix and other operating systems to allow running other commands with elevated privileges. For one, why would Microsoft try to patent something like this? Secondly, does USPTO grant patents on anything you ask them for?

We are witnessing a time in the history of technology when there is more free (open source or otherwise) software available than anyone ever cares to know, and it’s increasing at a higher rate than anyone can even keep track of. For any application that one can conceivably imagine, chances are that there is a free alternative out there. Why in the world then a company such as Microsoft would patent tiny things such as sudo commands, especially when they “borrowed” the original idea from elsewhere anyway? On one hand we see companies like Google releasing entire programming languages into open source, and on the other hand companies like Microsoft acquiring patents on simple sudo commands… we live in truly amazing times don’t we!

Groklaw has much more detailed information on this story. You can also find the original Microsoft patent at the USPTO here.