Click here to Skip to main content
12,508,112 members (43,196 online)
Click here to Skip to main content
Articles » Languages » C# » General » Downloads

Tagged as

Stats

12.7K views
331 downloads
26 bookmarked
Posted

Lazy Alternatives - LazyAndWeak and BackgroundLoader

, 1 Dec 2011 CPOL
This article will present two alternatives to Lazy.
LazyAlternatives
LazyAlternatives.suo
LazyAlternativesSample
Properties
Pfz
Caching
Collections
DataTypes
DynamicObjects
Internal
Extensions
Factoring
Pfz.csproj.user
Pfz.Phone.csproj.user
Pfz.ruleset
Pfz.Silverlight.csproj.user
Pfz.snk
Pfz.suo
PhoneSpecific
Properties
Remoting
Instructions
Internal
Serializers
Udp
Serialization
BinaryBuiltIn
Threading
Contexts
Disposers
Unsafe
using System;
using System.Reflection;
using System.Runtime.Serialization;
using Pfz.Extensions;
using Pfz.Remoting.Serializers;
using Pfz.Serialization.BinaryBuiltIn;

namespace Pfz.Serialization
{
	/// <summary>
	/// An already configured binary serializer.
	/// It is capable of fast serialization for registered types and conventional (reflection based)
	/// serialization for non-registered but [Serializable] classes.
	/// </summary>
	public class BinarySerializer:
		ConfigurableSerializerBase
	{
		/// <summary>
		/// Creates and configures a new BinarySerializer.
		/// </summary>
		public BinarySerializer()
		{
			Register(DBNullSerializer.Instance);

			Register(AssemblySerializer.Instance);
			Register(BooleanSerializer.Instance);
			Register(ByteSerializer.Instance);
			Register(DateTimeSerializer.Instance);
			Register(new DoubleSerializer());
			Register(Int32Serializer.Instance);
			Register(Int64Serializer.Instance);
			Register(StringSerializer.Instance);
			Register(TypeSerializer.Instance);

			Register(ArraySerializer<Assembly>.Instance);
			Register(BooleanArraySerializer.Instance);
			Register(ByteArraySerializer.Instance);
			Register(ArraySerializer<DateTime>.Instance);
			Register(ArraySerializer<Double>.Instance);
			Register(ArraySerializer<int>.Instance);
			Register(ArraySerializer<long>.Instance);
			Register(ArraySerializer<string>.Instance);
			Register(ArraySerializer<Type>.Instance);
		}

		/// <summary>
		/// Adds a new type that should be supported using a fast (and compressed) approach, but still using
		/// reflection based serialization.
		/// </summary>
		public void AddDefaultType(Type type)
		{
			if (type == null)
				throw new ArgumentNullException("type");

			if (CanSerialize(type))
				return;

			if (type.IsArray)
			{
				var serializer = ArraySerializer.GetForElementType(type.GetElementType());
				Register(serializer);

				AddDefaultType(type.GetElementType());
			}
			else
			{
				var serializer = GetItemSerializerForUnregisteredType(type, null);
				if (serializer == null)
					throw new ArgumentException("Can't discover which serializer to use for " + type.FullName);

				Register(serializer);

				foreach(var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
					AddDefaultType(field.FieldType);
			}
		}

		/// <summary>
		/// Serializes null as byte 0.
		/// </summary>
		protected sealed override void OnSerializeNull()
		{
			Stream.WriteByte(0);
		}

		/// <summary>
		/// Serializes a reference by writing the byte 1 and then the id as a compressed int.
		/// </summary>
		/// <param name="id"></param>
		protected sealed override void OnSerializeReference(int id)
		{
			Stream.WriteByte(1);
			Stream.WriteCompressedInt32(id);
		}

		/// <summary>
		/// Gets a serializer for a non-registered item. [Serializable] items or remoting items.
		/// </summary>
		protected override IItemSerializer GetItemSerializerForUnregisteredType(Type type, Type deserializerWillExpectType)
		{
			if (!type.IsSerializable && !type.IsArray)
				return null;

			if (Stream != null)
			{
				if (type != deserializerWillExpectType || !type.IsValueType)
				{
					Stream.WriteByte(2);
					TypeSerializer.Instance.Serialize(this, type);
				}
			}

			if (type.IsArray)
			{
				var serializer = ArraySerializer.GetForElementType(type.GetElementType());
				return serializer;
			}

			var result = _GetItemSerializer(type);
			return result;
		}

		/// <summary>
		/// Serializes a type by its id.
		/// </summary>
		protected sealed override void OnSerializeType(int typeIndex, Type type, Type deserializerWillExpectType)
		{
			if (type.IsValueType && type == deserializerWillExpectType)
				return;

			Stream.WriteCompressedInt32(typeIndex+4);
		}

		/// <summary>
		/// Deserializes an object.
		/// </summary>
		protected override object OnDeserialize(Type expectedType)
		{
			Type effectiveType = null;
			if (expectedType != null && expectedType.IsValueType)
			{
				if (!(expectedType.IsGenericType && expectedType.GetGenericTypeDefinition() == typeof(Nullable<>)))
					effectiveType = expectedType;
			}

			IItemSerializer itemDeserializer = null;
			if (effectiveType == null)
			{
				var stream = Stream;
				int value = stream.ReadCompressedInt32();

				switch(value)
				{
					case 0:
						return null;

					case 1:
					{
						int referenceId = stream.ReadCompressedInt32();
						return ResolveReference(referenceId);
					}

					case 2:
					{
						effectiveType = TypeSerializer.Instance.Deserialize(this);
						itemDeserializer = GetItemDeserializerForUnregisteredType(effectiveType, expectedType);
						break;
					}

					case 3:
						effectiveType = typeof(object);
						itemDeserializer = RemotingObjectSerializer.Instance;
						break;

					default:
						effectiveType = GetTypeById(value-4);
						break;
				}
			}

			using(var serializationIdGenerator = CreateIdGenerator(effectiveType))
			{
				if (itemDeserializer == null)
				{
					var itemDeserializerReference = TryGetItemSerializer(effectiveType);
					itemDeserializer = itemDeserializerReference.ItemSerializer;

					if (itemDeserializer == null)
						itemDeserializer = GetItemDeserializerForUnregisteredType(effectiveType, expectedType);
				}

				object result = itemDeserializer.Deserialize(this);
				serializationIdGenerator.Result = result;
				return result;
			}
		}

		/// <summary>
		/// Gets the deserializer for the given type, considering it is not a registered one.
		/// </summary>
		protected virtual IItemSerializer GetItemDeserializerForUnregisteredType(Type type, Type expectedType)
		{
			if (type.IsArray)
			{
				var deserializer = ArraySerializer.GetForElementType(type.GetElementType());
				return deserializer;
			}

			if (!type.IsSerializable)
				throw new SerializationException("There is not a registered type for " + type.FullName + " and it is not [Serializable].");

			return _GetItemSerializer(type);
		}

		private static IItemSerializer _GetItemSerializer(Type type)
		{
			if (typeof(ISerializable).IsAssignableFrom(type))
				type = typeof(SerializableInterfaceSerializer<>).MakeGenericType(type);
			else
				type = typeof(SerializableSerializer<>).MakeGenericType(type);

			var field = type.GetField("Instance");
			var untypedResult = field.GetValue(null);
			var result = (IItemSerializer)untypedResult;
			return result;
		}
	}
}

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 The Code Project Open License (CPOL)

Share

About the Author

Paulo Zemek
Engineer Microsoft Corporation
United States United States
I started to program computers when I was 11 years old, as a hobbyist, programming in AMOS Basic and Blitz Basic for Amiga.
At 12 I had my first try with assembler, but it was too difficult at the time. Then, in the same year, I learned C and, after learning C, I was finally able to learn assembler (for Motorola 680x0).
Not sure, but probably between 12 and 13, I started to learn C++. I always programmed "in an object oriented way", but using function pointers instead of virtual methods.

At 15 I started to learn Pascal at school and to use Delphi. At 16 I started my first internship (using Delphi). At 18 I started to work professionally using C++ and since then I've developed my programming skills as a professional developer in C++ and C#, generally creating libraries that help other developers do their work easier, faster and with less errors.

Now I just started working as a Senior Software Engineer at Microsoft.

Want more info or simply want to contact me?
Take a look at: http://paulozemek.azurewebsites.net/
Or e-mail me at: paulozemek@outlook.com

Codeproject MVP 2012, 2015 & 2016
Microsoft MVP 2013-2014 (now I work at Microsoft so I can't be a Microsoft MVP anymore)

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160927.1 | Last Updated 1 Dec 2011
Article Copyright 2011 by Paulo Zemek
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid