Windows Impersonation for .Net Made Easy

by Mike Chatfield 1. December 2010 20:02

References:

Echis Framework on Source Forge
Echis Framework Wiki
Echis Framework "MSDN" Style Documentation

Introduction

One of the missing pieces to the System.Security.Principal namespace in the .Net Framework is the ability to Impersonate a user by using the user's credentials (e.g. Name, Domain and Password).  Microsoft provided a way to do impersonation provided you have a valid User Token.  The problem is there was no way within the .Net Framework to "log on" a user to get this token.  In order to perform impersonation using credentials a programmer needed to consult his handy Windows API reference and use functions such as LogonUser, DuplicateToken and CloseHandle.

Since my so-called "Echis Framework" is all about getting rid of the need to constantly write and re-write (or copy and paste) such code, I decided it was time to add some much needed classes to the System.Security.Principal namespace.  The classes described below can be downloaded from the Echis Framework page on Source Forge. The class files are located in the Echis.Core project in the .\Security\Principal folder.


ImpersonationCredentials

The System.Security.Principal.ImpersonationCredentials are exactly what the name implies.  Simply put the class is an XmlSerializable class containing properites for UserName, Domain and Password.  I created this class so that the Impersonation Credentials could be stored as part of a config settings section.  I have left encryption and decryption of the password up to the consuming developer.  As an example of this, I have extended the ImpersonationCredentials class in the Echis.Data.DataAccessCredentials class which uses the already defined DecryptionProvider setting in the Echis.Data.Settings class to decrypt the password.

WindowsIdentityImpersonator

The System.Security.WindowsIdentityImpersonator class is the class that performs the impersonation logic.  The class derives from IDisposable and when the Dispose method is called, the impersonation is stopped.  There is also a static method which instantiates a new instance of the class, begins impersonation and then returns the instance of the class; this static method is called BeginImpersonation.  Alternatively you can simply create an instance of the class and use the BeginImpersonation and EndImpersionation instance methods.

NOTE: The enumerations within the class I "stole" from another blog and forgot where.  If you're the original author of these enumeration classes I appologize in advance!

Here is some sample code showing use of the class:

   try
   {
    using (WindowsIdentityImpersonator impersonator =
      WindowsIdentityImpersonator.BeginImpersonation("UserName",
       "Domain", "Password"))
    {
    // Upon entering the using block (when using the
    // WindowsIdentityImpersonator.BeginImpersonation() method)
    // the identity is impersonated using the supplied credentials
     Trace.WriteLine("Impersonated Identity: " +
       WindowsIdentity.GetCurrent().Name);


     /*** Perform action(s) requiring special permissions ***/

    }

    // After leaving the using block, the identity has reverted
    // back to the user's identity.
    Trace.WriteLine("Normal Identity: " +
      WindowsIdentity.GetCurrent().Name);
   }
   catch (ImpersonationException ex)
   {
    // Handle error message.  NOTE that if the exception is
    // thrown while reverting back to the original Windows
    // Identity, it may be best to gracefully shut down
    // the application rather than allow it to continue
    // running under the Impersonated Identity.
    Console.WriteLine(ex.GetExceptionMessage());
   }

ImpersonationException

The System.Security.Principal.ImpersonationException is the only exception which will be thrown from the WindowsIdentityImpersonator class.  This makes it easy to specifically catch any exception related to the Impersonation logic.

Conclusion

Just one more piece of the puzzle, and hopefully (particularly if you are a .Net developer) you find these classes to come in handy in your own code.  Note that I have put them in the System.Security.Principal namespace, so simply dropping these three class files into your own solution should be sufficient if you don't want to use the Echis Framework.  This is the same for all of the classes found in the Echis Framework.  I published this as Public Domain so that developers were free to "rip apart" the Framework and use the components/classes that are most useful to them.

 

Echis Bible on Source Forge

by Mike Chatfield 23. October 2010 09:38

References:
Echis Bible on Source Forge
Echis Bible Applicaiton Wiki

The Echis Bible Application

The Echis Bible Program began with a desire to simply have an electronic copy of the Bible so that I could keep it on portable media.  My belief is that as we see the Return of our Lord getting closer, that true Christians everywhere (even in the United States) will face real persecution and our Bibles (or at least certain translations) may even be confiscated.  And it will be alot easier to hide an electronic Bible than an actual Bible.  Thus the Bible program began simply as downloading the text from the internet.  The only translations of the Bible which I have included in the program are Public Domain; but I designed the Bible Application so that adding additional translations is simply a matter of copying a resource assembly into the Bible program's directory.

Once I had the text downloaded, I set out to simply create an application that would allow me to view and search through the text.  That concept morphed over time into the Bible Application I have released on Source Forge.  I added in Public Domain versions of Strong's Concordance and 1828 Webster's Dictionary. Then I added the ability to record and keep notes.

