Thursday, September 23, 2010

Covariance & Contravariance Examples

I recently held a discussion on this topic and put together some sample code for demonstration purposes. Here it is if anyone is interested. It goes along with Part 1 of the Covariance & Contravariance discussion.

Monday, September 20, 2010

Covariance & Contravariance - Part 1

One of the new features of C# 4.0 is support Covariance and Contravariance. The most basic example of the concept is pretty straightforward to grasp, but after further inspection, you'll find it can be tricky. In short, the concept describes how to determine equivalence between types. There are only 3 cases to consider when determining if two types are equivalent. Given two types S and T:
  1. S is more general than T.
  2. S is more specific than T. 
  3. Neither case 1 nor 2.

Covariance
You already know from experience that in case 1, you can assign an instance of type T to a variable of type S. The reason you can do this is because the compiler assumes that because S is a superclass (more general) than T, then a variable of type S can surely point to an instance of type T. This type of determination by the compiler is called Covariant

Covariance has actually been around since .NET 1.0, we just didn't realize it. Take the following example:
Employee[] employees = new Employee[10];
Person[] people = employees;
 


Array assignments in C# have always been assumed to be covariant. When C# 2.0 came around, they added another kind of implicit covariance. Take a look at the following:

delegate TOut GetItem<TOut>();

Programmer GetProgrammer()
{
    return new Programmer();
}

GetItem<Employee> getEmployee = GetProgrammer;
 

This should make sense because if I execute getEmployee, the result would still be an instance of type Employee since a Programmer is an Employee. The equivalence operation is going from specific to general, which is known as covariance.



Contravariance
Following from our previous example, if we take our types and instead of making them be the return type, we make them the parameter type, we get the following:
delegate void PutItem<TIn>(TIn item);

void PutProgrammer(Programmer item) { }

PutItem<Employee> putItem = PutProgrammer;
 


All we've done is move the types from being a return value, to a parameter value. If you were to try this, it would be illegal in C# because you could potentially pass in an instance of ProductManager into the putItem method reference; which would mean you're passing in a ProductManager instance into the PutProgrammer method which expects a Programmer. So if the PutProgrammer method were accessing a Programmer specific property such as KnownProgrammingLanguages, it would fail because that property doesn't exist on a ProductManager. In order to make this legal, we'd have to reverse the types in the assignment operation on line 5, and the type in the method on line 3:
delegate void PutItem<TIn>(TIn item);

void PutEmployee(Employee item) { }

PutItem<Programmer> putItem = PutEmployee;
 

Now this is valid because I can only put a Programmer instance into the putItem method, the PutEmployee method that putItem points to will be able to accept the Programer instance since a Programmer is an Employee. Notice now that the operation on line 5 is now reversed. This is an example of case 2 because the equivalence operation on line 5 is now going from general to specific. This is known as contravariance, which (surprise!) is the reverse of covariance. 


Naturally, methods are covariant in their return types, and contravariant in their parameter types. This is not always the case, but is an important observation.


In Covariance & Contravariance - Part 2, I'll go into how this seemingly meaningless knowledge can be applied to C# 4.0.

Wednesday, September 15, 2010

Visual Studio Tips

I recently attended a class led by John Robbins on .NET Debugging which discussed how to use the various debugging tools in Visual Studio. There were a few ticks I found interesting that I thought I'd share.


Quickly Find a File and Open it
If you are like me and have solutions and projects that contain lots of files, it can sometimes be a trick to remember where that one particular file is. You can't remember the exact name, but know what it starts with. Pressing CTRL+D (the default hot key for Edit.GoToFindCombo) and then typing >open followed by the partial name of the file will bring down the list of files. You can then select the file of interest and press Enter to open it.


Placing a Breakpoint in a Function
Sometimes you know the name of a function that you want to place a breakpoint in, but don't have the file open. A quick way to put a breakpoint at the function is to press CTRL-D (the default hot key for Edit.GoToFindCombo), type the name of the function, and press  F9. This places a break point on the first line of the specified function. This is pretty useful if you are looking at a log file with a stack trace and want to jump straight to a particular function and debug.


Seeing the Current Exception
There are times when you catch an exception but don't care about the actual exception instance.


try
{
}
catch(InvalidOperationException)
{
    // Do something special, then throw
    throw;
}
When you're debugging, you might need the actual instance to dig deeper into the cause. If you put $exception into your watch window, you 'll see it.

Friday, September 10, 2010

