Click here to Skip to main content
15,888,527 members
Articles / Desktop Programming / WPF

Calcium: A Modular Application Toolset Leveraging PRISM – Part 2

Rate me:
Please Sign up or sign in to vote.
5.00/5 (48 votes)
23 Nov 2009BSD12 min read 116.6K   3   90  
Calcium provides much of what one needs to rapidly build a multifaceted and sophisticated modular application. Includes a host of modules and services, and an infrastructure that is ready to use in your next application.
#region File and License Information
/*
<File>
	<Copyright>Copyright © 2007, Daniel Vaughan. All rights reserved.</Copyright>
	<License see="prj:///Documentation/License.txt"/>
	<Owner Name="Daniel Vaughan" Email="dbvaughan@gmail.com"/>
	<CreationDate>2009-03-12 12:01:40Z</CreationDate>
	<LastSubmissionDate>$Date: $</LastSubmissionDate>
	<Version>$Revision: $</Version>
</File>
*/
#endregion

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Xml;

namespace DanielVaughan.Logging.Configuration
{
	public class LogRepository
	{
		#region Singleton implementation

		LogRepository()
		{
		}

		public static LogRepository Instance
		{
			get
			{
				return Nested.instance;
			}
		}

		class Nested
		{
			// Explicit static constructor to tell C# compiler
			// not to mark type as beforefieldinit
			static Nested()
			{
			}

			internal static readonly LogRepository instance = new LogRepository();
		}

		#endregion
 
		readonly Dictionary<ILogStrategy, List<IFilter>> logStrategies = new Dictionary<ILogStrategy, List<IFilter>>();
		readonly Dictionary<string, ILogStrategy> logStrategyNames = new Dictionary<string, ILogStrategy>();
		string configurationErrorPrefix = "Configuration Error: "; /* TODO: Make localizable resource. */
		
		public IEnumerable<ILogStrategy> LogStrategies
		{
			get
			{
				return logStrategies.Keys;
			}
		}

		public IEnumerable<IFilter> GetFilters(ILogStrategy logStrategy)
		{
			ArgumentValidator.AssertNotNull(logStrategy, "logStrategy");
			return logStrategies[logStrategy];
		}

		internal void Load(XmlElement rootElement)
		{
			ArgumentValidator.AssertNotNull(rootElement, "rootElement");

			StringBuilder errorBuilder = new StringBuilder();

			/* GetElementsByTagName ignores namespace, where as SelectNodes doesn't. */
			var logStrategiesElements = rootElement.GetElementsByTagName("LogStrategy");
			bool strategyExists = false;
			foreach (XmlElement logStrategyElement in logStrategiesElements)
			{
				strategyExists = true;
				var strategyNameAttribute = logStrategyElement.Attributes["Name"];
				if (strategyNameAttribute == null)
				{
					/* TODO: Make localizable resource. */
					WriteConfigurationError(errorBuilder, "Name attribute does not exist for strategy. Element: " 
						+ logStrategyElement, null);
					continue;
				}

				var strategyTypeElement = logStrategyElement.Attributes["Type"];
				if (strategyTypeElement == null)
				{
					/* TODO: Make localizable resource. */
					WriteConfigurationError(errorBuilder, "Type name attribute does not exist. Element: " 
						+ logStrategyElement, null);
					continue;
				}

				ILogStrategy logStrategy;
				try
				{
					Type type = Type.GetType(strategyTypeElement.Value);
					logStrategy = (ILogStrategy)Activator.CreateInstance(type);
				}
				catch (Exception ex)
				{
					/* TODO: Make localizable resource. */
					WriteConfigurationError(errorBuilder, "LogStrategy is missing or of wrong type. Name: " 
						+ strategyNameAttribute, ex);
					continue;
				}

				var filters = new List<IFilter>();
				logStrategies.Add(logStrategy, filters);
				logStrategyNames.Add(strategyNameAttribute.Value, logStrategy);

				InternalLog.Info(string.Format("Added log strategy to repository. Name: {0}, Type: {1}", /* TODO: Make localizable resource. */
					strategyNameAttribute.Value, strategyTypeElement.Value));

				var filterElements = logStrategyElement.GetElementsByTagName("Filter");
				foreach (XmlElement filterElement in filterElements)
				{
					var filterNameAttribute = filterElement.Attributes["Name"];
					if (filterNameAttribute == null)
					{
						errorBuilder.Append(configurationErrorPrefix);
						string errorMessage = "Name attribute does not exist for filter. Name: " + strategyNameAttribute; /* TODO: Make localizable resource. */
						InternalLog.Error(errorMessage);
						errorBuilder.Append(errorMessage);
						continue;
					}

					var filterTypeAttribute = filterElement.Attributes["Type"];
					if (filterTypeAttribute == null)
					{
						/* TODO: Make localizable resource. */
						WriteConfigurationError(errorBuilder, string.Format("Type name for filter attribute does not exist. Strategy name: {0}, Filter name: {1}", 
							strategyNameAttribute, filterNameAttribute), null);
						continue;
					}

					IFilter filter;
					Type filterType;
					try
					{
						filterType = Type.GetType(filterTypeAttribute.Value);
						filter = (IFilter)Activator.CreateInstance(filterType);
					}
					catch (Exception ex)
					{
						/* TODO: Make localizable resource. */
						WriteConfigurationError(errorBuilder, string.Format("Filter is missing or of wrong type. Strategy name: {0}, Filter name: {1}",
							strategyNameAttribute, filterNameAttribute), ex);
						continue;
					}

					if (filter != null)
					{
						try
						{
							filter.Load(filterElement);
						}
						catch (Exception ex)
						{
							/* TODO: Make localizable resource. */
							WriteConfigurationError(errorBuilder, string.Format("Filter could not be loaded. Strategy name: {0}, Filter name: {1}, Filter type: {2}",
								strategyNameAttribute, filterNameAttribute, filterType), ex);
							continue;
						}
						
						filters.Add(filter);

						InternalLog.Info(string.Format("Added filter for strategy '{0}'. Name: {1}, Type: {2}", /* TODO: Make localizable resource. */
							strategyNameAttribute.Value, filterNameAttribute.Value, filterType));
					}
				}
			}

			if (!strategyExists)
			{
				InternalLog.Warn("No log strategies found in Clog config element.");
			}

			string errors = errorBuilder.ToString();
			if (errors.Length > 0)
			{
				throw new ClientLoggingException(errors);
			}
		}

		void WriteConfigurationError(StringBuilder errorBuilder, string message, Exception exception)
		{
			errorBuilder.Append(configurationErrorPrefix);
			InternalLog.Error(message, exception);
			errorBuilder.Append(message + "Exception: " +  exception);
		}
	}
}

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 BSD License


Written By
Engineer
Switzerland Switzerland
Daniel is a former senior engineer in Technology and Research at the Office of the CTO at Microsoft, working on next generation systems.

Previously Daniel was a nine-time Microsoft MVP and co-founder of Outcoder, a Swiss software and consulting company.

Daniel is the author of Windows Phone 8 Unleashed and Windows Phone 7.5 Unleashed, both published by SAMS.

Daniel is the developer behind several acclaimed mobile apps including Surfy Browser for Android and Windows Phone. Daniel is the creator of a number of popular open-source projects, most notably Codon.

Would you like Daniel to bring value to your organisation? Please contact

Blog | Twitter


Xamarin Experts
Windows 10 Experts

Comments and Discussions