Coding Guidleines – how do you do yours?

StyleCopLogoHaving looked at different code bases this past 3 weeks, one thing springs to mind, if you use StyleCop use it in a way where all projects are consistent, no point having only a few rules if the code base can compile but look entirely different project to project, be much nicer for a new start to open up 3 or 4 solutions and they all look fairly similar in layout, same naming conventions etc.

What I am getting it really is if you have coding standards how do you enforce them?, oh such a strong words brings terror to co-workers opinions on writing code, but with a little bit of discipline you may be surprised when you look at someone else’s project and the code looks very similar to yours as they are sharing the teams ReSharper and StyleCop settings.

Here is a list of a few things which I think can improve code quality

  • Remove all use of regions
  • If you have coding guidelines – use tools to enforce them otherwise what’s the point
  • Put Using statements in alphabetical order at the top of the file
  • Naming conventions for your code/test projects – check these in code reviews.

So does your company have coding standards?, and if so how do you go about implementing them?, are they enforced? if not why not? – no need to piss developers off, in time they should see the light and you can shape your StyleCop rules etc. to fit.

I still bet out in the wild many teams have a coding standards guide yet they don’t enforce it other than the odd glance if your lucky.

Octopus Deploy – my wishlist

Tags

OD First of all I’ve been using Octopus Deploy for a couple of months maybe less, and to be honest its freaking awesome, its easy to set up, easy to use, has an awesome API and is just a really well thought out piece of software.

Having used it I have one or two minor little things I’d love to see in the next version, I could go off and find out if there in the uservoice system for Octopus but I like giving credit where credits due so mentioning Octopus Deploy in another blog post is never a problem, anyone I talk to who I don’t work with currently, I always try to get them to go off and take a look at Octopus Deploy.

Moving on here is my wish list for the next version of Octopus, some of them may already be done, may not be an issue, might even just be pilot error from myself but any hoo here goes, off the top of my head.

  • Ability to make a step disabled I know a workaround is to create a dummy environment and set the task to this which will be ignored but disabling steps would be great.
  • Export settings option to be able to export all of the variables.
  • Variables, be able to go back and time and see the variables held against a specific release at on the date and time it was released at.
  • Email Template that you can use to send out which allow variables, this can be used across all projects.
  • Automated releases for doing out of hours releases, this options hard to find.
  • Automated releases which have the option to ignore manual step, so we can release to production out of hours without having to still accept the manual step we normally have
    for production.
  • Backups, when you take a backup have the ability to restore it and not lose all of the packages you had originally – this isn’t huge but a bit of a shock when I restored and we had no packages.
    • I will add more if I come across any but to be very fair this is all pretty much nice to have options.

      By the way did you check our the api for Octopus Deploy in case I haven’t mentioned it before – real nice work!

Squirrel – replace ClickOnce the easy way

Tags

Last week I was taking a look at Squirrel which states

Squirrel: It’s like ClickOnce but Works™

The goal of me looking at Squirrel was to find a decent replacement to ClickOnce, I read a tweet from @paulcbetts mentioning his work and how he had created Squirrel as a replacement to using ClickOnce.

Having spent some time implementing this and coming across one or two issues which I overcame, the good news is ClickOnce is hopefully no longer needed.

Squirrel works and does exactly what we require, our windows forms application’s can have a ‘check for updates’ option, which updates to the latest release, close the old application down after its updated, re-open from the original desktop or start menu shortcut and your done.

