Convert C# code to JavaScript

There are some tools which convert C# code to JavaScript. Obviously these will only be useful if your code is not tightly coupled with any C# library as the library won’t be available in JavaScript. These conversion tools may come handy for model classes or any other logic which is, for the most part, independent of .Net framework classes.

The main focus of these tools is not code conversion, rather they primarily try to do for C# what GWT does for Java. They allow you to write code in C#, access the DOM and JavaScript libraries to develop web applications. When the code is compiled, the output is not .Net Application but a web application written in JavaScript and HTML.


Conversion Tool Description
duocode duocode is a new tool on the block, currently in beta. It is going to be a commercial software but free to use as of now. duocode uses Microsoft Roslyn and support debugging C# code your compiled JavaScript is running in the browser. It supports pretty comprehensive set of C# feature including Await/Async, C# 6.0 language features, resource files etc.


SharpKit SharpKit is commercial (free for open source & small projects) as opposed to the alternatives listed below but does an excellent job of converting C# to JavaScript which is clean and readable. Moreover, it supports all features of C# language.You can see SharpKit live in action here. Give it a C# class or a snippet, it will convert it to JavaScript right there.Sharpkit compares itself with JSC, Script# and GWT at

Google Code:

JSIL JSIL is a compiler that transforms .NET applications and libraries from their native executable format (CIL bytecode) into standards-compliant, cross-browser JavaScript.There are quite a few demos on JSIL website, one of them allows you to convert C# code to JavaScript right in the browser (though the generated code looks a bit obscure).


JSC JSC is an Open Source cross-compiler where you can create web applications for Java, JavaScript, Flash ActionScript, PHP and Google App Engine using Microsoft .NET in C#, VB or F#. And also integrates into the .NET frameworks, Silverlight and ASP.NET.

Wiki & Tutorials:

Script# Script# is a compiler that generate the JavaScript instead of MSIL (Microsoft Intermediate Language) from C# source code like GWT (Google Web Toolkit).Script# supports a subset of language features, for instance enum and struct are not supported.

GitHub Repository:

Saltarelle Saltarelle is an open source C# to JavaScript compiler. Saltarelle is not an entire framework for web application development (such as GWT), rather it consists of a compiler and a small runtime library that only contains the things necessary for the language features to work. It is, however, designed with interoperability in mind so you can use any existing JavaScript framework with it. It comes with support for jQuery, and other libraries can be used either by authoring an import library (which is just a class / set of classes with special attributes on their members) or by using they ‘dynamic’ feature of C# 4.

Git Repository:

For a comprehensive list of tools that convert C# and other languages to JavaScript, visit

Developed Custom .Net Font Dialog

Developed a Custom FontDialog as an alternative to the standard .Net FontDialog. Key advantage of CustomFontDialog is the full control over look and feel as it is open source. Source and binary files are available at sourceforge.


CustomFontDialog avoids ‘This is not a True Type Font’ exception that affects the standard dialog in some cases. Most probably the exception happens when some installed fonts have invalid meta information. This exception cannot be caught using try/catch block because the exception is thrown from the code outside .Net framework. The exact exception message is ‘Only TrueType fonts are supported. This is not a TrueType font.’. CustomFontDialog gets around this problem by loading only True Type fonts. More details about the problem with standard dialog can be found here and here.

Moreover, CustomFontDialog provides easy access to recently used fonts by moving them at the top of the list in ‘Recently Used’ section.


Following C# code snippet demonstrates how to instantiate and display Custom FontDialog.

CustomFontDialog.FontDialog fontDialog = new CustomFontDialog.FontDialog();

// sets the default font
fontDialog.Font = new Font(FontFamily.GenericSansSerif, 10);

