Thursday, September 17, 2009

LINQPad as a .Net Snippet Code IDE

InI Posted a very simple question about "a ? b : c" expression to Stackoverflow last night. I was at Cafe with my friend discussing a case of this expression: if b and c are different types. Since we did not have Visual Studio available to test my codes out. I posted the question to Stackoverflow. Within minutes, we got several answers to confirm my guess: a Cast can be used before either one to make them the same type. The question is indeed a very simple one. However, this lead to a new discovery, at least for me, of a great IDE tool, only one EXE with 2MB size, for .Net C# snippet codes.

The tool is called as LINQPad. Its user interface is very simple. On the top are menus and tool bars. The left panel is for Database connection or database structure list. The right panel is composed of top and bottom parts: code IDE and result view. This tool supports C# & VB expression, statements, programs, and SQL. It is very easy to use. However, it is very buggy. This morning I give it a try. After I added a reference to my library and added several my namespace lists. I could not to get a simple Console out work in a new tab when I tried to show it to my work colleges. I had to restart the application and removed references and namespaces to get it back to work.

All the codes can be saved an xml file. Within the xml file, all the references, namespaces, and code snips are saved there. It is really cool. No wonder a user who answered my question recommended me to try this tool. I guess he knew I had no VIsual Studio available. We actually had a Mac computer.

The project is not an open source project. It is a closed project. The standard version is free and an advanced version with auto-completion feature is for sale. After I give it a thought for this back engine, I guess that application is not hard to create. I would use the .Net CodeCom namespace as .Net compiler engine to create a dynamic project with a template for a snippet as plug in codes, just as I posted in my previous blogs. The dynamic project could be a simple console application> if it compiles OK, then run it through Process class. The process is hidden and all the outputs can be redirected as output back to the application. The application interface parts can be done with MEF framework so that each view parts can be plugged with various UIs to support IDE code editor (such as supporting syntax color schemas for various languages), result view (grid or table layout) and other views.

With this structure, LinPad should be an open source project so that talent developers can make it much better and extendable. One person's dedication is great, but with Web world available, great resources from the world should be utilized.

Read More...

Tuesday, September 15, 2009

My Stackoverflow Reputation Points Reach to 1K

Today my reputation score at Stackoverflow reaches to 1007 points! The recent question on Parse String to Enum Type boosts my score over 1K points. I could touch this target earlier than up to today, but my main intention to use this web site is to help me to get the best and the quickest resources and answers for my programming questions or issues. I have not focused on gaining scores or badges at all. Therefore, I only spend some time to search and answer other people's questions when I have time.

The following is my statics:

  • Score: 1007
  • Badges: 15 bronze badges
    • Popular questions: 7
    • Tumbleweed: 1
    • Scholar: 1
    • Organizer: 1
    • Editor: 1
    • Commentatior: 1
    • Teacher: 1
    • Supporter: 1
    • Student: 1
  • Questions asked: 86
  • Questions answered: 34
  • Votes: 70
  • Tags: 66

With Stackoverflow, it have been my great resources to helpresolving my questions and issues. I got many great answers and explanations for my program questions. Normally, if I cannot resolve my issue within short period time, or I have concerns about my strategy, or just want to consult experts, I post my questions there. In most cases, I get answers in just less than 5 minutes. Sometimes, I have to wait longer. Soon I learned that I don't need to mark the quick response as answer right away. People compete on Stackoverflow for earning score points. However, sometimes, good ones may not be the quick ones. Just wait for the good ones.

Unfortunately, recently I cannot access Stackoverflow from my work by using my Blogger OpenID. Husky would not allow me to access to my Blogger login web page. I had to create another account (David Chu) by using Google OpenID. With that account, I have about 185 score points. I was reluctant to use that account to ask questions initially, since I preferred to use one account to accumulate scores. However, I do need to get my issues resolved during my work most of time. Therefore, recently I started to use that account more. Still if I can wait, I'll post my questions after work or early in the morning. That's the reason my reputation score points have grown slow. By the way, the total score of points of my two accounts have reached 1K more than one month ago.

Anyway, I set 1k as a target day to celebrate my reputation on Stackoverflow.

Cheers!

Read More...

Sunday, September 13, 2009

Free CodeRush Xpress Tool by DevExpress

toolsDevExpress released a free tool for .Net Visual Studio 2008 users: CodeRush Xpress. I found this out from DVRTV show 143: Mark Miller on CodeRush Xpress.

