Coding

Visual Studio 2017 Preview 3 is out

Preview 3 of Visual Studio 2017 is out, learn more about this update at: https://www.visualstudio.com/en-us/news/releasenotes/vs2017-preview-relnotes

By |June 27th, 2017|Coding|0 Comments

What’s new in Microsoft Visual Studio 2017

Here is an excellent poster to find out what’s new in Visual Studio 2017:

 

(source: https://blogs.msdn.microsoft.com/visualstudio/2017/03/13/visual-studio-2017-poster)

By |March 13th, 2017|Coding|0 Comments

Setting up Redis on a windows server and testing connectivity

In this post I will show you how to install redis on windows and test for connectivity.

 

Installation

Download the latest release at https://github.com/MSOpenTech/redis/releases

Perform the installation, leave everything as default. By default, redis should already configure your windows firewall to allow communication with the redis-server.exe file, redis server runs on port 6379 so make sure that port is opened on hardware firewalls, etc.

Configuration

After the installation is complete, a window service called “Redis” is created, this is your redis server.

Browse to the installation path, on my setup this was C:\Program Files\Redis

Open the file redis.windows-service.conf NOT redis.windows.conf

We want to make a couple changes to secure the server with a password and set the ip address binding:

  • Setting Password: Search for the word “requirepass”, this was on line 445 in my configuration file, uncomment and set a proper password, something strong.
  • Setting IP Address binding: By default it seems the redis server is configured to only work locally, because of the one binding to the loopback interface address, you should see a line “bind 127.0.0.1”, make sure to comment this, by doing so your redis server will be bound to all ip addresses on the server.

After making these changes, restart your Redis service and check the log file server_log.txt for error, you should see something like:

“[5676] 10 Sep 09:38:35.358 * The server is now ready to accept connections on port 6379”

Testing Remote Connectivity

After installing you may want to test your remote connectivity to the redis server.

Grab a copy of redis-cli.exe in the installation folder and place on another computer to test.

I then opened a command prompt and went to that folder where redis-cli.exe was placed and issued the command:

.\redis-cli.exe -h MYSERVER.COM -a MY_SECURE_PASSWORD

 

I hope this helps! If you have any questions feel free to contact me on twitter: @tekguy

By |September 10th, 2016|Coding|0 Comments

The definitive guide to form based web authentication

If you are using form based authentication, here is a great stack overflow post that provides some guidelines on how to implement form based authentication properly: http://stackoverflow.com/questions/549/the-definitive-guide-to-form-based-website-authentication

By |July 22nd, 2016|Coding|0 Comments

OWIN WsFederation custom authentication and authorization

I recently setup OWIN WsFederation in my app, but I needed a way to perform an additional check against my local database to validate the user. For example the user authenticating from the STS may not be allowed to authenticate to the app, because of their department, etc. So in order to perform this additional authorization check I needed to setup a “notification”. In this case the notification is called “SecurityTokenValidated”, here is a sample implementation:

app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
    {
    Wtrealm = AppSettings.IdpRealm,
    MetadataAddress = AppSettings.IdpMetadata,                 

    Notifications = new WsFederationAuthenticationNotifications
    {
        // check and create additional claims
        SecurityTokenValidated = notification =>
        {
            // identity object to access claims from IDP
            var identity = notification.AuthenticationTicket.Identity;
            
            return Task.FromResult(null);
        }
    }
});
					
					
By |June 20th, 2016|Coding|0 Comments

My experience at Build 2016

Now that Build is over I had some time to reflect on the experience. This was my first time at a major developer conference. I’d like to thank my employer for sending me to this awesome event. The theme at this conference has been creating a better developer experience. If you haven’t seen the videos I encourage you to take a look at: https://channel9.msdn.com/events/build/2016

Some of the key announcements at this event:

  • Bash on Windows: This is incredible news. It’s not a full linux system, it’s not a VM, it’s 100% native. You get all the great dev tools that’s on Linux such as awk, grep. Launch vim (or emacs), imagine the ability to launch a bash command and use apt-get.
  • Xamarin is now free: That’s right, 100% free. For all versions of Visual Studio 2015, even community edition.
  • Windows Anniversary edition: Bio-metric security integration for apps and edge, Ink improvements

My favorite sessions:

Introducing ASP.NET Core 1.0: A breif overview of things to come in .NET Core 1.0. Hanselman did a live demo showing off the power of ASP.NET Core, running on docker containers on Azure, AWS, etc.


Power BI Embedded: You now have the ability to integrate Power BI directly into your apps, for some sample code click here.

As I have time I will continue to update this list.

 

 

By |April 2nd, 2016|Coding|0 Comments

Setting the time zone for an azure web app

If you need to set the timezone for your azure web app, you now have an option to create an app setting. You can do this via the azure portal:

Click on “Application Settings” then add a new key/value under the app settings section, for example:

Key: WEBSITE_TIME_ZONE

Value: Eastern Standard Time

2015-11-23_2051

 

By |November 24th, 2015|Coding|0 Comments

Undo almost anything in Git

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

 

https://github.com/blog/2019-how-to-undo-almost-anything-with-git

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

Creating and publishing nuget packages

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 Nuget.org 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

Download Sample Project

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

Download

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 = 'https://www.nuget.org/api/v2/package'
$build_mode = 'Release' 

if(!$build_mode){
    Write-Error "Cannot find build mode"
}else{
	# 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 `
	    /ToolsVersion:12.0
}

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 nuget.org account (https://www.nuget.org/packages/SampleNugetLib).

 

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:

  <PropertyGroup>
    <Root>$(MSBuildStartupDirectory)</Root>
    <nugetexe>$(Root)\_build\lib\nuget\nuget.exe</nugetexe>
    <ProjectBuildMode></ProjectBuildMode>
    <NuGetPackageVersion></NuGetPackageVersion>
    <ProjectName></ProjectName>
    <SolutionName></SolutionName>
    <VisualStudioVersion>12.0</VisualStudioVersion>
    <NugetApiKey></NugetApiKey>
    <NugetServer></NugetServer>
    <NugetPackageName></NugetPackageName>
  </PropertyGroup>

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 -->
    <ItemGroup>
      <FilesToDelete Include="$(Root)\_build\Published\**\*.*" />
      <FilesToDelete Include="$(Root)\_build\Artifacts\**\*.*" />
    </ItemGroup>
    <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>

  <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>

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

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

    <!-- Add NuGet files-->    
    <ItemGroup>
      <NuSpecSourceFile Include="$(Root)\_build\BaseNugetSpec.nuspec" />
    </ItemGroup>
    <ItemGroup>
      <NuSpecDestinationFiles Include="$(Root)\_build\Published\$(NugetPackageName).nuspec" />
    </ItemGroup>
    <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)" />
  </Target>
</Project>

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: https://docs.nuget.org/consume/command-line-reference

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: http://stackoverflow.com/questions/6319274/how-do-i-run-msbuild-from-the-command-line-using-windows-sdk-7-1

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

.\build.ps1

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

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

Automating azure powershell cmdlets

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: http://azure.microsoft.com/en-us/downloads/

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 http://manage.windowsazure.com, browse to Settings on the left side, then click on Management Certificates:

2015-04-09_1107

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: https://msdn.microsoft.com/en-us/library/azure/gg551722.aspx

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:

.\Authenticate.ps1

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

Get-AzureWebsite

See the Azure Cmdlet reference by browsing to: https://msdn.microsoft.com/en-us/library/azure/jj554330.aspx for a full listing of commands you can now run.

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

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