Matt Ward

MonoDevelop NuGet Addin 0.5 Released

A new version of the NuGet addin for Xamarin Studio 4.0 has been released.

New Features

  • NuGet 2.6 support.
  • Support for prerelease packages.
  • Support for packages using XML Document Transformations (XDTs).
  • File conflict dialog when installing a package that is trying to add files that already exist in the project.
  • Installation errors now displayed in the Manage Packages dialog.
  • Support for packages that include MSBuild targets and properties files.
  • Support for accessing authenticated feeds.
  • Update All button added to Manage Packages dialog so all packages can be updated in a project or solution in one step.
  • Package title displayed in the list of packages instead of the package id. The package id displayed when a package is selected on the right hand side of the dialog.

For a detailed look at the new features please read the release note.

IronPython Error: Attribute of Namespace Object is Read-Only

If you are seeing an AttributeError, as shown below, when running IronPython 2.7 then check you have added all the required assembly reference to your application.

AttributeError: attribute 'Xml' of 'namespace#' object is read-only

The attribute name displayed will most likely be different but the underlying problem is that you are trying to use a type that exists in an assembly that is not referenced. Here is a simple example that reproduces the error.

import System
doc = System.Xml.XmlDocument()

The code above is importing the System namespace and then attempting to create an XmlDocument object. Running the above code with ipy.exe will result in the AttributeError being displayed.

D:\projects>ipy
IronPython 2.7.3 (2.7.0.40) on .NET 4.0.30319.296 (32-bit)
Type "help", "copyright", "credits" or "license" for more information.
>>> import System
>>> doc = System.Xml.Document()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: attribute 'Xml' of 'namespace#' object is read-only
>>>

The cryptic error message indicates that we do not have a reference to the System.Xml assembly. To fix the problem we add the following two lines of code before the code that creates the XmlDocument object.

import clr
clr.AddReference("System.Xml")

Running the code again will now cause the XmlDocument object to be created without an error.

D:\projects>ipy
IronPython 2.7.3 (2.7.0.40) on .NET 4.0.30319.296 (32-bit)
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> clr.AddReference("System.Xml")
>>> import System
>>> doc = System.Xml.XmlDocument()
>>> doc.ToString()
'System.Xml.XmlDocument'
>>>

Cloning a CodePlex Repository over to GitHub

How do you clone a CodePlex Git repository over to GitHub?

Here we take a look at how to clone the Entity Framework Git repository, which is available on CodePlex, over to GitHub. The goal is to be able to take new commits from the original CodePlex Git repository and update the repository being hosted on GitHub.

  1. Create a repository on GitHub.

    Do not initialise the repository with a readme file just create the repository. We are going to call this repository entityframework-sharpdevelop since this will be a port of the Entity Framework which will work with SharpDevelop.

  2. Clone the CodePlex repository to your local machine.

    Using your favourite Git client clone the Entity Framework repository at CodePlex to your local machine.

     git clone https://git01.codeplex.com/entityframework entityframework
    
  3. Configure Git Remotes

    Our goal is to have a setup similar to the following.

     git remote -v
    
     origin  git@github.com:mrward/entityframework-sharpdevelop.git (fetch)
     origin  git@github.com:mrward/entityframework-sharpdevelop.git (push)
     upstream        https://git01.codeplex.com/entityframework (fetch)
     upstream        https://git01.codeplex.com/entityframework (push)
    

    We want an upstream remote that points to the original Entity Framework repository on CodePlex. We also want an origin remote that points our GitHub repository

    First we create the upstream remote by renaming the origin remote. From inside the entityframework folder we run the following command.

     git remote rename origin upstream
    

    Now we add the new origin remote.

     git remote add origin git@github.com:mrward/entityframework-sharpdevelop.git
    

    Run git remote -v to check that the configuration is correct.

  4. Push the code to GitHub

     git push -u origin master
    
  5. Get the latest Entity Framework Commits into GitHub

    Now when you want to get the latest Entity Framework commits from CodePlex you can run the following commands to merge these commits into your local master branch.

     git fetch upstream
     git merge upstream/master
    

    Then you can push the changes up to GitHub.

