h3mm3's blog

Stories from behind the keyboard

  • RSS
  • Twitter
Showing posts with label CSharp. Show all posts
Showing posts with label CSharp. Show all posts

ScriptCS-GUI has evolved a little bit. At the moment the following helpers are declared inside the static class Gui.

  • Gui.OpenFileDialog(): open a classic Open File Dialog and return the path of the selected file.
  • Gui.SaveFileDialog(): act similar to OpenFileDialog()...
  • Gui.PopUp(): open a pop-up and returns a form object. You can use its Sta.Enqueue(action) method to inject code in the form's main thread (e.g. to add controls at runtime) while working inside the console!
  • Gui.Drawing(): open a drawing form and returns the Graphics object you can use to draw on the form (the console stays responsive in this case too!)

Probably the most useful thing is that I've managed to open Windows Forms from the console while leaving the console "alive responsive" (tipically the console would (in-)act like a zombie after any Application.Run() over the form!). This means that now you can go on using the ScriptCS console and send any command to any window you created FROM the console. This was not obvious and I've got lots of ideas about how to implement ScriptCS-GUI further! - Stay tuned :)

I'm going to write more about these in my next post. For now you can just launch the interactive script "gui-demo.csx", run it and - *hopefully* - send me some feedback :)

The interactive script "gui-demo.csx" lets you play with classic Windows Forms while the console stays responsive!

ScriptCs is a great yet simple to use framework for writing and executing C# scripts.

TL;DR
Chocolatey + NuGet + Roslyn = ScriptCs
ScriptCs + Command Prompt = C# REPL

Beeing able to write and freely execute C# scripts is a great opportunity and can be a time saver. What I lack more at this stage of development of ScriptCs is a simple toolset to implement basic user interactions. I've sterted a new project on GitHub called ScriptCS-GUI. At the moment it holds some vanilla C# scripts but I wish to evolve it to a full featured Script Pack.

As a starter I implemented classic interactions such showing an OpenFileDialog and a SaveFileDialog. In the following example the Console asks the user to select a file and then writes the selected file name.

> #load "gui.csx" // <-- load gui.csx
> var file = Gui.OpenFileDialog(); // <-- show a classic Open File dialog and wait the user to pick a file
> file // <-- write the selected file name on console
C:\temp\foobar.txt

The following script shows you how to read a folder name from the command argument and use it with the Gui.OpenFileDialog helper.

#load "../script/gui.csx"
// Run with:
// scriptcs -script "{filename}.csx" -- c:\some-path

var folder = ScriptArgs.FirstOrDefault(); // <-- the starting folder name
var path = Gui.OpenFileDialog(folder);
Console.WriteLine("You selected: '{0}'.", path ?? "nothing");

Launch the script as shown in the picture and enjoy your interaction... :)

Recently I needed to write some test against an utility class. This class handles an unmanaged type and of course I didn’t want to use this unmanaged type in my tests. I wrote an interface to target the only members of the unmanaged type that were used by my utility class. It turned out that this contract was really simple, having as its only member an indexer:

public interface IIndexable<T>    
{     
       object this[T fieldname] { get; set; }     
}

What I was not aware of (…shame on me…) is that you cannot cast a type to an arbitrary interface if the type doesn’t implement the interface. For instance, let’s consider Dictionary<string, object>. It’s indexer is declared as

public object this[string key] {get; set;} 

It looks like Dictionary<string, object> implements IIndexable<string>... True?

False. That would be duck-typing… Indeed Dictionary<string, object> *could* implement my new interface, but it doesn’t, since when it was defined, it didn't implement it.

Since a posteriori interface implementation is not possible, let’s see if you can define a cast operator, in order to convert a Dictionary to an IIndexable. Well, in C# defining a cast operator towards interfaces is denied. There’s no way to do this, and maybe for an handful of plausible reasons. The following code won’t ever compile (in other words, I cannot write any supplementary code in order to support the following line):

var indexme = (IIndexable<string>) new Dictionary<string, object>();

Since I couldn’t define any conversion method, I decided to implement a kind of proxy (I call it proxy for literal reasons, even if it resembles to me more like a tunnel). A class implements IIndexable<T> and is internally plumbed to the getter and the setter of the other class (e.g. the Dictionary), thanks to Reflection. Moreover, I wrote an extension method to easily create an instance of the proxy.

Let’s start from the extension method:

public static IIndexable<T> AsIndexable<T>(this object source)    
{     
    var t = source.GetType();     
    var idx = t.GetProperty(     
        "Item",     
        new Type[] {typeof (T)});

    var get = idx.GetGetMethod();    
    var set = idx.GetSetMethod();

    return new Indexable<T>(source, get, set);    
}   
As you can see, the extension method looks for the indexer –  t.GetProperty("Item", …) – and passes its getter and setter to the constructor of the proxy class (Indexable<T>). This class is defined like this:

public class Indexable<T> : IIndexable<T>    
{     
        public Indexable(object innerObject, MethodInfo get, MethodInfo set)     
        {     
            _innerObject = innerObject;     
            _get = get;     
            _set = set;     
        }     
        public readonly object _innerObject;     
        public readonly MethodInfo _get;     
        public readonly MethodInfo _set;     
        public object this[T property]     
        {     
            get     
            {     
                return _get.Invoke(_innerObject, new object[] {property });     
            }     
            set     
            {     
                _set.Invoke(_innerObject, new[] { property, value });     
            }     
        }     
    }

