Category Archives: .NET

Write your Node.js app in C# with Roslyn

When the Microsoft Managed Languages team announced in December 2013, that they replaced the existing C# and Visual Basic compiler, and they use a new compiler to create the daily builds of the next version of Visual Studio, it became obvious to all developers, that something big is coming. The new tool, codename “Roslyn”, has far more capabilities than the previous csc.exe and vbc.exe, so it is not a coincidence that .NET Compiler Platform became its official name.

Roslyn is not only about converting our source code to an executable format, we already had a excellent tools for that for many years. The goal of Roslyn is to open the power of the compiler to developer and development environments (such as for Visual Studio), so this is a compiler-as-a-service solution.

Why do we need that? Compilers are very complicated, and during their execution they collect a huge amount of information about our source code:


It would be a huge mistake, if we would lock that information into a single tool, instead let other tools benefit from this knowledge. The compiler is our only tool that really understands our source code, as it obviously knows from every single character in our source code whether it is code, data, comment etc. Using this knowledge, we can build much better tools, for example many features of the Visual Studio 2015 would never exist without Roslyn.

Here you can see the Roslyn architecture (click for a larger image):


If you want to understand all little boxes feel free to visit the project home page, I just want to point out that you can find here everything from understanding the source code to generating the executable output, and because it is a platform, naturally you have API for everything.

The key item is the Syntax Tree highlighted with yellow, which is the inner representation of our source code, created by the Parser. The API for that is the Roslyn Syntax API, which allows you not only to analyze your source code from source code, but you can even change that on the fly. Let’s take this simple expression as an example:

Regex.Match("my text", @"\pXXX");

Roslyn builds the following syntax tree from that:


(I borrowed the example from the Use Roslyn to Write a Live Code Analyzer for Your API article of the MSDN Magazine, which shows you how to build a Visual Studio plugin on top of Roslyn.)

It is totally up to you, whether you want only analyze or modify this tree.

This has been also recognized by the TypeScript team, and they are using Roslyn from version 1.3 to provide the necessary data for several Visual Studio IDE features. As a result of that the architecture of the TypeScript compiler became much cleaner and much more understandable:


