This is a mirror of official site:

Roslyn: C# is cheating on me with JavaScript (or how to compile C# into JavaScript)

| Tuesday, August 21, 2012
While working extensively on development of the Single Page Applications (SPA) I was facing a fact that my server-side data models were evolving quicker than their JavaScript counterparts. Both the client-side and the server-side data models were getting quickly out of sync.

The brute force solution of using the T4 templating engine to emit both the client-side and the server side data models didn’t look that appealing to me. Primarily due to a simple fact that it’s not that easy to refactor the T4 templates. And, the ReSharper junkie like me, can’t tolerate this fact.

So I’ve decided to give the latest release of Roslyn compiler-as-a-service CTP another spin and use it as part of my build sequence and compile my C# models directly into the appropriate JavaScript ones. This was giving me the advantage of using the C# as a primary development environment and leaving the JavaScript to follow the “big-brother”.

Jinx C#-to-JavaScript compiler was created as a result of this exercise. You’re welcome to get the Jinx source from the GitHub. I’ll appreciate any collaboration on this project.

Note: all of the code is an intermediate solution that was answering my personal needs for the project I was running. It is in no-way represent the full fledge solution. If you want something bigger and more feature-reach, you can either contribute to my solution or look into projects like Script# or SharpKit.

The workflow, I ended up with, was very simple:

Build a web application
In the web application create C# data models and, those that have to be compiled to JavaScript, mark them with the [JavaScript] attribute (*)
As a post-build step, run the “jinxc” command line compiler to emit the JavaScript data models directly into your Scripts folder
(*) – I’ve decided to use attribute as an option to reduce unnecessary noise from the compilation. The compiler will ignore all of the non-marked classes. This is not a requirement, but an option.

The example, we’re going to discuss here, is a simple To-Do list SPA application (based on the ToDoMvc with Knockout.js) with the Asp.Net WebApi REST service.

The simple C# data model that I needed for the client-server communication looks like this:

public class ToDoItem
  public Guid guid { get; set; }
  public string title { get; set; }
  public bool completed { get; set; }

QR: Inline image 1

Posted via email from Jasper-net