DataContractSerializer Utility for Serialize – Deserialize

1 Comment

Here is a utility class that helps you serialize and deserialize objects with the DataContractSerializer.
There are 2 things you have to add yourself:

1. KnownTypes.txt file – in it you should insert for each known type (that is unknown to the DataContractSerializer) its full name of the type.
for example if the DataContractSerializer doesn’t recognize type T with namespace N, the KnownTypes file must have such line:


2. KnownAssemblies.txt – in it you should insert for each external assembly (that can be unknown to a type assembly at runtime) its location.
Meaning that if you want to serialize object O that Resides in Assembly A1 , that has a reference to some type T that resides In Assembly A2 (and therefore is not known to Assembly A1), you must add this line to KnownAssemblies file:

A2 Assembly Location

you should put both files in a resource file (here is “Resource1”) and thats it, you can easily serialize / deserialize objects.
(just remember to add to each Class you want to serialize / deserialize class attribute [DataContract] , and to each member you want to S/D member attribute [DataMember].

and the code:

 public static class SerializeUtil
        private static Dictionary<string, List<Type>> sAssembliesKnownTypes;

        private static Dictionary<string,List<Type>> AssembliesKnownTypes
                if (sAssembliesKnownTypes == null)
                    sAssembliesKnownTypes = new Dictionary<string, List<Type>>();
                    var tKnownAssemblies = Regex.Split(Resource1.KnownAssemblies, "\r\n");
                    foreach (var tKnownAssembly in tKnownAssemblies)
                return sAssembliesKnownTypes;

        private static List<Type> KnownTypes

                return AssembliesKnownTypes.Values.SelectMany(pTypes => pTypes).Distinct().ToList();

        public static string Serialize(object pO)
            MemoryStream tMemoryStream = new MemoryStream();
            DataContractSerializer serializer = new DataContractSerializer(pO.GetType(),KnownTypes);
            serializer.WriteObject(tMemoryStream, pO);
            ASCIIEncoding enc = new ASCIIEncoding();
            return enc.GetString(tMemoryStream.ToArray());

        public static object Deserialize(Type pType, string pXML)
            DataContractSerializer serializer = new DataContractSerializer(pType, KnownTypes);
            ASCIIEncoding enc = new ASCIIEncoding();

            MemoryStream tMemoryStream = new MemoryStream(enc.GetBytes(pXML));
            return serializer.ReadObject(tMemoryStream);

        private static void AddToKnownAssemblies(Assembly pAssembly)
            if (!AssembliesKnownTypes.ContainsKey(pAssembly.Location))
                var tKnownTypes = Regex.Split(Resource1.KnownTypes, "\r\n");
                var tNewTypes = new List<Type>();
                foreach (var tTypeStr in tKnownTypes)
                    Type tType = null;
                    if (pAssembly != null)
                        tType = pAssembly.GetType(tTypeStr);
                    if (tType == null)
                        tType = Type.GetType(tTypeStr);
                    if (tType != null)
                AssembliesKnownTypes[pAssembly.Location] = tNewTypes;


Gridview sorting both ascending and descending

Leave a comment

If you want to make your gridview sort ascending and descending you would probably have to do it manually with the help of the view state.

this small example below will show you how:

attaching the Sorting event:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
DataSourceID="ObjectDataSource1"  onsorting="GridView1_Sorting">

implementing the sorting event:

 protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
if (ViewState["HeadersDirection"] == null )
ViewState["HeadersDirection"] = new Dictionary();

var tSortDirections = ((Dictionary)ViewState["HeadersDirection"]);

if (tSortDirections.ContainsKey(e.SortExpression))
e.SortDirection = tSortDirections[e.SortExpression] == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;

tSortDirections[e.SortExpression] = e.SortDirection;


and that’s it!
now the sort expression get “flipped” as it should 🙂

LINQ dynamic orderby and reflection

1 Comment

When you need to use the orderby query of linq on some object property, you sometimes need to specify it dynamically (in runtime).

so in order to do that we can use reflection.

the way to do that can be seen in this example:

static IEnumerable<Item> GetItems(string sortExpression)
from item in items
where <something>
orderby OrderBy(sortExpression , item)
select item ;

static object OrderBy(string sortExpression, Item item)
Type t = item.GetType();
var tPropertyInfo = t.GetProperty(sortExpression);
if (tPropertyInfo != null)
return tPropertyInfo.GetGetMethod().Invoke(item, null);
return null;

you can see that the item property invoked by reflection, so therefore the orderby get dynamically set.

Undoer (C#)

Leave a comment

public class Undoer
        private static Stack sUndoStack = new Stack();
        private static Stack sRedoStack = new Stack();
        public static int UndoStackCount { get { return sUndoStack.Count; } }
        public static int RedoStackCount { get { return sRedoStack.Count; } }

        public static bool InsertEnabled = true;

        public static void Insert(Func pObj)
            if (InsertEnabled)

        public static T Undo()
            var tObj = sUndoStack.Pop();
            if (sUndoStack.Count &gt; 0)
                return sUndoStack.Peek();
            return default(T);

        public static T Redo()
            var tObj = sRedoStack.Pop();
            return tObj;

        public static bool CanUndo { get { return sUndoStack.Count &gt; 0; } }

        public static bool CanRedo { get { return sRedoStack.Count &gt; 0; } }

        public static void Init()


Company Automatic Hibernation

Leave a comment

In order to cut on electricity costs on this recent Economic Crises, I came up with an idea.

It’s a simple one, but as I see it, it can save a company a lot of money on electrical.

The idea is to develop a cross-company process that will put every employee computer in hibernation at a specific time.

So how will the Automatic Hibernation work?

  1. A daily Hibernation time is set.
  2. 30 minute grace period before hibernation lets the user cancel the hibernation.
  3. If not canceled the computer hibernates.
  4. If the user wants to connect to the computer, a wakeup call is initiated on the computer, and it’s turned on.

Now we’ll see why people do not turn off their computer, and how Automatic Hibernation deals with each one of the problems:

  1. Don’t remember
  • Don’t need to remember, that’s why it’s automatic.
  1. 2. Don’t really care
  • Don’t need to care anymore, the company cares about the electrical bill.
  1. Want to get back to their already opened applications
  • Hibernation lets you get right back to the state where you were before the hibernation.
  1. Want to have the ability to remotely connect from home to their computer
  • In order to remotely connect to a shut down / hibernated computer we need to do 2 things:

1)      Make sure that each network card on an employee PC has what’s called wake up capability.

2)      Add a wake up feature to the company remote access.