Creating a GitHub hosted blog with Octopress

Octopress is a blogging framework created by Brandon Mathis. Octopress has great documentation on how to setup Octopress on a GitHub hosted blog which this guide is not trying to replace. The following guide is a simple overview of how to setup Octopress with Windows being used to create the blog posts and push them to GitHub.

Prerequisites

  1. You have GitHub account.
  2. You have a Git client, such as Tortoise Git, installed.

Software Versions

This guide is based on the using the following software:

  • Octopress 2.0
  • Windows 7 (client machine)
  • Ruby 1.9.3

How to setup a GitHub based blog with Octopress

  1. Download and install Ruby 1.9.3 from http://rubyinstaller.org/downloads/
  2. Add ruby to your path

     PATH=c:\ruby193\bin
    
  3. Download the Ruby devkit from http://rubyinstaller.org/downloads/

    Extract to c:\RubyDevKit

    Change into this folder and run

     ruby dk.rb init
     ruby dk.rb install
    

    If you do not install the Ruby devkit then you will get an error when running setting up Octopress and running gem in step 5):

     Gem::InstallError: The 'posix-spawn' native gem requires installed build tools.
    
  4. Clone octopress

     git://GitHub.com/imathis/octopress.git octopress
    
  5. Setup Octopress

    Open a command prompt in the octopress folder. Run the following commands

     gem install bundler
     bundle install
     rake install
     rake generate
     rake preview
    

    Then open a browser and go to http://localhost:4000 to view your blog.

  6. Create a GitHub repository for your blog

    See the Octopress guide.

    Create a new repository in GitHub that has your GitHub username followed by .github.com (e.g. mrward.github.com).

  7. Deploy your blog to GitHub

    From the octopress folder run

     rake setup_GitHub_pages
     rake generate
     rake deploy
    

    The deploy command will cause your blog to be pushed to the master branch of your GitHub repository. Your blog will then be published and accessible via http://username.github.com (where username is replaced with your GitHub username).

    Then you will need to commit your changes made in the source branch and push them to GitHub.

    You now have a repository on GitHub containing your blog. It will have two branches master and source. The master branch contains your blog web pages. The source branch contains the octopress files and your original blog posts. On your local machine the master branch will exist in the _deploy folder. The octopress folder will be tracking the source branch.

  8. Configure your blog

    You will want to configure various settings, such as google analytics, for your blog. The documentation on the Octopress site has the full details on how to configure everything.

  9. Creating blog posts

    From the Octopress folder run:

     rake new_post["Name of your post"]
    

    This will generate a file in the source\_posts folder which you can edit.

    To generate your blog and preview it in the browser run

     rake generate
     rake preview
    

    The generate command will regenerate your blog web pages in the public folder. You will need to copy these files to the _deploy folder. The final step is then to commit and push your changes to GitHub. You will want to commit the changes made in the Octopress folder (i.e. the source branch) and also your blog pages in the _deploy folder (i.e. the master branch). You can use the rake deploy command to automate this copying of pages, committing and pushing your blog web pages to GitHub but if you want more control over the commit message then you can do this final set of steps yourself and commit the pages using your favourite Git client.

ExecutionEngineException thrown when using Code Contracts

Whilst changing the Entity Framework 5.0 NuGet package to work with SharpDevelop a custom build of the NuGet package was causing Visual Studio 2010 to crash when the package was being installed. Debugging the crash by attaching another instance of Visual Studio revealed that an ExecutionEngineException was being thrown when the following line of code was being executed.

Contract.Requires(project != null);

The exception itself had no other information. The exception’s message just repeated the exception that was being thrown: “Exception of type ‘System.ExecutionEngineException’ was thrown.”. This exception indicates an internal error occurred in the CLR execution engine.

The real problem is the use of Code Contracts and not following the Entity Framework documentation on how to build it from source code.