The hearth of the class is the indexer member. As you can see, its accessors invoke the accessors of the actual class, so you can simply use it like in the following example:

var dict = new Dictionary<string,object>();

dict.Add("foo", null); /* Allowing subsequent safe assignment operations,
like dict["foo"] = something */

var indexable = dict.AsIndexable();

Assert.IsNull(indexable["foo"]); 

indexable["foo"]="bar";

Assert.AreEquals("bar", indexable["foo"]); 

Writing such a proxy let my write a better decoupled code, since I managed to define my utility class methods as dependant to an interface (IIndexable<T>) instead of an unmanaged class. Perhaps this approach has to be unvestigated further, for instance against garbage collection issues.

I hope any reader comments about this soon. Happy programming!

In C# you can easily unsubscribe a handler to an event using an handy (!) syntax. For instance let’s consider the following class, that exposes an event called MyEvent.

public class MyClass{
  public event EventHandler MyEvent;
  public void Fire() 
  {
    if (MyEvent!=null)
      MyEvent(this, EventArgs.Empty);
    else 
      Console.WriteLine("Nothing to do");
  } 
}

You can subscribe/unsuscribe to that event with the following code:

var myClass = new MyClass();
//Subscribing: 
myClass.MyEvent += MyMethod;

//Unsubscribing:
myClass.MyEvent –= MyMethod;

So far so good. Things gets complicated if you use an anonymous method, since you don't have a method identifier.

myClass.MyEvent+=(s,e)=>{
        Console.WriteLine("Gotcha!");
    };

myClass.MyEvent –= ??? //What's the price of anonymity?

Of course you can store a delegate to the anonymous method in a field or a local variable and use it when you need to unregister that handler:

var myClass = new MyClass();

var handler = (s,e) => { Console.WriteLine(“Gotcha!”); };
//Subscribing: 
myClass.MyEvent += handler;
//Unsubscribing:
myClass.MyEvent –= handler;

What I don’t like in this solution is that you have to store every delegate you think you will possibly unsubscribe. In effect those delegates (a.k.a. “Invocation list”) are yet stored somewhere (i.e. inside a MulticastDelegate - more info here) so storing them once again is kind of a repetition (and somewhat un-DRY-ish).

Unfortunately the only “code” authorized to peek inside a MulticastDelegate is the class that owns it. That’s to say: you cannot cycle through MyEvent’s handlers from outside MyClass.

One possible solution can be instrumenting your class (e.g. MyClass) in order to give that invocation list back to the caller. Let’s add the method GetMyEventHandlers() to MyClass and use some Linq:

public class MyClass 
{
  public event EventHandler MyEvent; 
 
  public void Fire() 
  {    
    if (MyEvent!=null)      
      MyEvent(this, EventArgs.Empty);    
    else
      Console.WriteLine("Nothing to do");  
  } 

  public IEnumerable<EventHandler> GetMyEventHandlers()
  {
    return from d in MyEvent.GetInvocationList() select (EventHandler)d;
  }  
}

In the previous code, note how the EventHandler delegate type associated to the event MyEvent is the same type used in the cast operator inside GetMyEventHandlers method.

Now we can simply ask MyClass the event invocation list and use it to unsubscribe our anonymous method.

//Subscribing an anonymous method:
myClass.MyEvent += (s,e)=>{ Console.WriteLine(“Gotcha!”) };

//Removing last handler:
myClass.MyEvent -= myClass.GetMyEventHandlers().Last();

The following code shows the whole definition of MyClass and an usage example; you can take the entire code and paste it inside LinqPad…

//A working example...
void Main()
{
  var myClass = new MyClass();
  myClass.MyEvent += MyMethod;
  myClass.MyEvent+=(s,e)=>{
    Console.WriteLine("Gotcha!");
  };
  
  //Will execute 2 handlers
  myClass.Fire(); 
  
  //Removing last handler:
  myClass.MyEvent -= myClass.GetMyEventHandlers().Last();
  
  //Will execute just MyMethod
  myClass.Fire(); 
}

void MyMethod(object s, EventArgs e) 
{
  Console.WriteLine("I got you!");
}

public class MyClass 
{
  public event EventHandler MyEvent;
  
  public void Fire() 
  {
    Console.WriteLine("Fire!");
    if (MyEvent!=null)
      MyEvent(this, EventArgs.Empty);
    else 
      Console.WriteLine("Nothing to do");
  }
  
  public IEnumerable<EventHandler> GetMyEventHandlers()
  {
    return from d in MyEvent.GetInvocationList()
           select (EventHandler)d;
  }
}

As expected, the output of the previous example will be:

Fire! 
I got you! 
Gotcha! 
Fire! 
I got you! 

Happy programming!

In a previous post I told how I implemented a simple Mandelbrot fractal generator by using WebMatrix. At last the page is accessible to everyone at http://www.hemme.somee.com/MandelPage.cshtml.

