Simple autogenerated facade WCF service with T4

If you don’t want to use a lot of money on service virtualization tools you can create a simple autogenerated WCF facade service that does a little bit of the things the big service virtualization tools does.

This gives you the option to hide service between one common service. The services behind this service could be a service from your backend system, a service from your CRM system and it might even be some external services.

You could do it manually, but then you would have to update it each time one of the backend services changes and with the human factor as an error source. Visual Studio gives you the option to use text templates which can be used to generate code.

Start by creating a WCF Service Application in Visual Studio and add a text template to this project, which will give you a *.tt file. This is the file that you will edit to create the autogenerated code. You might want to read a bit about it at MSDN before reading on. Here is the link.

Working with tt files is like going back in time. Back to the time with ASP and where you don’t have intellisense. I stongly recommend to use Visual Studio 2012 that at least gives you a good debug option.

The first part of the tt file is the part where you specify which .Net namespace you want to use. The tt files knows nothing about the references that you have in your project, which I found out the hard way. My initial thoughts were to use reflection to get information about the services that I was going to work with, but I got into problems when I wanted to work with service references. So I ended up using the EnvDTE namespace, where you work with the FileCodeModel in Visual Studio. So this gives me this first part of the tt file:

<#@ template debug=”true” hostspecific=”true” #>
<#@ output extension=”cs” #>
<#@ assembly name=”EnvDTE” #>
<#@ assembly name=”System.Xml” #>
<#@ import namespace=”EnvDTE” #>
<#@ import namespace=”System.Diagnostics” #>
<#@ import namespace=”System.Xml” #>
<#@ import namespace=”System.Collections.Generic” #>

I wanted to control which services got autogenerated in an XML file, so I at a *.mapping file to the solution where I created a structure with the name of the service I wanted.