What is needed for the Automatic Hibernation to be applied on the employees’ computer?

  1. Develop Automatic Hibernation.
  2. Enable wake up capability on all network cards (replace the ones that don’t have if needed).
  3. Add a wake up feature to the company remote access
  4. Reserve in each computer HDD enough space for the hibernation (RAM memory size will suffice).
  5. Inform all employees about Automatic Hibernation and the hibernation time.
  6. Install in all the computers the Automatic Hibernation process.

And finally what’s the rough cost cut for the company?

1.            E employees/Computers.

2.            C consumption cost per hour.

3.            about 8 hours (12:00PM – 8:00AM) hibernation.

E X C X 8 per day

E X C X 8 * 30 = per month

E X C X 8 * 30 * 12 per year

If we put some values in the variables like E = 5000, C = 0.02 $ then:

5000  X 0.02  X 8  = 800$ per day

5000  X 0.02  X 8 * 30 = 24,000$ per month

5000 X 0.02  X 8 * 30 * 12  = 288,000$ per year

We of course need to decrease from the above number a onetime development and deployment rough cost, so here is an example that is not that farfetched:

  1. 6000$ average developer cost for a month.
  2. 10 team members doing the development and deployment.
  3. 4 months development.
  4. 2 months deployment.
  5. ¼ network cards to be replaced (assumption).
  6. 10$ per network card.

6000$ X (4 +2) X 10 +( E = 5000)/4 X 10 = 372,500$

A cost that will be covered in about a year, and from that point on there will only be a cut on the company electricity costs.

Interesting idea, not?

XML Serialization Derived Types Problem Can be resolved!



I wanted to share with you a solution I found to a long annoying problem I had with C# Automatic XML Serialization.

Some of you may know this solution, but it is important so everyone should know that.

The background is XML Serialization of objects. C# gives us an automatic method to serialize object by using XMLSerializer.

For example serialize object A like this:

Class Base{}

Class DerivedBase : Base{}

Class A


Base b;

DerivedBase db;

public virtual XmlSerializer ser { get { return new XmlSerializer(typeof (A)); } }

public override string ToString()


var sw = new StringWriter();

ser.Serialize(sw, this);


return sw.ToString();



Now if we call A.ToString() we will get this Exception:

“The type namespace.DerivedBase was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically”

Usually the solution is to add XMLInclude to Class Base:


Class Base{}

But 2 problems can rise in this implementation:

  1. What if DerivedBase is not in the namespace of class Base, or even worse in a project that depends on Base namespace, so Base cannot XMLInclude DerivedBase
  2. What if we only have class Base as a dll ,so again  Base cannot XMLInclude DerivedBase

Till now I used only this method while trying to be truth to the class and namespace inheritance structure, but now I confronted with some class that I don’t wanted to move to the DerivedBase Project.

So the solution to the 2 problems is by using XmlSerializer Constructor (Type, array<Type>[]()[]) :

XmlSerializer ser = new XmlSerializer(typeof(A), new Type[]{ typeof(DerivedBase)});

And even if class B will inherit A, and have some DerivedDerivedBase property, it can override the XmlSerializer ser property with its own XmlSerializer.

Hope it could help you like it helped me…

Newer Entries