Tag Archive for CodeSnippets

Double Hop and ASP.NET – a workaround.


Many people have stumbled across the IIS Double-Hop issue when trying to access Active Directory information on an ASP.NET page.
In short – when we access an ASP.NET page, IIS can impersonate our user credentials for code execution (if set in the web.config). On Windows networks, impersonated credentials can’t be used to access network resources – this prevents a web-server from maliciously or accidently using the credentials of a user who innocently logged on to it to access protected network resources.
The problem is that when we try to access the Active Directory for legitimate purposes (to display the current user’s details, for instance) while impersonating the user (as SPS does by default) we can’t pass the credentials on and our AD query uses the understandbly-limited Anonymous Logon account.

The suggested workaround is to supply teh DirectoryServices request with a username and password so as not to use the impersonated credentials – but this, of course, opens up a whole set of problems relating to security and maintainability.


This workaround will work only if the IIS worker process is running under a domain account.
Under IIS 6 – this is the user specified in the Identity tab of the Application Pool.
Under IIS 5 – this is the user specified in the Identity tab of the COM+ application that is generated for the IIS application.

Since our problem arises from having our code run in an impersonation context, the solution is simply to undo the impersonation so that the executing identity isn’t the connecting user, but the user who started the process. Since we don’t have any convenient .NET WindowsImpersonationContext object we can Undo(), we’ll simply have to go deeper into Win32 code:

[DllImport(“advapi32.dll”)]
private static extern int RevertToSelf();

This very simple function (no parameters – no marshalling! Yipee!) will cancel the current impersonation session and return the actual running user – our IIS WP identity.
It would be prudent to re-impersonate the connected user after our code runs:

WindowsIdentity connectedUser = WindowsIdentity.GetCurrent();
RevertToSelf();
// DirectoryServices code here.
connectedUser.Impersonate()

If this revert/reimpersonate code is something we’ll be running a lot, it would be nice to wrap this in a nice disposable object so we can wrap our code in a using() block:

using (new UnImpersonator())
{
   // Code running as the Worker Process identity.
}

This is similar to the ImpersonationContext class I described here – the constructor will save the current Identity in a member and call Revert, and the Dispose() will re-impersonate the user.

 

Debugging HTML that is rendered at runtime.

A little tip when we’re generating HTML content on-the-fly using client-side code, whether HTC behaviours or javascript:

As we all know, when we try to View Source on such a page, the HTML we see is the base HTML that was received from the server, not the final layout after all the client-side code has run and changed things. This often makes it hard to debug, since we can’t see the final layout that the user sees. This technique will help us get the final, rendered page for debugging.

We’ll add this script block to the end of our HTML:

This can be written with our choice of scripting languages, of course. I don’t know if other platforms have objects equivalent to the FileSystemObject for easily creating a text-file. We’ll have to allow the browser to run ActiveX’s for this to work, of course.

The RenderedPage.html file we save here is the final version of the page as it is rendered, running after all other code has run (at least code that runs on load). This can often point the way to the source of the bug – especially layout bugs.

By Hook or by Crook

While trying to implement custom shortcut keys in Outlook, I came across an old column by Dino Esposito on implementing custom Windows hooks in .NET. At first I wanted to use it as reference and inspiration only, and only when I finished did I notice I simply rewrote, from scratch, most of the code he offers in his article. The main difference is that he supplies a base, generic WindowsHook class and a derived CBTHook class to handle window opening/closing/etc events, while I implemented my generic parent class and a derived KeyboardHook class for keyboard events. This is implemented as thread-local hooks on the currently running process, rather than expensive global system hooks.

The basic premise is simple – keep all the Win32 P/Invoke code well hid inside the private implementation, and have the WindowsHook class simply raise an event when the hook function is invoked, passing the hook function paraemeters as event args to the HookInvoked event.

However, since the hook parameters are different for each kind of hook, the KeyboardHook class also raises a different event, KeyPressed, that parses the hook parameters and gives more intelligble and specific meaning to the parameters – which key was pressed, as well as the state of the Control, Alt and Shift keys.

Additionally, the KeyboardHook class allows setting filters, so that the event will only be raised for specific keystrokes. This allows us to get only the keystrokes we want (say, our chosen keyboard shortcut keys).

Code such as this sample will raise the KeyPressed event whenever the user presses Ctrl-Shift-F, or Alt-F6:

KeyboardHook hook;
private void Form1_Load(object sender, System.EventArgs e)
{
  hook = new KeyboardHook();
  hook.AddFilter(Keys.F, true, false, true);
  hook.AddFilter(Keys.F6, false, true, false);
  hook.KeyPressed +=new KeyboardHookEventHandler(hook_KeyPressed);
  hook.Install();
}

KeyboardHook hook;
private void Form1_Load(object sender, System.EventArgs e)
{
  hook = new KeyboardHook();
  hook.AddFilter(Keys.F, true, false, true);
  hook.AddFilter(Keys.F6, false, true, false);
  hook.KeyPressed +=new KeyboardHookEventHandler(hook_KeyPressed);
  hook.Install();
}

