Navigation

Search

Categories

On this page

How to : Sign XML messages with a SHA-1 signature, for Adobe Content Server
Test Smells and Test Code Quality Metrics
Avoid the slow Add Reference dialog box in Visual Studio 2008
Slides and code from my Clean Code session
When all fails, extract method

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 148
This Year: 1
This Month: 0
This Week: 0
Comments: 42

Sign In
Pick a theme:

# Sunday, February 14, 2010
Sunday, February 14, 2010 11:38:53 AM (GMT Standard Time, UTC+00:00) ( .Net General )

The past week I’ve been doing a spike to talk to Adobe Content Server 4 (ACS4). Querying the content in ACS4 is done in a REST style. The client sends a XML message via HTTP POST to the admin endpoint. The endpoint details are in the documentation but are vague.  This is usually at  http://youracs4server/admin/EndPoint.

These need a signed XML message, in the POST body. A typical message looks like this

<request>
    <nonce>ABCD123==</nonce>
    <hmac>XXXXXXXXX===</hmac>
    <distributor>uid:8888-43434-34343434</distributor>
   <resource>
     ......
   </resouce>
</request>

The hmac element contains the SHA1 signature  of the XML message. The signature is generated using a shared secret.  The signature is for the whole XML except the hmac element. Before signing the message, we have to construct the XML without the hmac, then sign it, and then add then hmac.

I did this by using a two stage Xml serialization process. This may not be the best way to do it, and there has to be a better solution.  I created a class named SignedXMLSerializer, and this inherits from XmlSerializer. SignedXMLSerializer serializes objects that are of the base type Signable. The Signable class has two properties, Nonce and Hmac. Any class that has to be sent as a signed XML message must inherit from Signable

public abstract class Signable
    {
        [XmlElement("nonce")]
        public string Nonce { get; set; }

        [XmlElement("hmac")]
        public string HMAC { get; set; }
    }

In the serialize method of the SignedXMLSerializer, we first generate the nonce. The nonce makes each message unique. Then we serialize the object to a string. The signature is generated using this string, and assigned it to the Hmac property.

We then serialize the signed object to the writer that was passed in.

public void Serialize(T o, XmlTextWriter writer) {
            o.Nonce = GenerateNonce();
            StringBuilder stringBuilder = GetXMLToSign(o);
            string hmac = GetSignature(stringBuilder);
            o.HMAC = hmac;
            Serialize(writer, o);
        }
To use the SignedXMLSerializer, pass in one of the HashAlgorithm types. I’ve used SHA1 in my case.
This makes it easier to use with different signing algorithms. 
Typical usage of the SignedXMLSerializer is as follows
HMACSHA1 hmacsha1 = new HMACSHA1 {Key = Encoding.ASCII.GetBytes("consumerSecret")};
            SignedXmlSerializer<Request> signedXmlSerializer = new SignedXmlSerializer<Request>(hmacsha1);

 StringBuilder sb = new StringBuilder();
            StringWriter writer = new StringWriter(sb);
            signedXmlSerializer.Serialize(req, new XmlTextWriter(writer));

The final serialized string can be sent via HTTP post to ACS4. 

Code for the SignedXMLSerializer class is here http://gist.github.com/303962

Comments [0] | | # 
# Wednesday, December 09, 2009
Wednesday, December 09, 2009 10:15:58 PM (GMT Standard Time, UTC+00:00) ( Agile | development | TDD )

The major highlight at XP Day 2009, was Mark Striebeck’s talk on unit testing practices at Google.  What makes a good test depends on experience , skill and school of thought. I had to agree when he said that developers can be almost religious when it comes to the topic of what makes a good test. This made them solve this problem the Google way, by gathering data. Let the data speak.

He went on to describe metrics that they were collecting on tests and test code.  A test that has never failed is likely to be a bad test. If the test was fixed to make the test pass, then this is also an attribute of a bad test. A test can be a good test if the code was fixed to make the test pass.

This got me thinking. Generally I haven’t gathered metrics on test code. We have a pretty good metrics dashboard for production code. What metrics can I gather on test code ?

Metrics on test code should also focus on the readability of the code. Having large test methods is ok, but not too big. My opinion is that a test method with more than 20 lines is too big.

Tests should be concise, the assert should be obvious. Some code duplication is fine to make the test readable. This is all fine, but how can I get these as metrics  ? Only way to judge this is to eyeball the tests, and there are differences of opinion.

However, there are ways to measure what a test should not be. These are test smells. Test smells are described in xUnit Test Patterns

I’ve listed a few test smells and NDepend CQL queries find these smells. These can be automated in the build process and flagged up.

Large Test Methods

These can be a chore to read. Tests should be written as simply as possible. These also  point to too many responsibilities and dependencies in the code being tested, as most of the test code is used to do setup for the test.