if (fontDialog.ShowDialog() == DialogResult.OK) {
   // Font is selected. Get the selected font using 'fontDialog.Font'
else {
   // FontDialog is canceled by the user
   // your code here to handle cancel action

For the CustomFontDialog to retain the recently selected fonts at the top of the list, the dialog should be instantiated only once and ShowDialog function should be called on the same object whenever the dialog needs to be displayed.

To programmatically add Fonts to be ‘Recently Used Fonts’ section, call AddFontToRecentList method.

Limitation: As compared to the standard FontDialog, CustomFontDialog doesn’t support changing text color.




Version 0.2.0 (31-May-2014)

Following fixes and enhancements are included in this version:

1- In Font List, arrow keys can be used to move between ‘Recently Used’ and ‘All Fonts’ sections.
2- When user starts typing in Font List, the focus shifts to the filter Text box automatically.
3- Whenever CustomFontDialog is displayed, the focus is on Font List by default.

Quick and dirty way of creating Numeric TextBox in .Net (C#)

Handle KeyDown event of the TextBox and set the e.Handled property to true if the character is not numeric.

this.myNumericTextBox.KeyDown +=
                       new KeyEventHandler(this.myNumericTextBox_KeyDown); 


private void myNumericTextBox_KeyDown(object sender, KeyEventArgs e)
            switch (e.KeyData)
                case Keys.D0:
                case Keys.D1:
                case Keys.D2:
                case Keys.D3:
                case Keys.D4:
                case Keys.D5:
                case Keys.D6:
                case Keys.D7:
                case Keys.D8:
                case Keys.D9:
                case Keys.End:
                case Keys.Enter:
                case Keys.Home:
                case Keys.Back:
                case Keys.Delete:
                case Keys.Escape:
                case Keys.Left:
                case Keys.Right:
                case Keys.Decimal:
                case (Keys)190: //decimal point
                    if (myNumericTextBox.Text.Contains('.'))
                        e.SuppressKeyPress = true;
                        e.Handled = true;
                    e.SuppressKeyPress = true;
                    e.Handled = true;


Switch cases list all desired characters which will be displayed, rest of the characters are ignored. If additional characters are required, they may be included as switch cases. For instance, negative sign may be allowed based on your requirement.

How to embed chrome browser in .net application

Chrome browser can be embedded in native application taking a hybrid approach to development where application is partly developed in native technology and partly in web. This has several advantages:

  • Salvage the existing investment in HTML/Javascript projects.
  • The part of application written in web technology is platform independent. This is very important due to variety of devices that are prevalent today.
  • Overcome the limitation of web technology and leverage the full power of the hardware through native code.

We need to know about three projects:

Project Type Description
Chromium Web Browser Chromium is the open source browser project which is behind Google Chrome.
Web Browser Control Based on Chromium project, an open source embed-able Web Browser Control is developed called ChromiumEmbedded. ChromiumEmbedded supports programming interface for C++.
Xilium.CefGlue .Net Wrapper Quite a few wrappers are available to make ChromiumEmbedded accessible in other languages. The most updated and active wrapper for .Net is Xilium.CefGlue.

Follow the below steps to embed Chromium Web Browser control in your .Net application.

  1. Download the source code for Xilium from here (Click on the Branches tab and download the Master branch).
  2. Check for the current ChromiumEmbedded (CEF) build supported by Xilium here. As of now, the ChromiumEmbedded supported build is CEF 3.1547.1448. Download the relevant pre build binaries from here.
  3. Unzip the two downloaded files. Copy all DLLs from the Release folder of ChromuimEmbedded and place it in Debug folder of CefGlue.Demo.WinForms project in Xilium source code.
  4. Copy the locales folder under Resources from ChromuimEmbedded and place it in the Debug folder of CefGlue.Demo.WinForms project in Xilium source code.
  5. Open the Xilium source code in Visual Studio using Xilium.CefGlue.sln. Set CefGlue.Demo.WinForms as the startup project.
  6. Build and run the solution and you will get the demo .Net application running with embedded chromium browser.

Programmatically scroll Listbox in .Net (Windows Forms, C#)

It seems that .Net library doesn’t provide any way to scroll contents of ListBox through code. Selecting an item by setting SelectedIndex automatically scrolls the list to bring the item into view but this may not produce the desired effect. In my case, I wanted to programmatically select an item and make it the first visible item in the list. This effect cannot be achieved through changing SelectedIndex.

The way around this problem is to invoke Windows API SendMessage function.

To call a function from an un-managed DLL, we have to declare it along with DLLImport attribute.

private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg,
                                         uint wParam, uint lParam);

As the declaration shows, we have supply four arguments.

S/N Parameter Description
1 IntPtr hWnd This is the handle to ListBox Control. We can get the handle through Handle property of ListBox control e.g. myListBox.Handle
2 uint Msg This should be set as WM_VSCROLL. It says that we want to send message for scrolling vertically. Find list of messages that could be passed to a control here.
3 uint wParam This 32 bit parameter has two parts.

  • Lower 16 bits called LOWORD should specify one of the scroll bar commands. In our case, it should be SB_THUMBPOSITION.
  • Higher 16 bits called HIWORD should specify the numerical value for position of the scroll bar thumb. If we pass the index of a list item, list will scroll such that the item becomes the first visible item in the list.
4 uint lParam This parameter is for additional message specific information. For our purposes, we will just pass 0.

Following is the SendMessage function call to scroll the list. First, we define the constants WM_VSCROLL and SB_THUMBPOSITION. Then we develop the thrid paramter by combining LOWORD and HIWORD. Finally the function is called.

const uint WM_VSCROLL = 0x0115;
const uint SB_THUMBPOSITION = 4;

uint param = ((uint)(lstFont.SelectedIndex) << 16) |
                          (SB_THUMBPOSITION & 0xffff);

SendMessage(myListBox.Handle, WM_VSCROLL, param, 0);

Custom .Net (C#) Collection: Recently Used List

I came across a situation where I needed a collection which can hold recently used objects of a particular kind. For instance, recently opened files, recently used fonts or colors etc. Such a list should demonstrate following behavior:

  • List should have a limited size (or call it maximum size). As list grows beyond the maximum size, the oldest item should be dropped.
  • Newly added items should be inserted at the top of the list i.e. index 0.
  • If an item to be added already exists in the list, it should be moved to the top of the list (at index 0) rather than being duplicated. This means that entries in the list will always be unique and order of the items will follow how recently they were used.

Following custom collection class provides this functionality:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyNamespace
    public class RecentlyUsedList<T>
        public RecentlyUsedList(int maxSize)
            this.maxSize = maxSize;

        private List<T> list = new List<T>();

        public T this[int i]
                return list[i];

        private int maxSize;

        public int MaxSize
                return maxSize;

        public int Count
                return list.Count;

        public void Add(T item)
            int i = list.IndexOf(item);
            if (i != -1)    list.RemoveAt(i);

            if (list.Count == MaxSize) list.RemoveAt(list.Count - 1);

            list.Insert(0, item);

One nice enhancement to the class would be to implement System.Collections.IEnumerable interface. It will enable the collection to be iterated using foreach loop.

Handle arrow key events in Windows Forms .Net (C#)

Pressing of a key is detected and handled in Windows Form using KeyPress, KeyDown or similar events.

this.KeyDown += myForm_KeyDown;

private void myForm_KeyDown(object sender, KeyEventArgs e)
   //Your code here

But these events does not fire when arrow keys are pressed. One way to get around it is to set KeyPreview as true for your Form. In many cases, this also doesn’t work, for instance, when you have buttons on your Form.

In such cases, ProcessCmdKey can be overridden to detect and handle arrow key events.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
           case Keys.Down:
               //Handle down arrow key event
           case Keys.Up:
               //Handle up arrow key event
           case Keys.Right:
               //Handle right arrow key event
           case Keys.Left:
               //Handle left arrow key event
        return base.ProcessCmdKey(ref msg, keyData);

After handling the arrow key event if you do not want the standard arrow key functionality to kick in, return true rather than calling return base.ProcessCmdKey(ref msg, keyData); Standard functionality could be to move focus to the next or previous control.

Returning true from ProcessCmdKey means event has been handled and should not be routed further for processing.

Excel Add-in for Exporting data to XML


ExcelExportXML is a Microsoft Excel 2010 Add-in that generates XML data from excel sheet. It is developed in Visual Studio 2010 using C#.

It is a very simple add-in. To understand how to works, consider an excel sheet having following data.

Country Capital Continent
France Paris Europe
Germany Berlin Europe
India New Delhi Asia
Indonesia Jakarta Asia

Using the add-in, above can be exported to following Xml.

        <capital>New Delhi</capital>

Once the Add-in is installed, you will have a ‘Generate XML’ button on Add-ins tab of Excel Ribbon as shown below. Clicking ‘Generate XML’ will pop up the save file dialog which will allow you to save the generated Xml file.


Use Case & Assumptions

ExcelExportXml is useful when you have tabular data in excel and the first row contains the column headings. It works based on following assumptions.

  1. First row is considered as column headers and will be converted to Xml tags.
  2. After encountering the first empty cell in header row, rest of the columns to the right will be ignored.
  3. Supports columns up to ‘Z’ only i.e. maximum of 26 columns.
  4. First row for which all values are empty will be considered the end of sheet.
  5. Sheet name and column names should not have any spaces.

Why not use standard Save As Xml functionality

Excel provides more than one ways to export xml data. One of them is ‘Save As Xml Data’ available in Save As dialog. This requires Xml Mappings to be defined which I believe requires developer Add-in from Microsoft to be installed.

Another option is ‘Save As Xml Spreedsheet 2003’ which generates following Xml.

<Worksheet ss:Name="Sheet1">
  <Table ss:ExpandedColumnCount="3" ss:ExpandedRowCount="5" x:FullColumns="1"
   x:FullRows="1" ss:DefaultRowHeight="15">
   <Column ss:Width="51"/>
   <Column ss:Width="54"/>
   <Column ss:Width="51.75"/>
   <Row ss:StyleID="s64">
    <Cell><Data ss:Type="String">Country</Data></Cell>
    <Cell><Data ss:Type="String">Capital</Data></Cell>
    <Cell><Data ss:Type="String">Continent</Data></Cell>
    <Cell><Data ss:Type="String">France</Data></Cell>
    <Cell><Data ss:Type="String">Paris</Data></Cell>
    <Cell><Data ss:Type="String">Europe</Data></Cell>
    <Cell><Data ss:Type="String">Germany</Data></Cell>
    <Cell><Data ss:Type="String">Berlin</Data></Cell>
    <Cell><Data ss:Type="String">Europe</Data></Cell>
    <Cell><Data ss:Type="String">India</Data></Cell>
    <Cell><Data ss:Type="String">New Delhi</Data></Cell>
    <Cell><Data ss:Type="String">Asia</Data></Cell>
    <Cell><Data ss:Type="String">Indonesia</Data></Cell>
    <Cell><Data ss:Type="String">Jakarta</Data></Cell>
    <Cell><Data ss:Type="String">Asia</Data></Cell>

As you can see, the above might not be what you want. It is more a representation of excel sheet than semantics of your data. ExcelExportXML is quite limited but effective in a common scenario where you have tabular data and the first row contains column headers.


Writing Add-in for Microsoft Excel 2010 using Visual Studio 2010

Using Visual Studio 2010 Professional, creating Excel Add-in is pretty simple. Following are the steps I followed for writing an Add-In for exporting Xml:

Step # 1

Create new project of type ‘Excel 2010 Add-in’. The project will have a class file called ThisAddin.cs.

Step # 2

For creating a button on the Excel ribbon, right click on the project and select Add – > New Item.

Step # 3

Select ‘Ribbon (XML)’ from the list of new items and name the ribbon class, say Ribbon1. This will add two files to the project which are Ribbon1.cs and Ribbon1.xml.

Step # 4

Add the following code in ThisAddin class

protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
    return new Ribbon1();
Step # 5

In Ribbon1.xml define the properties of the button that will be displayed on the Excel ribbon. The onAction attribute specifies the method which will be called from Ribbon1.cs on clicking the button (onAction="OnTextButton").

 <?xml version="1.0" encoding="UTF-8"?>
	<customUI xmlns="" onLoad="Ribbon_Load">
	      <tab idMso="TabAddIns">
	        <group id="MyGroup"
	               label="Export XML">
	          <button id="textButton" label="Generate XML"
	             screentip="Export to XML" onAction="OnTextButton"
	             supertip="Export excel sheet to XML file."/>
Step # 6

Add following method declaration to Ribbon1.cs and implement your functionality here.

public void OnTextButton(Office.IRibbonControl control)
    //TODO:Add your implementation here


Microsoft Visual Studio LightSwitch

Visual Studio LightSwitch is a new tool from Microsoft for developing business applications. Currently available development technologies from Microsoft (like VS C#) are general purpose and can be used to develop a wide variety of applications. LightSwitch, on the other hand, is focused on simplifying development of business applications by handling the basic plumbing itself.

I downloaded the currently available Beta1 version of LightSwitch and started playing with it. It took about 5 minutes to get following application ready.

Employee Information Sample App

The above sample application supports addition, updation and deletion of employee records along with employee qualifications and skills. It is an impressive output considering the effort that was put in.

I performed the following steps to develop the sample app.

  1. Click on ‘create table’ in App Designer, name the table as Employee and define its attributes.
  2. Do the same as step 1, for Qualification and Skill.
  3. Create the relationship two relationships using designer i.e. employee-qualification and employee-skills.
  4. Click on  ‘new screen’ in App Designer and specify the table and desired layout.
  5. Hurrah! Application is ready.


LightSwitch Application Designer:

Following is the LightSwitch application designer for tables. Additional settings are available for each attribute from the properties window.

LightSwitch Table Designer
LightSwitch Table Designer


Below is the screen shot of application designer for screens. I didn’t make any changes here except changing the display names for qualification and skill tabs.

LightSwitch Screen Designer


LightSwitch also has a query designer. Queries can also be used as a basis of screen design apart from tables. Following screen shot shows the query designer.

LightSwitch Query Designer


Key Features:

  • We can extend the functionality of LightSwitch application by writing code in C#.Net or VB.Net. LightSwitch allows the developers to easily hook their business logic in application events. We can even write a custom control or fully custom screen.
    I believe this is the single most important feature of LightSwitch, this is where most of the LightSwitch precursors struggled.
Screen Shot shows partial list of methods which can be implemented for a table. Screen designer has a similar 'Write Code' functionality with method like loaded, closed etc.


  • Another important feature is the ability of LightSwitch to connect to various data sources, its not tied up to a particular back-end technology. It support Sql Server, Azure (Cloud), SharePoint, Entity Framework as data sources.
  • The application generated by LightSwitch is a Silverlight application. It runs in out-of-browser mode if application type is desktop. So multiple platforms are supported.
  • Support Master details screen (e.g. invoice and invoice lines)
  • Support searching, sorting and paging of records without writing any code.
  • Support user authentication and role based security using ASP.Net Membership Provider.
  • Handle image as one of the basic attributes of an object.


LightSwitch Links: