Sunday, September 27, 2009

Library Of The Week: Json.NET

{

In the Christian Bible there’s a story of 10 lepers miraculously healed by Jesus. Even if you don’t believe in Christianity, imagine a leper living in the dregs of society, totally dejected until one day a man shows up and heals him and nine other fellow outcasts. Imagine how happy they should be.

They’d say thank you, right?

In the Bible story, only one of the men returns to say thank you and the other nine are so busy getting back to the lives they wished they had that they forget about the reason they were healed in the first place.

There’s evidence of this kind of lack of gratitude in the ecosystem of free libraries and projects available for .NET developers on the web. I’m a part of that club and not proud of it. I use open source .NET libraries on a regular basis and don’t say thank you. But more than just me, I look at the community participation on CodePlex projects and find it amazing how few people say a simple “thank you.”

With that in mind, I’m going to start profiling libraries that I’ve used with success to build up awareness of their existence and hopefully inspire the people who write them to do more good work since what they do is so tremendously helpful.

The first library I want to profile is the Json.NET library available from CodePlex. It contains a great, intuitive Json serialization/deserialization library. You can point to most serializable objects and convert them to a JSON format with such simple sleight of hand as:

	List<Foo> data = new List<Foo>();
// adds to data
string json = JsonConvert.Serialize(data);




As if that wasn’t simple, retrieving values from their serialized format is also made trivial:





	string jsonItems = GetYourJSON();
List<Foo> data = JsonConvert.DeserializeObject<List<Foo>>(jsonItems);




One great differentiator of Silverlight versus existing web technologies is the ability to have a virtual file system on a client computer. While HTML 5 seems to include facilities for this it is not yet built into existing browsers and even when it is, previous track records on “standards” are a precedent for how balkanized the implementation of them can be. In many areas of web development, you can push the envelope of existing technologies to get what you do out of Silverlight, but the existence of Isolated Storage is a killer feature.



Give Json.NET a try whether you’re doing Silverlight or using a different .NET related paradigm. It’s a great library.



}

Sunday, September 20, 2009

Exception HOF Pattern in C#

