NameObjectCollectionBase Sample c#

this is a  special collection in  System.Collections.Specialized . Main speaciality that it allows duplication keys to be added to the hashtable. It provides the abstract base class for a collection of associated String keys and Object values that can be accessed either with the key or with the index.

An Example:

 public sealed class ExecutionModuleCollection : NameObjectCollectionBase
    {
        private readonly object syncRoot = new object();
 
        public object SyncRoot
        {
            get { return this.syncRoot; }
        }
 
        public string[] AllKeys {
            get
            {
                return this.BaseGetAllKeys();
            }
        }
 
 
        public IExecutionModule this[int index]
        {
            get
            {
                return (IExecutionModule) this.BaseGet(index);
            }
            internal set
            {
                this.BaseSet(index, value);
            }
        }
 
        public IExecutionModule this[string name] {
            get
            {
                return (IExecutionModule) base.BaseGet(name);      
            }
            internal set
            {
                base.BaseSet(name, value);
            }
        }
 
 
        public void CopyTo(Array dest, int index)
        {
            Array.Copy(base.BaseGetAllValues(), dest, index);
        }
 
        public IExecutionModule Get(string name)
        {
            return (IExecutionModule)base.BaseGet(name);
        }
 
        public string GetKey(int index)
        {
            return  this.Keys[index].ToString() ;
        }
 
        public void Add(ExecutionModule module)
        {
            base.BaseAdd(module.Name, module);
        }
    }

Attention:

You can not insert value in specific order because it uses a hashtable in background and this kind of insertation break it.If you need it to be ordered, you should  use  an OrderedDictionary or SortedDictionary<T,T>.

About Thread Safety

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Enumerating through a collection is intrinsically not a thread safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

What is the difference of Server.HtmlEncode and HttpUtility.HtmlEncode

There is no diffrence just Server.HtmlEncode calls  HttpUtility.HtmlEncode.
if you use reflector you realise that server object is kind of Httputility.

For more info:
http://msdn.microsoft.com/en-us/library/ms525347.aspx
http://msdn.microsoft.com/en-us/library/system.web.httputility.htmlencode.aspx

Hide your asp.net tag attribute from HTML output

You have an attribute and you want to hide this attribute in your HTML output . It useful when you dont want extra junk in your response then  use “meta:”

Example:

<asp:Label id=”myLabel” runat=”server”  text=”hello”  myattribute=”mello”  />

Output is

<span myattribute=”mello”>hello </span>

with using meta:

<asp:Label id=”myLabel” runat=”server”  text=”hello”  meta:myattribute=”mello”  />

output is

<span>hello</span>

May the code be with you…

SyncRoot , lock(this) and Syncronized Pattern

You have an object and you want to use one of function that object as threadsafe you can use lock(object) statement for syncronization. But it can cause a deadlock if you are using “lock(this) ” . it occurs when derived classes want to try lock before your inner function execute and also it never gonna execute , because of your inner function wating first lock to be removed but it never be done here is the DeadLock!!  .

    public class MyClass
    {
        public void DoSomething()
        {
//DO NOT USE locking like this
            lock (this)
            {
               
            }
        }
    }

Dead Lock Example:

        MyClass cs = new MyClass();
        public void ThreadWorker() //this function is called by another thread
        {
            lock (cs) // DEADLOCK !!!
            {
                cs.DoSomething();
            }
        }

Here is the golden rule :

 If you have an internal data structure that you want to prevent simultaneous access to by multiple threads, you should always make sure the object you’re locking on is not public.

The reasoning behind this is that a public object can be locked by anyone, and thus you can create deadlocks because you’re not in total control of the locking pattern.
This means that locking on this is not an option, since anyone can lock on that object. Likewise, you should not lock on something you expose to the outside world.
Which means that the best solution is to use an internal object, and thus the tip is to just use Object.
Locking data structures is something you really need to have full control over, otherwise you risk setting up a scenario for deadlocking, which can be very problematic to handle.

Example

 public class MyClass
    {
// Use an inner object for locking.
        object _SyncRoot = new object();
        public void DoSomething()
        {
            lock (_SyncRoot)
            {
                int val = DateTime.Now.Second;
                Console.WriteLine("1) Do Someting Called by " + Thread.CurrentThread.Name);
                while (val - 1 != DateTime.Now.Second)
                {
                    //do some thing 
                }
                Console.WriteLine("1) out");
            }
        }
    }

Most of syncronization tasks  be used when working on collections  and Syncronized Pattern and  ICollection.SyncRoot Property is already exists for c# collections you dont need to create your own.
But if you have a custom object you can use  Syncronized Pattern for your classes . There is an example of Thread Safe wrapper code:

    class MyClass
    {
        private class SynchronizedClass : MyClass
        {
            private object syncRoot = new object();
            private MyClass _instance;
            public SynchronizedClass(MyClass cls) { _instance = cls; }
            public override bool IsSynchronized { get { return true; } }
            public override void Funk1() { lock (syncRoot) { _instance.Funk1(); } }
            public override void Funk2() { lock (syncRoot) { _instance.Funk2(); } }
        }
        public virtual bool IsSynchronized { get { return false; } }
        public static MyClass Synchronized(MyClass cls)
        {
            if (!cls.IsSynchronized)
                return new SynchronizedClass(cls);
            return cls;
        }
        public virtual void Funk1() { /* Your code here */ }
        public virtual void Funk2() { /* Your code here */ }
    }
See:
http://msdn.microsoft.com/en-us/library/system.collections.icollection.syncroot.aspx
http://stackoverflow.com/questions/728896/whats-the-use-of-the-syncroot-pattern
Happy Codding !!!

XmlSerializer Memory Leak Solution

This problem occurs because an assembly that contains Microsoft intermediate language (MSIL) is created and loaded into memory when you create an XmlSerializer object. You cannot unload the assembly without unloading the application domain that it resides in. Therefore, when you create several XmlSerializer objects, you may notice unexpectedly high memory usage.

For example, if you use the following constructor to create several XmlSerializer objects, a new temporary assembly is created every time:

public void XmlSerializer( Type t, Type[] extraTypes)

To work around this problem of re-creating assemblies, use one of the following methods:
Create one instance of the XmlSerializer class, and put that instance in the cache by using the caching APIs. For example, for a .dll file that is named HighSchool, the following code caches one instance of the XmlSerializer class:
XmlSerializer mySerializer = new XmlSerializer(typeof(HighSchool.MyClass), attrOverrides, extraTypes, root, “http://www.microsoft.com“);
Cache[“HighSchoolSerializer”] = mySerializer

  • Use the instance of the XmlSerializer class that you put in the cache instead of creating a new XmlSerializer object every time.
  • Use the following XmlSerializer class constructors. These class constructors cache the assemblies:
    In the .NET Framework version 1.0
     public XmlSerializer(Type);
    In the .NET Framework version 1.1
    public XmlSerializer(Type type);
    public XmlSerializer(Type type, string defaultNamespace);
  • Declare the XmlSerializer object to be a static member of a class.

Source:
http://support.microsoft.com/kb/886385