Based on this I could load the FileCodeModel and find the CodeFunctions that needed to be exposed.

 <#   
    
 EnvDTE.DTE dte = GetEnvDTE();
 string myFile = this.Host.ResolvePath(“AutoGeneratedFacade.Mapping”);
 XmlDocument xdoc = new XmlDocument();
 xdoc.Load(myFile);
 foreach (XmlNode node in xdoc.SelectNodes(@”//class/name”))
 {
      string sourceFileName = node.InnerText;
      sourceFileName = @”Service References\” + sourceFileName + @”\Reference.cs”;
      ProjectItem enumProjectItem = dte.Solution.FindProjectItem(sourceFileName);
      FileCodeModel codeModel = enumProjectItem.FileCodeModel;

      CodeNamespace codeNamespace = FindNamespace(codeModel.CodeElements);
      CodeInterface codeInterface = FindInterface(codeModel.CodeElements);
      List<CodeFunction> codeFunctions = FindMethods(codeInterface.Children);
 #>

In the above code there are a couple of utility functions:

<#+
    
    private CodeNamespace FindNamespace(CodeElements elements)
     {
         foreach (CodeElement element in elements)
         {
             CodeNamespace ns = element as CodeNamespace;
        
            if (ns != null)
                 return ns;
         }
    
        return null;
     }
    
    private CodeInterface FindInterface(CodeElements elements)
     {
         foreach (CodeElement element in elements)
         {
             CodeInterface codeInterface = element as CodeInterface;
        
            if (codeInterface != null)
                 return codeInterface;
    
            codeInterface = FindInterface(element.Children);
    
            if (codeInterface != null)
                 return codeInterface;
         }
    
        return null;
     }
    
    private List<CodeFunction> FindMethods(CodeElements elements)
     {
         List<CodeFunction> methods = new List<CodeFunction>();
        
        foreach (CodeElement element in elements)
         {
             CodeFunction method = element as CodeFunction;
        
            if (method != null)
                 methods.Add(method);           
        }
    
        return methods;
     }
    
    private EnvDTE.DTE GetEnvDTE()
     {
         IServiceProvider hostServiceProvider = (IServiceProvider)Host;
        
        if (hostServiceProvider == null)
                throw new Exception(“Host property returned unexpected value (null)”);
        
        EnvDTE.DTE dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE));
        
        if (dte == null)
                throw new Exception(“Unable to retrieve EnvDTE.DTE”);
    
        return dte;
     }
 #>

With the CodeFunctions in hand I am now able to create the new interface and class implementation for the autogenerated WCF facade service:

<#+
private void WriteInterface(CodeFunction method)
{
    foreach(CodeElement element in method.Attributes)
    {
         string at = “”;
         CodeAttribute att = element as CodeAttribute;
        
         if (att != null)
         {
              at = at + “[“;
              at = at + att.Name;
              at = at + “(“;
              at = at + att.Value;
              at = at + “)]”;
              WriteLine(at);
         }
    }
        
    Write(method.Type.AsString);
    Write(” “);
    Write(method.Name);
    Write(“(“);
    string sparameter = “”;        
    foreach(CodeElement element in method.Parameters)
    {
        int count = 0;           
        CodeParameter parameter = element as CodeParameter;
        
        if (parameter != null)
        {
            sparameter =sparameter + parameter.Type.AsString + ” “;
            sparameter = sparameter + parameter.Name;
                
            if(count < method.Parameters.Count)
                sparameter = sparameter + “, “;
                
            count++;
        }
    }
    sparameter = sparameter.Substring(0,sparameter.Length -2);
    Write(sparameter);
    Write(“);”);
}
#>

And with the interface I am able to create the class the implements the interface:

<#+
private void WriteServiceClass(CodeFunction method, string servicename)
{
     Write(“public “);
     Write(method.Type.AsString);
     Write(” “);
     Write(method.Name);
     Write(“(“);
     string sparameter = “”;
     string sparameternames = “”;        
     foreach(CodeElement element in method.Parameters)
     {
         int count = 0;           
         CodeParameter parameter = element as CodeParameter;
        
         if (parameter != null)
         {
             sparameter =sparameter + parameter.Type.AsString + ” “;
             sparameter = sparameter + parameter.Name;
             sparameternames = sparameternames + parameter.Name;
             if(count < method.Parameters.Count)
             {
                 sparameter = sparameter + “, “;
                 sparameternames = sparameternames + “, “;
              }  
              count++;
         }
     }
     sparameter = sparameter.Substring(0,sparameter.Length -2);
     Write(sparameter);
     Write(“)”);
     WriteLine(String.Empty);
     WriteLine(“{“);
     PushIndent(”        “);
     Write(“FacadeService.”);
     Write(servicename);
     Write(“.”);
     Write(servicename);
     Write(“Client service = new FacadeService.”);
     Write(servicename);
     Write(“.”);
     Write(servicename);
     Write(“Client();”);
     WriteLine(String.Empty);
     Write(“return service.”);
     Write(method.Name);
     sparameternames = sparameternames.Substring(0,sparameternames.Length -2);
     Write(“(“);
     Write(sparameternames);
     Write(“);”);
     WriteLine(String.Empty);
     ClearIndent();
     PushIndent(”        “);
    WriteLine(“}”)  
}
#>

The final piece is to change the SVC file to point to the autogenerated class with changes to the Service and Codebehind attributes.

I used this article as inspiration and borrowed some lines of code from it.

With this I just have to update the service proxy and save the tt file to update my facade service and I don’t have to write copy paste code.

Random posts:

Help me, help you. You know how 😉 (click, click, click…)

7 parts series "BizTalk360 a monitoring and support tool" by Sandro Pereira

The success of the product comes to light when people get excited and starts talking about it. Especially when someone like Sandro Pereira who is considered as one of the most influential person in the BizTalk community.  We are really humbled and delighted to see Sandro spent lot of time figuring out the capabilities of […]

The post 7 parts series "BizTalk360 a monitoring and support tool" by Sandro Pereira appeared first on BizTalk360 Blog.

Blog Post by: Saravana Kumar

Interview Series: Four Questions With  Tom Canter

Interview Series: Four Questions With Tom Canter

Happy New Year! Thanks for checking out my 45th interview with a thought leader in the “connected technologies” space. This month, we’re talking to Tom Canter who is theDirector of Developmentfor consultancy CCI Tec, a Microsoft “Virtual Technology Specialist (V-TS)” for BizTalk Server, and a smart, grizzled middleware guy. He’s seen it all, and I […]
Blog Post by: Richard Seroter

My year 2012 In retrospective

My year 2012 In retrospective

First of all happy new year! 

In this post I would like to summarize how my year 2012 went. For one it has been a very busy year like last year 2011. To summarize all my activity bullet wise:

  • I have had multiple speaking engagements in the Netherlands and abroad (Canada, Sweden, Norway)
  • Had a book published the BizTalk Server 2010 Cookbook through Packt Publishing
  • Technically review another the (MCTS): Microsoft BizTalk Server 2010 (70-595) Certification Guide
  • Published a white paper on Supportability and operation of BizTalk
  • Written dozen blog posts on this blog, BizTalkadminsblogging and on TechNetWiki Blog
  • Created the blog post series on BizTalk community members
  • Written multiple TechNet wiki articles on BizTalk

During 2012 I became good friends with quite a few people. Some of them I visited their homes, wedding and companies. It is great to have Kent Weare, Randal van Splunteren, Richard Seroter, Tord G. Nordahl, Sandro Pereira, Saravana Kumar, Nino Crudele, Johan Hedberg, Mikael Hakanson, Stephen W. Thomas, and Mick Badran as a friend and fellow BizTalk now Microsoft Integration MVP to collaborate with (some of them are in the picture below).

DSCN0585

Mikael, Me, Richard, Kent, Johan, Sravana, Stephen, Tord and Mick having a drink at Earls, Bellevue.

February this year I organized a BizTalk innovation event with Saravana as one of the speakers. This turned out to be a success, which was followed up by Nino organizing one in Milan with myself, Saravana, Nino, Tord and Sandro as speakers. Again this turned out to be a successful event. In September Tord (since 1st of January 2013 also a Microsoft Integration MVP) organized a two day BizTalk Innovation event at Bouvet with the same speakers. This turned out to be a huge success.

This year in two weeks from now there will be an event with all of us speaking at the London BizTalk Summit 2013 organized by Saravana, Microsoft UK and BizTalk product group. This will be a great event for us and another possibility to speak as a group, which unofficially is named the “BizTalkCrew” (you’ll sometimes will see the hashtag BizTalkCrew in some of our tweets).

On the personal side I got interested in running and start doing so since April 2012. I have run over 200 miles so far and completed two runs (10 miles in Amsterdam, the Dam-to-Dam run and 9,5 miles in Nijmegen, Seven Hills run).

Steef

Running the Seven Hills run (Zevenheuvelen loop, Nijmegen) at 10 kilometers mark.

Besides running I dedicated most of my time with my family and friends, travelling and of course the BizTalk community. Thanks everyone for reading my blog and I will continue to share my knowledge through speaking and writing in 2013.

Cheers,

Steef-Jan

Congratulations to new and renewed Microsoft Integration MVPs (Jan 2013)

Microsoft Most Valuable Professional (MVP) program is an annual program awarded by Microsoft for most influential community members in the world. Getting an MVP status in their chosen technology area is a dream for many of the technical professionals. The MVP award is not just restricted to developers, there is no easy way to achieve […]

The post Congratulations to new and renewed Microsoft Integration MVPs (Jan 2013) appeared first on BizTalk360 Blog.

Blog Post by: Saravana Kumar

ALM MVP for a 7th year

January 1st is one of 4 dates during the year when Microsoft announce their new and renewed Most Valuable Professionals (MVPs). As someone that was awarded on January 1st, it means the year starts off with a regular scan of my emails to see if my community contributions have been sufficient to be re-awarded.

Sitting proudly in my Inbox was the much anticipated email confirming that I have once again reached the bar to be an ALM MVP for another year.

In addition to my community contributions, I’ve been very busy with our TFS training curriculum. We start 2013 with 6 TFS 2012 courses, the most comprehensive curriculum for TFS 2012 in the world today. Over the next 3 months we’re also releasing two new courses to bring the total up to 8 courses.

Stay tuned for news on the following two courses.

  • Mastering Builds with TFS 2012
  • Applied Scrum with TFS 2012
BizTalk360 a monitoring and support tool for BizTalk Server environments (Part 7)

BizTalk360 a monitoring and support tool for BizTalk Server environments (Part 7)

Governance and Auditing Capabilities I leave it to the end, which in my opinion is perhaps one of the main and important functionality of this tool and that no other on the market enables: the ability to bring auditing functionalities to BizTalk Server platform. The same way as it is imperative for organizations to be […]
Blog Post by: Sandro Pereira

2012 Year in Review

2012 Year in Review

2012 was a fun year. I added 50+ blog posts, built Pluralsight courses about Force.com and Amazon Web Services, kept writing regularly for InfoQ.com, and got 2/3 of the way done my graduate degree in Engineering. It was a blast visiting Australia to talk about integration technologies, going to Microsoft Convergence to talk about CRM […]
Blog Post by: Richard Seroter

Microsoft XBOX360 Media setup experience

As a pure Microsoft fan, I pretty much buy anything that gets shipped by Microsoft whether I use it or not. XBOX is one such device which was just sitting and collecting dust in my TV cabinet for a while now. During this holiday season I decided to clean up the TV cabinet, get rid […]

The post Microsoft XBOX360 Media setup experience appeared first on BizTalk360 Blog.

Blog Post by: Saravana Kumar