Navigation

Feed your aggregator (RSS 2.0)   Send mail to the author(s)

Recent Entries
Archives
<July 2010>
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567


Categories
Blogroll
Login

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.


Copyright 2010 Manish Kumar Singh
 Sunday, May 17, 2009
Getting Started with WCF

WCF Kick Start

In this article I would be describing the simplest form of WCF (Windows Communication Foundation) project which would get you started with the WCF concepts and best practices. The purpose is to minimise the confusion from code and configuration and explain the idea along with the best practice. I would also provide description and links to help you move to a more advanced WCF topics as and when required.

For the sake of kick start I would be using basicHttpBinding for the service and consumer, which does not require any kind of authentication when accessing the service. It is kind of open to all.

Below is an overall image of the solution, projects and project files that I have used to demonstrate the simplest form of WCF implementation.

solution

The solution contains a project WcfServiceOne which defines types for contracts exposed by the service. The person class is the data contract, MyService is the service and IMyService is an interface acting as a service contract. This project acts as an API for the services.

The ServiceOneHost is the service exposed to the client. It references the project WcfServiceOne which the actual implementation of the Service as an API. Though, I could have had the service implementation written in the same project, I preferred following the best practices, by implementing the Service and Service API (contracts and its implementation) in a separate project. One advantage of doing this is that, you have decoupled service and Service API, which simplifies using the API in a non-WCF environment by directly referencing it. The web.config file in this project contains the binding information for the service which I will be explaining later in this article.

The ServiceOneConsumer is a simple ASP.Net web application consuming the service exposed by ServiceOneHost. The web.config in this web application contains the binding information defined by the host.

WcfServiceOne

WcfServiceOne project contains:

  • Data Contract - Person.cs
  • Service Contract - IMyService.cs
  • Service Implementation - IMyService.cs
Also notice that the project references System.ServiceModel and System.Runtime.Serialization which are required to assign attributes like ServiceContract, OperationContract, DataContract and DataMember.

Person.cs

using System.Runtime.Serialization;

 

namespace WcfServiceOne

{

    [DataContract]

    publicclassPerson

    {

        [DataMember]

        publicstring FullName { get; set; }

 

        [DataMember]

        publicstring Gender { get; set; }

    }

}

IMyService.cs

using System.ServiceModel;

 

namespace WcfServiceOne

{

    [ServiceContract]

    publicinterfaceIMyService

    {

        [OperationContract]

        string Callme(Person p);

    }

}

MyService

namespace WcfServiceOne

{

    publicclassMyService : IMyService

    {

        publicstring Callme(Person p)

        {

            return"Hello " + p.FullName + "  " + " you are a " + p.Gender;

        }

    }

}

ServiceOneHost

Add a reference to WcfServiceOne and then right click on the project. Select "Add New Item" from the context menu and select "WCF Service" templates. Name the new file ServiceOneHost.svc. The template would also create the code files for you in the App_Code folder. You can delete it, the code file is not required. Open the ServiceOneHost.svc and change the line to:

<% @ ServiceHost Language ="C#" Debug ="true" Service ="WcfServiceOne.MyService" %>

 

Now open the web.config file in this project and add the following block at the last within the closing of configuration tag.

  < system.serviceModel >

    < behaviors >

      < serviceBehaviors >

        < behavior name ="ServiceOneHostBehavior">

          < serviceMetadata httpGetEnabled ="true"/>

          < serviceDebug includeExceptionDetailInFaults ="false"/>

        </ behavior >

      </ serviceBehaviors >

    </ behaviors >

    < services >

      < service behaviorConfiguration ="ServiceOneHostBehavior"name="WcfServiceOne.MyService">

        < endpoint address =""binding="basicHttpBinding"contract="WcfServiceOne.IMyService">

          < identity >

            < dns value ="localhost"/>

          </ identity >

        </ endpoint >

        < endpoint address ="mex"binding="mexHttpBinding"contract="IMetadataExchange"/>

      </ service >

    </ services >

  </ system.serviceModel >