The fractal image is computed server-side by a razor C# script. The computation is fired directly by a standard HTTP request (no JSON, just an old- plain-GET-url) like the following one
(you can read more about the interior of Get.cshtml in my previous post):

domain/Mandelbrot/Get.cshtml/Mandelbrot/Get.cshtml
   ?w=470&h=350&maxiter=1000&minr=-2.2&maxr=1&mini=-1.15

After the image returns to the client, the user can zoom it with her mouse. The zoom works just like the HTML5+Javascript implementation that I described in this post. What's different here is that now the page must load a new image from the server, GETting a new URL (instead of computing the image client-side using javascript code). This task is easily accomplished with the help of a JQuery instruction. Actually, the following code registers an handler for the mouse click on the image; the mouse coordinates are then converted in the complex plane and the vertices of the zoomed region are written in the querystring of the new HREF of the image [1]. At this point the HREF attribute is rewritten and the browser reloads the image (that will be computed by the razor server script).

$("#mandel").click(function (e) {
    
     var x = e.pageX - this.offsetLeft;
     var y = e.pageY - this.offsetTop;
    
    $("#spinwheel").css("visibility","visible");

     var halfdeltare = (Mr - mr)/(zoom * 2.0);
     var halfdeltaim = (Mi - mi)/(zoom * 2.0);

     var refac = (Mr - mr) / (w - 1);
     var imfac = (Mi - mi) / (h - 1);
     minre = mr + x * refac - halfdeltare;
     minim = mi + (@h - y) * imfac - halfdeltaim;
     maxre = minre + 2*halfdeltare;
     maxim = minim + 2*halfdeltaim;
    
    $("#mandel img").attr("src","@(Html.Raw(Href("~/Mandelbrot/Get.cshtml")+"?w="+w+"&h="+h))&maxiter="+(maxiter *= 1.5)+"&minr="+minre+"&maxr="+maxre+"&mini="+minim);
    
    mr = minre;
    Mr = maxre;
    mi = minim;
    Mi = maxim;
    
})

The code contains some razor syntax (basically, every identifier starting with '@') since I cut'n'pasted it from the CSHTML source file.

Happy programming!

[1] Note how the region is described by only three numbers, minr, mini and maxr, since the fourth (maxi) can be deduced by the former.

I recently read an interesting MSDN whitepaper about the correct usage of disposable Windows SharePoint Services object. Simply put, handling SharePoint objects without sufficient care can lead to ugly memory leaks.

For instance, one of the subtleties of SharePoint programming best practices is seen in the following sample (taken from the aforementioned article): although the outer object (an SPSite) is correctly instantiated inside an using statement, the dependent objects (i.e. every SPSite siteCollectionInner) wont be disposed when the program exits the using block! (This looks quite scary...)

public static void SPSiteCollectionForEachBestPractice() 
{ 
  string sUrl = "http://spvm"; 

  using (SPSite siteCollectionOuter = new SPSite(sUrl)) 
  {   
    SPWebApplication webApp = siteCollectionOuter.WebApplication; 

    SPSiteCollection siteCollections = webApp.Sites; 

    SPSite siteCollectionInner = null; 

    foreach (siteCollectionInner in siteCollections) 
    {
      Console.WriteLine(siteCollectionInner.Url);
    }
  } // SPSite object siteCollectionOuter.Dispose() automatically called. 
}

This problem can be seen as a specific SharePoint problem, but in this post I mean to describe a solution to the more general question: how you can easily enforce the disposition of object cycled inside a loop. (Of course you can can wrap the inner code with a try..finally statement, and call siteCollectionInner.Dispose() inside the finally block, as illustrated in the whitepaper)
Here is my two cents: an extension method that applies an Action to any element of an IEnumerable<IDisposable> collection, and then dispose it under the hood.

static void DisposingForEach<T>(
IEnumerable<T> collection, Action<T> action) where T:IDisposable 
{
  foreach(var element in collection)
  {
  try
  {
    action(element); 
  }
  finally 
  {
    if (element!=null)
      element.Dispose();
  }
}

Now we can apply the extension method to the sample code. The result looks pretty nice:

public static void SPSiteCollectionForEachBestPractice() 
{ 
  string sUrl = "http://spvm"; 
  using (SPSite siteCollectionOuter = new SPSite(sUrl)) 
  {   
    SPWebApplication webApp = siteCollectionOuter.WebApplication; 

    SPSiteCollection siteCollections = webApp.Sites; 

    SPSite siteCollectionInner = null; 

    siteCollections.DisposingForEach( 
        inner=> Console.WriteLine(inner.Url)};
    }
  } // SPSite object siteCollectionOuter.Dispose() automatically called. 
}

We haven’t affected code readability, code complexity is quite the same and code stability is much higher.

Happy programming!

The Post/Redirect/Get (PRG) pattern is a practical remedy against the “refresh-your-page-after-you-sent-form-data” troubles. In this article I present a simple way to implement this pattern in a WebMatrix website.

The pattern

Simply put, in the PRG pattern, the server, after receiving data from a form page P1, answers with a REDIRECT message to a different page (P2). Doing so, the browser will REQUEST the page P2 and if the user will try to refresh the page (e.g. hitting F5) the browser will simply reload the page P2, without sending any more data to the server.