{

There’s probably a name for this specific approach but in a personal project of late I’ve found a useful pattern for generalizing my exception handling. I write a ExceptionHelper class that takes a variety of high order function style methods to handle my exceptions in a single spot. Here is a somewhat simple form of what I've been doing:

    public class ExceptionHelper
{

public static void ExecuteWithSuppress(Action code)
{
try
{
code();
}
catch (Exception ex)
{
// pass and ignore the exception
}
}

public static void ExecuteWithHandler(Action code)
{
try
{
code();
}
catch (Exception ex)
{
Console.WriteLine("An exception occured! Details: \n" + ex.ToString());
}
}

public static void ExecuteWithHandler(Action code, string errorMessage)
{
try
{
code();
}
catch (Exception ex)
{
Console.WriteLine((errorMessage.Length > 0) ? errorMessage : ex.ToString());
}
}

public static void ExecuteWithHandler(Action code, Action onError)
{
try
{
code();
}
catch (Exception ex)
{
if (onError != null)
{
onError();
}
}
}

public static void ExecuteWithHandler(Action code, Action onError, string errorMessage)
{
try
{
code();
}
catch (Exception ex)
{
Console.WriteLine((errorMessage.Length > 0) ? errorMessage : ex.ToString());
if (onError != null)
{
onError();
}
}
}

public static bool ExecuteWithNotificationButIgnore(Action code)
{
bool ret = true;
try
{
code();
}
catch (Exception ex)
{
ret = false;
}
return ret;
}

public static void ExecuteWithLogging<T>(Action code) {
try
{
code();
}
catch (Exception ex)
{
if (ex is T) {
Console.WriteLine("Logging exception " + ex.ToString());
}
}
}

public static void ExecuteWithLogging(Action code, Action<Exception> handles) {
try
{
code();
}
catch (Exception ex)
{
handles(ex);
}
}

}


At this point I use it in a lot of places, here are a few scenarios:



ExecuteWithSuppress(Action code) – code that has a low impact of failure or an expected failure under some conditions. For example, a client of mine once had a legacy database they wanted to me parse a “name” field from. We set up basic heuristics to separate out first and last and so on, but on failure we just returned a blank string.



ExecuteWithHandler(Action code) – you have some generalized exception handling to do something: prompt the user, do logging, etc. ExecuteWithHandler(Action code, Action handler) – you get to pass in the exception handling you want


ExecuteWithHandler(Action code, string errorMessage) – pass a custom error message


ExecuteWithNotificationButIngore(Action code) – try to execute some code but return a boolean to indicate success


ExecuteWithLogging<T>(Action code) – run some code, indicate the types of exceptions to differentiate


ExecuteWithLogging(Action code, Action<Exception> handles) – pass a method to catch be passed the exception that occurs.




The resulting code I write with this pattern, I find pleasant. Here are some examples:



    string userName = String.Empty;
ErrorHelper.ExecuteWithSuppress(() => userName = doc.Descendants("Name").First().Value);
return userName;


if (ErrorHelper.ExecuteWithNotificationButIgnore(() =>
{
SendEmail();
}
else
{
// message not delivered, etc, etc.
}


I want it to be absolutely clear that this is not a replacement for try/catch/finally logic where it is warranted. It is simply an alternative that can help to keep code clear and readable. As with many things in software, there is taste involved in when and where something like this is leveraged. But it works well enough for me that I thought I’d share.



}

Saturday, September 19, 2009

FizzBuzz Functional

{

I’ve been reading Tomas Petricek and John Skeet’s Functional Programming for the Real World. I’m hoping I can, as Steve McConnel says, program into1 my C# projects some elements of functional problem solving. As I was working to grok the beginning portions of the book I thought I’d rewrite FizzBuzz since I’ve aleady posted a few versions of a solution. Here is my solution:

Func<int, int[], bool> isMultiple = (n, n2) => n2.Any(m => n % m == 0);
Func<int, int, string, string> fb = (n, n2, s) => (n % n2 == 0) ? s : String.Empty;


foreach(var i in Enumerable
.Range(1, 100)
.Select(n =>(isMultiple(n, new int[]{3,5}))
?fb(n, 3, "Fizz") + fb(n, 5, "Buzz")
:fb(n, n, n.ToString())
)Console.WriteLine(i);


Another version, using ForEach on a List<T>:



Func<int, int[], bool> isMultiple = (n, n2) => n2.Any(m => n % m == 0);
Func<int, int, string, string> fb = (n, n2, s) => (n % n2 == 0) ? s : String.Empty;

Enumerable
.Range(1, 100)
.Select(n => (isMultiple(n, new int[] { 3, 5 }))
? fb(n, 3, "Fizz") + fb(n, 5, "Buzz")
: fb(n, n, n.ToString()))
.ToList()
.ForEach(num => Console.WriteLine(num));


I'm just starting to wade into using F# but I'm hoping to start building my proficiency the further I get into the book



1"Don't limit your programming thinking only to the concepts that are supported automatically by your language. The best programmers think of what they want to do, and then they assess how to accomplish their objectives with the programming tools at their disposal." – Steve McConnell, Code Complete 2nd Edition



}

UI Inspiration for Silverlight’s Blank Slate

{

I’ll admit that I spent an inordinate amount of time last week thinking about dialog boxes. Silvelright’s canned prompt comes courtesy of a call to MessageBox.Show which displays the browser’s native modal dialog. I think you get the same thing from HtmlPage.Window.Alert too. Needless to say, these should leave you wanting.

A good place to start, rather than wasting the better part of a day playing around like me, is to begin with a really good convention rather than making something “original.”

So without further ado, I’m linking to a nice PSD courtesy of teehan+lax that contains visual styles for many of the iPhone’s UI Elements. I’ll have to build a nice workflow to get things like this into XAML.

 

One more philosophical note (noted below so that if you just needed the link you won’t be daunted by my long windedness) – almost 100 episodes ago the Hanselminutes podcast featured Scott interviewing David Heinemeier Hansson and Martin Fowler at RailsConf 2007. When talking about UI design and originality here is what DHH had to say:

“I think the low level of
expressiveness that we have in HTML and CSS
and JavaScript is actually a huge boon to most
applications that constraints are a good thing,
that constraints leads to better applications when
we don’t need to reinvent everything
. When you
just have blank canvas where you can paint
whatever you want on it, you pretty much end up
with something “original” every time; and I don’t
think originality in UI design is necessarily a good
thing; I just think actually most of the time it's a
bad thing.”

I agree with DHH on this point. It’s worth listening to the entire podcast to put some context to his comments. Where my opinion veers from his or at least my hope for Silverlight is that conventions more powerful than those of HTML/CSS/JavaScript begin to come together for developers and they spend less time thinking about a blank slate and more about how their application works with the benefit of a better experience. Themes are a good step in this direction but things like dialogs go beyond to interactions as opposed to just colors and gradients.

}