Close

(Maybe) best practice: Use shared projects in Visual Studio involved with Nuget

I wrote many solutions in Visual Studio. Some of them includes components, which intend to be published to Nuget.

Previously, I wrote these projects directly and publish them to Nuget. This is not a smooth way. Consider this: You have project A need to be published to Nuget. Project B, as well. Project C need to reference project A and B, and also need to be published to Nuget. Project D need to reference C for testing. Obviously, following Nuget standard, the Project C need to reference A by using Nuget Packages instead of the projects of A and B directly. But it seems that there is no called testing mode publishing in Nuget supported. There is no easy way to test your project before publishing to Nuget. Maybe you need to change the references in Project C and D repeatedly, switching mode between testing and publishing.

Recently, Shared Project support added to Visual Studio. Now I use a better way, IMHO, in developing such a solution mentioned above.

  • Create a shared project for each project need to be published to Nuget.
  • Put all codes into shared project instead of original one.
  • Create a project for publishing to Nuget, reference the shared project related. — Project N
  • Create a project for testing, reference the shared project related. — Project T

If your Nuget projects need more references which will be published to Nuget from this solution, add them from Nuget to the Project N, and add them as reference from their Project T to this Project T.

All Project Ns will only be used for publishing to Nuget. As well as all Project Ts will be used for testing. They share the same code but the different source for referencing.

TFS 2015 Upgrading

There are 2 things you should have in mind about TFS 2015 Upgrading.

1 The database upgrading process will cost much more time than upgrading among Update package of TFS 2013.

2 The dedicated SharePoint integration package is removed and M$ did a shit test again. If you, like me, installed TFS on a server other than SharePoint cluster, now you have to install the whole TFS on all SharePoint servers. After the installation, the upgrading wizard will be popped up but it will failed due to no database can be found. You have to choose to install SharePoint integration role yourself. And after that, you will know that TFS SharePoint integration package 2013 will NOT and NOT ABLE to be removed, lol, just another piece of crap.

A way to run nearly all functions of dotNet from SQL Server

Last night, I got a case to write a function in SQL Server 2005 to support the user account and password check against Active Directory. The user requirement is quite clear:

  • Create a scalar-valued function named LDAPUserCheck;
  • Parameter @username nvarchar(MAX) for user name to check;
  • Parameter @password nvarchar(MAX) for password matching the username specified;
  • Return bit 1 if succeeded, or 0 for all other reasons.

After a digging, I found that LDAP password authentication is not supported directly by SQL Server. But SQLCLR is a way to build the native dotnet program into SQL Server. In a new created SQLCLR project in VS 2005, I realized it’s unable to add the reference System.DirectoryServices.AccountManagement, which is required by running the code for Active Directory authentication. But a Web Service is a choice.

My steps to achieve that:

1 Create and deploy a Web Service for the authentication check.

1.1 Create a Web Service project.

1.2 Add System.DirectoryServices.AccountManagement as a reference.

1.3 Add a setting DomainName as string for storing the domain name.

1.4 Add a service like this:

    public class LDAPAuthentication : System.Web.Services.WebService
    {
        static string domainName = Settings.Default.DomainName;

        [WebMethod]
        public bool Check(string userName, string password)
        {
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName))
            {
                // validate the credentials
                bool isValid = pc.ValidateCredentials(userName, password);
                return isValid;
            }
        }
    }

1.5 Deploy this service and use a application pool running by a domain user. This user should be added to IIS_WPG group in Windows Server 2003.

2 Create a SQLCLR project to call the Web Service.

2.1 Create a SQLCLR project in Visual Studio 2005.

2.2 Add a Web Service reference. It’s named as LDAP in my project.

2.3 Add a User Defined Functions.

    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlBoolean LDAPUserCheck(
        SqlString username, SqlString password)
    {
        using (LDAPAuthentication.LDAP.LDAPAuthentication service = new LDAPAuthentication.LDAP.LDAPAuthentication())
        {
            if (service.Check(username.ToString(), password.ToString()))
            {
                return SqlBoolean.True;
            }
            else
            {
                return SqlBoolean.False;
            }
        }
    }

2.4 Set Permission Level to External in Database page of project setting.