I knew this tool for long time but I have never tried the tool as I used Resharper before. With the free offering, I tried this re-factory tool right away. It is a nice tool for .Net developers. But I found that some features are not working such as Tab to Next Reference and Template snip codes for switch and for loops. Maybe there are some option settings I have not set up yet. I also realize that the tool does provide hint on the left scroll bar to indicate questionable codes such as greying out unreferenced using statements, like Resharper has (which provides hints as yellow marks).

Here are some additional links related to this tool:

Read More...

Sunday, September 06, 2009

CodeDom and Expression Calculator (2)

In order to compile a snip of codes dynamically, I need to define a template in the class of ExpressionEvaluation so that it can be used as a base. The template contains several parameters which will be replaced (such as a class name, a data type and an expression). I defined a string with parameters enclosed by {} so that those parameters can be easily replaced by dynamic values (string.Format(template, parameters...)).

Here is the template of snip codes in the class:


using System;
using System.Reflection;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

public class ExpressEvaluation { // class name
  private const string _InitalizeValueCode = "private {0} _value = {1};"; // valType, valExp
  private const string _ClassName = "_CalculatorWithFormula"// 0
  private const string _MethodAnswer = "Answer"// 1
  private const string _SourceCodeTemplate = @"
using System;
public class {} {{ // {{0}} Class name
  {2}
  public {} {1}()  // {{1}} method to be called to get result
  {{
    return _value;
  }}
}}";


  public int GetAnswer()         // method to get result as type
  {
    return _value;
  }
}


The key methods in the class are BuildCodes() and GetAnswerByBuildAndRunCodes():

private static string BuildCodes(
    string valueExp,
    string varType)
{
    string initializeValueCodes = string.Format(
            _InitalizeValueCode, varType, valueExp);

    string codes = string.Format(_SourceCodeTemplate,
        _ClassName, _MethodAnswer, initializeValueCodes, varType);

    return codes;
}

private static T GetAnswserByBuildAndRunCodes<T>(
    string sourceCodes) where T : struct
{
    object value = default(T);
    CompilerResults cr = GetCompiler(sourceCodes);

    var instance = cr.CompiledAssembly.CreateInstance(_ClassName);
    Type type = instance.GetType();
    MethodInfo m = type.GetMethod(_MethodAnswer);
    value = m.Invoke(instance, null);

    return (T)value;
}

Those two methods are very straightforward. In GetAnswserByBuildAndRunCodes(), a method GetCompiler() is called to get a C# CompilerResults object in the current context:

private static CompilerResults GetCompiler(string codes)
{
    CSharpCodeProvider codeProvider = new CSharpCodeProvider();

    CompilerParameters parameters = new CompilerParameters();
    parameters.GenerateExecutable = false;
    parameters.GenerateInMemory = true;
    parameters.IncludeDebugInformation = false;

    foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
    {
        parameters.ReferencedAssemblies.Add(asm.Location);
    }

    return codeProvider.CompileAssemblyFromSource(parameters, codes);
}

Here is the complete source codes for download.

Read More...

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...

Saturday, July 25, 2009

LINQ and Lambda Expressions in .Net 3.5

I began to switch to .Net 3.5 framework and to use Visual Studio 2008 about couple months ago. As a experienced .Net developer in 2.0 for many years, I did not notice the big difference at the beginning. When I created a new project or new class, I saw Visual Studio adding System.LINQ, System.Data and System.XML automatically. Since I did not use any classes from those namespaces, I had to remove or delete them manually. I felt quite annoying. I had been basically writing the .Net 2.0 codes. Of course, I took advantage of Property features at the start point and that one makes codes much simpler than before.

Until the last week, I started to realize the simplicity and power of .Net 3.5 framework. Actually, it started to get my attention from some people's blogs, open source codes, and especially from Stackoverflow. The initial trigger was to search for something in a collection. I have quite good experience to use anonymous delegate to search for item or items in a collection. Then I tried to ask people about the same search in LINQ and Lambda expressions:


I got so many great answers and alternative ways to do the job by using LINQ and Lambda. I really like them. They are more descriptive and shorter. As you can see the performance difference is not a big deal, even LINQ is marginally with small amount of time slower. When I start to use them, I think the approach in much easy way. Since the codes are more descriptive, it makes my code maintenance much easy. I can recall the logic of codes much fast.

