Tag Archives: c#

Windows Identity Impersonation Made Easy(ish)

There are lots of different reasons why you would want to use identity impersonation in an application. The most common situation that I see is that you need to access a network resource, and you’ve been given a domain user account and password that has rights.

It would be nice to have an easy way to do the impersonation without having to do a lot of mucking around. I sat down to do this and came up with a nice, simple solution that does just that. I used this MSDN article as the basis for my solution, and there was a small amount of copying/pasting involved. I’m going to work my way backwards through the solution and then present the entire solution at the end.

What I wanted to have in the end was an extension method that could be used from any object. This was the goal usage:

var f = new Foo();
f.ExecuteAs(domainName, userName, password, x => x.Bar("Hi!"));

In order to have the extension method available, I needed to have a static class with a static method. The static method should accept the user credentials necessary to authenticate and the actual method to be executed.

public static class ExecuteAsExtension
{
    public static void ExecuteAs<T>(this T source, string domainName,
        string userName, string password, Action<T> action)
    {
        var token = GetToken(domainName, userName, password);
        using (token)
        {
            var identity = new WindowsIdentity(token.DangerousGetHandle());
            using (identity.Impersonate())
            {
                action(source);
            }
        }
    }
}

So that’s pretty easy! Now we just need to implement the GetToken method. This is the part of my solution that relies on the aforementioned MSDN article. I’ll just post the entire contents of my ExecuteAsExtension.cs file so that you can see it all:

using System;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;

namespace MyImpersonationNamespace
{
    public static class ExecuteAsExtension
    {
        [DllImport("advapi32.dll", SetLastError = true,
            CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String lpszUsername,
            String lpszDomain, String lpszPassword,
            int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);

        internal static SafeTokenHandle GetToken(string domainName,
            string userName, string password)
        {
            SafeTokenHandle safeTokenHandle;

            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token.
            const int LOGON32_LOGON_INTERACTIVE = 2;

            // Call LogonUser to obtain a handle to an access token.
            bool returnValue = LogonUser(userName, domainName, password,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                out safeTokenHandle);

            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                throw new System.ComponentModel.Win32Exception(ret);
            }

            return safeTokenHandle;
        }

        public static void ExecuteAs<T>(this T source, string domainName,
            string userName, string password, Action<T> action)
        {
            var token = GetToken(domainName, userName, password);
            using (token)
            {
                var identity = new WindowsIdentity(token.DangerousGetHandle());
                using (identity.Impersonate())
                {
                    action(source);
                }
            }
        }
    }

    public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle()
            : base(true)
        {
        }

        [DllImport("kernel32.dll")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        protected override bool ReleaseHandle()
        {
            return CloseHandle(handle);
        }
    }
}

To recap, using this new extension method to execute a function as another use requires just two steps:

  1. Add a using statement for your extension method’s namespace
  2. Use the extension method to execute a function

For reference, here is my test console application:

using System;
using System.Security.Principal;
using MyImpersonationNamespace;

namespace MyImpersonationNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            var domainName = "XP";
            var userName = "Administrator";
            var password = "SecretPassword";

            Console.WriteLine("Starting as {0}",
                WindowsIdentity.GetCurrent().Name);
            var f = new Foo();
            f.ExecuteAs(domainName, userName, password, x => x.Bar("dude"));
            Console.WriteLine("Finishing as {0}",
                WindowsIdentity.GetCurrent().Name);
            Console.ReadLine();
        }
    }

    class Foo
    {
        internal void Bar(string name)
        {
            Console.WriteLine("Executing as {0}",
                WindowsIdentity.GetCurrent().Name);
            Console.WriteLine("Hello, {0}!", name);
        }
    }
}

9/28/2012 Update:
Fixed a bug in the ExecuteAs methods above where the “Action action” argument should be “Action<T> action”
Also, here’s the static class implementation provided by ericrouse in his comment. Thanks, Eric!

public static void Action(SecurityKey securityKey, Action action)
{
	using (SafeTokenHandle token = GetToken(securityKey.Domain, securityKey.UserName, securityKey.Password))
	{
		WindowsIdentity identity = new WindowsIdentity(token.DangerousGetHandle());

		using (identity.Impersonate())
		{
			action();
		}
	}
}

