Import Json object from Javascript into C# with Dynamic keyword

I never really used the dynamic keyword in a real application. I did some tutorials but not much.

This week, I got a situation where I was getting from Silverlight a Json object that I did not want to create an object for.

string response = HtmlPage.Window.Invoke("GetMyJson").ToString();
MyObject data = (MyObject)JsonConvert.DeserializeObject(response);

But, I did not wanted to create the MyObject because it was just for transferring data; a simple DTO object. Instead, I used the dynamic keyword provided by .Net framework 4.0.

The dynamic keyword will be resolved in runtime and this give us the leverage to access property that might not exist. For example, “GetMyJson” function was returning a simple object with 2 properties “Abc” and “Def”.

{'Abc':'123','Def':'456'}

So, in the C# code, I simply called those properties from the dynamic object.

string response = HtmlPage.Window.Invoke("GetMyJson").ToString();
dynamic data = JsonConvert.DeserializeObject(response);
string s1 = data.Abc;
string s2 = data.Def;

This is pretty useful for accessing quickly some data from Json object.

How to enable CGI extension on IIS7 server?

I had to install Mercurial Server on IIS 7 recently. One of the prerequirement is to have Python installing on IIS has a CGI extension.

For this, you need to add an handler on IIS to map .cgi to Python. Unfortunately, this operation is not straight forward. If you try to add the Handlers Mapping for CGI you will get this error message.

Add Script Map error

The specified module required by this handler is not in the modules list. If you are adding a script map handler mapping, the IsapiModule or the CgiModule must be in the modules list.

To fix that, you need to open the Server Manager (%SystemRoot%\system32\CompMgmtLauncher.exe) and go to Roles and Web Server (IIS). From here you may have to wait few minutes and you will be able to add the Cgi extension.

Add Cgi extension to IIS server

Then, the last step is to Install. This also takes few minutes. Once done, restart IIS and you will be able to add the Http Handler for Python (or what ever CGI you need).

How to localize Silverlight Application with Resource File

Having your Silverlight application in multiple language is pretty the same as ASP.NET localization mechanism.

The first step is to create a new Resources File for your default language (English is the default one). You will find the Resources File template in the “Add New Item” under General tab.

Add a Resources File in Visual Studio 2010

Once it’s done, you can repeat that task for other language. Like with ASP.NET, you need to change the file name to have the two letters acronym of the language.

Two Resources Files

The second part is to add string into it. Simply double click the file and add Name and value for the string you want to be localized.

The last step is to use those values. To do it, simply use the code that has been generated by Visual Studio under the resource file (.designer).

var errorCaption = ErrorMessages.CaptionEmpty;

And that’s it, you have now inside errorCaption your localized string.

How to access Session information from HttpHandler (Ashx file)

You may pass manually the information but would it be easier if the http handler could read the session information?

This can be done with .Net Framework easily. In theory, this should not be a problem because the handler is in the server. It only needs to provide the session of the current user. To do, you need to use special interface that will allow you to reach this information.

This interface is called IReadOnlySessionState or IRequiresSessionState.

Here is an example:


<% @ webhandler language="C#" class="MyClass" %>

using System;
using System.Web;
using System.Web.SessionState;

public class MyClass: IHttpHandler, IReadOnlySessionState
{
   public bool IsReusable { get { return true; } }

   public void ProcessRequest(HttpContext ctx)
   {
       ctx.Response.Write(ctx.Session["ID"]);
   }
}

This example show you how to get the ID session’s variable from the HttpHandler.

The second interface IRequiresSessionState is the same but will let you write also in the session.

How to load application resource into a stream?

Sometime it can be useful to get a file that is a resource into the application. For example, using an XML file as resource for testing purpose instead of having them outside the application.

File Property

The first step is to get the file into the project and mark the Build In Action to resource in the property of the file.

File Property

Application.GetResourceStream Methods

After, the only code required will be to read this resource from your C# code. To extract the content of this resource you need to use the GetResourceStream method of the System.Windows.Application. Don’t worry if you are a Silverlight user, you still have access to this namespace. This method take a URI as parameter. This is where it can be tricky. First, you need to use a syntax that will define the namespace and then a relative path to the file.

Let say that my project name is Project1 and the file is in Folder1/Folder2. The file name is Test.xml. You have a URI that would look like this.