Single Sign-on for Cross Domain Applications

In general, web authentication puts a cookie in your browser that says, "I've authenticated with you, and I am who I say I am." This is works great until you have parts of your application that exist on another domain; or even multiple applications for that matter. The system breaks down in this scenario because a cookie put into the browser is only accessible to the domain (and sub domains) that created it.

For example, if you have www.MyServiceA.com and you login there, it puts a cookie into your browser that says you've authenticated. When you visit other parts of www.MyServiceA.com, they see the cookie and give you access. If www.MyServiceA.com links you to www.MyServiceB.com, the latter site will not have access to the cookie created for www.MyServiceA.com and will force you to login again.

The Basic Approach
One method of doing this requires several redirects and passing the cookie info in a URL string.


At step 1, the user logs into mail.com/login and gets the authentication token xyz. The user then clicks a link that takes them to calander.com/default (step 2), which sends back a redirect to a special page on mail.com that gets the authentication cookie and sends it back in the URL's query string (step 3). The redirect from step 3 sends the browser to a special page on calander.com that looks at the query string to determine the cookie value and sets the cookie in the browser accordingly (step 4), redirecting the user back to the original page at calander.com requested in step 2.

A Simpler Approach
This solution works, but when I first saw it I thought there had to be a better way. Upon further research, I found that you can actually simply things by combining steps 3 and 4 into an HTML img tag. The silence and blank expression on your face tell me you need more explanation.

The trick, is to include an image tag that has its source set to the special setCookie URL at calander.com, passing the current authentication token in the query string part of the URL. This way when the browser renders the image on the mail.com page, it will hit the URL (which has the authentication token in its query string), which will be giving the cookie value to the other domain (calander.com). The other domain can then take the cookie value and tell the browser to set that cookie for the calander.com domain. Now when the user navigates to calander.com the cookie will be available and the user can be considered authenticated.

<html>
    <head>
    </head>
    <body>
        <script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                var singleSignOnUrl = "<%= this.SingleSignOnUrl %>?c=<%= this.SingleSignOnToken %>";

                //
                // Add an image element with the source set to the special cookie
                // setter URL. Since the URL is not responding with a valid image,
                // the element's onload event will not fire. Instead, the onerror
                // event will be fired after the special URL finishing processing.
                //
                $("#img").attr("src", singleSignOnUrl));
            });

            function onError() {
                    $("#lblMessage").text("Cookie in the other domain has been set!");
                    // Make link to calander.com available
            }
        </script>        
  <img id="img" style="display: none;"></img>
  <span id="lblMessage">Setting cookie...</span>
    </body>
</html>

The example above assumes you have an aspx page with SingleSignOnUrl and SingleSignOnToken properties on the page that return the special calander.com/setCookie and authentication cookie value respectively. The setCookie page could be an http handler (setCookie.ashx) that does something like this:

///////////////////////////////////////////////////////////////////////////
    /// 
    /// Handler that looks for a specific query string parameter and reflects
    /// it back as a cookie.
    /// 
    ///////////////////////////////////////////////////////////////////////////
    public class SingleSignOnHttpHandler : IHttpHandler
    {
        ///////////////////////////////////////////////////////////////////////////
        /// Key used to represent the single sign on token.
        ///////////////////////////////////////////////////////////////////////////
        public const string AuthenticationTokenKey = "authentication-token";

        ///////////////////////////////////////////////////////////////////////////
        /// 
        /// Initializes a new instance of the  class.
        /// 
        ///////////////////////////////////////////////////////////////////////////
        public SingleSignOnHttpHandler()
        {
        }

        #region IHttpHandler Members

        ///////////////////////////////////////////////////////////////////////////
        /// 
        /// Gets a value indicating whether another request can use the  instance.
        /// 
        /// 
        /// true if the  instance is reusable; otherwise, false.
        /// 
        ///////////////////////////////////////////////////////////////////////////
        public bool IsReusable
        {
            get { return true; }
        }

        ///////////////////////////////////////////////////////////////////////////
        /// 
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the  interface.
        /// 
        /// An  object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.        ///////////////////////////////////////////////////////////////////////////
        public void ProcessRequest(HttpContext context)
        {
            //
            // Take the appropriate query string parameter and reflect it back as a cookie.
            //
            context.Response.ContentType = "text";
            context.Response.AddHeader("p3p", @"CP=""NON ADM OUR""");

            string value = context.Request.QueryString["c"];
            if (value.IsValid())
            {
                context.Response.SetCookie(new HttpCookie(AuthenticationTokenKey, value));
            }
        }

        #endregion
    }

