in

ASP.NET Weblogs

Zubair.NET!

  • Getting started with Managed Extensibility Framework (MEF)

    Recently I got a chance to work with WordPress and Drupal, those are the coolest PHP based blogging and content management systems out there, while I was impressed with the simplified installation and configuration, one thing that struck me was how simple it is to add plugins to the system. For instance I wanted a photogallery, so I downloaded the plug-in from WordPress.com, unzipped, dropped it in the plugins folder, went to the Administration panel and there it was, the plug-in sitting right there ready to activate.

    Fortunately .NET now gets its own plug-in architecture framework in the form of Managed Extensibility Framework or MEF.

    MEF makes it really easy to build extensible .NET applications with just a few lines of code.

    Here’s how. 

    In the application that needs to be extended you define a common interface that your plugins can implement.

       1:  public interface IRule   
       2:  {   
       3:      void DoIt();   
       4:      string Name { get; }   
       5:      string Version { get; }   
       6:      string Description { get; }   
       7:  }

    Then you make a collection where all the plugins are stored and mark it with Import or ImportMany attribute.

       1:  [Import( typeof( IRule ) )]   
       2:  internal IList<IRule>: _rules { get; set ;} 

    Then all you need to do is write your plug-in that implements the above IRule interface that you defined in your extensible application and mark it with Export attribute.

       1:  [Export( typeof( IRule ) )]   
       2:  internal class RuleInstance1 : IRule   
       3:  {   
       4:      public void DoIt() {}   
       5:    
       6:      public string Name   
       7:      {   
       8:          get { return "Rule Instance 1"; }   
       9:      }   
      10:    
      11:      public string Version   
      12:      {   
      13:          get { return "1.0.0.0"; }   
      14:      }   
      15:    
      16:      public string Description   
      17:      {   
      18:          get { return "Some Rule Instance"; }   
      19:      }   
      20:  }   
      21:    

    With that only a few lines of code is required to load the plug-in into your extensible application.

       1:  public void Init()   
       2:  {   
       3:      var catalog = new AggregateCatalog();   
       4:      var container = new CompositionContainer( catalog );   
       5:      var batch = new CompositionBatch();   
       6:      batch.AddPart( this );   
       7:      // because all our types are in the same assembly we simply use the current one.       
       8:      catalog.Catalogs.Add( new AssemblyCatalog( Assembly.GetExecutingAssembly() ) );   
       9:      container.Compose( batch );   
      10:      foreach ( var rule in _rules )   
      11:      {   
      12:          Debug.WriteLine( rule.Name );   
      13:      }   
      14:  }  

    While this simple example is great for exploring MEF and building plug-in that live in the same assembly, in the real world scenario your plugins will be built as part of a different solution or a project, do check out some of the resources below that demonstrate in detail how to leverage MEF in your applications.

    Resources:

    MEF on CodePlex – contains assemblies, source code and sample applications, do checkout the Silverlight grid sample.

    The PDC09 demo
    http://twurl.nl/3cj8dp

    Hanselminutes podcast on MEF (with Glenn Block, the PM)
    http://twurl.nl/v6zoio

    ScottGu’s awesome demo from PDC08 showing how MEF is used in the new VS2010 IDE to make it extensible, a must see.
    http://blogs.msdn.com/brada...

    The code sample shown above is taken from here, uses the Preview 8 drop of MEF on Codeplex
    http://devlicio.us/blogs/derik_whittaker/archive..

    MEF on MSDN – covers MEF in detail including the scenario to load multiple plugins and other details.

  • “Application Lifecycle Management in VS2010” session of TechiesUAE

    I attended this session of TechiesUAE presented by Rolf Eleveld. First he took us through the installation and configuration steps required to run Team Foundation Server 2010 and Visual Studio 2010 beta 2.

    Rolf then showed some of the new features in TFS 2010 version control and its integration with VS2010 including the web interface of TFS.

    Also during the session, one of the interesting tool that he showed us is the new Problem Steps Recorder (or PSR) that ships with Windows 7.

    psr

    This tool can help developers and IT Pros know the steps required to reproduce any problem to resolve it more quickly. For more info on it watch this video  

    During the session we also discussed the use of Entity Framework & Linq to Entities in the enterprise and also saw the demo of the interesting new Lab management capabilities introduced in VSTS 2010. This helps testers test the software in a virtual environment and raise any bugs, the developers can then launch the virtual machine from the IDE and find all the rich information along with the check point link included in the bug, for more info on this read this post on Soma’s blog.

    The session lasted more than 3 hours.

  • WCF Service Contract and XML Serialization

    I am building a Service using the WCF REST Starter Kit. This Service contains a method that accepts a complex type as input, it then deserializes the object into it’s concrete type.

    Here’s how a service call looks like

    using (HttpClient client = new HttpClient())
    {
    RequestObject req = new RequestObject { FirstName = "John", LastName = "Doe", Email="johndoe@somecompany.com"};

    HttpContent body = HttpContentExtensions.CreateXmlSerializable<RequestObject>(req);

    HttpResponseMessage resp = client.Post("http://localhost:1575/Web/Service.svc/SendMail", body);

    Response.Write(resp.Content.ReadAsString());
    }

    What the above does is simply prepare a RequestObject, call a SendMail method on the service using the HttpClient, read and print the response, nothing fancy.

    Here’s how the service looks like

    [WebHelp(Comment = "Sample description for SendMail")]
    [WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat =
    WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml,UriTemplate = "SendMail")]
    [OperationContract]
    public RequestObject SendMail(RequestObject request)
    {
    return new RequestObject()
    {
    FirstName = request.FirstName, LastName = request.LastName,Email = request.Email
    };
    }

    Notice what I’m doing is preparing the same RequestObject and simply pass it as the response.

    As you’d expect I’m suppose to get the following response in the browser.

    - <RequestObject>
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
    <Email>johndoe@somecompany.com</Email>
    </RequestObject>

    But the response I receive is similar to this

    <RequestObject>
    <FirstName i:nil="true" />
    <LastNameName i:nil="true" />
    <Email>johndoe@somecompany.com</Email>
    </RequestObject>

    After a few hours of trying it occurred to me that XML Serialization is done in the alphabetical order if no ordering is specified even if the properties in the class are not in the alpha-order. (arrgh. If only I had used the Paste XML as Type as demo’ed in this screencast by Aaron Skonnard)

    So to make it work I had to change the RequestObject class in both places to look like the following.

    public class RequestObject
    {
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    }
  • VS 2010 Beta 1 and Functional UI Testing

    I just watched a video over at Channel9 which explains how to leverage some of the UI Testing capabilities that are going to be introduced with VS 2010 beta 1 expected next week.

    Visual Studio had testing capabilities for C# code for a long but now I’m glad to see for the first time an integrated UI testing built right into VS 2010 IDE. In particular I like the option to store the tests in the database and be able to run them automatically.

    See it for yourself, there is also a Mix09 video here

  • Return JSON objects the right way

    Today I experienced a weird behavior when I was passing JSON string back to a jQuery call using an Ajax-enabled WCF Service.

    My code looked something like this.

    [OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetJson")]
    public string GetJson()
    {
        return new JavaScriptSerializer().Serialize(MyCustomObject)
    }

    The problem with above code is that the string returned is escaped and enclosed with inverted commas that for some reason was not handled properly using jQuery that looked like this.

    “[{\"Id\":1,\"SomeKey\":\"SomeMoreText\"}]”

    Not sure what I was missing and while there is a JsonResult action in ASP.NET MVC with a .svc there’s nothing that I could use (or may be there is).

    To fix it I changed the method like this.

    [OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetJson")]
    public System.IO.Stream GetJson()
    {
       byte[] resultBytes = System.Text.Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(MyCustomObject));
       
       WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
     
       return new MemoryStream(resultBytes); 
    }
     

    Here’s how Json is returned.

    [{"Id":1,"SomeKey":"SomeMoreText"}]

  • Don’t use UriTemplate = "/MethodName/Param1/{Param1}/Param2/{JsonObject} for Json input with WCF Service

    When building Ajax-enabled WCF service that expect a Json object as input then the following would not work

    [OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Methodname/jsonvariable/{jsonvariable}/param2/{param2}")]
    public void MethodName(string jsonvariable, string param2)
    {
     
    }

    Where jsonvariable is a json object passed through jQuery (or ASP.NET Ajax) to a WCF service that looks like this

    [{"Name":"za","Email":zubairdotnet@hotmail.com}]

    After spending a while I figured out that the following UriTemplate should be used instead

     

    [OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Methodname/?jsonvariable={jsonvariable}&param2={param2}")]
    public void MethodName(string jsonvariable, string param2)
    {
     
    }
  • Using Regular Expressions to Rename Textbox IDs

    How can you use regular expression in Find and Replace in Visual Studio to use the Textbox IDs same as your Column name in the Eval statement?

    Consider the following two textboxes and there are couple of textboxes like them in the form

    <cmpst:Textbox ID="txtAppNo" Text='<%#Eval("AppDate") %>' runat="server" />
     
    <cmpst:Textbox ID="txtAppNo" Text='<%#Eval("NIN") %>' runat="server" />

    You want to convert the IDs of the above textboxes as following

     

    <cmpst:Textbox ID="txtAppDate" Text='<%#Eval("AppDate") %>' runat="server" />
     
    <cmpst:Textbox ID="txtNIN" Text='<%#Eval("NIN") %>' runat="server" />

     

    I took me a while to get this regular expression right, so I'm posting it here for reuse, here's how

    Find

    ID=\"txt(.*)\" Text=\'\<\%\#Eval\(\"{(.*)}\"\)

     

    Replace

    ID="txt\1" Text='<%#Eval("\1")
More Posts