system.servicemodeltag defines how the consumer is going to connect to the service exposed here. When you add a "WCF service" to the project using template, it responds with adding the above system.servicemodel in the web.config, except the following two lines.

      < service behaviorConfiguration ="ServiceOneHostBehavior"name="WcfServiceOne.MyService">

        < endpoint address =""binding="basicHttpBinding"contract="WcfServiceOne.IMyService">

Change the name, contract and binding information as shown above. The wsHttpBinding is used to provide more secured communication using certificate. Visit The pattern and practices for WCF security at Codeplex for further guidance on how to implement wsHttpBinding using certificates.

ServiceOneConsumer

Before you proceed with consumer, you need to generate a proxy for the service and define how it connects, in the web.config file. To generate the proxy and the configuration block we would use svcutil. Open the Visual studio command prompt from Visual Studio Tools and use the following command to generate the proxy and configuration.

svcutil http://localhost/ServiceOneHost/ServiceOneHost.svc /Language:C# /out:ServiceHostProxy.cs /config:ServiceHost.config

This will create a ServiceHostProxy.cs and ServiceHost.config. Open the ServiceHost.config and copy the block. Now open the web.config file and paste the block at the end before the closing tag of configuration. The endpoint address might differ depending your host and consumer address URL.

    < system.serviceModel >

        < bindings >

            < basicHttpBinding >

                < binding name ="BasicHttpBinding_IMyService"closeTimeout="00:01:00"

                         openTimeout ="00:01:00"receiveTimeout="00:10:00"

                         sendTimeout ="00:01:00"allowCookies="false"

                         bypassProxyOnLocal ="false"

                         hostNameComparisonMode ="StrongWildcard"

                         maxBufferSize ="65536"maxBufferPoolSize="524288"

                         maxReceivedMessageSize ="65536"

                         messageEncoding ="Text"textEncoding="utf-8"

                         transferMode ="Buffered"

                         useDefaultWebProxy ="true">

                    < readerQuotas maxDepth ="32"maxStringContentLength="8192"

                                  maxArrayLength ="16384"

                                  maxBytesPerRead ="4096"

                                  maxNameTableCharCount ="16384" />

                    < security mode ="None">

                        < transport clientCredentialType ="None"proxyCredentialType="None"

                            realm ="" />

                        < message clientCredentialType ="UserName"algorithmSuite="Default" />

                    </ security >

                </ binding >

            </ basicHttpBinding >

        </ bindings >

        < client >

            < endpoint address ="http://localhost/ServiceOneHost/ServiceOneHost.svc"

                binding ="basicHttpBinding"bindingConfiguration="BasicHttpBinding_IMyService"

                contract ="IMyService"name="BasicHttpBinding_IMyService" />

        </ client >

    </ system.serviceModel >

Default.aspx

Now add the following UI in the home page of your consumer site. In this case it is Default.aspx.

< table style =" width: 400px;"cellspacing="0"cellpadding="0">

    <tr>

        <tdstyle="width:100px; vertical-align:top; text-align:left;">

            Your Name

        </td>

        <tdstyle="width:10px; vertical-align:top; text-align:left;">

            :

        </td>

        <tdstyle="width:290px; vertical-align:top; text-align:left;">

            <asp:TextBoxID="txtName"runat="server"Width="200"></asp:TextBox>

        </td>

    </tr>

    <tr>

        <tdstyle="vertical-align:top; text-align:left;">

            Gender

        </td>

        <tdstyle="vertical-align:top; text-align:left;">

            :

        </td>

        <tdstyle="vertical-align:top; text-align:left;">

            <asp:DropDownListID="ddlGender"runat="server">

                <asp:ListItemSelected="True"Text="Male"Value="male"/>

                <asp:ListItemText="Female"Value="female"/>

            </asp:DropDownList>

            <asp:ButtonID="btnSubmit"runat="server"Text="Submit"

                onclick="btnSubmit_Click"/>

        </td>

    </tr>

    <tr>

        <tdcolspan="3">

            <br/>

            <asp:LabelID="lblResult"runat="server"Text=""Font-Bold="true"
                    Font-Size="Large"></asp:Label>

        </td>

    </tr>

