Tuesday, January 14, 2014

Running C# in PowerShell

How to develop C# without Visual Studio?

I have't bought a laptop in the last 8 years of my career as the companies I worked and working provided me laptops and allowed to take it to home. Now a days my current company is not allowing me to take laptop to home due to auditing. It was OK in the initial days. But now it started affecting my learning. I tried to install Visual Studio express editions in my old desktop with 1 GB RAM. But it cries. So started thinking about alternatives. Algorithms I can try using Javascript and PowerShell. But recently I had to try something particularly in C#. Basically my problem was how to compile and debug C# applications without VisualStudo ?. I thought of using C# compiler (csc.exe) alone. But it will stop any hope of debugging.

Running C# in PowerShell

When I was reading blogs in Feedly, one of the post got my attention. It was talking about adding Types into PowerShell. If I can inject a type which is created from C# source I can write C# apps in PowerShell. Some more google revealed the technique. Its as follows
  • Wrap the C# class definition in a variable.
  • Use the Add-Type cmdlet to load the class from source code stored in above variable
  • Create object of new class using New-Object as usual and use it.

$cs_source = "
public class Calc
    public void Foo()
        System.Console.WriteLine(""Foo called"");
    public static int Add(int n1, int n2)
        return (n1 + n2);
Add-Type -TypeDefinition $cs_source
#Call static variable
[Calc]::Add(4, 3)
$basicTestObject = New-Object Calc
#Call instance variable

Limitations are there for this method. If we modify the C# code and try to load again it will say

Add-Type : Cannot add type. The type name 'Calc' already exists.

This is the behaviour of .Net runtime. In .Net we cannot change the types once its loaded into an AppDomain. PowerShell runs on .Net and uses single AppDomain. So its not possible to remove and load again unless we start a new PowerShell session. We can adopt different methods based on our situation.

Rename the class along with modification

This might not be possible if we have frequent modifications. Also we need to modify the places we are creating objects.

Run in different session

Keep the original PowerShell code in one file say cstest.ps1 Then invoke it from different PS session. You may open cstest.ps1 in one tab of PowerShell ISE and execute the below script from another tab.

powershell D:\Temp\cstest.ps1

Other alternatives to develop C# code without VisualStudio

1 comment:

Anuraj said...

You can try - dotnetfiddle.net or http://www.sliver.com/dotnet/snippetcompiler/