Temporary Identity Impersonation in ASP.NET
Posted by Ryan Baxter Tue, 27 May 2008 16:01:00 GMT
Uploading files in an ASP.NET application is relatively easy to do. Uploading to a remote machine is a little bit trickier, but certainly doable. I followed a set of instructions on aspalliance.com, but rather than declare an account to impersonate in my web.config file, I decided to do it in code. That way I could use impersonation only when needed and encapsulate it for later use.
I referred to an article on Microsoft’s Help and Support website about how to implement impersonation. Their code worked great, but I decided to put it in a class to help keep things DRY.
using System;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Runtime.InteropServices;
namespace Utilities
{
public class ImpersonateUser
{
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
public bool ImpersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}
public void UndoImpersonation()
{
impersonationContext.Undo();
}
}
}After referencing my Utilities namespace I was then able to impersonate the account required for uploading:
if (FileUpload1.HasFile)
{
ImpersonateUser impersonateUser = new ImpersonateUser();
if (impersonateUser.ImpersonateValidUser("userName", "", "password"))
{
FileUpload1.SaveAs(Server.MapPath("~/files/fileName.txt"));
impersonateUser.UndoImpersonation();
}
else
{
throw new Exception("Identity impersonation has failed.");
}
}*The SaveAs method of the FileUpload control requires a root path. Using Server.MapPath will provide the root path of your IIS virtual folder.
- Posted in Code Snippets
- Meta no trackbacks, 2 comments, permalink, rss, atom
A Few Date Methods
Posted by Ryan Baxter Tue, 06 May 2008 18:45:00 GMT
An ASP.NET project of mine recently required the calculation of the start and end date of the current date’s previous month. This was more difficult putting into words than code. It did, however, get me thinking about other common date routines.
public static DateTime FirstDayOfPreviousMonth
{
get
{
return new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1);
}
}
public static DateTime LastDayOfPreviousMonth
{
get
{
return new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1);
}
}Being preemptive, I decided to include a few methods for determining the start and end date of the current date’s fiscal quarter. I started by calculating the current date’s quarter. This was accomplished with just a little division.
public static int CurrentQuarter
{
get
{
return (DateTime.Now.Month + 2) / 3;
}
}Finding the start and end dates of the current quarter was harder, but could still be expressed in a single line of code (or two).
public static DateTime FirstDayOfCurrentQuarter
{
get
{
return new DateTime(DateTime.Now.Year, 1 + ((CurrentQuarter - 1) * 3), 1);
}
}
public static DateTime LastDayOfCurrentQuarter
{
get
{
int lastMonthOfCurrentQuarter = 3 + ((CurrentQuarter - 1) * 3);
return new DateTime(DateTime.Now.Year, lastMonthOfCurrentQuarter, DateTime.DaysInMonth(DateTime.Now.Year, lastMonthOfCurrentQuarter));
}
}I’d like to extend this collection to include other common date routines. Feel free to post your date methods as comments if you’d like to share.
*The methods I’ve created for calculating the current quarter’s start and end dates assume the fiscal year starts on January 1st. This may not be suitable for your needs.
- Posted in Code Snippets
- Meta no comments, permalink, rss, atom
Setting Focus in ASP.NET Ajax Pages
Posted by Ryan Baxter Mon, 31 Mar 2008 22:24:00 GMT

At the new job I’ve been using a lot of ASP.NET Ajax to help ease the transition of users from VB6 desktop applications to web applications on our company intranet. In doing this, the UpdatePanel has become my new best friend. Albeit charming, my old ASP.NET 2.0 friends were not as impressed.
With ASP.NET 2.0, came the long-awaited Focus method that allowed developers to set the page focus without having to write any JavaScript. Developers loved it and all was right with the world. That is until ASP.NET Ajax showed up.
I recently spent way too much time trying set the page focus on a page that contained just a few TextBox controls and an UpdatePanel. My site’s ScriptManager was located in a MasterPage, but more on that later. My obligatory googling turned up many work arounds, but none as simple as the following:
// Example
if (Page.IsPostback)
{
// Use the GetCurrent method if your ScriptManager is located
// in a MasterPage. Word.
ScriptManager.GetCurrent(this.Page).SetFocus(TextBox1);
}
else
{
// Here is the money.
AjaxControlToolkit.Utility.SetFocusOnLoad(TextBox2);
}The above example is a two-fer. The ScriptManager’s SetFocus method is handy, but remember that only one ScriptManager is allowed per page and if you’ve put your ScriptManager in a MasterPage, then you’ll need to access it in code using the GetCurrent method of the ScriptManager class.
Two. The ASP.NET 2.0 UpdatePanel is not the only Ajax control. Download the ASP.NET Ajax Control Toolkit. With this toolkit, you’ll have access to dozens of controls and best of all – the SetFocusOnLoad method. Located in the Utility class, the SetFocusOnLoad method is the answer to your !Page.IsPostback problems.
- Posted in Code Snippets
- Meta no trackbacks, no comments, permalink, rss, atom

