This post will give an introduction to JSON, and also I'll share a couple of handy C# extension methods to handle serialization and de-serialization of JSON (Java Script Object Notation) Data. from your Silverlight apps

To know more about JSON format, check out the http://www.json.org - To quote,
JSON (J avaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. These properties make JSON an ideal data-interchange language.

Understanding JSON


In JSON, any object can be serialized to
  • A collection of name/value pairs. (For eg, from C# point of view, a simple example is Dictionary)</STRING,STRING>
  • An ordered list of values. (An array or a list)
JSON is used widely by various web apps, and is ideal for light weight data transfer over REST protocol. For example, Twitter. The following URL gives you the current twitter trends as a JSON string.

URL: http://search.twitter.com/trends/current.json - You may get something like this as reply (I've shortened it a bit :)).

{ "as_of" : 1256965326,
  "trends" : { "2009-10-31 05:02:06" : 
         [ 
          { "name" : "Happy Halloween",
            "query" : "\"Happy Halloween\" OR #Halloween"
          },
          { "name" : "#foofighterslive",
            "query" : "#foofighterslive"
          },
          { "name" : "#Backnthedaycartoon",
            "query" : "#Backnthedaycartoon"
          },
          { "name" : "Follow Friday",
            "query" : "\"Follow Friday\""
          }
        ] }
}

And for your information, here is a quick Online Json Formatter to format your JSON data a bit so that it'll look pretty

JSON In Silverlight


JSON serialization support is provided in Silverlight for long time. Let us have a close look at how an object gets serialized to JSON. Consider a simple Human class.

 public class Human
    {
        public List Children { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

Let us create a simple Human object and try serializing the same.
  var human = new Human() { Name = "Joe", Age = 10 };

If you serialize the human object using JSON serializer, you'll get something like
{"Age":10,"Children":null,"Name":"Joe"}


You may find that each property/value is represented using a Key Value pair. Now, Let us try with an object graph.
  var human = new Human() 
                { 
                    Name = "Joe", Age = 30 ,
                    Children = new List<Human> 
                    {
                        new Human() {Name="Jim", Age=3},
                        new Human() {Name="July", Age=2}
                    }
                };
And here is the result if you serialize the human object now. Note how the elements in Children collection of human object is serialized and represented in JSON.
{ "Age" : 30,
  "Children" : [ { "Age" : 3,
        "Children" : null,
        "Name" : "Jim"
      },
      { "Age" : 2,
        "Children" : null,
        "Name" : "July"
      }
    ],
  "Name" : "Joe"
}

Serialization and De-Serialization In Silverlight


Now, let us get back to the initial point, how to serialize and deserialize objects to/from JSON in Silverlight? You may use these extension methods I've put together. They are pretty straight forward. The first method adds an extension method to strings for deserializing them, and the second one adds an extension methods to objects for serializing them.
using System;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;


namespace JSONHelper
{

    public static class JsonSerializerHelper
    {
        /// <summary>
        /// Adds an extension method to a string
        /// </summary>
        /// <typeparam name="TObj">The expected type of Object</typeparam>
        /// <param name="json">Json string data</param>
        /// <returns>The deserialized object graph</returns>
        public static TObj JsonDeserialize<TObj>(this string json)
        {
            using (MemoryStream mstream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = 
                         new DataContractJsonSerializer(typeof(TObj));

                return (TObj)serializer.ReadObject(mstream);
            }
        }

        /// <summary>
        /// Serialize the object to Json string
        /// </summary>
        /// <param name="obj">Object to serialize</param>
        /// <returns>Serialized string</returns>
        public static string JsonSerialize(this object obj)
        {
            using (MemoryStream mstream = new MemoryStream())
            {
                DataContractJsonSerializer serializer =
                        new DataContractJsonSerializer(obj.GetType());
                serializer.WriteObject(mstream, obj);
                mstream.Position = 0;

                using (StreamReader reader = new StreamReader(mstream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
}

You may import JSONHelper namespace to use these extension methods, like this. Caution: Please make sure that you've valid JSON string or a serializable object when you use these methods
var human = new Human() 
{ 
    Name = "Joe", Age = 30 ,
    Children = new List 
    {
        new Human() {Name="Jim", Age=3},
        new Human() {Name="July", Age=2}
    }
};

//Serialize the object.
var hstr = human.JsonSerialize();

//Create a cloned object by deserializing the same
var cloned = hstr.JsonDeserialize<Human>();

Alright, that is it for now. Enjoy coding.

 

Shout it
Read more >>

Back To Basics - Anonymous Types In C# 3.0



About Back To Basics - It's often good to look back and fill any gaps we might be having, in certain aspects of the language or framework we use. I'll be examining and blogging about some well known features of C# and .NET, in Back To Basics series - Probably in a bit more detail.




This post is about the Anonymous types in C#, and the object initializer syntax.

It is well known that starting from C# 3.0, you can initialize an object like this.
var boy = new { Name = "Jim", Age = 2 };
You specify the properties of an object, and at compile time, the compiler will create a new (anonymous) type, with the properties you specify, and with a constructor that can take the same number of arguments.

Now, let us examine our anonymous type in detail by using reflection. We'll examine whether the type is a class, along with the type's name. If you run this,
static void Main(string[] args)
        {

            var boy = new { Name = "Jim", Age = 2 };

            Console.WriteLine("Name=" + boy.GetType().Name);
            Console.WriteLine("BaseType=" + boy.GetType().BaseType.Name);
            Console.WriteLine("Asm=" + boy.GetType().Assembly.FullName);
            Console.WriteLine("IsClass=" + boy.GetType().IsClass);
        }

You'll get some output like
Name=<>f__AnonymousType0`2
BaseType=Object
Asm=AnonymousTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
IsClass=True

Needless to say, the Name will be a random name, and the Assembly's name depends on your own project name. The key point is, we just established that the type is there in the assembly - which means, as I mentioned, the compiler created a type at compile time itself. You can have a look at the IL if you are interested.

Now, let us examine the observation that the anonymous type has a constructor that takes the same number of arguments as that of properties (i.e, in this case, the number of constructor arguments will be equal to the number of properties we specified in the object initializer, of types string and int). We can do that easily by creating a new instance of the anonymous type we have, using reflection. Add this to the tail end of the last piece of code.
//These two calls will fail with a run time exception, Just keep them commented
//var newboy = Activator.CreateInstance(boy.GetType(), null);
//var newboy = Activator.CreateInstance(boy.GetType(), new object[] { "Joe"});

//Only this will work. Creating a new boy
var newboy=Activator.CreateInstance(boy.GetType(),new object[]{"Joe",2});

//Just write back the name of new boy
Console.WriteLine(newboy.GetType().GetProperty("Name").GetValue(newobj, null));

You can see that only the last call will work, as we need to pass the same number of arguments while instantiating.

Note that you can have arrays of anonymous types as well, like this.
   var guys = new[]
            {
                    new {Name="Joe", Age=10},
                    new {Name="James", Age=22},
                    new {Name="Jim", Age=23},
                    new {Name="Jerard", Age=10},
            };

Further more, I just want to mention one more point. You may not need to assign the property explicitly, when you use the object initializer syntax. Consider this code.
            var guy1 = new { Name = "Ken", Age = 30 };
            var guy2 = new { guy1.Name, Age = 30 };

            Console.WriteLine(guy1.GetType().Name + " - " + guy1.Name);
            Console.WriteLine(guy2.GetType().Name + " - " + guy2.Name);


The key point to note here is, for guy 2, we are not explicitly specifying the Name property. Instead, we are just specifying that the name of Guy2 is same as Guy1. The compiler will assume the property name from the given parameter's name (in fact, the last part of the specified parameter, in this case 'Name') - This is called Projection. Obviously, you'll find that both guy1 and guy2 are of the same type as well.

Can you guess the output of this code as well?
            string Name = "Guy2";

            var guy1 = new { Name = "Ken", Age = 30 };
            var guy2 = new { Name, Age = 30 };

            Console.WriteLine(guy1.GetType().Name + " - " + guy1.Name);
            Console.WriteLine(guy2.GetType().Name + " - " + guy2.Name);


Why anonymous types are interesting? Because we use them in various ways, especially while using LINQ syntax. Here is a basic example

  var oldGuys = from guy in guys
                            where guy.Age > 20
                            select new { guy.Name };


Here, you'll probably find that we are using projection in the select new block. And as the last pointer, just debug and observe the type of oldGuys, and have a look at the base's type. I'll cover more on LINQ and Expression trees later.
Shout it
Read more >>

Weekend Hacks - Surface SDK, Silverlight, Math and Data Visualizations




About Week End Hacks - Most weekends I do some digging around new and emerging technology and geek stuff. I do this by picking the links I bookmarked, or by going through the tweets I Favorited in Twitter.


For this Weekend, mostly these are the links I'll be going through.


  1. Anoop Madhusudananamazedsaint Here is where to download the Microsoft Surface SDK https://partner.surface.com... from web
  2. Jon Gallowayjongalloway Chris Harrison is consistently awesome. Scratch input is a recent example. http://www.chrisharrison.ne... from Witty
  3. Pete Cashmoremashable PhotoSketch: Photoshop + Image Recognition = Awesome - http://bit.ly/tBPKv from bit.ly
  4. Brad Abramsbrada Blog: Building The Basics: Silverlight 3, .NET RIA Services, & NHibernate (Fluent) http://bit.ly/2BGjrW from TweetDeck
  5. JoeStagnerMisfitGeek New blog post: http://tinyurl.com/yd2gpjk - SQL Azure Explorer for Visual Studio from API
  6. Google CodeGoogleCode Surf's up! Read the latest on Google Wave:http://bit.ly/207oXA (via @google) from Brizzly
  7. Dan WahlinDanWahlin RT @timheuer: A must watch video series on#channel9. Hear from @scottgu and others. Visual Studio-A documentary - http://bit.ly/1BtLG from TweetDeck
  8. Anoop Madhusudananamazedsaint APP Architecture Guide 2.0 book -http://www.codeplex.com/App... from web
  9. Scott Guthriescottgu New post from @Haacked about the new Auto HTML Encoding syntax coming w/ ASP.NET 4 Beta2:http://tinyurl.com/autoencode from web
  10. Anoop Madhusudananamazedsaint MIT Free online courses - http://bit.ly/QwD4J from web


Read more >>


Any software or technology, in it's final form, is expected to solve a business problem for an end user. And hence, it makes perfect sense to enable the end user to validate the requirements visually, before the actual construction - to ensure that there are no surprises in the end.

 
Yes, this sounds so obvious, but it is often amazing to see how teams neglect such a powerful technique like prototyping

Prototyping the user interfaces and workflows early enough will ensure
  • There are no frequent change requests and release time hotch-potch
  • Requirements are captured properly
  • There is clarity in functional scope (in scope and out of scope)
  • Analysis is good enough to start the construction phase.
Why you need Prototyping?

In most scenarios, customers are not really aware about what they need. Capturing the requirements also means working with the customer to envision the final system, and at times, to suggest possible alternatives.

Let us take an example. Assume that you have a whole-sale carrot distributor as your customer, who is owning the company "Thick Red Carrots" and he is having a requirement.
"I need a simple program to manage the distribution of carrots I purchase from my suppliers. I also need to view and track the location of all my sales guys in the field; to know the number of shops they are covering a day, and to track the number of carrots they are selling in each shop. I also need the software to give my tax statement from my sales data"

When you dissect the requirements for this 'simple' software - obviously you can see the scope is increasing. And after several rounds of discussions with your carrot whole seller, you understood the actual requirements - still on a high level.

Briefly, the system should include
  • A user management and payroll module to enter and manage sales staff details.
  • An allocation module to allocate a geographical boundary for each of his sales guys on a daily or weekly basis.
  • A module for interfacing with sales guys - the sales guys will use their mobile device to enter the collection data back to the system, from the field.
  • A supplier management module
  • A stock management module to track the in house stock, allocated stock etc to foresee and report possible stock deficits
  • Admin module to enter master data - including employees, stocks, suppliers, shops (customers) etc
  • Reports for reporting all this
You also found that you need to address specific conditions, like overlapping of sales regions, back-collection of damaged carrots etc. Gasp. Gasp. Gulp, Gulp.

Prototyping To Help

You have several challenges. To mention a few, you need to
  • Make sure your carrot seller understands the features required for the final system, so that he won't cry about the scope creep.
  • Ensure your design and development teams are understanding the requirements, so that they won't miss out any functionality, and at the same time they won't over engineer.
  • Ensure all workflows and specific business cases are documented
  • Ensure all customer expectations are clearly identified and captured (remember, the tax calculation part)
You turn to a white board, and start visualizing the screens and user actions. (For an illustration, I'm using http://www.balsamiq.com/ for some quick drawings). You decided that the main screen should allow easy navigation to all modules, and hence should be having a tabbed interface. The entry screen will display a summary of statistics, and will may have few quick links as shown.

You go further, and sketch up few individual screens as well, based on each requirement. To enable the end user to define sales regions, you might create a user interface with a map - so that the end user may draw a sales region with in the map, to specify the allocated stock for the sales guy to sell in that region, and the date of allocation.

With these sketches, you might goto your end customer, and take him through these screens. You might get straight forward comments like "The dashboard screen looks awesome, but I need to view my current stock there in numbers". Few comments might definitely alter the scope, like "I need to import my employee contacts from outlook".

And once the end customer agrees on the screen protoypes and how he may switch back and forth between them, you are good to pass it to your design and dev guys, to take it to the next step.

Another key point to have in the back of your mind - When you present the prototypes, make it clear that it is just a wire frame to demonstrate the functionality. And if possible, present a real life snapshot of atleast one of your screens, to clarify your point.

Tools for doing prototyping

There are various online and offline tools for doing prototyping. You can google around to find a few. I use Balsamiq for quick and static UI prototyping, http://www.balsamiq.com/ - and Microsoft Expression Sketchflow for some serious prototyping.

The good thing about Sketchflow is that it supports workflow prototyping and behaviour prototyping to some extent. What's catchy about Expression Sketchflow is its ability to provide a dynamic, 'clickable' interface for the user - so that the user can get a some what realistic experience.
Read more >>

top