0 Comments

I was perusing stackoverflow.com questions and came upon a question regarding JavaScriptSerializer that I found quite interesting.  I decided to do a quick spike in Visual Studio to find out if I can get answer for the question.  Fired up Visual Studio 2010, created a new Console Application and tried to instantiate a JavaScriptSerializer in my code, but of course, the IDE did not recognize JavaScriptSerializer since I haven't added a reference to the necessary assembly.  In trying to fix that, I launched the Add Reference dialog and chose the .NET tab and scrolled down... and guess what.... no System.Web.Extensions... hmmm...

Thinking the problem through I know System.Web.Extensions is part of .NET 4 (which was installed when I installed VS 2010), so how come it is not available in the Add Reference dialog?

After a bit more thinking I came to realize that it's probably because Console Application is targeting the .NET Framework 4 Client Profile which does not include all the web stuffs in it.  Switching the Target framework to .NET Framework 4 (Full profile) from the Project Property, Application tab, solved the problem.

0 Comments

When you use .NET Activator.CreateInstance to create a new object of a certain type, make sure you reference the Project / DLL that contain the type definition or load it manually somehow to an AppDomain.  Otherwise your call will fail. Say you have the following solution:

Solution Foo
    Project Bar1
        IUser
        IDataMapper
          IUser Load(...);
    Project Bar2 (references Bar1)
        ADSpecificDataMapper : Bar1.IDataMapper
          IUser Load(...) { ... }
    Project Bar3
       User : IUser
          IDataMapper m_Mapper = Settings.Instance.UserMapper
          IUser Load(...) { return m_Mapper.Load(...) }
    Project Baz (references Bar1)
        Settings
           Settings Instance = new Settings() //singleton
           IDataMapper Mapper = CreateMapper(ConfigurationManager.AppSettings[...])
           IDataMapper CreateMapper(SpecificMapperClassNameFromAppConfig)
    Project ConsoleTester (references Baz, Bar3)
       Main
          IUser user = User.Load(...);

Note that ConsoleTester is not referencing Project Bar2 (which contain the ADSpecificDataMapper that will be created through the Factory Method CreateMapperin Baz.Settings class.  This will cause it to fail.  Adding Bar2 to the ConsoleTester project reference will remedy the problem.

0 Comments

I was reading this particular entry from AlexJ's blog, in which he discussed how to use anonymous type returned from one function in another function.  I strongly recommend you read it first before reading any further.

Basically, most people would think that there is no easy way to return a strongly typed anonymous type from a function since you wouldn't know what it is that you are returning beforehand. Thus, if you wish to return an anonymous type from a function, you are forced to return it as object like so:

object CreateAnonymousObject() 
{
    return new { Name = "John Doe" };
}

The problem of doing it like this is that you lost the ability to access the Name property since object does not have a Name property.  So, your option is to cast it back to its original anonymous type, but alas, how could you do it?

It turned out that there is a way to do this using generic.  If you create a generic function that will return a generic type T and also pass an object of type T in the parameter, you can cast whatever object that you pass as T.  In effect, you are using the object of type T as your example to cast the boxed object to.  See the following code:

T CastByExample<T>(object source, T example)
{
      return (T)source;
}

So now, you can do something like this (for the sake of clarity, I am not going to shorthand these examples):

var o = CreateAnonymousObject();
var prototype = new { Name = "" };
var result = CastByExample(o, prototype);
Console.WriteLine(result.Name); //This should work just fine

To make things a little bit easier to read, we can use the new extension method feature of .NET 3.5 like so:

public static class MyExtensions
{
    public static T CastToTypeOf<T>(this object source, T example)
    {
        return (T)source;
    }
}

And rewrite the example to:

var o = CreateAnonymousObject();
var prototype = new { Name = "" };
var result = o.CastToTypeOf(prototype);
Console.WriteLine(result.Name); //This should work just fine.

This is great.  I don't know what I am going to use it for, but it's nice to know that I can do it when I need it.

And then, another idea comes to my mind.  Hey, what if we need to do similar thing to an anonymous object collection.  How could I do that? How could one creata a generic list of anonymous object?  As it turned out, Kirill Osenkov already solve this particular problem.  You can see it here.

So, let's come up with something interesting to explore this problem.  Lets say that you are querying a Contact database through LINQ, but instead of returning the entire Contact fields, you wish to only return some of them.

Making thing simpler, I decided to mock the Contact class like so (too lazy to create a dbml, so I am querying from in-memory object :) ):

   public class Contact
   {
       public string FirstName { get ; set; }   
       public string LastName { get; set; }   
       public string PhoneNumber { get; set; }   
       public string StreetAddress { get; set; }   
       public string City { get; set; }
   }

And here is an example function that will return you a list of Contacts:

IEnumerable<Contact> GetContacts()
{
    return new List<Contact> {
        new Contact {
            FirstName = "John", 
            LastName = "Doe", 
            PhoneNumber = "555-5501", 
            StreetAddress = "123 Lala Lane", 
            City = "Los Angeles" 
        },           
        new Contact {
            FirstName = "Jane", 
            LastName = "Doe", 
            PhoneNumber = "555-5502", 
            StreetAddress = "567 Lala Lane", 
            City = "New York" }       
        };
    }
}

