dotnet

ESXiPXE: Install ESXi from networking

A small tool for deploying VMware ESXi from another computer running with Microsoft Windows.

DotNet framework runtime 4.o is required.

Freeware.

Download Link

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

Weak Reference

本文简述dotNet中Weak Reference(弱引用)的功能,并举例在具体应用场景中的效果。

 

首先,让我们回忆一下dotNet CLR的对象生命周期管理。为了解决对象引用计数器以及编码不慎可能导致的内存泄漏,dotNet CLR引入了Garbage Collection(GC)机制。GC会不时的扫描程序,将程序中不再使用的对象进行回收。

那么,怎样的对象才是不再被使用的呢?通常的,我们可以简单认为,在未关联至任何变量(包括对象属性、集合内成员等)的情况下的对象,也就是说,无法被安全的访问到的对象,会被认为是不再被使用的对象。那么,有没有例外呢?

这个例外,就是dotNet中的Weak Reference。它的直接功能,就是封装对一个对象的引用,但不会被GC认做有效的关联。换言之,GC在判断对象是否不再被使用时,不会考虑Weak Reference的引用。

Weak Reference类位于System命名空间下。我们可以通过其构造器直接构造一个对象。System.WeakReference有两个构造器,通常我们使用的第一个,要求传送一个object作为其引用的实际对象(Target属性);第二个构造器需要传送一个bool类型变量,用以定义是否进行长程跟踪,本功能不在本文中进行描述。

当我们构造好一个System.WeakReference后,我们可以通过访问其Target属性,设置或读取其引用的实际变量。由于GC不会考虑Weak Reference中对象的引用,如果Target属性的对象仅被引用于Weak Reference对象时,这个对象则随时可能被GC回收。

我们可以通过判断Weak Reference对象的IsAlive属性,来确定Target属性指向的对象是否已经被回收。当IsAlive为false时,Target属性也将被自动赋值为null。特别的,由于Target属性也可以被显式的赋值为null,我们应该使用IsAlive来进行判断,而不要使用Target属性是否为null来推断。

 

那么,Weak Reference有什么实际用途呢?

有时候,我们需要访问一个对象,却又不想管理其生命周期。例如,我们可能在要某段代码中,将某个窗体对象赋值至一个对象属性中,但我们又不希望由于这个对象未被回收,影响到原窗体的生命周期。如果我们使用Weak Reference对象,代替原属性值,即可避免这种情况的出现。

另外,有些数据,我们并不会经常的访问,但所有的访问又相对密集。这时候我们也可以使用Weak Reference来对数据进行封装。每次访问时,通过判断IsAlive来确定,是否需要构造其Target。由于GC通常不会在系统繁忙时激活,所以这种类似Cache的应用,通常只会在资源不足或系统空闲时才会被回收,而且这种回收是由dotNet CLR负责实现,无需用户编码干预。