Fixing comctl32.dll WIN32Exception

A C# project was recently upgraded from .NET 3.5 to .NET 4.0.
The program worked fine, except on a Windows 8 Pro x64 machine where this error was given:

Win32Exception: Cannot load the “comctl32.dll” DLL into memory.

The solution that worked for us (after a long search) was removing CorFlags to set the application to 32-bits mode. When a new build was created without CorFlags and setting Visual Studio to build the project to x86 instead of x64 solved the problem.

It looks like CorFlags is not reliable…

Get information from Team Foundation Server (TFS) via C# code

This code shows you how you could interact with your team foundation server. In my case a TFS 2010.

Open a new console application in Visual Studio and add these references:

  • Microsoft.TeamFoundation.Client
  • Microsoft.TeamFoundation.VersionControl.Client
TeamFoundationServer tfs = new TeamFoundationServer("http://yourtfsserver:port/something");
List<string> changedFiles = new List<string>();

VersionControlServer VCServer = (VersionControlServer)tfs.GetService<VersionControlServer>();

try
{
string path = @"C:\Users\<username>\Documents\Visual Studio 2010\Projects\just the path to your solution";
VersionSpec version = VersionSpec.Latest;
int deletionId = 0;
RecursionType recursion = RecursionType.Full;
string user = @"domain\yourusername";

foreach (Changeset item in VCServer.QueryHistory(path, version, deletionId, recursion, user, null, null, Int32.MaxValue, true, false, true))
{
  foreach (Change c in item.Changes)
  {
	// c.Item.ServerItem;
  }
}
}
catch { }

Happy coding ;)

C#: Save a canvas as an image

This C# code saves a Canvas as a *.PNG image:

private void CreateSaveBitmap(Canvas canvas, string filename)
     {
       RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
        (int)canvas.Width, (int)canvas.Height,
        96d, 96d, PixelFormats.Pbgra32);
      // needed otherwise the image output is black
       canvas.Measure(new Size((int)canvas.Width, (int)canvas.Height));
       canvas.Arrange(new Rect(new Size((int)canvas.Width, (int)canvas.Height)));

renderBitmap.Render(canvas);

//JpegBitmapEncoder encoder = new JpegBitmapEncoder();
       PngBitmapEncoder encoder = new PngBitmapEncoder();
       encoder.Frames.Add(BitmapFrame.Create(renderBitmap));

using (FileStream file = File.Create(filename))
       {
         encoder.Save(file);
       }
     }

Use it like this:

CreateSaveBitmap(myCanvas, @"C:\temp\out.png");

ASP.NET Web API

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

Can’t wait for the full version of MVC 4! :-)

[ link ]

ASP.NET MVC: place JavaScript from a View inside the head-section by using sections

When working with ASP.NET MVC, you often need some JavaScript in your views.
The most obvious way of doing this is just adding the JavaScript inside the view:

@{
     ViewBag.Title = "About Us";
 }

<script type="text/javascript">
     // some code
   </script>

<h2>About</h2>
 <p>
      Put content here.
 </p>

Your html source code will end up with a mess:

<!DOCTYPE html>
<html>
 <head>
<meta charset="utf-8" />
<title>About Us</title>
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
</head>
 <body>
     <div>
         <header>
             <div id="title">
                 <h1>Title</h1>
             </div>
            <div id="logindisplay">
                     [ <a href="/Account/LogOn">Log On</a> ]
            </div>
             <nav>
                 <ul id="menu">
                     <li><a href="/">Home</a></li>
                     <li><a href="/Product">Products</a></li>
                     <li><a href="/Home/About">About</a></li>
                 </ul>
             </nav>
         </header>
         <section id="main">
<script type="text/javascript">
            // some code
          </script>
          <h2>About</h2>
          <p>      Put content here. </p>
</section>
        <footer>
        </footer>
     </div>
 </body>
 </html>

As you can see in the code above, the JavaScript was added where the your view was rendered.
To keep your code clean, you can use and render sections!

Open your master View _Layout.cshtml and add a RenderSection:

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="utf-8" />
     <title>@ViewBag.Title</title>
     <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
     <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
     <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
     @if (IsSectionDefined("MyOtherJavascript"))
     {
       @RenderSection("MyOtherJavascript");
     }
 </head>
 <body>

Now in your View (in my case /Home/About.cshtml) add the section:

@{
     ViewBag.Title = "About Us";
 }
@section MyOtherJavascript {
   <script type="text/javascript">
     // some code
   </script>
 }
