Gaurav's profileWalk To Languages World PhotosBlogListsMore Tools Help

Walk To Languages World

{C#, Java, F#, Ruby, Erlang ...}
June 26

C# 4.0 – Complete Coverage + Videos To Watch => Part 1

The next version of .NET, 4.0 is nearby, so i try to cover all the new features showing up in the language space as well as other important things. I will put up links to different posts + important videos one should watch. The most exciting addition to .NET is DLR ( Dynamic Language Runtime ) which is hosted on top of CLR & adds functionality that brings several dynamic languages to .NET Platform as well, e.g. IronPython, IronRuby are already being in progress by Microsoft team & many more. So lets begin upon what's new in C# 4.0 and how DLR helps in achieving that :

C# v4.0

The most popular language on .NET platform continues to evolve under the supervision of Anders Hejlsberg, after adding several functional constructs & the popular LINQ support in v3.0, its time for some dynamic flavor & making office development easy. New Features can be categorized as:

  1. Dynamic Lookup,
  2. Named & Optional Parameters,
  3. COM Interop,
  4. Covariance & Contravariance

Try out Visual Studio 2010 Beta 1 => http://www.microsoft.com/visualstudio/en-us/products/2010/default.mspx and C# 4.0 Samples from here => http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=csharpfuture&DownloadId=5822.

I will post more stuff & links in the next part. #CHEERS#

December 04

Young & Upcoming Generation Of Powerful Languages

Several new languages have come into existence and are becoming more popular with time. Well some of them(Ruby, Haskell, Python, Erlang, others ..) have been around for long time but there implementations on top of CLR (.NET) and JVM has made them more powerful & exciting. One of the major factors for emergence of these languages is “Concurrency”, well said by Herb Sutter in his popular article The Free Lunch Is Over : A Fundamental Turn Toward Concurrency in Software way back in 2005.

Well One of the advices in “The Pragmatic Programmer” says: "Learn at least one new language every year", in order to be a good hacker. The theory is that by learning a new language you “expand your mind” and become “a better programmer”. But one should be careful of choosing what language to learn rather than just learning up new syntax for same things.

Peter Norvig, Director of Research at Google, wrote an article called Teach Yourself Programming in Ten Years where he gave explicit advice on how to choose languages to learn:

Learn at least a half dozen programming languages. Include one language that supports class abstractions (like Java or C++), one that supports functional abstraction , one that supports syntactic abstraction (like Lisp), one that supports declarative specifications , and one that supports parallelism .

For some developers learning new language have been hard since they didn’t want to leave their worlds of .NET and JVM, but now it has become easy to learn new language for them while still benefiting the features of the above two platforms. Microsoft has gone even one step ahead & have built DLR ( Dynamic Language Runtime ) layer on top of CLR. It will be officially included in .NET 4.0 and is very exciting as a technology which is used to run IronPython and IronRuby and support further dynamic langs. My intent here is to summarize about some of the new popular languages & learn them to involve in my coding tasks.

Capture  IronRuby: is ruby on top of CLR [.NET] ( similar offering on JVM is JRuby ). Ruby supports multiple programming paradigms, including functional, object oriented, imperative and reflection. It also has a dynamic type system and is therefore similar in varying respects to Python, Perl, Lisp.

erlang  Erlang: is a general-purpose concurrent programming language and runtime system. Erlang is a functional language, with dynamic typing and for concurrency it follows the Actor model. It has been around for more than 20 years but has recently become very very popular for Concurrency reasons because of its Message Passing Model.

 Capture2 Groovy: An agile dynamic language for the Java Platform. It can leverage Java's enterprise capabilities but also has cool productivity features like closures, builders and dynamic typing.

F#: A succinct, type-inferred, expressive, efficient functional and object-oriented language for the .NET platform. It is combination of type safety, succinctness, performance, expressivity and scripting. It is now being developed at Microsoft Developer Division and will be distributed as a fully supported language in the .NET Framework and Visual Studio ecosystem.

clojure-icon Clojure: Its also supposed to tackle concurrency issues strongly. It is a dynamic, functional programming language that targets the JVM and is a dialect of LISP. Clojure offers a software transactional memory system and reactive Agent system that ensure clean, correct, multithreaded designs.

Capture3  (Scalable Language) is a multi-paradigm programming language designed to integrate features of object-oriented programming and functional programming. Scala runs on the JVM and class abstractions are extended by sub classing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance.

Capture4  Haskell is an advanced purely functional programming language with non-strict semantics . With strong support for integration with other languages, built-in concurrency and parallelism, debuggers, profilers, rich libraries. Unique concepts include monads, and type classes.

#cheers#

which one will you be learning next ..-> comments welcomed

September 20

Programming Bytes Part-1 & Introduction to The Series

In my new ongoing quest to read source code, books, technical blogs, listen podcasts, watch screencasts & videos and do everything in order to be a better developer. Dear Readers, here I present you the 8 bestest of links (often weekly), both widely and deeply related to programming languages & technologies but somewhat close to the worlds of Java, C++, .NET(C#,F#), Ruby, Erlang... ! This series is the motivation from Scott Hanselman's - The Weekly Source Code series.

So lets just start with the stuff for this weekend and feel free to post comments & sending me links to cool stuff that you would like to share.

1# Creating and Destroying Java Objects: Part 2 - This article is based on Effective Java, Second Edition, by Joshua Bloch, which presents proven rules ("items") for improving your programs and designs (a format, by the way, borrowed from Scott Meyers's Effective C++.

2# Erlang - Software for a concurrent world - Erlang is a concurrent functional programming language designed for programming fault-tolerant systems. With share-nothing semantics and pure message passing, Erlang programs scales on multicore computers. It may be the answer to Software Industry's biggest question - How do you program a multicore computer? This talk is presented by Joe Armstrong who is the principle inventor of Erlang and coined the term "Concurrency Oriented Programming".

3# Try Ruby! - It is a 15 min. introductory tutorial for newcomers to Ruby language which is A dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. It runs in the browser and must do if you have never tried Ruby before.

4# F# in 20 Minutes - Part I - F# is a functional programming language built on .NET. F# makes writing some classes of programs much easier than its imperative cousins like C#. Parallel Programming and Language-Oriented Programming are two such domains that can be expressed easily in F#.

5# CLR Garbage Collector - Justin Smith presents the internals of the .NET Garbage Collector and how you should design your types to play nicely with it. Learn about heap allocations, the GC Algorithms, Multiprocessor considerations, and the IDisposable pattern.

6# Dynamic Languages Strike Back - A talk on dynamic languages: the tools, the performance, the history, the religion, everything with lot of fun and humor in it.

7# Easy LINQ Queries, Becoming A Better Developer, And Logging Help - LINQ, a set of classes and language enhancements designed to offer a universal data-querying syntax introduced in .NET 3.5 and Logging Important Information, Warnings, and Errors using Enterprise Library 4.0.

8# Polyglot Plurality - The Pragmatic Programmer says, "Learn a new language every year".This, then, opens the much harder question of, "Which language?".

It'll be fun to watch how this evolves and feedback on quality of links would be helpful too.


#cheers#

August 29

Hiding Windows Form in C# using Global Keyboard Shortcut

Continuing from my previous post, I will explain how to hide your windows form application from Desktop & Taskbar, thus making it completely invisible using a keyboard shortcut. We will use global keyboard hook to achieve this functionality. For those reading the post directly must read my previous post on Easy Way To Achieve Global Keyboard Hook in .NET which explains the design & usage of KeyboardHook class. Below is the code that you would have to add in Program.cs class of your Windows Form Project.

   1: static class Program
   2:     {
   3:         public static bool IsFormHidden;    // For Checking Form is Currently Hidden or Not
   4:         public static IntPtr WindowHandle;  // Handle To Main Window, Registered at First Run of 'HideOrUnhideWindow' Method
   5:         public static bool firstRun;        // To register 'WindowHandle' at first run of method, after that set to false 
   6:  
   7:         [STAThread]
   8:         static void Main()
   9:         {
  10:             firstRun = true;
  11:  
  12:             // Registering Keyboard Hook with Ctrl+Shift+H .
  13:             // HideOrUnhideWindow Method will be called each time when shortcut button is pressed.
  14:  
  15:             KeyboardHook.SetHook(HideOrUnhideWindow, KeyboardHook.BeginKeys.Control_Shift, KeyboardHook.EndKey.H);
  16:  
  17:             Application.EnableVisualStyles();
  18:             Application.SetCompatibleTextRenderingDefault(false);
  19:             Application.Run(new Form1());
  20:  
  21:             KeyboardHook.UnhookWindowsHook();   // Always remember to unhook
  22:         }
  23:  
  24:         // Called Everytime When Keyboard Shortcut is pressed.
  25:         public static void HideOrUnhideWindow()
  26:         {
  27:             // for registering main form window handle at first call to HideOrUnhideWindow Method
  28:             if (firstRun)
  29:                 WindowHandle = Process.GetCurrentProcess().MainWindowHandle;
  30:                 firstRun = false;
  31:  
  32:             if (!IsFormHidden)
  33:             {
  34:                 ShowWindowAsync(WindowHandle, 0);
  35:                 IsFormHidden = true;
  36:             }
  37:             else
  38:             {
  39:                 ShowWindowAsync(WindowHandle, 9);
  40:                 IsFormHidden = false;
  41:             }
  42:         }
  43:  
  44:         [DllImport("user32.dll")]
  45:         private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
  46:     }

To achieve global keyboard shortcut, we make use of KeyboardHook class by simply calling two methods- one for registering and other for unhooking or unregistering keyboard hook as in line no. 15 and 21 above. Note that HideOrUnhideWindow method will be called each time the user presses keyboard shortcut. When this method is called first time, we get the handle to main windows form and then set firstRun boolean variable to false so that in future runs of above method, we don't need to get handle again. IsFormHidden boolean variable simply tells the form is currently in which state, depending on that we call ShowWindowAsync method which requires first argument as handle to window and second argument to tell what to do with that window. We use P/Invoke to call method as signature is shown in line no. 44 to 45. Rest of code is pretty easy and well commented. You can download the project from Hiding Windows Form Project - Visual Studio 2008.


cheers

kick it on DotNetKicks.com

August 23

Easy Way Global Keyboard Hooking In .NET Application

I was looking for a way to use global keyboard hooking in my personal .net application and I came to know that there is no easy way of doing it. So I designed this particular class, which is really easy to use for simple purposes without requiring you to understand any thing. But it is always good to study, you can download these from below & modify as per your requirements & any suggestions are welcomed as well.

SIMPLE USAGE OF CLASS

   1: static class Program
   2:     {
   3:         /// <summary>
   4:         /// The main entry point for the application.
   5:         /// </summary>
   6:         [STAThread]
   7:         static void Main()
   8:         {
   9:             Application.EnableVisualStyles();
  10:             Application.SetCompatibleTextRenderingDefault(false);
  11:  
  12:             KeyboardHook.SetHook(   () => MessageBox.Show("Hello From Hook "),
  13:                                     KeyboardHook.BeginKeys.Control_Shift,KeyboardHook.EndKey.A );
  14:  
  15:             Application.Run(new Form1());
  16:             KeyboardHook.UnhookWindowsHook();
  17:         }
  18:     }

You just need to add methods calls to SetHook and UnhookWindowsHook as shown above in code sample. The first parameter of SetHook method takes a function which takes no parameters & returns no value. The second and third parameter together forms a valid keyboard shortcut. So the function passed in first parameter will be called every time when the user presses Ctrl+Shift+A irrespective of application is currently active or not since it is using global hooking. Remember its very important to call the method UnhookWindowsHook when done, so that there are no leaks because the KeyboardHook class is just a wrapper and it uses P/Invoke calls to do all dirty work.

DESIGN OF KEYBOARDHOOK CLASS

   1: using System;
   2: using System.Diagnostics;
   3: using System.Runtime.InteropServices;
   4: using System.Windows.Forms;
   5:  
   6: public static class KeyboardHook
   7: {
   8:     #region ExternMethods
   9:  
  10:     [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  11:     private static extern IntPtr SetWindowsHookEx(int idHook,
  12:         LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
  13:  
  14:     [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  15:     [return: MarshalAs(UnmanagedType.Bool)]
  16:     private static extern bool UnhookWindowsHookEx(IntPtr hhk);
  17:  
  18:     [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  19:     private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
  20:         IntPtr wParam, IntPtr lParam);
  21:  
  22:     [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  23:     private static extern IntPtr GetModuleHandle(string lpModuleName);
  24:  
  25:     #endregion
  26:  
  27:     public enum BeginKeys
  28:     {
  29:         Alt_Control = Keys.Alt | Keys.Control,
  30:         Alt_Shift = Keys.Alt | Keys.Shift,
  31:         Control_Shift = Keys.Control | Keys.Shift,
  32:         Alt_Control_Shift = Keys.Alt | Keys.Control | Keys.Shift,
  33:     } ;
  34:  
  35:     public enum EndKey
  36:     {
  37:         A = Keys.A, B = Keys.B, C = Keys.C, D = Keys.D, E = Keys.E, F = Keys.F, G = Keys.G, H = Keys.H,
  38:         I = Keys.I, J = Keys.J, K = Keys.K, L = Keys.L, M = Keys.M, N = Keys.N, O = Keys.O, P = Keys.P,
  39:         Q = Keys.Q, R = Keys.R, S = Keys.S, T = Keys.T, U = Keys.U, V = Keys.V, W = Keys.W, X = Keys.X,
  40:         Y = Keys.Y, Z = Keys.Z
  41:     } ;
  42:  
  43:     public static void SetHook(Action act,BeginKeys b, EndKey e)
  44:     {
  45:         _beginKeys = b;
  46:         _endKey = e;
  47:         _action = act;
  48:  
  49:         _hookID = SetHook(_proc);
  50:     }
  51:  
  52:     public static void UnhookWindowsHook()
  53:     {
  54:         UnhookWindowsHookEx(_hookID);
  55:     }
  56:  
  57:     private delegate IntPtr LowLevelKeyboardProc(
  58:                     int nCode, IntPtr wParam, IntPtr lParam);
  59:  
  60:     private const int WH_KEYBOARD_LL = 13;
  61:     private const int WM_KEYDOWN = 0x0100;
  62:     private const int WM_SYSKEYDOWN = 0x0104;
  63:     private static LowLevelKeyboardProc _proc = HookCallback;
  64:     private static IntPtr _hookID = IntPtr.Zero;
  65:     private static BeginKeys _beginKeys;
  66:     private static EndKey _endKey;
  67:     private static Action _action;
  68:  
  69:     private static IntPtr SetHook(LowLevelKeyboardProc proc)
  70:     {
  71:         using (Process curProcess = Process.GetCurrentProcess())
  72:         using (ProcessModule curModule = curProcess.MainModule)
  73:         {
  74:             return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
  75:                                          GetModuleHandle(curModule.ModuleName), 0);
  76:         }
  77:     }
  78:  
  79:     private static IntPtr HookCallback(
  80:                         int nCode, IntPtr wParam, IntPtr lParam)
  81:     {
  82:         if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN)
  83:         {
  84:             int vkCode = Marshal.ReadInt32(lParam);
  85:             if ((Keys)(_endKey) == (Keys)vkCode && (Keys)_beginKeys == Control.ModifierKeys)
  86:             {
  87:                 _action();
  88:             }
  89:         }
  90:         return CallNextHookEx(_hookID, nCode, wParam, lParam);
  91:     }
  92: }

Attachments : Hook.cs File, Sample Keyboard Hook Project [ VS 2008 ]

In next post i will show you how i used this class to hide my personal .NET application using a keyboard shortcut and then displaying it back from same keyboard shortcut.

Cheers

kick it on DotNetKicks.com

July 25

F# is Cool |> Very Cool

F# is multi-paradigm language involving all the big three - Functional, Imperative & Object Oriented features. Moreover it completely supports all the .NET libraries. We have seen recently how Functional language features becoming important in the mainstream, as in C# 3.0 with the introduction of LINQ. So, I have started learning F# and it really is powerful language developed by Don Syme at Microsoft Research. It will be productized and soon become the part of the .NET framework and Visual Studio.

So, I ll be posting, some posts about the ins & outs of F# language. For guys, who have played always with OO languages, will take just some time to adapt them to Functional concepts but they are powerful and we all know, its easy to handle Parallel or Multi Core problems in functional languages.

Check around these links :

Download Links : Microsoft Research - F#                                                                                                                                       Don Syme Blog  : http://blogs.msdn.com/dsyme/

stay tuned..

Immutability in C#

There has been lots of talk about immutability & immutable objects around C# and how one should follow on creating immutable types, what are the benefits of it and what it is all about..?

An object is immutable if its state cannot be changed, once it is created. If you change it ,then new instances of it are created. System.String class is popular example of it in .NET framework. The string objects we create in our code are actually immutable, and when we change it, actually new instance of string object is created and reference to it is returned, this all happens behind the scenes. StringBuilder class is also provided in .NET if you don't want to create too many of string objects in memory in cases where you do lot of string manipulations.

The biggest benefit of immutability is resulting in simplified Concurrent Programming. Since there is no need for synchronization. There can be many types of immutability and many more things to it. People from C# community have posted excellent articles, links are given below including implementation of some popular data structures too..

Luca Bolognese Blog :-

Creating an immutable value object in C# - Part I - Using a class
Creating an immutable value object in C# - Part II - Making the class better
Creating an immutable value object in C# - Part III - Using a struct
Creating an immutable value object in C# - Part IV - A class with a special value
Creating an immutable value object in C# - Part V - Using a library

Erric Lippert Blog :-

Immutability in C# Part One: Kinds of Immutability
Immutability in C# Part Two: A Simple Immutable Stack
Immutability in C# Part Three: A Covariant Immutable Stack
Immutability in C# Part Four: An Immutable Queue
Immutability in C# Part Five: LOLZ!
Immutability in C# Part Six: A Simple Binary Tree
Immutability in C# Part Seven: More on Binary Trees
Immutability in C# Part Eight: Even More On Binary Trees
Immutability in C# Part Nine: Academic? Plus my AVL tree implementation
Immutability in C# Part Ten: A double-ended queue

cheers#

Good Finalize/Dispose Pattern

This is the approach one should follow to clean up internal unmanaged resources. Remember one thing you should use this only if make use of some unmanaged stuff that you want to be cleaned up before your application closes in a better way so that there are no leaks. If you are just using all managed stuff then you should not need to write Finalize() methods only Dispose() pattern would work. Else GC is very intelligent itself to handle all the stuff & auto optimize itself. Rest being said lets focus on practical example that what should we follow in order to write robust code.

Let us say we have some class that does a bit of work with unmanaged types. We follow both the finalize & dispose patterns so that if the user forgot's to call Dispose(), then the garbage collector cleans up the stuff by calling finalize(), & as long as user dispose off objects, the garbage collector doesn't need to finalize things. So in this model, we have best technique & doesn't end up with leaking things. But remember if we are disposing things ourselves then we can afford to call other managed types around & dispose them too if required but if Garbage Collector does Finalize() the object then we can't reference or call any other managed objects around, since we can't be sure if they exist or not.

You should also be aware that objects having Finalize() method are cleaned by GC in two collections. When an object is allocated on managed heap, the runtime determines if it supports Finalize() method & if it does then it is marked as finalizable, & a pointer to it is stored on finalization queue. This queue helps, so that the objects must be finalized before they are removed from heap. When GC starts executing to free memory, then it checks each entry in finalization queue & copies the object off the heap to another managed structure named as freachable (finalization reachable). A separate thread is used by GC to invoke Finalize() on each object present on the freachable table at the next Garbage Collection.

 

   1: public class Wrapper : IDisposble
   2: {
   3:     // to determine if Dispose() method has already been called.
   4:     private bool disposed = false;
   5:  
   6:     // user should call on this method when they are finished with object.
   7:     public void Dispose()
   8:     {
   9:        // passing "true" signifies that the user triggered the cleanup.
  10:        // so dispose managed objects & clean unmanaged stuff too.
  11:        CleanAllStuff(true);
  12:        // suppress the finalization by GC, we don't need it now.
  13:        GC.SupressFinalize(this);
  14:     }
  15:  
  16:     private void CleanAllStuff(bool disposing)
  17:     {
  18:         // check if already been disposed.
  19:         if(!this.disposed)
  20:         {    
  21:             // if disposing == true, then clean up managed resources.
  22:             // i.e. called by user through Dispose() method.
  23:             if(disposing)
  24:             {
  25:                 // dispose managed resources here
  26:             }
  27:             // clean up unmanaged resources here.
  28:         }
  29:         disposed = true; // for future reference that object has been cleaned already.
  30:     }
  31:     
  32:     // Finalize() method, invoked by GC only.
  33:     ~Wrapper()
  34:     {
  35:         CleanAllStuff(false); // cleans only unmanaged stuff signified by passing "false".
  36:     }
  37: }

You can also check out some new GC class methods available in .NET 3.5 i.e. AddingMemoryPressure() & RemovingMemoryPressure() methods.

MSDN Sample available here.

kick it on DotNetKicks.com

Small Useful Utilities For .NET Developer

LinqPad is really one of the great tools, if U really use LINQ very much & can be handy to learn LINQ.It allows to query against the SQL server databases & offers much more functionality.Its portable too, just a 2MB executable, no installation. Moreover it comes with more than 200 examples from the C# 3.0 in a Nutshell Book. So all in all this one is must have for C# & LINQ developers.

LINQpad

Snippet Compiler Live 2008 Ultimate Edition             

This one is awesome, so many frequent times U need to just run a code file but don't want to create a project. When you are just testing small pieces of code, then this tool is really very helpful & its customizable to great extent & provides almost all important features while writing code ( intellisense too).

Snippet Compiler (3.5 .NET Edition)

cheers

My Own .NET based Apps

I have written some small applications. You can always check them out in my public folder of Sky Drive Service. I have added a couple of applications, in future will keep to add some nice handy applications. HideMan is nice example on how to hide & restore currently running windows on your desktop.

You can check them here at : My Apps Folder

cheers

 

Gaurav Kalra

Occupation
Location
Interests
B.Tech - Computer Science Engg,
National Institute of Technology,
India

Channel 9

Loading...Loading...