Friday, 14 January 2011

IIS7 and WCF MIME types

Problem

I needed to deploy a WCF service to IIS7 running on windows server 2008. The service was accessed via a .svc file but upon calling it from a browser an error was reported stating that the .svc extension was not recognised.

Solution

The solution was to reregister the WCF Service Model with IIS by running ServiceModelReg.exe:

"%windir%\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe" -r -y

The flags used were:

Flag Description
-r Re-registers this version of WCF and updates scriptmaps at the IIS metabase root and for all scriptmaps under the root. Existing scriptmaps are upgraded to this version regardless of the original versions.
-y Do not ask for confirmation before registering or re-registering components.

After reregistering the WCF Service Model the .svc extension was correctly installed. Note that IIS7 did not require a restart.

Full details of ServiceModelReg.exe and all its flags can be found here: ServiceModel Registration Tool (ServiceModelReg.exe)

Friday, 14 January 2011,

Generating temp SSL certificates for development

Update 01/03/2014

If you’re using IIS 7 there is a quick way to create self-signed certificates. Details can be found in this post: Create a self-signed certificate for development in IIS 7.

If you still want to know about the manual method read on.

Original post

I needed to generate an SSL certificate for testing a WCF service which needed to be secure. Not wanting (or having the budget for) a real SSL certificate I elected to generate my own. The following batch file contains the main ingredients:

@echo off

echo Step 1 - Creating a self-signed root authority certificate and export the private key.
echo You will be prompted to provide a password to protect the private key.
echo The password is required when creating a certificate signed by the root certificate.
echo ===================================================================================
makecert -n "CN=RootTempCA" -r -sv RootTempCA.pvk RootTempCA.cer

echo Step 2 - Create a new certificate signed by a root authority certificate
echo ========================================================================
makecert -sk domain.to.secure -iv RootTempCA.pvk -n "CN=domain.to.secure" -ic RootTempCA.cer -sr localmachine -ss my -sky exchange -pe

The domain.to.secure should be replaced to match the environment (this could be localhost, the machine name, whatever you need). Step 2 should install the certificate into the certificate store – no need to do it manually.

The makecert flags used above breakdown as follows:

Flag Step Description
-n subjectname 1, 2

Specifies the subject name. The convention is to prefix the subject name with "CN = " for "Common Name".

-r 1

Specifies that the certificate will be self-signed.

-sv privateKeyFile 1

Specifies the file that contains the private key container.

-sk subjectKey 2

The location of the subject's key container that holds the private key. If a key container does not exist, one is created. If neither of the -sk or -sv options is used, a key container called JoeSoft is created by default.

-iv issuerKeyFile 2

Specifies the issuer's private key file.

-ic issuerCertFile 2 Specifies the location of the issuer's certificate.
-sr location 2

Specifies the subject's certificate store location. location can be either currentuser (the default) or localmachine.

-ss store 2

Specifies the subject's certificate store name that stores the output certificate.

-sky keytype 2

Specifies the subject's key type, which must be one of the following: signature (which indicates that the key is used for a digital signature), exchange (which indicates that the key is used for key encryption and key exchange), or an integer that represents a provider type. By default, you can pass 1 for an exchange key or 2 for a signature key.

-pe 2

Marks the generated private key as exportable. This allows the private key to be included in the certificate.

Because this process creates a self-signed certificate if you access the service from a remote machine you will likely run in to problems because the certificate was issued by an unknown Certification Authority. To get around this you need to import the root certificate into the trusted root certificate store on the client machine. I find it best to import the certificate using a Personal Information Exchange (pfx) file. To create the .pfx run the following:

pvk2pfx.exe -pvk RootTempCA.pvk -spc RootTempCA.cer -pfx RootTempCA.pfx -po password_here

References

 

See also

Thursday, 13 January 2011

Creating shortcuts to Remote Desktop to a specific machine

I like using Launchy to open and close applications. This includes opening Remote Desktop but it’s nice to be able to jump straight to a Remote Desktop session on a particular machine by simply typing the machine name into Launchy.

The way I do this is:

  1. Create a folder under C:\Documents and Settings\<username>\Start Menu\Programs\ called Shortcuts.
  2. Add this folder to the Launch catalog using the Launchy options dialog.
  3. Create a new shortcut in the new folder.
  4. For the ‘Location of the item’ type %windir%\system32\MSTSC.EXE /v:MACHINE_NAME where MACHINE_NAME is replaced with the name of the machine you want to Remote Desktop to.
  5. For the name of the shortcut use the machine name.
  6. Save the shortcut and get Launchy to rescan its catalog.

 

untitled

Untitled2


Now, by tying the machine name into Launchy you can immediately open a Remote Desktop session to the machine.

Untitled3

NUnit tests being ignored

Problem

I created a test assembly and added NUnit test fixtures to it. Everything was proceeding nicely until I added an App.config file to the test project. Thereafter, I could not run any of the tests with the ReSharper test runner which reported that each test was being ignored.

untitled

I also found it was impossible to add the test assembly to the Gallio test runner.

Solution