Steps to get Squirrel working

  1. Sourcecode is on GitHub.
  2. Create a simple Windows Forms Application
  3. Add the nuget package called squirrel.windows nugetinstalllike so:-
  4. Add the following to the program.cs like so (line 19 is the only one I added) :-
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    using Squirrel;
    
    namespace WindowsFormsApplication1
    {
        static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                SquirrelAwareApp.HandleEvents(onAppUpdate: Form1.OnAppUpdate, 
                onAppUninstall: Form1.OnAppUninstall, 
                onInitialInstall: Form1.OnInitialInstall); 
                
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
    }
    
  5. Add some content like a simple button or a menu with the choice to check for updates
  6. in the code behind we implement squirrel like so:-
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    using System.Configuration;
    using Squirrel;
    using System.Reflection;
    using System.IO;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            private const ShortcutLocation DefaultLocations = ShortcutLocation.StartMenu 
           | ShortcutLocation.Desktop; 
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
            {
                // Check for Squirrel Updates
                var t = UpdateApp();
            }
    
            public async Task UpdateApp()
            {
                var updatePath = ConfigurationManager.AppSettings["UpdatePathFolder"];
                var packageId = ConfigurationManager.AppSettings["PackageID"];
    
                using (var mgr = new UpdateManager(updatePath, packageId, FrameworkVersion.Net45))
                {
                    var updates = await mgr.CheckForUpdate();
                    if (updates.ReleasesToApply.Any())
                    {
                        var lastVersion = updates.ReleasesToApply.OrderBy(x => x.Version).Last();
                        await mgr.DownloadReleases(new[] { lastVersion });
                        await mgr.ApplyReleases(updates);
                        await mgr.UpdateApp();
    
                        MessageBox.Show("The application has been updated - please close and restart.");
                    }
                    else
                    {
                        MessageBox.Show("No Updates are available at this time.");
                    }
                }
            }
    
            public static void OnAppUpdate(Version version)
            {
                // Could use this to do stuff here too.
            }
    
            public static void OnInitialInstall(Version version)
            {
                var exePath = Assembly.GetEntryAssembly().Location;
                string appName = Path.GetFileName(exePath);
    
                var updatePath = ConfigurationManager.AppSettings["UpdatePathFolder"];
                var packageId = ConfigurationManager.AppSettings["PackageID"];
    
                using (var mgr = new UpdateManager(updatePath, packageId, FrameworkVersion.Net45))
                {
    
                    // Create Desktop and Start Menu shortcuts
                    mgr.CreateShortcutsForExecutable(appName, DefaultLocations, false);
                }
            }
    
            public static void OnAppUninstall(Version version)
            {
                var exePath = Assembly.GetEntryAssembly().Location;
                string appName = Path.GetFileName(exePath);
    
                var updatePath = ConfigurationManager.AppSettings["UpdatePathFolder"];
                var packageId = ConfigurationManager.AppSettings["PackageID"];
    
                using (var mgr = new UpdateManager(updatePath, packageId, FrameworkVersion.Net45))
                {
                    // Remove Desktop and Start Menu shortcuts
                    mgr.RemoveShortcutsForExecutable(appName, DefaultLocations);
                }
            }
        }
    }
    
  7. We now need to create a .nuspec file which we will use to package up our application, Squirrel needs to have every file within the lib\net45 folder.

    To create a .nuspec file I simply copied nuget.exe into the solution and then went to a command prompt and typed:- nuget spec, this creates a .nuspec file which we can then hand edit inside Visual Studio and looks like this:-

    <?xml version="1.0"?>
    <package >
      <metadata>
        <id>WindowsFormsAppliation1</id>
        <version>1.0.0.0</version>
        <authors>Gregor Suttie</authors>
        <title>WindowsFormsAppliation1 Squirrel Tester</title>
        <description>Testing out Squirrel</description>
        <requireLicenseAcceptance>false</requireLicenseAcceptance>
        <releaseNotes>None</releaseNotes>
        <copyright>Copyright 2015</copyright>
      </metadata>
      <files>
        <file src="bin\Debug\*.*" target="lib\net45\"></file>
      </files>
    </package>
    
  8. Next we need to pack the .nuspec file to generate the nuget package, so run the following:-
    Nuget pack WindowsFormsApplication1.nuspec
  9. From the package manager console inside Visual Studio we now need to run the following command:-

    squirrel –releasify C:\Squirrel\WindowsFormsApplication1\WindowsFormsApplication1\WindowsFormsApplication1.1.0.0.0.nupkg

  10. In the folder above we should now have a folder called Releases, containing a setup.exe which we use to install the application.
  11. Run setup.exe and your app will install with shortcuts on the desktop and the start menu if you use the code above which has defined these as shortcut options.
  12. If you then run check for updates, the code will go off and check the folder you specify in the app.config like so:-
    <add key="UpdatePathFolder" value="c:\updatesForMyApp\"/>
    
  13. In order to update our app we also need the following appsetting which is the id of the Nuget package we created earlier, be careful not to have the id with a space or a dot (.) within the Nuget package Id.:-
    <add key="PackageID" value="WindowsFormsApplication1"/>
    
  14. Also add this one line to the assmblyinfo.cs:-
    [assembly: AssemblyMetadata("SquirrelAwareVersion", "1")]
    
  15. Once you install the application, go back and make a change to the code, save it, update the .nuspec file version number from 1.0.0 to 1.0.1 and then redo steps 7 and 8 (with the path to the new WindowsFormsApplication1.1.0.0.1.nupkg file)
  16. Almost done, copy the content of the releases folder to our location where we store the updates (our app.config setting for UpdatePathFolder which was set to c:\updatesForMyApp\)
  17. Run the app and choose the menu option ‘Check for Updates’ and you’ll get the latest version.
  18. Also note of you add a Debugger.Launch() statement in the code you can debug the code and step through line by line.