The Contract class is used to define required preconditions and postconditions for a method and is used when defining Code Contracts. It is part of the .NET Framework 4.0 and can be found in mscorlib.dll in the System.Diagnostics.Contracts namespace.

The problem with the custom build of Entity Framework is that there are parts of Code Contracts included with .NET Framework 4.0 so you can compile a project that uses Code Contracts without any errors but on running the application you can have an ExecutionEngineException thrown. This can occur if you do not have the Code Contracts Visual Studio extension installed when the project is built. With this extension installed your assembly will be modified when it is compiled by the code contracts binary rewriter. The rewriter will inject the contracts into your assembly so the checks will be run when the code is executed.

Solution

To get around this problem you have two options.

  1. Install the Code Contracts Visual Studio extension and then rebuild your project. After installing you should have a Code Contracts page in your project options.

  2. Remove CONTRACTS_FULL from the conditional compilation symbols in the project’s options.

CONTRACTS_FULL is used to enable runtime checking of the code contracts. If this is not defined then the calls made to the any of Contract methods are ignored by the compiler when building your project.

ASP.NET MVC 3 T4 Template Properties

Here are the properties that ASP.NET MVC 3.0 provides to T4 templates when you use the Add View and Add Controller dialogs inside Visual Studio 2010.

Add Controller

Property Name Type Description
AddActionMethods Boolean Adds action methods to the generated controller class.
AreaName System.String The name of the Area that the controller is created for.
ContextType System.Type The type of the data context.
ControllerName String The name of the controller class that will be generated.
ControllerRootName String The name of the controller class excluding the Controller part at the end of the name.
EntitySetName String Name of the property on the data context class containing the set of entities.
ModelType System.Type The type of the model class specified in the Add Controller dialog.
Namespace String Namespace that will be used for the generated controller class.
PrimaryKeys PrimaryKey[]
(Microsoft.
VisualStudio.
Web.Mvc.
Scaffolding.
BuiltIn)
Primary keys for the model. See table at end for PrimaryKey properties.
RelatedProperties Dictionary<String,
RelatedModel
(Microsoft.
VisualStudio.
Web.
Mvc.
Scaffolding.
BuiltIn)>
Related properties on the model. See table at end for RelatedModel properties.

Add View

Property Name Type Description
AreaName System.String The name of the Area that the view is being created for.
ContentPlaceHolderIDs List<string> List of content place holder IDs in the master page.
IsContentPage Boolean True if the generated view will be created with a master page or a Razor layout page.
IsPartialView Boolean True if the generated view is a partial view (e.g. an ASP.NET user control).
MasterPageFile String Master page file or Razor layout to be used with view (e.g. ~/Views/Shared/Site.Master).
Namespace String Namespace that will be used for the generated view.
PrimaryContentPlaceHolderID String Primary content place holder ID to be used when creating a view using a master page.
ReferenceScriptLibraries Boolean True if checked in the Add View dialog.
ViewDataType System.Type The view model's type.
ViewDataTypeName String Fully qualified name for the view model's type.
ViewName String Name of the view.

Common Properties

Property Name Type Description
AssemblyPath List<string> List of assemblies referenced by the project and the project's output assembly. Internal use.
Errors CompilerErrorCollection
(System.CodeDom.Compiler)
Used to stored errors that occur whilst processing the T4 template. Internal use.
FileEncoding System.Text.Encoding The encoding of the file that will be generated.
FileExtension String Not set.
FrameworkVersion System.Version The .NET framework version.
OutputFileExtension System.String The extension of the file that will be generated.
TemplateFile System.String The full path to the T4 template file being used.

Primary Key Properties

Property Name Type Description
Name String
ShortTypeName String
Type System.Type

Related Model Properties

Property Name Type Description
DisplayPropertyName String
EntitySetName String
ForeignKeyPropertyName String
PrimaryKey String
PropertyName String
TypeName String

T4 Import Directive - Namespace Alias

