FridayThe13th the Best JSON Parser for Silverlight and C#/.NET

Up until a couple of months ago I was writing most of my code using WPF. Recently, a project came up where Silverlight made more sense to use. I’d thought that wouldn’t be a problem since I’d just use JavaScriptSerializer [wrote about it here] like I did for my WPF project.

Uh oh. It turns out that Silverlight doesn’t have JavaScriptSerializer. Never fear! DataContractJsonSerializer is here! Or so I thought.

It turns out that if you want to use DataContractJsonSerializer you must actually create POCOs to backup this “data contract.” I didn’t want to do that.

I wanted to turn this…

{
	"some_number": 108.541,
	"date_time": "2011-04-13T15:34:09Z",
	"serial_number": "SN1234"
	"more_data": {
		"field1": 1.0
		"field2": "hello"
	}
}

into..

using System.Web.Script.Serialization;

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);

Console.WriteLine(dict["some_number"]); //outputs 108.541
Console.WriteLine(dict["more_data"]["field2"]); //outputs hello

So I set out to write my own JSON parser. I call it FridayThe13th… how fitting huh? Now, using either Silverlight or .NET 4.0, you can parse the previous JSON into the following:

using FridayThe13th;

var jsonText = File.ReadAllText("mydata.json");

var jsp = new JsonParser(){CamelizeProperties = true};
dynamic json = jsp.Parse(jsonText);

Console.WriteLine(json.SomeNumber); //outputs 108.541
Console.WriteLine(json.MoreData.Field2); //outputs hello

Since I work with a lot of Ruby on Rails backends, I want to add a property “CamelizeProperties” to turn “some_number” into “SomeNumber”… it’s more .NET like.

Try it! You can find it on Github. Oh yeah… it’s also faster than that other .NET JSON library that everyone uses.

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

If you made it this far, read my blog on software entrepreneurship and follow me on Twitter: @jprichardson.

-JP

Missing DockPanel? Add DockPanel for Silverlight 4 or Silverlight 5

When I first created a demo project for Silverlight 5, I opened the XAML code to start editing. I started typing “DockPanel” but then I noticed that intellisense didn’t show anything. It turns out that DockPanel and some other controls aren’t included in the default installation of Silverlight 4 or Silverlight 5 beta.

Here’s what you need to do:

  1. Download the Silverlight 4 Toolkit. Install it. (Yes, this will work with Silverlight 5 beta)
  2. Add a reference to “System.Windows.Controls.Toolkit”. In Silverlight 5, you will need to navigate to the file:
    %ProgramFiles%\Microsoft SDKs\Silverlight\v4.0\Toolkit\Apr10\Bin\System.Windows.Controls.Toolkit.dll
  3. Add the following attribute to your UserControl: xmlns:tk=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit”
  4. So your code might look like:

    <UserControl x:Class="Project1.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    	xmlns:tk="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"
        mc:Ignorable="d"
        d:DesignHeight="300" d:DesignWidth="400">
    
        <Grid x:Name="LayoutRoot" Background="White">
    		<tk:DockPanel>
    			
    		</tk:DockPanel>
        </Grid>
    	
    </UserControl>
    

    Enjoy.

    Advertisement:
    Make Git simple. Let Gitpilot show you the right way to Git things done. Gitpilot will help you write software faster.

    Follow me on Twitter: @jprichardson and read my blog on software entrepreneurship: Techneur

    -JP

DataGrid Not Found in Silverlight 4

I created a fresh new Silverlight 4 project. I opened up MainPage.xaml and started typing “DataGrid”… but intellisense didn’t show it.

I found out that I needed to add the following to the top of my Xaml file:

xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"

In then started showing up in intellisense. I tried to compile the simple app and I got an error out of the MainPage.g.i.cs file. The error is:

“The type or namespace name ‘DataGrid’ could not be found (are you missing a using directive or an assembly reference?)”

I opened up the Silverlight MSDN for the DataGrid control and found out that my DataGrid is in the System.Windows.Controls namespace and the System.Windows.Controls.Data assembly. I didn’t see it in my references tree, so I tried to add a .NET reference. Unfortunately, “System.Windows.Controls” or “System.Windows.Controls.Data” weren’t in the list.

It turns out that you need to navigate to the “Browse” tab in the “Add Reference Dialog” and then add the file “System.Windows.Controls.Data” which is typically found in “C:\Program Files\Microsoft SDKs\Silverlight\v4.0\Libraries\Client”

Hope this helps someone.

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Follow me on Twitter: @jprichardson or read my blog on entrepreneurship: Techneur.

-JP

Get All ProgID on System for COM Automation

If you want to use Silverlight COM Automation, you need to know the ProgID of your COM component. These are buried in the registry. Here is a snippet that I found (don’t remember where) and modified a bit to do this:

var regClis = Registry.ClassesRoot.OpenSubKey("CLSID");
var progs = new List<string>();

foreach (var clsid in regClis.GetSubKeyNames()) {
	var regClsidKey = regClis.OpenSubKey(clsid);
	var ProgID = regClsidKey.OpenSubKey("ProgID");
	var regPath = regClsidKey.OpenSubKey("InprocServer32");

	if (regPath == null)
		regPath = regClsidKey.OpenSubKey("LocalServer32");

	if (regPath != null && ProgID != null) {
		var pid = ProgID.GetValue("");
		var filePath = regPath.GetValue("");
		progs.Add(pid + " -> " + filePath);
		regPath.Close();
	}

	regClsidKey.Close();
}

regClis.Close();

progs.Sort();

var sw = new StreamWriter(@"c:\ProgIDs.txt");
foreach (var line in progs)
	sw.WriteLine(line);

sw.Close();

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Follow me on Twitter: @jprichardson and read my blog on entrepreneurship: Techneur

-JP

Silverlight 4 and COM/ActiveX Integration

Silverlight 4 supports COM/ActiveX controls with Trusted permissions. However you must configure your app to be an Out-of-Browser app with Trusted permissions.

Here is the snippet of code that will open Excel and place a value in the first cell:

dynamic ex = AutomationFactory.CreateObject("Excel.Application");
ex.Visible = true;
ex.workbooks.Add();

dynamic sheet = ex.ActiveSheet;
sheet.Cells[1, 1].Value = "hello!";

However this won’t compile out of the box. First make sure that your app is enabled to run as an Out-of-Browser app. Open up your project properties and on the “Silverlight” tab make sure that “Enable running application out of the browser” and then click the button “Out-of-Browser Settings…” and at the bottom check “Require elevated trust when running outside the browser.”

If you’ve read other tutorials, you’ll see that a lot of them are using ComAutomationFactory. This is because these tutorials were written with a beta release of Silverlight 4. That’s why you’re getting this error:

The name 'ComAutomationFactory' does not exist in the current context

Change “ComAutomationFactory” to “AutomationFactory” and you’ll still notice that it won’t compile. Now you’re probably getting this error:

The name 'AutomationFactory' does not exist in the current context

ComAutomationFactory was previously in the namespace System.Windows.Interop. AutomationFactory has been moved to System.Runtime.InteropServices.Automation.

Now you might be getting the following error:

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll

All you need to do is add a reference to “Microsoft.CSharp.dll.” You can do this by right-clicking “References” in the “Solution Explorer” and then navigating to the “.NET” tab and selecting it.

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Follow me on Twitter: @jprichardson or read my blog on entrepreneurship: Techneur.

-JP