Singleton and Thread Safe Methods on .Net

Español

Recently I had a code review on one of my colleagues project and found this common implementation there:

public sealed class TheClass {
   private TheClass() {}
   private static _theClass value;
   private static object obj = new Object();
    public static Instance Value {
          get {
                 if (TheClass.value == null) {
                        lock (syncRoot) {
                               if (TheClass.value == null) {
                                      TheClass.value = new TheClass();
                               }
                        }
                 }
                 return TheClass.value;
          }
   }
}

Yes we are talking about the classic Singleton pattern here, but not implemented as the proper or, more importantly, safer way. This implementation could permit a double instantation at some point. In short I’ll just recommend to make _theClass volatile, but I know it’s not the unique way to achieve this and is not always the safer way in all platforms. So searching this on the internet I found a lot of discussions so if you are interested on a deep level reading check this links:

volatile and MemoryBarriers
Double-checked locking in .net at Stackoverflow

Alois Kraus even shows the assembled code!
Lazy Vs Eager Init Singletons / Double-Check Lock Pattern

http://www.yoda.arachsys.com/csharp/singleton.html

And of course the Official Microsoft Pattern

Good reading!

System.DirectoryServices.AccountManagement.UserPrincipal Serialization

Español

You can’t serialize this Type, the first reason is simple: Doesn’t have [Serialize] attribute on the base classes, but more important it has a lot of dependencies on non-managed resources that has to be connected to this class. If you could serialize making some tricks the class would expect to connect to Active Directory on the client consumer side, and assuming that the class could connect then it will be non sense to send the class in the first place. It will be more easy that the final client create and connect to the class directly.

So if you need to serialize just “data” of this class like some info on the attributes of an user. The recommended way will be to implement a memento pattern.

When you had a lot of properties and you are not worried of a coupled internal constructor (for example when the class will be serialized for a .Net Web Service and that constructor will not be used on the client consumer side) you could use a internal constructor that get as an argument the original class like:

[Serialize]
public class UserInfo
{
  private string displayName;
  ...

  public UserInfo()
  {
  }

  internal UserInfo(UserPrincipal user)
  {
      this.displayName = user.DisplayName;
      ...
  }
}

This way you can use it in your return methods like this:

return new UserInfo(user);

Visual Studio Solutions Tips

Español

Another (I think useful) tips for you Visual Studio

Create Visual Studio Solutions from Windows Explorer. This has the advantage that you can create the project folder structure that you want and then create an empty solution. I use this quite a lot because I use Solutions as diferent views of my projects (specially when they are big with a lot of visual studio projects). And it’s handy when you are using a folder structure for all your project and the visual studio solution is just the “code” part maybe in src directory.

To get to that create this registry key (you can copy this on a .reg file an execute that):

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.sln\ShellNew]

“Data”=hex:EF,BB,BF,D,A,4D,69,63,72,6F,73,6F,66,74,20,56,
69,73,75,61,6C,20,53,74,75,64,69,6F,20,53,6F,6C,75,74,69,
6F,6E,20,46,69,6C,65,2C,20,46,6F,72,6D,61,74,20,56,65,72,
73,69,6F,6E,20,31,30,2E,30,30,D,A,23,20,56,69,73,75,61,6C,
20,53,74,75,64,69,6F,20,32,30,30,38,D,A,47,6C,6F,62,61,6C,
D,A,9,47,6C,6F,62,61,6C,53,65,63,74,69,6F,6E,28,53,6F,6C,
75,74,69,6F,6E,50,72,6F,70,65,72,74,69,65,73,29,20,3D,20,
70,72,65,53,6F,6C,75,74,69,6F,6E,D,A,9,9,48,69,64,65,53,6F,
6C,75,74,69,6F,6E,4E,6F,64,65,20,3D,20,46,41,4C,53,45,D,A,
9,45,6E,64,47,6C,6F,62,61,6C,53,65,63,74,69,6F,6E,D,A,45,6E,
64,47,6C,6F,62,61,6C,D,A

Or just take the file in the article of this guy that I google/find last time I had to edit this (you know when my freaking can’t wait this slow computer make me reformat again my lap hehe)

The second tips has to do with solutions again, if you already notice Visual Studio 2005 and further creates a top level Solution.root folder when you have projects in your solution and IIS Web Sites that are on another location (i.e. C:\Inetpub\wwwroot\…) I think that it’s not a very good practice this folder layout and when you upload this with Visual Source Safe and .root is created is more confusing for your development team. So if you take care of the solution and each project folder destination, even the destination of the web sites (I take the mapping of those manually, this way I have the web site project in as a subfolder, as any other project on the solution) you have to tell to Visual Studio not to create the .root folder:

Click Start, click Run, type Regedit, and then click OK.
Open HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\7.1\SourceControl
Select key DoNotCreateSolutionRootFolderInSourceControl, click Edit, and then click Modify.
In the Value data box, change 0 to 1, and then click OK.

(you have to change the version if have a newer Visual Studio, 7.1 correspond to Visual Studio 2005, the first Visual Studio with this behaviour.

References:

http://flux88.com/blog/right-click-new-visual-studio-solution/

http://msdn.microsoft.com/en-us/library/aa290096(VS.71).aspx

ecoder a web based code editor

I’m searching ways to build all of my development and collaboration tools on the Internet (I know now everybody calls it “the cloud”). It will be great if you don’t need anything not event the code editor neither the compiler. Searching for the current approach I found ecoder. It’s really a very good concept. It’s difficult just to throw out all your heavy and sophisticated development IDE and tools but it’s nice to have your code in your source control and have an editor to change or to work remotely without the dependency of your computer. I don’t know if is just a nice try one or two days idea but I will give it a try.

References:
http://www.gmeditor.com/wiki/code-downloads/ecoder-web-based-code-editor/

I have to learn XSLT AGAIN

Do you remember when someone ask you about some technology, language or something else and your eyes start trying to reach the sky and you start blabbing trying to find anything in your head and nothing comes to you? Well today was my lucky day, some friend ask me about some trouble with XSLT and I couldn’t even remember the most simple things. I remember those days when was the SOA big bang and you HAVE to know all about XML, DTD, XSLT, and so on. Today that bubble was gone and with it much of the knowledge.

Authentication with Active Directory from Forms Authentication

Español

There are two ways that .Net can use to do Active Directory Authentication and this are:

To make a “bind” to Active Directory using LDAP.
To use the Win32 Logon API.

If .Net 3.5 is available you can authenticate with this method:

private bool ValidateExternalUser(string username, string password)
{
    using(PrincipalContext context = new PrincipalContext(ContextType.Domain, _defaultDomain))
    {
          return context.ValidateCredentials(username, password, ContextOptions.Negociate);
    }
}

Before .Net 3.5 you can just bind with your own object:

public bool AuthenticateActiveDirectory(string Domain, string UserName, string Password)
{
    try
    {
          DirectoryEntry entry = new DirectoryEntry(”LDAP://” + Domain, UserName, Password);
          object nativeObject = entry.NativeObject;
        return true;
    }
    catch (DirectoryServicesCOMException) { return false; }
}

Using Win32 Logon API:

It’s very large and fortunately already documented here:
http://www.pinvoke.net/default.aspx/advapi32/LogonUser.html

Another method that we can use when the authentication has to consider Active Directory or SAM local accounts is the following:

[SecurityCritical, DirectoryServicesPermission(SecurityAction.Assert, Unrestricted=true)]
public bool Validate(string userName, string password, ContextOptions connectionMethod)
{
    if ((userName != null) && (userName.Length == 0))
    {
        return false;
    }
    if ((this.contextType == ContextType.Domain) || (this.contextType == ContextType.ApplicationDirectory))
    {
        try
        {
            NetworkCredential creds = new NetworkCredential(userName, password);
            this.BindLdap(creds, connectionMethod);
            return true;
        }
        catch (LdapException exception)
        {
            if (exception.ErrorCode != ExceptionHelper.ERROR_LOGON_FAILURE)
            {
                throw;
            }
            return false;
        }
    }
    return this.BindSam(this.serverName, userName, password);
}

Final Conclusions:

The Win32 Logon API method may be is more verbose of all but has more capabilities like inform the reason behind a failed authentication like account expiration, or if the password has not been set, etc. If you don’t need this advanced behavior it’s recommended the 3.5 or just bind approach.

References:

http://stackoverflow.com/questions/290548/c-validate-a-username-and-password-against-active-directory
http://stackoverflow.com/questions/30861/authenticating-domain-users-with-system-directoryservices
http://archive.devx.com/security/articles/ps0602/ps0602-4.asp
http://support.microsoft.com/kb/316748/en-us
http://msdn.microsoft.com/en-us/library/ms180890(VS.80).aspx
http://www.adventuresindevelopment.com/2009/06/02/how-to-authenticate-a-user-in-active-directory-using-aspnet/
http://support.microsoft.com/kb/180548/en-us
http://www.pinvoke.net/default.aspx/advapi32/LogonUser.html