The problem was that I had accidentally created a badly formatted App.config file (I had forgotten to wrap <add/> elements in an <appSettings/> element). Correcting this error allowed all tests to run normally. The incorrectly formatted App.config file looked something like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <add key="SomeKey" value="SomeValue" />
</configuration>

The corrected version looked something like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="SomeKey" value="SomeValue" />
  </appSettings>
</configuration>

Friday, 7 January 2011

Useful NUnit attributes

I can never remember the various NUnit attributes I find useful (other than the basics like TestFixture, Test, SetUp, TearDown and ExpectedException) so here’s a quick aide-mémoire (NB: this is not a complete list by any means):

Attribute Description
CombinatorialAttribute Used on a test to specify that NUnit should generate test cases for all possible combinations of the individual data items provided.

ExplicitAttribute

Causes a test or test fixture to be ignored unless it is explicitly selected for running.

RandomAttribute

Used to specify a set of random values to be provided for an individual parameter of a parameterized test method.
RangeAttribute Used to specify a range of values to be provided for an individual parameter of a parameterized test method.

SequentialAttribute

used on a test to specify that NUnit should generate test cases by selecting individual data items provided for the parameters of the test, without generating additional combinations.
TestCaseAttribute Serves the dual purpose of marking a method with parameters as a test method and providing inline data to be used when invoking that method.
TestCaseSourceAttribute Used on a parameterized test method to identify the property, method or field that will provide the required arguments.
ValuesAttribute Used to specify a set of values to be provided for an individual parameter of a parameterized test method.

Row testing with NUnit

In times past there was an extension to NUnit that facilitated row testing (i.e. allowing a test case to be executed multiple times, passing in different values to each run). The extension is no longer required; you can use the [TestCase] attribute instead:

[TestCase("wrongusername", "password")]
[TestCase("username", "wrongpassword")]
[TestCase("worngusername", "wrongpassword")]
[ExpectedException(typeof(SecurityTokenException))]
public void Validate_WithInvalidUsernameOrPassword_ThrowsException(string username, string password)
{
    var validator = new SimpleUsernameValidator();
    validator.Validate(username, password);
    Assert.Fail();
}

Note that you can also specify an expected result if the method under test returns a value*:

[TestCase(12,3, Result=4)]
[TestCase(12,2, Result=6)]
[TestCase(12,4, Result=3)]
public int DivideTest(int n, int d)
{
  return( n / d );
}

There is also a [TestCaseSource] attribute that can be used in conjunction with [TestCase] to identify a class that can supply test case arguments**:

[Test, TestCaseSource("DivideCases")]
public void DivideTest(int n, int d, int q)
{
    Assert.AreEqual( q, n / d );
}

static object[] DivideCases =
{
    new object[] { 12, 3, 4 },
    new object[] { 12, 2, 6 },
    new object[] { 12, 4, 3 } 
};

 

References

* TestCaseAttribute (NUnit 2.5)
** TestCaseSourceAttribute (NUnit 2.5)

Wednesday, 5 January 2011

Basic unit test coverage reporting with PartCover

I’m fed up with having to guess at how much of my code is covered with unit tests and there’s no budget for NCover. So, after a bit of hunting I came across PartCover, an open source code coverage tool for .Net (https://github.com/sawilde/partcover.net4). As I’ve just started using it so I thought I’d jot down a few notes on the basics of getting a coverage report working.

The first step is creating a settings file. This is an XML file containing the settings PartCover will use to produce a coverage report.

<PartCoverSettings>
  <Target>C:\path_to_nunit\nunit-console-x86.exe</Target>
  <TargetWorkDir>C:\path_to_source\EnquirySubmissionServiceCoreTests\bin\Debug</TargetWorkDir>
  <TargetArgs>EnquirySubmissionServiceCoreTests.dll</TargetArgs>
  <Rule>+[*]*</Rule>
  <Rule>-[EnquirySubmissionServiceCore]EnquirySubmissionServiceCore.Some.Namespace*</Rule>
  <Rule>-[log4net*]*</Rule>
  <Rule>-[Moq*]*</Rule>
  <Rule>-[nunit*]*</Rule>
  <Rule>-[EnquirySubmissionServiceCoreTests*]*</Rule>
</PartCoverSettings>

You need to provide a path to NUnit, a working directory (the directory containing the assembly to check), the target assembly and a set of rules. The rules are basically RegEx and tell PartCover what to include and what to exclude from the report. My rules say include everything (+[*]*) then start excluding assemblies I don’t want in the report.

Note line 6 of the above settings file. It is possible to exclude specific namespaces within an assembly so you can exclude files you don’t want to be tested for coverage. In fact, you can even exclude specific classes in the same way.

I saved the settings file into the PartCover installation directory and then ran PartCover.exe:

partcover.exe --settings settings.xml --output output.xml

This runs the PartCover with the settings file and creates an XML file containing the output (in this case named output.xml). The output file can be opened with PartCover.Browser.exe to view the results:

untitled

That’s it for a basic setup and first report generation. Looks like I’ve got a few unit tests to write…