Therefore, I have to keep change and update my skills along the time. It is good to upgrade my knowledge and skills to another level and it has been really enjoyable experience.

Read More...

Sunday, July 19, 2009

My Favorite Browser Still FireFox

Google has launched its Chrome for a while. It was very impressive in terms of its peed and simplicity. I enjoyed it very much. It does have have Mac version and it is still in development stage.

Apple released Safari for Windows for quite a while, but the most impressive version is the recent 4.0. It is speedy fast and has vice nice interface. I like its' Top Sites and History, with Cover Flow Interface. I actually has been used it a lot. For most of my web surfing, I start to use Safari.

However, as a developer, I cannot live without FireFox. The main reason for this is my favorite add-ins: Vimperator and Firebug. In addition to that, its context menu item "See selection source" is very convenient for me just viewing partial source html codes. Safari, on the other hand, does have this choice at all! Therefore, I actually use two browsers most of time. If I cannot get what I get from Safari, I then switch to FireFox. From my experience, I think this is the best choice. Just depending on one browser only is not practical at all. The biggest problem for FireFox is that it does crashes constantly and very slow sometimes(launching at start and loading pages), comparing to Safari. I think this might be caused by Add-ins.

Safari has a list of very convenient short-cut keys. The most keys I used are:

  • Command-L: jump to URL address area
  • Command-W: close tab
  • Command-T: new tab
  • Command-R: refresh tab

With those keys, I can do similar quick actions like I use Vimerator in FireFox. However, one thing is missing in Safari is undo closing tab!

Talking about speed, I found Opera actually very fast in one case. For this web site, vimcolorschemetest, there are some links to lists of vim color schemes, C for example. All those schemes are in frames, with hundreds of frames. I tried with both FireFox and Safari, both are very slow to load all the frames, but Opera is fast! Even though, I rarely use Opera since I can get most from Safari and FireFox.

Read More...

Network Drive Mapping Class

Today my friend asked me a question about how to map to a network share-point as a local logical drive with user name and password. I recalled that I had written a utility class to do that.

Basically this static class contains two methods: MappingDrive() and UnMappingDrive(). The first one is used to map to a network share point by its path, user name and password, as well as a specified local logic drive name. The unmap method just takes one parameter of a mapped drive name.

There are many ways to do that. I saw many people using Windows API method. However, I don't like that. The reason is that 1) API are un-managed codes based on dynamic library dll files; and 2)possible un-catchable exceptions, which are very nasty for applications. To map to a network shared point, it is very possible to pass incorrect parameters. Then I found a simple way to do it: by using .Net Process to shell net.exe, which is one of core Windows utilities. Actually, I have used this many times in cmd console. I think most Windows UI tools, including File Explorer, may rely on this tool to do the job.

When I revisit my codes today, I saw that MappingDrive() method is checking if the specified drive is already mapped or not first. If it is true, it will un-map and remap it again. It is done behind sense. This may un-map other people's mapping. I keep this logic and remind my friend about the logic.

I also updated the class with some changes. First, I expose the previously private method of IsMappedDrive() as public. Secondly, I added two methods: GetLocalDrives() and GetLocalUnusedDrives(). The first one is very simple. It is based on System.IO.Directory.GetLogicalDrives(), but I think the second one is more useful. It will get all the un-used local logical drives, which depends on the first method.

Finally, I uploaded this simple NetworkDrive class to my code project. Enjoy it!

Read More...

Wednesday, July 08, 2009

Json.NET and Its Usage (2)

In this blog, I'll continue to describe my wrapper class based on Json.Net. The main reason I want to write a wrapper class to hide Json.Net is to provide only APIs I am interested in. Json.Net provides a rich framework of classes, interfaces, types, and enums. I don't know all of them. In practice, there is no need to know all.

The second reason is to break direct dependency on Json.Net. My wrapper class provides all the APIs I need. There may be some cases in the future that a better library available than Json.Net or some potential problems preventing me from using Json.Net. Then what I need to do is to rewrite the wrapper class's internal implementation without change my application or libraries which are dependent on the wrapper class. Actually, I find this the best practice to use other library or components.

I created a common .Net library, DotNetCommonLibrary, with some common and generic classes, including my wrapper class for Json.Net. The first thing I need is to add a reference to Newtonsoft.Json to the library.

Next, I include the following namespace in the wrapper class:

# region Using
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Newtonsoft.Json;
using JsonFormatting = Newtonsoft.Json.Formatting;
using Newtonsoft.Json.Converters;
# endregion

The wrapper class is called as JsonXMLHelper. The class does not contain any private instance data, therefore, the class is a static class.

public static class JsonXMLHelper
{
...
}

The first method is a simple one: convert a Jsonstring to an instance.

public static T GetInstance<T>(
  string jsonString)
  where T : class
{
  T instance = JsonConvert.DeserializeObject(jsonString, typeof(T)) as T;
  return instance;
}


Vice-versa, there is the method to convert instance to Jsonstring:


public static string GetJsonString<T>(
  T instance) where T : class
{
  return GetJsonString<T>(instance, false);
}

public static string GetJsonString<T>(
  T instance,
  bool indented)
  where T : class
{
  return GetJsonString<T>(
    instance, indented, true, null);
}

public static string GetJsonString<T>(
  T instance,
  bool indented,
  bool quoteName,
  string dtFormat) where T : class
{
  JsonFormatting f = indented ?
    JsonFormatting.Indented :
    JsonFormatting.None;
  string jsonStr;
  // Date format available?
  if (!string.IsNullOrEmpty(dtFormat))
  {
    JsonSerializerSettings jss =
      new JsonSerializerSettings();
    IsoDateTimeConverter dtConvert =
      new IsoDateTimeConverter();
    dtConvert.DateTimeFormat = dtFormat;
    jss.Converters.Add(dtConvert);
    jsonStr = JsonConvert.SerializeObject(
      instance, f, jss);
  }
  else
  {
    jsonStr = JsonConvert.SerializeObject(
      instance, f);
  }

  if (!quoteName)
  {
    jsonStr = ConvertToFormattedJsonString(
      jsonStr, quoteName);
  }

  return jsonStr;
}

GetJsonstring() has several overloads, which provide options to specify if a Jsonstring is indented, if a quote " char is used for Jsonstring names, and what is the format for DateTime type. By default, a Jsonstring is not indented as one long string and Json names are quoted by ", and DateTime values are displayed in the format of Date(tick_numbers). I need to log some instances as Jsonstrings in a nice and readable format. Those overloads provide options I need.

I used this GetJsonstring() method a lot. It saves me a lots of time to override ToString() method to format instance in a nice string. The most frustrated thing is that when I update class property names, I often forget to update ToString(). With this API method, I don't need to worry about this.

I even don't need to override ToString() any more. I can directly call this method with an instance to get a nice Json string. It is the most handy way to print or log .Net or third party class instances. You can even print or log an instance of List<T> type, but be prepared for very long strings.

Read More...

Tuesday, June 23, 2009

Json.NET and Its Usage (1)

Json.NET is an open source project by James Newton-King. I have used this framework in my project in the past months and I am really enjoying its simplicity and power.

I mainly use this framework to convert objects or instances to an Json string or XML string, vice visa. The framework provides many classes but I only use a very small set of them. For my purpose, what I need its classes related serialization and de-serialization. Based on my practice and experience, I wrote a wrapper class with several methods for my usages. I like to wrapper Json.NET framework is based on the following reasons:

  • To hide Json.NET from its clients or users. As a result, users will not see Json.NET or need to add reference to Json.NET. All my projects need is to reference to my wrapper class.
  • To provide a clean and simplified set of methods for my usages. This relates to the previous reason. Users will not see rich and complicated Json.NET framework.

Basicaly, I use Json.NET for the following usages:
  • Configuration file for applications; and
  • Simplify my overrides of ToString() methods for classes.


Microsoft .Net provides framework for configuration. By default, you can have configuration in XML files like app.config or web.config. The problem is that the configuration file is very restrict in sense of its structure. You have to follow its XML structure to put your settings there. The most annoying thing is that when you save some settings, whatever comments you used as reference will be gone.

I like to write configuration in any way I would like. With Json.NET, this is possible. The configuration file can be either Json string or XML string in a file. Both of them can be easily converted or mapped to an instance of a class, called as configuration class. For example, I load my XML configuration file by using TextReader class as XML string. Then I convert it a Json string. From Json string, I use Json.NET to deserialize it to an instance of my confiugration class.

In case I need to make changes of some configuration settings, I use XMLDocument and Parser classes to make changes in XML string and leave other parts not touched. Finally I save the XML string to my configuration file.