I used the .Net Framework's new LINQ capabilities to quickly search the Bible.  While I haven't yet documented the searching capabilities, I'll talk a little about them here. By default the search window comes up with all books selected. Using the Tree views of the Old and New Testament books you can select precisely which books you want to search. You can select and desect books by grouping (Law, History, Wisdom, etc) or select or deselect the entire Old or New Testament. Once you've establish which books of the Bible you wish to search you can select your search option. NOTE: All search options are case insensitive: in other words CREATED, Created, and created are all considered "equal."

Match Any Word - This is the default search option, and as the name implies it will find any verse which contains any of the words you've typed in.  You can alter this behavior by including a plus (+) or minus (-) before a word. A plus (+) indicates that the verse must contain that word; a minus (-) indicates that the verse must not contain the word.  Additionally you can indicate a phrase to search for by wrapping the phrase with double quotes.

Match All Word - As the name implies here, only verses which match all of the words will be included in the search results.  You can alter this by adding a minus (-) before the word to indicate that the verse must not contain the word.  And again you can wrap a phrase with double quotes.

Match Exact Phrase - As the name of this search option implies, the application will search for the exact phrase entered.

Use Regular Expression Matching - This may seem a little foreign to any non-programmers, but Regular Expression Matching is a powerful tool.  I recommend reading up on this capability by visiting Wikipedia's Regular Expression page. Or google Regular Expression Matching and you'll find pages like this and this.

Suggested Features

I am open to suggestions on new features or modifications to existing features. So if you have an idea simply click on the Contact link above and I'll be happy to consider adding your request (if it is possible) to a future release.

One thing I would love is to do is add additional translations, however, they must be Public Domain, or the Copyright holder must grant permission.  I am simply not interested in doing the "leg work" to get the Copyright holder on board, but if you're willing to do the work there, then I could be inclined to provide a resource file for that translation (provided I can get an electronic copy of the text to start with).

Additionally, I would also love to translate the application into more languages, but I would need a great deal of help with this since I am no linguist.  Additionally the translation of the Bible would once again need to be Public Domain, or permission granted from the Copyright holder.

Donations

There is a link on the Source Forge page for donations.  I originally thought about trying to get this application published, but I've been sitting on it for over a year without doing anything with it, so I decided to just go ahead and release it.  Donate whatever you would like, or if you prefer simply donate $5 to your local Church toward missions (as that's what I plan on doing with the vast majority of any donations I recieve from this).

Thank you all, and may God Bless you.

Tags:

Bible | Echis Bible

Echis Framework on SourceForge

by Mike Chatfield 22. October 2010 20:22

References:
Echis Framework on Source Forge
Echis Framework Wiki
Echis Framework "MSDN" Style Documentation

Introduction

As I stated earlier, one of the primary reasons for me to start a blog was to talk about the Echis "framework."  While I call it a framework (I don't know what else to call it), it pales in comparison to true Application Frameworks.  Essentially the Echis Framework is a collection of classes, utilities and components which I've developed over the years.  For the most part (with the exception of a class or two, or a method here and there) the implementations are my own, however many of the concepts I've adapted into the framework were learned by various colleagues over the years and from the various places where I've worked.  I have released this "framework" as Public Domain; the intention being that developers can pick and choose what components they want, (if they want) modify them for their own use and/or even change the names to suit their evironment/naming conventions.

As part of an effort to document the Echis Framework, I've installed ScrewTurn Wiki on my website and have begun adding pages there.  The intention behind the Wiki is to discuss the reasons for the classes/utilities and how to use them.  In many cases I plan on showing sample code. In some cases sample code may be too complex; in those instances I plan on creating sample applications that hopefully will help demonstrate the capabilities and features of the component(s).  For now, I am the only one working on both the Framework code and the Wiki documentation, so please, be patient. :) So far I have documented two components (well, I've documented one and started on the other): Collections and Configuration.

Echis Framework - Collections

The collections part of the framework started with ListEx and IListEx, it was primarily an attempt to "fix" the .Net Framework's lack of functionality in IList.  I started using the ForEach, Find, FindAll and Exists methods of the List class as soon as I learned about them.  I was dissapointed to find that IList had NONE of these methods!  How was I supposed to use Interface driven design, if the interface I was starting with didn't have the methods I wanted to use?  Casting an IList to List just to use these functions breaks the very idea of using interfaces.  So I created IListEx to "add" the functions that List already had, and then I created ListEx as the "implementation" of IListEx.  Originally ListEx was empty, simply extending List.  Later I added Events to deal with an issue of a background thread adding items to a List which I had bound to a WinForms DataGrid (the DataGrid would obviously not display the items added by the background thread until it was manually refreshed).  I also added the AddIf, AddRangeIf and CountIf methods because I found myself in need of this functionality at one time or another.

I was also disappointed to find that many of the collections and, of course, arrays did not have the ForEach method added to them like List did.  So upon learning about Extension methods I created a Collection Utilities class and added a ForEach for any IEnumerable<T> collection.  I also added an IsNullOrEmpty for Arrays and while working on comparing and matching products by name, I added the Edit Distance method. This came in very handy for matching products that had the same name components, but in different orders (e.g. "Rice Krispies, Kelloggs" and "Kelloggs Rice Krispies").  The version on SourceForge hasn't been updated yet, but I've also recently added Extension methods for Find, FindAll and Exists.

