Click here to Skip to main content
15,891,607 members
Articles / Programming Languages / C#

UniversalSerializer

Rate me:
Please Sign up or sign in to vote.
4.97/5 (108 votes)
15 Apr 2018Ms-RL31 min read 261.4K   4K   299  
An universal and easy serialization library for .NET and .NET Core.

// Copyright Christophe Bertrand.

// A ITypeContainer for BindingContext.


using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Windows.Forms;
#if DEBUG
using System.Diagnostics;
#endif

namespace UniversalSerializerLib2
{

	internal class BindingContextContainer : ITypeContainer
	{
		#region Store
		public Dictionary<object, BindingManagerBase> Data;
		#endregion Store

		static BindingContextContainer()
		{
			var HashKeyClass = _tBindingContext.GetNestedType("HashKey",BindingFlags.Static | BindingFlags.NonPublic);
			wRefInHashKey = HashKeyClass.GetField("wRef", BindingFlags.Instance | BindingFlags.NonPublic);
			AddInBindingContext = _tBindingContext.GetMethod("Add", BindingFlags.Instance | BindingFlags.NonPublic);

		}
		static readonly FieldInfo wRefInHashKey;
		static readonly MethodInfo AddInBindingContext;

		public ITypeContainer CreateNewContainer(object ContainedObject)
		{
			var c = new BindingContextContainer();
			c.Data = new Dictionary<object, BindingManagerBase>();
			foreach (var o in ContainedObject as BindingContext)
			{
				DictionaryEntry item = (DictionaryEntry)o;
				c.Data.Add(
					((WeakReference) wRefInHashKey.GetValue(item.Key)).Target,
					((WeakReference)item.Value).Target as BindingManagerBase);
			}
			return c;
		}

		public object Deserialize()
		{
			var bc = new BindingContext();
			foreach (var item in this.Data)
			{				
				AddInBindingContext.Invoke(bc, new object[2] { item.Key, item.Value });
			}
			return bc;
		}

		public bool IsValidType(Type type)
		{
			return Tools.TypeIs(type, _tBindingContext);
		}
		static readonly Type _tBindingContext = typeof(BindingContext);

		public bool ApplyEvenIfThereIsANoParamConstructor
		{
			get { return true; }
		}

		public bool ApplyToStructures
		{
			get { return false; }
		}

		public bool ApplyEvenIfThereIsAValidConstructor
		{
			get { return true; }
		}
	}

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under Microsoft Reciprocal License


Written By
Software Developer (Senior) independent
France France
Hi !

I made my first program on a Sinclair ZX-81.
Since that day, I have the virus of computers. Smile | :)

Here is my website:
https://chrisbertrand.net

And my blog:
https://chrisbertrandprogramer.wordpress.com/

Comments and Discussions