/* Usage:
ExecuteAs.Action(SecurityKey,
    () =>
    {
        // Perform some action
    });
*/

11/5/2012 Update:
I was having some problems using this code to access a UNC path from within a unit test. The solution was to change the Logon Type parameter from “Interactive” to “New Credentials.”

const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

bool returnValue = LogonUser(userName, domainName, password,
                LOGON32_LOGON_NEW_CREDENTIALS, 
                LOGON32_PROVIDER_DEFAULT,
                out safeTokenHandle);
Advertisements

Testing Hard-to-Test Code with Rhino Mocks

One of the most common gripes that I hear about getting started with unit testing is that the code isn’t testable or it doesn’t have a testable design. People will make claims like, “We need X hours to make the project testable before we can start writing tests.” Well, I don’t buy into that. There are techniques that you can employ to extract the pieces of code you’re modifying into little, testable nuggets that have nothing to do with the rest of the not-so-test-friendly project. I’m going to cover two of my favorite, most-commonly used techniques in this post.

Extract the code to be tested.

This is a pretty straightforward solution to a not-so-obvious problem. The most common scenario that I’ve seen for this technique is the “monster function.” I’m sure you’ve seen this before. It’s the 1000-line function that contains all the logic for the module or application you’re modifying. This is a classic hard-to-test situation because, at first glance, it seems like you need to set up everything necessary to complete the entire process in order to do any sort of unit testing.

To transform this mess into an unit testing masterpiece, you just need to do what nobody before you thought of: create a new function. Your new function can do whatever you need it to do. It can accept inputs. It can return outputs. And, it can do it all in a testable manner! So, make your function, test the hell out of it, then call your function from the appropriate place in the main function. Congratulations–you just made a unit tested change to a previously non-testable function.

Extract the code to be avoided.

The second scenario is a little more difficult, and the solution is a little less obvious. I use this technique when I’m dealing with external dependencies that aren’t enough to warrant an entire interface or when I’m working with tricky internal dependencies. Let’s look at an example. Consider the following function:

public class HardToTest
{
    public void ProcessFile()
    {
        string contents;
        using (var fs = new FileStream(@"c:\data.xml", FileMode.Open))
        {
            var sr = new StreamReader(fs);
            contents = sr.ReadToEnd();
        }
        // Do something interesting with file contents
    }
}

When sitting down to write a unit test for this function, you might be tempted to create a “data.xml” file in the root directory of the C drive during TestInitialize. That would probably result in a passing unit test on your machine, but please, don’t do that. You can trust that the FileStream and StreamReader objects will do their jobs correctly, so let’s just take them out of the equation for our unit testing. With a quick refactor, we end up with something like this:

public class HardToTest
{
    public void ProcessFile()
    {
        string contents = GetFileContents();
        // Do something interesting with file contents
    }
    
    internal protected virtual string GetFileContents()
    {
        using (var fs = new FileStream(@"c:\data.xml", FileMode.Open))
        {
            var sr = new StreamReader(fs);
            return sr.ReadToEnd();
        }
    }
}

Ok, great! Now, here’s where it gets fun. We can write a test for this function by mocking just the function we’re trying to avoid. Check it out:

[TestMethod()]
public void ProcessFileTest()
{
    HardToTest target = MockRepository.GeneratePartialMock();
    target.Expect(x => x.GetFileContents()).Return("File contents!");
    target.ProcessFile();
    target.VerifyAllExpectations();
}

Because we made our GetFileContents function virtual, the generated mock class can override its functionality. The Partial Mocks gives us this functionality; if the function were not overridden, it would be called as-is and would try to read from the hard-coded file path.

You could stick with this same approach to handle different scenarios that might arise in the isolated code. For instance, what would happen if the file did not exist? You would expect the isolated code to throw a System.IO.FileNotFoundException, right? Well, let’s test that!

[TestMethod]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void ProcessFile_ThrowsFileNotFoundException()
{
    HardToTest target = MockRepository.GeneratePartialMock();
    target.Expect(x => x.GetFileContents()).Throw(
        new System.IO.FileNotFoundException());
    target.ProcessFile();
}

