Three Is It

Because two isn't enough and four is just too many

Peace cannot be achieved through violence, it can only be attained through understanding.
Ralph Waldo Emerson
Home Blogs Genealogy Brad's Bookshelf Subscriptions Contact Sign in
 

About the author

Brad Butts is a .NET developer and architect. He is married with children and enjoys reading, working out, and genealogy is his five minutes of spare time.
E-mail me Send mail
National Debt Clock

Recent comments

Authors

Disclaimer

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

© Copyright 2010

Key/Value Pair Configuration Section

Here’s another suggestion for Microsoft: give me a nice key/value pair configuration section.

Now, you might say, don’t you already have appSettings?  The appSettings configuration section is certainly handy, but occasionally, I’ll have to store sensitive data in my configuration file—data required to be encrypted.  I’ve made a few attempts to encrypt the appSettings section to no avail, although I’m not sure why it won’t encrypt—the new System.Configuration.AppSettingsSection v2.0 implements System.Configuration.ConfigurationSection, which tends to play nicely with the configuration encryption infrastructure…so either I’m not doing something right or I’m missing something.

You might say, fooey on appSettings, why don’t you put your secret in the connectionStrings section and encrypt that?  I could do that (and I know it does play nicely with configuration encryption), but what if I have sensitive data I need to store that’s not a connection string—like a plain old password?  That would look kind of silly in a connectionStrings section:

<connectionStrings>
  <add name="myPassword" connectionString="bob sent me"/>
</connectionStrings>

In code:

string myPassword = ConfigurationManager.
                ConnectionStrings["myPassword"].ConnectionString;

 

I just don’t think that reads very well.

No, what I really want is a third option: a good ‘ol Key/Value pair configuration section that will encrypt/decrypt consistently.  Well, interestingly, two-thirds of the work to make such a section available is already done in the .NET framework. 

Most custom configuration sections require that you implement three abstract classes: ConfigurationSection, ConfigurationElementCollection, and ConfigurationElement.  As it turns out, the .NET framework already contains a public System.Configuration.KeyValueConfigurationCollection which manages a collection of System.Configuration.KeyValueConfigurationElement objects.  The only thing left to do is to expose this collection to configuration via an implementation of ConfigurationSection.  It’s as simple as this:

using System.Configuration;

