Month: March 2010

Coding a plug in and using LINQ:


Few time ago I’ve created a post where I used LINQ to load  a plug in. At this time I have learned how to improve some aspects of this original idea. It’s possible to make a lot of improvements, however I’m only make a simple change.. However in my previous post I didn’t provided any code (only a couple of screen shots, so now I’ve the chance to add formatted code 😉 in wordpress ).

The following some notes about this sample:

  • I think it’s possible to use threads for loading the files, so it won’t freeze the application in order to load the files.
  • If you’re using .NET 3.5 on Windows, you might consider to use PLINQ (I’m not sure if it’s feasible).
  • The sample assumes that the concrete implementations of the plugins have a parameterless constructor.

Sample.CustomPlugin.Api is a dll project. This project contains the file IPluginInfo.cs.  It’s an interface that defines the contract that the plugins must implement. It is allocated in a separated dll project in order to distribute the contract to third parties.

using System;
namespace Sample.CustomPlugin.Api
 public interface IPluginInfo
 string Name {get;}
 string Description {get;}

Sample.CustomPlugin.Api.Apple and Sample.CustomPlugin.Api.Cherry are two separated dll projects. For each project there is a implementation of the Plugin contract.The implementations are ApplePlugin.cs and CherryPlugin.cs respectively.

<pre>using System;
using Sample.CustomPlugin.Api;

namespace Sample.CustomPlugin.Api.Apple
 public class ApplePlugin : IPluginInfo
 public string  Name { get {return @"Apple tm"; }}
 public string Description {get {return @"This is the Apple plug in!";}}


using System;
using Sample.CustomPlugin.Api;

namespace Sample.CustomPlugin.Api.Apple
 public class CherryPlugin : IPluginInfo
 public string  Name { get {return @"Cherry OpenPlugin"; }}
 public string Description {get {return @"This is the Cherry OpenPlugin in!";}}


Sample.CustomPlugin is the application project. This only references the Sample.CustomPlugin.Api project that defines the contract. The other two dlls will be loaded dynamically by the main application. These give us the chance of changing the implementation of the the others dlls without recompiling the entire application.

These is the main routine in charge of loading dynamically the dlls:

public static IEnumerable<IPluginType> PluginLoaderFor<IPluginType>(string pluginDirectory, string fileFilterPattern, bool hasToCheckIntoSubDirectories) {

	string interfaceName = typeof(IPluginType).Name;
	string[] files = null;

	fileFilterPattern = String.IsNullOrEmpty(fileFilterPattern) ? @"*.dll" : fileFilterPattern;
	pluginDirectory = Directory.Exists(pluginDirectory) ? pluginDirectory : Environment.CurrentDirectory;
	files = Directory.GetFiles(pluginDirectory,fileFilterPattern,hasToCheckIntoSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
Console.WriteLine(String.Format("Plugin Path Expression: {0}{1}.\nThere are {2} files has been found.",pluginDirectory,fileFilterPattern,files.Length));
          from filename in files
	      where File.Exists(filename)
			  from type in Assembly.LoadFile(filename).GetTypes()
			  where type.IsClass && !type.IsAbstract && type.GetInterface(interfaceName) != null
			  select (IPluginType)Activator.CreateInstance(type);
public static void Main(string[] args)
	var plugins = PluginLoaderFor<IPluginInfo>(string.Empty,string.Empty,false);
	Console.WriteLine("There're {0} implementations for {1}", plugins.Count(), typeof(IPluginInfo).Name);
	if (plugins!=null)
		foreach (var pluginInfo in plugins)
			Console.WriteLine("PluginInfo Name: {0} Description: {1}", pluginInfo.Name,pluginInfo.Description);

Today I was kinda bored so I decided to code this in monodevelop to see if it works as same as visual studio… and indeed it happened smoothly. Here is the source code for this sample: Herberth


Windows Mobile Notes


People from Coding4Fun (@ )has sent this list of very nice resources to get started with Windows Mobile Phone Development.

A really nice link collection,


Windows Mobile 7 Silverlight or XNA?


You might be wondering why there are two programing models for Window Mobile 7. Well, it’s simple it’s because each model satisfy a different need.
The following link contains a table comparing general capabilities in both frameworks (XNA and Silverlight)


Implementing a Plug-in Loader in C# (Using Unity)


In my old post I explained a way for implementing plug-in with reflection and IO file operations, and Indeed this is one way for doing it. Currently there are frameworks that can simplify this kind of tasks, and these frameworks are more flexible. Here there are two of frameworks:

Microsoft Extensibility Framework (@

From codeplex site:

“MEF presents a simple solution for the runtime extensibility problem. Until now, any application that wanted to support a plugin model needed to create its own infrastructure from scratch. Those plugins would often be application-specific and could not be reused across multiple implementations.

  • MEF provides a standard way for the host application to expose itself and consume external extensions. Extensions, by their nature, can be reused amongst different applications. However, an extension could still be implemented in a way that is application-specific. Extensions themselves can depend on one another and MEF will make sure they are wired together in the correct order (another thing you won’t have to worry about).
  • MEF offers a set of discovery approaches for your application to locate and load available extensions.
  • MEF allows tagging extensions with additonal metadata which facilitates rich querying and filtering”

Unity (@

From codeplex:

“The Unity Application Block (Unity) is a lightweight extensible dependency injection container with support for constructor, property, and method call injection.

Unity addresses the issues faced by developers engaged in component-based software engineering. Modern business applications consist of custom business objects and components that perform specific or generic tasks within the application, in addition to components that individually address cross cutting concerns such as logging, authentication, authorization, caching, and exception handling.

The key to successfully building such applications is to achieve a decoupled or very loosely coupled design. Loosely coupled applications are more flexible and easier to maintain. They are also easier to test during development. You can mock up shims (lightweight mock implementations) of objects that have strong concrete dependencies; such as database connections, network connections, ERP connections, and rich user interface components. ”

So, are they the same framework?

Although both frameworks struggle to allow a better application extensibility, their attack the problem from different fronts. And of course, each framework has their own set of concepts.

Let prepare a quick plug-in with unity

Before continuing, I’d like to clarify that this is only one approach for using unit, I can bet that there might be more interesting implementations, however mine is really good for getting started ;-). BTW, I’m doing this sample based on this article @ I’m going to try to sum up all the step I’ve followed to create this (Unity) plug in. At the end of the post (or sample) the source code will be published for download.

Project Structure

The following are the projects that have been created, and the (relevant) files that each project contains.

Sample.UnityPlugin This is the default project (in this case a console application). This project uses the plug in implementation, although it does not need to know how is the concrete implementation, this project only references to the Sample.UnityPlugin.Contracts.
Sample.UnityPlugin.Contracts This project contains common content between the plug in contract and the plug in implementation. This common content is an interface (aka Contract) which defines what the plugin must provide. This project is referenced by the two parts, the first part if the part of the application that will implement the functionality of the plug in. The second part is the part of the application that will be using the implementation of the plug in.
Sample.UnityPlugin.Cocoa This project represents the plug in implementation. It references to the Sample.UnintyPlugin.Cocoa in order to know the plugin’s contract.

Now,  lets prepare some references:
Sample.UnityPlugin needs to reference the Microsoft.Practices.UnityMicrosoft.Practices.Unity.Configuration, Sample.Unity.Contracts.
Sample.UnityPlugin.Cocoa only needs to reference to Sample.UnityPlugin.Contracts.

Defining the Plug in Contract

To implement our plug in lets start by defining the Contract (interface) in our Sample.UnityPlugin.Contracts project. The following is the contract file:

namespace Sample.UnityPlugin.Contracts
    public interface IProvider
        object Connection { get; }
        string Name { get; }

The IProvider only defines a “Connection” and a Name. Really simple, isn’t ?

Implementing the plug in

The concrete implementation of the plug in will be in the Sample.UnityPlugin.Cocoa (sorry, I was thinking in a Cocoa provided when I wrote this). So, our concrete implementation will be:

using Sample.UnityPlugin.Contracts;

namespace Sample.UnityPlugin.Cocoa
    public class Provider : IProvider
        public Provider(string providerName)
            this.Name = providerName;

        public object Connection { get; set; }

        public string Name { get; set; }

As you might notices the implementation references the contract (aka interface), and implements the behavior for this contract.

Consuming the plugin

Now lets add the unity.config file to the Sample.UnityPlugin application. The Unity configuration can be loaded from a configuration file, o being set by code.

<?xml version="1.0" encoding="utf-8" ?>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
      <typeAlias alias="string" type="System.String, mscorlib" />
      <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
      <typeAlias alias="IProvider" type="Sample.UnityPlugin.Contracts.IProvider, Sample.UnityPlugin.Contracts" />
      <typeAlias alias="Provider" type="Sample.UnityPlugin.Cocoa.Provider, Sample.UnityPlugin.Cocoa" />
      <container name="container">
          <type type="IProvider" mapTo="Provider" >
            <lifetime type="singleton" />
            <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
                <param name="providerName" parameterType="string">
                  <value value="The big Cocoa Provider (tm)"/>

In a quick review this configuration file is in charge of making the connection between contract and the concrete implementation, by doing it in a configuration file.
It can be changed any time (by providing the correct files). Please, notices that the configuration file is able to call the Provider constructor and send custom values to it.
Also the application is able to label relations between contracts and implementations, and group them into a container, which can be labeled too.
The last comment is about the location of this file, this file uses Configuration API, so it can be referenced indirectly by your app.config (or web.config), however in this sample it’s being loaded
and referenced directly in the code.

Now lets write our main code that will load the plug in:

using System.Text;
using Microsoft.Practices.Unity;
using System.Configuration;
using Microsoft.Practices.Unity.Configuration;
using Sample.UnityPlugin.Contracts;

namespace Sample.UnityPlugin
    class Program
        private static IUnityContainer GetContainer()

            var map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = "unity.config";
            var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            var section = (UnityConfigurationSection)config.GetSection("unity");
            var container = new UnityContainer();
            return container;

        static void Main(string[] args)
            IUnityContainer container = GetContainer();
            var myProvider = container.Resolve<IProvider>();
            System.Console.WriteLine("Provider Name:{0}", myProvider.Name);

Get container function will load our custom plugin, and the main function will make use of it.
At this time, this post is quite big, and certainly there is more things that unity can do. I’ll try to provide a plug in implementation using MEF, but in my next post 😉

BTW, I almost forgot … here is the source code (Visual Studio 2010 and Unity 2 beta)

Microsoft book for Windows Mobile 7


Microsoft press is giving a free preview of the Microsoft Book for Windows Mobile 7. Check it at:

Article (and download)

Online preview

Getting started with Silverlight and Pixel Shader 02

Getting started with Silverlight and Pixel Shader 02

See an update about my project at

I’ll continue this thread about my experience while I’m trying to create an installer for Expression Blend 3 for adding custom (pixel shader) effects. So let’s get started. First of all we need to write shaders… hm… I’m not really good writing pixel shaders I’ll be using the pixel shaders from , unfortunately the last updated is based on the SL3 beta. If you want I’ll be indicating the updated source code so you can skip all this ‘update comments”. First I’ve download the ‘Mar 25 2009’ release.

Pre requisites:

Just check the first part @

As far as I remember these products were installed when I started this journey.

  • Visual Studio 2008 SP1
  • Expression Blend 3
  • Silverlight SDK
  • Silverlight Toolkit
  • Shader Effects BuildTas Template

I think this last product requires XNA Framework SDK or Direct X SDK, however I’m not quite sure because of I have them already installed.

Getting the Windows Presentation Foundation Pixel Shader Effects Library
You can download the WPF FC  from codeplex at (please notices that I’m providing a link to a particular build, not the latest).  The project in is ‘Windows Presentation Foundation Pixel Shader Effects Library’ at Once you have gotten the WPFFX and try to compile it. If it compiles then go ahead to the next section (where it’s the link to my CodePlex Project Xhader)

Trouble shouting  (the previous post also has some trouble shouting items).

The “ShaderBuildTask.PixelShaderCompile” task could not be loaded from the assembly ShaderBuildTask, Version=1.0.3072.18169, Culture=neutral, PublicKeyToken=44e467d1687af125. Could not load file or assembly ‘ShaderBuildTask, Version=1.0.3072.18169, Culture=neutral, PublicKeyToken=44e467d1687af125’ or one of its dependencies. The system cannot find the file specified. Confirm that the declaration is correct, and that the assembly and all its dependencies are available.

You will have to install the “Shader Effects BuildTask and Template”. The project is in codeplex at . Please read the readme file about how to install it appropriately. Also you will know how to create projects that uses pixel shaders.For additional information about this build task

The type or namespace name ‘Theming’ does not exist in the namespace ‘System.Windows.Controls’ (are you missing an assembly reference?) MainPage.xaml.cs 13 31 SLEffectHarness

You will have to install the “Silverlight Toolkit”.I downloaded (July 2009 release). Once It has been installed, you can copy the assemblies to a folder in your solution or use the assemblies in the default installation folder. The important thing here is to update the references.

The name ‘PixelFormats’ does not exist in the current context MainPage.xaml.cs 57 148 SLEffectHarness

Basically breaking changes for the SL3.3.19 WriteableBitmap changes The PixelFormat parameter for the WriteableBitmap constructor has been removed. WriteableBitmap(int pixelWidth, int pixelHeight, PixelFormat format) is now WriteableBitmap(int pixelWidth, int pixelHeight). The only supported PixelFormat is now Pbgra32.Similarly, the PixelFormat and PixelFormats type has been removed.Lock() and Unlock() have been removed.”From

The tag ‘Expander’ does not exist in XML namespace ‘clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls’. MainPage.xaml 225 10 SLEffectHarness

The tag ‘Viewbox’ does not exist in XML namespace ‘clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls’. MainPage.xaml 314 13 SLEffectHarnessUpdate the namespace and assembly where the controls are stored.Add a reference to the dll ‘System.Windows.Controls.Toolkit.dll’.After xmlns:ctls=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls” Add the following namespace:xmlns:ctrlsToolkit=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit”Replace all the ‘ctls:Expander’ with ‘ctrlsToolkit:Expander’Replace all the ‘ctls:Viewbox’ with ‘ctrlsToolkit:Viewbox’Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.Parser Error Message: Could not load file or assembly ‘System.Web.Silverlight’ or one of its dependencies. The system cannot find the file specified.

If you run your web project and then this error comes up. To solve this, remove the Silverlight reference from the properties in your web project.  Then remove all the Silverlight pages, and JavaScript’s for Silverlight, and the ClientBin folder too. Then re add the silverlight project by using the silverlight tab in the web project properties.

At last set the ‘Start up page’.System.Windows.Markup.XamlParseException occurredMessage=”Invalid attribute value SearchMode for property Property. [Line: 5772 Position: 26]”LineNumber=5772LinePosition=26StackTrace:at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)at SLEffectHarness.App.InitializeComponent()at SLEffectHarness.App..ctor()InnerException:– OR –System.Windows.Markup.XamlParseException occurredMessage=”Invalid attribute value controls:Expander for property TargetType. [Line: 6281 Position: 45]”LineNumber=6281LinePosition=45StackTrace:at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)at SLEffectHarness.App.InitializeComponent()at SLEffectHarness.App..ctor()InnerException:XamlParserExceptions are thrown because of there are a couple of Xaml syntax outdated.Remove the setter tag for the ‘SearchMode’ property from the following files:…\WPFSLFx\WPFSLFx\SL\Demo_silverlight\SLEffectHarness\ShinyBlue.xaml(5772)…\WPFSLFx\WPFSLFx\SL\Demo_silverlight\SLEffectHarness\System.Windows.Controls.Theming.ShinyRed.xaml(5738)

Update namespace controls:Expander and controls:Viewbox. Remember first we need to add the ‘xmlns:ctrlsToolkit’ namespace, and then we replace the old namespace with this new one. These are the files:

  • …\WPFSLFx\WPFSLFx\SL\Demo_silverlight\SLEffectHarness\ShinyBlue.xaml(6281)
  • …\WPFSLFx\WPFSLFx\SL\Demo_silverlight\SLEffectHarness\ShinyBlue.xaml(6286)
  • …\WPFSLFx\WPFSLFx\SL\Demo_silverlight\SLEffectHarness\System.Windows.Controls.Theming.ShinyRed.xaml(5997)
  • …\WPFSLFx\WPFSLFx\SL\Demo_silverlight\SLEffectHarness\System.Windows.Controls.Theming.ShinyRed.xaml(6002)

Error: Unhandled Error in Silverlight ApplicationCode: 4004Category: ManagedRuntimeErrorMessage: System.InvalidOperationException: Collection was modified; enumeration operation may not System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()at System.Windows.FrameworkElement.NotifyDataContextChanged(DataContextChangedEventArgs e)at System.Windows.FrameworkElement.OnTreeParentUpdated(DependencyObject newParent, Boolean bIsNewParentAlive)at System.Windows.DependencyObject.UpdateTreeParent(IManagedPeer oldParent, IManagedPeer newParent, Boolean bIsNewParentAlive, Boolean keepReferenceToParent)at MS.Internal.FrameworkCallbacks.ManagedPeerTreeUpdate(IntPtr oldParentElement, IntPtr parentElement, IntPtr childElement, Byte bIsParentAlive, Byte bKeepReferenceToParent)Source File: http://localhost:36397/Default.htmlLine: 54

This is a very unusual exception. Unfortunately I haven’t been able to solve it. However I’ve noticed some scenarios that trigger this exception.Make sure you have installed Silverlight Runtime 3.0.40818.0 instead of 3.0.40624.0The error is very a constant in Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv: Gecko/20090729 Firefox/3.5.2 GTB5 (.NET CLR 3.5.30729). Internet explorer and Chrome does not fail after updating Silverlight Runtime.If you run the application in ‘Release’, the issue is not triggered.

Error 6 The “PixelShaderCompile” task failed unexpectedly.System.NullReferenceException: Object reference not set to an instance of an ShaderBuildTask.PixelShaderCompile.Execute()at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult) WPFTransitionEffects.csproj 139 5 WPFTransitionEffectsUnfortunately I don’t why this happens, it’s solved by closing and reopening the visual studio.