</ table >

Default.aspx.cs - Code Behind

using System;

using WcfServiceOne;

 

public partial class _Default : System.Web.UI.Page

{

    protectedvoid Page_Load(object sender, EventArgs e)

    {

        txtName.Text = "Manish Kumar Singh";

    }

    protectedvoid btnSubmit_Click(object sender, EventArgs e)

    {

        var p = newPerson {FullName = txtName.Text, Gender = ddlGender.SelectedValue};

 

        var proxy = newMyServiceClient();

        lblResult.Text = proxy.Callme(p);

    }

}

That's it. Now run the consumer site and give it a try.

Enjoy!
Manish


.Net
Sunday, May 17, 2009 5:42:17 PM (GMT Standard Time, UTC+00:00)  #  Comments [1] Trackback
 Saturday, May 16, 2009
Beautiful Dream

It was a Dream

Sometimes a dream seems so neat and well formed in its set of events and story line up, that it makes one feel like a creative writer. Though, I am nowhere near to good novel and creative writers, I hope the beauty of this story would appeal to the readers.

This was a dream that has nothing to do with my real life, but still had a lot of steam in its story and hidden meaning. This is my first write-up for the same and I would try to bring it very near to what I dreamt and how I felt while seeing it. I hope I would be able to generate the same enthusiasm and excitement going ahead.

Even though, I was playing the role of main character in my dreams, feeling every part of the emotions gushing through his nerves, in real life, I didn't have any resemblance to the face, background, nature or story of the character. It is more like as if, I got attached to this character at a different dimension of time and space (for few hours), feeling his inner realm without him noticing it. It is like as if, I stayed as a host inside that character for some time sharing every piece of his thoughts and emotions. The only thing I know better is it was not me still it was me.

Hence, let’s replace the name to say “John”, and let me take you to meet John, his emotions, thoughts and his story.


John!

John was in his teenage happily living with his family. The family consisted of his father, mother and an elder sister. Everyone in his family was an earning member employed. John was the only one studying. In his general routines, he used to spend the first half of the day at his college nearby, and then the rest, either playing basketball with local friends, or staying back at home doing some studies. He really cherished the great moments spent together with his family, and eagerly waited for them to return. John’s dressing sense was like many other teens, wearing rugged jeans, t-shirt and his favorite red cap having the letter “J” embroidered on the front. He used to wear it front-side-back.

John and his family stayed in a beautiful city with a lot of greenery and beautiful weather. Let me describe the place I visited in my dreams. Let me show you what I saw. It was a beautiful city having mountain ranges on one side, hazily visible, with peaks touching the sky. It was a pleasant weather, generally found in cities located near to major mountain ranges. It was not a place with high rise buildings. In fact it was a wide open area with condos located at a good 200-300 meter distance from each other. The area had an uneven slope (common near hilly areas), nicely covered with evenly cut grass and trees planted randomly all over. It did not seem to be a crowded place, an area with a small population but well designed and clean. It seemed it was a time of autumn when I visited the place in my dreams, though in realty it was winter. The fallen yellow leaves all over the place, including roads supported my assumption of less traffic here. It was a windy day as well.

There was a big common play ground at half a mile on left of John’s house. It was a good hangout for John and his friends. It was the only place where I saw a little crowd. Children playing outdoor sports, people walking or simply time passing. It had a basketball court where John used to play with his friends. Located further ahead of the play ground, maybe another half a mile was a church, clearly visible from John’s house. As what I read from the illegally invaded thoughts of John, was that a graveyard was also located behind the church.


Memories