2.5 Build this project to get the dll files. In my case, these files are named LDAPAuthentication.dll and LDAPAuthentication.XmlSerializers.dll.

3 Deploy this project into SQL Server 2005.

3.1 Enable the CLR support in SQL Server 2005 by running this code:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO

sp_configure 'clr enabled', 1;
GO
RECONFIGURE;
GO

sp_configure 'show advanced options', 0;
GO
RECONFIGURE;
GO

3.2 Create a database for storing this function. Or, you can use any existed database as well. In my case, I created a database “tester”.

3.3 Set trustworthy on this database by running:

ALTER DATABASE [tester] SET trustworthy ON

3.4 Copy the 2 dll files created in step 2 to this server. In my case, these are stored in C:\SQLCLR folder.

3.5 Create assemblies in SQL Server by running:

create assembly [LDAPAuthentication] from 'C:\SQLCLR\LDAPAuthentication.dll' with permission_set = external_access
create assembly [LDAPAuthentication.XmlSerializers] from 'C:\SQLCLR\LDAPAuthentication.XmlSerializers.dll' with permission_set = external_access

3.6 Create function to run the method we’ve created in VS 2005:

CREATE FUNCTION [dbo].[LDAPUserCheck](@username [nvarchar](4000), @password [nvarchar](4000))
RETURNS [bit] WITH EXECUTE AS CALLER
AS 
EXTERNAL NAME [LDAPAuthentication].[UserDefinedFunctions].[LDAPUserCheck]

Now everything is done. You can call this function like all others created by SQL. Run this for test.

select dbo.LDAPUserCheck('myusername','mypassword')

 

Solved: Why Linq Where.FirstOrDefault is faster than use FirstOrDefault with condition on an array?

Hi all.

 

Why applying “.Where(condition).FirstOrDefault()” is much faster than “.FirstOrDefault(condition) when it’s applied on an array?

20140725100245

 

Answer: While calling method Where() on an Array or a List, it’s optimized to use the enumerator of the source directly. But FirstOrDefault(), which doesn’t have this mechanism, runs the virtual method version from IEnumerator.GetEnumerator().

Special thanks to Iris Sakura.

Official feedback about removing orphan collection in TFS 2013

Continued from: Remove orphan collection item without related database in TFS 2013 with Update 2

 

It’s announced that this will be fixed in Update 3 of TFS by Microsoft Officially.

https://connect.microsoft.com/VisualStudio/feedback/details/874523/delete-a-collection-without-related-database-connected-vs2013u2

 

A workaround, editing database directly, is provided also.

http://social.msdn.microsoft.com/Forums/en-US/cceec4ba-1712-4905-9e7b-8669bf81880f/damaged-project-collection-on-tfs-2013-no-solution-to-delete-it-from-server?forum=tfsadmin

But you should keep in mind that editing database directly is dangerous and will lose all supports from Microsoft.

Remove orphan collection item without related database in TFS 2013 with Update 2

Last week, the Configuration Manager in our company tested to create a collection in Team Foundation Server (TFS for short) 2013 with Update 2. After test, the database of this collection is deleted directly from SqlServer by mistake and there is no backup for it. So an orphan item for this collection is still existed there and have to be removed manually.

 

First, I try to remove it from Team Foundation Server Administration Console (TfsMgmt.exe). It failed in detach process.

Then, I try to do it with TFSconfig.exe in console mode. I’m pretty sure that’s work in previous version of TFS, maybe 2012. But in 2013 with Update 2, it failed the same as TfsMgmt.

I tried to use a database from another collection by renaming it as the deleted one, or even use a database created with another TFS instance with the same collection name, all failed.

At that time, I turned to MSDN forum. One MVP provided some tables within Tfs_Configuration database. Some deleting operations should be taken there. After that, the collection is removed from the TfsMgmt but it still can be found in Visual Studio at client side.

Finally, I detached all collections and redeployed the whole TFS instance. That works as predictable.

 

If somebody falls into the same jam, the detachment and redeployment is the only way to correct it, unless you have the backup of that deleted database.

 

Related: http://social.msdn.microsoft.com/Forums/vstudio/en-US/3a072d51-298a-48b5-a57e-301f5ef2670f/how-to-delete-a-collection-without-related-database-connected-tfs-2013-update-2?forum=tfsgeneral

