SharpDevelop Community

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

Matt Ward

  • 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

  • ASP.NET MVC Support

    One of the new features in SharpDevelop 4.2 is better support for ASP.NET MVC 3 applications. Previous versions contained project templates for ASP.NET MVC but not much more. With SharpDevelop 4.2 the following features have been added:

    • Razor project and file templates for C# and Visual Basic
    • Razor syntax highlighting
    • Add Controller dialog using T4 templates
    • Add View dialog using T4 templates
    • HTML folding

    Now let us take at these new features.

    Prerequisites

    Before using SharpDevelop you should install ASP.NET MVC 3 and IIS, either IIS Express or full IIS. You can get MVC 3 and IIS Express from Microsoft's Web Platform installer or download them directly from the following pages:

    After installing IIS Express make sure that you run IISExpress.exe once so it can generate its configuration files for your user profile. If you do not then SharpDevelop will fail to configure IIS Express.

    Creating an ASP.NET MVC Application

    Now we shall create a new C# ASP.NET MVC application that uses the Razor view engine. First run SharpDevelop and then from the File menu select New Solution to open the New Project dialog.

    New ASP.NET MVC project dialog

    On the left in Categories select ASP.NET MVC under C#. On the right you will see three project templates.

    • Empty MVC Application - creates an MVC application with a minimal set of files.
    • MVC Application - creates an MVC application that uses the Web Forms view engine (.aspx).
    • Razor MVC Application - creates an MVC application that uses the Razor view engine.

    Select the Razor MVC Application project template. Enter a name for the project and select a location where the project will be created. Click Create to create the MVC project.

    ASP.NET MVC project in Projects window

    If you open the Projects window by selecting Projects from the View menu you will see that the project template created a Home Controller, two Razor view pages - Index and Contact, as well as installing the jQuery and Modernizer NuGet packages.

    Syntax Highlighting and Folding

    If you open the a Razor file (.cshtml) you will see that there is html folding and Razor syntax highlighting.

    Razor syntax highlighting

    The Razor syntax highlighting is still under development and does not work in all cases since it is not using Microsoft's Razor parser and uses a basic syntax definition file. In the screenshot above, for example, the Razor @ symbol is not correctly highlighted in the script and link tags.

    Running an ASP.NET MVC Application

    In order to be able to run your application first you will need to configure the project to use IIS Express or IIS. From the Project menu select Project Options. Select the Debug tab. At the bottom of this tab you will see options for IIS Express and IIS.

    IIS project options

    For this walkthrough we will use IIS Express. Select IIS Express and enter a port number. Then click the Create Applicaton/Virtual Directory button. A message will then be displayed telling you that the application/virtual directory was created successfully. Now we can run the application.

    To run the application select Run from the Debug menu. IIS Express will then be launched and your application will be loaded into your default web browser.

    ASP.NET MVC application running in browser

    You can set breakpoints in your application and debug your code in the standard way. For example, set a breakpoint in the HomeController's Contact method and then click Contacts in your browser and you will see SharpDevelop stop at the breakpoint.

    Breakpoint hit in HomeController Contact method

    To stop debugging select Stop process from the Debug menu. You will then see a prompt asking you to detach or terminate the process being debugged, in this case IIS Express. Detaching will leave IIS Express running.

    File Templates

    SharpDevelop includes a set of file templates for ASP.NET MVC applications. You can create a new file using these templates by selecting the project or a folder in the Projects window, right clicking and select Add New Item.

    ASP.NET MVC file templates in New File Dialog

    Select the appropriate template, give the file a name and click Create to add a new file to your project.

    Add Controller Dialog

    You can add a new controller to your project using a file template as described in the previous section or you can use the Add Controller dialog.

    Select the Controllers folder in the Projects window, right click and select Add Controller to show the Add Controller dialog.

    Add controller dialog

    In the dialog you specify the controller's name and select one of the templates that will be used to generate the controller class. These templates are defined by a single T4 template that you can edit if you want to customise it. The T4 template exists in the following subfolder where SharpDevelop was installed:

    AddIns\BackendBindings\AspNet.Mvc\ItemTemplates

    Click the Add button to create a new controller from the T4 template.

    Add View Dialog

    A new view can be created by using a file template or by using the Add View dialog. Select one of the Views folders, right click and select Add New View to show the Add View dialog.

    Add view dialog

    In the dialog you can specify the following items:

    • View Name - specifies the name of the view
    • View Engine - selects either web forms (ASPX) or Razor view engine. The options displayed in the dialog will change based on this selection.
    • Strongly Typed - allows you to generate a view based on a type in your project.
    • Model - a list of types in your project. You may have to compile your project for a class to be displayed in this drop down.
    • Template - specifies which of the T4 templates will be used when generating the view. Templates available are - Empty, Create, Delete, Details, Edit, List.
    • Use Layout (Razor) - specifies whether the view will use a layout.
    • Layout (Razor) - specifies the path to the layout page. The browse button allows you to select a layout page from those in your project.
    • User Master Page (ASPX) - specifies whether the view will use a master page.
    • Master Page (ASPX) - specifies the path to the master page. The browse button allows you to select a master page from those in your project.
    • Main Content ID (ASPX) - specifies the main content ID.
    • Partial View - used to generate a partial view.

    Views generated from this dialog use T4 templates which exist in the following folder if you need to customise them:

    AddIns\BackendBindings\AspNet.Mvc\ItemTemplates

    That concludes the walkthrough of the new ASP.NET MVC 3 support in SharpDevelop. Further information on ASP.NET MVC 3 can be found at the Getting Started with ASP.NET MVC page.

  • New Icons for SharpDevelop

    Thanks to Yusuke Kamiyamane's Fugue Icons, and icons created and remixed by Michael Seeger, SharpDevelop 4.2 has a new look. A selection of before and after screenshots are shown below:

    SharpDevelop 4.1 Toolbar

    Old toolbar

    SharpDevelop 4.2 Toolbar

    New toolbar

    SharpDevelop 4.1SharpDevelop 4.2
    Posted Jan 21 2012, 05:55 PM by MattWard with 6 comment(s)
    Filed under:
  • Machine.Specifications (MSpec)

    Here is a preview of a new feature that is planned for SharpDevelop - integrated support for Machine.Specifications.

    Machine.Specifications, or MSpec for short, is a Behaviour Driven Development framework for .NET created by Aaron Jensen which takes its inspiration from SpecUnit.NET and RSpec.

    Support for MSpec has been added thanks to Tomasz Tretkowski.

    So let us take a look at how the MSpec integration works in SharpDevelop.

    MSpec Integration

    The first thing you will need to do is add a reference to MSpec in the project that will contain your specifications. The easiest way to do this is to use NuGet. Select your project, right click and select Manage Packages.

    Manage Packages context menu

    Search for the Machine.Specifications package and then click the Add button to add the NuGet package to your project.

    MSpec NuGet package selected in Manage Packages dialog

    This will add a Machine.Specifications assembly reference to your project.

    Now let us create our first specification. We are going to create a specification which is based on an example provided with the MSpec source code. The specification is for transferring an amount of money between two bank accounts and is shown below.

    using System; 
    using Machine.Specifications; 
     
    namespace Banking.Tests 
    { 
        [Subject(typeof(Account), "Funds transfer")] 
        public class when_transferring_between_two_accounts 
        { 
            static Account fromAccount; 
            static Account toAccount; 
             
            Establish context = () => { 
                fromAccount = new Account { Balance = 1m }; 
                toAccount = new Account { Balance = 1m }; 
            }; 
             
            Because of = () => 
                fromAccount.Transfer(1m, toAccount); 
             
            It should_debit_the_from_account_by_the_amount_transferred = () => 
                fromAccount.Balance.ShouldEqual(0m); 
             
            It should_credit_the_to_account_by_the_amount_transferred = () => 
                toAccount.Balance.ShouldEqual(2m); 
        } 
    }

    MSpec uses Establish/Because/It which is equivalent to Given/When/Then that is used with SpecFlow. Establish is used to setup the initial state. Because is used to define the event/action that you are testing. It is used to test the final state and see if it matches what is expected.

    The Account class that is used by this specification is shown below.

    using System; 
     
    namespace Banking 
    { 
        public class Account 
        { 
            public decimal Balance { get; set; } 
            
            public void Transfer(decimal amount, Account toAccount) 
            {             
            }
        } 
    }

    Specifications are displayed in the Unit Tests window. This window can be opened by selecting Unit Tests from the View | Tools menu. The specification we have defined will be displayed in the Unit Test window as shown below.

    MSpec tests in Unit Tests window

    The Unit Tests window will update as the specification is written in the same way it does when you are writing NUnit tests.

    To run MSpec you can right click a specification and select Run tests or you can click the toolbar buttons at the top of the Unit Tests window.

    Run tests context menu in Unit Tests window

    Failures will be highlighted in Red in the Unit Tests window.

    MSpec failures in Unit Tests window

    The output from MSpec is displayed in the Output window.

    MSpec runner output in Output window

    Failures are also added to the Errors window. Clicking on an error will take you directly to the source code for the failing test.

    MSpec failures in Errors window

    Now we have to fix the failures by implementing the Account's Transfer method. The updated Transfer method is shown below:

    public void Transfer(decimal amount, Account toAccount) 
    { 
        Balance -= amount; 
        toAccount.Balance += amount; 
    }

    After making this change and running MSpec again everything passes, as shown below.

    MSpec passes shown in green in Unit Tests window

    MSpec success output in Output Window

    That completes the quick introduction to using MSpec with SharpDevelop. Now let us take a look at MSpec Behaviours.

    MSpec Behaviours

    MSpec Behaviours are a way to group together a set of tests that you want to re-use with different contexts. To do this you create a separate class, add a Behaviors attribute to it, and move your tests into that class. This behaviour class is then referenced by using the Behaves_like syntax. An example taken from the MSpec examples is shown below.

    using System; 
    using Machine.Specifications; 
     
    namespace Banking.Tests 
    { 
        [Subject("Date time parsing")] 
        public class when_a_date_is_parsed_with_the_regular_expression_parser 
         : DateTimeParsingSpecs 
        { 
            Establish context = () =>  
             Parser = new RegexParser(); 
     
            Because of = () =>  
             ParsedDate = Parser.Parse("2009/01/21"); 
     
            Behaves_like<DateTimeParsingBehavior> a_date_time_parser; 
        } 
     
        [Subject("Date time parsing")] 
        public class when_a_date_is_parsed_by_the_infrastructure 
         : DateTimeParsingSpecs 
        { 
            Establish context = () =>  
             Parser = new InfrastructureParser(); 
     
            Because of = () =>  
             ParsedDate = Parser.Parse("2009/01/21"); 
     
            Behaves_like<DateTimeParsingBehavior> a_date_time_parser; 
        } 
     
        public abstract class DateTimeParsingSpecs 
        { 
            protected static DateTime ParsedDate; 
            protected static IParser Parser; 
        } 
     
        [Behaviors] 
        public class DateTimeParsingBehavior 
        { 
            protected static DateTime ParsedDate; 
     
            It should_parse_the_expected_date = () =>  
                ParsedDate.ShouldEqual(new DateTime(2009, 1, 21)); 
        } 
    }

    Here the behaviour of the parser returning a particular date has been extracted and re-used across two different contexts.

    SharpDevelop is aware of MSpec behaviours and will display the underlying tests. The date time parser specifications above will be displayed in the Unit Tests window as shown below.

    MSpec behaviours in Unit Tests window

    For further details on MSpec behaviours take a look at the Behaviours in MSpec post by James Gregory.

    Further MSpec Information

    Here is a selection of links to further information on MSpec that you may find useful.

    MSpec on Github

    Introducing MSpec - Aaron Jensen's post that first introduced MSpec.

    Getting Started with MSpec

    Learning BDD - If you prefer to learn by watching a video check out Rob Conery's BDD screencast where he discusses BDD and also covers MSpec.

    Make BDD your BFF - Rob Conery walks through BDD with MSpec.

    Teaching a String Calculator How to Behave

    Behaviours in MSpec

     

     

     

    Posted Nov 09 2011, 10:07 PM by MattWard with no comments
    Filed under:
  • SubSonic T4 Templates

    SharpDevelop 4.2 now supports SubSonic T4 templates. Subsonic is an open source object-relational mapper and makes use of T4 templates in all but one of its supported methods to provide access to your data. Before we take a look at what new T4 features were added to SharpDevelop to support SubSonic let us see what you need to do to get everything working.

    Using SubSonic T4 Templates with SharpDevelop

    In order to use the SubSonic T4 templates with SharpDevelop you need to make two modifications to the Settings.ttinclude file.

    Replace the EnvDTE assembly reference:

    <#@ assembly name="EnvDTE" #>

    With the following:

    <#@ assembly name="$(addinpath:ICSharpCode.PackageManagement)PackageManagement.dll" #>

    This references SharpDevelop's NuGet addin assembly which implements its own version of the Visual Studio object model.

    In SharpDevelop 4.3 an extra assembly directive is needed, as shown below:

    <#@ assembly name="SharpDevelop.EnvDTE.dll" #>

    Add a new import directive as shown below:

    <#@ import namespace="EnvDTE = ICSharpCode.PackageManagement.EnvDTE" #>

    This creates a namespace alias for EnvDTE so the references to the Visual Studio object model in the SubSonic T4 template will work.

    In SharpDevelop 4.3 the EnvDTE import directive does not need to be changed.

    All that is left now is to save the changes made to the Settings.ttinclude file and generate the database access code by executing the ActiveRecord.tt, Context.tt and Struct.tt T4 templates. This can be done by right clicking them in the Projects window and selecting Execute Custom Tool.

    Now we will take a look at the new features that made this possible.

    Referencing SharpDevelop Properties and Environment Variables in T4 Templates

    The T4 assembly and include directives now support the $(PropertyName) syntax to use SharpDevelop properties such as SolutionDir and ProjectDir.

    <#@ assembly name="$(ProjectDir)lib\MyLibrary.dll" #> 
    <#@ include file="$(SolutionDir)Templates\MyTextTemplate.tt" #> 

    The assembly and include directives also support environment variables through the %EnvironmentVariableName% syntax.

    <#@ assembly name="%ProgramFiles%\lib\MyLibrary.dll" #> 
    <#@ include file="%HOMEPATH%\MyTextTemplate.tt" #>

    This new feature also supports the addinpath property and is used to allow a T4 template to reference SharpDevelop's NuGet addin using the $(addinpath:AddIn-ID) syntax which is expanded to the directory containing the addin.

    Accessing the SharpDevelop IDE from a T4 Template

    The SubSonic T4 templates use the Visual Studio object model to find the project's app.config file and read the database connection string stored here in order to access your database. To support this the T4 templating host in SharpDevelop now implements the IServiceProvider interface which allows you to access SharpDevelop's implementation of the Visual Studio object model.

    To access the Visual Studio object model you set the T4 template so it is host specific:

    <#@ template language="C#" hostspecific="true" #>

    Then you can access the DTE object, which is the top-level object of the Visual Studio object model, as shown below.

    <#
        IServiceProvider provider = (IServiceProvider)Host; 
        EnvDTE.DTE dte = (EnvDTE.DTE)provider.GetService(typeof(EnvDTE.DTE));
    #>

    The Visual Studio object model is not fully implemented in SharpDevelop so you may run into problems if you make extensive use of this object model.

    [Update 2012-10-11] Added changes required for SharpDevelop 4.3

    Posted Oct 05 2011, 09:33 PM by MattWard with no comments
    Filed under:
  • SpecFlow Integration

    The SpecFlow team recently released version 1.7 and with it they included support for SharpDevelop 4.0. SpecFlow is an open source framework that you can use to do Behaviour Driven Development (BDD) on .NET. It allows you to bind business requirements to the code. Let us take a look at how SpecFlow integrates with SharpDevelop.

    Installation

    Download and install the following:

    1. SharpDevelop 4.0
    2. SpecFlow 1.7.0

    If SharpDevelop is installed first then the SpecFlow installer will detect SharpDevelop, as shown in the screenshot below.

    SpecFlow installer detecting SharpDevelop 4.0

    The installer will then add a set of SpecFlow templates to SharpDevelop. It will also install a SharpDevelop addin which you will need to register using the addin manager. To register the SpecFlow addin start SharpDevelop and from the Tools menu select AddIn Manager. This will open the AddIn Manager dialog.

    AddIn Manager dialog

    Click the Install AddIn button and browse to the SpecFlow installation folder. The default installation folder for SpecFlow is C:\Program Files\TechTalk\SpecFlow. In this folder find the TechTalk.SpecFlow.SharpDevelop4Integration.addin file, select it and click the Open button. The SpecFlow addin should then be displayed in the AddIn Manager dialog.

    SpecFlow addin installed in SharpDevelop 4.0

    Restart SharpDevelop so the SpecFlow addin is loaded and is ready to be used.

    Now let us take a look at how to use SpecFlow with SharpDevelop.

    Using SpecFlow

    Here we will follow the workflow that is shown on the SpecFlow web site. This workflow looks at creating a bowling game using SpecFlow.

    In SharpDevelop create a new C# class library project called Bowling. Right click the project just created and select Add New Item. In the New File dialog open the SpecFlow category and select the SpecFlow Feature template. Change the filename to be ScoreCalculation.feature. Click the Create button to save the file.

    SpecFlow feature file template in New File Dialog

    Replace the existing text in the feature file created with the text shown below.

    Feature: Score Calculation 
     In order to know my performance 
     As a player 
     I want the system to calculate my total score 
     
    Scenario: Gutter Game 
     Given a new bowling game 
     When all of my balls are landing in the gutter 
     Then my total score should be 0 
     
    Scenario: All Strikes 
     Given a new bowling game 
     When all of my rolls are strikes 
     Then my total score should be 300

    This is the specification for one part of the game. It is written in a language called Gherkin which gives you a user friendly way to specify a set of behaviours that your application should have. More information about the Gherkin language can be found on the Gherkin wiki.

    Now select this feature file in the Projects window, right click and select Properties. In the file properties change the Custom Tool to be SpecFlowSingleFileGenerator.

    SpecFlowSingleFileGenerator custom tool set in file properties

    Now every time you save the feature file a new file will be auto-generated.

    ScoreCalculation.feature.cs generated file.

    If you open this generated file you will see that it contains a class that has two NUnit tests.

    Generated file with NUnit tests.

    To run the unit tests you will need to add a reference to NUnit and SpecFlow to the project. In the Projects window, right click your project and select Add Reference. Select the .NET Assembly Browser tab and browse to the NUnit.Framework.dll file that can be found in the SharpDevelop folder C:\Program Files\SharpDevelop\4.0\bin\Tools\NUnit and add that file as a reference. Do the same for the TechTalk.SpecFlow.dll file which can be found in the C:\Program Files\TechTalk\SpecFlow folder.

    Now create a new file called BowlingSteps.cs and copy the following code into it.

    using System; 
    using NUnit.Framework; 
    using TechTalk.SpecFlow; 
     
    namespace Bowling 
    { 
     
     [Binding] 
     public class BowlingSteps 
     { 
      private Game _game; 
     
      [Given(@"a new bowling game")] 
      public void GivenANewBowlingGame() 
      { 
       _game = new Game(); 
      } 
     
      [When(@"all of my balls are landing in the gutter")] 
      public void WhenAllOfMyBallsAreLandingInTheGutter() 
      { 
       for (int i = 0; i < 20; i++) 
       { 
        _game.Roll(0); 
       } 
      } 
     
      [When(@"all of my rolls are strikes")] 
      public void WhenAllOfMyRollsAreStrikes() 
      { 
       for (int i = 0; i < 12; i++) 
       { 
        _game.Roll(10); 
       } 
      } 
     
      [Then(@"my total score should be (\d+)")] 
      public void ThenMyTotalScoreShouldBe(int score) 
      { 
       Assert.AreEqual(score, _game.Score); 
      } 
     
      [When(@"I roll (\d+)")] 
      public void WhenIRoll(int pins) 
      { 
       _game.Roll(pins); 
      } 
     
      [When(@"I roll (\d+) and (\d+)")] 
      public void WhenIRoll(int pins1, int pins2) 
      { 
       _game.Roll(pins1); 
       _game.Roll(pins2); 
      }  
     
      [When(@"I roll (\d+) times (\d+) and (\d+)")] 
      public void WhenIRollSeveralTimes2(int rollCount, int pins1, int pins2) 
      { 
       for (int i = 0; i < rollCount; i++) 
       { 
        _game.Roll(pins1); 
        _game.Roll(pins2); 
       } 
      } 
     
      [When(@"I roll the following series:(.*)")] 
      public void WhenIRollTheFollowingSeries(string series) 
      { 
       foreach (var roll in series.Trim().Split(',')) 
       { 
        _game.Roll(int.Parse(roll)); 
       } 
      } 
     
      [When(@"I roll")] 
      public void WhenIRoll(Table rolls) 
      { 
       foreach (var row in rolls.Rows) 
       { 
        _game.Roll(int.Parse(row["Pins"])); 
       } 
      } 
     } 
    }

    The BowlingSteps.cs file shown above implements the scenarios defined in the feature file and will be used by the unit tests to verify the implementation works as expected.

    The only bit that is missing is the code that implements the bowling game logic. Create a file called Game.cs and copy the code shown into it.

    namespace Bowling 
    { 
     public class Game 
     { 
      public void Roll(int i) 
      {     
      } 
       
      public int Score {  
       get { return -1; } 
      } 
     } 
    } 
    

    The Game.cs file contains the main Game class that implements the logic that we are going to test. Currently this code is incorrect so we are expecting the unit tests to fail.

    In the Unit Tests window (View | Tools | Unit Tests) click the Run all tests toolbar button. All the tests should fail as shown below.

    All specflow unit tests failed.

    Now we need to fix the tests. The GutterGame test is the easiest to get working. Edit the Game class and change the Score property so it returns 0.

    namespace Bowling 
    { 
     public class Game 
     { 
      public void Roll(int i) 
      { 
      } 
       
      public int Score {  
       get { return 0; } 
      } 
     } 
    }

    Now when you run the unit tests again the GutterGame test will pass.

    SpecFlow gutter game unit test passes

    The next step would be to change the Game class so the AllStrikes unit test will pass. Then you could define more scenarios in feature files to cover more functionality that you want the bowling game to have. Then you would go through the process just described until you have a working solution that meets all the requirements. These steps are not shown here but hopefully you get the idea.

    We have looked at how SpecFlow integrates with SharpDevelop and walked through the process of defining a set of scenarios that our application should have, creating unit tests to check the scenarios are implemented correctly and finally implementing the application logic so the unit tests pass.

    Further Information

    More information on SpecFlow can be found on the SpecFlow web site and on the SpecFlow GitHub wiki.

    Posted Aug 09 2011, 08:23 PM by MattWard with no comments
    Filed under:
  • NuGet 1.4

    The NuGet 1.4 release included some great new features for managing NuGet packages across a solution. SharpDevelop has now been updated to NuGet 1.4 so let us take a look at the changes in the latest version of SharpDevelop.

    Manage Packages Dialog

    The first thing that you will notice is that the menu name has changed. When you right click on a project or a solution you now select Manage Packages to open the Manage Packages dialog.

    Manage packages right click context menu

    The dialog name has changed and now shows the name of the project or the solution in the its caption. Opening the dialog by right clicking on a project and selecting Manage Packages allows you to add or remove NuGet packages from the selected project. In the screenshot below the MyApplication.Tests project was selected when the Manage Packages dialog was opened.

    Manage Packages dialog - MyApplication.Tests project selected

    Right clicking on the solution and selecting Manage Packages allows you to add or remove NuGet packages from multiple projects in one step. In the screenshot below the MyApplication solution was selected when the Manage Packages dialog was opened.

    Manage Packages dialog - MyApplication solution selected

    NuGet packages can now be added to multiple projects in one step. Find the NuGet package you want to add and click the Manage button. You will then be prompted to select which project you want the package to be installed into.

    Manage Packages - Select Projects dialog

    Click the OK button to install the package into the selected projects.

    To remove a NuGet package from multiple projects switch to the Installed packages tab, select the package and click the Manage button. You will then be shown a list of projects. To remove a package uncheck one or more projects and click the OK button.

    Update-Package PowerShell Command

    The Update-Package PowerShell command has been changed to support updating a NuGet package across multiple projects. The following commands can be used in the Package Management Console window to update packages across projects.

    Update all Packages in the Solution

    update-package

    Update all Packages in a Project

    update-package -ProjectName MyProject

    Update a Package across the Solution

    update-package jQuery

    That covers the changes in the current version of SharpDevelop. Note that not all of the features that were added in NuGet 1.4 are currently available in SharpDevelop. For example, the Package Visualiser and the safe updating of NuGet packages using Update-Package -Safe, have not been implemented.

  • T4 Templates in SharpDevelop

    SharpDevelop 4.1 now has integrated support for T4 Templates. The T4 code generation engine for MonoDevelop has been used to make this feature possible so a big thanks to Michael Hutchinson for creating this. Features include:

    • Syntax highlighting for T4 templates (.tt and .t4 files).
    • Support for TextTemplatingFileGenerator and TextTemplatingFilePreprocessor custom tools.
    • T4 template errors shown in Errors window.

    Code completion for T4 templates is not currently supported.

    Creating a T4 Template

    Open a project in SharpDevelop, right click the project and select Add, New Item. This will open the New File dialog. There are two T4 templates available, one for C# and one for VB.NET.

    C# T4 template selected in New File dialog

    Select the appropriate file template, give it a name and click the Create button.

    New C# T4 template open in text editor.

    Now you can edit the T4 template. In the example below we have modified the T4 template so it generates the current date and time when it is saved.

    <#@ template language="C#" #> 
    <#@ output extension=".txt" #> 
     
    Date and time: <#= DateTime.Now #>

    When the file is saved a new file will be created. In the Projects window this new file will be a child of the T4 template file.

    File generated from T4 template in Projects window.

    Opening this file in the text editor shows text generated by the T4 template.

    File generated from T4 template open in text editor.

    Creating a Preprocessed T4 Template

    SharpDevelop also supports preprocessed T4 templates. A preprocessed T4 template will create a class which can be used by your application at runtime to generate text. We will take our previous template and convert it to a preprocessed T4 template. To do this select the T4 template file in the Projects window, right click and select Properties. Select the Custom Tool property and change it to be TextTemplatingFilePreprocessor.

    T4 template custom tool property changed to TextTemplatingFilePreprocessor

    Now when you save the T4 template a file will be generated containing a class.

    Preprocessed T4 template generated file.

    This class can then be used in your application to generate text at runtime. Shown below is a simple example of how this class could be used.

    using System; 
     
    namespace MyProject 
    { 
     class Program 
     { 
      public static void Main(string[] args) 
      { 
       MyTextTemplate template = new MyTextTemplate(); 
       string text = template.TransformText(); 
        
       Console.WriteLine(text); 
       Console.ReadLine(); 
      } 
     } 
    }

    The result of running the above code is shown below.

    Preprocessed T4 template class output displayed in Console output.

    For more information on creating T4 templates take a look at Oleg Sych's excellent set of T4 tutorials.

    Posted Jun 26 2011, 06:38 PM by MattWard with 3 comment(s)
    Filed under:
  • Project Templates with NuGet Packages

    At MIX this year Microsoft released a tools update to ASP.NET MVC 3. One of the new features was a set of ASP.NET MVC project templates that install libraries, such as jQuery and Modernizr, as NuGet packages. SharpDevelop 4.1 now includes this feature. Let us take a look at how to create a project template for SharpDevelop that installs NuGet packages.

    Creating a Project Template

    As an example we will create a C# project template that installs NUnit as a NuGet package. To keep things simple we will take a copy of an existing C# project template and modify it rather than creating a template from scratch.

    SharpDevelop's project templates can be found in the C:\Program Files\SharpDevelop\4.1\data\templates\project directory, assuming the default installation directory was not changed. The C# project templates are stored in the CSharp directory.

    C# project templates folder open in Windows Explorer

    Find the Library.xpt file. This file is a class library project template. Make a copy of the Library.xpt file in the same directory and call it UnitTestsProject.xpt. Then open UnitTestsProject.xpt with your favourite text editor.

    First change the name of the template so it can be identified when creating a new project. In the TemplateConfiguration section of the template change the Name and the Description as shown below.

     <TemplateConfiguration> 
      <Name>Unit Tests</Name> 
      <Category>C#</Category> 
      <Icon>C#.Project.Library</Icon> 
      <Description>Creates a Unit Tests project.</Description> 
      <SupportedTargetFrameworks>v2.0;v3.5Client</SupportedTargetFrameworks> 
     </TemplateConfiguration>

    Now we need to get the template to run a command when the project is created. This command will be responsible for installing any NuGet packages defined in the project template. Find the Actions element and add a new RunCommand element as shown below.

     <Actions> 
      <Open filename = "MyClass.cs"/> 
      <RunCommand path="/AddIns/PackageManagement/TemplateCommands/InstallPackages"/> 
     </Actions> 
    

    Now we can define the NuGet packages that will be installed when the project is created. Find the Files element and inside that add a new File element as shown below.

       <File name="packages.config"> 
    <![CDATA[<?xml version="1.0" encoding="utf-8"?> 
    <packages> 
      <package id="NUnit" version="2.5.10.11092" /> 
    </packages> 
    ]]> 
      </File>

    This file is the standard NuGet packages.config file. Inside here you can put any NuGet package that you want the template to install. In the example above the NuGet package version has been specified. If you want to install the latest version of a NuGet package then do not include the version attribute, as shown below.

       <File name="packages.config"> 
    <![CDATA[<?xml version="1.0" encoding="utf-8"?> 
    <packages> 
      <package id="NUnit" /> 
    </packages> 
    ]]> 
      </File>

    Finally save the new project template file. We now have a project template that will install the NUnit NuGet package but we have not defined where the NuGet package needs to be stored. We will look at where the NuGet packages need to be located in the next section.

    Configuring NuGet Package Sources

    By default SharpDevelop will look in the data\templates\packages directory for NuGet packages when creating a new project.

    Project template NuGet packages folder open in Windows Explorer

    So we can add the NUnit NuGet package into this directory. To get the NuGet package you can use the NuGet Package Explorer. From the NuGet Package Explorer's File menu select Open from Feed. In the Select Package dialog search for the NUnit package.

    NUnit package searched for in NuGet Package Explorer

    Then double click the NUnit package to open it. Finally from the File menu select Save As and save the package to the data\templates\packages directory.

    Adding NuGet packages into the packages directory is all you need to do to be able to use the project template however you do not have to use this directory. You can configure where the project templates will look for packages in SharpDevelop's options. From the Tools menu select Options. In the Options dialog select Template Package Sources from the Package Management category.

    Project Template Package Sources Options dialog

    In this dialog you can add and remove package sources. You can configure SharpDevelop to use the official NuGet package repository or another directory. If you specify multiple package sources then all of these will be used as a possible source when the project is created.

    With the source of the NuGet packages configured all that is left for us to do is use the project template.

    Creating a New Project

    Now we can try our new project template. From the File menu select New Solution.

    Unit tests project template with NuGet packages selected in New Project dialog.

    Expand the C# category and select the Unit Tests project template. Give the project a name and location and click the Create button.

    Unit tests project created with NuGet packages and open in SharpDevelop

    The project will then be created and the NUnit NuGet package will be installed too.

    Posted Jun 19 2011, 07:04 PM by MattWard with no comments
    Filed under:
  • Installing NuGet Packages outside of Visual Studio

    There have been discussions about using NuGet outside of Visual Studio as well as an open work item in the NuGet issue tracker. Outside of Visual Studio in this context means using NuGet from the command line. There is support for this already with NuGet.exe so let us take a quick look at what is supported at the moment.

    Currently you can use NuGet.exe to download packages without having to use Visual Studio. You can download a single package:

    nuget install nunit

    You can point NuGet.exe to your packages.config and it will download any missing packages:

    nuget install packages.config

    What NuGet.exe will not do is update your project file (.csproj) nor will it run any PowerShell scripts that the package uses. Which is OK in the majority of cases.

    You can go further than this though. Since SharpDevelop supports updating project files as a proof of concept we have used SharpDevelop to extend NuGet further so now NuGet can support everything it does from within Visual Studio but from the command line. From the command line we are able to install a package, have the project file updated with assembly references and any new files, and finally have any PowerShell scripts included in the NuGet package processed.

    Since NuGet uses PowerShell the simplest approach was to extend the existing PowerShell cmdlets included with SharpDevelop. Now you can write a few lines of PowerShell script to install a NuGet package into a project that has never had a NuGet package before, have the project itself updated and any package PowerShell scripts run. All this from the command line without Visual Studio open.

    Setting Everything Up

    Download the zip file containing the cmdlets and extract the assemblies.

    First you will need to modify the PowerShell configuration. By default PowerShell will run under .NET 2.0 but we need it to run under .NET 4.0 since the cmdlets use .NET 4.0. Create a powershell.exe.config file in the C:\Windows\System32\WindowsPowerShell\v1.0 folder with the following contents:

    <configuration>  
        <startup useLegacyV2RuntimeActivationPolicy="true">  
            <supportedRuntime version="v4.0.30319"/>  
            <supportedRuntime version="v2.0.50727"/>  
        </startup>  
    </configuration>   

    Note that if you are running Windows x64 then you should run the 32 bit version of PowerShell and create a powershell.exe.config file in the C:\windows\syswow64\WindowsPowerShell\v1.0 folder.

    The useLegacyV2RuntimeActivationPolicy attribute is required. For a great explanation of what this attribute is take a look at What is useLegacyV2RuntimeActivationPolicy for? written by Mark Miller.

    To be able to run PowerShell scripts included with a NuGet package the execution policy will need to be changed:

    Set-ExecutionPolicy RemoteSigned -Scope Process

    Now import the Package Management Cmdlets assembly. The command below assumes the assembly is in the current working directory otherwise the full path to the assembly will be needed.

    import-module PackageManagement.Cmdlets.dll

    Now we are ready to use the cmdlets.

    Installing a Package

    First the install-package cmdlet has a new -solution parameter to support specifying the solution.

    install-package nunit -solution MySolution\MySolution.sln

    If you do not specify the project name then the first project in the solution will be used as the default project.

    install-package nunit -solution MySolution.sln -projectname MyProject

    Uninstalling a Package

    To uninstall a package we can use the new -solution parameter.

    uninstall-package nunit -solution MySolution.sln -projectname MyProject

    Updating a Package

    Once again we can specify the solution filename when updating a package.

    update-package nunit -solution MySolution.sln -projectname MyProject

    Ideally we would like to be able to update all projects in the solution in one go however this is not currently implemented.

    Setting a Default Project

    Instead of specifying the solution when running each command you can set a default project with the new Set-Project command.

    set-project MyProject d:\Projects\MyProject\MySolution.sln

    After setting the default project the other commands can be run without the need to specify the -solution parameter or the name of the project.

    Package PowerShell Scripts

    Since SharpDevelop has its own set of DTE objects any PowerShell scripts in the package can be run. Each of the cmdlets described above define the DTE variable before any Powershell scripts included with the package are run.

    Conclusion

    So finally we can now use a single PowerShell script to install packages into an empty project. As a simple example:

    setup.ps1:

    import-module d:\scripts\PackageManagement.Cmdlets.dll 
     
    $solution = "d:\Projects\MyProject\MyProject.sln" 
    set-project MyProject $solution
    
    install-package nunit

    To run this from the command line with PowerShell:

    powershell -ExecutionPolicy RemoteSigned -File d:\projects\MyProject\setup.ps1

    Issues

    If you are using $host.Version then within the PowerShell this will return the PowerShell host version and not the NuGet PowerShell host version.

    Several extra SharpDevelop assemblies are included in the zip file. This could be reduced with some more work.

    The formatting for NuGet packages is not defined so the output is a list of properties for each package object.

    Source Code

    The source code is available on github. It is not a part of SharpDevelop since this was an prototype. So there are no unit tests for the new code and core parts of SharpDevelop have been changed to support the new PowerShell cmdlets.

    [Update - Oct 16, 2012] - Added information on using 32 bit version of PowerShell if using Windows x64

  • NuGet PowerShell Console

    Since the NuGet support in SharpDevelop was previewed back in January development has continued and some new features have been added. One of the new features that we will take a look at now is a new PowerShell console that allows SharpDevelop 4.1 to support installing, updating and uninstalling NuGet packages that contain PowerShell scripts.

    Package Management Console

    The Package Management Console is SharpDevelop's new PowerShell console. It provides several cmdlets that can be used to install, uninstall or update NuGet packages. NuGet packages can contain PowerShell scripts that will automate SharpDevelop and extend the functionality provided by NuGet.

    To open the Package Management Console from the View menu select Tools and then select Package Management Console.

    Package Management Console window

    The Package Source drop down list is used to select the NuGet package repository that will be used by default when running commands. The Default Project drop down list has a list of projects in the currently open solution and is used to select the project that the console will use by default. There is also a clear button which clears the text in the console window.

    Help on the commands can be displayed by typing get-help NuGet. To see detailed help on a specific command type get-help followed by the name of the command. Help on the commands can also be found in the official NuGet Package Manager Console PowerShell Reference. Please note that at the time of writing some of the commands are not available but will be added at some point in the future. The unsupported commands are specified in the Issues section at the end of this blog post.

    Finding NuGet Packages

    To find available NuGet packages from a NuGet package source first select that source in the console's drop down list and use the Get-Package command.

    To look for the NUnit.Sample package:

    Looking for all NUnit NuGet packages in PowerShell Console

    To display the packages installed in the project selected in the drop down list run the Get-Package command without any parameters.

    Getting all installed NuGet packages in the PowerShell console

    Adding NuGet Packages

    To install a package first select the required NuGet package source, then select the project where the package should be installed and then use the Install-Package command.

    Installing a NuGet package with the PowerShell console

    Removing NuGet Packages

    To remove a NuGet package use the Uninstall-Package command.

    Uninstalling a NuGet package with the PowerShell console

    Updating NuGet Packages

    To see packages that have updates available you can run the Get-Package -Updates command. To update a package use the Update-Package command.

    Updating a NuGet package in the PowerShell console

    Add Package Reference Dialog

    The Add Package Reference dialog supports installing, updating or uninstalling a package with PowerShell scripts. If it detects that a PowerShell script needs to be run then the package install, update or uninstall actions will be run in the Package Management Console. If PowerShell is not installed then the package will still be installed but the PowerShell scripts will not be run.

    Package PowerShell Scripts

    There are three PowerShell scripts that if included in a NuGet package will be run.

    • init.ps1 - Runs when a package is first installed in a solution and then every time the solution containing this package is opened.
    • install.ps1 - Runs every time a package is installed.
    • uninstall.ps1 - Runs every time a package is uninstalled.

    More details on these scripts can be found in the NuGet documentation on Creating and Publishing a Package.

    When these PowerShell scripts are run they are passed the package, information about the package such where it will be installed and a project object. The scripts also have access to a global $dte variable which is made available by the PowerShell console. If you are using NuGet within Visual Studio then both the project object passed to a PowerShell script and the DTE object, made available via the $dte variable, are part of the Visual Studio object model and can be used to automate Visual Studio. When using SharpDevelop's PowerShell console these objects are also available and can be used to automate SharpDevelop. To do this SharpDevelop provides its own partial implementation of the Visual Studio object model. SharpDevelop implements a set of classes that provide methods and properties that to PowerShell scripts look like Visual Studio's object model but are not dependent on Visual Studio being installed.

    Since SharpDevelop's implementation of Visual Studio's object model is not a full implementation there are going to be some gaps which will mean a PowerShell script may produce some errors when it is run. If a script tries to use a feature provided only by Visual Studio then that will fail too. Another problem is that if a NuGet package directly references and uses the Visual Studio object model then the package will also not work. So this means whilst a package such as Phil Haack's MoodSwings, which changes the text editor fonts and colours, does work a package such as Steve Sanderson's MvcScaffolding that directly accesses Visual Studio directly does not work.

    Issues

    The Package Management Console does not currently support tab completion.

    The entire Visual Studio object model (DTE) is not implemented so PowerShell scripts that use unimplemented features will fail.

    Multline PowerShell commands are not currently supported in the console window.

    Information messages, such as successfully installing a package, are not displayed in the console window and only errors are displayed. These messages are only available in the Output window.

    The NuGet PowerShell profile is not currently supported.

    The New-Package, Open-PackagePage, Add-BindingRedirect cmdlets are not currently implemented.

    Feedback

    Please report any issues on the SharpDevelop forum or feel free to send me an email.

  • NuGet Support in SharpDevelop

    SharpDevelop 4.1 now includes support for NuGet. You can now add references to NuGet packages to your projects from SharpDevelop.

    Adding NuGet Packages

    To add a NuGet package reference select your project in the Projects window, right click and select Add Package Reference.

    Add Package Reference menu item

    The Add Package Reference dialog will then be displayed.

    Add Package Reference dialog

    The dialog has four tabs at the top. The Installed tab shows all packages that have been installed for the current project. The Available tab shows all the packages available from the NuGet package repository. The Updates tab shows the packages that have newer versions available. The Recent tab shows packages that were recently installed.

    Select the Available tab to show the packages that can be installed. Information on a package will be displayed on the right hand side when the package is selected.

    To find a package you can either page through the packages by clicking the arrows and page numbers underneath or you can search for a package by name. To search for a package enter the name in the search text box at the top right and press return or click the search icon. The matching packages will then be displayed. To clear the search results remove the search text and run the search again.

    Searching for package references

    To install a package, select it and click the Add button. If the package requires you to accept a license agreement a dialog will be displayed allowing you to accept or decline the agreement.

    Package license agreement window

    After that the package and any dependencies will be installed. Your project will be updated to include new assembly references and source code files from the package. The installed package will now have green tick icon next to it showing that is has been installed.

    NuGet package installed

    Click the Close button to close the Add Package Reference dialog.

    Removing NuGet Packages

    To remove a NuGet package open the Add Package Reference dialog and select the Installed tab.

    Installed packages in the Add Package Reference dialog

    Select the package you want to remove and click the Remove button. The package will then be removed and your project will be updated.

    Updating NuGet Packages

    To update a NuGet package open the Add Package Reference dialog and select the Updates tab.

    Package updates in the Add Package Reference dialog

    Select the package you want to update and click the Add button. The package and its dependencies will then be updated.

    Configuring NuGet

    By default the official NuGet repository will be used when searching for available packages. If you want to set up a different NuGet repository, such as one on your local file system, then select Options from the Tools menu. In the Options dialog select Package Management and then Package Sources.

    Packagement repository configuration

    Here you can add and remove NuGet repositories as required.

    Under the General options you can clear the recent packages and the local package repository cache.

    General Package Management options

    PowerShell Console

    SharpDevelop has a PowerShell console that can be used to install NuGet packages with PowerShell scripts.

    PowerShell console window

    Further information on the PowerShell console can be found in the NuGet PowerShell Console post.

    Posted Jan 23 2011, 02:27 PM by MattWard with 1 comment(s)
    Filed under:
  • NuGet Packages for SharpDevelop

    Now that NuGet 1.0 has been released and the NuGet package submission process has been made much easier there are now NuGet packages for SharpDevelop that can be downloaded from the main NuGet package repository.

    SharpDevelop packages in NuGet Add Package Reference dialog

    The packages currently available are:

    AvalonEdit

    Contains AvalonEdit the WPF-based text editor that is included with SharpDevelop 4.0. Two versions of AvalonEdit are included. One that targets .NET 3.5 and one that targets .NET 4.0. Download this package if you just want the AvalonEdit assembly and nothing else.

    AvalonEdit.Sample

    Contains sample code for AvalonEdit taken from Daniel Grunwald's CodeProject article. The sample code shows how to use the text editor's inside a WPF application including a simple example of code completion.

    To get the sample code working in a WPF application created in Visual Studio 2010 you will need to:

    1. Add references to System.Windows.Forms and WindowsFormsIntegration.
    2. Modify your App.xaml file so the StartupUri points to the AvalonEdit Sample window.

      <Application 
      x:Class="WpfApp.App"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      StartupUri="/AvalonEdit.Sample/Window1.xaml">
      <Application.Resources>
      </Application.Resources>
      </Application>

    ICSharpCode.TextEditor

    Contains the text editor that is included in SharpDevelop 3.2.1. This text editor targets .NET 2.0.

    ICSharpCode.TextEditor.Sample

    Contains sample code for the text editor that is included in SharpDevelop 3.2.1. The code shows how to use the text editor in a Windows Forms application including a simple example of code completion.

     

    Posted Jan 16 2011, 10:42 PM by MattWard with no comments
    Filed under:
  • WPF and Silverlight Templates for IronPython and IronRuby

    SharpDevelop 4.0 now includes templates to create WPF and Silverlight applications for IronRuby and IronPython.

    IronRuby project templates

    The WPF template will create a basic WPF application that loads its main window from disk by using XamlReader.Load and then displays it.

    The Silverlight template will create a basic Silverlight project with an IronPython or IronRuby script file and a web page. The web page (index.html) will open up the IronPython or IronRuby console in the browser and run the script. The script file does not do much apart from change the text in the browser.

    On running the Silverlight project SharpDevelop will launch Chiron and allow you to browse to the project's web page. Chiron is an application that can be used as a personal web server to host your silverlight application. It can also be used to package up your Silverlight application ready for deployment.

    IronRuby silverlight application running in the browser

    All the existing IronPython project templates have also changed. When a new IronPython project is run, by selecting the menu item Debug | Run, it will now run the IronPython console (ipy.exe) instead of starting the project's executable. This change makes IronPython projects consistent with IronRuby projects. It also means you can debug a new IronPython application straight away without having to change the project options.

    To switch back to the previous behaviour, and launch the project's executable instead of ipy.exe, change the Start Action in the project options to Start project. Note that debugging the project's executable is not supported.

    The screenshot below shows the project options for a new IronPython project.

    IronPython project options

    For more information on writing Silverlight applications in IronPython and IronRuby see the following web sites.

    http://ironpython.net/ironpython/browser/

    http://ironruby.net/Browser

     

  • Unit Testing with IronRuby

    SharpDevelop 4 has been updated to support unit testing with IronRuby.

    It uses the Ruby testing framework Test::Unit so you will need to have the Ruby standard library on your machine. IronRuby 1.0 targets Ruby 1.8.6 and includes it in its download so one way to get the Ruby standard library is to download IronRuby from codeplex and install it.

    SharpDevelop then needs to know where the Ruby standard library exists. This can be done by setting the path to the Ruby library in the Options dialog (Tools | Options | Tools | Ruby | Path), as shown below.

    Setting the Ruby standard library path in Tools Options

    Now we need to create some tests. Create two IronRuby projects one to hold the unit tests and the other to hold the code that will be tested.

    In the test project we add the following simple test class that has two tests, one that will pass and one that will fail.

    require 'test/unit' 
    require 'MyClass'

    class MyClassTests < Test::Unit::TestCase
    def test_pass
    myclass = MyClass.new
    assert_equal(1, myclass.return_one(), 'Test should work')
    end

    def test_fail
    myclass = MyClass.new
    assert_equal(2, myclass.return_one(), 'Test should fail')
    end
    end

    Once this class is created you should see the unit tests displayed in the Unit Tests window (View | Tools | Unit Tests).

    IronRuby unit tests in Unit Tests window

    In the other project we create a new class with the following code.

    class MyClass 
    def return_one
    return 1
    end
    end

    Now in the project containing the unit tests we need to add a project reference to the project containing MyClass. This is so that SharpDevelop can set up the load paths correctly allowing MyClass to be found when the unit tests are run.

    Once the project reference is added the unit tests can be run in the normal way by right clicking in the Unit Tests window and selecting Run tests. You can run all the tests in a project, all tests in a class or a single test method.

    IronRuby test results in Unit Tests window

    The output generated when running the unit tests is shown in the Output window.

    IronRuby tests results in Output window

    Test failures are displayed in the Errors window. Clicking an error will open the corresponding code in the editor.

    IronRuby test results in Errors window

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