It was the last working day of the weekend. At 1 pm, John was eagerly waiting for the last class to get over - the math class. It was not common for John to feel gloomy, especially in his math classes, which was his favorite subject. He was blaming it to the weather and his not-so-good night sleep. He was having hard time concentrating in the class, while his mind today was wandering more on the philosophical side. Memories from past were dominating his present. Some childhood games, he used to play, the kind of comics he used to read, how preciously, he used to keep those comics in the drawer, places he remembered, the things of his childhood, precious memories of friends and family get together, all this were hovering inside his head, one after another like several movie clips knitted into a sequence.

His mind was wandering in his past while his eyes were looking outside the classroom window where some kids were playing near a tree located few meters away. Those kids were playing with the fallen leaves, arranging them on the ground to form an art work like house, tree, animal and other nice things. One of the kids had scribbled a word out of those fallen leaves. It read “Happy Birthday”. Seeing, this John’s mind started knitting the memories of his birthdays he had enjoyed the most. Then suddenly he remembered the date today – It felt like an important day, it appeared as a day, having some event associated with it. “Was it someone’s birthday?” …. “Something, forgotten falls on this day”. John was trying hard to remember, but somehow, he was not able to recollect any event associated with this date. Yet the date was hovering like a feeling of Déjàvu. The shadows of past memory had now stopped disturbing him and the date had taken its place. John was now randomly picking up his family, friends and relatives to figure out whether today was associated to any of these people.

The class had ended and his colleagues were all packing up their bags. John too started packing his bag and wishing his friends. One of his friends had probably noticed his state of absence in the class. Peter came to John and enquired – “Hey John, something wrong? You seem a bit disturbed today.” “Oh no, nothing serious”, replied John. They walked out of the class together while John explained him about his mood swing and past memories. Soon, they were on the street and walking towards home. John’s house was just a mile away and he preferred walk down. Peter usually accompanied John, till the nearby bus stop, from where he used to take a bus to his house.

After Peter had left, John started walking down towards his house. On his way to home, and, even while he was talking to Peter, his mind was busy figuring out any event associate with today. He was sure that today was some important day, and he was trying hard to remember any event associated to this day. The feeling of Déjàvu was strong yet the answer seemed far away.


Déjàvu

After arriving home John threw his bag on his bed and picked up the TV remote to watch some of his favorite channels. He pushed himself into a comfortable couch in front of the television and started playing with the remote. John was glad to find a sports channel showing a basket ball tournament. John made himself comfortable, almost in a lying position, concentrating on the match. The match kept him glued to the television till it ended in a tie. It was a great match, the game was now over and the commentator was uttering his final speech. Before, ending his speech the commentator revealed that the captains of both teams were a childhood friends and also, one of the captain was having his birthday anniversary today. On hearing this, the Dejavu effect again engulfed John’s thought and he started thinking about event that slipped out of his mind. For few minutes, he concentrated hard thinking about it, but in vain, no auspicious event he could memorize had a date today. Then he stopped thinking about it and planned to visit his friends for some refreshment and game at the playground.

John reached the playground and found three of his friends already practicing basket ball. John was greeted with warmth and he joined them. He stayed there for an hour chatting and playing, then decided to go back home. Then suddenly, it clicked to him, and he asked his friends – By the way! … any Birthday today? I mean do you guys remember today as any important day? They looked puzzled, and then answered in chorus – No, Nope, Why? John knew they could not remember any important event for today and thus confused, so he said – Just a thought, forget it – and then left for his home.

On his way back he saw a person selling flowers on the roadside. He had not seen that person selling flowers before, here in this place. John kept walking looking at the person, who noticed his attention, and greeted him – Sir, any occasion today, would you like to buy some flowers; they are fresh, handpicked! - John was caught in a bit of surprise, by the coincidences happening one after another, that seemed like pointing to something that he was unable to remember.

