ASP.NET MVC JsonResult on Mono and the JavaScriptSerializer

I have been doing a little work on an ASP.NET MVC solution on Visual Studio and Windows and then a little later i moved it to MonoDevelop on OS X to continue development. Opening the Visual Studio solution file in MonoDevelop just works and compiling the code has no issues, however running it I got the following exception:

Cannot cast from source type to destination type.

System.InvalidCastException: Cannot cast from source type to destination type.
  at System.Web.Script.Serialization.JavaScriptSerializer..ctor (System.Web.Script.Serialization.JavaScriptTypeResolver resolver, Boolean registerConverters) [0x0000d] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/System.Web.Extensions/System.Web.Script.Serialization/JavaScriptSerializer.cs:66 
  at System.Web.Script.Serialization.JavaScriptSerializer..cctor () [0x00000] in <filename unknown>:0 

After a little investigation I found that it is mixed up DLL's causing this. You can see on the screenshot below two versions of System.Web.Extensions.dll is loaded both 3.5 and 4.0.

System.Web.Extensions loaded twice in two different versions

The reason for this seems to be that the System.Web.Mvc.dll is compiled referencing the 3.5 version and not the 4.0 version so we can easily fix this with a redirect using assemblyBinding element in our web.config:

<runtime>
	<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
		<dependentAssembly>
			<assemblyIdentity name="System.Web.Extensions" culture="neutral" publicKeyToken="31bf3856ad364e35" />
			<bindingRedirect oldVersion="3.5.0.0" newVersion="4.0.0.0"/>
		</dependentAssembly>
	</assemblyBinding>
</runtime>

And that should make you able to proceed with your ASP.NET MVC development with Mono

UPDATE: This is already reported as a bug describing the workaround aswell: https://bugzilla.novell.com/show_bug.cgi?id=664813

Posted on 18 Jan 2012 by Jakob T. Andersen

Generating static blog using Mono's LameBlog

This blog is generated using Mono LameBlog a tool created by Miguel de Icaza to run his own blog. I stumpled upon it in the mono source tree a couple of years back when i was doing some work with Mono. Without offending anyone I think you can say that LameBlog is not a polished piece of software, but it is actually very convinient for a couple of reasons:

  • Blogentries in your favorite VCS
  • Easy offline editing with your favorite editor
  • Simple hosting setup, only needs to support basic HTML
  • Scalable as it is only HTML