... = new Uri("Project1;component/Folder1/Folder2/Test.xml", UriKind.Relative)

Has you can see, the path needs to have the “component” before all directories.

Example of using XML with file resource

So, if you want to load a text file you will need to write:

     //...
     StreamResourceInfo sr1 = Application.GetResourceStream(new Uri("Project1;component/Folder1/Folder2/Test.xml", UriKind.Relative));
     var file = new StreamReader(sr1.Stream);
     return file.ReadToEnd();

Silverlight communication with Javascript

You may have some situation that you need to communicate with the page that your Silverlight reside.

This can be done by three methods:

  • Passing parameter to Silverlight
  • Silverlight call a Javascript method of your page
  • The Javascript call a Silverlight method

Silverlight parameter

All Silverlight application contain a startup method that has a StartupEventArgs. This class has a InitParam dictionary (IDictionary) that contains all parameters.

private void Application_Startup(object sender, StartupEventArgs e)
{
   if (e.InitParams.ContainsKey("debug"))
   {
        Debug.WriteLine(e.InitParams["debug"]);
   }
}

To pass parameters you need to add in the html a new element with the attribute name “initParams”.

<div id="silverlightControlHost">
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
		  <param name="source" value="ClientBin/MyProject.xap"/>
		  <param name="onError" value="onSilverlightError" />
		  <param name="background" value="white" />
		  <param name="minRuntimeVersion" value="4.0.50826.0" />
		  <param name="autoUpgrade" value="true" />
		  <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
 			  <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
		  </a>
          <param name="initParams" value="debug=false, secondParameter=2 " 
          />

	    </object>
        <iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe>
</div>

As you can see in this example, if you need more than one parameter you need to use a comma between all parameter. The value is automatically a string. You will need to parse it to the desired type inside Silverlight.

Silverlight communicate with Javascript

The communication between Silverlight and Javascript is straight forward. You need to use the Invoke method of HtmlPage.Window.

System.Windows.Browser.HtmlPage.Window.Invoke("MyFunction", "Parameter1");
System.Windows.Browser.HtmlPage.Window.Invoke("MyFunction", "Parameter1", "Parameter2");

The invoke method has a params[] for its second parameter. That let you add has many parameter value that the function in Javascript require.

public virtual object Invoke(string name, params object[] args);

Javascript to communicate with Silverlight

Javascript can also call method inside a Silverlight application. To do, you need to first declare an entry point name.

System.Windows.Browser.HtmlPage.RegisterScriptableObject("Page123", this);  

This code can be added at the beginning of the constructor of the method that will be called. It specifies a unique identifier that will be used in the Javascript.

The second thing that need to be done inside Silverlight is to add an attribute to the method that you want to expose to the external.

[ScriptableMember]
public void JavascriptWillCallThisMethod(string textFromJavaScript)
{
    Debug.WriteLine(textFromJavaScript);
}

The third and last step is to call this method from the Javascript code.

 var control = document.getElementById("silverlightControl"); 
 control.Content.Page123.JavascriptWillCallThisMethod("Hello from Javascript!");

As you can see, you find the “Page123” again here. It’s the name declared in the Silverlight application when calling the RegisterScriptableObject method.

How to debug Silverlight application with only XAP file?

Sometime, when the application is deployed to IIS server you may still need to do some debugging. Debugging a Silverlight application is in fact very easy, and pretty much the same when you are working inside Visual Studio but change when you need to debug it on the server.

The first step is to be sure that you .xap file deployed on IIS is the same as the one that you have in your developer environment. This can be automated when a Post-Build condition like this:

copy $(TargetDir)YOURxapFILEname.xap c:\wwwroot\mywebsite\ClientBin\YOURxapFILEname.xap

The second step is to go in Debug menu of Visual Studio and choose Attach To Process. This is a step that you would have to do to debug ASP pages. But, this will require a modification. When debugging .Net code, you usually set your debugging type to Managed. In the case of Silverlight, you must select Silverlight. This will automatically popup you a message saying that you cannot continue to debug in Managed. Just accept.

The debugging type must be Silverlight

The third step is to attach to the process. This also require a modification. When debugging a ASP page you usually select W3WP.exe (the IIS application pool). This time, you need to attack to your browser. This can be Internet Explorer, Firefox or Chrome. The reason is that Silverlight is not server side but client side.

You must attach to the browser, not IIS