And you only wish to return the FirstName and LastName from your LINQ query like so:

var query = from c in GetContacts()
            select new { Name = c.FirstName + " " + c.LastName };

Again, for whatever reason, you really really want to encapsulate this as a method, so, you do something like this:

    object GetContactNamesFrom(IEnumerable<Contact> contacts)
    {
        var query = from c in contacts 
                    select new { Name = c.FirstName + " " + c.LastName }; 
        return query.AsEnumerable();
    }

Great!  Now you have something that can return a generic collection of an anonymous type.  But how can we use this in our own function and allow our function to access the Name property?

Well, combining what we've learnt so far, we can come up with something like this...

First, we know we can now cast something to an anonymous type (sort of) using the generic method CastByExample or CastToTypeOf as seen above.

Second, we need a way to create an anonymous collection.

Let's start with the second one first.  We need a way to create an anonymous collection.  So let's think about this a bit.  i hope you've read the blog post by Kirill by now.  If not, well, here is how you do it...

Now you can do something like:

var prototype = new { Name = "" };   
var prototypeCollection = CreateEnumerablesByExample(prototype); //This is now a generic collection of anonymous.

What's left for us to do is cast our LINQ result back as the prototypeCollection so we can get access to the Name property from our code like so:

var contactInfo = GetContactNamesFrom(GetContact()); 
var prototype = new { Name = "" }; 
var prototypeCollection = CreateEnumerablesByExample(prototype); 
var result = contactInfo.CastToTypeOf(prototypeCollection);
foreach (var c in result)
{
    Console.WriteLine(c.Name);
};

We can do one better by using extension method.  Let's refactor CreateEnumerableFrom as an extension method like so:

public static IEnumerable<T> CreateEnumerablesOfThis<T>(this T prototype)
{
    return new List<T>();
}

The refactored code of our final example will look like this:

var contactInfo = GetContactNamesFrom(GetContact()); 
var prototype = new { Name = "" }; 
var protoypeCollection = prototype.CreateEnumerablesOfThis(); 
var result = contactInfo.CastToTypeOf(prototypeCollection);
foreach (var c in result)
{
    Console.WriteLine(c.Name);
}

So, why would go through all these trouble?  Honestly, I have no idea.  I am just exercising my brain just to see if I can do such a thing.  I have no real need for this type of things yet.  Who knows... maybe someday...

0 Comments

As usual, I started my day perusing hundreds RSS subscription (I used to use Outlook for this, but I am getting to like Google Reader more and more).

Lots of neat stuffs you can find just reading other people's writing.

For example:

http://thewpfblog.com/?p=92 (Talking Anna WPF application)

Funny thing is, although not as fancy as this WPF app, I was playing around with Vista Speech Synthesizer in .NET about a couple of weeks before and created the following console application in VS2005 and Windows SDK for Vista (you need to reference System.Speech.dll for this to work):

using System;
using System.Speech.Synthesis; 

namespace SpeechTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SpeechSynthesizer ss = new SpeechSynthesizer())
            {
                while(true)
                {
                    Console.Write("Enter what you want me to say:");
                    string s = Console.ReadLine();
                    if (s.Trim().Equals(string.Empty))
                        return;
                    ss.SpeakText(s);
                }
            }
        }
    }
} 

Which work just fine minus all the fancy stuffs in Talking Anna.

To read more about this, you can peruse this MSDN magazine article.

http://www.researchchannel.org/prog/displayevent.aspx?rID=11087&fID=2740 (Designing .NET Class Libraries)

It feels good when what you are doing get confirmed by one of the experts like Krzysztof. He was talking about how to design class library (in this case .NET Framework itself) and how Microsoft staffs would write a sample code first on how the code would look like before even going to the case tools for diagramming, etc. I've been doing this sort of thing as long as I can remember when designing my own class library.

0 Comments

Most of the time I found myself working with Console application in .NET Framework is when I want to create a spike / test on a concept or idea.

Really... what is there to be excited about the old plain Console?

All you do mostly is: Console.WriteLine(...), yes?  And maybe a Console.ReadLine() at the end to stop the Console window from being closed automatically before you can see the results you want.

This is all too true in .NET Framework 1.x....

But not in 2.0...

Perhaps it's just me, but I didn't really bother looking over what's new in the Console class until recently.  And to my surprise. They added a lot of improvement into the class.  Like the ability to position the cursor, changing color, etc.

Take a look here: http://msdn2.microsoft.com/en-us/library/system.console_members.aspx

Being the geek that I am, I couldn't help myself but being excited when I discovered this.  Even if it is not truly something new, but it brought back a lot of memories, a trip to memory lane if you will,  to the days when I was still doing DOS based development in Pascal, QBASIC, and the like.  Creating my own windowing framework and control libraries in QBASIC and Pascal :)

Oh... what fun :)