How do you specify a namespace alias when using the Import directive in a T4 template?

The Import directive in a T4 template is used to bring a namespace into scope for any code that will be run when the T4 template is processed. Here is an example template that imports the System.IO namespace without using a namespace alias.

<#@ template language="C#" #> 
<#@ output extension=".txt" #> 
<#@ import namespace="System.IO" #> 
<# 
 string text = File.ReadAllText(@"d:\MyFile.txt"); 
#> 
File content: <#= text #>

The T4 template reads all the text in the d:\MyFile.txt which is then saved in the file generated by the template.

If you want to use a namespace alias you can specify it in the import directive in a similar way to how it is done with C# or VB.NET. Here is the example template modified so that an alias of IO is used for the System.IO namespace.

<#@ template language="C#" #> 
<#@ output extension=".txt" #> 
<#@ import namespace="IO = System.IO" #> 
<# 
 string text = IO.File.ReadAllText(@"d:\temp\test.xsd"); 
#> 
File content: <#= text #>

Why does this Work?

T4 templates use the CodeDom to generate C# or VB.NET code which is then executed as the template is processed. When the T4 templating engine processes the Import directive it creates a CodeNamespaceImport Object and passes it the Namespace attribute's value. The CodeNamespaceImport object supports generating a namespace alias when you specify a string of the form "Alias = Namespace" and pass this to its constructor.

Creating a JavaScript Parser with ANTLR that can be used from CSharp

How do you create a JavaScript parser that you can use from C#? One way is to use ANTLR. ANother Tool for Language Recognition (ANTLR) is a parser generated created and maintained by Terence Parr.

The ANTLR website has a JavaScript grammar already defined so we will take that grammar, get ANTLR to create a parser, and then use that parser to parse some JavaScript code. The following guide is based on using ANTLRWorks 1.4.2, which includes ANTLR 3.3, and the CSharp3 code generator version 3.3.1.

Installing ANTLR

  1. Install the Java JDK 1.5. Newer versions than 1.5 may work with ANTLR.
  2. Download ANTLRWorks 1.4.2 (which includes Antlr 3.3).

Check ANTLRWorks can be started by either double clicking the antlrworks-1.4.2.jar file or opening a command prompt and running the following command.

java -jar antlrworks-1.4.2.jar

Generating a JavaScript Parser

Download a JavaScript grammar from http://www.antlr.org/grammar/list](http://www.antlr.org/grammar/list).

I used Chris Lambrou’s JavaScript grammar since this was the most recent.

Open the JavaScript.g file in ANTLRWorks by selecting Open from the File menu.

Edit the JavaScript.g file and add “language=CSharp3” to the options section.

options 
{ 
    output=AST; 
    backtrack=true; 
    memoize=true; 
    language=CSharp3; 
}

The language determines what language the parser code will be generated in. To generate C# there are 3 choices for the language.

  1. CSharp (.NET 1.1 code generated)
  2. CSharp2 (.NET 2.0 code generated)
  3. CSharp3 (.NET 3 code generated)

To specify a namespace for the generated C# classes add another line to the JavaScript.g file.

@namespace { ICSharpCode.JavaScriptBinding }

In ANTLRWorks select Generate Code from the Generate menu. Three files should be generated in an output directory below where JavaScript.g file is located

  • JavaScript.tokens
  • JavaScriptLexer.cs
  • JavaScriptParser.cs

The two C# files are the ones we are interested in and we will now take a look at how we can use them in a C# application.

Using the JavaScript Parser

The C# files that were generated depend on another set of assemblies.

If you generated code using the CSharp3 target then download the CSharp3 assemblies.

For code generated using the CSharp2 and CSharp then download CSharp2 assemblies.

In both cases the assembly you need is Antlr3.Runtime.dll so extract that file from the downloaded zip file.

Now we need to use our parser and lexer.

Create a C# console project and add the JavaScriptLexer.cs and JavaScriptParser.cs files into the project. Add a reference to the Antlr3.Runtime.dll.