The p3p header information is necessary for compatibility with Internet Explorer. Without that header, IE would ignore the returned cookie.

At this point, once the user accesses the page at mail.com with the hidden image, the users's browser will have the authentication cookie set in both the mail.com and calander.com domains, which will allow them to navigate between the two domains without having to authenticate.

Tuesday, June 8, 2010

Refactoring Comments in Visual Studio 2010

I just refactored some function arguments in Visual Studio 2010 and saw that it now also refactors your function XML comments as well! One of the minor pain points up until now when you refactor your function arguments is that you have to remember to also update the arguments in your function XML documentation. It was nice to see that those XML function comments are also updated during the refactor.

Thursday, May 27, 2010

Customized Drop Folder in Team Build 2010

In my experience, build output that's ready to be deployed is rarely flat. Meaning that there are many components and layers in a system and having the binaries all be in one directory is pretty useless. In my situation, I had a custom MSBuild script that took the outputs from many different solutions and projects and organized them into a final output folder. I did this so that local builds outside of Team Build would benefit from the same folder structure. The problem is that Team Build 2010 was not playing nice when it came to my custom build script doing all of the output folder structuring. Organizing the output in prior versions of Team Build could be done by overriding the [TargetName] target in your TFSBuild.proj file. In Team Build 2010 however, things are different. 2010 uses Windows Workflow 4.0 for build orchestrating and MSBuild for the actual build, therefore there's not a target to override.

The solution is to clear the OutDir property so that projects built will use their default output location. You can then pass in the "would be" output location as another property and use that in your build script.

Find the MSBuild activity in the workflow and select it.

Clear the value in the OutDir property and update the CommandLineArguments property.

When setting the CommandLineArguments, you can pass in the value that used to be passed into the OutDir property.

String.Format("/p:SkipInvalidConfigurations=true;MyOutputDir=""{0}"" {1}", outputDirectory, MSBuildArguments)

The fact that the OutDir property is now empty keeps the default output directories for your projects in tact. You can then use your custom MyOutputDir to manually structure your output. The final drop site is created from a full copy of the output directory, so as long as your output directory looks right, the drop site will as well!

Monday, May 24, 2010

MSBuild Batching & Item Metadata

When it comes to build scripts, I'm in the NAnt camp. However, I recently found a scenario where it made more sense to use MSBuild and found the basics easy to understand because the ideas are the same as NAnt. One of the more interesting things in MSBuild is batching. Batching allows you to execute a task over a set of items in a foreach loop style.
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Sample">
  
  <Target Name="Sample">
    <ItemGroup>
      <MyItem Include="#1">
        <Name>Item 1</Name>
        <Description>Description for Item 1</Description>
      </MyItem>
      <MyItem Include="#2">
        <Name>Item 2</Name>
        <Description>Description for Item 2</Description>
      </MyItem>
      <MyItem Include="#3">
        <Name>Item 3</Name>
        <Description>Description for Item 3</Description>
      </MyItem>
      <MyItem Include="#4">
        <Name>Item 4</Name>
        <Description>Description for Item 4</Description>
      </MyItem>
    </ItemGroup>

    <Message Text="-- Using '@' --"/>
    <Message Text="@(MyItem)" />
    <Message Text=" "/>
    <Message Text="-- Using '%' --"/>
    <Message Text="%(MyItem.Identity): %(MyItem.Name) - %(MyItem.Description)" />
  </Target>
  
</Project>
Running the above gives you:
-- Using '@'--
  #1;#2;#3;#4

  -- Using '%' --
  #1: Item 1 - Description for Item 1
  #2: Item 2 - Description for Item 2
  #3: Item 3 - Description for Item 3
  #4: Item 4 - Description for Item 4

The difference in the two is how the item group is prefixed. The '%' character tells MSBuild to expand the batch and iterate over each item in the batch; the '@' symbol tells MSBuild to join the items into one list. Also notice how I've used metadata (i.e. Name, Description) to have properties associated with each item that can be used in each iteration. The built in property 'Identity' returns whatever is in the 'Include' attribute of the item. One thing you should know is that the 'Include' attribute must be unique and is required if you are going to execute a batch.

