8 06, 2015

Undo almost anything in Git

By |June 8th, 2015|Coding|0 Comments

A great blog post on how to undo almost anything in Git:

23 04, 2015

Creating and publishing nuget packages

By |April 23rd, 2015|Coding|0 Comments

Ever since the initial release of Nuget Package Manager in 2010 its helped thousands of .NET developers easily integrate third party libraries into their existing project. It has also helped reduce “DLL hell”. But how do you create one of these packages and publish it to or a private nuget server?

It’s actually very easy. Lets start with a simple real world project.

I have a simple c# solution called “SampleNugetLib” that contains two projects: (C# class library called “SampleNugetLib” and a Test project called “SampleNugetLib.Tests”), our goals are:

  1. Use MSBuild to compile the C# library.
  2. Create/publish nuget package.



Download Sample Project

Make sure to grab a copy of the sample project from my github repo so you can follow along.


Use MSBuild to compile the C# library

Open the file src/_build/build.proj. This is your basic Visual Studio project file. This file was created specifically for compiling and publishing our nuget package. With a help of a powershell script we can create and pass in the parameters such as the solution name, nuget api key and build mode to decouple ourselves from the vs project file.

Everything starts in the root, open the file src/build.ps1, this is your basic powershell script, this will be the file that we execute to get everything started.

Here is the contents of this file:

$project_name = 'SampleNugetLib'
$solution_name = 'SampleNugetLib.sln'
$nuget_packageVersion = '1.0.1'
$nuget_packageName = 'SampleNugetLib'
$nuget_apikey = 'YOUR_API_KEY'
$nuget_server = ''
$build_mode = 'Release' 

    Write-Error "Cannot find build mode"
	# Run MSBuild
	msbuild.exe _build\build.proj `
	    /p:Build_Number=$version `
	    /p:Environment=$env `
	    /p:ProjectName=$project_name `
	    /p:SolutionName=$solution_name `
	    /p:NugetApiKey=$nuget_apikey `
	    /p:NugetServer=$nuget_server `
	    /p:NugetPackageName=$nuget_packageName `
	    /p:NugetPackageVersion=$nuget_packageVersion `
	    /p:ProjectBuildMode=$build_mode `

As you can see we are simply passing along project file and some parameters for msbuild.

