Click here to Skip to main content
Click here to Skip to main content
Articles » Languages » C# » General » Downloads
 
Add your own
alternative version

Tagged as

Lazy Alternatives - LazyAndWeak and BackgroundLoader

, 1 Dec 2011 CPOL
This article will present two alternatives to Lazy.
LazyAlternatives.zip
LazyAlternatives
LazyAlternatives.suo
LazyAlternativesSample
Properties
Settings.settings
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.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Pfz.DataTypes;
using Pfz.Extensions;

namespace Pfz.Threading.Contexts
{
	/// <summary>
	/// Use this class if you want to "pack" many database errors at once, or
	/// use it's statics methods to add, get or clear errors.
	/// </summary>
	public sealed class ThreadErrors:
		IDisposable
	{
		[ThreadStatic]
		private static object _threadRecord;
	
		[ThreadStatic]
		private static Dictionary<object, HashSet<object>> _errors;

		[ThreadStatic]
		private static HashSet<object> _errorsHashSet;
		
		[ThreadStatic]
		private static ThreadErrors _owner;
		
		private object _oldRecord;
		
	
		/// <summary>
		/// Creates a new database error "pack".
		/// </summary>
		public ThreadErrors(object record=null)
		{
			if (_owner == null)
			{
				_errors = new Dictionary<object, HashSet<object>>();
				_errorsHashSet = new HashSet<object>();
				_owner = this;
			}
			else
				_oldRecord = _threadRecord;
			
			_threadRecord = record;
		}
		
		/// <summary>
		/// Disposes this object and maybe throws and exception if there
		/// are errors.
		/// </summary>
		public void Dispose()
		{
			_threadRecord = _oldRecord;
			
			if (_owner == this)
			{
				_owner = null;
				var errors = _errors;
				var errorsHashSet = _errorsHashSet;
				_errors = null;
				
				if (errorsHashSet.Count > 0 || errors.Count > 0)
					OnThrowingException(errorsHashSet, errors);
			}
		}
		
		/// <summary>
		/// Gets a value indicating if there are errors packed.
		/// </summary>
		public static bool HasErrors
		{
			get
			{
				return _errors != null && (_errors.Count > 0 || _errorsHashSet.Count > 0);
			}
		}
		
		/// <summary>
		/// Gets the errors that are not specific to a data-context.
		/// </summary>
		/// <returns></returns>
		public static HashSet<object> GetGlobalErrors()
		{
			return _errorsHashSet;
		}

		/// <summary>
		/// Gets the dictionary with the errors.
		/// </summary>
		public static Dictionary<object, HashSet<object>> GetErrorsDictionary()
		{
			return _errors;
		}
		
		/// <summary>
		/// Clear all the errors.
		/// </summary>
		public static void ClearErrors()
		{
			if (_errors != null)
			{
				_errors = new Dictionary<object, HashSet<object>>();
				_errorsHashSet = new HashSet<object>();
			}
		}
		
		/// <summary>
		/// Adds an error to the packet, or throws an exception immediatelly.
		/// In general errors are string, but you can add any object if you
		/// know how to use it later.
		/// </summary>
		public static void AddError(object error)
		{
			if (error == null)
				throw new ArgumentNullException("error");
		
			HashSet<object> hashset;
			if (_errors == null)
			{
				hashset = new HashSet<object>();
				hashset.Add(error);

				var dictionary = new Dictionary<object, HashSet<object>>();
				OnThrowingException(hashset, dictionary);
			}
			
			if (_threadRecord == null)
			{
				_errorsHashSet.Add(error);
				return;
			}

			if (!_errors.TryGetValue(_threadRecord, out hashset))
			{
				hashset = new HashSet<object>();
				_errors.Add(_threadRecord, hashset);
			}
			
			hashset.Add(error);
		}
		/// <summary>
		/// Adds a PropertyError object to the error list.
		/// </summary>
		public static void AddError(PropertyInfo propertyInfo, object error)
		{
			AddError(new PropertyError(propertyInfo, error));
		}
		
		/// <summary>
		/// Adds a PropertyError object to the error list.
		/// Uses an expression to know what propertyInfo to use.
		/// </summary>
		public static void AddError<T>(Expression<Func<T>> getPropertyExpression, object error)
		{
			var propertyInfo = ReflectionHelper.GetProperty(getPropertyExpression);
			AddError(propertyInfo, error);
		}

		/// <summary>
		/// Gets a single string with all errors.
		/// </summary>
		public static string GetSimpleAllErrorsMessage()
		{
			if (_errors == null || (_errors.Count == 0 && _errorsHashSet.Count == 0))
				return null;
			
			return _GetSimpleAllErrorsMessage(_errors);
		}

		internal static string _GetSimpleAllErrorsMessage(Dictionary<object, HashSet<object>> dictionary)
		{
			StringBuilder result = new StringBuilder();

			foreach(var error in _errorsHashSet)
			{
				result.Append(error);
				result.Append("\r\n");
			}
			
			foreach(var list in dictionary.Values)
			{
				foreach(var error in list)
				{
					result.Append(error);
					result.Append("\r\n");
				}
			}
					
			return result.ToString();
		}

		/// <summary>
		/// Event invoked when an exception is about to be thrown.
		/// </summary>
		public static event Action<ThrowingExceptionEventArgs> ThrowingException;

		private static void OnThrowingException(HashSet<object> globalErrors, Dictionary<object, HashSet<object>> errorsDictionary)
		{
			var throwing = ThrowingException;
			if (throwing == null)
				throw new ValidationException(globalErrors, errorsDictionary);

			var args = new ThrowingExceptionEventArgs();
			args.ErrorsDictionary = errorsDictionary;
			args.GlobalErrors = globalErrors;
			throwing(args);

			if (!args.WasHandled)
				throw new ValidationException(globalErrors, errorsDictionary);
		}
	}
}

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 hobbist, 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 they 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
Microsoft MVP 2013-2014

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