Home About

 September 3rd, 2013

Impersonate another user in C# - Comments Off

Sometimes is useful to switch to another user account, while your program is already executing. In my situation, I needed to build a JSON alternative for the deprecated SOAP layer in MS-SQL server 2012.In previous MS-SQL versions the SOAP server would accept a username and password, and query the database server using those credentials. Based on the permissions set up in the database , users have access to certain procedures, tables and views.

In C# the SqlConnection class uses the current user when building the connection, you are always logged in as the user running the task. Thus this would require building a whole new security layer, on top of an existing one.

The solution comes in the form of Uwe Keim’s Impersonator class.

This class allows you to pass a valid set of Windows credentials to the runtime, changing the login temporarily.

using (new Impersonator(username, WindowsDomain, password))
/* The code in this block is executed using the impersonated credentials */

Calling SqlConnection.Open from within this block allows you to build a connection using the correct privileges. If the credentials are invalid, an exception is thrown which you can then report back.

How does it work ?

The actual implementation is both simple and elegant. LogonUser is used to validate the login, and obtain a login token. This token is duplicated using DuplicateToken to obtain an Impersonation token. Finally, WindowsIdentity is instantiated to switch the actual Identity for the duration of the using clause.

if (LogonUser(
ref token) != 0)
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();

On exiting the using block, the dispose() method undo’s the impersonation and you are back to who you were.

Foto credit: Elvis the King Kitty by Lisa Larson

 March 20th, 2009

Exploring C# Boxing - 6

C# Boxing Explained

Boxing in C# has little to do with Saturday night television but quite a bit more with that part-time job at the warehouse you had as a student. It is an important concept in C# that is related to how the compiler handles different kinds of variables in memory. Knowing how the compiler handles the various types allows you to avoid unexpected side effects in your code.

This article explains what boxing is, how it works and how it can negatively effect your code if you don’t pay attention to it. We also look at how generics can be used to improve your code’s efficiency. And we try to answer the ultimate question: Is everything in C# an object?

Read the rest of this entry »

 March 17th, 2009

10 C# Shorthands that improve productivity - 21

C# shortcuts and shorthand

One of the best things about C# is that as the language and libraries expand thought is put into keeping things readable. Below I have listed 10 shorthands that you can use to make your code tighter and less wordy. No doubt you know one or more already — but do you currently use all ten of them ?

Read the rest of this entry »

 March 6th, 2009

C# Regular Expression Cheat Sheet - 1

I have been doing quite a bit with regular expressions recently and to avoid having to look them up again and again I made myself a little table with the most important C# regular expression operators and stuck it on the wall. This post contains the C# regular expression operators as used by the .NET regular expression classes such as RegEx.

If you would like to print this, click here for a pure HTML version.

Read the rest of this entry »

 March 4th, 2009

Safely cleaning HTML with strip_tags in C# - 8

Removing unwanted tags with StripTags/strip_tags

One of my favorites in the PHP libraries is the strip_tags function. Not only does it neatly remove HTML from an input it also allows you to specify which tags should stay. This is great if you are allowing your visitors to apply some basic HTML tags to their comments. This post explores two issues: using C# to remove unwanted tags, and cleaning up unwanted attributes that might be hidden in the allowed tags.

Read the rest of this entry »

 March 3rd, 2009

Using C# and .NET to send an e-mail through SMTP - 5

Sending an e-mail using .NET

Sending an e-mail is pretty old news by now so it should come as no surprise that .NET contains a significant SMTP mail client. One old programming truth still holds: All programs will expand to eventually include sending (and receiving) e-mails. So how about adding e-mail to your program ? This post explores how we can use the System.Mail.SmtpClient to send formatted e-mails. There are plenty of options available and we will explore most of them.

Read the rest of this entry »

 February 24th, 2009

Show all assemblies loaded by your C# program - 3

Sometimes it is handy to have a quick overview of all the assemblies that your C# program has loaded. Maybe because you are trying to debug a version conflict, or because you want to distribute your application and want to get an idea of its dependencies.

Read the rest of this entry »

 February 24th, 2009

Simple class to submit (POST) a Web form from C# - 8

Today I needed to automate posting some data to a web form from a C# program, and sure enough this is not at all that difficult. But surprisingly you need to call quite a large number of methods to get your data ready to ship. A working code example only took a few minutes to write but it took quite a bit more time to clean things up. You can find the full implementation at the end of this post.

Read the rest of this entry »

 February 23rd, 2009

Using the C# WebClient class to upload and download FTP files - 1

Your C# program has just calculated the weekly sales report and you need to upload it to the company file server. The C# System.Net.Webclient class makes this quite trivial. The same for downloading a file from the server and then parsing it for content. This post shows how you can use basic FTP actions to upload, download files and either store them in memory or write them to disk.

At the end of this post you will find my BasicFTPClient class that implements the uploading and downloading code.

Read the rest of this entry »

 February 17th, 2009

Exploring C# reflection - 1

Reflecting on our C# selves

In this post I look at how we can simply retrieve basic information about our own types, discover their methods and lastly how we can import a foreign assembly, inspect its contents, load a class and execute its methods.

When C# compiles your code it not only stores the program in the assembly but the complete information on each of the structures you have defined. Each class, its types, parameters and methods described into detail are all available. This might sound like stating the obvious, but until recently most compilers treated this kind of “meta” data as a waste of space and never included it into the final assembly.

Read the rest of this entry »

Most popular
Recent Comments
  • ARS: great plugin! I love it! but, it will be so nice if you can add attribute ‘title’ as one of...
  • Nelson: Saved me from doing it myself. Good article.
  • andy: i am currently playing taiwanese server wow in 奈辛瓦里(PVP) and i would like to realm transfer to somewhere there...
  • berties: any english speaking playing on a taiwanese server?
  • web application development: has C# search volume really so constant over the years? really surprising.