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.


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.


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!


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 :
  string jsonStr;
  // Date format available?
  if (!string.IsNullOrEmpty(dtFormat))
    JsonSerializerSettings jss =
      new JsonSerializerSettings();
    IsoDateTimeConverter dtConvert =
      new IsoDateTimeConverter();
    dtConvert.DateTimeFormat = dtFormat;
    jsonStr = JsonConvert.SerializeObject(
      instance, f, jss);
    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.