namespace Brad.Configuration
{
    public class KeyValueSection : ConfigurationSection
    {
        [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
        public KeyValueConfigurationCollection Settings
        {
            get
            {
                return (KeyValueConfigurationCollection)this[""];
            }
            set
            {
                this[""] = value;
            }
        }
    }
}
It’d be nice if such a class were already available in the framework instead of me having to code the last piece.  Maybe some nice Microsoft employee can add this class in a future release.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Technology Blog
Posted by Brad on Tuesday, September 15, 2009 11:38 PM
Permalink | Comments (1) | Post RSSRSS comment feed

Unit Testing in ASP.NET

I’m all for unit testing and even Test Driven Development (although I can do without some of the TDD zealotry out there).  Recently, I began writing some libraries for ASP.NET applications and really struggled with how I was going to write my unit tests to test my work.  Certainly, we have the MVP and MVC patterns and lots of great examples, frameworks, and miscellaneous tools to help you implement these patterns and greatly simplify the unit tests you need to write—but I’m writing an ASP.NET-based library, not an end-to-end application.

Here’s what I’m doing:

I have to write components around a commercial security device that injects certain identity information into the request header of http requests (via an ISAPI filter).  Specifically, I am writing an HttpModule (a few, actually, for different scenarios) to build out a custom Identity object and insert it into the Current.User object.  Additionally, I’m writing a couple of RoleProviders to manage the roles returned by the device.

These components obviously have a tight reliance on HttpContext, so how do you unit test under such a scenario?  Incidentally, these components have to work with a pure ASP.NET 2.0 solution, which means I don’t have access to the new System.Web.Abstractions assembly which is supposed to make testing in this space much easier—I’d still like to see what the Abstractions assembly could do for me, though.

Phil Haack offered up this effort at mocking HttpContext, but I simply couldn’t get that to work for my scenario.  I then looked at TypeMock.  Here’s some code I wrote against TypeMock that still doesn’t work:

[Test]
[VerifyMocks]
public void TestOnAuthenticateRequest2()
{
string fname = "John";
string lname = "Smith";
string fullName = fname + " " + lname;
string roles = "cn=Role1,ou=APPS,o=SomeCompany:cn=Role2,ou=APPS,o=SomeCompany";
string login = "jxsmith";
string commonName = "Smith";
//TestedImplementation is an alias for my custom HttpModule
TestedImplementation target = new TestedImplementation();
MockObject<HttpApplication> applicationMock = MockManager.MockObject<HttpApplication>();
MockedEvent authRequestEvent = applicationMock.ExpectAddEvent("AuthenticateRequest");
target.Init(applicationMock.Object);
MockObject<HttpRequest> httpRequestMock = MockManager.MockObject<HttpRequest>();
applicationMock.ExpectGetAlways("Request", httpRequestMock.Object);
MockObject<HttpResponse> httpResponseMock = MockManager.MockObject<HttpResponse>();
applicationMock.ExpectGetAlways("Response", httpResponseMock.Object);
httpRequestMock.ExpectGetAlways("HttpMethod", "POST");
httpRequestMock.ExpectGetAlways("AppRelativeCurrentExecutionFilePath", "foobar.aspx");
httpRequestMock.Object.Headers.Add("LOGIN", login);
httpRequestMock.Object.Headers.Add("FIRSTNAME", fname);
httpRequestMock.Object.Headers.Add("LASTNAME", lname);
httpRequestMock.Object.Headers.Add("ROLE", roles);
httpRequestMock.Object.Headers.Add("COMMONNAME", commonName);
authRequestEvent.Fire(applicationMock.Object, EventArgs.Empty);
//once I can actually mock the context, I'll write some asserts
}

As I recall, I could never figure out how to stub in data to the request header of the mocked request.  Doing this is pretty important as my components behave differently based on the data present (or not present) in the header.  A sister project to TypeMock called Ivonna (no pun intended) actually might let me do this, though.  Of course, both these products cost money—so, I’d still like to find a free answer to my problem.

Some folks have suggested refactoring my IHttpModule and RoleProvider implementations such that I move as much code as possible out of the direct implementations and into separate classes that can be more easily tested.  I assume they mean separate private classes that aren’t exposed to clients using my components.  To that end, here’s what I tried in my implementation:

public class MyHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.AuthenticateRequest += OnAuthenticateRequest;
}
private void OnAuthenticateRequest(object sender, EventArgs e)
{
HttpApplication httpApp = sender as HttpApplication;
MyHttpModuleHelper helper = new MyHttpModuleHelper();
helper.DoStuff(httpApp.Request.Headers);
}
public void Dispose()
{
//dispose stuff here
}
}
//the private class that can be tested
class MyHttpModuleHelper
{
public string[] DoStuff(NameValueCollection headers)
{
//process the headers in some way
return new[]{"hello world"};
}
}

And in my unit test class:

private MethodInfo DoStuffMethod;
private object MyHttpModuleHelper;
[SetUp]
public void Init()
{
Assembly testAssembly = Assembly.GetAssembly(typeof (MyHttpModule));
MyHttpModuleHelper =
testAssembly.CreateInstance("MyNamespace.HttpModules.MyHttpModuleHelper");
Type helperType = MyHttpModuleHelper.GetType();
BindingFlags bf = BindingFlags.Instance | BindingFlags.Public;
DoStuffMethod = helperType.GetMethod("DoStuff", bf);
}
[Test]
public void DoStuffTest()
{
NameValueCollection stubHeaders = new NameValueCollection();
//stubHeaders.Add();  //add some fake data
object returnValue = DoStuffMethod.Invoke(MyHttpModuleHelper, new object[] { stubHeaders });
Assert.IsTrue(returnValue.GetType().IsArray, "Expected the type to be a string array");
string[] roleArray = returnValue as string[];
Assert.IsTrue(roleArray.Length == 1, "Expected the array length to be 1");
StringAssert.IsMatch(roleArray[0], "hello world", "Expected the first value to be hello world");
}

This works, but it’s such a pain.  One frustration I’ve had is that I tend to refactor my helper methods a lot—the parameters I pass, the return values I return, even the names of the methods themselves.  Every time I refactor, I have to go back to my unit tests and refactor them accordingly—even Resharper isn’t smart enough to cascade through such refactoring when I’m using Reflection to invoke those methods.  Do I have any other options?