The Post/Redirect/Get pattern

Image courtesy Wikimedia Common. Original URL: [http://en.wikipedia.org/wiki/File:PostRedirectGet_DoubleSubmitSolution.png]

The solution

In order to keep things clear and simple, my solution is built around three files:

  • A form page (form.cshtml)
  • A server-side page that collects data from the form page (formaction.cshtml)
  • An answer page (result.cshtml)

In form.cshtml we write a simple HTML form, like this:


<body>
   <h1>Enter something</h1>
   <form action="formaction" method="post">
     <input type="text" name="textbox"/>
    <input type="submit"/>
   </form>
</body>

Notice how the action attribute of the form points to the formaction.cshtml page (look ma: no extension! ...more details here).

In formaction.cshtml we read form data from the Request, validate them and finally answers the browser with a REDIRECT, putting an exit code directly inside the URL:

@* A pure server-side page *@
@{
    var textvalue = Request["textbox"];
    
    if (textvalue.IsEmpty()) {
        Response.Redirect("result/ko");
    } else {
        Response.Redirect("result/ok");
    }
}

The last page is result.cshtml. Here we read the exit code from the request (it is in the UrlData List) and write in the page accordingly.

@* The answer page *@
@{
    var result = UrlData[0];
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        @switch (result){
            case "ok":
                <text>All right!</text>
                break;
            case "ko":
                <text>Something left!</text>
                break;
            default:
                <text>Dunno...</text>
                break;
        }
        Back to your <a href='@Href("~/form")'>form</a>.
    </body>
</html>

Happy programming!

When time permits, I like to experiment mixing some old algorithm and new technologies. This time it was up to Mandelbrot fractals generation (an old algorithm) and the WebMatrix (a new application development tool) plus Razor (a new templating engine for ASP.NET web pages). In effect, the Mandelbrot set is a well-known geometric guy, but it never ends to amaze me, especially when it’s time to figure out and try new coloring algorithms. This time it was also the occasion to practice the Razor syntax inside a vanilla WebMatrix project.

imageThe solution

My solution is built around two methods: the Mandelbrot fractal algorithm and a PNG picture generator, that creates a colored image from the fractal data generated by the former algorithm. Both methods are described ahead in this post. The home page Default.cshtml is a simple HTML page, including an <div id=”mandel” /> tag that will host the fractal image.

<!DOCTYPE html>
<html lang="en">     
<head>
        <meta charset="utf-8" /> 
        <title>Razor Mandelbrot Generator</title>
        <script src='@Href("~/Scripts/jquery-1.4.4.min.js")' type='text/javascript'></script> 
    </head> 
    <body>  
        <h1>Razor Mandelbrot Generator</h1>  
        <div id="mandel">@H.MandelbrotHtmlImage(w,h,minR,maxR,minI,maxiter)</div>  
        <!--Zoom box will go here-->
    </body>  
</html>
An <img /> tag will go inside the div#mandel and it’s build by an helper snippet declared in an /App_Code/H.cshtml file, as follows:

@helper MandelbrotHtmlImage(int w, int h, double minr, double maxr, double mini, int maxiter)
{
  <img alt="Mandelbrot Fractal" src="@Href("~/Get?w=" + w + "&h=" + h + "&maxiter=" + maxiter + "&minr=" + minr + "&maxr=" + maxr + "&mini=" + mini)" />
}
As you can see, the image’s href is a request to a Get “page” – in effect WebMatrix will route the request to a Get.cshtml file, as described here). This request gives the page all the parameters it needs to create a fractal image (more details ahead).

Getting the fractal image as a binary stream

The Get.cshtml page does tree things:

  1. Calculating the fractal data
  2. Building and coloring a PNG image from the fractal data
  3. Returning the image as a binary stream
The first and the last tasks are accomplished invoking helper @functions declared inside H.cshtml. The following code is the main fragment of Get.cshtml:

//The Get.cshtml main fragment:

@{
    var data = H.GetMandelbrotSet(w,h,minR,maxR,minI,maxiter);

    var img = new Bitmap(w, h); 
 
   // The coloring algorithm stuff
   // ...

   var ram = new MemoryStream();
   img.Save(ram,ImageFormat.Png);
   ram.Seek(0, SeekOrigin.Begin);
   H.BinaryResponse(ram, String.Format("mandel_{0}_{1}_{2}.png", minR, maxR, minI), "image/png");
}
Starting from the bottom,  the BinaryResponse() method is a @function declared inside H.cshtml page, as follows:

@functions {
  public static void BinaryResponse(Stream s, string filename, string mimetype)
  {
      Response.Clear();
      Response.Buffer = true;

      Response.AddHeader("Content-Length", s.Length.ToString());
      Response.AddHeader("Content-Disposition", "inline; filename=" + filename.Replace(" ", "_"));
      Response.ContentType = mimetype;

      s.CopyTo(Response.OutputStream);
      Response.End();
  }
  // other functions…
}
Also the GetMandelbrotSet() method is declare inside H.cshtml page. It is a classic Mandelbrot algorithm; w and h are respectively the width and the height of the image, minr and mini are the coordinates of the lower-left Complex point and maxr is the Real part of the rightmost point, maxiter is the maximum number of iterations for each single point in the complex plane.

public static int[][] GetMandelbrotSet(
            int w, int h, double minr, double maxr, double mini, long maxiter)
{
    var image = new int[w][];
    for (int i = 0; i < w; i++)
        image[i] = new int[h];

    //Boring implementation details about generating a Mandelbrot fractal
    //...

    return image;
}
In the next article I will describe how I implemented a zooming capability using jQuery and javascript.
Edit: I finally published the second part of the article .

Stay tuned and happy programming!

mandel_-0_794068504594819_-0_682957393483708_0_228786727456941mandel_-0_807063956186762_-0_794718277174417_0_175446076775865mandel_-0_656811782542777_-0_655440040430294_0_343173133450913

Some days ago Raffaele Rialdi spoke at the 18th DotNetMarche Workshop about .NET Parallel Extensions and other goodies – by the way, if you speak Italian you cannot miss the recordings of the event: go here and grab Raffaele’s sessions and Alkampfer’s whole recap about Linq.

In this post I will use the .NET Parallel Library to implement a simple producer/consumer pattern. The scenario is quite simple: a method, a.k.a. the producer, keeps on pushing data inside a collection (in my case, a queue) while one or more methods, a.k.a. the consumers, access - in parallel - the collection and grab their own bits of data. In order to keep things simple, I’m implementing these methods in the form of lambdas.

The queue I’m going to use is a ConcurrentQueue<T>: it is included in a new namespace called System.Collections.Concurrent and it supports parallel computation in a simple and stable way.

var queue = new ConcurrentQueue<int>();

The producer will insert 1000 numbers inside the queue, at intervals of 10 milliseconds. The ForAll() extension method is available to ParallelQuery objects; they, in turn, are the “parallelizable” version of a query or an IEnumerable<T>. In the following code, I use Enumerable.Range() to get one thousand integers, then I convert this IEnumerable<int> to a ParallelQuery<int> and, finally, I set up a parallel computation, pushing the integers into the queue.

Action producer = ()=>{
 Enumerable.Range(0,1000).AsParallel().ForAll(
   n=>{
  queue.Enqueue(n);
  Thread.Sleep(10);
 });
};

The consumer is meant to consume the queue, trying to pull out the next number, if available. If the queue looks empty, the consumer returns and writes the number of items it could de-queue. In this simulation, each cycle of the consumer is delayed by random Thread.Sleep(..). The following code declares a Random object and the consumer Action (the integer index the consumer receives is used to label the messages it writes to the Console):

var r = new Random();

Action<int> consumer = idx=>{
  var count = 0;
  do{
     Thread.Sleep(r.Next(150));
     int n;
     if (queue.TryDequeue(out n))
     {
        count++;
        Console.Write("({0}:{1})",idx,n);
     }
  } while (queue.Count>0);

  Console.Write("\n[#{0}: count={1}]",idx,count); 
};

The following instruction is the magic that starts the producer and – in parallel – activates ten instances of the consumer Action:

Parallel.Invoke(producer, ()=>Parallel.For(0,10,consumer));

All of this stuff is done thanks to the Parallel static class, that belongs to the brand new System.Threading.Tasks namespace. In effect, Parallel.Invoke() is able to launch a parallel computation, running all the actions it receives in input. In this case, it gets only two actions: the producer, and another one (written as a lambda expression) that calls the Parallel.For() method. Parallel.For() is the the asynchronous equivalent of a for(int i;i<max;i++)  statement: in the previous code, it will cycle from 0 (included) to 10 (excluded) and will pass each value to a consumer action, establishing a parallel computation.

You can test the code inside a simple Console application project or – as I did – using LINQPad. The following picture is a sample of the output I got running the code with LINQPad. As you can see, various instances of the consumer alternate each other and grab numbers from the ConcurrentQueue<int>, consuming each datum at different speed - thanks to the random duration Thread.Sleep().

...
(2:890)(7:922)(4:891)(0:923)(9:892)(6:924)(8:893)(5:925)(6:894)(1:926)(8:895)
(1:927)(3:896)(2:928)(7:897)(4:929)(6:898)(5:930)(1:899)(7:931)(0:900)(2:932)
(2:901)(2:933)(9:902)(3:934)(8:903)(7:935)(2:904)(4:936)(6:905)(5:937)(8:938)
(1:906)(6:939)(0:907)(9:940)(3:908)(5:941)(9:909)(7:942)(9:910)(6:943)(2:911)
(1:944)(5:976)(8:945)(8:977)(6:946)(4:978)(8:947)(7:979)(6:980)(0:948)(3:949)
(5:981)(1:982)(2:950)(8:983)(9:951)(2:984)(8:952)(6:953)(1:985)(5:954)(9:986)
(7:987)(4:955)(3:988)(0:956)(1:957)(3:989)(4:958)(8:990)(3:991)(6:959)(2:960)
(9:992)(0:993)(7:961)(5:962)(9:994)(4:995)(9:963)(7:964)(9:996)(1:997)(8:965)
(2:966)(4:998)(3:967)(6:999)(5:968)(0:969)(0:970)(7:971)(9:972)(7:973)(3:974)
(0:975)
[#0: count=113]
[#9: count=71]
[#1: count=115]
[#8: count=89]
[#2: count=107]
[#5: count=108]
[#4: count=77]
[#6: count=110]
[#3: count=112]
[#7: count=98]

The code described in this post lets you try some of the new classes (and patterns) included in the .NET Parallel Extensions. These classes provide powerful yet simple-to-use methods that let you implement parallel algorithms.

Happy programming!

LINQPad 4 doesn’t seem to let you Dump() an ExpandoObject. For instance, the following code doesn’t compile:

dynamic x = new ExpandoObject();
x.Name = "Mario";
x.Age = 23;
x.Dump();

A simple solution is to cast the object to an IDictionary<string,object>:

dynamic x = new ExpandoObject();
x.Name = "Mario";
x.Age = 23;
((IDictionary<string,object>)x).Dump();

The Dump().

By the way, casting to IDictionary<string,object> is the way you can control the dynamic properties of an ExpandoObject, as described in MSDN website.

Edit: Joe Albahari pointed out that you can simply cast an ExpandoObject to (object). For instance:

//...
((object)x).Dump();

Happy programming!

C# generic type inference is a cool feature but you cannot use it at full power with anonymous types, without some hack. Lets see what I mean...

Could the compiler do more?

One useful feature about C# generics is the ability of the compiler to recognize (precisely to infer) the type of the type parameter(s) when you invoke a generic method, based on the type of the corresponding input parameter(s).

For instance, let's consider the following class:

class ClassA
{
  public void Method<T>(T input)
  {
    //Use input in some way...
    Console.Write(input);
  }
}

You can call ClassA.Method() in this way:

Method<T>("Hello generics!");

…or without specifing the value of the T parameter:

Method("Hello generic type inference!");

This feature is most useful when you work with anonymous types, since anonymity deprives you the ability to specify the type name:

var something = new {Text="Hello generics", CanInfer=true};
MethodOne(something);

Type inference in generic classes

Unfortunately, generic type inference is not allowed during constructor invocations because the value of the type parameter is part of the definition of the class you want to instanciate. For instance, let's declare a generic class:

class ClassB<T> {  
  public ClassB(T input) {
    _Input = input; 
  }

  private readonly T _Input; 

  public Method {
    //This will use the _Input field in some way…
  } 
}

In order to instanciate ClassB<T> you have to pass an input type parameter to the constructor, like this:

var c = new ClassB<string>("Hello generics!");

c.MethodOne();

Even if the constructor gets an input parameter of type T, you are not allowed to invoke the constructor without passing explicitly the generic type. For instance, the following invocation will produce a compilation error:

var a = new {Text="Hello generics", CanInfer=false};
var c = new ClassB(a); //This line wont compile

Here comes the hack

There are situations when the lack of generic type inference for generic classes is critical. The previous example is one of them: it looks like you cannot use ClassB<T> with anonymous types at all!

Luckily you can achieve generic type inference …with a little hack! Sorriso All you need is to define a non-generic version ClassB of your generic class ClassB<T> and to implement a generic factory method like this:

static class ClassB
{
  public static ClassB<T> GetInstance<T>(T input)
  {
    return new ClassB<T>(input);
  }
}

Now you can use generic type inference at full power!

var a = new {Text="Can you infer my type?", CanInfer=true};

//Look ma, no generic type parameter!
var cba = ClassB.GetInstance(a);
cba.Method();

Enjoy.

The Iterator

In the article Closing the Gap Between IEnumerator and IEnumerable, Henon describes the class Iterator and its generic version Iterator<T>. An Iterator is basically a wrapper around an IEnumerator, and exposes an IEnumerable interface. This way you can easily apply IEnumerable extension methods to any object that implements GetEnumerator() - such as Sum(), Min(), and so on...

The following code is an implementation of a generic Iterator<T>, slightly adapted from the implementation described in the article above-mentioned:

public class Iterator<T> : IEnumerable<T>
{
  readonly IEnumerator<T> _iterator;

  public Iterator(IEnumerator<T> enumerator)
  {
    _iterator = enumerator;
  }

  public Iterator(IEnumerable<T> enumerable)
  {
    _iterator = enumerable.GetEnumerator();
  }

  public IEnumerator<T> GetEnumerator()
  {
    return _iterator;
  }

  IEnumerator IEnumerable.GetEnumerator()
  {
    return _iterator;
  }
}

Visiting n-dimensional arrays along a defined dimension

DotNet n-dimensional arrays implement GetEnumerator() but they don't implement any method to visit their elements along a defined dimension (e.g. by rows or by columns..); luckily enough, the Iterator<T> can be used over n-dimensional arrays to solve the problem.

For the sake of simplicity, let's consider the basic case of a two-dimensional array. Since Array implements GetEnumerator() and every T[,] is an Array, let's write an adapter to recover an IEnumerable<T> from Array.GetEnumerator().

public static class EnumeratorExtensions
{
//Adapted from Jon Skeet, at StackOverflow http://stackoverflow.com/questions/828342/what-is-the-best-way-to-convert-an-ienumerator-to-a-generic-ienumerator   
  public static IEnumerator<T> AsEnumerator<T>(this IEnumerator e)
  {
   while (e.MoveNext())
     yield return (T) e.Current;
  }
}

As a consequence, you can grab an IEnumerable<T> from a T[,] array in two simple steps:

int[,] numbers;

//Initialization code goes here...

var typedEnumerator = numbers.GetEnumerator().AsEnumerable<int>();
var iterator = new Iterator(typedEnumerator);

Now that we have in iterator, we have in effect an IEnumerable, and so we can use some nice extension method, from the Linq API. For instance, just combining Take(), Skip() and the magic yield return instruction, we can easily write extension methods to visit a bi-dimensional array by rows or by columns,

public static IEnumerable<IEnumerable<T>> Rows<T>(this T[,] table)
{
  var rows = table.GetLength(0);
  var cols = table.GetLength(1);

  for (int r = 0; r < rows; r++ )
    yield return new Iterator<T>(
      table.GetEnumerator().AsEnumerator<T>())
      .Skip(r*cols).Take(cols);
}
public static IEnumerable<IEnumerable<T>> Columns<T>(this T[,] table)
{
  var cols = table.GetLength(1);
  for (int c = 0; c < cols; c++)
    yield return new Iterator<T>(
      table.GetEnumerator().AsEnumerator<T>())
      .Where((d, i) => i % cols == c);
}

Just put the previous two static methods inside a static class and you have powerful extension methods you can use to extract stats like these:

_2Darray = new int[100,100];
//Initialize the array here... 

int[] rowTotals = new int[100];
for (int r = 0; r < 100; r++)
{
  rowTotals[r] = _2Darray.Rows().ElementAt(r).Sum();
}

int[] colTotals = new int[100];
for (int c = 0; c < 100; c++)
{
  colTotals[c] = _2Darray.Columns().ElementAt(c).Sum();
}

And what about finding the best column? This is the code:

var bestCol = table.Columns()
  .Select((c,i)=>new {Idx=i, Total = c.Sum()})
  .OrderByDescending(x => x.Total)
  .First();
Console.WriteLine("Best column is {0}, total: {1}",
bestCol.Idx, bestCol.Total);

Your imagination is the limit

You can use the Column() extension method to sort of transposing the GetEnumerator() method that comes with the Array class. The following code produces an array joining the columns of a bi-dimensional array called _2DArray:

var lineArray = _2Darray.Columns().SelectMany(n=>n).ToArray();
1 2 3 4
5 6 7 8
9 10 11 12

Fig1 - _2DArray.

1 5 9 2 6 10 3 7 11 4 8 12

Fig2 - lineArray

Finally, the following extension method lets you invert the process, starting from a 1-dimensional array and "wrapping" it over a bi-dimensional layout.

public static IEnumerable<IEnumerable<T>> HorizontalWrap<T>(
this IEnumerable<T> collection, 
int width)
{
  yield return new Iterator<T>(collection.Take(width));
}

For instance, let say we have the following array of 31 numbers:

1 2 3 4 ... ... 28 29 30 31

then we can use the HorizontalWrap() method to split the array in chunks of 7 cells and use them to fill a jagged-array (does this remind you of something?):

var days = Enumerable.Range(1,31).ToArray();

var weeksCollection = days.HorizontalWrap(7); 
int[][] weeks = new int[7][];
int weekNo = 0;
foreach(var week in weeksCollection)
{
  weeks[weekNo] = week.ToArray();
  weekNo++;
}

Happy programming!

In a previous post I introduced X2ml, a lightweight library that enables you to produce XML code using strings and overloaded operators. Compared to the state-of-the-art XElement, using operators gives you a better programming experience, since you can avoid nested constructor calls in favor of simple operand-operator concatenation.

Operators and operands

In the following code, slash '/' and percentage '%' operators are used to create the first child (H1) and it's siblings, respectively; star '*' is used to generate attributes or text values:

var x = X.X2ml;
var xExpression = x["div"] 
                     * "@id:main"
                   / "h1" 
                     * "Hello X2ml!"
                   % "p" 
                     * "@class:intro"
                     * "This is vanilla HTML."
                   % "img" 
                     * "@src='x2ml.png'";

var htmlString = xExpression.ToXmlString();

Slash '/' operator is defined in the X2ml.X sealed class as following

public static X operator /(X x, string child)

Other operators are defined in a similar way: each one takes an X object as first operand and returns a reference to an X object. Since every X2ml binary operator is defined such a way, once you have established the very first operand as an instance of X, you can combine any other string in cascade, obtaining each time an X object as a partial result.

The operand x["div"] in the previous sample is used to generate the first instance of X, enabling the cascading invocation of X2ml operators.

So far so good. What's with the very first declaration? X.X2ml is a readonly property that returns a singleton object of type X2ml.X.X2. The indexer defined in X2 is a factory method and returns new X objects named like the string index. For instance, in the previous sample, x["div"] is logically equivalent to the following code:

return new X { Name = "div", Type = XType.Element };

Why only three operators?

X2ml.X declares (overloads) only three operators: star, slash and percentage. They are, in effect, the only highest precedence binary overloadable operators (they are known as the "multiplicative operators" since they are commonly used as mulipication, division and remainder symbols among scalar .Net types).

Using highest precedence (and "same" precedence) operators is crucial in order to let X2ml do its job, since the order in which the compiler generates IL code invocations must not be messed up. Messing up this order could lead the compiler to translate inner expressions before resolving the previous ones, and this could eventually result in a type mismatch. For instance, let's use some parenthesis to alter the expression precedence:

//1. Here expression parsing flows left-to-right:
var expr1 = x["table"] / "tr" / "td";
//2. Here parsing order is altered using parenthesis
var expr2 = x["table"] / ("tr" / "td");

In the second expression, the compiler evaluates first the expression ("tr" / "td") and produces a compilation error, since the division operator is not defined in the domain Strings×Strings. The first expression, on the contrary, gives no error, since each operator is being applied in X's×Strings.

X2ml (X to ML) is a library I’m writing in C# to ease and speed-up the emission of markup code (such as HTML or XML) in .Net projects. The idea behind X2ml is to combine standard strings (System.String) with ad-hoc operators (ATM /, * and %) in order to produce a visual layout representing the structure of the resulting markup. Moreover, the library shows also good performance, comparable if not better to Linq2Xml (don't tell anyone).

For instance, in order to produce this HTML snippet

<div id='main'>
<h1>Hello X2ml!</h1>
<p class='intro'>
This is vanilla HTML.
</p>
</div>

..you can use X2ml this way:

var x = X.X2ml;
var xExpression = x["div"] 
* "@id:main"
/ "h1" 
* "Hello X2ml!"
% "p" 
* "@class:intro"
* "This is vanilla HTML.";

var htmlString = xExpression.ToXmlString();

The library can also be used in combination with Linq, to produce elements from collections. Can you spot what the following code does? (Solution is here)

//Building documents from Linq expressions is easy! 
var x = X.X2ml; //X is the magic class
var q = x["html"] 
/ "body" 
/ "table" * "@align=center" // '@' means 'class'
/ from row in tableInRam
select x["tr"] 
/ "th" * row.Key // '/' creates a child; 
% "td" * row.Value.ToString(); // '%' creates siblings 
var xml = q.ToXmlString(); //This one makes the XML string 

As you can see, apart from the starting operand of the expression, which signals the root element of the XML, all the other operands are plain strings. Operators, special 1-char prefixes like “@” and the indexer do the magic.

While I’m writing this post I’m thinking I can push the syntax a step further, for instance introducing the “#” prefix (ATM it does NOT work), e.g:

/* Introducing the '#' prefix you could reach 
the same effect of "div" * "@id:main" with a simpler: */

"div" * "#main"  

/* The following mod will stretch the syntax even more, allowing the usage 
of special chars like '@' and '#' inside a tag string: */

"div#main"          // <div id='main'/>
"p@intro"           // <p class='intro'/> 
"div#menu@floating" //<div id='menu' class='floating'/>

The project is published on http://x2ml.codeplex.com. Any suggestion and testing effort are welcome!

Some days ago I was demonstrating the use of the yield C# keyword. As MSDN states

The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block

One of the most non-intuitive effects of the yield operator is that when you are visiting the collection, what’s declared inside the block persists in memory throughout the cycle, and the body of the yield block is invoked multiple times, corresponding to each step of the visiting cycle.

For instance, let’s write an iterator block such the following.

IEnumerable<int> Numbers(int min, int max)
{
  int n = min;
  while(n<=max) {
    //Dump invocation time here  
    yield return n++;
  }
}

The comment “Dump invocation time here” invites you to write some code to track the time each yield instruction is being invoked. In this sample, I used the LINQPad, which you can download and test here. By the way, LINQPad is a great piece of software allowing you to execute instant .Net code without creating stuff like Projects or Solutions. Moreover it’s a great tool to test and improve your LINQ skills.

The simplest way to dump something in LINQPad is invoking the Dump() extension method. My iterator code becomes:

IEnumerable<int> Numbers(int min, int max)
{
  int n = min;
  while(n<=max) {
    var stats = new {
      Time = DateTime.Now.ToLongTimeString(),
      Value = n
    };
    stats.Dump(); //this one dumps the stats on the LINQPad output window

    yield return n++;
  }
}

In order to test the Numbers() method, I wrote the following code:

void Main()
{
  DelayVisit(Numbers(2,10));
  Numbers(30,33).Dump();
}
void DelayVisit(IEnumerable<int> e)
{
  foreach(var i in e) // VISITING LOOP
  {
    System.Threading.Thread.Sleep(1000);
  }
}

Main() is the entry point; it invokes DelayVisit() which in turn visits the collection returned (built) by the Numbers() function, waiting 1 second between each loop step. The second line of the Main() method cycles through the elements returned by the Numbers() method (in effect, Dump() “recognizes” the invoker is an IEnumerable, so it dumps each element of the collection).

The output of this test is shown in the following picture. As you can see, the inner block of the while() loop defined in the Numbers() function is invoked at intervals of 1 second. This is an evidence that the yield loop is “surviving” among each cycle of the visiting loop.

yield