Sunday, January 6, 2013

Fiddler WCF Binary Extension Tweaked

We all know the *GREAT* Fiddler, it doesn’t need further introductions, and most of us also know the WCF Binary Extension that someone one on msdn did for us some year ago.

Well, I’ve always felt a bit unhandy to see endless responses within the Fiddler inspector window without the chance to collapse nodes or have a basic color syntax, so I used to copy and paste text from fiddler to Notepad2 (love it too!).

Some time ago I stumpled upon a control on Codeproject that caught my attention: FastColoredTextBox. Putting all together has been a really trivial task, I’ve just changed some lines of code here and there, however I’ve to say that the resulting prototype is quite pretty.

image

By the moment I’m sharing the code in a Zip on my SkyDrive, but if someone else is willing to try the project there is room for several improvements, like a proper folding, searching within the inspector and so on.

Sunday, October 28, 2012

Entity Framework 5 Code First and WCF Ria Services

Starting from a question on stackoverflow site, I thought it could be useful to publish a working sample of Entity Framework 5 and WCF ria Services tight together.
Everything it’s pretty simple but there are some not obvious pitfalls that can lead to tedious waste of time.
First thing to do, create a new Silverlight Application and don’t forget to put a mark on “Enable WCF RIA Services” as in the image below
image
then, server side, on the project that will host our silverlight application (here named EFCodeFirst _WCFRiaDemo.Web) right click the project, then select “Manage Nuget Packages”; look for entity framework then click on install as in the image below
image
In my demo I’ll use the domain model classes from another assembly, as an usual path with POCO domain model, so let’s reference in the EFCodeFirst _WCFRiaDemo.Web project the assembly that contains our classes.
I’ll use a very basic one
image
Please note the BlogId field in the Post class. It really looks like the db that is leaking into the model, and indeed it is, but… that’s the way WCF Ria Services work with relations. Just pretend not to see this field Sorriso
Then create the DbContext including the related mapping, as in the snip below
public class BlogContext : DbContext
    {
        public BlogContext() : 
            base("BlogContext")
        {

        }
        public DbSet<Blog> Blogs { get; protected set; }

        public DbSet<Post> Posts { get; protected set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Here goes our custom mapping
            //we can comment out the row below and completely customize the entities mapping
            //base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Post>()
                .HasRequired(x => x.Blog)
                .WithMany(x => x.Posts)
                .HasForeignKey(x => x.BlogId);


        }
    }


and in the web.config add the connection strings section and relevant info

<connectionStrings>
    <add name="BlogContext" connectionString="Data Source=.\SQLEXPRESS; AttachDBFilename=|DataDirectory|\WcfRiaDemo.mdf;Integrated Security=SSPI; MultipleActiveResultSets=True;User Instance=true" providerName="System.Data.SqlClient" />
</connectionStrings>


I’ve leveraged Package Manager Console to create my database running in it Enable-Migrations –EnableAutomaticMigrations

Now, our DbContext should be up and running, let’s add out DomainService class. I’m not a fan of shining wizard, so I’ll not leverage automatic DomainServices creation, taking into account that it needs some tricks in order to work with EF Code First. I’ll rather add a DbDomainService manually. Consider also, that this is the way you’ll normally deal with when adding classes and methods to your model.

In order to work with EntityFramework and take advantages of mapping info defined into the DbContext, we need to derive our DomainContext from the DbDomainService class. This is a class defined in the WCF Ria Services tookit, available here.

Then, “expose” our classes to the client, adding methods these

    [EnableClientAccess()]
    public class WCFRiaDemoDomainService : DbDomainService<BlogContext>
    {
        [Query]
        public IQueryable<Blog> GetBlogs()
        {
            return this.DbContext.Blogs;
        }

        [Query]
        public IQueryable<Post> GetPosts()
        {
            return this.DbContext.Posts;
        }
    }

The QueryAttribute  it’s not strictly needed as it will be picked from convention (the method returns an IQueryable<T>) however, I like to mark those methods.

Please note that I’m not exposing the related Insert/Delete/Update methods, so my entity will be generated as read-only.


Now come the tricky part: if we try to build the client it will NOT generate our DomainContext, but rather just the WebContext and no Classes.

This come from a version compatibility issue between the code generator and entitiy framework. The Code generator will look for EntityFramework v4.2, will of course not found it, and will not generate our classes and unfortunately will not notify us of such problem.

The solution I usually use rely on, is assembly binding redirect. Putting the lines below into our web.config will trick the code generator that finally will generate our proxy

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>



A final note: Consider that the proxy generator come in two flavours: the CodeDom generator (the one that we are using here) and the T4 based code generator. You can learn how to use and leverage it from the (no long updated) blog of varun puranik

That’s it for now. I’ve attached the solution for everyone to download and take a look.

Friday, September 21, 2012

WCF Ria Services overcoming limitations on "Return Types”

I’m a fan of WCF Ria Services,  however it sometimes have strange limitations whose motivations doens’t appears obvious. One of them I believe it’s the limitation on types that a DomainServices can returns.
If you try to return for example a IEnumerable<IList<string>> you’ll get a message like that
Operation named 'MyOperation' does not conform to the required signature. Return types must be an entity or complex type, a collection of entities or complex types, or one of the predefined serializable types.
A simple way to overcome this limitation is to “pre-serialize” your object. I use a couple of methods to serialize/deserialize both client and server side
public static class Serialization
    {
        public static string Serialize<T>(T obj)
        {
            var ms = new MemoryStream();
            var ser = new DataContractSerializer(typeof (T));
            ser.WriteObject(ms, obj);
            byte[] array = ms.ToArray();
            ms.Close();
            return Encoding.UTF8.GetString(array, 0, array.Length);
        }

        public static T Deserialize<T>(string obj) where T : class
        {
            if (obj == null)
                return null;
            var serializer = new DataContractSerializer(typeof (T));
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(obj));
            var result = serializer.ReadObject(stream) as T;
            return result;
        }
    }


So, Server side I use something like
[Invoke]
public IEnumerable<string> MyOperation()
{
    List<string> list1 = new List<string>(){"ciao", "a" , "tutti"};
    List<string> list2 = new List<string>(){"hello", "world"};
    List<string> listOfSerializedList = new List<string>();
    listOfSerializedList.Add(Serialize(list1));
    listOfSerializedList.Add(Serialize(list2));
    return listOfSerializedList;
}


while client side
var myOperationResult = myDomainContext.MyOperation();
List<List<string>> myRealResult = new List<List<string>> ();
foreach (var myList in myOperationResult )
{
    myRealResult.Add(Deserialize<List<string>>(myList));
}
Of  course the code is just a proof of concept, and it’s better to package it in more “productive” methods but it should get the idea behind it.
Hope this helps


Wednesday, September 12, 2012

Auto increment build number msbuild 4



If you just need to increment that number in the AssemblyVersion, it’s amazingly easy:
[assembly: AssemblyVersion("1.0.*")]


However the above  will increment only the AssemblyVersion (as a note: the third number represent the number of days since 1/1/2000 and the third HHmm of your local time) if  you rather want to increment the AssemblyFileVersion things complicate a bit… as someone suggest on stackoverflow you can omit the AssemblyFileVersion in your AssemblyInfo.cs and you’ll get the operating system displaying as FileVersion the value of AssemblyVersion.


I, however, was looking for something different. I wanted the FileVersion to auto increment at each build accordingly to my day’s fantasies.


I’ve discovered from the msbuild master Sayed Ibrahim that in msbuild 4.0 ther’s a new feature called Inline Task. It’s just like a regular msbuild custom task, but it’s defined inline within the project file. And that's a great news.


So I created an inline task like this


<UsingTask
    TaskName="SetVersion"
    TaskFactory="CodeTaskFactory"
    AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll" >
    <ParameterGroup>
      <FileName ParameterType="System.String" Required="true" />
      <MajorVersion ParameterType="System.Int32" Required="true" />
      <MinorVersion ParameterType="System.Int32" Required="true" />
    </ParameterGroup>
    <Task>
      <!--<Reference Include=""/>-->
      <Using Namespace="System"/>
      <Using Namespace="System.IO"/>
      <Code Type="Fragment" Language="cs">
        <![CDATA[
            string dayCount = Math.Floor(DateTime.Now.Subtract(new DateTime(1979,5,2)).TotalDays).ToString();
            string text = String.Format("[assembly:System.Reflection.AssemblyFileVersion(\"{0}.{1}.{2}.{3}\")]", MajorVersion, MinorVersion, dayCount, DateTime.Now.ToString("HHmm") );
            File.WriteAllText(FileName, text);
            return true;
  ]]></Code>
    </Task>
  </UsingTask>