It was now getting on his nerves, something inside his head was clearly indicating him that today was special, but it was like pondering in dark, as he had no clue about the event, its type and whether good or bad. The Dejavu effect felt stronger now, the birthday written with leaf, birthday of the basketball team captain and now this person selling flower asking him to buy few for an occasion.

Something urged John to buy some flowers and he followed his urge. He bought some flowers and headed to his home.


Revelation

John kept the flowers on the table and went to bathroom for a shower. After a hot bath, John felt more relaxed, though he was still wondering about the incidents. It was already 5 pm now and, he had no clue of any event today. He looked at the flowers while combing his hairs, as if these flowers might help him to find another clue, or solve the mystery for him. He did not want to act like a crazy asking people about any event today, just because he was experiencing a strong force of Dejavu. But, the day was about to end and soon it would be all over, which made him more impatient. He was thinking about ways that can help, in revealing the Dejavu effect. At the same time he did not want to push things beyond logical explanation, making a fool out of himself. Finally, John decided to give up and stop thinking on the issue. He went to the kitchen to make some sandwiches for himself.

It took him just a few minutes to get the grilled vegetable sandwich ready. He took the sandwich on a plate and came back to his room. He again sat on his couch watching television and enjoying his sandwich. He had switched on a channel showing the top number songs. It was an old Phil Collins number playing on the screen “Another day in paradise…”. John had listened to his song many a times before, and liked it. He started singing along in a low voice trying to match the words and tune. John remembered he had performed the same song in school and had received a flower vase as prize for a good performance. His eyes instantly went to the flowers he had kept on the table, and then he stood up and headed towards the store room, where he remembered he had kept his precious belongings – the flower vase too. His whole day spent roaming in the past and now looking at his belongings were pretty exciting for him. He wanted to see and cherish few of his memories which had gripped him since morning.

The store room was small with lot of things stuffed and piled inside. It was untidy with dust filled all over. Most of the things were John’s childhood possessions. John’s eyes started searching for the most probable place for the vase. His eyes went to a box, which was of the size of vase. John immediately recognized it – it was the vase he had received as a prize. John reached for the vase but, it had other thing piled upon it. John was careful about taking it out without disturbing the balance of other items on the top. John almost succeeded except one thing that fell from the top when he brought out the vase. It was an old album containing photographs. John stared at the album lying beside his feet filled with dust, quiet old, but he remembered it. It was his precious procession, and a time to go back into the past. He picked it up and kept looking at it for a while, then saw up from where it had fallen. Probably, it had touched his heart. He brought it, along with the vase and cleaned the dust. After keeping the flowers in the vase, John sat in his couch with his album on his lap.

John turned the page and saw young John in a school dress smiling at him. His memories started sketching scenes he remembered about the photograph and his school. He turned to next photograph, which was a group photograph of all his class mates and teachers. He kept looking at the photographs with his finger touching every person in the photograph. His mind was helping him to regenerate the live moving images of these persons. Suddenly, his finger stopped at a boy – Steve, his best friend. Steve and he were the one who had sung this song in school. Steve had also received the same prize. They had spent a real good time together. In most of the games and plays he was either his partner or rival of equal potential. Steve was always there to help, whether study or play. They had even childishly decided to opt for same school, same job and even same city when they grow up. Unfortunately, Steve had not kept his promises - he had left him alone and moved to a different world. It was the sample place, same city, John was still there but Steve had left. John remembered how bad he felt when he heard about Steve’s demise. It was an unfortunate accident, which had taken Steve away. He remembered putting flowers on his grave and promising that he would never forget the friendship and Steve. It had been seven years now, without Steve.

Suddenly, John jumped out of his couch - the album fell from his lap on the floor. He was now feeling guilty, he had actually forgotten his promise and not only that, the Dejavu effect was now very clear to him, it was his birthday today – Steve’s birthday. The circumstance, past and the clues were all clear and revealed.

The “Happy Birthday”, with the fallen leaves
The two childhood friends playing basket ball as a rival team captains.
The man selling flowers, the same flowers that he had kept on Steve’s grave.