At this time the project should compile and you should be able to see the samples running. If you didn’t want to do all this work you might try to download my updated code from:

My code that sum up all this tricky work, my code has been posted at:



Google Apps Engine: Thinking in the Cloud


I still working on learning Google Application Engine (w/ Python) and understanding how the cloud differ from the “normal” web app.

There is no such as a server for your application, so your app will be hosted in many (virtual or physical.. not sure yet) different servers.

There is no server: It’s a cloud!

I think planning is the key for the success of an Cloud Application. Certainly you already know the speech about the importance of planning and designing your application. The fact is that the design and architecture for cloud applications is quite different from a regular applications, for example Google App have restrictions about response time for (web) requests, or the amount of data that can be fetch from the data storage per query. These practices are in favor of creating scalable applications, but they change the playground.

The tight relation between performance and price

The second aspect about the Cloud application is about the performance. Certainly developers do their best for creating well-performed applications. However, not all the applications are thought in this way, and the Cloud is going to charge you for your resource consumption. This means that if you can do all your work with less resources it might cost less in long term.

One cloud for each need: Read the fine print

Other important aspect is the “kind of cloud‘ that you are buying. For example, Amazon offers services for storage, so they might charge you for bandwidth and the storage, I think this service is S3 from AWS. ( see ).  Also, Amazon offers EC2, which is based on processing, and their charge you for CPU time consumption In this quick sample both services are easy to set up, but they are oriented to different needs. If your application exceeds your quota Amazon services are able to auto upgrade your plan. It’s important to notices that Amazon is capable of charging you in two different plans, your regular plan and the the exceeded quota  in a different plan.