and called it in “BeforeBuild” Target


<Target Name="BeforeBuild">
    <SetVersion FileName="$(MSBuildProjectDirectory)\Properties\VersionInfo.cs" MajorVersion="1" MinorVersion="3" />
</Target>


The file “Properties\VersionInfo.cs” is an empty file included in my project, that my InlineTask code fills.


Of course there are other ways to do the same thing with AutoBuildVersion being one of the easiest, but this one is customizable by code and  don’t have dependencies so it compile fine everywhere .net 4 is installed.


Marco Casamento

Thursday, February 23, 2012

TFS 2010 Reconcile Workspace

From time in time Visual Studio 2010 don’t reconcile the workspace after a gated check-in. I’ve seen that this happens regularly if UAC is enabled, Visual Studio is running under elevated permission and the reconcile operation is started from the Build Notification tool’s MessageBox, how well documented in this blog post.
However, for some other reasons that I don’t know, sometime Visual Studio (or maybe the Source Control plug-in) simply refuses to reconcile the workspace.
In that case I know a good persuader: the Team Foundation Server 2010 Power tools. It expose a command that permits you to undo the unchanged file. Basically it do a compare between the TFS latest version and the current workspace, then execute an “undo"  on all files that are identicals.
So… let’s intall the TFS Powertools and execute “tfpt uu”  from the command line in the main folder of our workspace and the command will do the trick. Unfortunately Visual Studio isn’t smart enough to self notice that the status of files has changed, but we can always use “File/Source Control/Refresh Status” and avoid a really uncomfortable restart of the IDE.

HTH!
Marco

p.s.
Yes, first post in english after a long silence. Why ? It’s not to spread the word about my english ignorance, but all of the readers of the previous post came from abroad, so why force them to Google translator ? Additionally, the blog it’s all around the .NET world, and I believe that every Italian developer know english enough (probably better than me)!

Tuesday, October 12, 2010

Combinare due query LINQ

Sembra una vita che non riesco più a trovare il tempo per scrivere due righe sul blog… Colpa del lavoro, a cui sto dedicando decisamente troppo tempo, ok, cerco di rimediare con un mini post.

Vi è mai capitato di avere la necessità di combinare due query LINQ? Sembra una baggianata (e in effetti lo è) ma io ho avuto difficoltà a trovare un esempio bello e pronto… Io ho incontrato il caso con i DomainService, ove mi è servito combinare alla query proveniente dal client, degli altri “pezzi” definiti sul server (si tratta di un evoluzione basata sui due post precedenti sui WCF Ria Services e nHibernate, di cui penso prima o poi di scrivere un post) ma la problematica è decisamente generica.

Definite due query, una che chiamerò “sorgente” è quella al cui queryProvider chiederò di eseguire il risultato della composizione e l’altra, “destinazione”, contiene i “pezzi” che voglio aggiungere alla sorgente.

Per far ciò è sufficiente far “visitare” l’espressione “destinazione” (ovvero quella da aggiungere) da un ExpressionVisitor istanziato sull’espressione sorgente e chiedere al queryProvider “sorgente” di creare una nuova query a partire dall’espressione “visitata”.

Ok, qui servirebbero pagine e pagine di spiegazione su LINQ, ma c’è tanto materiale in giro, e così ben fatto che non mi azzardo nemmeno a scrivere due righe… :-)

…Però il codice necessario lo posto subito!

Come dimostrazione ho creato una semplicissima applicazione console

 using  System;

 using  System.Collections.Generic;

 using  System.Linq;

 using  System.Text;

 

 namespace  ConsoleApplication1

 {

     class  Program 
     { 
         static  void  Main(string [] args)
         {
             List <MyEntity > myList = new  List <MyEntity >()
             {
                 new  MyEntity () 
                 {  
                     Id = 1,
                     MyProperty = "Messina" 
                 },
                 new  MyEntity ()
                 {
                     Id = 2,
                     MyProperty = "Palermo" 
                 },
                 new  MyEntity ()
                 {
                     Id=3,
                     MyProperty="Catania" 
                 }
                 new  MyEntity ()
                 {
                     Id = 4,
                     MyProperty = "Milazzo" 
                 }
             };
             //let's obtain an IQueryable... 
             var  query = myList.AsQueryable();
             //and define a query  over it 
             var  otherQuery = query.Skip(1).Take(2).OrderByDescending(x=> x.Id);
             //print out original count 
             Console .WriteLine("querCount = "  + query.Count().ToString());
             //combine the two queries... 
             var  newQuery = QueryCombiner .Combine<MyEntity >(query, otherQuery);
             //and see something about the result! 
             Console .WriteLine("newQueryCount  = "  + newQuery.Count().ToString());
             foreach  (var  item in  newQuery)
             {
                 Console .WriteLine("rimasti: "  + (item as  MyEntity ).MyProperty);
             }
             Console .ReadKey();
         }
     }
     public  class  MyEntity 
     {
         public  int  Id { get ; set ; }
         public  string  MyProperty { get ; set ; }
     }
 }



