Thursday 10 September 2015

Dependent Assembly needed for MSTest Unit Testing Assembly

Problem

In my case, when testing an assembly that had a generated XmlSerializers assembly associated with it the unit tests would fail when loading the SUT assembly.  The problem was caused by the serializer assembly not being copied to the deployment location of the tests.

Solution

To get the serializer assembly to deploy you need to:

  1. Mark the test class or method with a DeploymentItem attribute like so [DeploymentItem("MySubjectAssembly.XmlSerializers.dll")]
  2. Change your solution's LocalTestRun.testrunconfig to include, in the Deployment section, the XmlSerializers.dll from the bin\debug folder of your test project.

Wednesday 2 April 2014

Windows Authentication not setting User.IsAuthenticated in .NET 4.0

Problem

You’ve just upgraded your web project to .NET Framework 4.0 and all of a sudden your code that checked HttpContext.Current.User.Identity.Name returns a blank string. User.Identity.IsAuthenticated also returns false but strangely Request.ServerVariables["LOGON_USER"] gives the user name.

Solution

In your web.config add the following two keys to your appSettings:

<configuration>
<appSettings>
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false" />
</appSettings>
</configuration>



To me Microsoft have got lazy in their configuration stuff … why put this in the appSettings and not in the authentication section?



Digging Deeper



It looks like this problem may have been introduced in ASP.NET 3 but that in my case changing the .Net version up to 4 forced an upgrade to ASP.NET 3+ perhaps.



Technorati Tags: ,

Wednesday 26 March 2014

Beyond Unit Testing

Problem

Unit testing is, IMHO, the essential bare minimum automated testing that should be employed on any software development project beyond the very simplest CRUD application.  So once you have unit tests in place what is the next step?

My preference is for there to be Business Driven Development (BDD) style user acceptance tests. Ideally these would be specified by, where available, the users themselves with help from the developer.  One problem with this however is that the user will probably be thinking in terms of a user interface - be it a web page, an SMS service, a web service or anything in between.  If you test through a user interface then a lot more work is going to be involved and the tests will be a lot more fragile.

Solution

The best option is to test through an API.  One that will be used by the UI programmer to interact with the system as a whole.  That said, systems rarely stand alone and often interact with other systems and again this makes the testing hard.  Even introducing a database or any other state retaining part of the system can

make the testing harder as it will need to be reset to a known state between each test.  For these dependencies then it is better to mock them out of the tests – ensuring that they will not fail no matter what environment you are running on.

The following diagram illustrates the priority I would assign to each kind of test.  The priority indicates not only how early in the project the tests should be developed but also how many tests I would expect to see in each case and how often you would execute them.

With respect to the number of tests at each priority there is no hard and fast mathematical rule.  However I am inclined to think of it as an exponential decrease in number, for instance 1000 tests at priority 1, 100 at priority 2, 10 at priority 3 and 1 at 4.  Actual numbers will depend on how critical the system is and how much effort you are willing to put in to avoid manual testing.

1 API-Mock Testing

This is your bread and butter testing.  Where unit tests leave off so these take over – you are aiming for really good coverage here. These should be run all the time – either in a continuous testing system or at least before check-in.

2 API-Actual Testing

First stage of integration testing.  You may be less reliant on the actual results of tests against the dependencies and more concerned that the structure of the communication protocol is correct.  How often these are run will count on how difficult it is to get your dependencies reset to a baseline.  Database dependencies should be easier in this respect and so the tests can be run before each check-in.  Dependencies on hard to reset (like a payment gateway) or expensive to replicate for testing (like a telephone exchange) systems may be relegated to only being automatically ran just before user/manual testing.

3 UI-Mock Testing

First stage of UI testing.  You may be just ensuring that the screens flow correctly. There should be no need to test your business services behaviour as such since this is tested by the type 1 tests.  These should be run by your build system.  Generally you wouldn’t want it to break the build if they fail as it may be a small issue or perhaps you are working up to a fully functional system.  Failing tests can either be a warning to manual testers of what to avoid, a cue to the test writers that the test needs updating or a cue to the developers that they got something wrong.  It should never indicate that business logic is wrong as that should be covered by type 1 API-Mock testing.