On the other hand, Google’s Cloud ( sets a quotas for different services based on a plan, for example a plan defines a limit for storage, CPU, etc. The Google’s could does not increase your quota automatically; If you reach your quota, then the system will deny the additional requests until the next period starts.

Just because of I’m a Microsoft Developer I’ll mention that Microsoft also has its Cloud services. Sadly, I haven’t done anything on it yet, so you can check their capabilities at

NoSQL, and scalable databases: Think in bigger things!

This is other interesting thing about data storage in the cloud. Developers are very used to ER Databases (, however in the Cloud you might find other kind data storage. It’s a model called NoSQL (, and it’s used for some Clouds such as Google and Amazon clouds. These NoSQL implementations can vary among clouds. Sadly, I’m not sure if Microsoft has implemented this NoSQL model yet. (BTW, thanks to David Mora for the talks about NoSQL).

Does the cloud  speak any language?: The language of the Cloud

This might not be a critical point. It’s important to notice that depending of the cloud you would like to use, this might define a set of tools (or languages)  to be used for development in your application. For example Google application engine is currently targeting Java (  and python ( Even though it normal to think that both languages should be equivalent, they’re not!.  So, Googlers are trying to keep both with the same capabilities, but from time to time you might be able to do things in one language easier than the other language.

While (true) {Print this.Read(CloudCollection)}

This so far represents some basic thoughts about the Cloud versus the traditional server-hosted applications. My best advice is to check the capabilities of each platform to see if it fits your needs (and budget 😉 ).