Let’s say you’re working on a HTML Metro app and you’d like to reuse some C# code instead of rewriting, the good new is that you can, here’s how:

Create a blank new WinJS application and add a div inside default.html page:

<body>
    <div id="output"></div>
</body>

Now add a new C# library to WinJS solution:

image

Change the output type of the library project to WinMD file

image 

let’s add a couple of classes to C# library, we’re going to consume them from our HTML application:

public sealed class Person 
{
      public Person(string name)
       {
          this.Name = name;
          this.Address = new Address() { City = "Milano", Code = 20100 };
       }

       public Address Address { get; private set; }

       public int Age { get; set; }

       public string Name { get; private set; }

       public int CalcSum(int a, int b)
       {
          return a + b;
       }
 }

public sealed class Address
{
      public string City { get; set; }

      public int Code { get; set; }
}

note how both Person and Address are marked as sealed, this is a mandatory requisite if you want expose them to others WinRT languages.
Let’s now add a reference from HTML application to our C# library:

image

and create an instance of Person class using Javascript:

app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize 
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension. 
                // Restore application state here.
            }
            WinJS.UI.processAll();

            //This uses C# objects
            var person = new MyLib.Person("corrado");
            person.age = 12;
            var res = person.calcSum(3, 5);            
            output.innerText = "out is:" + person.name + "-" + person.age + "-" + res + "-" + person.address.city;
        }

and here’s simulator output:

image

I know it might sound strange to mix Javascript with C# when you can do exactly same things with both languages on Metro but when you have some complex logic
or you want to hide some code as much as possible (you can do exactly the same with C++ code) this may be a viable alternative.

Technorati Tags: ,