Published: 25 May 2011
By: John Katsiotis
Download Sample Code

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

Contents [hide]

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.

Listing 1: C# code

Listing 2: JavaScript Code being generated

The code being produced is readable and feels like we wrote it!

Other benefits of using Scripts# are:

  • Intellisense support
  • Build errors at compile time
  • Ability to create documentation
  • Refactoring Support
  • Debug and Release (minified) version of the produced scripts

Getting Started

In order to start authoring your client-side libraries with Script# you need to Download and Install a Visual Studio plugin that adds the appropriate tools.

After successfully installing the plugin you will notice a new section (named Script#) when creating a new Project.

Figure 1: The Script# sections appears when creating a new Project

The Script# sections appears when creating a new Project

There are seven (7) project types available. Most of them are self-explained. For now, I will explain on two (2) of them.

Script Library Project Type

This project type allows you to create your client-side helpers or classes that normally referred to every page of your website. This type produces a single JavaScript file for the entire project.

Web Application Project Type

This project type differs for a Script Library on the fact that it can produce different JavaScript files for every folder inside the project. This is useful when you want to write code that is specific to a single page of your website. Also if you want code to be included in every produced file you can put it in a folder named Shared.

NOTE

You can also edit the .csproj file of a Script Library and change <WebAppPartitioning> tag to true

For the purpose of this article we will use a Script Library.

Creating a Script Library

Now that our tools are set let's create our first client-side library with Script#.

We need to follow the steps below:

  1. Create a blank solution named GettingStartedWithScriptSharp in Visual Studio 2010
  2. Create an Empty Web Application Project inside the solution named GettingStartedWithScriptSharp.Web
  3. Create an Index.html page
  4. Create a Scripts folder inside our Web Application Project
  5. Add a new project to the solution which is a Script# Script Library Project named GettingStartedWithScriptSharp.Scripts
  6. When asked we should point as our deployment path the Scripts folder of our Web Application

Script# projects have the ability to take produced scripts and put it in a folder of our selection (besides the /bin folder).

Figure 2: Select the Scripts folder of the Web Application Project as a Deployment path when asked

Select the Scripts folder of the Web Application Project as a Deployment path when asked

Of course you can edit that option anytime later by editing the .csproj file and specifically the <DeploymentPath> tag.

Figure 3: Configuration of DeploymentPath

Configuration of DeploymentPath

Eventually we should have a project that looks like this:

Now let's add a Script# class in our Scripts project named TextPreviewer.cs

Figure 5: Adding a new Script# class

Adding a new Script# class

When we have our TextPreviewer class created we put the following code inside

Listing 3: TextPreviewer.cs class

This class takes two ids in the constructor - one that corresponds to an input element and one to div element. In its initialize method checks if the input element is defined and if so it creates a listener for the key up event. So every time the user hits a button the OnKeyUpListener is being called. The last method checks if the div element is defined and takes the value from the input element and put it in the InnerHTML property of the div.

When our project builds successfully we should see inside our Scripts folder four (4) files. Actually we have two (2) files and each file has a debug and a release version.

The first file – named GettingStartedWithScriptSharp.Scripts.js (looong name!) – is the file produced from our Script Library project.

The second file – named mscorlib.js – is file that allows us to do things like string.IsNullOrEmpty and more, and is the only file needed (22 KB) in order to run scripts created with Script#.

Figure 6: Files inside the Scripts folder after a successful build of the Script Library Project

Files inside the Scripts folder after a successful build of the Script Library Project

NOTE

The first time we need to include the files in the solution. To do that we can click on "Show all files", right click on them and select "Include in Project"

Now let's go to our Index.html file and put the following code.

Listing 4: Index.html inside the body tag

In order to instantiate our class we do new Scripts.TextPreviewer and that is because we have decorated our C# class with the Attribute ScriptNamespace. If the attribute was missing then we should have written new GettingStartedWithScriptSharp.Scripts.TextPreviewer which is a full namespace of the C# class.

If we run the page through a browser we should be able to see the functionality that is being explained above. Anything written inside the text field should be copied to the preview div every time we release a key.

Using jQuery

Is it possible to use jQuery? Not only it's possible but we will use Script# to encapsulate the above functionality in to a jQuery plugin.

Let's create a Script# jQuery Plugin named TextPreviewerjQuery.cs

Figure 7: Creating the Script# jQuery Plugin

Creating the Script# jQuery Plugin

Delete the contents of the newly created file and replace them with the following code

Listing 5: TextPreviewerjQuery.cs

Now let's take a moment and see what we have here.

Mixin Attribute concatenates its value with the members of this class.

The TextPreviewerjQuery method is our plugin implementation

TextPreviewerjQueryOptions is a class which is actually a JSON object; holds our plugin options and the Imported Attribute that decorates this class, tells the compiler that no code should be generated. ScriptName attribute with value "Object" is being used when we refer to a JSON object.

And last but not least inside the region Script# Support we have code that allows us to call and refer to our plugin from C#. Also no JavaScript code is being generated.

In order to use this plugin inside our page we write the following code.

Listing 6: Using TextPreviewer jQuery Plugin

Frequent JavaScript calls with Script#

Things that you do a lot in JavaScript and might want to do with Script# also:

  • alert -> Script.Alert
  • typeof(object) === "undefined" -> Script.IsUndefined or Script.IsNullOrUndefined
  • eval -> Script.Eval
  • Script.Literal("alert(1)") – writes alert(1)

Summary

I hope this was a good kick-start on how to use Script#. Script# is a powerful tool and can really speed-up and improve client-side development.

Before I close this article I want to point out something. I don't believe in any way that if you start with Script# you will never have to write JavaScript again and neither should you see it like that.

Client-side development is all about JavaScript. But when you need to create a library – code that will be used by other code, then Script# can be of great help.

Whatever the case is, Script# is a project that definitely deserves a second look.

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About John Katsiotis

John Katsiotis is a Microsoft MVP in ASP.NET since 2008 and .NET Developer for the past 4 years. You can find more info at his personal site or follow him on Twitter

This author has published 3 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Android for .NET Developers - Location and Maps
In Windows Phone and iOS getting the current position of the device in terms of latitude and longitu...
Android for .NET Developers - Using Web Views
In this article, I'll show a native app that contains a web-based view. The great news is that HTML ...
Android for .NET Developers - Building a Twitter Client
In this article, I'll discuss the features and capabilities required by an Android application to ta...
Developing a Hello World Java Application and Deploying it in Windows Azure - Part II
In this article we will see the steps involved in deploying the WAR created in the first part of thi...
Ref and Out (The Inside Story)
Knowing the power of ref and out, a developer will certainly make full use of this feature of parame...

You might also be interested in the following related blog posts


Getting Started with Script# read more
Assembly-Free jQuery in SharePoint Sites Using the SmartTools jQueryLoader read more
Private Extension Methods read more
Trials & Tribulations of running windows scripts in Vista read more
Make SharePoint 2007 Act Like SharePoint 2010 (sort of ...) read more
Starter Project Templates (VS 2010 and .NET 4.0 Series) read more
PowerShell Script with ASP.NET and Console Application read more
Script# (Script Sharp) writing javascript in C# read more
Finding malware in your Web Site using IIS SEO Toolkit read more
Why is ASP.NET encoding &s in script URLs? A tale of looking at entirely the wrong place for a cause to a non-existing bug. read more
Top
 
 
 

Discussion


Subject Author Date
placeholder additional methods ?. Rekna Anker 11/4/2011 11:13 AM
RE: additional methods ?. John Katsiotis 11/23/2011 1:18 AM
placeholder RE: RE: additional methods ?. Rekna Anker 11/27/2011 12:23 PM

Please login to rate or to leave a comment.