SELECT METHODS WHERE HasAttribute "NUnit.Framework.TestAttribute" AND  NbLinesOfCode > 20

Large setup methods

Usually when unit testing the same code, we tend to have a common setup method, in order to make the test more readable. What happens is, more and more code is moved into the common setup method. We get blind to this after a while, and all the dependencies for the test are hidden away. If you do have [Setup] methods, keep them small.

SELECT METHODS WHERE HasAttribute "NUnit.Framework.SetUpAttribute" AND NbLinesOfCode  > 10

Deep inheritance trees in test fixtures

Again, common test code moved up to a base class and the base class is used in many tests. Then more base classes are created. This creates more tight coupling between test classes. Which makes tests harder to change. Low coupling and high cohesion applies to test code as well. Make each unit test class as independent as possible.

SELECT TYPES WHERE HasAttribute "NUnit.Framework.TestFixtureAttribute"  AND DepthOfInheritance >2

Test fixture setup

TestFixtureSetup is bad. The TestFixtureSetup is run once before all tests. This leads to fragile tests and inadvertently leads to using some shared state. Use Setup instead

SELECT METHODS WHERE HasAttribute "NUnit.Framework.TestFixtureSetUpAttribute"

Tests that fail when they are run in a different order

The xUnit test runner helps with this, by randomizing the order tests are run.

Ignored tests

Ignored tests are like comments. Dead code that doesn’t do anything. Either fix them or delete them.

I have yet to find some way of detecting duplicated tests, shared state in tests and multiple asserts in tests. What other ways can I find test smells ?

Comments [2] | | # 
# Saturday, November 28, 2009
Saturday, November 28, 2009 1:31:31 PM (GMT Standard Time, UTC+00:00) ( .Net General | development | TDD )

 

When you are in the zone, and want to add a reference to Rhino, NUnit or any other common reference, adding it via the Add Reference dialog can be painfully slow. Fortunately VS has a good automation interface, which lets you to write macros.

I wrote a simple macro to add a NUnit reference to the current project. Add this to your Macros project in Visual Studio, map a button or a shortcut key to it. This way you can add those common references pretty quick.

This is a cleaned up version of the sample here http://msdn.microsoft.com/en-us/library/vslangproj80.reference3%28VS.80%29.aspx

 

   1:      Sub AddNUnitReference()
   2:          AddNewReference(DTE, "C:\Tools\NUnit\nunit.framework.dll")
   3:      End Sub
   4:   
   5:      Sub AddNewReference(ByVal dte As DTE2, ByVal referencePath As String)
   6:          Dim aProject As Project
   7:          Dim aVSProject As VSProject
   8:   
   9:          aProject = dte.ActiveDocument.ProjectItem.ContainingProject
  10:   
  11:          aVSProject = CType(dte.ActiveDocument.ProjectItem.ContainingProject.Object, VSProject)
  12:          ' Add an Assembly reference and display its type and additional
  13:          ' information.
  14:          Dim newRef As Reference
  15:          newRef = aVSProject.References.Add(referencePath)
  16:   
  17:      End Sub
Comments [0] | | # 
# Saturday, September 05, 2009
Saturday, September 05, 2009 6:43:29 PM (GMT Daylight Time, UTC+01:00) ( Agile | Books | development )

A while back I organised a coding session during an internal training day at work.  The aim of the session was to introduce practices  from the Clean Code book, to make code a little bit cleaner and practice the boy scout rule.  I’ve tried to include the important points from the book, though everything in the book is equally important.

I’m sharing the slides and the code. Feel free to use it and improve on it. The code is a Sudoku solver from the Programming In the Small session at SC ‘09. I’ve converted the Java code to C#. The code includes acceptance tests, so you can fearlessly refactor without breaking it.

http://www.hibri.net/content/binary/cleancode.zip

The session was planned for 90 minutes. It includes slides introducing clean code concepts, with coding exercises to practice them. I recommend 10-15 minutes for the coding exercises.

Comments [0] | | # 
# Sunday, August 30, 2009
Sunday, August 30, 2009 11:18:18 AM (GMT Daylight Time, UTC+01:00) ( )

Sometimes (most of the time) when looking at a piece of un-clean code, it’s not clear what path to take to make the code that little bit more better. The easiest first refactoring to do is extract method.  Use extract method ruthlessly. Attempt to get and get many smallest methods. Repeat till these methods become smaller and smaller as close as possible to one line of code in a method.

Patterns emerge when creating more and more methods. The methods start to show groupings and responsibilities. When the methods obey the Law of Demeter, they can be moved around to other classes and also create new classes. It becomes easier to see duplication.

Methods are the smallest building blocks of a piece of software. These small and granular building blocks are more flexible. They give more ways to build things and allow greater reuse. When these building blocks are available, the code becomes much clearer. The big refactorings are made possible.

Comments [0] | | #