To find out more about further options available and much more about Squirrel click here.

One week using Octopus Deploy

Tags

ODSo its been a one week of using Octopus Deploy for me and its fair to say I am impressed.

API
Octopus deploy was written API-first with the UI built on top, this mean that anything you need to do or access can be done either from the command line or from the available Nuget package, documentation for the API is also great and is up on github here.

Documentation
The documentation is very thorough, don’t think I have managed to come across anything which hasn’t either been covered or discussed via the support forums which have plenty of detail.

Blue/Green Deployment
One necessity at work for us is repeatable automated deployments, we currently have this already as I’ve mentioned before with MSBuild scripts and use of TeamCity for the builds. The idea of Blue/Green deployments is something we need for our external facing website at work and is a major plus point with Octopus Deploy, we can build our release version of the website and publish this internally for testing purposes and then switch this to production in an instant, this way we know our production environment includes the latest fixes/changes and has been tested by our QA department.

The documentation for OD covers Blue-green deployments and this along with Scheduled Deployments make the case for using Octopus Deploy a strong one.

Why you should look at Octopus Deploy
I have spent a week trying out different kinds of project deployment, as per previous post as well as testing out deploying an internal .Net website, its been pretty much very straight-forward, it handles web.config transforms, app.config transforms and even substituting variables held within OD for settings in both app.configs and web.configs (connection strings, NLog settings etc.).

Scheduled deployments, Blue/Green deployments are a big selling point to us, on top of that a well written API with good documentation (which uses confluence which is also nice) makes it an easy sell – I am fairly sure we will be changing our deployment strategy to use this going forward and I am happy about that.

One last very nice thing is the sharing of PowerShell scripts which means you can make use of existing scripts, write new ones and share them with the community up on github and help make OD even better – version 3.0 also looks like it will bring even more good stuff to the mix when that is released in the coming months.

I hope to look at deploying database’s using Octopus Deploy at some point fairly soon.

So take a look at Octopus Deploy and I’m sure you wont be disappointed! – that’s all for now.

Giving Octopus Deploy a Test Drive

Tags

OD
The last couple of days I have been taking Octopus Deploy for a spin, we have been working on a new project and I have been tasked with using Octopus Deploy to see how easy it would be to deploy our application to our Development, Staging and Production environments.

The application itself isn’t really import but its a TopShelf Web Service running on Katana which includes the use of certificates, url acl’s, MSMQ and some RavenDB for good measure.

Current Setup
Our current deployment setup makes use of Teamcity and MSBuild to deploy our applications, making use of a set of standard .proj files we use to deploy all types of applications, we have it down to 1 click deployments, which covers:-

  • Checkout from Source Control
  • Inspections
  • Compile/Build
  • Unit Tests / Integration Tests
  • Deploy

Change to our process
With Octopus Deploy (calling it OD from here on in) I changed this slightly removing the Deploy step above from our MSBuild script and looked into how to deploy the code using OD.

OD takes your code and bundles into a nuget Package using a tool called OcotPack, an add-on for Visual Studio as well as an executable which looks at your code and figures out what’s needed to package your code into a Nuget package. Once you have your Nuget package you put that into your Nuget feed, either your own or using OD’s in built Nuget feed (very handy and much quicker to use) and then you create a Release based on the nuget package, steps outlined below for clarification:-

  • Run OctoPack on project you wish to Deploy, this creates you a Nuget package
  • Copy your nuget package to Nuget Feed (even has an option to do that for you)
  • Create a Release pointing to your package
  • Deploy to chosen environment
  • Job done

I will be covering more on Octopus Deploy but so far I have managed to deploy the application in question to Development and Staging, register URLACL’s, register the Certificate, create our private message queues, and install and start the Katana based Top Shelf Service in 2 days worth of work from having really no idea about how Octopus Deploy works, fair to say I like what I see and so far so good! – Oh and the documentation and sample videos are excellent – more coming soon on my use of OD, if your deployments aren’t using Octopus Deploy I recommend you take some time and take a look, its been well thought out with a REST API and the UI built on top of that, it allows you to run custom PowerShell scripts which I really like and in general looks like a good addition to our tools belt.

Nuget bug I ran into with solution level packages and dependencies

nugetIf your using nuget and have a solution level nuget package you wish to add to a project, install-package will install your package as suggested, however update-package wont work as it wont find the nuget package your trying to update, this is only the case if the solution level package contains any dependencies, remove your dependencies and update-package does work.