For us the two important components are in the lower box: the Parser and the Emitter. Parser is responsible for building the syntax tree – in this case from the TypeScript source –, and Emitter is responsible for generating the compiler output based on the syntax tree – in this case the JavaScript (.js), the definition (.d.ts) or the source map ( file.

It is important to note that the architecture of Roslyn and TypeScript are pretty similar: first they build a syntax tree, and then they generate the output based on the tree. For Roslyn this is C# –> tree –> IL, for TypeScript it is TypeScript –> tree –> JavaScript.

Because the two trees are similar, we can combine them, and now we have the following solution:


This means we can compile C# to JavaScript with Roslyn and TypeScript!

The huge benefit of this architecture is that the input is the original C# source code (in contrary to the JSIL project for example that compiles Common Intermediate Language to JavaScript), which contains way more information (e.g. inheritance, scoping, etc.) that are lost in the output of the C# compiler. This gives us the opportunity for more efficient code optimization!

Let’s take the Raytracer demo from the JSIL project as an example. The original C# source is 429 lines, the JSIL-generated JavaScript is 793 lines. You could say, that at least it runs, however the memory management is far from optimal:


Processing the same source code with the Roslyn Parser + TypeScript Emitter combo you can get the following results:


We also measured the CPU utilization and Visual throughput (FPS) with the UI Responsiveness tool in Internet Explorer Developer Tools (F12), and we got better results for both metrics as well.

Obviously better memory management and better performance do not come free, the generated code is bigger, in this case 1844 lines of code. The significant increase is the result of the richness of the syntax tree: in contrast to the IL code, it contains information about the classes and member visibility, which can be translated only to complex JavaScript code, but if we do (and the TypeScript Emitter can do that), than we can get better performance with the price of more code to download. We experienced the same result when we analyzed other applications.

This method works not only with browser based applications, but also with native JavaScript apps, for example with your Node.js app. These are the required steps:

  1. Install the Node.js Tools for Visual Studio plugin, which gives you everything you need to develop Node.js apps with Visual Studio.
  2. Download and install the Node.js with C# plugin from the Visual Studio Gallery (coming soon).
  3. After installation, you will see a “Node.js application” project template within the C# project templates. Create your new project with that template.
  4. Implement your application in C#, and of course you can use Visual Studio for that.
  5. You can debug and run your code as usual, because the project template contains the necessary MSBuild targets, that compiles your code with Roslyn and TypeScript, and then passes it to the Node.js Tools for Visual Studio which in turn runs it with Node.

We are looking for beta testers! Before publishing the Visual Studio plugin, we would like to do a broader test and collect feedback from you. If you would like to try our tool, please read these guidelines and leave a comment below, and I will contact you with the download link. Thank you!



This article hit the top of the node.js subreddit:



JSON or not JSON: that is the question

When you write unit tests for a REST API, you probably want to test whether the given response is in the expected format. For example you want to ensure, that the response string is a valid JSON or not.

You can find a very simple tip on StackOverflow and in other blogs as well: just check whether the first character of the response is a < or { character, because JSON is about Object Notation, right? The problem with this approach is not only that it does not perform a thorough analysis, but also that its basic statement is simply not true. According to, a JSON can also contain only a single value, the specification does not require it to be an object or an array at all:


So I love JSON, 123, true and false are all valid JSON strings.

Unfortunately I could not find a simple IsValidJson method, but I could come up with this solution using Newtonsoft JSON.NET library:

    return true;
catch (JsonReaderException)
    return false;

Is there a better solution?


Technorati-címkék: ,,

Calling a PHP webservice from .NET

It happened that I had to call a webservice implemented in PHP from a .NET client via a standard SOAP interface, however it turned out again that Simple Object Access Protocol is not so simple in the real world.

The client received a 400 Bad Request response status from the server which itself, without any more details, didn’t help much to find the real problem. The Apache webserver log contained an Invalid URI in request entry, but that didn’t bring me closer to the solution either.

As many times before, Fiddler helped. Diving into the HTTP traffic I noticed that the request contained an Expect: 100-continue header which was not handled by the webserver. This is a very interesting header, which allows the client to ask the server to evaluate the request headers before the client submits the request body (see RFC 2616 Section 8.2.3 for more details). In short this single header can drastically change the classic request-response sequence to something like this:

Client –> Server:

request headers
Expect: 100-Continue

Server –> Client:

HTTP/1.1 100 Continue
response headers

Client –> Server:

request body

Server –> Client:

HTTP/1.1 200 OK
response headers
response body

The .NET client always sends this header to minimize the network traffic, but it seems that not all servers tolerate it. You can use the Expect100Continue property of the ServicePointManager class to override this behavior:

ServicePointManager.Expect100Continue = false;

You may even have better performance this way, because the HttpWebRequest class by default waits 350 msec for the Continue response.


Technorati-címkék: ,,

.NET Framework 4.5.2

Microsoft has just released a new version of the .NET Framework. Announcement and quick overview of the new features: Announcing the .NET Framework 4.5.2

More details about the new features: What’s new in the .NET Framework 4.5.2

Install packages:

This is an in-place upgrade! It installs side-by-side with the 3.5 SP1 and earlier versions, but in-place upgrades the 4, 4.5 and 4.5.1 version. That’s why the following knowledge base article my be important for you:
KB 2962547 – Known issues for the .NET Framework 4.5.2




You may need .NET 2.0 even if you have 4.0

We have an application that is built on .NET 4.0 Client Profile and uses SQL Server Compact Edition. Because it does not rely on the latest core OS technologies, it runs very well on older Windows versions, which is required by the end-users. To test the latest version I booted a fresh Windows XP virtual machine, and successfully installed the app on it. However the app crashed at the first database operation with the following exception:

System.DllNotFoundException: Unable to load DLL ‘sqlceme35.dll’: The specified module could not be found. (Exception from HRESULT: 0x8007007E)

Obviously, the requested file was in the right folder, and we didn’t change anything in the last version of the app that could explain this exception. So what has been changed?

I couldn’t reproduce the issue neither on Windows 8.1, nor on Windows 7, and not even on older XP machines that had the previous version of the app. And although the previous version was running perfectly on XP, it crashed in the fresh VM, so my conclusion was that something is different in the VM.

First I used the VM downloaded from the site, and I thought that VM has some specificity that breaks our app. So I installed Windows XP from ISO and spent hours and hours to install all the patches from Windows Update. However it didn’t help, the app crashed like before.

Finally I used ILSpy and peeked into the System.Data.SqlServerCe assembly, and because it was referencing .NET Framework 2.0, I gave it a try and installed that older Framework version side-by-side to the new version. And to my surprise the issue was gone!

The beauty of the case:

  • Windows Update was not installing .NET Framework 2.0, only the newer version. It was not the case previously.
  • The .NET 4.0 Client Profile was not enough, SQL Compact Edition required version 2.0 as well.
  • I understand that there was no problem on Windows 7, because that OS contains .NET 2.0, but why didn’t the app crash on Windows 8.1 which doesn’t install .NET 2.0 by default?



.NET Interview Cracker blog

In a job interview you can face with several topics. Even if you are applying for a C# developer position, you have a fair good chance that you will get a few general .NET, database- or webservice-related questions. Of course there are several checklists available online that try to cover these topics one by one, but Chandan Kumar Sinha, a software developer from India, thought that a blog could be a better format.

On the .NET Interview Cracker blog he publishes about 2-3 posts every week and touched C#, .NET, SQL and webservices so far. The posts are not in question-answer format, but instead he summarizes the most important aspects of the topics. This format is great also for professional developers, because it helps to refresh and set out long learned concepts.


Technorati-címkék: ,,,

ASP.NET Medium trust is dead

About 11 years ago, one of the great new features of the .NET Framework was, that you could use code access security (CAS) to control applications: now not only the permissions of the user matter, but thanks to CAS, the code can also have permissions, and in the end they both define what an app can do and what not.

This architecture seemed really promising, but only very few people started using it, although you could use CAS to isolate server applications. For example, according to a Patterns & Practices guidance from 2005, setting Medium trust for ASP.NET is good way to isolate applications from each other on the same server and within the same process.

Since then, many things happened, but CAS has not evolved since version 1.1. No surprise that Jeroen Frijters could find a weak spot in the system, which made Microsoft to update the previous guidance.

According to the KB2698981 knowledge base article, ASP.NET Medium trust is not suitable to isolate apps any more within the same process. The new guidance drops the same process option, and recommends running your web apps in separate application pools, which essentially means separate processes. This is reasonable, because that’s what application pools are originally made for in IIS 6.

I strongly recommend reading KB2698981 for sysadmins as well as developers, because it describes:

  • How to put sites in separate application pools
  • How to configure application pools for isolation
  • How to configure DACLs
  • How to configure a Temporary ASP.NET Files folder location and how to set DACLs per site
  • How to remove sensitive configuration data from root configuration files

Please take application pools seriously and use them, especially with ApplicationPoolIdentity. It can help you sleep better.


Technorati-címkék: ,

Daily .NET quiz

What is the output of the following code:

using System;
using System.Collections.Generic;

public class Program
  static void Main()
    var funcs = new List<Func<string>>();
    var urls = new List<Uri>
      new Uri( "" ), 
      new Uri( "" )

    foreach( var u in urls )
      funcs.Add( () => u.ToString() );

    foreach( var f in funcs )
      Console.WriteLine( f() );

A little help from ReSharper:


As the warning says, this piece of code behaves differently if compiled with the C# 4.0 and the C# 5.0 compilers! Actually this is the only breaking change in C# 5.

The problem is not new (check Eric Lippert’s post from 2009), this piece of code is not mine. I borrowed it from Martin Doms’ blog, who started a daily quiz series about .NET, and this is Quiz #006. The series goes for 3 weeks now, and Martin touches really deep topics. Maybe one day you will meet these questions in a job interview, so I definitely recommend reading them 🙂

You can read the full series at .

Which question do you like most?


Technorati-címkék: ,