Some additional notes about this solution:

  • The function must be internal (see next note) protected (prevents calling of the function while setting expectation) virtual (allows function to be overridden).
  • The target project must expose its internals to the test project. This can be done by adding the “[assembly: InternalsVisibleTo(“YourTestProjectName”)]” attribute to the target project’s assembly.info file. You can read more about this attribute here.

Getting Started with Rhino Mocks (AAA)

When you’re writing unit tests for your code, you want to write specific tests for specific units. Unfortunately, it is not uncommon for you code to have many external dependencies that may not be related to the functionality that you’re trying to test. This is where one of my very favorite unit testing tools, Rhino Mocks, comes into play.

Rhino Mocks is great because it allows you to mock or stub objects in your code so that you can really focus on the functionality that you’re trying to test without having to worry about doing an excessive amount of setup or external dependencies.

When you’re getting started with Rhino Mocks, one of the most confusing things that you’ll run into is that there are several different syntaxes that can be used to accomplish the same thing. The AAA (Arrange, Act, Assert) syntax is the newest and was introduced with version 3.5. The primary distinction of the AAA syntax is that you don’t need to create and manage a MockRepository object and its various states.

In this article, I will walk you through the task of writing a unit test using Rhino Mocks.

So, before we begin writing our tests, let’s look at the code we’ll be testing.

public class Controller
{
    public IDataSource DataSource { get; set; }

    public int[] Data { get; set; }

    public void Process()
    {
        if (this.DataSource.DataAvailable())
        {
            this.Data = this.DataSource.GetData();
        }
    }
}

We can see that we have a Controller class that utilizes some sort of IDataSource object to check for and retrieve data. When we’re testing our controller class, we may or may not have access to our data source, though. And, even if we do have access to the data source, we may not have complete control over it. So this is an excellent situation to employ Rhino Mocks!

The first step to using Rhino Mocks is simply adding a reference to your project. Once the reference is in place, we can add the using statement to the top of our test class and get to mockin’.

Creating a mock object is extremely simple with Rhino Mocks’s AAA syntax. You just use the static MockRepository class’s GenerateMock function.

var mockDataSource = MockRepository.GenerateMock();

Now that we’ve created our mock object, we need to configure our target object to use it. In this case, our class’s IDataSource is a public property on the class. So configuring the target object is a simple assignment.

Controller target = new Controller();
target.DataSource = mockDataSource;

Okay, great! Our next step is to set the expectations for our mock object. For our first test, we’ll just have the call to DataAvailable return false.

mockDataSource.Expect(x => x.DataAvailable()).Return(false);

The last steps for this test are to run the function we’re testing and verify that our mock object was used as expected.

target.Process();
mockDataSource.VerifyAllExpectations();

When we run this test, the Process function will call our mock object’s DataAvailable function–which we have pre-configured to return false–and the test will pass as long as DataAvailable is called.

We can run this test, and it should pass. Awesome, now let’s write another test. This time, we’ll have DataAvailable return true. We create the mock object the same way as previously, but we’ll need to set the expectations differently.

mockDataSource.Expect(x => x.DataAvailable()).Return(true);
var data = new int[] {1, 2, 3};
mockDataSource.Expect(x => x.GetData()).Return(data);

Since we’re passing some data in, we can also add an extra assertion in our unit test.

mockDataSource.VerifyAllExpectations();
Assert.AreEqual(data, target.Data);

This unit test will fail unless both DataAvailable and GetData are called. Additionally, the target object’s Data property must be the object returned by GetData.

Here is the complete text for the two unit tests we’ve just created.

[TestMethod()]
public void ProcessTest_DataAvailableReturnsFalse()
{
    var mockDataSource = MockRepository.GenerateMock();

    Controller target = new Controller();
    target.DataSource = mockDataSource;

    mockDataSource.Expect(x => x.DataAvailable()).Return(false);

    target.Process();
    mockDataSource.VerifyAllExpectations();
}