C#: Split a Distinguished Name of Active Directory into array of string

class DistinguishedNameSplit
{
    static string[] hexCodes = new string[] { "0""1""2""3""4""5""6""7""8""9""a""A""b""B""c""C""d""D""e""E""f""F" };
 
    public static List<string> Split(string distinguishedName)
    {
        List<string> pool = new List<string>();
        StringBuilder working = new StringBuilder();
        string hexHigh = "";
        MachineStatus status = MachineStatus.A;
        int index = 0;
        int indexMax = distinguishedName.Length - 1;
 
        while (index <= indexMax)
        {
            string value = distinguishedName.Substring(index, 1);
            switch (status)
            {
                case MachineStatus.A:
                    if (value == ",")
                    {
                        pool.Add(working.ToString());
                        working.Clear();
                    }
                    else if (value == "\"")
                    {
                        working.Append("\"");
                        status = MachineStatus.B;
                    }
                    else if (value == "\\")
                    {
                        status = MachineStatus.C;
                    }
                    else
                    {
                        working.Append(value);
                    }
                    break;
                case MachineStatus.B:
                    if (value == "\"")
                    {
                        working.Append("\"");
                        status = MachineStatus.A;
                    }
                    else if (value == "\\")
                    {
                        status = MachineStatus.E;
                    }
                    else
                    {
                        working.Append(value);
                    }
                    break;
                case MachineStatus.C:
                    if (value == "," || value == "\"" || value == "\\")
                    {
                        working.Append(value);
                        status = MachineStatus.A;
                    }
                    else if (hexCodes.Contains(value))
                    {
                        hexHigh = value;
                        status = MachineStatus.D;
                    }
                    else
                    {
                        throw new ArgumentException("The distinguished name specified is not typed legally.");
                    }
                    break;
                case MachineStatus.D:
                    if (hexCodes.Contains(value))
                    {
                        working.Append((char)Convert.ToByte(String.Format("{0}{1}", hexHigh, value), 16));
                        status = MachineStatus.A;
                    }
                    else
                    {
                        throw new ArgumentException("The distinguished name specified is not typed legally.");
                    }
                    break;
                case MachineStatus.E:
                    if (value == "," || value == "\"" || value == "\\")
                    {
                        working.Append(value);
                        status = MachineStatus.B;
                    }
                    else if (hexCodes.Contains(value))
                    {
                        hexHigh = value;
                        status = MachineStatus.F;
                    }
                    else
                    {
                        throw new ArgumentException("The distinguished name specified is not typed legally.");
                    }
                    break;
                case MachineStatus.F:
                    if (hexCodes.Contains(value))
                    {
                        working.Append((char)Convert.ToByte(String.Format("{0}{1}", hexHigh, value), 16));
                        status = MachineStatus.B;
                    }
                    else
                    {
                        throw new ArgumentException("The distinguished name specified is not typed legally.");
                    }
                    break;
            }
            index++;
        }
 
        if (status == MachineStatus.A)
        {
            pool.Add(working.ToString());
            return pool;
        }
        else
        {
            throw new ArgumentException("The distinguished name specified is not ended correctly.");
        }
    }
 
    enum MachineStatus
    {
        A, B, C, D, E, F
    }
}

Recursive Enumerator

using System;
using System.Collections.Generic;

namespace SecretNest.RecursiveEnumerator
{
    /// <summary>
    /// Get the enumerator for querying the parents of specified item.
    /// </summary>
    /// <typeparam name="T">Item type</typeparam>
    /// <param name="current">Item for querying parents</param>
    /// <returns>Enumerator of parents querying</returns>
    public delegate IEnumerator<T> GetParentsEnumerator<T>(T current);

    /// <summary>
    /// Enumerator for querying parents
    /// </summary>
    /// <typeparam name="T">Item type</typeparam>
    public class Enumerator<T> : IEnumerator<T>
    {
        T current, initial;

        Queue<T> notQueried = new Queue<T>();

        HashSet<T> queried = new HashSet<T>(); //for avoiding duplicated query
        Queue<T> rollbackHistory = new Queue<T>(); //for soft reset
        Queue<T> history = new Queue<T>(); //for soft reset
        IEnumerator<T> activeQuery;