Compile the project.

If you receive an error about HIDDEN being undefined then rename HIDDEN to Hidden in the JavaScriptLexer.cs file.

Remove the “[System.CLSCompliant(false)]” from the lexer and parser files to fix the warning about not requiring CLSCompliant to be set.

In order to get access to the results the parser generates you will need to make a modification to the JavaScriptParser.cs. Make the program() method public, as shown below.

public JavaScriptParser.program_return program()

If you generate the parser and lexer as java source code files this method is public but for it is private when using any of the CSharp targets.

The correct way to fix the problem with the program method being private is to modify the JavaScript grammar file. If you add the public keyword to JavaScript.g grammar file as shown below then after regenerating the lexer and parser files using ANTLRWorks the program method will be public.

 public program 
      : LT!* sourceElements LT!* EOF! 
      ; 

Now how do we use the parser? The following code shows you how.

using System; 
using Antlr.Runtime; 
using Antlr.Runtime.Tree; 
using ICSharpCode.JavaScriptBinding; 

namespace JavaScriptParserConsole 
{ 
    class Program 
    { 
        public static void Main(string[] args) 
        { 
            try { 
                string text = "var a = 1;"; 

                var stream = new ANTLRStringStream(text); 
                var lexer = new JavaScriptLexer(stream); 
                var tokenStream = new CommonTokenStream(lexer); 
                var parser = new JavaScriptParser(tokenStream); 
                JavaScriptParser.program_return programReturn = parser.program(); 

            } catch (Exception ex) { 
                Console.WriteLine(ex.ToString()); 
            } 

            Console.Write("Press any key to continue..."); 
            Console.ReadKey(true); 
        } 
    } 
} 

First we have some JavaScript code to parse. In this case we have a simple variable assignment. This JavaScript code is then passed to a ANTLRStringStream class. The lexer takes this stream and produces a set of tokens. We turn the lexer into a CommonTokenStream and then this is passed to the parser. The program_return class returned from the parser is an Abstract Syntax Tree (AST). Getting access to the AST will depend on how the grammar has been defined. In the JavaScript grammar the top part of the AST is called program.

  public program 
      : LT!* sourceElements LT!* EOF! 
      ;

This maps to a method called program in our parser class.

Does a grammar always create an AST? It depends on the grammar options. For the JavaScript grammar we are using:

options 
{ 
    output=AST; 
    backtrack=true; 
    memoize=true; 
    language=CSharp3; 
}

The output is defined to be AST so ANTLR generates classes to produce an AST after parsing the source code. There are two options for output: AST and template. If this option is not specified the default is AST.

Now we still have not done anything useful with the parse results. So let us display the AST.

using System; 
using Antlr.Runtime; 
using Antlr.Runtime.Tree; 
using ICSharpCode.JavaScriptBinding; 

namespace JavaScriptParserConsole 
{ 
    class Program 
    { 
        public static void Main(string[] args) 
        { 
            try { 
                string text = "var a = 1;"; 

                var stream = new ANTLRStringStream(text); 
                var lexer = new JavaScriptLexer(stream); 
                var tokenStream = new CommonTokenStream(lexer); 
                var parser = new JavaScriptParser(tokenStream); 
                JavaScriptParser.program_return programReturn = parser.program(); 

                var tree = programReturn.Tree as CommonTree; 
                WriteTree(tree); 

            } catch (Exception ex) { 
                Console.WriteLine(ex.ToString()); 
            } 

            Console.Write("Press any key to continue..."); 
            Console.ReadKey(true); 
        } 

        static void WriteTree(CommonTree tree) 
        { 
            WriteLine("Tree.Text: " + tree.Text); 
            WriteLine("Tree.Type: " + tree.Type); 
            WriteLine("Tree.Line: " + tree.Line); 
            WriteLine("Tree.CharPositionInLine: " + tree.CharPositionInLine); 
            WriteLine("Tree.ChildCount: " + tree.ChildCount); 
            WriteLine(""); 

            if (tree.Children != null) { 
                IncreaseIndent(); 
                foreach (CommonTree child in tree.Children) { 
                    WriteTree(child); 
                } 
                DecreaseIndent(); 
            } 
        } 