Usefulness
In my scenario, I had a set of files that I needed copied from one location to another using xcopy.
<Target Name="RealWorldScenario">
    <ItemGroup>
      <Component Include="ProjectA" />
      <Component Include="ProjectB" />
      <Component Include="ProjectC" />
    </ItemGroup>

    <Exec Command="xcopy /Y $(BaseDir)\bin\%(Component.Identity)\*.dll $(Output)" />
    <Exec Command="xcopy /Y $(BaseDir)\bin\%(Component.Identity)\*.xml $(Output)" />
    <Exec Command="xcopy /Y $(BaseDir)\bin\%(Component.Identity)\*.config $(Output)" />
    
  </Target>

In my situation, I didn't want to duplicate the 3 copy commands for each component. I wanted to make it so that as new components are developed, you only have to add it to the item group.

Tuesday, May 11, 2010

Supporting Multiple Logins in a Windows Application

One of the issues that can come up when you're developing a line of business application is the ability to support a user logging out, then logging back in as a different user. This really only becomes an issue when you're trying to access resources that require an IPrincipal to be set. The first thing someone does in this situation is make a call to AppDomain.CurrentDomain.SetThreadPrincipal  with the principal of the user who just logged in. However, the second time you call this method (i.e. the user logged out and logged back in), you'll get a PolicyException: Default principal object cannot be set twice.

Don't even try it
You can always set the current thread's principal by calling Thread.CurrentPrincipal. So why can't you just set this on the UI thread each time the user logs in? This trick will not work because the .NET framework captures the execution context (i.e. credentials and other stuff) every time something is dispatched to the UI thread. It then restores that execution context when the message is being handled, and throws away the context when it's done. In other words you can set the principal, but it will be thrown away before the next UI event. .NET does this because it could be a potential security flaw. What if someone handled a UI event in your application and decided to post some work to be done that you didn't want them to have permission to do? Trapping the execution context keeps the security of the code that posts the work, the same as the code that executes the work.

My Solution
There are many solutions to this problem, and coming up with them is not hard. I just thought I'd share one that you might find elegant. The idea is to store the IPrincipal of the logged in user in your own class, and set the current thread's principal before making any calls that require that authentication. This sounds like a pain, but it doesn't have to be. You can setup an IDisposable object that when created, sets the current thread's IPrincipal and then restores the previous value when the object is disposed of.
public class ClientSecurityContext
{
    public static IPrincipal CurrentPrincipal
    {
        get;
        set;
    }

    public static IDisposable CreateSecurityContext()
    {
        //
        // Save a copy of the previous IPrincipal so we 
        // can restore it when the caller is finished.
        //
        IPrincipal previous = Thread.CurrentPrincipal;

        //
        // Set the current thread's principal.
        //
        Thread.CurrentPrincipal = CurrentPrincipal;

        //
        // Return a notifier that will call the action 
        // when the caller disposes of it. This will be 
        // used to restore the previous IPrinicpal back 
        // on the current thread.
        //
        return new DisposeNotifier(
            () => Thread.CurrentPrincipal = previous);
    }
}

The above code makes use of a handy DisposeNotifier object that calls a delegate when it's disposed of. It's really just my laziness in creating a special class just for this purpose. You can see how a call using this would look in action.
private string[] GetEmployeesUsingService()
{
    using (ClientSecurityContext.CreateSecurityContext())
    {
        //
        // This is where you would make a call that 
        // requires a particular IPrincipal.
        //
        return new string[]
        {
            Thread.CurrentPrincipal.Identity.Name,
            "Ben Bernanke",
            "Tim Geithner"
        };
    }
}

Download the sample project here if you're needing to support something like this.

Thursday, May 6, 2010

Javascript and 'this' keyword

One of the most confusing things about javascript is function scope the this keyword. I mostly use it for setting fields and accessing member functions from within my javascript class. Depending on how you call the methods, this be something you wouldn't expect.

For those of you who don't know what the this keyword is, it always points back to the object that owns the function your in. Most problems come up when you think your getting the owning object, but instead your getting the current window object. Huh? Taking the example in this article, notice the different behaviors depending on how the methods are being called.
function  foo()
{
    var privateVal = "Private Val";
    this.publicVal = "Public Val";

    var privateAlert = function(str)
    {
        alert(str + this.publicVal);
        alert(str + privateVal);
    }

    this.Run = function()
    {
        privateAlert("Private Call: ");

        this.publicAlert = privateAlert;
        this.publicAlert("Public Call: ");
    }
}