        /// <summary>
        /// Callback for getting the enumerator, which is used for querying the parents of specified item.
        /// </summary>
        public GetParentsEnumerator<T> GetParentsEnumeratorCallback { get; set; }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="initial">Initial item</param>
        public Enumerator(T initial)
        {
            notQueried.Enqueue(initial);
            this.initial = initial;
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="initial">Initial item</param>
        /// <param name="callback">Callback for getting the enumerator, which is used for querying the parents of specified item.</param>
        public Enumerator(T initial, GetParentsEnumerator<T> callback)
        {
            notQueried.Enqueue(initial);
            this.initial = initial;
            GetParentsEnumeratorCallback = callback;
        }

        /// <summary>
        /// Gets the current element in the collection.
        /// </summary>
        public T Current
        {
            get { return current; }
        }

        bool disposed;
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    current = default(T);
                    notQueried = null;
                    queried = null;
                    history = null;
                }
                disposed = true;
            }
        }

        /// <summary>
        /// Gets the current element in the collection.
        /// </summary>
        object System.Collections.IEnumerator.Current
        {
            get { return current; }
        }

        /// <summary>
        /// Skip same items
        /// </summary>
        public bool SkipSameItems { get; set; }

        /// <summary>
        /// Advances the enumerator to the next element of the collection.
        /// </summary>
        /// <returns>true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection. </returns>
        public bool MoveNext()
        {
            if (disposed) throw new ObjectDisposedException(null);
            if (rollbackHistory.Count > 0)
            {
                current = rollbackHistory.Dequeue();
                history.Enqueue(current);
                return true;
            }
            if (activeQuery != null)
            {
            here:
                if (activeQuery.MoveNext())
                {
                    if (SkipSameItems && history.Contains(activeQuery.Current)) { goto here; }
                    current = activeQuery.Current;
                    history.Enqueue(current);
                    notQueried.Enqueue(current);
                    return true;
                }
                else
                {
                    activeQuery = null;
                }
            }
            if (GetParentsEnumeratorCallback != null)
            {
                while (notQueried.Count != 0)
                {
                    T item = notQueried.Dequeue();
                    if (!queried.Contains(item))
                    {
                        IEnumerator<T> enumerator = GetParentsEnumeratorCallback(item);
                        queried.Add(item);
                        here:
                        if (enumerator != null)
                        {
                            if (enumerator.MoveNext())
                            {
                                activeQuery = enumerator;
                                if (SkipSameItems && history.Contains(enumerator.Current)) { goto here; }
                                current = enumerator.Current;
                                history.Enqueue(current);
                                notQueried.Enqueue(current);
                                return true;
                            }
                            else
                            {
                                enumerator = null;
                            }
                        }
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// Sets the enumerator to its initial position, which is before the first element in the collection. Keep all histories for caching.
        /// </summary>
        public void Reset()
        {
            if (disposed) throw new ObjectDisposedException(null);
            while (history.Count > 0)
            {
                rollbackHistory.Enqueue(history.Dequeue());
            }
            current = default(T);
        }

        /// <summary>
        /// Sets the enumerator to its initial position, which is before the first element in the collection. Reset all data, and close active sub-query.
        /// </summary>
        public void HardReset()
        {
            if (disposed) throw new ObjectDisposedException(null);
            queried.Clear();
            notQueried.Clear();
            notQueried.Enqueue(initial);
            history.Clear();
            activeQuery = null;
            current = default(T);
        }
    }
}

 

Download code and demo projects

OrderedDictionary

Dictionary with ordered keys.
One c# (4.0) class which implements ICollection, IDictionary, IList and IXmlSerializable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace System.Collection.Generic
{
    [Serializable]
    public class OrderedDictionary : 
        ICollection>, 
        IDictionary, 
        IList>, 
        System.Xml.Serialization.IXmlSerializable
    {
        List keys;
        Dictionary dict;

        #region Constructors
        /// 
        /// Initializes a new instance of the OrderedDictionary class that is empty and has the default initial capacity. 
        /// 
        public OrderedDictionary()
        {
            keys = new List();
            dict = new Dictionary();
        }

        /// 
        /// Initializes a new instance of the OrderedDictionary class that is empty and has the specified initial capacity. 
        /// 
        /// The number of elements that the new dictionary can initially store.
        public OrderedDictionary(int capacity)
        {
            keys = new List(capacity);
            dict = new Dictionary(capacity);
        }

        /// 
        /// Initializes a new instance of the OrderedDictionary class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied. 
        /// 
        /// The collection whose elements are copied to the new dictionary.
        public OrderedDictionary(IEnumerable> collection)
        {
            keys = new List();
            dict = new Dictionary();
            var enumerator = collection.GetEnumerator();
            while (enumerator.MoveNext())
            {
                keys.Add(enumerator.Current.Key);
                dict.Add(enumerator.Current.Key, enumerator.Current.Value);
            }
        }

        /// 
        /// Initializes a new instance of the OrderedDictionary class that contains elements copied from the specified OrderedDictionary or Dictionary and uses the default equality comparer for the key type. 
        /// 
        /// The OrderedDictionary or Dictionary whose elements are copied to the new OrderedDictionary.
        public OrderedDictionary(IDictionary dictionary)
        {
            keys = new List();
            dict = new Dictionary();
            foreach (var item in dictionary)
            {
                keys.Add(item.Key);
                dict.Add(item.Key, item.Value);
            }
        }
        #endregion

        #region Add / Insert
        /// 
        /// Adds an item to the OrderedDictionary. 
        /// 
        /// The object to add to the OrderedDictionary.
        public void Add(KeyValuePair item)
        {
            dict.Add(item.Key, item.Value);
            keys.Add(item.Key);
        }

        /// 
        /// Adds an element with the provided key and value to the OrderedDictionary.
        /// 
        /// The object to use as the key of the element to add.
        /// The object to use as the value of the element to add.
        public void Add(TKey key, TValue value)
        {
            dict.Add(key, value);
            keys.Add(key);
        }

        /// 
        /// Inserts an item to the OrderedDictionary at the specified index. 
        /// 
        /// The zero-based index at which item should be inserted.
        /// The object to insert into the OrderedDictionary
        public void Insert(int index, KeyValuePair item)
        {
            dict.Add(item.Key, item.Value);
            keys.Insert(index, item.Key);
        }

        /// 
        /// Inserts an element with the provided key and value to the OrderedDictionary at the specified index. 
        /// 
        /// The zero-based index at which item should be inserted.
        /// The object to use as the key of the element to inserted.
        /// The object to use as the value of the element to inserted.
        public void Insert(int index, TKey key, TValue value)
        {
            dict.Add(key, value);
            keys.Insert(index, key);
        }

        /// 
        /// Gets the value associated with the specified key.
        /// 
        /// The key whose value to get.
        /// When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized. 
        /// true if the object that implements OrderedDictionary contains an element with the specified key; otherwise, false.
        public bool TryGetValue(TKey key, out TValue value)
        {
            return dict.TryGetValue(key, out value);
        }
        #endregion

        #region Remove / RemoveAt
        /// 
        /// Removes all items from the OrderedDictionary.
        /// 
        public void Clear()
        {
            dict.Clear();
            keys.Clear();
        }

        /// 
        /// Removes the specific object from the OrderedDictionary. The value property will be ignored.
        /// 
        /// The object to remove from the OrderedDictionary.
        /// true if item was successfully removed from the OrderedDictionary; otherwise, false. This method also returns false if item is not found in the original OrderedDictionary.
        public bool Remove(KeyValuePair item)
        {
            if (keys.Remove(item.Key))
            {
                return dict.Remove(item.Key);
            }
            else
            {
                return false;
            }
        }

        /// 
        /// Removes the element with the specified key from the OrderedDictionary.
        /// 
        /// The key of the element to remove.
        /// true if the element is successfully removed; otherwise, false. This method also returns false if key was not found in the original OrderedDictionary.
        public bool Remove(TKey key)
        {
            if (keys.Remove(key))
            {
                return dict.Remove(key);
            }
            else
            {
                return false;
            }
        }

        /// 
        /// Removes the OrderedDictionary item at the specified index. 
        /// 
        /// The zero-based index of the item to remove.
        public void RemoveAt(int index)
        {
            var key = keys[index];
            keys.RemoveAt(index);
            dict.Remove(key);
        }
        #endregion

        #region Count / Contains / IndexOf
        /// 
        /// Gets the number of elements contained in the OrderedDictionary. 
        /// 
        public int Count
        {
            get { return keys.Count(); }
        }

        /// 
        /// Determines whether the OrderedDictionary contains a specific value. The value property will be ignored.
        /// 
        /// The object to locate in the OrderedDictionary.
        /// true if item is found in the OrderedDictionary; otherwise, false. 
        public bool Contains(KeyValuePair item)
        {
            return keys.Contains(item.Key);
        }

        /// 
        /// Determines whether the OrderedDictionary contains an element with the specified key. 
        /// 
        /// The key to locate in the OrderedDictionary.
        /// true if the IOrderedDictionary contains an element with the key; otherwise, false. 
        public bool ContainsKey(TKey key)
        {
            return keys.Contains(key);
        }

        /// 
        /// Determines the index of a specific item in the OrderedDictionary.
        /// 
        /// The key to locate in the OrderedDictionary.
        /// The index of key if found in the list; otherwise, -1.
        public int IndexOf(TKey key)
        {
            return keys.IndexOf(key);
        }

        /// 
        /// Determines the index of a specific item in the OrderedDictionary. The value property will be ignored.
        /// 
        /// The item to locate in the OrderedDictionary.
        /// The index of item if found in the list; otherwise, -1.
        public int IndexOf(KeyValuePair item)
        {
            return keys.IndexOf(item.Key);
        }
        #endregion

        #region Misc
        /// 
        /// Apply the new comparer to OrderedDictionary.
        /// 
        /// The IEqualityComparer implementation to use when comparing keys, or null to use the default EqualityComparer for the type of the key.
        public void ApplyComparer(IEqualityComparer comparer)
        {
            var newDict = new Dictionary(keys.Count, comparer);
            var newKeys = new List(keys.Count);
            foreach (var key in keys)
            {
                newDict.Add(key, dict[key]);
                newKeys.Add(key);
            }
            keys = newKeys;
            dict = newDict;
        }

        /// 
        /// Gets a value indicating whether the OrderedDictionary is read-only. Value false will be returned always.
        /// 
        public bool IsReadOnly
        {
            get { return false; }
        }

        /// 
        /// Copies the elements of the OrderedDictionary to an Array, starting at a particular Array index. 
        /// 
        /// The one-dimensional Array that is the destination of the elements copied from OrderedDictionary. The Array must have zero-based indexing.
        /// The zero-based index in array at which copying begins. 
        public void CopyTo(KeyValuePair[] array, int arrayIndex)
        {
            int index = arrayIndex;
            foreach (var key in keys)
            {
                array[index++] = new KeyValuePair(key, dict[key]);
            }
        }
        #endregion

        #region Enumerator
        /// 
        /// Returns an enumerator that iterates through the collection. 
        /// 
        /// An IEnumerator that can be used to iterate through the collection.
        public IEnumerator> GetEnumerator()
        {
            return (from key in keys
                    select new KeyValuePair(key, dict[key]))
                    .GetEnumerator();
        }

        /// 
        /// Returns an enumerator that iterates through the collection. 
        /// 
        /// An IEnumerator that can be used to iterate through the collection.
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        /// 
        /// Returns an enumerator that iterates through the collection. 
        /// 
        /// An IEnumerator that can be used to iterate through the collection.
        IEnumerator> IEnumerable>.GetEnumerator()
        {
            return GetEnumerator();
        }

        /// 
        /// Returns an enumerator that iterates through the keys collection.
        /// 
        /// An IEnumerator that can be used to iterate through the keys collection.
        public IEnumerator GetKeysEnumerator()
        {
            return keys.GetEnumerator();
        }
        #endregion

        #region Collection
        /// 
        /// Gets an ICollection containing the keys of the OrderedDictionary.
        /// 
        public ICollection Keys
        {
            get { return new ReadOnlyCollection(keys); }
        }

        /// 
        /// Gets an ICollection containing the values of the OrderedDictionary.
        /// 
        public ICollection Values
        {
            get
            {
                return new ReadOnlyCollection
                    ((from key in keys
                      select dict[key]).ToList());
            }
        }
        #endregion

        #region indexer
        /// 
        /// Gets or sets the element with the specified key.
        /// 
        /// The key of the element to get or set.
        /// The value which linked to the specified key.
        public TValue this[TKey key]
        {
            get
            {
                return dict[key];
            }
            set
            {
                dict[key] = value;
            }
        }

        /// 
        /// Gets the value at the specified index.
        /// 
        /// The zero-based index of the value to get or set.
        /// The value at the specified index.
        TValue this[int index]
        {
            get
            {
                return dict[keys[index]];
            }
            set
            {
                dict[keys[index]] = value;
            }
        }

        /// 
        /// Gets the element at the specified index. The method set is not supported.
        /// 
        /// The zero-based index of the element to get.
        /// The element at the specified index.
        KeyValuePair IList>.this[int index]
        {
            get
            {
                var key = keys[index];
                return new KeyValuePair(key, dict[key]);
            }
            set
            {
                throw new NotSupportedException();
            }
        }

        /// 
        /// Gets the key at the specified index.
        /// 
        /// The zero-based index of the key to get.
        /// The key at the specified index.
        public TKey GetKeyOfIndex(int index)
        {
            return keys[index];
        }
        #endregion

        #region Serialization
        /// 
        /// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return Nothing( Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the XmlSchemaProviderAttribute to the class.
        /// 
        /// An XmlSchema that describes the XML representation of the object that is produced by the WriteXml method and consumed by the ReadXml method.
        public Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        /// 
        /// Generates an object from its XML representation.
        /// 
        /// The XmlReader stream from which the object is deserialized.
        public void ReadXml(Xml.XmlReader reader)
        {
            System.Xml.Serialization.XmlSerializer keySer = new System.Xml.Serialization.XmlSerializer(typeof(TKey));
            System.Xml.Serialization.XmlSerializer valueSer = new System.Xml.Serialization.XmlSerializer(typeof(TValue));
            reader.Read();
            reader.ReadStartElement("OrderedDictionary");
            if (reader.NodeType == System.Xml.XmlNodeType.EndElement)
                reader.ReadEndElement();
            else
            {
                while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
                {
                    reader.ReadStartElement("Item");
                    reader.ReadStartElement("Key");
                    TKey key = (TKey)keySer.Deserialize(reader);
                    reader.ReadEndElement();
                    reader.ReadStartElement("Value");
                    TValue value = (TValue)valueSer.Deserialize(reader);
                    reader.ReadEndElement();
                    dict.Add(key, value);
                    keys.Add(key);
                    reader.ReadEndElement();
                    reader.MoveToContent();
                }
                reader.ReadEndElement();
                reader.ReadEndElement();
            }
        }

        /// 
        /// Converts an object into its XML representation.
        /// 
        /// The XmlWriter stream to which the object is serialized.
        public void WriteXml(Xml.XmlWriter writer)
        {
            System.Xml.Serialization.XmlSerializer keySer = new System.Xml.Serialization.XmlSerializer(typeof(TKey));
            System.Xml.Serialization.XmlSerializer valueSer = new System.Xml.Serialization.XmlSerializer(typeof(TValue));
            writer.WriteStartElement("OrderedDictionary");
            if (Keys.Count > 0)
                foreach (TKey key in keys)
                {
                    writer.WriteStartElement("Item");
                    writer.WriteStartElement("Key");
                    keySer.Serialize(writer, key);
                    writer.WriteEndElement();
                    writer.WriteStartElement("Value");
                    valueSer.Serialize(writer, dict[key]);
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                }
            writer.WriteEndElement();
        }
        #endregion
    }
}

TreeView with CheckBox

If you wanna use CheckBox enabled TreeView in Windows Vista and further systems, you need to pay attention. If you double click the CheckBoxes in the TreeView, some useful event handlers, like BeforeClick and AfterClick, will not be raised. And, the vision of CheckBoxes will be changed (checked or not) but the property of related TreeNode will not.

To fix this, you have to create your own TreeView instead of the provided one.

using System;
using System.Windows.Forms;
public class FixedTreeView : TreeView {
protected override void WndProc(ref Message m) {
// Suppress WM_LBUTTONDBLCLK
if (m.Msg == 0x203) { m.Result = IntPtr.Zero; }
else base.WndProc(ref m);
}
}

Source: http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/9d717ce0-ec6b-4758-a357-6bb55591f956