Virtually at the end of my rope, I even contemplated the mildly insane notion of writing a test ASP.NET app to Response.Write out values from my Identity and Principal objects rendered by my HttpModules and RoleProviders…then use a product like Selenium or WatiN to perform assertions on those values in the pages.

Just when I thought all hope was lost, a friend of mine reminded me of the ASP.NET host adapter.  The ASP.NET host adapter allows you to run a unit test that smells a lot more like an integration test—like integration testing, you have to develop a web app within which your test will run.  The big difference, though, is that you can perform assertions on server-side objects. 

You invoke the ASP.NET host adapter by decorating your MSTTest test method with the attribute, [HostType(“ASP.NET”)].  You also have to include the attribute [UrlToTest(“someUrl”)]—where you specify the ASPX page that establishes the server-side context you’d like to test.  You can add one more attribute, AspNetDevelopmentServerHost, to have you test web app run under the Development Server (a.k.a. Cassini) as opposed to IIS.

It’s lame that I need a web app to run a unit test, but I’m desperate, so I’ll play along.  As I started all this work, one obstacle I kept running into was the UrlToTest attribute: it seemed to only understand the “localhost” domain name.  As I mentioned earlier, I’m writing components that have to play nicely under this third party ISAPI filter.  The ISAPI filter will only be invoked when it detects certain domain names it’s configured to listen for.  Localhost is not one of these—if it were, every time anyone would run an app under localhost, the ISAPI filter would invoke a particular set of policies that may or may not have anything to do with your work—frankly, it would just be bad.

Instead, in Development, until we can get a real IP assigned to our app, we create fictitious domain names by mapping 127.0.0.1 to that fictitious name in our local hosts file.  We configure the ISAPI filter to apply our particular policy when it detects this fictitious host name being requested and all is right in the world.  That is, until you try to invoke the ASP.NET host adapter using your fictitious domain name: it seems that the ASP.NET host adapter could care less about what mappings I have in my hosts file.  I even tried my own IP address and it didn’t like that, either.  Finally, I tried my machine name and, ta-da, the ASP.NET host adapter worked and my test ran.  It just so happens that I can use my machine name as one of these fictitious domain names, but I consider that bad form—it tightly associates my machine to the development environment.  Now, even my tests are tightly associated to my machine.  That really stinks—so much for running my tests on a separate build server…they just won’t work.

Here’s an example of one of my test methods:

[TestMethod]
[HostType("ASP.NET")]
[UrlToTest("http://MyMachineName/SomeVirDir/Default.aspx")]
public void IdentityType()
{
Assert.IsNotNull(HttpContext.Current.User, "Current.User object is null");
Assert.IsNotNull(HttpContext.Current.User.Identity, "Current.User.Identity object is null");
Assert.IsInstanceOfType(HttpContext.Current.User.Identity, typeof(MyCustomIdentity),
"Current identity is not of type MyCustomIdentity");
}

Another thing I noted regarding the UrlToTest attribute is that it only likes my “short” machine name—I had to truncate off my DNS suffix in order to get my test to run properly.

So, this is a terrible way to test—my tests are tightly bound to my machine and require a web app of all things to run a simple unit test—but, at least it works on my machine.  The alternatives would be scraping together a few hundred bucks to buy TypeMock/Ivonna (which would come out of my pocket, not my company’s—see here on why that’s the case) or upgrade to .NET 3.5 SP1 with hopes that the new Abstractions assembly can help me out.

For the moment, I’ll stick with this approach.  My next challenge is to figure out how to dynamically change my web configuration between tests to swap out HttpModules and RoleProviders, as I need to test a few of these.  Any ideas?

Currently rated 2.5 by 4 people

  • Currently 2.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by Brad on Saturday, February 21, 2009 7:14 PM
Permalink | Comments (7) | Post RSSRSS comment feed

Suggestions for Microsoft, Part 1

Let's just call this Part 1 in a potentially lengthy series of frustrations suggestions aimed at Microsoft.  

To be clear, I like Microsoft: I make my living using Microsoft tools.  However, as with all things, I occasionally encounter frustrations with their tools and/or services and need a place to vent.  Well, here it is.