This appears to be a bug, the obvious way to get around it is to use uninstall-package then install-package but its a bug none the less, I spent some time trying to get around this.

I was hoping this would have been fixed in nuget version 2.8 but it hasn’t been as yet.

Issue I ran into when using Nuget/SlowCheetah

Tags

,

nugetCannot add part to the package. Part names cannot be derived from another part name by appending segments to it

Last week I ran into an issue where I was using nuget to package a .csproj file.
What I was after was the contents of the nuget package to contain a Content folder and inside this Content folder have one file called app.config.transform, that’s it.

If my .csproj file contained the following:-

<PropertyGroup Label="SlowCheetah">
    <SlowCheetahTargets>..\.shared\SlowCheetah.Transforms.targets</SlowCheetahTargets>
  </PropertyGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(SlowCheetahTargets)" Condition="Exists('$(SlowCheetahTargets)')" Label="SlowCheetah" />

Then the package contents had a single file called content – which is incorrect.

The way I fixed this was inside the .csproj file I changed the type of the app.config.transform from Content to None. I then changed my .nuspec file to have the following:-

<files>
    <file src="App.config.transform" target="Content" />
</files>

This fixed my issue with the contents of my nuget package, just incase anyone runs into the same issue.

Nuget Packages – solution level versus project level

nugetI’ve recently been working on a number of projects/solutions which contain nuget packages, one of the requirements I had been given was to add a nuget package which I had created at a solution level instead of it being at project level.

This means just that, the package is for the project solution and not for a particular project within the solution. If you’re still not sure what I mean let me explain with an example to better illustrate.

If you create an empty console application and add the nuget package called xunit runners:-

xunit.runners2

This will add the package at the solution level rather than to the consoleapplication1 project as shown below:-

xunit.runners3

Contrast this will a package level nuget package such as NUnit which is a project level nuget package:-

xunit.runners4

If you need to create a solution level nuget package then here is what I have found so far:-

  • Don’t reference a version of the framework within your Nuspec file
  • Don’t reference any dll’s

If you do either then you’ll end up with a project level nuget package.

There is more information on this here.

Learning PowerShell – Using PowerShell Community Extensions

Tags

ps The PowerShell Community Extensions are a set of additional cmdlets, providers, functions and scripts which the community asked for and have been written for us to use and take advantage of.

Once you download PSCX you’ll want to add this module to something called your PowerShell Module path, this is the place you’d normally put your PowerShell Modules so that you can import them for using in your scripts. To check what your PowerShell Module path is from within PowerShell type:-

$env:PSModulePath

Add PSCX to your $env:PSModulePath so you can import it and use it anytime you start using PowerShell, to add PSCX type the following:-

$env:PSModulePath = $env:PSModulePath + “;C:\Program Files (x86)\PowerShell Community Extensions\Pscx3\;”

the last part should be where you chose to install PSCX.

Ok so no we have this added to our PowerShell Module path lets see if we can start using it.

To check what PowerShell modules are already imported type:-

Get-Module

The screen shot below shows me which modules have been imported:-

get-module

To add PSCX you need to import the module, so lets do that by typing:-

Import-Module PSCX

And that’s it we can call any of the PSCX cmdlets from our scripts, the list of which are extensive and include:-

Write-Zip
Format-XML
Get-XML
UnBlock-File

and many more

Hopefully this is enough to whet your appetite.

Learn PowerShell – Piping

Tags

Piping in PowerShell is awesomesauce and best explained by some examples, but firstly a quick explanation of piping, lets say we want to get a list of files from the c:\windows folder on your machine, order them by the last modified date and select the first 50 files and output the list to a text file in the current folder, simple requirements and here it is:-

Set-Location c:\windows
Get-ChildItem | Sort-Object LastWriteTime -Descending | Select-Object -First 50| Out-File files.txt

  • Set-Location is the cmdlet which is roughly the equivalent to the cd command found in a command prompt.
  • Get-ChiLdItem is the cmdlet which is roughly the equivalent to the dir command found in a command prompt, but you can use it with objects, lists and so on.
  • Sort-Object is the cmdlet to sort obviously and can be used against your objects, lists and much more.
  • Select-Object tis the cmdlet to select a number of objects (files, records, results), you can use this with -first, -last, -skip and much more
  • Out-File will is the cmdlet to simply write output to a file.

Obviously a very simple example but you take A pass the results to B, B then does work on it, passes it to C and you got the idea. This is a how piping works and can yield the data your looking for quickly and in very little code indeed.

PowerShell Blog Posts

Follow

Get every new post delivered to your Inbox.

Join 28 other followers