        static int indent = 0; 

        static void WriteLine(string text) 
        { 
            string indentText = String.Empty.PadRight(indent * 2); 
            Console.WriteLine(indentText + text); 
        } 

        static void IncreaseIndent() 
        { 
            indent++; 
        } 

        static void DecreaseIndent() 
        { 
            indent--; 
        } 
    } 
} 

We have taken the program_return class that is returned from the parser’s program method and displayed its tree.

public class program_return 
    : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<object> 
{ 
    private object _tree; 
    public object Tree { 
        get { return _tree; } 
        set { _tree = value; } 
    } 
}

The Tree property is a CommonTree but by default ANTLR returns this as an object. We then pass this tree to a method that displays a few properties from the tree and then looks at the tree’s children and displays them. Each child is also a tree so we call the WriteTree method recursively. With the simple javascript code of “var a = 1;” we get the following output when running this code:

Tree.Text: 
Tree.Type: 0 
Tree.Line: 1 
Tree.CharPositionInLine: 0 
Tree.ChildCount: 4 

  Tree.Text: var 
  Tree.Type: 37 
  Tree.Line: 1 
  Tree.CharPositionInLine: 0 
  Tree.ChildCount: 0 

  Tree.Text: a 
  Tree.Type: 5 
  Tree.Line: 1 
  Tree.CharPositionInLine: 4 
  Tree.ChildCount: 0 

  Tree.Text: = 
  Tree.Type: 39 
  Tree.Line: 1 
  Tree.CharPositionInLine: 6 
  Tree.ChildCount: 0 

  Tree.Text: 1 
  Tree.Type: 7 
  Tree.Line: 1 
  Tree.CharPositionInLine: 8 
  Tree.ChildCount: 0 

Can we specify the type of the Tree? The answer is yes. In the JavaScript grammar we can specify the type to be used for the Tree property by using the ASTLabelType.

options 
{ 
    output=AST; 
    backtrack=true; 
    memoize=true; 
    ASTLabelType=CommonTree; 
    language=CSharp3; 
} 

So we can set the tree’s type to be CommonTree and we would not need to convert the Tree property from an Object to a CommonTree each time. With this change made the lexer and parser class files need to be regenerated with AntlrWorks. We also have to make the fixes described above (HIDDEN and ClsCompliant) to the generated code.

Now the program_return class has been changed:

public class program_return 
    : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> 
{ 
    private CommonTree _tree; 
    public CommonTree Tree {
        get { return _tree; } 
        set { _tree = value; }
    } 
} 

Unfortunately this code does not compile and we get the error shown below.

Error CS0738: ‘ICSharpCode.JavaScriptBinding.JavaScriptParser.program_return’ does not implement interface member ‘Antlr.Runtime.IAstRuleReturnScope.Tree’. ICSharpCode.JavaScriptBinding.JavaScriptParser.program_return.Tree’ cannot implement ‘Antlr.Runtime.IAstRuleReturnScope.Tree’ because it does not have the matching return type of ‘object’.

Looking at the interface definitions it looks like there is a problem with the code generation since the new program_return class does not implement the IAstRuleReturnScope interface completely:

public interface IAstRuleReturnScope<TAstLabel> 
    : IAstRuleReturnScope, IRuleReturnScope 
{ 
    TAstLabel Tree 
    { 
        get; 
    } 
} 

public interface IAstRuleReturnScope : IRuleReturnScope 
{ 
    object Tree 
    { 
        get; 
    } 
}

So we will have to switch back to not defining the tree’s type by not using the ASTLabelType option.

Summary

In summary we have taken an existing JavaScript grammar, generated a parser using ANTLR and then used this parser to parse some JavaScript code and display the results held in the AST.