For my purpose of overriding ToString() methods, before Json.NET I had to write hard codes to format property values to a string. This is really inconvenient. If I make changes of property names, I have to remember to change my ToString(); otherwise, my ToString() is unsynched. I do need to override ToString() when I need to debug my codes into a log file. With Json.NET, I can simply to serialize instance of this to a Json string. The serialization takes care of all the properties in a nice Json style. This is really very handy!

I'll continue to discuss my wrapper class in detail in my next blog.

Read More...

Thursday, June 18, 2009

Google's aBowman

This is a very interesting gadget from Google. I was search in Google this evening. Then I was asked to sign in to Google. After I signed in, I quickly got to aBowman page.

Gadgets >> Hamster



I was using Firefox with this web page. I found this hamster. There is Get & Share section under the gadget, such as send email and blogger. I tried to send email and add to blogger, but I could not type in any words in the text area. Not sure why. Anyway, I copied the link to Safari and everything is working there. It is much faster when I am in Safari. However I could not use Vimperator in
Safari.

Read More...

Saturday, June 06, 2009

Dependency Injection and StructureMap (5)

In my preview articles, I have covered most commonly cases to describe dependency mappings. In this article, I'll conclude this series with chained registry strategy.

For many applications, there may be a lots of relationships between interfaces and implementations. You could define all those DMs in one Registry DSL library. However, I prefer to break them into several libraries and chain them together. The advantage of this strategy is to make the DM library easy to maintain and reusable.

The key in StructureMap Regisry DSL is to define a customized class based on Registry. Therefore, in each chained library, you should define your DMs in one or more Registry classes. The root library of the chain will call all the other libraries to get lists of Registry instances and add them to StructureMap framework.

For example, I have a console application, called as MyConsoleApp, which needs an implementation instance of IProcessControler. I'll create a SM library, SMForMyConsoleApp to define the DM, and it only defines the mapping relationship: how to create or map implementation class to IProcessController. The implementation class may need other implementations for other interfaces such as IDataReader, IDataProcessor and IDataWriter, but those mappings are from other chained libraries, where implementation mappings are defined.

The SMForForMyConsoleApp has two classes:

public static class SMForMyConsoleApp {
private static _registered = false;
public static void Initialize()
{
if (!_registered )
{
IEnumerable<Registry> listRegs = SMResgiry.GetRegs();
ObjectFactory.Initialize(x =>
{
// Get registry list from other Registry classes
// and add them to x
// ...

foreach (Registry reg in listRegs)
{
x.AddRegistry(reg);
}
}
}
}

public static T GetInstance<T>() where T: class
{
T instance = default(T);
if (typeof(T) == typeof(IProcessController>))
{
instance = ObjectFactory.GetInstance() as T;
}
return instance;
}
}


internal class SMRegistry: Registry {
// CTOR
public SMRegistry() {
// define the DMs
}

public static IEnumerable<Registry> GetRegs()
{
List<Registry> list = new List<Registry>();
// Add registry from other chained registry
// ...

list.Add(new SMRegistry()); // finally add this instance
return list;
}
}


The class SMForMyConsoleApp has two static methods. Initialize() is used to add all Registry instances to StructureMap framework. This method should be called in MyConsoleApp to initialize mappings. The second method GetInsance() is used to get mapped instance, for IProcessController in this example, and then start the process.

Other chained SMxxx libraries have similar structure. In this way, the console application's mapping library does not need to know the complete mapping relations. It will let sub/chain libraries to do the mapping. You can see, this is a very clean strategy with great flexibilities.

Read More...

Tuesday, June 02, 2009

Finishd iPhone classes on iTunes by Standford U

Today I finished all the 16 classes, as well as some lectures by guests on iTunes. Not sure if there are any more coming or not. Anyway, it is really good program. It does provides very clear and overall picture about iPhone development. It helps me a lot to understand Cocoa and Object-C.

With many years of .Net development experience, I have to relate some aspects to .Net C#. Cocoa and Object-C are really interesting framework and it looks very powerful. I really like their unique features.

For example, objective-C is a dynamic type language. You can add or define properties or methods dynamically and you can call on methods without worry their existence. Calling a method on nil will not cause any exception. Of course, it is controversial issue, as the instructor mentioned. No exception may bring some bugs. You expect some results but nothing happening. However, xCode and some tools are available to help to detect all those issues.

Another great feature is the delegates in Cocoa and Objective-C. They look like methods defined in an interface in .Net, but they can be optional. SEL is a great will to describe delegates and it is widely used to describe and detect their availabilities. Delegate is a way to delegate actions to objects to inject actions instead inheritance. This provides valuable flexibility to delegate class or object to take responsibilities.

Cocoa framework provides many functions, classes and controls which makes Mac and iPhone development much easy with great features. Cocoa and Object-C works well C codes. This provides much wide range of APIs and tools from open-source world, or you can build tools and libraries based on them.

I have been watching those class shows in the past weeks, one show a day during business days and two shows on weekends. Now I finished all of them. It is time to roll my sleeves up and start a new adventure in Mac & iPhone development.

Read More...

Tuesday, May 26, 2009

iPhone Dev Classes by Stanford U

In the pass week, I have been watching iPhone Application Programming classes offered by Stanford University. I read a news on AppleInsider about Free Stanford iPhone dev podcasts downloaded 1 million times. Then I started the course.

Now I have watched 9 classes, one day a class during week days and two classes one day last weekend. It is really good program. I started to learn iPhone programming last year. I got iPhone SDK 2.0. I went to Apple's Dejavascript:void(0)veloper web page on iPhone. During evenings, I have read all the SDK documents and tried to use XCode to study some example applications. All those laid great foundation for me. This makes much easy for me to understand Object-C and Cocoa. I think after completion of the course, I am ready to put my hands on iPhone applications. I am really exited about this new journey!

Read More...

Monday, May 18, 2009

Dependency Injection and StructureMap (4)

In addition to the methods of dependency mapping described in my previous blog, SM provides several other alternative methods to describe the DM.

I use two common methods to specify how instances are created. One is IsThis() and another is ConstructedBy(). The first method takes one parameter as instance and the later one takes function name as parameter. The function returns an instance. Of course, you may create an instance and pass it by the first method. However, the instance must be a none-null instance, while the second method with function may return a null as DM.

For example, if ILog's mapping to instance is a LogToFile class:

public class LogToFile {
public LogToFile(
string file,
TextWriter standardOutput,
TextWriter errorOutput) { ... }
}


In the Registry class' CTOR, the DM then is described as:

internal class SMRegistry : Registry
{
private Configuration _config;
public SMRegistry(Configuration config)
{
_config = config;
ForRequestedType<ILog>().CacheBy(InstanceScope.Hybrid).
TheDefault.Is.ConstructedBy(GetLog);
...
}
private ILog GetLog()
{
ILog instance;
TextWriter writer1 =
_config.StandardOutput ? Console.Out : null;
TextWriter writerErr =
_config.ErrorOutput ? Console.Error : null;
instance = new LogToFile(_config.logFile,
wrtier1, writer2);
return instance;
}
}

where config is an instance of Configuration class which is loaded from an XML file. The LogToFile class CTOR takes a file name as log file name, and additional two TextWriter parameters as standard output and error output. The private function GetLog() is passed to ConstructedBy() to map an instance of ILog.

The above Registry can also be coded in this way:

internal class SMRegistry : Registry
{
private Configuration _config;
public SMRegistry(Configuration config)
{
_config = config;
ForRequestedType<TextWriter>.CachedBy(InstanceScrop.Hybrid).
TheDefault.Is.ConstractedBy(GetTW()).
WithName(LogToFile.StandardOutPutName);
ForRequestedType<TextWriter>.CachedBy(InstanceScrop.Hybrid).
TheDefault.Is.IsThis(Console.Error).
WithName(LogToFile.ErrorName);
ForRequestedType<ILog>().CacheBy(InstanceScope.Hybrid).
TheDefault.Is.OfConcreteType<LogToFile>().
ConstructedBy(GetLog);
...
}

private ILog GetLog()
{
return new LogToFile(_config.LogFile,
ObjectFactory.GetNamedInstance<TextWtiter>(
LogToFile.StandardOutPutName),
ObjectFactory.GetNamedInstance<TextWtiter>(
LogToFile.ErrorName));
}

private TextWriter GetTW()
{
return
_config.StandardOutput ? Console.Out : null;
}
}

This example shows how to use IsThis() method for an instance. LogToFile.StandardOutputName and LogToFile.ErrorName are constants defined within LogToFile class.

Here you can see SM's Registry DSL provides much flexible way to describe DMs.

Read More...

Another Example of Fluent Interface

As in my previous blog posts, Fluent Interface pattern makes codes very simple and easy to read. The key point of FI is to define a class with methods returning a type of the class itself. As a result, you can continue to call its methods to manipulate data within the class. I have seen this pattern in jQuery and Dojo.

Normally, we define a class with a constructor to initialize its data members when an instance is created, and all those data members are not editable or no setters are defined. As a result, the class has its limitation only for one set of cases. If you want to define different set of data with manipulation by methods, you have to recreate objects again.

With FI pattern, here is another example to define a class to handle various data cases. Instead of passing data through CTOR, you can set data by using a method and the the return type of the class is the class itself, for example:

class MyFICalc {
private int _result;
private int _leftVal;
private int _rightVal;

public MyFICalc SetData(int val1, int val2) {
_leftVal = val1;
_rightVal = val2;
return this;
}

...
}


An instance is created by its default CTOR and data are set by the method SetData(). The method SetData() return a reference to itself. With this structure, further methods on data are defined to get expected result.

For example, I define a set of calculations:

  int  Add() {
return _leftVal + _rightVal;
}

int Subtract() {
return _leftVal - _rightVal;
}

int Multiply() {
return _leftVal * _rightVal;
}


Here are some example of uses:

int result;
MyFICalc calc = new MyFICalc();
result = calc.SetData(2, 3).Add(); // 5
result = calc.SetData(300, result).Subtract(); // 295
result = calc.SetData(result, 4).Multiply(); // 1180

Of course, this is a very simple example. In practice in one of data reading from database case, I have used FI in this manor in a loop for each row to set data and then continue to update data based on business logic. In this way, I would not need to constantly create instances. I just reuse my instance to set data and to get my result.

Read More...

Wednesday, May 13, 2009

Dependency Injection and StructureMap (3)

SM uses Fluent Interface(FI) to describe dependency mapping relationships. The FI description is to read and straightforward. You may find out various ways to describe the dependency mapping(DM) relationships. Personally, I prefer to use FI in the following format:

[For a required type].[Use a cache mechanism].[Map to a specific type]

The first part is normally for an interface type, but it can be concrete class type. The caching method is an enum type. It covers almost all the cases such new instance per request, singleton, one instance within a thread, HttpContext, HttpSession and more, see SM's documentation on Scroping and Lifecycle Management for detail information.

For the example case as described in the previous blog, here are the codes to describe ILog dependency mapping:

public class SMRegistry : Registry
{
public SMRegistry (
Configuration config)
{
ForRequestedType<ILog>().
CacheBy(StructureMap.Attributes.InstanceScope.Singleton).
TheDefault.Is.OfConcreteType<Logtofile>().
WithCtorArg(LogToFile.CtorArgFile).EqualTo(config.FileName).
WithCtorArg(LogToFile.CtorArgLogFlags).EqualTo(config.LogFlags);
...
}
}

Where config is an instance of Configuration class. This instance contains configuration (loaded from xml file) to be passed to concrete instances.

ILog interface is mapped to class LogToFile. This class CTOR takes two primitive string parameters one for file name and another as log flags. Here you can specify the primitive parameters using WithCtorArg(...).EqualTo(...) pattern. Notice that the parameter name in WithCtorArg has to be exactly as same as the one used in the CTOR and it is case-sensitive. I prefer to define a public const in CTOR's class.

I want to skip the dependency mappings for IDataReader, IDataProcessor and IDataWriter. You can image continuing to do similar mappings for them. I'll discuss how to use SM's Registry to do mappings in a structured chain manor.

Now let's look at how to define DM for IProcessControl to a concrete class in the SMRegistry' CTOR:

    ForRequestedType<IProcessController>().
CacheBy(StructureMap.Attributes.InstanceScope.Hybrid).
TheDefault.Is.OfConcreteType<ProcessController>().
WithCtorArg(ProcessContoller.CtorArgID).EqualTo(config.ID);

That's it. Recall that ProcessController's CTOR has five parameters, but only one is primitive type. Other four are instances as interface types. Those interfaces can be defined in a similar way as ILog. As a result, SM has the knowledge to inject concrete instances for those interface parameters. As I said before, you don't need to create instances in your application, you just tell SM the DMs and how. SM will inject instances for you.

If a CTOR's parameter has one concrete class parameter, you can still implement the similar way to do DM. I'll explain it later.

Read More...