All posts by admin

Manage your DNS records with PowerShell

In my video course PowerShell 5 Recipes, I used the Dnsimple API as an example of writing PowerShell modules. In the course, I uploaded and made the library available in the PowerShell gallery. Even though it is not feature-complete with respect to the DNSimple API, it is still usable for the core parts of the API.

Getting started

In order to access the Dnsimple API, you need an access token. In order to create one, log in to the web page and generate one under

https://dnsimple.com/a/<account id>/account/access_tokens

For simplicity going forward, create a PowerShell object to hold the account id and the access token:

$account = [pscustomobject]@{Account=27928;AccessToken=(
convertto-securestring 'G2uiIZLhsHNWt4BFNq6Y8VnF1iRz2sB1' -asplaintext -for
ce)}

Then, the next step is to install the module from the PowerShell Gallery, and load it into the current PowerShell instance:

Find-Module DnsimplePS | Install-Module -Scope CurrentUser
Import-Module DnsimplePS

In order to check the available cmdlets, list them:

Get-Command -Module DnsimplePS

Listing, adding and removing Zone records

The simplest thing you can do, is to list the records for your domain:

$account | Get-ZoneRecord -Zone kongs.li

You can also search for records of a certain type (case-sensitive):

$account | Get-ZoneRecord -Zone kongs.li -RecordType MX

Or, you can get a certain record by name

$account | Get-ZoneRecord -Zone kongs.li -Name www

Or, you can match records by prefix using -NameLike:

$account | Get-ZoneRecord -Zone kongs.li -NameLike w

You can also add a record:

$account | Add-ZoneRecord -Zone kongs.li -RecordType URL `
  -Name dnsimple -Content https://dnsimple.com/

And you can delete a record:

$account | Remove-ZoneRecord -Zone kongs.li -Id 11601106

Storing your access token securely

In the getting started section above, I directed you to go to the DNSimple web page to get an access token. This is often not practical in automated scripts, so I provided a couple of cmdlets to store and retrieve an access token from a file, encrypted under the current user’s Windows credentials.

So, when you have retrieved the token from the web page, you can store it securely like so:

Write-AccessToken -AccessToken $t -Account 27928

This will create a file named .dnsimple.tokens next to your $PROFILE. The file will look something like this:


  
    
      Deserialized.System.Collections.Hashtable
      Deserialized.System.Object
    
    
      
        27928
        01000000d08c9ddf0115d1118c7a00c04fc297eb01000000fff8656bc71ed747aa82e30ddd65735a00000000020000000000106600000001000020000000e7dfc8caf9534e51b2e2eb56b6968171ceb6c6ce9c8a7d55193791a207ffc56a000000000e800000000200002000000066c532a677f69c0c478733114d01b4371577340b0051160d95a3728d07c466ca500000005bbf59cee4314675324296591beeadef7970fc4e8589fce2b5bd80c6b5368e5198da424d1554a269921da4f0c6ef02e50db416fe2b7cbe63f187eb91d94d759da11e63121142f7e8794079e1ea74040d40000000d3f2a0be38aaa111ce20eeba05bcabb594e62400658486ed1c4ec2fe027e5d7e0916bc797aba0a0c1325fd7d0043ba9c9754782f695bdafab8a627f2259636f4
      
    
  

If you want to place the file somewhere else, point to it using the -Path parameter.

Extra: URL-shortener

In order to show off PowerShell modules being dependent on other modules, I created a second module that was dependent on the DnsimplePS module. This module has one cmdlet which is a short-hand for the special case I showed above for adding a record.

It creates a URL type record, which is basically a redirect record that allows the creation of short urls.

Example:

$account | Add-ShortUrl -Zone kongs.li -Name dnsimple -Url https://dnsimple.com/

In the same vain, you can delete the url:

$account | Remove-ShortUrl -Zone kongs.li -Name dnsimple

My PowerShell video course is available!

For the last months, I have been working on my PowerShell 5 recipes video course. It is now finally published!

Why?

Why make a video course? – you might ask. I come from a system development background, having worked with many development platforms in my time (Java, .NET, Lotus Notes, JavaScript, etc.) Back in 2011, after resisted for a while, I decided to learn PowerShell. So I dived in, head first. Why? Because I realized that in order to get a better delivery process for software, we need a broader scope than just the development per se. We need to get a holistic view of the environment the applications will run in, and we need to automate the deployment. This has become more and more evident with the coming of DevOps and is key to continuous delivery.

I am first and foremost a PowerShell user, and I do not consider myself an expert. Maybe a little more advanced than the average user, though. When the opportunity came to create a video course, the temptation to do something new to me as too hard to resist. I hope I have been able to keep the view of the user, resulting in a pragmatic, hands-on, course.

For whom?

The course is thought to be a smorgasbord of relevant topics in PowerShell that is relevant to the daily work of developers as well as IT. For people new to PowerShell, it will get you started by installing, and/or upgrading to the latest versions (even on Linux), customize, and set up the environment for your preferences. For developers, it gives you hands-on guidance to set up automated build and deployment. For DevOps (and IT), it guides you in provisioning Azure resources. For more advanced users, it gives you recipes on how to develop reusable scripts, handle modules and publishing your scripts to repositories.

Enjoy!

HTTPS is here

During the last few months, I have written several blog posts in my company’s blog about how to secure a site with HTTPS. I started off talking about how to encrypt an Azure web site with Let’s encrypt, and then continued on to discuss how to try to prevent the browser being tricked into making non-HTTPS requests to the server. Finally, I talked about how to narrow the range of certificate issuers we want the browser to trust for our site in order to prevent ill-behaving issuers to make our site insecure, using so-called certificate pinning.

Quite recently, there has been discussions on how HTTPS is gaining traction, and that HTTPS is becoming the norm. Your web site should use it, too.

Slå opp i ordbøkene fra Powershell

Å bruke kommandolinjen er kjapt. Hvis du ønsker å slå opp i Bokmålsordboka eller Nynorskordboka på nett, kan du nå gjøre det fra Powershell. Slik konfigurerer du dette:

Hvis du ikke har det fra før, installér programvarepakkesystemet Scoop:

iex (new-object net.webclient).downloadstring('https://get.scoop.sh')

Neste steg er å legge til denne kilden til programvare:

scoop install git-with-openssh
scoop bucket add vidars https://github.com/vidarkongsli/vidars-scoop-bucket.git

Dernest installerer du pakken `norskord`:

scoop install norskord

Når du har gjort dette, er du klar! Slik slår du opp i Bokmålsordboka:

bokm omkostning

Tilsvarende kan du søke i Nynorskordboka:

nyn bevegelse

Språk-nerd? Ja.

(Edit: fikset installeringsskript etter innspill fra Discus:@yngvar)

ASP.NET 3.5: improving testability with System.Web.Abstractions

The testability of ASP.NET code has long been a challenge; creating unit tests for your ASP.NET code has been difficult. One of the main points of the new ASP.NET MVC framework has been to make code written for it easily testable. However, not many people know that in ASP.NET 3.5, Microsoft has added a few features to make any ASP.NET applications, not only ASP.NET MVC applications, more easy to test. The System.Web.Abstractions assembly adds a few classes to the System.Web namespace that will help the situation. For instance, looking at the documentation for System.Web.HttpRequestBase, it states that

The HttpRequestBase class is an abstract class that contains the same members as the HttpRequest class. The HttpRequestBase class enables you to create derived classes that are like the HttpRequest class, but that you can customize and that work outside the ASP.NET pipeline. When you perform unit testing, you typically use a derived class to implement members that have customized behavior that fulfills the scenario that you are testing.

Very well. Looking at the documentation for HttpRequest, we see that HttpRequest is not a decendent of HttpRequestBase as one might expect from the name. The reason for this is probably that that would break backwards compatability with older versions of ASP.NET. So, how can we exploit the HttpRequestBase then? The answer is the HttpRequestWrapper class which is a decendant of HttpRequestBase and has a constructor that takes an HttpRequest object as a parameter. Then, we can take the HttpRequest object passed to our code from the framework, wrap it inside an HttpRequestWrapper object and pass it on to our code as a HttpRequestBase object. As I will show you in the examples below, this will enable us to create unit tests of our code by creating fake implementations of ASP.NET framework clases (using Rhino.Mocks).

Example #1: Testing a page codebehind file

Take, for instance, this simple page codebehind code that we would like to test:

using System;
using System.Web;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
    }
}

The first step to take here, is to extract a method which take the request object as a parameter instead of fetching it from a method in a superclass. In general, this is a variation of the dependency injection pattern which in many situations will help us make our code testable (also, see my earlier related post). Like so:

using System.Web;
using System;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        SetCacheablityOfResponse(Response);
    }

    public void SetCacheablityOfResponse(HttpResponse response)
    {
        response.Cache.SetCacheability(HttpCacheability.NoCache);
    }
}

So, then having extracted our code in a separate method, the next step is to change the parameter type of this method from HttpRequest to HttpRequestBase. Furthermore, when calling this method, we need to wrap the HttpRequest object by creating an instance of HttpRequestWrapper. The code, then, looks like this:

<

pre class=”c-sharp” name=”code””>using System.Web;
using System;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
SetCacheablityOfResponse(new HttpResponseWrapper(Response));
}

public void SetCacheablityOfResponse(HttpResponseBase response)
{
    response.Cache.SetCacheability(HttpCacheability.NoCache);
}

}
Having now prepared our code for testing, we can create a unit test where we test the SetCacheabilityOfResponse method:

[TestMethod]
public void ShouldSetNoCacheabilityOnDefaultPage()
{
    _Default page = new _Default();
    MockRepository mocks = new MockRepository();
    HttpResponseBase responseStub = mocks.Stub<HttpResponseBase>();
    HttpCachePolicyBase cachePolicyMock = mocks.CreateMock<HttpCachePolicyBase>();
    With.Mocks(mocks).Expecting(delegate
    {
        SetupResult.For(responseStub.Cache).Return(cachePolicyMock);
        cachePolicyMock.SetCacheability(HttpCacheability.NoCache);
        LastCall.On(cachePolicyMock).Repeat.AtLeastOnce();
    }).Verify(delegate
    {
        page.SetCacheablityOfResponse(responseStub);
    });
}

If you are not familiar with Rhino.Mocks or any other mocking framework, there appears to be a lot going on in that test. The basic idea is that we create derivatives of the -Base classes and pass these to the code that we are going to test, mimicking the behavior of the “real” objects that the framework would pass our code at runtime. Also note that in this particular test we test the side effect of our code, namely that the code should call a the SetCacheability method with a specific parameter. This is achieved using a mock object.

Example #2: Testing an HTTP Handler

Given the following HTTP handler code:

using System;
using System.Web;

public class RedirectAuthenticatedUsersHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.IsAuthenticated)
        {
            context.Server.TransferRequest("/farfaraway");
        }
    }
}

Again, we extract the code we want to test into a separate method, passing it a -Base object and wrap the object passed to us from the framework in a -Wrapper object:

using System;
using System.Web;

public class RedirectAuthenticatedUsersHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        TransferUserIfAuthenticated(new HttpContextWrapper(context));
    }

    public void TransferUserIfAuthenticated(HttpContextBase context)
    {
        if (context.Request.IsAuthenticated)
        {
            context.Server.TransferRequest("/farfaraway");
        }
    }
}

This allows us to create unit tests for the TransferUserIfAuthenticated method, for instance:

[TestMethod]
public void ShouldRedirectAuthenticatedUser()
{
    RedirectAuthenticatedUsersHandler handler = new RedirectAuthenticatedUsersHandler();
    MockRepository mocks = new MockRepository();
    HttpContextBase httpContextStub = mocks.Stub<HttpContextBase>();
    HttpRequestBase httpRequestBaseStub = mocks.Stub<HttpRequestBase>();
    HttpServerUtilityBase httpServerUtilityMock = mocks.CreateMock<HttpServerUtilityBase>();
    With.Mocks(mocks).Expecting(delegate
    {
        SetupResult.For(httpContextStub.Request).Return(httpRequestBaseStub);
        SetupResult.For(httpContextStub.Server).Return(httpServerUtilityMock);
        SetupResult.For(httpRequestBaseStub.IsAuthenticated).Return(true);
        httpServerUtilityMock.TransferRequest("/farfaraway");
        LastCall.On(httpServerUtilityMock).Repeat.AtLeastOnce();
    }).Verify(delegate
    {
        handler.TransferUserIfAuthenticated(httpContextStub);
    });
}

Summary

I have shown two very simple examples on how some of the classes in the System.Web.Abstractions assembly can help us test our ASP.NET code. I have used HttpResponseBase, HttpServerUtilityBase, HttpContextBase, HttpRequestBase, and HttpCachePolicyBase. Note that there are a number of classes available, so if you are faced with not being able to test your ASP.NET code because of dependencies to classes in the framework, take a look in the System.Web namespace and see if there are -Base classes that can help you out.

Testability is a large topic, and there is much to be said about it. I have shown a couple of very simple examples on how to improve testability. Testability has a lot to do with code design as well; in a real world I would write the test before writing the code and I would move my code out of codebehinds. Those topics are discussed a lot elsewere, hopefully this post will bring you a small step further in writing testable code.