che dimostra la piccolissima classe a seguire




 using  System;

 using  System.Collections.Generic;

 using  System.Linq;

 using  System.Text;

 using  System.Collections;

 using  System.Linq.Expressions;

 using  System.ServiceModel.DomainServices.Server;

 

 namespace  ConsoleApplication1

 {

     public  class   QueryCombiner  : ExpressionVisitor 

     {

         // Methods 

         public  static  IQueryable <T> Combine<T>(IQueryable  source, IQueryable  query)

         {

             Expression  expression = Combine(source.Expression, query.Expression);

             return  source.Provider.CreateQuery<T>(expression);

         }

         public  static  IQueryable  Combine(IQueryable  source, IQueryable  query)

         {

             Expression  expression = Combine(source.Expression, query.Expression);

             return  source.Provider.CreateQuery(expression);

         }

 

         public  static  Expression  Combine(Expression  source, Expression  query)

         {

             Expression  retExp = new  Visitor (source).Visit(query);

             return  retExp;

         }

         

         //nested types 

         private  class  Visitor  : ExpressionVisitor 

         {

             // Fields 

             private  Expression  _root;

 

             // Methods 

             public  Visitor(Expression  root)

             {

                 _root = root;

             }

 

             protected  override  Expression  VisitMethodCall(MethodCallExpression  mce)

             {

                 if  (((mce.Arguments.Count > 0) 

                     && (mce.Arguments[0].NodeType == ExpressionType .Constant)) 

                     && ((((ConstantExpression ) mce.Arguments[0]).Value != null ) 

                     && (((ConstantExpression ) mce.Arguments[0]).Value is  IQueryable )))

                 {

                     List <Expression > list = new  List <Expression > {

                         _root

                     };

                     list.AddRange(mce.Arguments.Skip<Expression >(1));

                     return  Expression .Call(mce.Method, list.ToArray());

                 }

                 return  base .VisitMethodCall(mce);

             }

         }

     }

 }

 


I metodi statici in testa alla classe credo che parlino da soli… :)


Ciao a tutti e a presto (spero)


Marco

Wednesday, July 14, 2010

Sarà una lunga gestazione ?

Da un bel po’ di tempo non sto più scrivendo nulla sul blog e temo ci voglia ancora un po’ prima di scrivere qualche altro post. In questo momento oltre al “solito” lavoro in ufficio sto realizzando un add-in per estendere la già potente PivotTable di Excel 2007.
Per i pochi che non lo sapessero, la PivotTable è uno strumento integrato in Excel che consente di visualizzare facilmente dati da praticamente qualunque origine dati per cui esista un driver ODBC o OLEDB, incluso Analysis Services di cui rappresenta il front-end d’elezione.
Con la mia add-in intendo dare la possibilità di aggiungere misure calcolate in sessione a una PivotTable basata su SSAS2005/2008. Ho visto in giro un utility open source su codeplex che fa già qualcosa di simile a quello che ho in mente io, OlapPivotTableExtension  ma conto di realizzare qualcosa di più user-friendly, con una tree che consenta di selezionare gerarchie, membri, livelli, misure e funzioni MDX, e la textbox di editing che esegua almeno un po’ di Syntax Color di base. Intellisense ? Eh non lo so… magari nella ver. 2!
Quello sotto è una screenshot del form che permette di creare le misure calcolate (e dovrebbe integrare delle funzionalità di salvataggio/recupero misure calcolate da un file, alfine di facilitare la condivisione delle formule.

image
Bhe… io continuo a passi lenti lo sviluppo, dopotutto è pur sempre estate, il codice non è affatto “sexy” e il calore del portatile sulle gambe sempre meno piacevole…
A presto!