[TestMethod()]
public void ProcessTest_DataAvailableReturnsTrue()
{
    var mockDataSource = MockRepository.GenerateMock();

    Controller target = new Controller();
    target.DataSource = mockDataSource;

    mockDataSource.Expect(x => x.DataAvailable()).Return(true);
    var data = new int[] { 1, 2, 3 };
    mockDataSource.Expect(x => x.GetData()).Return(data);

    target.Process();
    mockDataSource.VerifyAllExpectations();
    Assert.AreEqual(data, target.Data);
}

Getting Started with Linq to XML

I was out at a customer site a few weeks ago and needed to whip up a quick program to extract a large number of values from an XML document. To me, the obvious way to accomplish this task was to write a quick application to read the XML, parse the values, and write them to a separate document. Linq to XML made this cumbersome task very easy, and I was reminded of just how amazing Linq to XML really is.

Linq to XML is one of the best things to happen to XML in recent history, but I think there are still a lot of developers out there who are either not familiar with Linq or are just comfortable working with XML using the same techniques that they always have. I haven’t done an extensive amount of XML processing in my career, but I haven’t exactly been a stranger to it, either. In my opinion Linq to XML makes working with XML downright trivial. If you haven’t looked into it, I definitely recommend that you do!

For the purposes of demonstration, consider an XML file “data.xml” with the following contents:

<Library>
  <Books>
    <Book>
      <Title>A Study in Scarlet</Title>
      <Author>Sir Arthur Conan Doyle</Author>
    </Book>
    <Book>
      <Title>A Thief in the Night</Title>
      <Author>E. W. Hornung</Author>
    </Book>
  </Books>
</Library>

Using Linq to XML, you can write code to parse the contents of the file into easy-to-use objects.

var xml = XDocument.Load(@"data.xml");
var data = from n in xml.Descendants("Book")
           select new
           {
               Author = n.Element("Author").Value,
               Title = n.Element("Title").Value
           };

foreach (var d in data)
    Console.WriteLine("{0},{1}", d.Title, d.Author);

Looking for a specific value in the XML? Just modify your Linq query!

var xml = XDocument.Load(@"data.xml");
var data = from n in xml.Descendants("Book")
           where n.Element("Author").Value == "E. W. Hornung"
           select new
           {
               Author = n.Element("Author").Value,
               Title = n.Element("Title").Value
           };

So cool!

Unit Testing: Hello, World!

The “Hello, World!” of unit tests typically involves a function that accepts inputs and provides an expected output. Consider the following Calculator class:

public class Calculator
{
    public static int Add(int x, int y)
    {
        return x + y;
    }
    public static int Divide(int dividend, int divisor)
    {
        return dividend / divisor;
    }
}

Writing unit tests for the Add method is simple and straightforward. We can declare our inputs, come up with the expected output, execute the function and verify the result.

[TestMethod]
public void AddTest()
{
    int x = 1;
    int y = 2;
    int expected = 3;
    int actual = Calculator.Add(x, y);
    Assert.AreEqual(expected, actual);
}

The Add method is so simple that there isn’t much more you can do with it, so let’s take a look a the Divide method. Similarly to the Add method, we can write a simple unit test to verify our core behavior.

[TestMethod]
public void DivideTest()
{
    int dividend = 10;
    int divisor = 2;
    int expected = 5;
    int actual = Calculator.Divide(dividend, divisor);
    Assert.AreEqual(expected, actual);
}

Now that we have that out of the way, let’s deal with an exception case: division by zero. Before we can test or code, we must decide what we want our application to do in this scenario. I have decided that application should simply throw the default divide-by-zero exception, so let’s write a test for it to help ensure that this functionality isn’t lost with future changes.

[TestMethod]
[ExpectedException(typeof(System.DivideByZeroException))]
public void DivideTest_DivisionByZero()
{
    int dividend = 10;
    int divisor = 0;
    int actual = Calculator.Divide(dividend, divisor);
}

By decorating the test method with the ExpectedException attribute, the test will fail if the exception is not thrown.

You can see that writing unit tests for these something-in-something-out functions can be very easy. Try to test as many different scenarios as you can come up with. Some common situations to consider are minimums, maximums, default values, and nulls. Write skeleton tests up-front to help you remember relevant scenarios to be handled by your code.

WPF Combo Box validation