private void hook_KeyPressed(object sender, KeyboardHookEventArgs e)
{
  this.label1.Text = “Found ” + e.KeyStroke.ToString();
}

void hook_KeyPressed(object sender, KeyboardHookEventArgs e)
{
  this.label1.Text = “Found ” + e.KeyStroke.ToString();
}

Full code for this class can be found in the attached ZIP file.

And thanks, again, to Dino Esposito for the inspiration, not to mention blatant plagiarism. :)

Debug Timing (and a little design pattern, to boot)

In almost every bit of code I write that’s actually destined to go into a real system, I find myself start to look for places to optimize code. But having read the writings of Rico Mariani, I am weary of premature optimizations. So what do we do? We measure, of course.
 
A full-fledged profiler is often overkill when I just want to check how long a method runs. Sometimes a few quick debug-printouts will do the job just fine. I’ve written hundreds of Debug.WriteLine(“Start block”) and Debug.WriteLine(“End Block”) statements, and it get wearisome typing the same commands, formatting the same start and end times, again and again.
 
So without further ado, he is the complete code for my little DebugTimer helper class, implemented using the Disposable Design Pattern of which I am so fond. Use it in good health.
 

public class DebugTimer : IDisposable
{
  
private DateTime start;
   private string label;
   private static int level = 0;

   public
static DebugTimer Start (string Label)
   {
      return new DebugTimer(Label);
   }

   private DebugTimer (string Label)
   {
      level++;
      this.label = Label;
      this.start = DateTime.Now;
      string message = string.Format(“{2}{0}: {1}”, this.label, “Starting”, new string(‘ ‘, level));
      System.Diagnostics.Debug.WriteLine(message);
   }

   public void Dispose()
   {
      TimeSpan time = DateTime.Now.Subtract(
this.start);
      string message = string.Format(“{2}{0}: {1}”, this.label, time.ToString(), new string(‘ ‘, level));
      System.Diagnostics.Debug.WriteLine(message);
      level–;
   }
}

EDIT: I forgot to add a little usage sample here. Should be pretty clear, but just to cover all my bases:

public void SomeMethod ()
{
   
using (DebugTimer.Start(“My Code Block”))
   {
      // Code to time.
   }
}

Disposable Unimpersonation

A while ago, I discussed the possibility of using RevertToSelf() to avoid Double Hop problems. I suggested this pattern can be wrapped inside a class implementing IDisposable to easily use it.

This is the implementation of this Unimpersonator class:

Code:

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
namespace Strawjackal.Utils
{
   public class Unimpersonator : IDisposable
   {
      private WindowsIdentity m_CurrentUser;
     
      public Unimpersonator()
      {
         m_CurrentUser = WindowsIdentity.GetCurrent();
         RevertToSelf();
      }

      public void Dispose()
      {
         if (m_CurrentUser != null)
         m_CurrentUser.Impersonate();
      }

      [DllImport(“advapi32.dll”)]
      private static extern int RevertToSelf();

   }
}

Usage:

using (new Unimpersonator())
{
   // Perform network access
}

Recycling Application Pools in IIS 6.0

A quick tip for those of us fond of iisreset. Restarting IIS takes quite a while. Sometimes 15-20 seconds, when my w3wp.exe processes are particularly unruly. In many cases, though, a full iisreset is unnecessary. Since IIS 6.0 expanded its process isolation model to include Application Pools, the simplest way is to simply recycle the application pool – takes only a second, and usually does the trick.

We can do this in .NET with very little effort:

using(DirectoryEntry appPool = new DirectoryEntry(string.Format(“IIS://{0}/w3svc/apppools/{1}”, host, poolname)))
{
   appPool.Invoke(
“Recycle”);
}

Or, if we want to use this in automation scripts or post-build events, we can wrap this in a console application (Here, full source code).

Enjoy. 

Adding custom headers to a WCF message – Jan CTP

Guy Burstein, again, writes about adding custom headers to a call made by a WCF proxy.
This is all very nice and well, but his code only works with the Feb. CTP of WCF, while I’m still using January here.
The differences seemed subtle at first – his instantiation of the OperationContextScope passed the proxy to the constructor, but there is no such constructor in the January CTP.
Simply instantiating the OperationContextScope with no parameters and adding headers seemed to work, but those headers never made it to the server-side.

After much fussing and digging, it turns out that the headers were transferred, but the way to fetch them was obscure. I don’t know if this was a design change from Jan to Feb or maybe it was just a bug that was fixed, but instead of accessing the headers like this:

string myHeader = OperationContext.Current.IncomingMessageHeaders.GetHeader(“myHeader”, “myNS”);

we have to do it like this:

string myHeader = OperationContext.Current.RequestContext.RequestMessage.Headers.GetHeader(“myHeader”, “myNS”);

Hope it helps.

Adding custom headers to every WCF call – a solution

At last, a solution presented itself. While I must admit that at first I was very skeptical of the extensibilty model for WCF which seemed far too involved and complicated, but after implementing a simple extension I must say it’s simple and quite intuitive.

My goal was to have several custom headers added to each call made through a proxy, rather than manually adding them to each call’s OperationContext. With a little help from Ralph Squillace’s blog, I was able to get an extension up and running within minutes, and it Just Works.

The first item to build is the actual extension logic. In this case, I needed an IProxyMessageInspector object that inspects each outgoing message and adds the custom headers:

public class ContextPusher : IProxyMessageInspector
    {
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            // Do nothing.
        }

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            MessageHeader myHeader = new MessageHeader(“HeaderValue”).GetUntypedHeader(“MyHeader”, “ns”);
            request.Headers.Add(
myHeader);
            return null;
        }
    }
}