4 UI-Actual Testing

Full UI integration testing.  Your best bet here is to simply smoke test that everything is configured correctly – something that can be quite challenging if you are using DI or IoC.  At times I have used a single screen for this that simply displays pass/fail indicators for every integration point.  True – this isn’t really a UI test but it is useful in confirming configuration and connectivity and can be used in the live environment.  These tests should be run as part of your deployment testing to each environment.

Conclusion

Once you have good coverage with unit tests or a test driven approach to development then it is time to level up to Business/Domain Driven Development where your tests are closer to what the customer understands and needs.  Although customers often think in terms of user interfaces your tests will be less fragile if you test against a coded application programming interface that will then be used by the user interface to drive the domain logic.  Also mock out your dependencies to ensure quick and reliable test execution.  Write fewer tests against the UI and dependencies which will only be executed as part of the build process or in deployment.

Sources

This is not entirely original thought.  Unfortunately I can’t remember where I first read about this approach.  If I find it or remember I’ll link here.

Technorati Tags: ,,,,

Tuesday 19 October 2010

Pre-generate Xml Serialisation of a WebService Proxy to speed load time

Problem

Microsoft .NET 2+ will dynamically create Xml Serialisation code when instantiating a WebService proxy.  If the WebService is a large one with many types and methods defined then the load time can be unacceptably slow.

Solution

The solution is to use .NET tools to pre-generate the serialisation code and then replace the serialisation attributes in the proxy with a reference to the generated dll.

The following PowerShell script automates the process for a WSDL file, MyService.wsdl:

# This Powershell script assists in the creation of a WebService proxy that loads in a reasonable time.
# .NET will usually dynamically generate Xml Serialization code when the service proxy is instantiated.
# This results in a ~1min delay.
# In order to speed the load time it is necessary to pre-generate the Xml Serialization code.
# You can then replace the Xml Serialization attributes with a single reference to the pre-compiled dll.
# The script below automates the process.

Write-Progress -activity 'Building Proxy' -status 'Progress->' -percentcomplete 0 -currentOperation 'Set Enviromnent'
$env:path = "C:\WINDOWS\system32; C:\WINDOWS; C:\WINDOWS\system32\WindowsPowerShell\v1.0; C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319; C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools; C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin"

Write-Progress -activity 'Building Proxy' -status 'Progress->' -percentcomplete 1 -currentOperation 'Create basic proxy'
wsdl /n:MyWebServiceProxy MyWebService.wsdl

Write-Progress -activity 'Building Proxy' -status 'Progress->' -percentcomplete 10 -currentOperation 'Compile basic proxy'
csc.exe /t:library /out:MyWebServiceProxy.dll MyWebServiceProxy.cs

Write-Progress -activity 'Building Proxy' -status 'Progress->' -percentcomplete 20 -currentOperation 'Build proxy serialisation'
sgen.exe /p /force MyWebServiceProxy.dll

Write-Progress -activity 'Building Proxy' -status 'Progress->' -percentcomplete 50 -currentOperation 'Remove XmlIncludeAttribute from proxy'
Get-Content MyWebServiceProxy.cs | % {$_ -replace '\[System\.Xml\.Serialization\.XmlIncludeAttribute', '//[System.Xml.Serialization.XmlIncludeAttribute'} | Set-Content -path MyWebServiceProxy_SerialisationRemoved.cs

Write-Progress -activity 'Building Proxy' -status 'Progress->' -percentcomplete 70 -currentOperation 'Add XmlSerializerAssemblyAttribute to proxy'
Get-Content MyWebServiceProxy_SerialisationRemoved.cs | % {$_ -replace 'public partial class MyWebService', '[System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = "MyWebServiceProxy.XmlSerializers")] public partial class MyWebService'} | Set-Content -path MyWebServiceProxy_SerialisationAdded.cs

Write-Progress -activity 'Building Proxy' -status 'Progress->' -percentcomplete 90 -currentOperation 'Compile new proxy'
csc.exe /t:library /out:MyWebServiceProxy.dll MyWebServiceProxy_SerialisationAdded.cs

Write-Progress -activity 'Building Proxy' -status 'Progress->' -percentcomplete 100 -currentOperation 'Finished.'



