ramlicious Blogs by Tina & Prabhu

September 13, 2011

Scoping WCF Services

Filed under: C#,Visual Studio,WCF — Prabhuram @ 5:04 am

Here is another example that will show the scope of the service and the fields to demonstrate the instancing behavior of services and clients. In this example I’ve created projects similar to my earlier WCF example but with few exception. This time I’m not using a business layer and I’m using simple return types instead of data contracts. I’ve used four projects:

  • ContextBehavior.Contract references System.ServiceModel
    • IMathOperation.cs
    • MathOperationClient.cs
  • ContextBehavior.Service references System.ServiceModel and ContextBehavior.Contract
    • MathOperation.cs
  • ContextBehavior.Host references System.ServiceModel, ContextBehavior.Contract and ContextBehavior.Service
    • Program.cs
    • App.config
  • ContextBehavior.Client references System.ServiceModel and ContextBehavior.Contract
    • Program.cs
    • App.config

First it is important to understand that WCF makes development easier.

  • The developer of the service doesn’t have to know about how the service will be used after implementation and so WCF clearly demarcates development and implementation
  • As an end product the service can be hosted in HTTP or TCP and so it brings together the advantages of web service and also remoting (.Net remoting) and hence you have the option on sending binary content over the wires and just not limited to plain text (XML)
  • Moreover WCF is highly secure and robust provides different instantiation capabilities (which we will see in our example)
  • Services can be either hosted in HTTP or as a Windows Services or can be self hosted (like our example)

The purpose of our service is demostrate a simple increment method. We are going to run our application in three different modes:

  • PerCall, each call made to the service is treated as an independent call
  • PerSession, each call from a particular session will be treated as part of an unexpired session (already instantiated session) and so retaining the state of the hosted object
  • Singleton, different calls from different sessions will be routed to one single hosted session and thus sharing the state of the hosted object

The complete project is available for download: ContextBehavior.zip (79.70 kb)

With this project we are going to test the three different instance contexts.  To test these we are going to decorate the service behavior of the service object with different settings to test the different behaviors from the client. Our host is a self-hosting console application that is set as the default project to run. To test the clients we are going to run the client application in debug mode such that both the host and client are debugged at the same time. First we will decorate our service with PerCall InstanceContextMode like this:

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
public class MathOperation : IMathOperation
{
}

We will run the client using the proxy client:

static void Main(string[] args)
{
  MathOperationClient client = new MathOperationClient();
  do
  {
    Console.WriteLine("Executed Increment(), value is " + client.Increment().ToString());
    Console.WriteLine("Press Y to continue...");
  }
  while (Console.ReadKey().Key.Equals(ConsoleKey.Y));
}

We can debug this by running multiple clients and making multiple calls to the service by repeatedly pressing N. As you can see since the result will always return 1 because of the PerCall Instance type. By just changing the Mode to PerSession,

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]

each call from the same session will retain the session’s state and you can see the numbers incrementiong, and by changing the Mode to Single,

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]

each call across all the session will retain the value made the earlier call.

Guess this gives you an understanding.

September 12, 2011

A simple implementation of WCF Service with an example

Filed under: C#,Visual Studio,WCF — Prabhuram @ 1:43 pm

I’ve created a sample set of projects for those who wanted to learn WCF basics. Let me assume that you wanted to learn the fundamentals of WCF and so I will assume that this is your first hands on WCF project, so that I can create a project for the dummies.

I created this project in VS2008 and the development is the same in VS2010 and I am using .NET Framework 3.5. Here is a screenshot of the solution explorer and I have created five projects. WCFSample.Host is a command-line application, WCFSample.Client is a winforms application and the remaining projects are class library.

So we will visit the projects in the order they should be created. My first project called the WCFSample.Business contains objects necessary for searching through abbreviations. I’ve used a simple collection (for the purpose just understanding the basics) which can be extended to search through database tables or XML files.

public class Abbreviation
{
  public string Abbr;
  public string Word;
  public Abbreviation(string Abbreviation, string Word)
  {
    this.Abbr = Abbreviation;
    this.Word = Word;
  }
}


and so basically my primary business method that will be used by the service will be FindByAbbreviation():

   public class AbbreviationHelper : Dictionary<string, string>
    {
        private static List<Abbreviation> list = new List<Abbreviation>(){
            new Abbreviation("fbi", "federal bureau of investigations"),
            new Abbreviation("cia", "central intelligence agency"),
            new Abbreviation("nypd", "new york police department")
        };
        public string FindByAbbreviation(string Abbreviation)
        {
            var sel = from item in list
                      where item.Abbr == Abbreviation
                      select item;
            return sel.Single().Word;
        }
    }

And the next project that comes to play is to create the WCFSample.Contract. First create the Interface that defines the contract. For more on how to refer to the MSDN article here.

    [ServiceContract]
    public interface IAbbrExpander
    {
        [OperationContract]
        WordSet Expand(string Abbreviation);
    }

And here is the declaration of WordSet:

    public class WordSet
    {
        public string Abbreviation;
        public string Word;
    }

And next is to create the implementation of IAbbrExpander in the WCFSample.CoreService project

    public class AbbrExpander : IAbbrExpander
    {
        public WordSet Expand(string Abbreviation)
        {
            AbbreviationHelper list = new AbbreviationHelper();
            string str = list.FindByAbbreviation(Abbreviation);
            WordSet word = new WordSet();
            word.Abbreviation = Abbreviation;
            word.Word = str;
            return word;
        }
    }

In our case we are going to create a self-hosting service and so the command-line project’s Main() will be like the one below:

       static void Main(string[] args)
        {
            using (ServiceHost svc = new ServiceHost(typeof(AbbrExpander)))
            {
                svc.Open();
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.Read();
            }
        }

The important thing in hosting the service is the configuration and I’ve done this configuration in App.config which can also be done programmatically:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="WCFSample.CoreService.AbbrExpander">
        <endpoint
          address="http://localhost:8080/abbr"
          binding="wsHttpBinding"
          contract="WCFSample.Contract.IAbbrExpander"/>
      </service>
    </services>
  </system.serviceModel>
</configuration>

At this time you can run the command-line application to see if it works. Also notice every little attribute and element in the app.config is important and you can learn more about them from MSDN reference library.

Now we will utilize this service from a winform application.  First introduce a app.config and make the necessary changes to give the ABCs of the service:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <client>
        <endpoint
          address="http://localhost:8080/abbr"
          binding="wsHttpBinding"
          contract="WCFSample.Contract.IAbbrExpander" />
    </client>
  </system.serviceModel>
</configuration>

To utilize the service we need to introduce a client proxy, and so we will add the class in WCFSample.Contract:

    public class AbbrExpanderClient : ClientBase<IAbbrExpander>, IAbbrExpander�
    {
        public WordSet Expand(string Abbreviation)
        {
            return Channel.Expand(Abbreviation);
        }
    }

and atlast we will introduce the event handler in our button_click to call the service and it simply goes like this:

     private void button1_Click(object sender, EventArgs e)
     {
         try
         {
             AbbrExpanderClient client = new AbbrExpanderClient();
             MessageBox.Show(client.Expand(textBox1.Text).Word);
         }
         catch(Exception ex){
             MessageBox.Show (ex.Message);
         }
     }

And so if you enter nypd in the text box and click search, a message box should pop-up with the result.

June 20, 2011

Reading last modified date from a file over the internet

Filed under: C# — Prabhuram @ 8:46 am

Here are the set of statements that will read the last modified date from any file over the internet.

//create web request
System.Net.WebRequest webreq = System.Net.WebRequest.Create("http://[web server]/[file]");
//include 3 statements if proxy is used
System.Net.WebProxy proxy = new WebProxy("http://[proxyserver or proxyid]:[port no]", true);
proxy.Credentials = new System.Net.NetworkCredential("[username]", "[password]");
webreq.Proxy = proxy;
//get the response
System.Net.WebResponse webres = webreq.GetResponse();
//read the required header
Response.Write(webres.Headers["Last-Modified"]);

June 14, 2011

Transforming files

Filed under: C# — Prabhuram @ 2:25 am

I have posted many samples for transforming files from one kind to another. Here is another example that uses composite formatting string that can be represented as output format. Additionally the object allows input line to be skipped based on conditions. Available parameters for this object:

  • Filename
  • Output format
  • Column delimiter
  • Lines to skip
  • Skip condition

FileProcessor.zip (2.88 kb)

Handling command-line parameters

Filed under: C# — Prabhuram @ 2:11 am

While creating a console application, it is always recommended to create a Program object that handles the command-line parameters. Its good practice to introduce all the parameters soon after a class is well defined. A template for creating Main() is available here: Program.zip (797.00 bytes)

April 22, 2011

A simple diff program

Filed under: C#,Visual Studio — Prabhuram @ 7:36 am

Here is a simple program that will perform text difference between two files.

FileDiff diff = new FileDiff(Filename1, Filename2);
diff.CompareTillFirstTab = CompareTillFirstTab;
diff.Execute();

Filename2 will compare against Filename1 and list all line differences within Filename1 that are not in Filename2.

FileDiff.zip (990.00 bytes)

March 16, 2010

Using (Java Script Object Notation) JSON in .NET

Filed under: C#,JSON,Visual Studio,XML — Prabhuram @ 3:39 am

In my earlier blog (Translation Methods by Google and Microsoft), I mentioned that Google will return a JSON string. Today we will see how to deserialize JSON string to a .NET object. I will take the same JSON string which was given as an example in my old blog:

{“responseData”: {“translatedText”:”aquí es una prueba que quería traducir”}, “responseDetails”: null, “responseStatus”: 200}

We will do this by creating a class (in .NET 3.5) called  myJson:


Before writing the class, the project should refer to the following assemblies:


and note the Response object that will have the object representation of the Json string:


Now simply call the Deserialze() function like this:

Find the complete code here: myJson.zip (689.00 bytes)

Key Characteristic Differences between XML and JSON

Filed under: C#,JSON,Visual Studio,XML — Prabhuram @ 2:24 am

 

Characteristic XML JSON
Data types Does not provide any notion of data types. One must rely on XML Schema for adding type information. Provides scalar data types and the ability to express structured data through arrays and objects.
Support for arrays Arrays have to be expressed by conventions, for example through the use of an outer placeholder element that models the arrays contents as inner elements. Typically, the outer element uses the plural form of the name used for inner elements. Native array support.
Support for objects Objects have to be expressed by conventions, often through a mixed use of attributes and elements. Native object support.
Null support Requires use of xsi:nil on elements in an XML instance document plus an import of the corresponding namespace. Natively recognizes the null value.
Comments Native support and usually available through APIs. Not supported.
Namespaces Supports namespaces, which eliminates the risk of name collisions when combining documents. Namespaces also allow existing XML-based standards to be safely extended. No concept of namespaces. Naming collisions are usually avoided by nesting objects or using a prefix in an object member name (the former is preferred in practice).
Formatting decisions Complex. Requires a greater effort to decide how to map application types to XML elements and attributes. Can create heated debates whether an element-centric or attribute-centric approach is better. Simple. Provides a much more direct mapping for application data. The only exception may be the absence of date/time literal.
Size Documents tend to be lengthy in size, especially when an element-centric approach to formatting is used. Syntax is very terse and yields formatted text where most of the space is consumed (rightly so) by the represented data.
Parsing in JavaScript Requires an XML DOM implementation and additional application code to map text back into JavaScript objects. No additional application code required to parse text; can use JavaScript's eval function.
Learning curve Generally tends to require use of several technologies in concert: XPath, XML Schema, XSLT, XML Namespaces, the DOM, and so on. Very simple technology stack that is already familiar to developers with a background in JavaScript or other dynamic programming languages.

JSON is a relatively new data exchange format and does not have the years of adoption or vendor support that XML enjoys today (although JSON is catching up quickly). The following table highlights the current state of affairs in the XML and JSON spaces.

Support Differences between XML and JSON

Support XML JSON
Tools Enjoys a mature set of tools widely available from many industry vendors. Rich tool support—such as editors and formatters—is scarce.
Microsoft .NET Framework Very good and mature support since version 1.0 of the .NET Framework. XML support is available as part of the Base Class Library (BCL). For unmanaged environments, there is MSXML. None so far, except an initial implementation as part of ASP.NET AJAX.
Platform and language Parsers and formatters are widely available on many platforms and languages (commercial and open source implementations). Parsers and formatters are available already on many platforms and in many languages. Consult json.org for a good set of references. Most implementations for now tend to be open source projects.
Integrated language Industry vendors are currently experimenting with support literally within languages. See Microsoft's LINQ project for more information. Is natively supported in JavaScript/ECMAScript only.

Note   Neither table is meant to be a comprehensive list of comparison points. There are further angles on which both data formats can be compared, but we felt that these key points should be sufficient to build an initial impression.

Source: An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET

March 14, 2010

Speech Controller – a reader tool for everything

Filed under: C#,Educational,Visual Studio — Prabhuram @ 7:56 am

Ever thought it would be easier to have an automated reader instead of reading something. Yeah! I have created a simple tool which will speak the text for you or even save the text as a wav file using Microsoft Speech SDK.

Say for example, you can go to Project Gutenberg and copy text from Alice in Wonderland and generate an E-book file in .wav format.


Or you can click Speak, to just listen. It's that simple.

Download the application here
Prabhuram.Com.VisualTools.exe
(9.50 kb).
and the source (in C#) from here: Prabhuram.Com.VisualTools.zip
(9.41 kb)
. Enjoy listening.

February 26, 2010

Translation Methods by Google and Microsoft

Filed under: C#,JSON,Visual Studio — Prabhuram @ 8:51 am

I've created an object which will use the translation services by Google and Microsoft in a .NET application. All you need is to simply call Translate() method like this:

Translator.Translate(Translator.TranslationSource.microsoft , "here is a test I wanted to translate", "en", "es")

which is going to give you this:

aquí es una prueba que quería traducir

 To call the Google's Translate just use  Translator.TranslationSource.google:

 Translator.Translate(Translator.TranslationSource.google, "here is a test I wanted to translate", "en", "es")

Microsoft's Translate, will require a Live Application Id and so get an appId and update it in the given class before using Microsoft's Translate.  Google's Translate will give the translated text in the form of JavaScript Object Notation (JSON). So the output to the above call will be:

{"responseData": {"translatedText":"aquí es una prueba que quería traducir"}, "responseDetails": null, "responseStatus": 200}

Download code here: Translator.zip (852.00 bytes)

« Newer PostsOlder Posts »

Powered by WordPress