SharpDevelop Community

Get your problems solved!
Welcome to SharpDevelop Community Sign in | Join | Help
in Search

Matt Ward

  • Branch Coverage with OpenCover

    SharpDevelop has had support for code coverage for a while now thanks to PartCover and more recently thanks to OpenCover. In SharpDevelop 5 an external contributor added support for showing branch coverage in the text editor. Branch coverage will show you whether all paths or branches through the code have been executed by your tests. So let us take a look at this in SharpDevelop 5.

    Branch Coverage

    First let us start with an existing C# project that has some unit tests for a BankAccount class. The source code and associated project is available as a .zip file to download.

    Our BankAccount class is shown below.

    public class BankAccount
    {
        decimal balance;
    
        public void Deposit(decimal amount)
        {
            balance += amount;
        }
    
        public decimal Balance {
            get { return balance; }
        }
    
        public void Withdraw(decimal amount)
        {
            // TODO.
        }
    }
    

    Now we will write a unit test for the Withdraw method.

    [Test]
    public void Withdraw_Deposit20PoundsThenWithdraw5Pounds_BalanceIs15Pounds()
    {
        var account = new BankAccount();
        account.Deposit(20m);
    
        account.Withdraw(5m);
    
        Assert.AreEqual(15m, account.Balance);
    }
    

    To get this test working we update the Withdraw method with the code shown below:

    public void Withdraw(decimal amount)
    {
        if (balance >= amount) {
            balance -= amount;
        }
    }
    

    Notice that there is an if statement at the start of the Withdraw method to prevent the account from being overdrawn. Now in SharpDevelop 4, if you ran the unit tests with code coverage, the Withdraw method would show 100% statement coverage. However the unit tests currently do not execute the path through the code where the amount being withdrawn is greater than the current balance. In SharpDevelop 5 the new branch coverage feature allows you to see this code is not fully covered. In SharpDevelop 5, right click the unit tests and select Run with code coverage.

    Unit Tests window - Run with Code Coverage menu item

    Now if you open the BankAccount class into the text editor you should see the following:

    Branch not covered in text editor

    The code highlighted in yellow shows you that all possible branches through this code have not been executed. Once another unit test is added that tries to to withdraw an amount larger than the current balance then all the code in the BankAccount will be highlighted in green showing that all the branches are covered.

    Finally the colour used to highlight the code in the partially covered branch can be configured by selecting Options from the Tools menu to open the Options dialog.

    Tools Options - Code Coverage - Partially covered text color configuration

    That is the end to this brief introduction to branch coverage in SharpDevelop 5.

  • Entity Framework 6 Code First Migrations

    SharpDevelop 4.4 now has support for Code First Migrations using Entity Framework 6.0.2.

    On NuGet there is an EntityFramework.SharpDevelop NuGet package that includes the original Entity Framework assemblies along with custom versions of the PowerShell cmdlets, listed below, that work with SharpDevelop

    1. Enable-Migrations: Adds support for migrations to your project.
    2. Add-Migration: Generates code for a database migration based on changes to your database model.
    3. Update-Database: Applies migrations to the database.
    4. Get-Migrations: Shows the migrations that have been applied to the database.

    Now let us take a look at how to use the EntityFramework.SharpDevelop NuGet package.

    Installation

    Before you begin you should have SQL Express installed. You will also need SharpDevelop version 4.4.0.9722 or above.

    We will look at using Entity Framework in a simple C# console application. This application will add a blog post to a SQL Express database and then read all the existing blog posts in the database. We used this example before in a previous blog post when using Entity Framework with SharpDevelop so we will not go into as much detail as before, instead concentrating on some of the new features that Entity Framework brings, such as logging and support for stored procedures.

    In SharpDevelop first create a new C# Console Application. Add the EntityFramework.SharpDevelop NuGet package to the project either by using the Manage Packages dialog or by using the Package Management Console window.

    Using Entity Framework

    Here is the code we will start with.

    using System;
    using System.Data.Entity;
    using System.Linq;
    
    namespace EFCodeFirst
    {
        public class Post
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public string Text { get; set; }
        }
    
        public class BloggingContext : DbContext
        {
            public DbSet<Post> Posts { get; set; }
        }
    
        class Program
        {
            public static void Main(string[] args)
            {
                Console.Write("Enter a post title: ");
                string title = Console.ReadLine();
    
                Console.Write("Enter the post text: ");
                string text = Console.ReadLine();
    
                using (var db = new BloggingContext()) {
    
                    db.Database.Log = Console.Write;
    
                    var newPost = new Post {
                        Title = title,
                        Text = text
                    };
    
                    db.Posts.Add(newPost);
                    db.SaveChanges();
    
                    Console.WriteLine("All posts in the database:");
    
                    IQueryable<Post> query = db.Posts
                        .OrderBy(p => p.Title)
                        .Select(p => p);
    
                    foreach (Post post in query) {
                        Console.WriteLine("Post.Title: " + post.Title);
                    }
                }
    
                Console.WriteLine("Press a key to exit.");
                Console.ReadKey();
            }
        }
    }
    

    The above code uses the new logging feature of Entity Framework 6. The line after the database context is created configures Entity Framework to write information, such as the queries executed, to the console:

    db.Database.Log = Console.Write;
    

    Running the console application will cause Entity Framework to create a new database, add a new post to the database, and then read all the posts from the database. You will also see information logged by Entity Framework:

    INSERT [dbo].[Posts]([Title], [Text])
    VALUES (@0, @1)
    SELECT [Id]
    FROM [dbo].[Posts]
    WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()
    -- @0: 'first' (Type = String, Size = -1)
    -- @1: 'first post' (Type = String, Size = -1)
    -- Executing at 21/12/2013 12:09:06 +00:00
    -- Completed in 11 ms with result: SqlDataReader
    
    All posts in the database:
    SELECT
        [Extent1].[Id] AS [Id],
        [Extent1].[Title] AS [Title],
        [Extent1].[Text] AS [Text]
        FROM [dbo].[Posts] AS [Extent1]
        ORDER BY [Extent1].[Title] ASC
    -- Executing at 23/12/2013 12:09:06 +00:00
    -- Completed in 2 ms with result: SqlDataReader
    

    Database Migrations

    Now let us take a look at adding a new migration. Open the Package Management Console and run the following command to configure database migrations for the project.

        Enable-Migrations
    

    We will now use the new stored procedure support that was added to Entity Framework 6. Instead of inserting, updating and deleting posts in the database using SQL we will use stored procedures. To do this we modify the database context as shown below.

    public class BloggingContext : DbContext
    {
        public DbSet<Post> Posts { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder
                .Entity<Post>()
                .MapToStoredProcedures();
        }
    }
    

    Here we have overridden the OnModelCreating method and configured Entity Framework to use stored procedures for our Posts.

    Now generate a code first migration for the stored procedures by running the following command in the Package Management Console.

        Add-Migration StoredProcs
    

    This creates a new migration that includes a set of simple stored procedures for inserting, updating and deleting Posts in our database. Part of this generated code is shown below:

    public partial class StoredProcs : DbMigration
    {
        public override void Up()
        {
            CreateStoredProcedure(
                "dbo.Post_Insert",
                p => new
                    {
                        Title = p.String(),
                        Text = p.String(),
                    },
                body:
                    @"INSERT [dbo].[Posts]([Title], [Text])
                      VALUES (@Title, @Text)
    
                      DECLARE @Id int
                      SELECT @Id = [Id]
                      FROM [dbo].[Posts]
                      WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()
    
                      SELECT t0.[Id]
                      FROM [dbo].[Posts] AS t0
                      WHERE @@ROWCOUNT > 0 AND t0.[Id] = @Id"
            );
    

    Now you can add the new stored procedures to your database by running the following command in the Package Management Console window.

        Update-Database
    

    The stored procedures can be seen using SQL Management Studio.

    Stored procedures created by Entity Framework

    If you run the console application now you will see the stored procedures being used when a new post is created in the console output.

    [dbo].[Post_Insert]
    -- Title: 'second' (Type = String, Size = 1073741823)
    -- Text: 'second post' (Type = String, Size = 1073741823)
    -- Executing at 23/12/2013 12:21:47 +00:00
    -- Completed in 5 ms with result: SqlDataReader
    

    That concludes our look at using Entity Framework 6 code first migrations with SharpDevelop.

    Further Information on Entity Framework

    1. Entity Framework on the MSDN.
    2. Entity Framework 6: Database Access Anywhere, Easily - Rowan Miller's Tech Ed 2013 Talk.

    The code for the modified NuGet packages is available on GitHub.

    Posted Dec 23 2013, 01:28 PM by MattWard with no comments
    Filed under: ,
  • Using Fody with SharpDevelop

    Fody is a NuGet addin, written by Simon Cropp, that will weave IL instructions into your assembly after it has been compiled. IL weaving is the creation and manipulation of IL without the use of a compiler. To do the IL weaving Fody uses a MSBuild task and Mono.Cecil.

    Fody is a general purpose IL weaver and is extended using Fody addins, which are also NuGet packages. One example is the PropertyChanged addin which will inject INotifyPropertyChanged code for your class properties into your assembly without you having to write the code. Another example is the NullGuard addin which will add null checks to your code.

    For the full list of Fody addins see the list on the Fody GitHub page:

    Now let us take a look at using the NullGuard addin with SharpDevelop.

    You will need to use the latest version of SharpDevelop 4.4. Any version from 4.4.0.9711 or above should work. Previous versions of SharpDevelop would not correctly configure the path to the Fody assembly which would cause the project to fail to compile.

    Installing Fody

    Fody is a NuGet package so use either the Manage Packages dialog or the Package Management console to install the Fody nuget package into your project.

    Fody NuGet Package in Manage Packages dialog

    Installing the Fody NuGet package will add a FodyWeavers.xml and a Fody.targets file to your project. The FodyWeavers.xml file configures the Fody addins that will be used. The project itself will be updated so it imports the Fody.targets file which is a custom MSBuild targets file. Also a FodyPath property will be added to your project so the Fody.dll assembly can be located and used by the Fody MSBuild targets file.

    Installing NullGuard addin

    Search for the NullGuard.Fody in the Manage Packages dialog or use the Package Management Console and install it.

    Fody NuGet Package in Manage Packages dialog

    Installing the NullGuard.Fody NuGet package will update the FodyWeavers.xml file so the NullGuard addin will be used by Fody.

    <?xml version="1.0" encoding="utf-8"?>
    <Weavers>
      <NullGuard />
    </Weavers>
    

    NullGuard Generated Code

    Now let us take a look at what code is generated by Fody and the NullGuard addin when the following class is included in the project:

    using System;

    namespace NullGuardTest
    {
        public class MyClass
        {
            public void MyMethod(string parameter)
            {
            }
        }
    }
    

    Compiling the project will now weave in null checks into your assembly. If you open your assembly into ILSpy you can view the generated code, which is shown below:

    using System;
    using System.Diagnostics;
    namespace NullGuardTest
    {
        public class MyClass
        {
            public void MyMethod(string parameter)
            {
                Debug.Assert(parameter != null, "[NullGuard] parameter is null.");
                if (parameter == null)
                {
                    throw new ArgumentNullException("parameter", "[NullGuard] parameter is null.");
                }
            }
        }
    }
    

    The NullGuard addin has added null checks for the parameter being passed into the method without you having to write the code yourself.

    The generated assembly IL can be further controlled by adding attributes to your class. Further information on the supported attributes that are available can be found on the NullGuard GitHub page.

    That is the end of the quick introduction to using Fody with SharpDevelop.

    Posted Dec 01 2013, 03:53 PM by MattWard with no comments
    Filed under:
  • NuGet 2.7 Support

    SharpDevelop 4.3.3 has been updated to use NuGet 2.7 and now has support for restoring NuGet packages.

    Restoring NuGet Packages

    To restore NuGet packages for your solution, from the Projects window right click the solution, project or References, and select Restore NuGet Packages.

    Restore NuGet Packages menu item

    This will run NuGet.exe and uses the new restore argument that has been added to NuGet 2.7. The full command line will be similar to the following:

    NuGet.exe restore YourSolution.sln
    

    The output from this command will be shown in the Output window. In the screenshot below you can see jQuery, Json.NET, Modernizr and NUnit being restored.

    NuGet Restore Output Window

    Posted Aug 26 2013, 02:06 PM by MattWard with no comments
    Filed under:
  • NuGet 2.6 Support

    SharpDevelop 4.3 has been updated to use NuGet 2.6 and also includes some new features that were missing when compared with using NuGet in Visual Studio.

    New Features

    • Support for prerelease packages.
    • Support for packages using XML Document Transformations (XDTs).
    • File conflict dialog is displayed when installing a package that is trying to add files that already exist in the project.
    • Support for packages that include MSBuild targets and properties files.
    • Support for accessing authenticated NuGet package feeds.
    • Update All button added to Manage Packages dialog so all packages can be updated in a project or solution in one step.

    Now let us take a look at some of these new features in more detail.

    Prerelease packages

    The Manage Packages dialog now has an Include Prerelease check box which when checked will allow you to search for and install prerelease packages. In the screenshot below the IronPython prerelease package has been selected.

    Manage Packages Dialog

    XML Document Transformations

    NuGet 2.6 added support for XDTs. This allows complex transformations of a project's app.config or web.config when a NuGet package is installed or uninstalled. In the NuGet package you can add XDTs by using naming your file after one or more of the following:

    • web.config.install.xdt
    • web.config.uninstall.xdt
    • app.config.uninstall.xdt
    • app.config.uninstall.xdt

    These files should target the content folder so in your .nuspec file you should have something similar to:

    <files>
        <file src="MyTransforms\*.xdt" target="content" />
    </files>
    

    Further information on XDTs is available on the MSDN.

    Authenticated NuGet Feeds

    You can now browse and install packages from authenticated NuGet feeds that use basic authentication and Windows authentication. Currently there is no login dialog but you can add your username and password to your NuGet.config file.

    To add your username and password to your NuGet.config file you will need to use NuGet.exe and run the following command, replacing the feed name, username and password with the correct values.

    NuGet.exe sources update -name FeedName -username user -password pass
    

    After adding your username and password to NuGet.config you will need to restart SharpDevelop since the information held in the NuGet.config file is cached.

    File Conflict Dialog

    NuGet 2.6 will now check for existing files in your project that match those being installed by a package. If there is a match then a dialog will be displayed so you can decide whether to overwrite the files.

    Manage Packages Dialog

    Posted Aug 10 2013, 10:23 AM by MattWard with no comments
    Filed under:
  • TypeScript Support in SharpDevelop

    SharpDevelop 4.3.1 now has support for TypeScript with an early beta release of a new Addin.

    The Addin glues together the TypeScript language services, which provide all the features needed for code completion and refactoring, and SharpDevelop using Javascript.NET as the bridge between them. Javascript.NET allows SharpDevelop to host Google's V8 JavaScript engine and have JavaScript code interact with .NET objects.

    Features

    • TypeScript compilation on save or build.
    • Code folding.
    • Code completion
    • Find references
    • Rename refactoring
    • Go to definition
    • Quick class browser support.
    • TypeScript syntax highlighting

    The addin supports:

    • SharpDevelop 4.3.1
    • TypeScript 0.8.3.1

    Let us take a quick look at some of these features.

    Code Completion

    Code completion works when you press the dot character.

    TypeScript dot code completion

    Code completion also works when you type the first bracket of a function.

    TypeScript function code completion

    Find References, Go to Definition and Rename

    These menu options can be found by right clicking on a class or a class member.

    TypeScript right click menu options

    Go To TypeScript Definition will show the corresponding type definition. Find TypeScript References will show the reference locations in the Output window. Rename will open a dialog box where you can type in the new name and click OK to have it updated everywhere it is referenced.

    Getting the Addin

    The addin's source code is available on GitHub. A zip file is available to download containing the pre-compiled addin. Simply unzip the files and install into SharpDevelop using the Addin Manager. The Addin Manager is available by selecting Addin Manager from the Tools menu. Install the addin by clicking the Install Addin button and then restart SharpDevelop.

    Configuring TypeScript Compiler Options

    The compiler options are available from the Options dialog (Tools - Options) under the Text Editor category. Here you can change when the compiler is run and what options are passed to the compiler when generating JavaScript code.

    Configuring TypeScript Compiler Options

    Limitations and Known Issues

    • Limitation with multiple projects using TypeScript files in the same solution. All files are included in the same scope.
    • Performance problems - currently doing work on the UI thread and also re-parsing all TypeScript files each time when a code completion action is triggered.
    • Different behaviour to Visual Studio with classes show in the code completion window. Visual Studio only shows code completion for TypeScript files you have explicitly referenced in a comment. SharpDevelop shows everything in the current project.
    • Unable to easily replace the existing SharpDevelop menu options such as Find References so the standard shortcuts will not work.
    • No support for hovering over a type with the mouse and seeing a tooltip with information about the type.
  • NuGet Addin for MonoDevelop

    It has been a while since NuGet support was added to SharpDevelop so, after David Fowler announced that he had got NuGet building under Mono, I had a look at porting the SharpDevelop addin over to MonoDevelop and created a NuGet addin for MonoDevelop.

    The addin provides a Manage Packages dialog that you can use to add, remove and update NuGet packages in a similar way to Visual Studio or SharpDevelop. Here is a screenshot of the Manage Packages dialog open in MonoDevelop running on OpenSuse 12.2

    Manage Packages Dialog with package operation messages

    The addin has been tested with the following:

    • MonoDevelop 3.0.5
    • Mono 2.10.9
    • OpenSuse 12.2
    • Windows 7

    The addin uses a slightly customised version of NuGet.Core based on the original NuGet's source code available from the mono-build branch. The source code for this customised NuGet.Core is available on GitHub.

    Getting the Addin

    The addin's source code is available on GitHub.

    The addin is also provided as a pre-compiled binary available to download from a custom MonoDevelop repository:

    http://mrward.github.com/monodevelop-nuget-addin-repository/3.0.5/main.mrep

    You can add this repository to MonoDevelop via the Add-in Manager.

    Please note that the addin is a beta release and more work is still to be done.

    Manage Packages Dialog

    The Manage Packages Dialog can be opened from the Projects menu by selecting Manage NuGet Packages.

    It can also be opened by selecting the Solution window, right clicking either the solution, the project or the project's references and selecting Manage NuGet Packages.

    As a NuGet package is installed or uninstalled you can see the package operations that executed by expanding the Messages section near the bottom of the dialog.

    Manage Packages Dialog with package operation messages

    Configuring Package Sources

    NuGet Package Sources can be configured in MonoDevelop's options.

    Configuring NuGet Package Sources in MonoDevelop's Options

    In Linux you can open the options dialog by selecting Preferences from the Edit menu. In Windows you can select Options from the Tools menu. In the Options dialog scroll down the categories on the left hand side until you find NuGet and then select Package Sources. Here you can add and remove NuGet package sources.

    PowerShell

    Any PowerShell scripts in a NuGet package will be ignored by the addin since Mono does not currently have support for them.

    There have been some attempts to implement PowerShell on Mono starting with Igor Moochnick who created Pash in 2008. Work on this was picked up launchpad.net by Jonathan Ben-Joseph but that work stopped. The latest effort on bringing PowerShell to Mono is Jay Bazuzi with recent work done on the Pash source code available on GitHub.

    There was also some discussion in the NuGet forums on allowing some way of being able to write a .NET version of the PowerShell scripts (install.ps1, uninstall.ps1 and init.ps1).

  • Code First Migrations with Entity Framework

    SharpDevelop 4.3 now has support for Code First Migrations using Entity Framework 5.0.

    Microsoft added Code First Migrations to Entity Framework in version 4.3 in February 2012. Code first migrations allows database changes to be implemented with code. The official Entity Framework NuGet package includes three PowerShell cmdlets that extend the NuGet Package Manager Console allowing you to quickly create and use these code first migrations:

    1. Enable-Migrations: Adds support for migrations to your project.
    2. Add-Migration: Generates code for a database migration based on changes to your database model.
    3. Update-Database: Applies migrations to the database.

    The PowerShell cmdlets in the official EntityFramework NuGet packages are Visual Studio specific, but there is now a SharpDevelop specific NuGet package (EntityFramework.SharpDevelop) that allows you to use these PowerShell cmdlets in SharpDevelop. This has been made possible by Entity Framework being open sourced.

    The EntityFramework.SharpDevelop NuGet package includes the original EntityFramework.dll along with custom versions of the assemblies containing the PowerShell cmdlets - EntityFramework.PowerShell.dll and EntityFramework.PowerShell.Utility.dll.

    Now let us take a look at how to use the EntityFramework.SharpDevelop NuGet package.

    Installation

    Before you begin you should have SQL Express installed. You will also need SharpDevelop version 4.3.0.9134 or above.

    We will look at using Entity Framework with a simple C# console application. This application will add a blog post to a SQL Express database and then read all the existing blog posts in the database.

    In SharpDevelop first create a new C# Console Application. Now open the NuGet Manage Packages dialog by right clicking the project and selecting Manage Packages. Search for the EntityFramework.SharpDevelop package in the main NuGet feed and click the Add button to add it to your project. A reference to the EntityFramework assembly will be added to your project and your app.config will be modified.

    Now we are ready to use Entity Framework to update and read from our database.

    Using Entity Framework

    First add a new Post class to your project.

    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Text { get; set; }
    }
    

    Now add a new database context class.

    public class BloggingContext : DbContext
    {
        public DbSet<Post> Posts { get; set; }
    }
    

    You will also need to add a using statement to the BloggingContext class so the EntityFramework's DbContext class can be found.

        using System.Data.Entity;
    

    Now open your Program.cs and add a using statement for System.Linq.

        using System.Linq;
    

    Then in Program.cs update the Main method as shown below:

    class Program
    {
        public static void Main(string[] args)
        {
            Console.Write("Enter a post title: ");
            string title = Console.ReadLine();
    
            Console.Write("Enter the post text: ");
            string text = Console.ReadLine();
    
            using (var db = new BloggingContext()) {
    
                var newPost = new Post {
                    Title = title,
                    Text = text
                };
    
                db.Posts.Add(newPost);
                db.SaveChanges();
    
                Console.WriteLine("All posts in the database:");
    
                IQueryable<Post> query = db.Posts
                    .OrderBy(p => p.Title)
                    .Select(p => p);
    
                foreach (Post post in query) {
                    Console.WriteLine("Post.Title: " + post.Title);
                }
            }
    
            Console.WriteLine("Press a key to exit.");
            Console.ReadKey();
        }
    }
    

    This code reads the blog post title and text entered on the command line, adds a new post to the database and then reads all the posts in the database. Compile and run this application and you should see output similar to the following.

        Enter a post title: First Post
        Enter the post text: Some text here...
        All posts in the database:
        Post.Title: First Post
        Press a key to exit.
    

    After running this application Entity Framework will have created a new database with the same name as the db context class you created. In the screenshot below you can see the database open in SQL Server Express Management Studio.

    Code first database created by Entity Framework

    You can see that Entity Framework has created a Posts table as well as a __MigrationHistory table. Now we will take a look at enabling database migrations.

    Enabling Migrations

    Open the Package Management Console and enter the command.

        Enable-Migrations
    

    This adds a Migrations folder to your project along with a Configuration.cs file and an initial migration.

    Project items after migrations are enabled

    The Configuration.cs file can be edited to add seed data and alter other settings used when migrating the database. The initial migration files contain code to generate the Posts table in the database.

    Now let us take a look at adding a new migration.

    Adding a Migration

    We want to add a Published Date to our Post class. Add the new PublishedDate property to the Post class as shown below.

    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Text { get; set; }
        public DateTime PublishedDate { get; set; }
    }
    

    You can generate a code first migration by entering the following command into the Package Management Console.

        Add-Migration AddPublishedDate
    

    This creates a new migration and gives it the name AddPublishedDate. A new file will be added to your migrations folder which contains the code to update the Posts table with the new PublishedDate column.

    namespace EFCodeFirst.Migrations
    {
        using System;
        using System.Data.Entity.Migrations;
    
        public partial class AddPublishedDate : DbMigration
        {
            public override void Up()
            {
                AddColumn("dbo.Posts", "PublishedDate", c => c.DateTime(nullable: false));
            }
    
            public override void Down()
            {
                DropColumn("dbo.Posts", "PublishedDate");
            }
        }
    }
    

    Now you can update your database.

    Updating the Database

    To update the database we run the following command in the Package Management Console window.

        Update-Database
    

    The new PublishedDate column will then be added to the Posts database table as shown in the screenshot below

    Posts table after code first migration applied

    That concludes the introduction to using Code First Migrations with SharpDevelop. More information on EntityFramework can be found on the Microsoft MSDN site.

    Changes Made to Original Entity Framework NuGet Packages

    1. Renamed NuGet package to EntityFramework.SharpDevelop and included files and assemblies from official EF NuGet package.
    2. Recompiled the EntityFramework.PowerShell and EntityFramework.PowerShell.Utility projects against SharpDevelop's EnvDTE implementation.
    3. Small modifications to the project to compile against .NET 4.0 and the EntityFramework.dll. Microsoft's released source code on Codeplex is for EntityFramework 6 and not for EF 5.
    4. EntityFramework.PowerShell and EntityFramework.PowerShell.Utility assemblies are no longer signed.
    5. Added workaround to fix AppDomain.CreateInstance failing to find constructors taking a EnvDTE.Project parameter.
    6. Add SharpDevelop.EnvDTE.dll to NuGet packages.

    All the code for the modified NuGet packages are available on GitHub.

    Posted Nov 11 2012, 05:00 PM by MattWard with 1 comment(s)
    Filed under:
  • MVC Scaffolding

    SharpDevelop 4.3 now has support for MVC Scaffolding.

    MVC Scaffolding, maintained by Steve Sanderson, provides a way to quickly generate code for views and controllers in your ASP.NET MVC application. It has support for scaffolding the following:

    • Views and controllers.
    • Entity Framework DbContexts.
    • Repositories.
    • Controller actions.
    • Unit tests.

    It makes use of T4 templates, which can be customised, and can be extended with custom scaffolders to support more than just the features listed above.

    The original MVC Scaffolding NuGet packages made heavy use of the Visual Studio API and have been modified to work with SharpDevelop. Full details of the changes made to the original NuGet packages can be found at the end of this post.

    Steve Sanderson has a great series of posts on MVC Scaffolding that covers more than this post will. Now let us take a look at how to use MVC Scaffolding with SharpDevelop.

    Installation

    MVC Scaffolding for SharpDevelop is available as a NuGet package. The NuGet package you should download is MvcScaffolding.SharpDevelop. Install the MvcScaffolding.SharpDevelop NuGet package either from the NuGet package management console or by using the Manage Packages dialog.

    Note that the NuGet package MvcScaffolding.SharpDevelop.1.0.9 requires SharpDevelop 4.3.0.9134 or above. If you have an older version installed then you should uninstall the MvcScaffolding.SharpDevelop package, before installing the latest version of SharpDevelop, and then reinstall the MvcScaffolding.SharpDevelop package. A breaking change made to SharpDevelop 4.3 to support the EntityFramework package will cause the older MvcScaffolding.SharpDevelop NuGet package to fail to uninstall cleanly in the newer version of SharpDevelop.

    Scaffolding a Controller and Views

    As an example we will create a simple blogging site. Create a Razor MVC application called BloggingSite. Then create the following class in a Models folder.

    using System;
    
    namespace BloggingSite.Models
    {
        public class Post
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public string Text { get; set; }
            public DateTime PublishedDate { get; set; }
        }
    }
    

    Now we can scaffold a controller and a set of Create, Read, Update and Delete (CRUD) views. In the Package Management console run the following command.

    Scaffold Controller Post
    

    This will generate a set of views, a controller and an Entity Framework database context.

    Scaffold Controller Post output in Package Management Console

    To run the Blogging Site application you will need to have IIS Express and SQL Server Express installed. Your project will also need to be configured to use IIS Express. Select Project Options from the Project menu and then select the Web tab. Choose IIS Express and then click the Create application/virtual directory button.

    Then run your application and visit the /Posts page in your browser.

    Scaffolded Posts page with empty database

    You can then create a new post by clicking the Create New link.

    Creating new blog post page

    After creating a new post then the post will be displayed on the original /Posts page.

    Scaffolded Posts page with one post

    Also scaffolded is the details page which you can view by clicking the Details link.

    Scaffolded Details page

    Finally there is the Delete page where you can remove a post.

    Scaffolded delete post page

    Scaffolding CRUD views is just one part of MvcScaffolding so let us take a look at some of other scaffolding that is supported. Steve Sanderson goes into more detail on what you can do with each of the MVC Scaffolders than will be covered here.

    Scaffolding a Repository

    The PostsController generated uses the BloggingSiteContext class which is derived from Entity Framework's DbContext.

    public class PostsController : Controller
    {
        private BloggingSiteContext context = new BloggingSiteContext();
    
        //
        // GET: /Posts/
    
        public ViewResult Index()
        {
            return View(context.Posts.ToList());
        }
    

    To allow unit testing of the controller we can instead using a repository interface which can be mocked. To do that we run the following command.

    Scaffold Controller Post -Repository -Force
    

    By default MVC Scaffolding will not overwrite views and controllers previously created in your project. In order to overwrite the views and controllers created previously we use the -Force option.

    The PostsController now looks like this.

    public class PostsController : Controller
    {
        private readonly IPostRepository postRepository;
    
        // If you are using Dependency Injection, you can delete the following constructor
        public PostsController() : this(new PostRepository())
        {
        }
    
        public PostsController(IPostRepository postRepository)
        {
            this.postRepository = postRepository;
        }
    
        //
        // GET: /Posts/
    
        public ViewResult Index()
        {
            return View(postRepository.All);
        }
    

    Scaffolding an Empty View

    You can scaffold an empty view by using the View scaffolder and specifying the name of the controller, without the Controller part, followed by the name of the view.

    Scaffold View Posts MyEmptyView
    

    In a Razor MVC application this will generate the file Views\Posts\MyEmptyView.cshtml in your project.

    Scaffolding Database Context

    You can scaffold extra properties for your database context by using the DbContext scaffolder and specifying the model class and the name of the database context class. Create a new Blog class, as shown below.

    using System;

    using System;
    
    namespace BloggingSite.Models
    {
        public class Blog
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
    }
    

    Now run the command below to update your database context and a new Blogs property will be added to your BloggingSiteContext class.

    Scaffold DbContext Blog BloggingSiteContext
    

    The new BloggingSiteContext class is shown below.

    public class BloggingSiteContext : DbContext
    {
        // You can add custom code to this file. Changes will not be overwritten.
        // 
        // If you want Entity Framework to drop and regenerate your database
        // automatically whenever you change your model schema, add the following
        // code to the Application_Start method in your Global.asax file.
        // Note: this will destroy and re-create your database with every model change.
        // 
        // System.Data.Entity.Database.SetInitializer(
            new System.Data.Entity.DropCreateDatabaseIfModelChanges
                <BloggingSite.Models.BloggingSiteContext>());
    
    
        public DbSet<BloggingSite.Models.Post> Posts { get; set; }
    
        public DbSet<BloggingSite.Models.Blog> Blogs { get; set; }
    }
    

    Scaffolding Controller Actions

    You can scaffold new controller actions by using the Action scaffolder and specifying the name of the controller, without the Controller part, and the name of the new action method.

    Scaffold Action Posts MyAction
    

    This will add a new MyAction method at the end of your PostsController class.

    public ViewResult MyAction()
    {
        return View();
    }
    

    It will also create an associated view.

    You can also scaffold actions that can have data posted to them. If you run the following command a new action will be created that takes a posted Blog object.

    Scaffold Action Posts MyPostAction -ViewModel Blog -Post
    

    The PostsController will now have a new MyPostAction method at the end.

    [HttpPost, ActionName("MyPostAction")]
    public ActionResult MyPostActionPost(Blog blog)
    {
        if (ModelState.IsValid) {
            return RedirectToAction("Index");
        } else {
            return View(blog);
        }
    }
    

    That is the end of our introduction to using MVC Scaffolding with SharpDevelop.

    Modifications Made to Original MVC Scaffolding

    1. Mvc Scaffolding projects now compiled against SharpDevelop's Package Management assembly which implements the Visual Studio API.
    2. T4 template generation now uses MonoDevelop's T4 Templating Engine.
    3. T4Scaffolding.SharpDevelop.1.0.8 NuGet package depends on EntityFramework.SharpDevelop NuGet package instead of the original EntityFramework NuGet package This allows an upgrade to the NuGet package EntityFramework.SharpDevelop.5.0.0 which supports migrations in SharpDevelop.

    Source code for the modified MVC Scaffolding can be found on CodePlex.

    [Update 2012-11-10] Added information on MvcScaffolding.SharpDevelop 1.0.9 NuGet package requiring newer version of SharpDevelop. Updated "Scaffolding Database Context" section with example Blog class. Updated "Modifications Made to Original MVC Scaffolding" section with change made to T4Scaffolding.SharpDevelop NuGet package.

  • Using T4MVC with SharpDevelop

    SharpDevelop 4.3 now has support for T4MVC.

    T4MVC is a set of T4 templates, created by David Ebbo, that will generate strongly typed helpers for an ASP.NET MVC application. It will allow you to remove strings from your MVC application making your application easier to maintain.

    So let us take a look at how to use T4MVC with SharpDevelop. First you should open or create a new ASP.NET MVC application in SharpDevelop.

    Installing T4MVC

    T4MVC is available as a NuGet package. The NuGet package you should download is T4MVC.SharpDevelop. This contains a modified version of the original T4MVC template that can be used with SharpDevelop. Further details on all the modifications made to the T4MVC template can be found at the end of this post. Install the T4MVC.SharpDevelop NuGet package either from the NuGet package management console or by using the Manage Packages dialog.

    Note that T4MVC 2.13.0 requires SharpDevelop 4.3.0.9132 or above.

    After installation two new T4 template files will be added to your project.

    1. T4MVC.tt - main template that generates the strongly typed helpers.
    2. T4MVC.tt.settings.t4 - holds configuration settings used by main T4MVC.tt template.

    Generating T4MVC's Strongly Typed Helpers

    To run the T4MVC template manually, select it in the Projects window, right click and select Execute Custom Tool. This will generate a set of files as dependencies of the T4MVC.tt file.

    T4MVC Generated Files in Projects window

    It will also make some modifications to your controller classes. The T4MVC template will change your controller classes so they are partial. It will also change your controller methods so they are virtual. What has been changed will be recorded as warnings in the Errors window.

    T4MVC modified code warnings in Errors window

    When you make modifications to your application you do not want to have to keep running the T4MVC template manually each time to regenerate the strongly typed helpers. Instead you can configure your project to re-generate the strongly typed helpers on each build.

    Generating T4MVC's Strongly Typed Helpers on each Build

    To do this you should open the options for the project. From the Projects menu and select Project Options. Open the Custom Tool tab. In this tab you can choose to run custom tools on each build. In the screenshot below the project is configured to run T4MVC on each build.

    Project options configured to run T4MVC on every build

    If you want to run other custom tools you can add filenames for items in your project either as a comma separated list or with each file on a separate line. Currently there is no support for wildcards when specifying filenames.

    Now that we have generated the strongly typed helpers let us take a look at how to use a selection of them.

    Using T4MVC's Strongly Typed Helpers

    View Names

    In your _ViewStart.cshtml you may have a reference to a Razor layout page.

    @{
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    

    You can replace this string with a strongly typed helper.

    @{
        Layout = MVC.Shared.Views._Layout;
    }
    

    Action Links

    In your views you may be passing action names and controller names as strings HtmlHelper.ActionLink(string linkText, string actionName, string controllerName).

        <li>@Html.ActionLink("Home", "Index", "Home")</li>
        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
    

    Instead you can use code that looks like you are calling the controller method.

        <li>@Html.ActionLink("Home", MVC.Home.Index())</li>
        <li>@Html.ActionLink("Contact", MVC.Home.Contact())</li>
    

    CSS Links

    You may be using strings for links, such as for CSS files, in your views.

    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css">
    

    These can be changed to use the Links.Content helper class.

    <link href="@Links.Content.Site_css" rel="stylesheet" type="text/css">
    

    That is a very quick introduction to T4MVC and covers only a few of the helpers it provides. Further information on T4MVC can be found on the T4MVC Codeplex site.

    Changes Made to Original T4MVC Template

    1. Visual Studio assembly references have been removed and replaced with a SharpDevelop assembly reference.
    2. Visual Studio namespace imports have been removed and replaced with namespace imports for SharpDevelop.
    3. Removed use of BeginInvoke/EndInvoke which was causing SharpDevelop to hang.

    The SharpDevelop specific T4MVC template is maintained in a repository on github.

    [Update 2012-10-11] Added information on T4MVC 2.13.0 requiring a newer version of SharpDevelop 4.3. Updated "Changes made to original T4MVC template" section after SharpDevelop EnvDTE API was modified to follow Visual Studio's API when using parameterised properties such as ProjectItem.FileNames() and CodeType.IsDerivedFrom()

    Posted Sep 15 2012, 01:40 PM by MattWard with no comments
    Filed under:
  • NUnit 2.6.1 Support

    SharpDevelop 4.3 has been updated to use NUnit 2.6.1 which was recently released. The full details on what has changed in NUnit 2.6.1 can be found in the NUnit release notes. One change in this release caused some of SharpDevelop's own unit tests to break so this change is highlighted in the following section.

    Running unit tests with an STA thread

    NUnit 2.6 no longer reads settings from your test configuration file (app.config). This means that you can no longer make NUnit use the STA thread by setting the default apartment state in your app.config file. So the following app.config file will not work:

      <configuration> 
        <configSections>
          <sectionGroup name="NUnit">
            <section name="TestRunner"  type="System.Configuration.NameValueSectionHandler" />
            </sectionGroup>
          </configSections>
          <NUnit>
            <TestRunner>
               <!-- The ApartmentState value here is ignored. -->
               <add key="ApartmentState" value="STA" />
            </TestRunner>
          </NUnit>
      </configuration>
    

    Instead you should use the RequiresSTA attribute.

    The RequiresSTA attribute can be used at the assembly, class or method level. To make NUnit to run all your unit tests with an STA thread you can add the following code to your AssemblyInfo.cs file in the project containing your unit tests.

    using NUnit.Framework;
    
    [assembly: RequiresSTA]
    
    Posted Aug 12 2012, 03:05 PM by MattWard with no comments
    Filed under:
  • Code Coverage with OpenCover

    SharpDevelop 4.3 now has integrated support for OpenCover thanks to Lex Li.

    OpenCover is an open source code coverage tool created by Shaun Wilde. It can be used to measure how much of your code is covered by your unit tests. OpenCover was created to fix the following problems in PartCover, another open source code coverage tool.

    • 64 bit support
    • Memory usage
    • Returning no coverage results

    For a more detailed look into why OpenCover was created you should read Shaun Wilde's OpenCover First Beta Release post.

    Back in 2006 SharpDevelop added support for NCover, then it switched to using PartCover a year later when NCover was turned into a commercial product. Now it supports and ships with OpenCover so let us take a tour of using OpenCover with SharpDevelop.

    OpenCover Feature Tour

    First you should install SharpDevelop 4.3. Version 4.3.0.8911 or above will have OpenCover support. Then you will need to use a project with unit tests or alternatively you can download a zip file which contains the set of projects created whilst writing this feature tour. Open your solution with SharpDevelop 4.3 and let us get started.

    Running Unit Tests with Code Coverage

    To run the unit tests with code coverage open the Unit Tests window by selecting Tools - Unit Tests from the View menu. Right click the project or tests that you want to check for code coverage and select Run with code coverage.

    Unit tests window Run with code coverage menu option

    At the top of the Unit Tests window there is the run with code coverage toolbar button which can be also used to run code coverage for all the tests.

    Another way to run the unit tests with code coverage is to right click in the text editor and select the Run with code coverage menu option.

    Text editor Run with code coverage menu option

    The unit tests will then be run and OpenCover will profile your code. The output from OpenCover will be displayed in the Output window. Once OpenCover is finished the code coverage results will be displayed in the Code Coverage window.

    Code Coverage Results

    Code coverage results window

    The code coverage window will show you the percentage of code covered for each class, method and property. On the right hand side you can see the visit count information or if you select the Show Source Code option you can see the corresponding source code with covered code highlighted in green and uncovered code highlighted in red.

    Code coverage results window show source code option

    Code coverage results window with source code

    The Code Coverage window also allows you to enable or disable code coverage highlighting in the text editor. The top left button in the Code Coverage window is used to enable or disable code coverage highlighting in the text editor.

    Code coverage window - toggle code coverage highlighting

    In the screenshot below the text editor has covered code in highlighted in green and uncovered code in highlighted in red.

    Code coverage highlighting in text editor

    Filtering Code Coverage Results

    By default OpenCover will show you code coverage for all your code including your tests. Typically you are not interested in code coverage for your unit tests. To exclude classes you can use a filter. The filters you can use are described on the OpenCover wiki. To specify a filter in your unit tests project select Project Options from the Project menu. Then open the Code Coverage tab. Here you can specify an include or exclude filter. In the screenshot below all types in the OpenCoverageFeatureTour.Tests assembly will be excluded.

    Filtering code coverage results

    64 bit or 32 bit

    On Windows x64 if your test project is set to target a 32 bit processor then the 32 bit version of NUnit will be used to run your unit tests. If it is set to Any CPU or a 64 bit processor then NUnit will run as a 64 bit process as OpenCover profiles your code.

    Code Coverage Options

    The colours used to highlight code coverage in the text editor and Code Coverage window can be configured in the Options dialog. From the Tools menu select Options. Then expand the Tools category and select Code Coverage.

    Code coverage tools options dialog

    That ends the tour of using OpenCover with SharpDevelop.

  • Using MSTest with SharpDevelop

    SharpDevelop 4.2 now has a new sample addin that adds integrated support for running tests with MSTest.

    Features

    Given the following code:

    In the Unit Tests window the MS Tests will be displayed. The unit tests can be run by right clicking and selecting Run tests. The Unit Tests window will update to show the tests that passed and failed.

    The output from the MS test runner (mstest.exe) will be displayed in the Output window.

    Any test failures are displayed in the Errors window.

    There is a default path defined for mstest.exe which points to the Visual Studio 2010 folder but you can alter this path from the Tools Options dialog under Tools - MS Test.

    Note that running tests with the debugger or with code coverage does not work.

    Full details on how the addin works can be found in the wiki.

    Using the MSTest addin

    To use the MSTest addin either follow the instructions in the wiki to build it from source or download the pre-built addin and register it with SharpDevelop using the Addin Manager by selecting AddIn Manager from the Tools menu.

    Posted May 06 2012, 06:32 PM by MattWard with no comments
    Filed under:
  • Adding a Service Reference

    SharpDevelop 4.2 now includes support for adding references to WCF services.

    Prerequisites

    Microsoft Windows SDK should be installed.

    In order to generate the service reference SharpDevelop uses Microsoft's ServiceModel Metadata Utility Tool SvcUtil which is included as part of the Microsoft Windows SDK.

    Configuring SvcUtil Location

    SharpDevelop should automatically detect where SvcUtil is installed however the path to SvcUtil can be overridden if required from the Tools - Options dialog.

    SvcUtil path configuration in Tools Options

    Adding a Service Reference

    To add a service reference, open the Projects window, right click on the project or the references and select Add Service Reference.

    Add service reference context menu

    In the Add Service Reference dialog enter the url to the WCF service and click Go. The WCF service that is discovered should then be displayed.

    Add service reference dialog

    Clicking the Advanced button will allow you to configure further generation options.

    Advanced service reference options

    In the main Add Service Reference dialog enter a namespace for the service and then click the OK button to generate the service reference.

    Generated service reference in projects window.

    A service reference proxy will be added to the project and the project's app.config file will be updated with the WCF binding information.

    Now you can use the WCF service in your application.

    Posted Apr 22 2012, 11:28 AM by MattWard with no comments
    Filed under:
  • JavaScript Code Folding

    SharpDevelop 4.2 now includes support for JavaScript code folding and code regions.

    When you open a JavaScript (.js) file into the text editor any functions that are defined can be folded.

    JavaScript code folding in text editor

    The text editor also supports code regions.

        //#region Canvas Test 
         
        tests['canvas'] = function() { 
            var elem = document.createElement( 'canvas' ); 
            return !!(elem.getContext && elem.getContext('2d')); 
        }; 
         
        //#endregion

    These regions can be folded as shown below.

    JavaScript code regions folded in the text editor

More Posts Next page »
Powered by Community Server (Commercial Edition), by Telligent Systems
Don't contact us via this (fleischfalle@alphasierrapapa.com) email address.