You’ll need to change the file and class names appropriately for your case or perhaps add parameters to the script.



 



What’s going on



Step by step:




  1. Add the locations of the tools used to the path environment variable.


  2. Use wsdl.exe .NET SDK utility to generate the proxy c# code file from the wsdl file.


  3. Compile the c# proxy into a dll.


  4. Use sgen.exe .NET SDK utility to generate an Xml Serialisation dll for the proxy.


  5. Using a regular expression strip out the XmlIncludeAttribute from the c# proxy.


  6. Using a regular expression insert a XmlSerializerAssemblyAttribute referencing the generated serialisation dll.


  7. Recompile the proxy dll with the reference to the serialisation dll.



References



With thanks to http://www.sharepoint-stuff.com/?p=199



Technorati Tags: ,

Thursday 24 June 2010

What is using a port on my machine?

Problem

My service connects to a TCP server over a particular port and when establishing the connection throws the exception: “SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted”.

Diagnosing the Issue

Use netstat at the command line to see what is using the port.

netstat –a
Displays all the ports in use.

netstat –b
Displays all the active connections and the process/exe that is using them

In my case a network error had occurred and I believe my service had left the client open, knew it was dead and so was trying to reconnect – throwing the exception.  Restarting the service resolved the issue but the code will need reviewing.

Monday 24 May 2010

Removing whitespace from HTML tags

The Problem

This situation occurs when using the .net 2.0 classes to transform XML into HTML with a style sheet the transform (System.Xml.Xsl.XslCompiledTransform).  the output will include whitespace inside of certain HTML tags that may occasionally display within form fields when output.  This can be a pain especially when displaying TextArea elements. In IE the behaviour appeared to change unexpectedly when some other element appeared before the TextArea – such as a dropdown list (select).

The Solution

A solution is to remove the whitespaces from these tags after it has been transformed.

private string CleanUpWhitespaceInTags(string xmlString)
{
return cleanUpWhitespaceInTagsRegEx.Replace(xmlString, cleanUpWhitespaceInTagsReplacement);
}

private static readonly Regex cleanUpWhitespaceInTagsRegEx = new Regex(@"<(?<tagName>[\w-]+)\b(?<attributes>[^>]*)>\s*(?<content>[^<]*?)\s*</\1>");
private const string cleanUpWhitespaceInTagsReplacement = "<${tagName}${attributes}>${content}</${tagName}>";


The above code uses a regular expression to match tags that have no inner xml/html and gets named captures of the tag name, it’s attributes and content (without any surrounding whitespace).



To break it down:

























































< match the opening tag’s starting brace
(?<tagName>[\w-]+) capture any valid tag name (containing one or more word characters or dashes)
\b check that we are at a word boundary
(?<attributes>[^>]*) capture any characters after the tag name and before an end brace as attributes
> match the opening tag’s end brace
\s* match any whitespace on the left of the content
(?<content>[^<]*?) capture any character that isn’t a starting brace but don’t be greedy
\s* match any whitespace on the right of the content
</\1> match the closing tag


Disclaimer: Whether this regex covers all scenarios has not been tested but it works for the situation we encountered.



The replacement string then reconstitutes the tag, attributes and content without the leading or trailing whitespace.



Technorati Tags: ,,

Friday 14 May 2010

Properly disposing a System.Threading.Timer

The following test fixture shows how a timer can be properly disposed in order to ensure that the thread executing the callback has completed (or we've timed out waiting for it):

[TestClass]
public class TimerFixture
{
[TestMethod]
public void Check_timer_dispose_behaviour()
{
System.Threading.Timer timer = new System.Threading.Timer(new System.Threading.TimerCallback(OnTick), null, 100, 0);

while (!isProcessing) Thread.Sleep(50);

WaitHandle waitHandle = new AutoResetEvent(false);

timer.Dispose(waitHandle);

isStopping = true;

WaitHandle.WaitAll(new[] { waitHandle }, 1000);

Assert.IsFalse(isProcessing);
}

private void OnTick(object state)
{
isProcessing = true;

while (!isStopping) Thread.Sleep(100);

Thread.Sleep(200);

isProcessing = false;
}

private bool isStopping = false;
private bool isProcessing = false;
}