Take note: You will need your own API Key ($nuget_apikey), and a unique name for the nuget package ($nuget_packageName) because “SampleNugetLib” already exists under my account (


Create/publish nuget package

Now lets take a closer look at what is going on in src/_build/build.proj. At first glance you can see a property group for all the parameters we are passing in:


Easy enough right? Lets take a look at the target that actually creates the nuget package:

We have a nuget spec file already created at src/_build/BaseNugetSpec.nuspec this contains all the meta data about the nuget package, take a look at the files node, we are including a file called “SampleNugetLib.dll”, lets take a look at the msbuild project to see how it all comes together:

  <Target Name="Clean">
    <!-- Clean up -->
      <FilesToDelete Include="$(Root)\_build\Published\**\*.*" />
      <FilesToDelete Include="$(Root)\_build\Artifacts\**\*.*" />
    <Delete Files="@(FilesToDelete)" ContinueOnError="true" />

    <!-- Ensure directories exists -->
    <MakeDir Directories="$(MSBuildProjectDirectory)\Artifacts" Condition="!Exists('$(MSBuildProjectDirectory)\Artifacts')" />
    <MakeDir Directories="$(MSBuildProjectDirectory)\Published" Condition="!Exists('$(MSBuildProjectDirectory)\Published')" />

  <Target Name="DebugInfo" DependsOnTargets="Clean" AfterTargets="Clean">
    <!-- Diagnostics -->
    <Message Text="Diagnostics:"/>
    <Message Text="Project Build Mode:    $(ProjectBuildMode)" />
    <Message Text="Solution Name:    $(SolutionName)" />
    <Message Text="Project Name:    $(ProjectName)" />
    <Message Text="Build dir:       $(MSBuildProjectDirectory)" />
    <Message Text="Project root:    $(Root)" />
    <Message Text="Nuget Api Key:   $(NugetApiKey)" />
    <Message Text="Nuget Server Url:   $(NugetServer)" />
    <Message Text="Nuget Package Name:   $(NugetPackageName)" />
    <Message Text="Nuget Package Version:   $(NuGetPackageVersion)" />

  <Target Name="BuildSolution" DependsOnTargets="DebugInfo" AfterTargets="DebugInfo">
    <!-- Restore Nuget Packages -->
    <Message Text="Restoring nuget..."/>
    <Exec Command="$(nugetexe) restore $(Root)\$(SolutionName)" />

    <!-- Compile -->
      <ProjectToBuild Include="$(Root)\$(SolutionName)" />
    <MSBuild Projects="@(ProjectToBuild)" Targets="Build" Properties="VisualStudioVersion=$(VisualStudioVersion);Configuration=$(ProjectBuildMode);Platform=Any CPU;OutputPath=$(Root)\_build\Published">
      <Output TaskParameter="TargetOutputs" ItemName="AssembliesBuiltByChildProjects" />
  <Target Name="Build" DependsOnTargets="BuildSolution" AfterTargets="BuildSolution">

    <!-- Add NuGet files-->    
      <NuSpecSourceFile Include="$(Root)\_build\BaseNugetSpec.nuspec" />
      <NuSpecDestinationFiles Include="$(Root)\_build\Published\$(NugetPackageName).nuspec" />
    <Copy SourceFiles="@(NuSpecSourceFile)" DestinationFiles="@(NuSpecDestinationFiles)"/>

    <!-- Replace version in nuspec file -->
    <FileUpdate Files="$(Root)\_build\Published\$(NugetPackageName).nuspec" Regex="0.0.0" ReplacementText="$(NuGetPackageVersion)" />
    <FileUpdate Files="$(Root)\_build\Published\$(NugetPackageName).nuspec" Regex="PID" ReplacementText="$(NugetPackageName)" />

    <!-- Run nuget pack -->
    <Exec Command="$(nugetexe) pack $(Root)\_build\Published\$(NugetPackageName).nuspec -o $(Root)\_build\Artifacts" />

    <!-- Run nuget push -->
    <Exec Command="$(nugetexe) push $(Root)\_build\Artifacts\$(NugetPackageName).$(NuGetPackageVersion).nupkg $(NugetApiKey) -Source $(NugetServer)" />

This is somewhat self explanatory by looking at the target steps:

  • Delete two folders: “Published” and “Artifacts” – The publish folder should hold all your assembly files, the artifacts folder should hold the final file, in this case a nuget package.
  • Recreate these two folders
  • Display some diagnostics information
  • Restore nuget packages for the solution
  • Build the solution and set the output path to the published folder
  • Take a copy of the BaseNugetSpec.nuspec file and place it in the published folder, remember the files node we looked at earlier in the nuspec file? Well now this DLL should be in that published folder as well.
  • Call the “nuget pack” command line, this creates the nuget package (.nupkg)
  • Call the “nuget push” command line, this publishes the newly created nuget package to the nuget server specified in the powershell script.

For more documentation on nuget pack and push command lines take a look here:

Putting it all together

Ok now that we reviewed the process and code, lets execute the powershell script. Please make sure to have msbuild in your PATH variable, see this link for more information:

Open up a windows powershell console, browse to the src folder and run the command:


Easy enough right? Please feel free to submit pull requests to make this code better. I am also available on twitter @tekguy

9 04, 2015

Automating azure powershell cmdlets

By |April 9th, 2015|Coding|0 Comments

Administering your azure subscription via powershell cmdlets is a great option for automating tasks such as starting and stopping vms, downloading blobs, etc. In the past I used the Azure-AddAccount cmdlet to authenticate. This is great but not the best option for scheduling your powershell scripts as it requires you to input your azure login credentials. The best option for automating your scripts is to authenticate via an X509 certificate. There are a couple steps to accomplish this:

  1. Download and install Azure Powershell cmdlets
  2. Generate  X509 cert (management cert) for Azure
  3. Upload the cer file to Azure
  4. Create authenticate powershell script

Lets get started, shall we?

Download and install Azure Powershell cmdlets

Grab the latest version of Azure Powershell cmdlets from:

Generate X509 cert (management cert) for Azure

Fire up Visual Studio 2010 or 2012 command prompt (run as Administrator) and run the following command, change SampleCompany to a name you can recognize:

makecert -sky exchange -r -n "CN=SampleCompany" -pe -a sha1 -len 2048 -ss My "SampleCompany.cer"

Upload the cert file to Azure

Login to your azure account by heading to, browse to Settings on the left side, then click on Management Certificates:


Click on Upload at the button and specify the .cer file you generated in the previous step.

After the certificate has been uploaded, take a note of the thumbprint property, we will use this later.

For more detailed instructions on this step, see this page:

Create authenticate powershell script

Now that we have our generated certificate uploaded to Azure we can go ahead and create a script to authenticate with that certificate. Fire up your favorite text editor and place the following in there:

$ThumbPrint = "<CERT THUMBPRINT>"
$SubscriptionId = "<SUBSCRIPTION ID>"
$SubscriptionName = "<SUBSCRIPTION NAME>"
$myCert = Get-Item cert:\\CurrentUser\My\$ThumbPrint

Set-AzureSubscription -SubscriptionName $SubscriptionName -SubscriptionId $SubscriptionId -Certificate $myCert
Select-AzureSubscription -SubscriptionName $SubscriptionName

Replace the value for the $Thumbprint variable from the information we noted in the previous step.

You can get your subscription id and subscription name from the settings page in Azure as well.

Save the file as “Authenticate.ps1”

In a powershell console, browse to the location where you saved Authenticate.ps1 and run the following command:


Now that you have authenticated, you can run any azure powershell cmdlet such as:


See the Azure Cmdlet reference by browsing to: for a full listing of commands you can now run.

If you have any questions, please feel free to contact me.

10 11, 2014

C# extension method to “prettyify” your xml output

By |November 10th, 2014|Coding|0 Comments

Here is simple c# extension method to format your XML data. This is useful for logging xml data to trace files, etc:

public static class XmlDocumentPrettyExtension
    public static string Prettyify(this XmlDocument xmlDocument)
        var stringWriter = new StringWriter(new StringBuilder());
        var xmlTextWriter = new XmlTextWriter(stringWriter) { Formatting = Formatting.Indented };
        return stringWriter.ToString();
23 10, 2014

Get SqlConnection from DbContext

By |October 23rd, 2014|Coding|0 Comments

I’ve been using Entity Framework for sometime now. But we all know using EF for everything may not be the best option. I decided to use Dapper for certain db queries.

Dapper requires an open SqlConnection object, I didn’t want to have to manage another connection string in my web.config so I looked at options for converting an EF connection string to an ADO connection string.

After some research I came up with the following:

private SqlConnection GetSqlConnection(DbContext dbContext)
    var ec = dbContext.Database.Connection;
    var adoConnStr = ec.ConnectionString;
    return new SqlConnection(adoConnStr);
6 08, 2014

Creating aliases in git

By |August 6th, 2014|Coding|0 Comments

If you are like me and use git bash, powershell cmd or some other command line utility for git you quickly learn there is a lot of keystrokes to do repetitive tasks. Creating aliases in git is a convenient way to minimize the amount of keystrokes you will have to make. Here are some alias I have setup that I use on a daily basis:

Alias Name Configuration Setup Example Usage Description
git b git config –global alias.b branch git b master Allows you to easily switch branches
git co git config –global checkout git co new_feature Checkout a new branch
git undo git config –global alias.undo “reset HEAD~1 –mixed” git undo Undo the last commit.

Each time you create an alias you are adding it to one of 3 config files: local, system and global. In the examples above I add it to the global config file. To learn more about these config files take a look here: git-config

24 07, 2014

Opinionated AngularJS styleguide for teams

By |July 24th, 2014|Coding|0 Comments

Excellent article explaining different styles of writing angularjs modules, controllers:

16 07, 2014

Using Azure Powershell to start and stop a VM

By |July 16th, 2014|Coding|0 Comments

Using an Azure VM is a convenient way to test new software without having to corrupt your own terminal or using more resources for a virtual instance using Virtual Box, VMWare, etc.

As you may already know if a VM is stopped there are no charges for computing cost. However you will still incur a charge for the storage used by the VM (which is significantly less). Using a powershell script to manage the state of these VMs are helpful. I have the shutdown powershell script on a scheduler that runs nightly.

In order to use azure powershell you must do the following:

  • Install Azure PowerShell.
  • Connect to your subscription within Azure Powershell

Fortunately Microsoft has documented this process in an article located at:

After installing feel free to try the following code (make sure to replace “MY_COMPUTER” with the name of your VM:

Start-AzureVM -ServiceName "MY_COMPUTER" -Name "MY_COMPUTER"

Stop-AzureVM -ServiceName "MY_COMPUTER" -Name "MY_COMPUTER" -Force
8 07, 2014

Generating a certificate and private key using openssl

By |July 8th, 2014|Coding|0 Comments

Sometimes you need to generate a quick certificate to test your app. Using openssl you can easily accomplish this, take a look at my example below:

# Generate Cert and Key in seperate file
# Provide the .cert to the end user
openssl req -new -newkey rsa:1024 -days 365 -nodes -x509 -keyout QA.key -out QA.cert
# Merge cert and private key to make a p12 file, this file will be used by .NET's X509Certificate2 class, The private key will be accessible via the "PrivateKey" property
openssl pkcs12 -export -in qa.cert -inkey qa.key -out qa.p12 -name "QA"

Got a question? Send me a message on twitter: @tekguy

5 07, 2014

Logging off WS-Federation by creating a wsignout1.0 message

By |July 5th, 2014|Coding|0 Comments

Recently I integrated my web app with Azure ACS but was having a difficult time signing out of ACS (deleting my cookie off the server). The following code will create a wsignout1.0 message. Essentially it will construct a url with the action parameter set to “wsignout1.0”. An additional parameter “wreply” allows you to specify a url to redirect to after you have been signed out:

public ActionResult LogOff()
    // Load Identity Configuration
    FederationConfiguration config = FederatedAuthentication.FederationConfiguration;
    // Get wtrealm from WsFederationConfiguation Section
    string wtrealm = config.WsFederationConfiguration.Realm;
    string wreply;
    // Construct wreply value from wtrealm (This will be the return URL to your app)
    wreply = wtrealm;
    // Read the ACS Ws-Federation endpoint from web.Config
    // something like "https://<your-namespace>"
    string wsFederationEndpoint = ConfigurationManager.AppSettings["ida:Issuer"];
    SignOutRequestMessage signoutRequestMessage = new SignOutRequestMessage(new Uri(wsFederationEndpoint));
    signoutRequestMessage.Parameters.Add("wreply", wreply);
    signoutRequestMessage.Parameters.Add("wtrealm", wtrealm);
    string signoutUrl = signoutRequestMessage.WriteQueryString();
    return this.Redirect(signoutUrl);

Got a question? Send me a message on twitter: @tekguy