var bar = new foo();
bar.Run();
And here is the output from that:
Private Call: undefined
Private Call: Private Val
Public Call: Public Val
Public Call: Private Val
The interesting behavior is that we're calling the same function, but in two different ways. When calling the function from the this keyword, the interpreter is correctly setting this inside the scope of the function. When calling without the this keyword, it uses the global (window) scope. The reasoning behind this can be found in the javascript spec, or you could take a look at the above referenced article. In short, if you call a function without a preceding object (i.e. this.aFunction(), or MyClass.aFunction()), then this gets defaulted back to window.

So what are you suppose to do? The article mention above proposes a solution to create a private class field call me that is initialized to point to this. The object that this points to at the time me is initialized will what you would expect. That way you can always use me instead of this throughout your class implementation. That's definitely a simple solution, but my VB nightmares scare me away from anything that uses me. One of the ways in which I get around this issue is by making use of the bind method from Prototype.
Function.prototype.bind = function(obj) 
{ 
    var method = this, 
    temp = function() 
        { 
            return method.apply(obj, arguments); 
        }; 
  
    return temp; 
 } 

This function wraps a new function around the calling function while binding that calling function to the obj parameter. Huh? This explains it pretty well. Let me show you how we can use it keep the value of this consistent with what we would expect.
function  foo()
{
    var privateVal = "Private Val";
    this.publicVal = "Public Val";

    var privateAlert = (function(str)
    {
        alert(str + this.publicVal);
        alert(str + privateVal);
    }).bind(this);

    this.Run = function()
    {
        privateAlert("Private Call: ");

        this.publicAlert = privateAlert;
        this.publicAlert("Public Call: ");
    }
}

var bar = new foo();
bar.Run();
Notice that I've added the bind call to the private function so that any references to this inside that private function will be reference the expected object. If you run the above code, this is the output you would now get.
Private Call: Public Val
Private Call: Private Val
Public Call: Public Val
Public Call: Private Val
That's more inline with what we would expect!

Monday, April 26, 2010

Spring.NET & Attribute Driven Configuration

I've been using Spring.NET for years for dependency injection and database transaction handling. I love it's ability to be extensible, but at the same time despise it's learning curve for new users. I get a lot of push back from people when they start using Spring because they don't like putting in the XML configuration and then spend time reading through exceptions to see what kind of typos they've had.

I was playing around with the Managed Extensibility Framework (MEF) and decided to steal some of its ideas. I wanted to provide an attribute drive dependency injection framework built on Spring.NET. This is something that is easier for developers to pick up, and avoids the error prone XML configuration. I wanted to put something together that would play nice with existing Spring configurations and was declarative. Although placing attributes in your classes couples them with the dependency injection framework, it provides a readable up front way to see how dependencies are being resolved.

The idea here, is to have something scan all classes in an assembly and for each class marked with an Export attribute, create a Spring.NET object for it. Any class being exported can also have its dependencies set by marking such properties with an Import attribute. Any property marked with an Import attribute will attempt to have its dependencies set.

[Import] & [Export] Attributes
[Export]
public class ViewModel : INotifyPropertyChanged
{
[Import]
public IModel Model { get; set; }

:
}
[Export(typeof(IModel))]
class Model : IModel
{
public string LoadData()
{
return "Here is some data!";
}
}

When a class is exported, it defines a contract name. This contract name is later used by those who wish to import an implementation of that contract. To make things easier, you can also use a System.Type as the contract, which is simply converted to its string representation.


Placing the Import attribute on a property tells the scanner to look at the specified contract name and find an implementation that has been exported with that contract name. Just like the Export attribute, if no contract name is specified it uses the System.Type of the property as the contract name. If you had some object definitions defined in a higher (or the same) IApplicationContext, you can use those object IDs as contract names and have them injected into the property.

Startup
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);

//
// Load Spring
//
GenericApplicationContext context = new Spring.Context.Support.GenericApplicationContext();
ObjectDefinitionScanner scanner = new ObjectDefinitionScanner(context);
scanner.Scan(System.Reflection.Assembly.GetExecutingAssembly());

//
// Load Main Window
//
this.MainWindow = (Window)context.GetObject(typeof(MainWindow).FullName);
this.MainWindow.Show();
}
}

To get things started, you pass in your current IApplicationContext into an ObjectDefinitionScanner; which scans the assembly and creates object definitions from the Import and Export attributes found. Notice that you can pass in an existing IApplicationContext that already has definitions in it (i.e. from XML) and reference those definitions in the attributes.

Download sample code here.