It works by generating the whole site structure from a predefined format of entries stored on your local disk, to do this it uses a template and a configuration file which you can use to tweak apperance (I didn't do this much as you can see). Furthermore the deployment process is hidden in the makefile of the projects and utilizes rsync to push changes to the server.

So to sum up the workflow this it how it looks like when i write a blog post:

vim ~/Activity/2012/jan-16.html
#Write the blog post using HTML and small #-prefixed lines for imagehandling etc
cd Projects/lb
make push

Note that i have my posts stored in VCS but commands not included above.

To make the interactive features of a common blog like commenting and search work third party providers is used, namely a Disqus and a Custom Google Search, its a little bit of an experiment and primarily aimed at making blogging so convenient as possible for me so i might do it more often, but we have to see.

Currently this site is hosted on a free-usuage-tier EC2 micro instance at Amazon with an nginx webserver

Posted on 16 Jan 2012 by Jakob T. Andersen

Writing a calculator in C# using Irony

My friend Mark wrote a post last week about implementing a calculating compiler using SableCC. I have worked with SableCC on a project where we needed to parse C# code and I have to admit I don't recall SableCC as a friendly framework, and reading Mark's post proves my memory right.

First of Mark's grammar is very specific to SableCC, a lot af tricks is made to make SableCC accept the grammar and furthermore the grammar is complicated further by handling operator precedence. If we disregard performance considerations and focus on an easily understandable and maintainable compiler structure our grammar for our parser generator ideally would look very much like the Extended Backus Naur Format (EBNF) of the language.

number = digit+ | digit+ '.' digit+
lparen = '('
rparen = ')'
binop = '+' | '-' | '/' | '*' | '%'
funcname = letter+
expression := lparen expression rparen | expression operator expression | funcname lparen expression rparen | number

Irony is like SableCC a scanner/parser generator but it is implemented as an internal DSL in C# for specifying grammars on a format very close to EBNF. The code is specified in the constructor body of a class inherting from Irony's Grammar class. The EBNF described above (slightly modified for readability) looks like this:

public class SimpleCalcGrammar : Irony.Parsing.Grammar{
    public SimpleCalcGrammar(){
        var number = TerminalFactory.CreateCSharpNumber("number");
        var identifier = TerminalFactory.CreateCSharpIdentifier("identifier");
        var expression = new NonTerminal("expression");
        var binexpr = new NonTerminal("binexpr");
        var parexpr = new NonTerminal("parexpr");
        var fncall = new NonTerminal("fncall");
        var binop = new NonTerminal("binop");
            
        expression.Rule =  parexpr | binexpr | number | fncall;
        parexpr.Rule = "(" + expression + ")";
        binexpr.Rule = expression + binop + expression;
        binop.Rule = Symbol("+") | "-" | "/" | "*" | "%";
        fncall.Rule = identifier + "(" + expression + ")";
        this.Root = expression;
        //...
    }
}

The first few lines are initialization of our Terminals and Productions, this is pretty trivial however a few things is worth noting. Irony is a very rich framework that provides a lot of prebaked functionality, one of these is the TerminalFactory for creating typically used terminals, in our case we use C#'s format for numbers and identifiers, that means we out of the bag get support in our language for suffix on numbers for specifying types etc.

The interresting part is after initialization, here we set up rules for the productions. Irony relies heavily on operator overloading so using our productions and the operators from EBNF we can describe the language pretty straight forward. Lastly we specify what productions is the root of our program, that is the production that contains the entry point for the whole language.

Next up we need to handle operator precedence, fortunately Irony knows that this is a common challenge when developing languages and hence it supports registering our operators and their precedence using the following code:

RegisterOperators(1, "+", "-");
RegisterOperators(2, "*", "/", "%");

Having specified this we have a working parser that can be used like this:

SimpleCalcGrammar g = new SimpleCalcGrammar();
Parser p = new Parser(g);
ParseTree t = p.Parse("25-37+2*(1.22+cos(5))*sin(5)*2+5%2*3*sqrt(5+2)");

This gives us a parse tree that is pretty rough in the edges and hard to work with, what we want instead is a pretty Abstract Syntax Tree that contains exactly the information we need. On our NonTerminal instances we can specify which nodes they should be transformed into, fortunately Irony contains some of the basic nodes that are needed in many languages for instance the binary expression node, so we can specify the built-in BinExprNode on our binexpr NonTerminal like this:

var binexpr = new NonTerminal("binexpr", typeof(BinExprNode));

For us to parse the language we need one aditional node in our AST, that is the FunctionCall node (the observant reader might have noticed i have choosen to implement an openended grammar that allows for extending with new built-in functions without modifying the grammar). Irony has a AST node for function calls built-in but for the sake of the example i will show a custom implementation here:

public class FunctionCallNode : AstNode{
    public string Name;
    public AstNode Argument;
    public override void Init (Irony.Parsing.ParsingContext context, Irony.Parsing.ParseTreeNode treeNode)
    {
        base.Init (context, treeNode);
        Name = treeNode.ChildNodes[0].FindTokenAndGetText(); 
        Argument = AddChild("Arg", treeNode.ChildNodes[1]);
        AsString = Name; 
    }
}
//Adding the node to our function call node
var fncall = new NonTerminal("fncall", typeof(FunctionCallNode));

So implementing our own AST nodes is pretty simple, and Irony has a rich infrastructure for getting text of tokens and adding childnodes as you can see in the sample. Because our parse tree contains a lot of "garbage" that we don't want transferred to our AST, so we need to inform Irony to import these, this is done by marking nonterminals as transient like this:

MarkTransient(parexpr, expression);

And at last we need to set a flag so that the parser generates the Ast using the following line of code:

LanguageFlags = LanguageFlags.CreateAst;

The next step is to actually work with the AST for sementic analysis, codegeneration or as in our case execution of the calculation. Mark did this using a visitor and Irony's AST supports visitors aswell, so we can make the "PrintVisitor" mark used for debugging like this:

public class PrintVisitor : IAstVisitor{
    int indentation = 0;
    public void BeginVisit (AstNode node)
    {
        for (int i = 0;i<indentation ;i++ ) {
            Console.Write("\t");
        }
        Console.WriteLine(node.ToString());
        indentation++;
    }
    
    public void EndVisit (AstNode node)
    {
        indentation--;
    }    
}

Using a visitor looks like this:

SimpleCalcGrammar g = new SimpleCalcGrammar();
Parser p = new Parser(g);
ParseTree t = p.Parse("25-37+2*(1.22+cos(5))*sin(5)*2+5%2*3*sqrt(5+2)");
var astnode = (AstNode)t.Root.AstNode
astnode.AcceptVisitor(new PrintVisitor());

And the result of this operation is:

+(operator)
    Arg: +(operator)
        Arg: -(operator)
            Arg:25
            Arg:37
        Arg: *(operator)
            Arg: *(operator)
                Arg: *(operator)
                    Arg:2
                    Arg: +(operator)
                        Arg:1.22
                        Arg: cos
                            Arg:5
                Arg: sin
                    Arg:5
            Arg:2
    Arg: *(operator)
        Arg: *(operator)
            Arg: %(operator)
                Arg:5
                Arg:2
            Arg:3
        Arg: sqrt
            Arg: +(operator)
                Arg:5
                Arg:2

However, there is no need for us to create a printvisitor, Irony comes with an UI that allows us to work with our grammar and can parse samples and show us AST, parsertrace with parserstatec and much more, this is very useful to see what the grammar actually does under the covers (shift/reduce). But basically we can go ahead and implement pretty much the same visitor as Mark have used for SableCC, but let's do something different. Irony has support for a basic LanguageRuntime, and actually for a basic interpreter aswell. So if we tell our AST-nodes how they should evaluate themselves we get all the infrastructure given to us by Irony!

So lets override the Evaluate method on our FunctionCallNode so it can be used in Irony's interpreter infrastructure:

public class FunctionCallNode : AstNode{
    //....
    public override void Evaluate (Irony.Interpreter.EvaluationContext context, Irony.Ast.AstMode mode)
    {
        Argument.Evaluate(context, AstMode.Read); //Evaluate the argument the result is saved in context.Data
        double input = Convert.ToDouble(context.Data[0]);
        double result;
        if(Name == "sqrt"){
            result = Math.Sqrt(input);
        }else if(Name == "cos"){
            result = Math.Cos(input);    
        }else if(Name == "sin"){
            result = Math.Sin(input);    
        }else{
            throw new NotSupportedException("Method " + Name + " not supported");    
        }
        context.Data.Replace(1, result); //Replace the argument value on the stack with the result of the function call
    }
}

Yes, in real life our methods would be in a method table and not hardcoded here, this is just to demonstrate the functionality of the interpreter in irony. To use the Interpreter we write code like this:

var interpreter = new Irony.Interpreter.ScriptInterpreter(new LanguageData(new SimpleCalcGrammar()));
interpreter.Evaluate("25-37+2*(1.22+cos(5))*sin(5)*2+5%2*3*sqrt(5+2)");
Console.WriteLine(interpreter.EvaluationContext.LastResult);

Voila, done with the code that corresponds to Mark's sample and the result of running the above is: -9.83033874894108 and the built-in Irony interpreter handle almost everything for us leaving me with only 57 lines of pure C# code:

public class FunctionCallNode : AstNode{
    public string Name;
    public AstNode Argument;
    public override void Init (Irony.Parsing.ParsingContext context, Irony.Parsing.ParseTreeNode treeNode)
    {
        base.Init (context, treeNode);
        Name = treeNode.ChildNodes[0].FindTokenAndGetText();
        Argument = AddChild("Arg", treeNode.ChildNodes[1]);
        AsString = Name;
    }
    
    public override void Evaluate (Irony.Interpreter.EvaluationContext context, Irony.Ast.AstMode mode)
    {
        Argument.Evaluate(context, AstMode.Read);
        double input = Convert.ToDouble(context.Data[0]);
        double result;
        if(Name == "sqrt"){
            result = Math.Sqrt(input);
        }else if(Name == "cos"){
            result = Math.Cos(input);    
        }else if(Name == "sin"){
            result = Math.Sin(input);    
        }else{
            throw new NotSupportedException("Method " + Name + " not supported");    
        }
        context.Data.Replace(1, result);
    }
}
public class SimpleCalcGrammar : Irony.Parsing.Grammar{
    public SimpleCalcGrammar(){
        
        var number = TerminalFactory.CreateCSharpNumber("number");
        var identifier = TerminalFactory.CreateCSharpIdentifier("identifier");
        var expression = new NonTerminal("expression");
        var binexpr = new NonTerminal("binexpr", typeof(BinExprNode));
        var parexpr = new NonTerminal("parexpr");
        var fncall = new NonTerminal("fncall", typeof(FunctionCallNode));
        var binop = new NonTerminal("binop", "operator");
        
        expression.Rule =  parexpr | binexpr | number | fncall;
        parexpr.Rule = "(" + expression + ")";
        binexpr.Rule = expression + binop + expression;
        binop.Rule = Symbol("+") | "-" | "/" | "*" | "%";
        fncall.Rule = identifier + "(" + expression + ")";
        
        RegisterPunctuation("(",")");
        RegisterOperators(1, "+", "-");
        RegisterOperators(2, "*", "/", "%");
        
        
        MarkTransient(parexpr, expression);
        
        this.Root = expression;
        this.LanguageFlags = LanguageFlags.CreateAst;
    }
}
Posted on 07 Oct 2009 by Jakob T. Andersen

Why I love extension points - nHibernate Driver

I have used nHibernate on linux for some time now without any major problems. The issues I have encountered have infact not been with Mono but with the MySql dialect in nHibernate. One of these where a nasty issue where nHibernate closed the connection to the database before retrieving the newly generated identifier which (in this case) unfortunately is bound to the current database connection. However I made a fix for this in the MySqlDialect and now it should be committet to nHibernate repository be included in next release.

Today I was starting a new project writing some tests and wanted to use SQLlite in memory for some pseudo integration testing, Mono has built-in support for SQLite in the Mono.Data.Sqlite assembly however nHibernate isn't aware of this and hence espects that you have the SQLite.NET assembly and the SQLite binaries present either in your bin directory or in the GAC. To avoid having to deploy these on my linux box which already has a .NET implementation of SQLite's IDbConnection and IDbCommand i turned to one of the extensions points in nHibernate and made my own Driver as follows:

public class MonoSqliteDriver : NHibernate.Driver.ReflectionBasedDriver
{
    public MonoSqliteDriver() : 
        base("Mono.Data.Sqlite",
        "Mono.Data.Sqlite.SqliteConnection",
        "Mono.Data.Sqlite.SqliteCommand")
    {
    }
    public override bool UseNamedPrefixInParameter {
        get {
            return true;
        }
    }
    public override bool UseNamedPrefixInSql {
        get {
            return true;
        }
    }
    public override string NamedPrefix {
        get {
            return "@";
        }
    }
    public override bool SupportsMultipleOpenReaders {
        get {
            return false;
        }
    }
}

Initially I wanted to derive from the existing SQLiteDriver in nHibernate, but unfortunately the important part is the call to the base constructor on ReflectionBasedDriver, and as SqlLiteDriver hides the constructor of this i can't hook in and provide the three parameters that I need to change. The things changed is the three strings in the constructor call, "Mono.Data.Sqlite" is the assembly where the IDbConnection and IDbCommand implementations are located, and the other two are the names of the implementation. The overridden properties are taken from the existing SqliteDriver in the nHibernate source.

Finally to use our driver we just specify it in our nHibernate configuration

<add key="connection.driver_class" value="Name.Space.MonoSqliteDriver, AssemblyName" />

Conclusion: Extension points are indeed nice, and the stack I use including nHibernate has a lot of them which makes my life a lot easier

Posted on 26 Aug 2009 by Jakob T. Andersen

Implementing Generate Constructor refactoring in MonoDevelop

In this post I will cover how to implement a simple generate constructor refactoring in the Open Source .NET IDE MonoDevelop. I have recently started using MonoDevelop because I run linux on my laptop for various reasons, most important one of them is that I miss the power of the commandline and all the small tools that is pretty standard on linux. But the IDE lacks some features and this weekend I decided to dig into the codebase to try to add a few refactorings, this post will cover the first one.

MonoDevelop is build using .NET and the user interface is based on Gtk. So its a little different structure than WinForms but MonoDevelop comes with a nice designer and the application itself contains a lot of UI code you can be inspired by. Im not much of an UI guy myself so I started in the code. The refactorings in MonoDevelop are all registred in the class MonoDevelop.Ide.Commands.CurrentRefactoryOperationsHandler, in this class a methods exists that generate the commands to be available in the Context menu on the currently chosen type, variable, parameter etc:

CommandInfo BuildRefactoryMenuForItem (ProjectDom ctx, ICompilationUnit pinfo, IType eclass, IDomVisitable item, bool includeModifyCommands)
{
    //Implementation
}

The CommandInfo is in its default implementation a single Command but has a specialisation CommandInfoSet that allows us to return multiple commands, so in the implementation of this method we can add several refactorings that is applicable based on the location in code. The parameters passed to the above method is for helping us determine which commands to add and to supply these commands with the information about the code they need to actually perform the refactoring.

ProjectDom contains information about the current project that is a collection of files containing classes etc. refactorings that modify the public interface of the current class needs this to ensure references to the public interface can be updated. A good example of this is the Rename refactoring, if you rename a public property on a class you need to update all references to this with the new name.

ICompilationUnit contains information of the current CompilationUnit which is typically corresponding to the current source file, it contains information about using directives, attributes and types present.

IType references the class if a interface is clicked so, is currently only there to support the "Implement interface" refactoring which needs to know about both the current class and the interface clicked.

IDomVisitable is the type that the user is currently on, that is a class, interface, member, enum etc. this is going to be the most important in our implementation because we only work on a single type and not modifying anything outside this.

includeModifyCommands is a flag that decides whether the CommandInfo's should include refactorings modifying the type. This is useful for not popping up refactorings modifying types we have no control over.

So we need to add logic to the BuildFactoryMenuForItem method to add our refactoring under certain circumstances, more specific when a we have a class marked in the UI, the code for this looks as this:

 

//Make sure the current item is a type
if(item is IType){ 
    IType type = (IType)item;
    //Make sure that the type is a class and it belongs to a project
    if(type.ClassType == ClassType.Class && type.SourceProject != null){ 
        //Add the command to our CommandInfoSet to be returned (ciset) with its name and a RefactoryOperation delegate
        ciset.CommandInfos.Add("Generate Constructor", new RefactoryOperation(refactorer.GenerateConstructor));
    }
}

As you can see existing code in the method already have initialized the ciset and the refactorer and for simplicity i left out localization of the name of the refactoring. The ciset initialization is pretty straight forward, however the refactorer is interesting: this class contains methods for actually doing the refactoring (or in most cases code that launches the UI that does the refactoring). The refactorer is initialized with pretty much the same parameters as passed to the BuildFactoryMenuForItem:

 

Refactorer refactorer = new Refactorer (ctx, pinfo, eclass, realItem, null);

 

Only difference is that we pass realItem instead of our raw IDomVisitable this is because there is some handling of instantiated types and compound types, but that's out of the scope of this post.

The GenerateConstructor method on our refactorer class is pretty simple as all it does is fire up our UI Dialog (which we still need to make):

 

public void GenerateConstructor(){
    GenerateConstructorDialog dialog = new GenerateConstructorDialog(item);
    dialog.Show();
}

 

Because we are only manipulating a single class and its contents, and we are only adding new code not modifying existing the only thing we need is the IDomVisitable called item which is the class we need to modify. With just a blank dialog put into this, we have now hooked into the structure of MonoDevelop and added our refactoring to the context menu:

 

The generate constructor context menu

 

Lets skip the UI part a little while and go to the actual codegeneration. We can utilize the built in code generation features of MonoDevelop namely the class MonoDevelop.Project.CodeGeneration.CodeRefactorer which has a method AddMember(IType cls, System.CodeDom.CodeTypeMember) we already have the IType that we are currently working on passed to our dialog so we need to construct a CodeTypeMember using the System.CodeDom classes.

Ideally we would like to decouple this generation of the CodeTypeMember completely from our UI code, however to keep in line with the style that the rest of MonoDevelop is written we will keep this coupling. However this is definitively a refactoring candidate that should be done throughout MonoDevelop to decouple the actual refactoringcommands from the UI.

I don't wan't to bore you with a lot of UI code so here as a screenshot instead:

The generate constructor dialog

We have some basic functionality a five column flat TreeView with the following columns:

  1. a checkbox that decides if the field should be in the constructor
  2. the name of the field
  3. the name of the type
  4. the name of the generated parameter that is editable
  5. a checkbox that decides if an assignment should be generated in the body of the constructor

Furthermore we can sort the order of the parameters and this will be reflected in the generated code. First thing we need to add the fields from the selected type to the TreeView, this is done with the following code:

 

//Contains our column and the reference to the actual IField
ListStore store = new ListStore(typeof(bool), typeof(string), typeof(string), typeof(string), typeof(bool),typeof(IField)); 
//Add the store to the model of our TreeView
treeview.Model = store;
//Check if the IDomVisitable is actually a class
if(item is IType){
    foreach(IField field in ((IType)item).Fields){
        //Generate a sensible parameter name from the name of the field
        string paramName = GenerateParamName(field.Name);
        //Add the field to our storage with some default values
        store.AppendValues(true, field.Name, field.DeclaringType.Name, paramName, true, field);
    }
}

 

The code is pretty straight forward, however as mentioned it's not exactly like Windows Forms, but notice the actual MVC approach with us binding the model to the TreeView, actually a very nice way to work with things compared to DataBinding in Windows Forms if you ask me. There is some UI code for generating the columns in the TreeView, handling edits and sorting that i won't post because it is pretty trivial and because this post isn't about programming Gtk. Lastly we should ideally retrieve fields from base types as well that could be initialized and provide them in the list if they are assignable from this type (i.e. protected or public). Lets move on to what happens when we click the OK button and we generate the CodeTypeMember i mentioned before:

 

//Get the CodeRefactorer from the IDE
CodeRefactorer refactorer = IdeApp.Workspace.GetCodeRefactorer (IdeApp.ProjectOperations.CurrentSelectedSolution);
//Get an iterator for our liststore that backs the TreeView
TreeIter iter;
if(!store.GetIterFirst(out iter))
    return;
//Generate our CodeConstructor from System.CodeDom namespace
var constr = new CodeConstructor();
//Loop over the fields in the store
do {
    //Extract information from store
    bool selected = (bool) store.GetValue (iter, colCheckedIndex);
    IField field = (IField) store.GetValue(iter, colFieldIndex);
    bool genassignment = (bool) store.GetValue(iter, colGenAssignmentIndex);
    string paramName = (string) store.GetValue(iter, colParamNameIndex);
    //Check if the user asked us to include this field as parameter
    if(selected){
        //Generate the parameter and add it to the constructor
        CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(field.ReturnType.DecoratedFullName, paramName);
        constr.Parameters.Add(param);
        //Check if the user asked us to generate a default assignment
        if(genassignment){
            //Generate assignment on the form "this.fieldname = paramname" and add to constructor body
            CodeAssignStatement expr = new CodeAssignStatement(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name),
                    new CodeVariableReferenceExpression(paramName)
                );
                constr.Statements.Add(expr);
            }else{
                //Generate a TODO comment if param not handled and add to and add to constructor body
                CodeCommentStatement comm = new CodeCommentStatement(string.Format("TODO: Handle parameter {0}", paramName));
                constr.Statements.Add(comm);
            }
        }
} while (store.IterNext (ref iter));
//Lastly use the refactorer to add the generated constructor to the type
refactorer.AddMember((IType)item, constr);

 

This might seem a bit confusing but actually its not that complicated, a fluent interface around System.CodeDom would certainly make it easier to read. That's basically the code for this refactoring.

There was one single change I had to make to the CodeRefactorer implementation in MonoDevelop because the constructor gets its name from the class, and when using AddMember the class name was hard-coded to be temp when generating the text from the CodeTypeMember, so instead I changed it to take the name from the supplier IType. On a more general note I was very surprised about MonoDevelop, I had expected code of a higher quality and certainly more tests than it has, but that may be the cost of pushing out a pretty feauture complete IDE within a short timeframe.

Posted on 28 Apr 2009 by Jakob T. Andersen
Older entries »