Now we want to attach that inspector to proxy. We do that wth Behavior objects. This can be done on an operation-by-operation basis or for all operations on a given channel. We can make the same class implement both behaviors, for flexibility:

public class CallContextAttribute : Attribute, IChannelBehavior, IOperationBehavior
    {
        #region IOperationBehavior Members

        public void ApplyBehavior(OperationDescription description, ProxyOperation proxy, BindingParameterCollection parameters)
        {      
            // Add my MessageInspector to each message sent by the proxy.
            proxy.Parent.MessageInspectors.Add(new ContextPusher());
  
        }

        public void ApplyBehavior(OperationDescription description, DispatchOperation dispatch, BindingParameterCollection parameters)
        {
            // No server-side behaviors for now.
        }

        #endregion
               
        #region IChannelBehavior Members

        public void ApplyBehavior(ChannelDescription description, ProxyBehavior behavior, BindingParameterCollection parameters)
        {
            // Add the MessageInspector to every message sent through the channel.
            behavior.MessageInspectors.Add(new ContextPusher());
        }

        #endregion
    }

And then simply put it on a Service or Operation.
I think in this case, putting the attribute on both will result in an error when trying to add duplicate headers. But this allows me flexibility in adding the headers only to certain calls.

[ServiceContract]
[CallContext]
public interface ILocalizationServices
{
   [OperationContract]
   [CallContext]
   string DoSomething(string param);
}

I think this is the first time I got really excited by the WCF framework and the ease of using and extending it. This is FUN.

How do I add a custom header to every WCF message?

One thing I still haven’t managed to do is create my proxy in such a way that a custom header is added to every call that is made through that proxy.
Currently, this is done by instantiating a new OperationContext around each call through the proxy. This can be optimized in several ways:
1) Create a shared OperationContext object and always instatiate the OperationContextScope with it:
using (OperationContextScope scope = new    
            OperationContextScope(standardContextObject))
{
   …
}

I don’t know if it’s a good idea, though. Should OperationContext objects be persisted between calls, or would it have unexpected side effects?

2) Create a wrapper around the OperationContextScope class that fills the OperationContext with the proper headers:

public class MyOperationContextScope : IDisposable
{
   OperationContextScope contextScope;

   public MyOperationContextScope ()
   {
      contextScope = new OperationContextScope();
      MessageHeader standardHeader = new   
      MessageHeader(“StringHeaderValue”).GetUntypedHeader(“StringHeader”, “ns”);
      OperationContext.Current.OutgoingMessageHeaders.Add(standardHeader );
    }

    public void Dispose()
    {
      if (contextScope != null)
      {
          contextScope.Dispose();
      }
    }     
 }

This is a bit cleaner, but still requires me to wrap every proxy call with a using() statement.

Is there a way to interecept all calls and have my headers added automatically?

A new conditional assignment operator??

This one may have slipped beneath the radar, with all the new .NET 2.0 and WinFX and other improvements and APIs and language changes. It appears that C# 2.0 adds a new operator to the mix, and I never even knew it was there.

The operator is ??, and it’s a conditional non-null operator. Since that doesn’t really mean anything, I’ll simply and say that the ?? operator returns the left hand operand if it is non-null, otherwise it returns the righthand operand:

string a =  null;
string b = “String”;
Console.WriteLine (a ?? b); // Will output “String”.

This is shorthand for the common pattern we see using the ternary conditional operator, like this:

Console.WriteLine (a != null ? a : b);

which is in turn shorthand for:

if (a != null)
{
   Console.WriteLine(a);
}
else
{
   Console.WriteLine(b);
}

The ternary conditional is held by many to be a sin against nature and code readability, though I personally find it quite clear and convenient. The non-null conditional is a bit less clear – there’s nothing in its syntax to suggest an either/or relation. Perhaps it will clear things up. Perhaps it will lie unused and forgotten . Time will tell.

Note: For some reason, the MSDN library groups the ?? operator with the Assignment operators, rather than the Conditional operators. Strange.