But how was this happening to him, how come the coincidences matched so well, how can it be logically explained, why was he feeling not-so-good in the college today.

John was guilty, confused and surprised all at the same time. Lot of emotions were exchanging hands at the same time, increasing his breathing speed.

John decided to go to his grave behind the church. It was 6 pm by now; it would take him around 20 minutes to reach there. He quickly, dressed up, grabbed the flower and ran to the door.


Forget Me Not

It was windy evening; the sun had already set, but it was still not dark yet. There were multiple graves lying in peace, very silent and calm. The sound of wind was loud and clear.

John was standing in front of Steve’s grave - his eyes were glimmering with water. He was thinking about the good times and emotions he had shared with his best friend. He wanted to ask Steve, why he left and remind his promise. On the other hand his mature mind was telling him, it is not possible – Steve has gone, gone forever – But, then why these coincidences, clues and Dejavu. Was it not Steve, who was trying to remind me of my promise? Why did birthday appeared so many times in front of me, Why was I feeling gloomy today, Why did I bought flowers today, Why did I thought of the Vase today – the vase, which we had received as a prize together, Why did the album fell today – Was it not Steve’s attempt to remind me my promise made at his grave? Was it really a coincidence and so many of them together? John, was so confused and affected by the Dejavu effect, that he softly spoke to Steve’s grave – Steve was it you, did you try to remind me, are you there? There was no reply, John new there won’t be any.

After spending some time there – praying for Steve – John decided to go back home. It was already late and the sky was quiet dark now. John remembered, his family members would be arriving anytime now, and would get worried not finding him at home. John kept the flowers on the stone and after giving it a last soft look, turned around. Suddenly, he felt, a paper fluttering sound behind, he turned again and saw an old and dusty greeting card stuck on the cross of Steve’s grave making the fluttering sound due to the wind, causing its edges to strike on the cross.

John slowly picked up the card removing it from the cross and saw a sketch of two cute little children embracing each other. It was a friendship card. John was amazed, and started looking everywhere to see where the card came from. There was no one around. Can this be another coincidence? He then slowly, with trembling fingers, turned the card, which had no name but a one liner printed in bold calligraphy “FORGET ME NOT”!

This was the instance when I woke up and the story ended right there. But I got up remembering each and every scenes. I decided to blog it, since it was too precious to loose or forget.


General
Saturday, May 16, 2009 9:16:59 AM (GMT Standard Time, UTC+00:00)  #  Comments [2] Trackback
 Saturday, May 09, 2009
Compile .NET code on the fly

