Sunday, August 30, 2009

RESTful Service Start Kit

I have been very interested in RESTful services, since it is a service based on HTTP Get, Put and Post protocol. Basically, you can use this service by using URL to provide your resources to end users with simple web protocol service. One way to explore the service is by using a web browser, which is URL based application to handle resources such as HTML and XML.

I have watched Pluralsight Screencast demos on Microsoft WCF REST Startkit. The Start Kit project was launched last year with Preview 1. Now it is in the stage of Preview 2. As MSD's artical: A Developer's Guid to WCF REST Start Kit, this new framework will be in the future versions of the .Net Framework.

However, what I tried the Preview 2 last week, I realized that some of template projects behavior differently from the version of Preview 1, as I saw in the Screencast. For example, one class of Service.basic.svc.cs is missing. From the class of Service.svc.cs I can see base class such CollectionServiceBase and ICollectionService but they are not available for editing. This makes it impossible to customized help descriptions, implementations and templates. Not sure if all these changes are available from other alternative classes or interfaces. I think I have to spend a little more time to read information about the Preview 2 and to get it work as I expected.

At the same time, I posted my questions about the change of Preview 2 and asking if there is other alternative Open Source based library available on StackOverflow. It seems like that there are very a few EST kits or libraries for .Net platform. One alternative is OpenRasta. It looks like that OpenRasta is very good package. Basically its architecture is based on three elements: resources, handlers and codec. Resources are information to be exposed to the REST service, handlers are HTTP handlers for GET, PUT and POST for various request patterns, and Codec is enCoding/deCoding of HTTP requests.

Though the person who provides OpenRasta is a very smart .Net developer, he has very limit resources, time and effort to move it out. So far it is not so widely used and it looks like that it does not support Atom and feed services. Maybe in the new release coming the next month, some more enhancement will be available.

I'll keep eye on this library and at the same time, I have to look at Preview 2 in a deep level. Enjoy exploring!

Read More...

Sunday, August 23, 2009

CodeDom and Expression Calculator (1)

I have subscribed to .Net Rock podcast and I enjoy listening to this talk on weekly base. At the beginning of almost each talk Carl always gives a small section about one .Net framework library. It is a very brief information about the .Net library or namespace and some descriptions or usages about using it. Recently he mentioned something about Compiler to compile codes but he admitted that he does not know where to use it and how to use it. He just thrown it out.

This reminded me immediately about System.CodeDom namespace. I have used this to dynamically build source codes, to compile codes, to create an instance and to get result by calling a method of the instance. It is very cool stuff. I use this feature to get result of a expression such as:

    24*60*60

so that I can use expression in a configuration XML file. Since the expression is evaluated by building a snip of dynamic codes, the expression can also be a expression of C# codes like:
   Date.Parse(Date.Now.ToShrotDateString())

in the configuration file as a current date in a short date string. Eventually, the value will be a DateTime value as a property value.

I created a class called as ExpressionCalculator. Here is an examples of how to use the class to evaluate expressions:


int iVal = true;
ExpressionCalculator expCalc = new ExpressionCalculator();
expCalc.SetConfiguration("24*60*60",
    ExpressionCalculator.ECValueType.Integer).
    GetAnswer<int>(ref iVal);

Think about the snip codes to evaluate an expression. This is very simple. Here is an example:

using System;
public class ExpresssionEvaluation { // class name
  private int _value = 24*60*60; // type and expression
  public int GetAnswer()         // method to get result as type
  {
    return _value;
  }
}

What I need to evaluate an expression result is to generate a snip of codes with expression and expected type dynamically replaced. By using CodeDom classes, the snip of codes can be built and compiled. Then instance of ExpressionEvaluation can be created. Finally the result can be obtained by calling the method GetAnswer().

Interestingly, I found that the CodeDom compiler uses the exactly same compiler to compile the source codes in %tmp% directory. The assembly then is loaded by using Reflection to get all the classes, properties and methods. I found those background stuff while I had some compiler error with the snip of codes.

Read More...

Sunday, August 16, 2009

MSDN Channel 9

In the past month I have been watching talks or conversations on MSDN Channel 9. Microsoft is going to be more open than before. I enjoyed those open talks on the technology and new stuff. Actually, I think that Microsoft attract many talent people who have been on Open development for years and Microsoft has learned that they can gain benefit by join the Open world!

