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

 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 »

 January 7th, 2009

Measuring memory usage of object creation in C# - 1

As your application grows it can be useful to get an idea of how much memory a particular data structure is using in memory. Measuring memory in a garbage collected environment is a somewhat of a moving target as the Garbage collector is able to move things around in the background.The .NET libraries offer two ways of measuring your applications memory. The total amount of memory allocated to the process (which includes code, unique libraries) and the amount of memory used that the Garbage collector is aware off (which is only your applications variables). This second set is of course a subset of the total amount of memory.

Read the rest of this entry »

 January 6th, 2009

Encrypting and Decrypting a C# string - 11

The .NET C# library provides all the basic elements for encrypting a string with a passphrase and decrypting it later. Doing this however requires a few steps in between. This post show a simple set of routines to help you do just that. We use the TripleDES encryption suite to do the actual encryption, with a little help from the MD5 hash sum generator.

The complete source code is listed below, but lets have a little look at how it works first.

Read the rest of this entry »

 December 29th, 2008

Debugging C# in Monodevelop on Ubuntu - Comments Off

As soon as I heard that the  MonoDevelop Subversion code included support for actually debugging my C# code I tried installing it to give it a go. Optimistically I kept notes, figuring that it would be useful to write a post about the install process later. As my notes started to turn into a book, and the arrows back and forth and crossed out scribbles increased I gave up on writing the ultimate “ten step guide to installing Monodevelop on Ubuntu”.

When I finally had MonoDevelop compiled and installed — the promised debugging didn’t actually work. Bummer. I gave up, and went back to coding the old way (with ticker tape). This morning I checked out the latest SVN, installed it and ran it, just for laughs.

And behold as shown below — debugging actually worked. I can step and trace through the code, and set watches making MonoDevelop suddenly that much more useful to me.

The best thing? The Mono C# libraries are not black boxes but open source — you can step and trace directly into the Mono libraries themselves and find out what Mono is doing as you call library functions.

MonoDevelop on Ubuntu

The problem with installing MonoDevelop 2.0alpha 2 is that the guides online don’t actually produce a working MonoDevelop installation. If you run MonoDevelop under Ubuntu like I do, the number of dependencies and sub-dependencies you need to resolve is large and I ended up compiling, re-compiling and changing version numbers of modules multiple times to find combinations that worked. In addition I had to change, add and resolve many missing library conflicts within Ubuntu as well.

Concluding: Yes, it is possible. Just do not expect a quick and easy install of MonoDevelop 2.0 alpha 2 on your Ubuntu installation.

This is fun only if you have plenty of spare time.

Some hints — this does not produce a working Mono Develop installation

  • Remove Mono 1.9, MonoDevelop 1.0, and any and all other mono related things from your ubuntu installation before attempting to compile MonoDevelop 2.0 Alpha 2 to avoid conflicts down the road.
  • Install mono 2.3, the debugger and mono develop from SVN, not from the packages provided on the website (they do not work)
  • $ svn co svn://anonsvn.mono-project.com/source/trunk/mono
    $ svn co svn://anonsvn.mono-project.com/source/trunk/mcs
    $ svn co svn://anonsvn.mono-project.com/source/trunk/debugger
    $ svn co svn://anonsvn.mono-project.com/source/trunk/mono-addins
    $ svn co svn://anonsvn.mono-project.com/source/trunk/olive
    $ svn co svn://anonsvn.mono-project.com/source/trunk/monodevelop
  • I installed gtk-sharp-2.12.5, gnome-sharp-2.20.0 and libglade-2.0.1 as support libraries
  • Compile and install monodevelop last of all

Mono JIT compiler version 2.3 (/trunk/mono r121276 Thu Dec 11 13:04:53 CST 2008)
Copyright (C) 2002-2008 Novell, Inc and Contributors. www.mono-project.com

 December 9th, 2008

Creating salted hash passwords in C# - 3

Hash values have many uses in computing: for storing password tokens, securing that a file hasn’t been tampered with, or to create a short semi-unique signature for a larger data set. A hash algorithm takes a data set — such as a string — and turns it into a numeric value of a certain length.

This article will go into how to create a hash of your passwords and how salting them makes them more secure.

Read the rest of this entry »

 November 27th, 2008

Setting up NUnit for C# Unit Testing with Visual Studio C# Express 2008 - 15

Unit testing helps you verify that each individual part of your code is working as expected and keeps doing that as you change your software. You do this by adding small bits of testing code and have the unit testing frame work execute them in order. I am currently writing some code that needs to have a basic unit testing framework and wanted to install the NUnit framework. This post is about how you can install NUnit, use it and run it with / install it for Visual Studio C# 2008 Express. I will leave the nuts and bolts of unit testing to a future post but this post should get you up and running.

Read the rest of this entry »

 November 19th, 2008

Creating and synchronizing Threads with C# - Comments Off

Multi-tasking / multi-threaded applications have always been a bit of a nightmare to create. Different operating systems and sometimes even different compilers and class libraries tends to have their own implementations. Fortunately the .NET / C# implementation of threading is extremely straightforward and makes it simple to create a multi threaded application. In this article we look at building some very simple threaded applications. We go into how to create them, synchronize them and how we can ensure that things such as shared variables are properly protected.

Read the rest of this entry »

 November 15th, 2008

Generics in C# - Comments Off

You heard might have heard about generics, but how do they work in C# ? And what is that <T> doing in the class definition? This article shows you the benefits of using generics, and how to implement them yourself.

Read the rest of this entry »

Most popular

    Sorry. No data so far.

Recent Comments
  • Juan Romero: Hi there, it’s a neat little class, but I believe you could do the same thing with the WebClient...
  • anthosh: Hey, THank you very much for your tutorial. It was awesome. But i have a problem that i am not able to...
  • bian: how to get passphase if i have encrypt and decrypt string?? Thanks alot
  • Michael: Hi, I really like your post, thanks a lot, it really helped clear up a few things I could not remember how...
  • Bharat Prajapati: i was trying to import keyword dictionary to this plugin which is in csv format, but i get an error...