In this section I would like to demonstrate how to compile a .NET code on the fly. The code has been written in C#. It contains a class "InlineParser" which does the main job. It mainly, defines the class, does in-memory compilation and exposes a method for the execution of an inner method defined in the class. It also supports a choice of language whether C# or VB.NET for compilation.

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 using Microsoft.CSharp;

    6 using Microsoft.VisualBasic;

    7 using System.CodeDom.Compiler;

    8 using System.Reflection;

    9 using System.Xml.Linq;

   10 

   11 namespace com.eforceglobal.crux.bre

   12 {

   13     internalclassInlineParser

   14     {

   15         string expression = string.Empty;

   16         string functionArguments = string.Empty;

   17         string language = "CSharp";

   18         XDocument paramList = null;

   19         object objBase = null;

   20 

   21         public InlineParser(string expr, string functionArgs, XDocument parameters, string lang)

   22         {

   23             expression = expr;

   24             functionArguments = functionArgs;

   25             paramList = parameters;

   26             language = lang;

   27         }

   28 

   29         publicbool init()

   30         {

   31             if(language.ToLower().Equals("csharp"))

   32                 return InitCSharp();

   33             else

   34                 return InitVB();

   35         }

   36 

   37         internalbool InitCSharp()

   38         {

   39             // Compile the expression in a class on the fly

   40             CSharpCodeProvider cp = newCSharpCodeProvider(

   41                 newDictionary<string, string>() { { "CompilerVersion", "v3.5" } } );

   42 

   43             //ICodeCompiler ic = cp.CreateCompiler();

   44             CompilerParameters cparam = newCompilerParameters();

   45             cparam.GenerateInMemory = true;

   46             cparam.GenerateExecutable = false;

   47 

   48 

   49             // Reference Assembly

   50             cparam.ReferencedAssemblies.Add( "system.dll" );

   51             cparam.ReferencedAssemblies.Add( "mscorlib.dll" );

   52             cparam.ReferencedAssemblies.Add( "System.Core.dll" );

   53             cparam.ReferencedAssemblies.Add( "System.Xml.dll" );

   54             cparam.ReferencedAssemblies.Add( "System.Xml.Linq.dll" );

   55 

   56 

   57             // Write your code

   58             StringBuilder sb = newStringBuilder();

   59             sb.Append( "using System;\n" );

   60             sb.Append( "using System.Collections;\n" );

   61             sb.Append( "using System.Collections.Generic;\n" );

   62             sb.Append( "using System.Text;\n" );

   63             sb.Append( "using System.Text.RegularExpressions;\n" );

   64             sb.Append( "using System.Reflection;\n" );

   65             sb.Append( "using System.Linq;\n" );

   66             sb.Append( "using System.Xml.Linq;\n" );

   67 

   68             sb.Append( "namespace com.eforceglobal.crux.bre {\n" );

   69             sb.Append( "public class EvalClass {\n" );

   70             sb.Append( "public EvalClass(){}\n" );

   71             sb.Append( "public object Evaluate(\n" );

   72             sb.Append( functionArguments ).Append( " ) {\n" );

   73             sb.Append( expression ).Append("\n");

   74             sb.Append( "}\n}\n}" );

   75 

   76             //Console.WriteLine( sb.ToString() );

   77 

   78             string code = sb.ToString();

   79             CompilerResults cres = cp.CompileAssemblyFromSource( cparam, code );

   80 

   81             // Compilation Unsuccessfull

   82             StringBuilder errors = newStringBuilder();

   83             foreach ( CompilerError cerr in cres.Errors )

   84                 errors.Append( cerr.ErrorText );

   85 

   86             if ( cres.Errors.Count > 0 )

   87                 thrownewException( errors.ToString() );

   88 

   89             // Compilation Successfull

   90             if ( cres.Errors.Count == 0 && cres.CompiledAssembly != null )

   91             {

   92                 Type ClsObj = cres.CompiledAssembly.GetType( "com.eforceglobal.crux.bre.EvalClass" );

   93                 try

   94                 {

   95                     if ( ClsObj != null )

   96                     {

   97                         objBase = Activator.CreateInstance( ClsObj );

   98                     }

   99                 }

  100                 catch ( Exception ex )

  101                 {

  102                     throw;

  103                 }

  104                 returntrue;

  105             }

  106             else

  107                 returnfalse;

  108         }

  109 

  110         internalbool InitVB()

  111         {

  112             // Compile the expression in a class on the fly

  113             VBCodeProvider vb = newVBCodeProvider(

  114                 newDictionary<string, string>() { { "CompilerVersion", "v3.5" } } );

  115 

  116             //ICodeCompiler ic = cp.CreateCompiler();

  117             CompilerParameters cparam = newCompilerParameters();

  118             cparam.GenerateInMemory = true;

  119             cparam.GenerateExecutable = false;

  120 

  121 

  122             // Reference Assembly

  123             cparam.ReferencedAssemblies.Add( "system.dll" );

  124             cparam.ReferencedAssemblies.Add( "mscorlib.dll" );

  125             cparam.ReferencedAssemblies.Add( "System.Core.dll" );

  126             cparam.ReferencedAssemblies.Add( "System.Xml.dll" );

  127             cparam.ReferencedAssemblies.Add( "System.Xml.Linq.dll" );

  128 

  129 

  130             // Write your code

  131             StringBuilder sb = newStringBuilder();

  132             sb.Append( "Imports System\n" );

  133             sb.Append( "Imports System.Collections\n" );

  134             sb.Append( "Imports System.Collections.Generic\n" );

  135             sb.Append( "Imports System.Text\n" );

  136             sb.Append( "Imports System.Text.RegularExpressions\n" );

  137             sb.Append( "Imports System.Reflection\n" );

  138             sb.Append( "Imports System.Linq\n" );

  139             sb.Append( "Imports System.Xml.Linq\n" );

  140 

  141             sb.Append( "Namespace com.eforceglobal.crux.bre \n" );

  142             sb.Append( "Public Class EvalClass \n" );

  143             sb.Append( "Public Function Evaluate ( " );

  144             sb.Append( functionArguments ).Append(" ) As Object\n");

  145             sb.Append( expression ).Append( "\n" );

  146             sb.Append( "End Function\n" );

  147             sb.Append( "End Class\n" );

  148             sb.Append( "End Namespace" );

  149 

  150             //Console.WriteLine( sb.ToString() );

  151 

  152             string code = sb.ToString();

  153             CompilerResults cres = vb.CompileAssemblyFromSource( cparam, code );

  154 

  155             // Compilation Unsuccessfull

  156             StringBuilder errors = newStringBuilder();

  157             foreach ( CompilerError cerr in cres.Errors )

  158                 errors.Append( cerr.ErrorText );

  159 

  160             if ( cres.Errors.Count > 0 )

  161                 thrownewException( errors.ToString() );

  162 

  163             // Compilation Successfull

  164             if ( cres.Errors.Count == 0 && cres.CompiledAssembly != null )

  165             {

  166                 Type ClsObj = cres.CompiledAssembly.GetType( "com.eforceglobal.crux.bre.EvalClass" );

  167                 try

  168                 {

  169                     if ( ClsObj != null )

  170                     {

  171                         objBase = Activator.CreateInstance( ClsObj );

  172                     }

  173                 }

  174                 catch ( Exception ex )

  175                 {

  176                     throw;

  177                 }

  178                 returntrue;

  179             }

  180             else

  181                 returnfalse;

  182         }

  183 

  184         publicstring Evaluate()

  185         {

  186             string result = string.Empty;

  187             Type type = objBase.GetType();

  188             MethodInfo mInfo = type.GetMethod( "Evaluate" );

  189 

  190             if ( mInfo != null )

  191             {

  192                 ParameterInfo[] pInfo = mInfo.GetParameters();

  193                 object[] arguments = null;

  194                 if(pInfo!=null) arguments = newobject[pInfo.Length];

  195                 if ( pInfo != null )

  196                 {

  197                     foreach(ParameterInfo p in pInfo )

  198                         if ( paramList.Element( "arguments" ).Elements( p.Name ) != null )

  199                         {

  200                             arguments[p.Position] = (paramList.Element( "arguments" )

  201                                 .Elements( p.Name ).Single().Value);

  202                         }

  203                     if ( pInfo.Length != arguments.Length )

  204                         thrownewArgumentException( "Insufficient parameters." );

  205                 }

  206 

  207                 result = mInfo.Invoke( objBase, arguments ).ToString();

  208             }

  209 

  210             return result;

  211         }

  212     }

  213 }

Notice that the class name of the class to be compiled is "EvalClass" and the inner method of the class is "Evaluate". Calling the "Evaluate()" method requires you to execute the following lines of code.

  1 var parser = newInlineParser(subExpression, funcArgs, Arguments.Document, lang);

  2 parser.init();

  3 retString = parser.Evaluate();

Manish


.Net
Saturday, May 09, 2009 6:21:03 AM (GMT Standard Time, UTC+00:00)  #  Comments [2] Trackback