From there you just need to refresh your page and the breakpoint you have set will be trig once reached.

Regex Tool For .Net Developers

I am far from being an expert in Regex but with good tools writing a Regex become easier.

First, I suggest you to download is RegexBuilder from Renschler. This Regex tool is ideal once the Regex is created to check few sentence and to quick see if something is wrong or not.

RegexBuilder

The second tool is something for helping you to create the Regex. This Regex tool is also free by RadSoftware. You can download it here.

Regex Designer

This tool is great to see what will be in your group and also contain a library of all Regex syntax.

With these two tools you should enjoy a little bit more the creation of Regex.

How to clone with Silverlight without ICloneable?

The .Net Framework allow to clone ICloneable interface. This interface has a single method that is Clone. This interface is not available in Silverlight. The reason is that Microsoft have found that since it does not provide specification between deep copy or shallow copy that it was useless to port this interface into the Silverlight SDK. In fact, this interface has been questionable since a long time ago.

An other way to clone is to serialize and deserialize your object. By using this mechanism all references are not there but the value are. The problem, is that Silverlight does not have the System.Runtime.Serialization has you may know in the .Net standard framework. You won’t fine the the IFormatter interface neither the BinaryFormatter class.

So, how to clone an object in Silverlight?

Here is a cloning method that is an extension for every object. It uses reflection to do it’s cloning. This is not a deep copy!

public static class CloningExtension
{
    public static T Clone<T>(this T source)
    {
        T cloned = (T) Activator.CreateInstance(source.GetType());
 
        foreach (PropertyInfo curPropInfo in source.GetType().GetProperties())
        {
            if (curPropInfo.GetGetMethod() != null && (curPropInfo.GetSetMethod() != null))
            {
                // Handle Non-indexer properties
                if (curPropInfo.Name != "Item")
                {
                    // get property from source
                    object getValue = curPropInfo.GetGetMethod().Invoke(source, new object[] {});
 
                    // clone if needed
                    if (getValue != null && getValue is DependencyObject)
                        getValue = Clone((DependencyObject) getValue);
 
                    // set property on cloned
                    curPropInfo.GetSetMethod().Invoke(cloned, new object[] {getValue});
                }
                    // handle indexer
                else
                {
                    // get count for indexer
                    int numberofItemInColleciton =(int)curPropInfo.ReflectedType.GetProperty("Count").GetGetMethod().Invoke(source, new object[] {});
 
                    // run on indexer
                    for (int i = 0; i < numberofItemInColleciton; i++)
                    {
                        // get item through Indexer
                        object getValue = curPropInfo.GetGetMethod().Invoke(source, new object[] {i});
 
                        // clone if needed
                        if (getValue != null && getValue is DependencyObject)
                            getValue = Clone((DependencyObject) getValue);
                        // add item to collection
                        curPropInfo.ReflectedType.GetMethod("Add").Invoke(cloned, new object[] {getValue});
                    }
                }
            }
        }
 
        return cloned;
    }
}

If you want more information you can read this forum thread.

Implementing Performance Counter in your application

Microsoft Windows has a Performance Counter application that is located in the Administrator Folder.

Performance Counter

Go to Control Panel\All Control Panel Items\Administrative Tools\ and select Performance Monitor. This will open a window with by default the processor performance. What is interesting is that you can see a lot of already coded performance counter by right clicking the list of counter and select Add Counters… or to press the button with the “+” icon.

Some already available .Net counters

What is interesting is that you can create your own inside your application and be able to visualize the result within this Performance Counter.

What you need is the System.Diagnostics namespace. From there you can verify if the counter you want to create exist with the static method ‘PerformanceCounterCategory.Exists’.

To create your counter, you need ‘PerformanceCounterCategory.Create’.

           PerformanceCounterCategory.Create("CategoryName",
                                              "CategoryHelpText",
                                               PerformanceCounterCategoryType.SingleInstance,
                                               "CounterNameInsideTheCategory",
                                               "CounterHelpText."); 

This code must only executed when a verification is made with the Exists method of PerformanceCounterCategory because an exception will be throw.

When you are ready to use the counter you need to use the method Increment or IncrementBy. The first one will increment by one and the other one with the value passed in a parameter. If it requires to decrease, you will need to pass a negative value.

var pc = new PerformanceCounter("CategoryName", "CounterNameInsideTheCategory", false);
pc.IncrementBy(10);