I’ve been working on a small WPF project that requires some business rule validation. I thought this would be relatively simple but proved to be slightly more complicated than expected. At the end of the day, I found two relatively simple ways to perform the validation.

The first is to simply bind ComboBox.Selected item to a property and do the validation in the set block.

    private MyDataObject _someData;
    public MyDataObject SomeData
    {
        get
        {
            return _ someData;
        }
        set
        {
            _ someData = value;
            if (value == null || string.IsNullOrEmpty(value.MyProperty))
                throw new ApplicationException("SomeData is required");
        }
    }

Then, in the XAML, you just need to hook it up to treat exceptions as validation errors.

    <ComboBox.SelectedItem>
        <Binding Path="SomeData" ElementName="Window">
            <Binding.ValidationRules>
                <ExceptionValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </ComboBox.SelectedItem>

The second method gives more flexibility but requires the creation of a custom ValidationRule class.

    public class MyCustomValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value is MyDataObject)
            {
                var myDataObj = (MyDataObject)value;
                if (myDataObj.CheckCustomBusinessRules())
                    return new ValidationResult(true, null);
            }
 
            return new ValidationResult(false, "Invalid selection!");
        }
    }

And then you hook up the validation rules to use the new custom class.

    <ComboBox.SelectedItem>
        <Binding Path="SomeData" ElementName="Window">
            <Binding.ValidationRules>
                <local:PersonValidation />
            </Binding.ValidationRules>
        </Binding>
    </ComboBox.SelectedItem>

(Note that the “local” prefix requires an additional namespace at the top of your XAML file, xmlns:local=”clr-namespace:MyNamespace”)

One last tip that threw me off for a bit is that I was missing x:Name=”Window” in my Window tag at the top of my XAML; this caused the ComboBox’s SelectedItem to not bind properly and the validation rules consequently didn’t work.

SFTP Access with SharpSSH

A project that I was working on required the use of SFTP to transfer some files. I was surprised to find that there seemed to be no support for this anywhere in the .net Framework. After Googling around for a bit, I found a nice open source project called SharpSSH.

SharpSSH was surprisingly easy to use and worked great! I was able to SFTP a file in 4 lines of code:

SshTransferProtocolBase sshCp = new Sftp("127.0.0.1", "ftp", "ftp123");
sshCp.Connect();
sshCp.Put("c:\\testdoc.txt", "test123.txt");
sshCp.Close();

This was exactly what I was looking for: a simple, lightweight SFTP library. I added some exception handling and logging, removed my hard-coded values with user-defined settings, and called it a day!

Resources:
SharpSSH
http://sourceforge.net/projects/sharpssh/

freeSSHd (a free SFTP server)
http://www.freesshd.com/

Link TFS Work Items Programmatically

One of the things that’s bothered me with TFS is the need to manually link Sprint Backlog Items to Product Backlog Items. During sprint planning meetings, we use Excel to quickly create lots of sprint backlog items for everybody on the team, but then we need to go through and manually create links to related product backlog items that we use for release planning and release progress tracking.

I decided to do a little research and found that TFS work items can be linked programmatically by utilizing the Visual Studio SDK’s TeamFoundation libraries. I use a TFPT command-line wiql query to find potential link candidates, then parse work item titles for a common number than can be used to find related work items. I do another wiql query to search for the work item ID of the related product backlog item. If found, I attempt to create a link between the two work items.

Here’s the relevant code:

TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer("mytfs");
WorkItemStore store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
 
WorkItem sbiWorkItem = store.GetWorkItem(sbiId);
 
try
{
    sbiWorkItem.Links.Add(new RelatedLink(pbiId));
    sbiWorkItem.Save();
    Console.WriteLine(string.Format("Linked SBI {0} to PBI {1}", sbiId, pbiId));
}
catch (Exception ex)
{
    // ignore "duplicate link" errors
    if (!ex.Message.StartsWith("TF26181"))
        Console.WriteLine("ex: " + ex.Message);
}

Resources:
Visual Studio 2008 SDK v1.1
http://download.microsoft.com/download/c/2/0/c20073e0-c842-44a8-a4e9-7dd5d289eafe/VsSDK_sfx.exe