DictionaryEx (and IDictionaryEx) were created out of the need for an XmlSerializable Dictionary. Since I was going through the trouble of making this new class, I decided to go ahead and add the missing ForEach, Find, FindAll, etc... functions.  While doing so I also added ByKey and ByValue methods for each of those as well (e.g., FindByKey, FindByValue)

Echis Framework - Configuration

One of the annoyances I've had to deal with at various places is inheriting an application with an overly used AppSetting section in the config file.  Seems every developer who ever had a need for a setting would just add a new one to the list.  Nevermind that the clever name they chose ("ConnStr") just happened to already be in use by someone else. Or that someone else may have already defined an AppSetting that they could have used instead.  I've seen some rather ugly, ugly web and app config files; most recently I had to deploy code into a massive environment where multiple development teams have all had their hand in wrenching on the web.config file, and every single one of them just used the AppSettings section. The AppSettings section was colossal, literally hundreds of settings.

I designed the SettingsBase<T> class to eliminate these kinds of scenarios.  I used the IConfigurationSectionHandler interface and created my own Section Handler that would simply deserialize the contents of a config section using the XmlSerializer.  This allows for a much more structured configuration file; with each component having it's clearly defined settings in it's own section.  Further it enabled settings to have collections of simple or complex types; it allowed settings to have properties that were complex types.  As a developer, you simply derive from SettingsBase, provide properties decorated with XmlAttribute or XmlElement attributes and then add your config section.  Visit the link above to more details including code samples.

Later I added the ability to "redirect" to an external configuration file.  This allowed me to "break up" large overwhelming configurations into multiple files (e.g. in the case above where multiple Development teams were all modifying the same config file, it would be possible for each team to have it's own config file separate from the main Web.Config) and it also allowed simplified deployment to various environments; all I needed to do was change the file the section was redirecting to (e.g. Dev.Config, QA.Config, or Prod.Config).

Lately I've been working on taking the redirection a step further by creating a Centralized Configuration Repository.  Thus far I have the classes written, but I have yet to fully test this functionality.  The concept is that instead of reading the configuraion from a local file, that a Service will deliver the configuration section instead.  Thus the only configuration needed locally is the information on the Configuration Service.  I have yet to document this, but the way it works is a request is made, including credentials (e.g. User, machine, domain, application, environment), to the Configuration Service.  The Service then confirms that the user and machine has access to the requested configuration section for the specified environment (e.g. Dev, QA, Prod); this way, the service can block someone from accidentally running against Production databases while working in the QA or Dev environment.  Once the user and machine pass validation, the service looks up the configuration section for the application and returns it as an Xml string.

 

Well, that's all I have for now folks, if you are a .Net developer then I suggest you at least take a look.  If nothing else you may come away with a few classes that will come in handy for you.  Next up I will be working on documenting the Data Access components which, in my opinion, are what ADO.Net should have been like to start with.  For instance, using the Echis components you can literally change from SqlClient to OleDbClient simply with a configuration change.  You can execute queries with just one or two lines of code; and you can let Jr. Developers have access to a DataReader without worrying if they are going to close it when they are finished or not.

Until next time...

Tags:

Framework | Programming

Joining the "Blogosphere"

by Mike Chatfield 12. October 2010 07:26

Why Blog?  That is what I used to ask myself; I mean, who would want to read my ramblings? I've found myself wanting to share two pieces of software which I've developed over the years, however I lack any real end-user documentation for either.  So I thought I might go ahead and release them to the public and then simply blog about their features here.

Thus I found myself in search of an Open-Source Bloggin Engine that didn't need to use a database.  I found the Blogging Engine I'm using now on Codeplex.com (http://blogengine.codeplex.com/).  So far I am really impressed with the quality and features of the application.

The first piece of software is not an application.  It is a "framework" of sorts that contain useful classes, utilities and interfaces to more complex true frameworks like Spring.net or the .Net Castle Project. My main goal was to provide simplicity; to provide interfaces and classes to Jr. Developers that would allow them to be more productive without needing to worry about making a mistake like not closing a Data Reader or Database Connection.  The Echis Framework was thus born out of necessity, and I've been altering and growing it since the early .Net 1.0 and 1.1 days.

The second "piece of software" is an application.  It is the Echis Bible; originally I thought I might be able to finish this application and sell it.  But now I think I am just going to release it to the public via the Open Source community.  Perhaps there are other Christian developers that have some ideas on what they'd like a Bible Applicaiton to do and might be willing to contribute.  I have two public domain versions of the Bible (King James and Young Literal Translation) and an working on obtaining a third (Geneva).  I am also considering adding other Public Domain Christian works such as Foxe's Book of Martyrs and Pilgrims Progress.

Having become frustrated with Facebooks 420 character limit on the "Status" (but the comments can go much longer?) I may also from time to time blog about other subjects, such as my Christian faith, politics, or just life in general.

Tags:

Framework | Bible | Echis Bible | Programming

Page List