Convert C# code to JavaScript

January 18, 2014 Leave a comment

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
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 http://sharpkit.net/Compare.aspxHomepage: http://sharpkit.net/

Homepage: http://sharpkit.net/
Google Code: https://code.google.com/p/sharpkit/

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).

Homepage: http://jsil.org/
GitHub: https://github.com/sq/JSIL

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.Homepage: http://www.jsc-solutions.net/
Wiki & Tutorials: http://wiki.jsc-solutions.net/
Sourceforge: http://sourceforge.net/projects/jsc/
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.

Homepage: http://scriptsharp.com/
GitHub Repository: https://github.com/nikhilk/scriptsharp

For a comprehensive list of tools that convert C# and other languages to JavaScript, visit https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS

Categories: .Net, Web Tags: , , ,

Developed Custom .Net Font Dialog

November 28, 2013 Leave a comment

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

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.

Usage

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.

Categories: .Net, WinForms Tags: , ,

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

October 17, 2013 Leave a comment

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:
                    break;
                case Keys.Decimal:
                case (Keys)190: //decimal point
                    if (myNumericTextBox.Text.Contains('.'))
                    {
                        e.SuppressKeyPress = true;
                        e.Handled = true;
                    }
                    break;
                default:
                    e.SuppressKeyPress = true;
                    e.Handled = true;
                    break;
            }

        }

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.

Categories: .Net, WinForms Tags: ,

How to embed chrome browser in .net application

October 16, 2013 9 comments

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.
ChromiumEmbedded
(CEF)
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.
Categories: .Net, Web Tags: , , , ,

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

October 13, 2013 Leave a comment

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.

[DllImport("user32.dll")]
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);
Categories: .Net, WinForms Tags: , ,

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

September 24, 2013 Leave a comment

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]
        {
            get
            {
                return list[i];
            }            
        }

        private int maxSize;

        public int MaxSize
        {
            get
            {
                return maxSize;
            }                      
        }

        public int Count
        {
            get
            {
                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.

Categories: .Net Tags: ,

Completed ‘HTML5 Game Development’ course from Udacity

September 23, 2013 Leave a comment

I have been taking Massively Open Online Courses at Coursera, but this is the first one at Udacity. The two platforms take different approaches… Coursera is more like a virtual classroom while Udacity feels like a very well designed interactive tutorial. Udacity is self-paced with very short video clips interspersed with questions and quick programming assignments. On the other hand, courses at Coursera start at specific dates and the assignments have deadlines. All students of a batch enroll in the class at the same time and discuss same topics on forums as the course progresses. This gives a more real university classroom like structure to Coursera.

The ‘HTML5 Game Development’ course teaches basic skills to get started with 2D game development. It does that by going through techniques and tools that were used to develop GRITS. GRITS can be downloaded from here. The overall quality of the course could be improved, particularly the grader bugs in some of the assignments were frustrating. Still I had a good time, mainly because Udacity as a platform is great and going by the posts in discussion forums, rest of the computer science courses at Udacity have excellent content. I would be hooked on Udacity for some time :)

Following are the tools used or recommended during the course:

Creating Sprite Sheets http://www.codeandweb.com/texturepacker
Map Editor http://www.mapeditor.org/ (Tiled)
Physics Engine http://box2d.org/
Audio Editor http://www.goldwave.com/

HTML5 Game Development - Udacity-page-001

Follow

Get every new post delivered to your Inbox.

Join 33 other followers