I found the Channel 9 one day when I tried to find out any shows or videos about REST web service with .Net or Visual Studio. To my surprise, I found a series talks on this at Channel 9. The best talks are offered by PluralSight.com, which is a search on its site for REST. PuralSight has better quality videos. Based on the talks, I found that Microsoft provided a REST package for REST web service development, and it is very impressive.

In addition to that, from Channel 9, I found many other great Open source projects posted to CodePlex, which is Microsoft Open Source web site. I have used many Open source libraries there, including Json.Net, MVC...

Read More...

Sunday, August 09, 2009

Json.NET and Its Usage (3)

In this blog, I'l continue to the issues related to XML. In many cases, I have XML strings as data source, such as configuration files, and data in the format of XML from ADO.Net. JSon.Net provides some APIs to convert from XML to Json strings or vice versa. Based on those APIs, I have added some methods to my wrap class.

The first method is to convert from a Json string to an XML string:

public static string ConvertToXMLString(string jsonString)
{
  XmlNode xmlNode = JsonConvert.DeserializeXmlNode(jsonString);
  string xmlString = xmlNode.OuterXml;
  
  return xmlString;
}

Note: make sure the JsonString must have a single root item on top. If the JsonString contains more than one property values at the top or root, this conversion will throw exception since the converted XML has to have a single root node.

The opposite method is to convert an XML string to a JsonString:

public static string ConvertToJsonString(string xmlString)
{
  var xmlDoc = new XmlDocument();
  xmlDoc.Load(new StringReader(xmlString));
  string jsonString = JsonConvert.SerializeXmlNode(xmlDoc.DocumentElement);

  return jsonString;
}

public static string ConvertToFormattedJsonString(
    string xmlString,
    bool quoteName)
{
  string jsonStr;
  using (MemoryStream msJson = new MemoryStream(xmlString.StrToByteArray()))
  {
    using (MemoryStream ms = new MemoryStream())

    {
       using (JsonTextWriter jtw = new JsonTextWriter(new StreamWriter(ms)))
       {
          jtw.QuoteName = quoteName;
          jtw.Formatting = Newtonsoft.Json.Formatting.Indented;
          jtw.WriteToken(new JsonTextReader(new StreamReader(msJson)));

          jtw.Flush();

          ms.Flush();
          ms.Position = 0;
          using (StreamReader sr = new StreamReader(ms))
          {
              jsonStr = sr.ReadToEnd();
          }
       }
    }
  }

  return jsonStr.Replace(@"\r\n", Environment.NewLine);
}

Depending on the usage, you may need to get a nice formatted JsonString or just a long JsonString.

One reason I added some XML API methods in my wrapper class is that I find out it is very easy to manipulate XML strings by using XML Parser or XMLDoc class. For example, when I get an XML string from a configuration file, before I convert it to an instance, I have to prepare the XML in a correct format. By the time I got Json.Net library, the library did not support XML string with comments(the author promised to handle this issue), So I have to remove all the comments before converting the XML string to JsonString.

Another example is that I may have only one node in XML file as a property value. However, to convert the property value to an array of property values, I have to add a dummy node to XML file so that the JsonString from XML file will be in the correct layout before I map it to an instance. Therefore, I have the following API methods to cover those cases:


public static int AddNewNodeToRefNode(
  ref string xmlString,
  string refNodeXPath,
  string newNodeName,
  string newInnerText,
  bool beforeOrAfter,

  bool firstOrAll)
{
  //  Add a new node to a reference node
  //  ...
}

public static int AddNewNodeToRefNodeAsChildNode(
  ref string xmlString,
  string refNodeXPath,

  string newNodeName,
  string newInnerText,
  bool firstOrLastChildren,
  bool firstOrAll)
{
  // Add new node as a child node to a reference node]
  // ...
}

public static int GetXMLNodesCount(

  string xmlString,
  string nodeXPath)
{
  // Get count of a node in XML string
  // Use this method get count before adding new dummy nodes
  // ...
}

public static string RemoveComments(
  string xmlString)
{

  // Remove all comments in XML string
  // ...
}

public static bool UpdateXMLNodes(
  ref string xmlString,
  string nodeXPath,
  string newInnerText,
  bool firstNodeOrAll)
{

  // Use this method to update XML node content
  // if you use XML as input to JsonString then to Instance
  // and save the changes in Instance back to XML
  // ...
}


This is the conclusion of my serials of brief introduction of Json.Net library and my wrapper class. I'll continue to provide some examples about how to use the library.

Read More...