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

 August 8th, 2009

C# Autosuggestion Textbox - 2

A few days ago I needed a textbox that automatically suggests common input options to the user. In my situation, names of companies. Because of screen space constraints I am unable to use a ComboBox (which already has this functionality).

The idea is that if the user enters one or more characters that the Textbox will search its list of suggestions. In this test implementation this is done through a simple List<>. Ultimately my list will contain many thousands of items and I will need to replace the List<> with a more efficient search algorithm.

In the below example code typing a single “W” will expand to “Waterland”, if you continue typing beyond the final “d” it will suggest “Waterland Investments”. Type a “T” and it will branch to “Waterland Telecommunication Systems”.

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Dijksterhuis.org
    class AutoSuggestControl : TextBox
        List<string> Suggestions;
        int PreviousLength; 

        // V1.0 We are using a simple sorted list for the suggestions
        public AutoSuggestControl() : base()
            Suggestions = new List<string>();

            // We keep track of the previous length of the string
            // If the user tries to delete characters we do not interfere
            PreviousLength = 0; 

            // Very basic list, too slow to be suitable for systems with many entries
            Suggestions.Add("Waterland Investments");
            Suggestions.Add("Waterland Telecommuncation Systems");

        /// <summary>
        /// Search through the collection of suggestions for a match
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>

        private string FindSuggestion(string Input)
            if (Input != "") 
            foreach (string Suggestion in Suggestions)
                if (Suggestion.StartsWith(Input))
                    return Suggestion;
            return null;

        /// <summary>
        /// We only interfere after receiving the OnTextChanged event. 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnTextChanged(EventArgs e)
            // We don't do anything if the user is trying to shorten the sentence
            int CursorPosition = SelectionStart;
            if (Text.Length > PreviousLength && CursorPosition >= 0)
                string Suggestion = FindSuggestion(Text.Substring(0, CursorPosition));
                if (Suggestion != null)
                    // Set the contents of the textbox to the suggestion
                    Text = Suggestion;
                    // Setting text puts the cursor at the beginning of the textbox, so we need to reposition it
                    Select(CursorPosition, 0);
            PreviousLength = Text.Length;



 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 16th, 2009

MonoDevelop Keyboard Shortcut overview - 1

Mono Develop Keyboard Shortcuts

Ever watched an experienced programmer flick through code like there is no tomorrow? That is what caffeine addiction does to you. If you think that normal scrolling up and down isn’t fast enough you will find that a good development environment offers many keyboard shortcuts to let you work ever faster.

Keyboard shortcuts allow for things like indenting a selection, making it uppercase or lowercase, commenting it , jumping between bookmarks and moving lines of code up and down. These can be real time savers.

I was looking for a printable overview of available keyboard shortcuts for MonoDevelop but couldn’t find one so I have created my own.

If you are running a standard Linux distribution you will probably still be using the 1.0 version of MonoDevelop. If you compiled MonoDevelop 2.0 from source then you will be pleased to discover many new shortcuts. As the difference between 1.0 and 2.0 is significant I have made separate tables for the both of them.

 March 13th, 2009

C# guidelines that improve your code quality - 1

I am inspired to better myself after reading Dennis Doomen’s freshly released coding guidelines for C# 3.0 . He provides a very nice PDF document that puts the dot to many common C# coding “confusions”. It addresses how to consistently name your variables, namespaces, classes and assemblies. He specifies when to declare a variable as static, as readonly and when to seal a class among others.

Another topic he pushes is code readability and ensuring that all code statements are as clear as possible.

Example Coding Guideline

You will often have your own way of doing things. A shared coding guideline is a good way to ensure that each member of your team is writing code styled as similar as possible.

If your company is looking at adopting a coding guideline for its C# development this would be a very good place to start.

At 32 pages it might seem a little long at first but it reads quickly and most topics should already be familiar if you do a lot of coding. Its companion quick reference guide neatly puts most key items onto a single page and makes for a great handout.

 March 11th, 2009

Advanced Regular Expressions in C# - 9

Regular Expressions in C# - Advanced Topics
In this third and for now last post on using regular expressions we look at some advanced topics. When your expressions become more complicated they also become harder to understand so documenting them can help. And isn’t standard string replacement a little bit too basic? We also look at how speeding things up can improve your code’s efficiency.

In this post we look at three topics:

  1. Improving your code’s readability by documenting regular expressions
  2. Creating conditional string replacement by using MatchEvaluators
  3. Speeding up regular expressions by compiling them, caching them in memory and pre-compiling them to their own DLL.

If you are new to regular expressions in C# have a look at the theory of regular expression in Regular Expressions : The Basics. The second post Regular Expressions in C#: Practical Usage introduced the most common uses of regular expressions.

Read the rest of this entry »

 March 10th, 2009

Regular Expressions in C# – Practical Usage - 6

Regular Expression - Practical Usage

This is the second post in the C# regular expression series and it follows up on “Regular Expressions in C# – The Basics” which explained the theory behind Regular expressions in C#. In this post we look at how to make practical use of regular expressions in our C# code.

This post touches on four major regular expression subjects:

  • String Comparison – does a string contain a particular sub-string?
  • Splitting a string into segments – we will take an IPv4 address and retrieve its dotted components
  • Replacement – modifying an input string
  • Stricter input validation – how to harden your expressions

Read the rest of this entry »

 March 9th, 2009

Regular Expressions in C# – The Basics - 7

Regular Expressions in C#

One of the most common coding tasks is to take an input, munch it around and turn it into something different altogether. Are you looking for FedEx numbers in a text file? Do you want to replace “love” with “hate” in your source files? Is a string a valid e-mail address? Problems like these can be solved by applying regular expressions, or “regex” for short.
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 »

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.