Monday, May 30, 2011

Getting started with Script#

Script# is a powerful framework that allows us to write C# code and be automatically translated into JavaScript. This article will present how Script# works and in what way can increase our productivity and improve the maintenance of our client-side libraries. Script# is created by Nikhil Kothari

What is Script#
Script# is C# to JavaScript compiler. That means that you write C# code and this code gets translated into JavaScript. This process I happening at development time and not at runtime. So, when you finish authoring your scripts in C# a JavaScript file will be produced in the output folder that you can then reference inside your project.

NOTE
Script# is not a tool that will help you port your .NET application into JavaScript. Instead is a tool that will help you write JavaScript code you normally would write with C#.

Why Script#
Naturally the first question that pops in to your mind is why? Why someone would want to create another dependency to the project?
As I mention above Script# will help you deal with JavaScript code that you would normally write by hand. The output of Script# is a JavaScript file. That means that you haven't added any dependencies to your project. You had JavaScript files before Script#, you have JavaScript files after.
But, those files are auto-generated. Auto-Generated files are often bad-written. If I wanted to leave Script# behind me and go back to writing pure JavaScript could I edit those files?
Script# produces scripts that feel hand-written. This is handy in a situation where you want to manually edit those files or you want to debug those files client-side (ex: with Firebug)
Let's see our first example. We have a function that takes a string and creates and alert message. After this message is displayed and the user clicks OK a callback function a being executed.

private void ShowMessage(string message, Action callback)
{
    Script.Alert(message);
    callback();
}
function _showMessage(message, callback) {        
alert(message);
callback();
}

Read more: dot Net Slackers