<h2>About</h2>
 <p>
      Put content here.
 </p>

Now your JavaScript will be injected inside the header:

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="utf-8" />
     <title>About Us</title>
     <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
     <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
     <script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
<script type="text/javascript">
     // some code
   </script>
 </head>
 <body>
<!-- ... -->

That’s it! :)
You can add more logic to it, there is also an overload of the RenderSection in case you just want to say it is optional or not.

I demonstrated the RenderSection by injecting JavaScript into the header, but this can be used in other places (and you can also inject and render normal html code). ;-)

FYI: I’m using ASP.NET MVC 3 with Razor engine.

msdn ]

Recursive Lambda Expressions in C#

The first two samples, loop & loop2, show you a recursive Lambda Expression. The first version has some console outputs for debugging. I’ve also added a sample that gives you the 10th Fibonacci number.

The other samples are just showing you some syntactic sugar that can be used when working with Lambda Expressions.

using System;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Func<int, string> consoleResult = x => string.Format("Result: {0}" + Environment.NewLine, x);

// loop version 1 (debug)
Func<int, int> loop = null;
loop = x => { Console.WriteLine(x); return x == 0 ? 1 : x * loop(x - 1); };
Console.WriteLine(consoleResult(loop(5)));

// loop version 2
Func<int, int> loop2 = null;
loop2 = x => x == 0 ? 1 : x * loop(x - 1);
Console.WriteLine(consoleResult(loop2(5)));


// Fibonnaci
Func<int, int> fib = null;
fib = x => x < 2 ? x : fib(x - 1) + fib(x - 2);
Console.WriteLine(consoleResult(fib(10)));

//-----------------------//
// Some other examples
//-----------------------//

// version 1
Func<int, int> calc = null;
calc = (x) => { Console.WriteLine(x); return x >= 1024 ? x : calc(x * 2); };
Console.WriteLine(consoleResult(calc(2)));

// version  2
Func<int, int> calc2 = null;
calc2 = x => x >= 1024 ? x : calc2(x * 2);
Console.WriteLine(consoleResult(calc2(2)));

// version 3
Func<int, int> calc3 = null;
calc3 = x => x >= 1024 ? x : calc3(x * 2);
Console.WriteLine(consoleResult(calc3(2)));

// version 4
Func<int, int> calc4 = null;
calc4 = x => { return x >= 1024 ? x : calc4(x * 2); };
Console.WriteLine(consoleResult(calc4(2)));

// version 5
Func<int, int> calc5 = null;
calc5 = (x) => x >= 1024 ? x : calc5(x * 2);
Console.WriteLine(consoleResult(calc5(2)));

// version 6
Func<int, int> calc6 = null;
calc6 = (x) => { return x >= 1024 ? x : calc6(x * 2); };
Console.WriteLine(consoleResult(calc6(2)));

// Don't close the console directly
Console.ReadLine();
}
}
}

You will see a compiler error Use of unassigned local variable ‘fib’  when you try something like this:

Func<int, int> fib = x => x < 2 ? x : fib(x - 1) + fib(x - 2);

The compiler cannot use fib because it is not yet assigned.
(Depends on which side the C# Compiler evaluates first).

Have fun exploring Lambda Expressions, recursion and Func<T, TResult> ;)

C# Expression Trees

Just a quick example that you can try yourself. It can be hard to write and debug Expression Trees but they are very powerful.

using System;
using System.Linq.Expressions;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Func<int, int> f = (x) => x + 1; // Same as: x++
var result = f(1);
Console.WriteLine("My result: " + result);

// ------

var result2 = f.Invoke(1);
Console.WriteLine("My result (via Invoke): " + result2);

// ------

ParameterExpression param0 = Expression.Parameter(typeof(int)); // first parameter
ParameterExpression param1 = Expression.Parameter(typeof(int)); // second parameter
ConstantExpression const0 = Expression.Constant(1);             // a constant

BinaryExpression expr = Expression.Add(Expression.Subtract(param1, const0), param0); // Same as: param1 - constant + param0
Expression<Func<int, int, int>> lambdaExpr = Expression.Lambda<Func<int, int, int>>(expr, param0, param1); // creates the lambda delegate

Func<int, int, int> compiledExpr = lambdaExpr.Compile(); // compiles the expression tree
var result3 = compiledExpr(1, 1); // executes the epxression tree with param0 and param1

Console.WriteLine("My result via Expression: " + result3);

// Don't close the console directly
Console.ReadLine();
}
}
}

See also the ExpandoObject in C#.

Enjoy ;)