Suggestion: Please decouple the different tools within Visual Studio
One huge frustration for me is the apparent assumption that most/all Microsoft customers use the full stack of Microsoft tools.  I see this theme manifest itself in many different areas of software development, but for this post, I just want to focus on the tools for building, testing, and deploying .NET applications (mainly web applications).

So, here's my caveman view of the software development lifecycle (absent project management methodology jargon and concepts like iterative development):



In my diagram, I've identified different activities and where they occur: for instance, coding and authoring of unit tests take place on the developer's workstation while I expect formal builds, formal unit testing and analysis and even formal packaging operations to occur on the build server.  Finally, I've added suggested tools that are used for each activity.

Now let's talk about my frustrations: thanks to the tight coupling of the different tools within the umbrella of Visual Studio, we have to be very careful about what tools we use in development because those tools may not be available to build/test/package our code on the build server.  Unlike other shops, my company has quite a mixture of technologies in the software development stack--most important, this means no Team Foundation Server.  Note: I've observed most of these frustrations under Visual Studio 2005, but I'm not optimistic that they've been remedied under Visual Studio 2008.

My first problem is with unit testing.  When Visual Studio 2005 rolled out, my inclination was to run with MSTest.  That is, until I realized that MSTest required an instance of Visual Studio be installed on the build serverOthers have railed against MSTest in general, but my most immediate problem with it is the fact that I would have to corrupt my formal build environment with a developer tool.  It seems to me that having a development tool on the build server would be a violation of the separation of duties we try to practice at my organization, not to mention the silliness of having to buy an extra Visual Studio license just so it can sit on a build server and facilitate unit testing.  Frustration #1: MSTest cannot stand alone from the Visual Studio IDE.

So, let's scrap MSTest like Jeff Palermo did and go with one of the open source testing frameworks like NUnit (maybe, some day, Microsoft will decouple MSTest from Visual Studio).  That's great, but how do I calculate code coverage?  Visual Studio Team System will calculate code coverage but I assume that only works against tests written on the MSTest framework.  If I don't go MSTest, I guess that means I'll have to scrape together a few bucks (albeit not that much) and buy something like NCoverFrustration #2: VSTS Code Coverage only works with MSTest (this is an assumption, to be sure, so if I'm wrong here, someone please let me know--and let me know how to configure VSTS to calculate code coverage on NUnit tests).

Alright: let's assume we've moved past the unit testing and code coverage issues.  We've made all the right decisions so that our code is going through formal builds and unit tests on a nice, clean build server.  Now, how do we push out our compiled artifacts to our Production server?  I get the impression that most folks at Microsoft advocate either XCopy or Visual Studio Publish.  These tools either require the Visual Studio IDE outright or a deeper knowledge of Microsoft deployment tools than the average deployment lackey will have (remember, separation of duties means that developers won't be the individuals deploying applications to Production servers).  

Personally, I'm a fan of deploying via Windows Installer files--that is, an MSI or installation EXE.  What's more, Visual Studio includes Setup project templates that make it easy for a developer to author the script that installs his product on the Production server--after all, who better knows how an application should be installed on a server than the developer himself?  

So, on my clean build machine, I have MSBuild or, perhaps, Nant compile my source code, run my unit tests, and maybe even do some code analysis.  Once that's all done, I have MSBuild use the instructions of my Setup project to build my MSI and...er, that didn't work?  You mean to tell me that MSBuild can't build my Setup project?!  Well, that's just nice.  And what's Microsoft's suggestion: use devenv.exe.  Yes, once again, sully my formal build environment with the Visual Studio IDE.  Frustration #3: MSBuild can't build my MSI.  

So, now, I either have to scrape together more dollars for a commercial product like Wise or InstallShield or learn to grapple with Windows Installer Xml (there do appear to be some MSBuild tasks for building WiX artifacts, though).

Confound it, Microsoft!  You have great tools, but your build and deploy story is a Grimms fairy tale!  Ok.  I feel a little better (not really).  If I'm totally off track here or if you have any better suggestions, please let me know.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by Brad on Sunday, October 26, 2008 9:12 PM
Permalink | Comments (19) | Post RSSRSS comment feed