Reading assembly attributes at runtime using Reflection in .NET

A lot of metadata of an assembly is stored by way of attributes in the AssemblyInfo.cs file. E.g. if you create a simple Console application then this file will be readily available in the Properties folder. Assembly-related attributes are denoted by an “assembly:” prefix and can carry a lot of customisable information. Examples:

[assembly: AssemblyTitle("ReflectionCodeBits")]
[assembly: AssemblyDescription("This is a container for Reflection related code examples")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Great Company Ltd.")]
[assembly: AssemblyProduct("ReflectionCodeBits")]
[assembly: AssemblyCopyright("Copyright ©  2014")]
[assembly: AssemblyTrademark("GC")]
[assembly: AssemblyCulture("sv-SE")]
[assembly: ComVisible(false)]
[assembly: Guid("8376337d-c211-4507-bc0d-bcd39bc9fb4f")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Most of these are self-explanatory but others deserve more attention:

  • AssemblyConfiguration: to specify which configuration is used for the assembly. You can specify this value like “DEBUG”, “RELEASE” or some custom configuration name, like “ALPHA”
  • AssemblyCulture: normally only used for satellite assemblies, otherwise an empty string denoting neutral culture – in fact you specify an assembly culture like I have done above you’ll get a compile error saying that executables cannot be satellite assemblies; culture should always be empty.

You can read the full documentation about assembly attributes here.

In order to extract the assembly attributes you’ll first need to get a reference to that assembly. You can then list all attributes of the assembly as follows:

Assembly executingAssembly = Assembly.GetExecutingAssembly();
IEnumerable<CustomAttributeData> assemblyAttributes = executingAssembly.CustomAttributes;
foreach (CustomAttributeData assemblyAttribute in assemblyAttributes)
{
	Type attributeType = assemblyAttribute.AttributeType;
	Console.WriteLine("Attribute type: {0}", attributeType);
	IList<CustomAttributeTypedArgument> arguments = assemblyAttribute.ConstructorArguments;
	Console.WriteLine("Attribute arguments: ");
	foreach (CustomAttributeTypedArgument arg in arguments)
	{
		Console.WriteLine(arg.Value);
	}
}

In my case I got the following output:

Assembly attributes output

You can also extract a specific attribute type as follows:

AssemblyDescriptionAttribute assemblyDescriptionAttribute =     executingAssembly.GetCustomAttribute<AssemblyDescriptionAttribute>();
string assemblyDescription = assemblyDescriptionAttribute.Description;

…which returns “This is a container for Reflection related code examples” as expected.

View all posts on Reflection here.

Externalising dependencies with Dependency Injection in .NET part 7: emailing

Introduction

In the previous post of this series we looked at how to hide the implementation of file system operations. In this post we’ll look at abstracting away emailing. Emails are often sent out in professional applications to users in specific scenarios: a new user signs up, the user places an order, the order is dispatched etc.

If you don’t know who to send emails using .NET then check the out mini-series on this page.

The first couple of posts of this series went through the process of making hard dependencies to loosely coupled ones. I won’t go through that again – you can refer back to the previous parts of this series to get an idea. You’ll find a link below to view all posts of the series. Another post on the Single Responsibility Principle includes another example of breaking out an INotificationService that you can look at.

We’ll extend the Infrastructure layer of our demo app we’ve been working on so far. So have it ready in Visual Studio and let’s get to it.

The interface

As usual we’ll need an abstraction to hide the concrete emailing logic. Emailing has potentially a considerable amount of parameters: from, to, subject, body, attachments, HTML contents, embedded resources, SMTP server and possibly many more. So the interface method(s) should accommodate all these variables somehow. One approach is to create overloads of the same method, like…

void Send(string to, string from, string subject, string body, string smtpServer);
void Send(string to, string from, string subject, string body, string smtpServer, bool isHtml);
void Send(string to, string from, string subject, string body, string smtpServer, bool isHtml, List<string> attachments);
.
.
.

…and so on including all combinations, e.g. a method with and without “isHtml”. I think this is not an optimal and future-proof interface. It is probably better to give room to all those arguments in an object and use that object as the parameter to a single method in the interface.

Also, we need to read the response of the operation. Add a new folder call Email to the Infrastructure.Common library. Insert the following object into the folder:

public class EmailSendingResult
{
	public bool EmailSentSuccessfully { get; set; }
	public string EmailSendingFailureMessage { get; set; }
}

The parameters for sending the email will be contained by an object called EmailArguments:

public class EmailArguments
{
	private string _subject;
	private string _message;
	private string _to;
	private string _from;
	private string _smtpServer;
	private bool _html;
		
	public EmailArguments(string subject, string message, string to, string from, string smtpServer, bool html)
	{
		if (string.IsNullOrEmpty(subject))
			throw new ArgumentNullException("Email subject");
		if (string.IsNullOrEmpty(message))
			throw new ArgumentNullException("Email message");
		if (string.IsNullOrEmpty(to))
			throw new ArgumentNullException("Email recipient");
		if (string.IsNullOrEmpty(from))
			throw new ArgumentNullException("Email sender");
		if (string.IsNullOrEmpty(smtpServer))
			throw new ArgumentNullException("Smtp server");
		this._from = from;
		this._message = message;
		this._smtpServer = smtpServer;
		this._subject = subject;
		this._to = to;
		this._html = html;
	}

	public List EmbeddedResources { get; set; }

	public string To
	{
		get
		{
			return this._to;
		}
	}

	public string From
	{
		get
		{
			return this._from;
		}
	}

	public string Subject
	{
		get
		{
			return this._subject;
		}
	}

	public string SmtpServer
	{
		get
		{
			return this._smtpServer;
		}
	}

	public string Message
	{
		get
		{
			return this._message;
		}
	}

	public bool Html
	{
		get
		{
			return this._html;
		}
	}
}

…where EmbeddedEmailResource is a new object, we’ll show it in a second.

So 6 parameters are made compulsory: to, from, subject, smtpServer, message body and whether the message is HTML. We can probably make this list shorter by excluding the subject and isHtml parameters but it’s a good start.

Embedded email resources come in many different forms. Insert the following enum in the Email folder:

public enum EmbeddedEmailResourceType
{
	Jpg
	, Gif
	, Tiff
	, Html
	, Plain
	, RichText
	, Xml
	, OctetStream
	, Pdf
	, Rtf
	, Soap
	, Zip
}

Embedded resources will be represented by the EmbeddedEmailResource object:

public class EmbeddedEmailResource
{
	public EmbeddedEmailResource(Stream resourceStream, EmbeddedEmailResourceType resourceType
		, string embeddedResourceContentId)
	{
		if (resourceStream == null) throw new ArgumentNullException("Resource stream");
		if (String.IsNullOrEmpty(embeddedResourceContentId)) throw new ArgumentNullException("Resource content id");
		ResourceStream = resourceStream;
		ResourceType = resourceType;
		EmbeddedResourceContentId = embeddedResourceContentId;
	}

	public Stream ResourceStream { get; set; }
	public EmbeddedEmailResourceType ResourceType { get; set; }
	public string EmbeddedResourceContentId { get; set; }
}

If you’re familiar with how to add embedded resources to an email then you’ll know why we need a Stream and a content id.

The solution should compile at this stage.

We’re now ready for the great finale, i.e. the IEmailService interface:

public interface IEmailService
{
	EmailSendingResult SendEmail(EmailArguments emailArguments);
}

Both the return type and the single parameter are custom objects that can be extended without breaking the code for any existing callers. You can add new public getters and setters to EmailArguments instead of creating the 100th different version of SendEmail in the version with primitive parameters.

Implementation

We’ll of course use the default emailing techniques built into .NET to implement IEmailService. Add a new class called SystemNetEmailService to the Email folder:

public EmailSendingResult SendEmail(EmailArguments emailArguments)
{
	EmailSendingResult sendResult = new EmailSendingResult();
	sendResult.EmailSendingFailureMessage = string.Empty;
	try
	{
		MailMessage mailMessage = new MailMessage(emailArguments.From, emailArguments.To);
		mailMessage.Subject = emailArguments.Subject;
		mailMessage.Body = emailArguments.Message;
		mailMessage.IsBodyHtml = emailArguments.Html;
		SmtpClient client = new SmtpClient(emailArguments.SmtpServer);

		if (emailArguments.EmbeddedResources != null && emailArguments.EmbeddedResources.Count > 0)
		{
			AlternateView avHtml = AlternateView.CreateAlternateViewFromString(emailArguments.Message, Encoding.UTF8, MediaTypeNames.Text.Html);
			foreach (EmbeddedEmailResource resource in emailArguments.EmbeddedResources)
			{
				LinkedResource linkedResource = new LinkedResource(resource.ResourceStream, resource.ResourceType.ToSystemNetResourceType());
				linkedResource.ContentId = resource.EmbeddedResourceContentId;
				avHtml.LinkedResources.Add(linkedResource);
			}
			mailMessage.AlternateViews.Add(avHtml);
		}

		client.Send(mailMessage);
		sendResult.EmailSentSuccessfully = true;
	}
	catch (Exception ex)
	{
		sendResult.EmailSendingFailureMessage = ex.Message;
	}

	return sendResult;
}

The code won’t compile due to the extension method ToSystemNetResourceType(). The LinkedResource object cannot work with our EmbeddedEmailResourceType type directly. It needs a string instead like “text/plain” or “application/soap+xml”. Those values are in turn stored within the MediaTypeNames object.

Add the following static class to the Email folder:

public static class EmailExtensions
{
	public static string ToSystemNetResourceType(this EmbeddedEmailResourceType resourceTypeEnum)
	{
		string type = MediaTypeNames.Text.Plain;
		switch (resourceTypeEnum)
		{
			case EmbeddedEmailResourceType.Gif:
				type = MediaTypeNames.Image.Gif;
				break;
			case EmbeddedEmailResourceType.Jpg:
				type = MediaTypeNames.Image.Jpeg;
				break;
			case EmbeddedEmailResourceType.Html:
				type = MediaTypeNames.Text.Html;
				break;
			case EmbeddedEmailResourceType.OctetStream:
				type = MediaTypeNames.Application.Octet;
				break;
			case EmbeddedEmailResourceType.Pdf:
				type = MediaTypeNames.Application.Pdf;
				break;
			case EmbeddedEmailResourceType.Plain:
				type = MediaTypeNames.Text.Plain;
				break;
			case EmbeddedEmailResourceType.RichText:
				type = MediaTypeNames.Text.RichText;
				break;
			case EmbeddedEmailResourceType.Rtf:
				type = MediaTypeNames.Application.Rtf;
				break;
			case EmbeddedEmailResourceType.Soap:
				type = MediaTypeNames.Application.Soap;
				break;
			case EmbeddedEmailResourceType.Tiff:
				type = MediaTypeNames.Image.Tiff;
				break;
			case EmbeddedEmailResourceType.Xml:
				type = MediaTypeNames.Text.Xml;
				break;
			case EmbeddedEmailResourceType.Zip:
				type = MediaTypeNames.Application.Zip;
				break;
		}

		return type;
	}
}

This is a simple converter extension to transform our custom enumeration to media type strings.

There you are, this is a good starting point to cover the email purposes in your project.

In the next part of this series we’ll look at hiding the cryptography logic or our application.

View the list of posts on Architecture and Patterns here.

Examining the Modules in an Assembly using Reflection in .NET

A Module is a container for type information. If you’d like to inspect the Modules available in an assembly, you’ll first need to get a reference to the assembly in question. Once you have the reference to the assembly you can get hold of the modules as follows:

Assembly callingAssembly = Assembly.GetCallingAssembly();
Module[] modulesInCallingAssembly = callingAssembly.GetModules();

You can then iterate through the module array and read its properties:

foreach (Module module in modulesInCallingAssembly)
{
	Console.WriteLine(module.FullyQualifiedName);
	Console.WriteLine(module.Name);
}

In my case, as this is a very simple Console app I got the following output:

C:\Studies\Reflection\ReflectionCodeBits\ReflectionCodeBits\bin\Debug\ReflectionCodeBits.exe
ReflectionCodeBits.exe

Therefore the FullyQualifiedName property returns the full file path to the module. The Name property only returns the name without the file path.

The Module class has a couple of exciting methods to extract the fields and methods attached to it:

MethodInfo[] methods = module.GetMethods();
FieldInfo[] fields = module.GetFields();

We’ll take up FieldInfo and MethodInfo in later blog posts on Reflection to see what we can do with them.

View all posts on Reflection here.

Externalising dependencies with Dependency Injection in .NET part 6: file system

Introduction

In the previous post we looked at logging with log4net and saw how easy it was to switch from one logging strategy to another. By now you probably understand why it can be advantageous to remove hard dependencies from your classes: flexibility, testability, SOLID and more.

The steps to factor out your hard dependencies to abstractions usually involve the following steps:

  • Identify the hard dependencies: can the class be tested in isolation? Does the test result depend on an external object such as a web service? Can the implementation of the dependency change?
  • Identify the tasks any reasonable implementation of the dependency should be able to perform: what should a caching system do? What should any decent logging framework be able to do?
  • Build an abstraction – usually an interface – to represent those expected functions: this is so that the interface becomes as future-proof as possible. As noted before this is easier said than done as you don’t know in advance what a future implementation might need. You might need to revisit your interface and add an extra method or an extra parameter. This can be alleviated if you work with objects as parameters to the interface functions, e.g. LoggingArguments, CachingArguments – you’ll see what I mean in the next post where we’ll take up emailing
  • Inject the abstraction into the class that depends on it through one of the Dependency Injection patterns where constructor injection should be your default choice if you’re uncertain
  • The calling class will then inject a concrete implementation for the interface – alternatively you can use of the Inversion-of-control tools, like StructureMap

In this and the remaining posts of this series we won’t be dealing with the Console app in the demo anymore. The purpose of the console app was to show the goal of abstractions and dependency injection through examples. We’ve seen enough of that so we can instead concentrate on building the infrastructure layer. So open the demo solution in VS let’s add file system operations to Infrastructure.Common.

File system

.NET has an excellent built-in library for anything you’d like to do with files and directories. In the previous post on log4net we saw an example of checking if a file exists like this:

FileInfo log4netSettingsFileInfo = new FileInfo(_contextService.GetContextualFullFilePath(_log4netConfigFileName));
if (!log4netSettingsFileInfo.Exists)
{
	throw new ApplicationException(string.Concat("Log4net settings file ", _log4netConfigFileName, " not found."));
}

You can have File.WriteAllText, File.ReadAllBytes, File.Copy etc. directly in your code and you may not think that it’s a real dependency. It’s admittedly very unlikely that you don’t want to use the built-in features of .NET for file system operations and instead take some other library. So the argument of “flexibility” might not play a big role here.

However, unit testing with TDD shows that you shouldn’t make the outcome of your test depend on external elements, such as the existence of a file if the method being tested wants in fact to perform some operation on a physical file. Instead, you should be able to declare the outcome of those operations through TDD tools such as Moq which is discussed in the TDD series referred to in the previous sentence. If you see that you must create a specific file before a test is run and delete it afterwards then it’s a brittle unit test. Most real-life business applications are auto-tested by test runners in continuous integration (CI) systems such as TeamCity or Jenkins. In that case you’ll need to create the same file on the CI server(s) as well so that the unit test passes.

Therefore it still makes sense to factor out the file related stuff from your consuming classes.

The abstraction

File system operations have many facets: reading, writing, updating, deleting, copying, creating files and much more. Therefore a single file system interface is going to be relatively large. Alternatively you can break out the functions to separate interfaces such as IFileReaderService, IFileWriterService, IFileInformationService etc. You can also have a separate interface for directory-specific operations such as creating a new folder or reading the drive name.

Here we’ll start with out easy. Add a new folder called FileOperations to the Infrastructure.Common C# library. Insert an interface called IFileService:

public interface IFileService
{		
	bool FileExists(string fileFullPath);		
	long LastModifiedDateUnix(string fileFullPath);		
	string RetrieveContentsAsBase64String(string fileFullPath);		
	byte[] ReadContentsOfFile(string fileFullPath);		
	string GetFileName(string fullFilePath);		
	bool SaveFileContents(string fileFullPath, byte[] contents);		
	bool SaveFileContents(string fileFullPath, string base64Contents);			
	string GetFileExtension(string fileName);		
	bool DeleteFile(string fileFullPath);
}

That should be enough for starters.

The implementation

We’ll of course use the standard capabilities in .NET to implement the file operations. Add a new class called DefaultFileService to the FileOperations folder:

public class DefaultFileService : IFileService
{
	public bool FileExists(string fileFullPath)
	{
		FileInfo fileInfo = new FileInfo(fileFullPath);
		return fileInfo.Exists;
	}

	public long LastModifiedDateUnix(string fileFullPath)
	{
		FileInfo fileInfo = new FileInfo(fileFullPath);
		if (fileInfo.Exists)
		{
			DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0);
			TimeSpan timeSpan = fileInfo.LastWriteTimeUtc - epoch;
			return Convert.ToInt64(timeSpan.TotalMilliseconds);
		}

		return -1;
	}

	public string RetrieveContentsAsBase64String(string fileFullPath)
	{
		byte[] contents = ReadContentsOfFile(fileFullPath);
		if (contents != null)
		{
			return Convert.ToBase64String(contents);
		}
		return string.Empty;
	}

	public byte[] ReadContentsOfFile(string fileFullPath)
	{
		FileInfo fi = new FileInfo(fileFullPath);
		if (fi.Exists)
		{
			return File.ReadAllBytes(fileFullPath);
		}

		return null;
	}

	public string GetFileName(string fullFilePath)
	{
		FileInfo fi = new FileInfo(fullFilePath);
		return fi.Name;
	}

	public bool SaveFileContents(string fileFullPath, byte[] contents)
	{
		try
		{
			File.WriteAllBytes(fileFullPath, contents);
			return true;
		}
		catch
		{
			return false;
		}
	}

	public bool SaveFileContents(string fileFullPath, string base64Contents)
	{
		return SaveFileContents(fileFullPath, Convert.FromBase64String(base64Contents));
	}

	public string GetFileExtension(string fileName)
	{
		FileInfo fi = new FileInfo(fileName);
		return fi.Extension;
	}

	public bool DeleteFile(string fileFullPath)
	{
		FileInfo fi = new FileInfo(fileFullPath);
		if (fi.Exists)
		{
			File.Delete(fileFullPath);
		}

		return true;
	}
}

There you have it. Feel free to break out the file system functions to separate interfaces as suggested above.

The next post in this series will take up emailing.

View the list of posts on Architecture and Patterns here.

Examining the Assembly using Reflection in .NET

The CLR code of a project is packaged into an assembly. We can inspect a range of metadata from an assembly that also the CLR uses to load and execute runnable code: classes, methods, interfaces, enumerations etc.

In order to inspect an Assembly in a .NET project we’ll first need to get a reference to the assembly in question. There are various ways to retrieve an assembly, including:

Assembly callingAssembly = Assembly.GetCallingAssembly();
Assembly entryAssembly = Assembly.GetEntryAssembly();
Assembly executingAssembly = Assembly.GetExecutingAssembly();

…where Assembly is located in the System.Reflection namespace.

The static methods above represent the following:

  • GetCallingAssembly: to get the assembly one level up the call stack, i.e. which contains the method the current executing code
  • GetEntryAssembly: to get the assembly which contains the entry point to the application, e.g. the Main method in a Console app
  • GetExecutingAssembly: to get the assembly of the currently running code

There’s also a way to load a specific assembly using the GetAssembly(Type type) method. E.g. if you have a Customer class then you can load the assembly that contains the Customer class as follows:

Assembly specificAssembly = Assembly.GetAssembly(typeof(Customer));

Once you have the assembly you can read various metadata from it, examples:

Console.WriteLine("Full name: {0}", callingAssembly.FullName);
Console.WriteLine("Location: {0}", callingAssembly.Location);
Console.WriteLine("Loaded for reflection only? {0}", callingAssembly.ReflectionOnly);
Console.WriteLine("Loaded from GAC? {0}", callingAssembly.GlobalAssemblyCache);
Console.WriteLine(".NET Version: {0}", callingAssembly.ImageRuntimeVersion);

…which in my case outputs the following:

Basic assembly information

You may wonder what “loaded for reflection” means. You can get hold of an assembly in order to inspect its metadata without the possibility to execute any action on it. This is how we can load the assembly containing the “string” class in .NET:

Assembly reflectionOnlyAssembly = Assembly.ReflectionOnlyLoad("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

You can execute an assembly by creating an instance of it using the CreateInstance method. However, if the assembly was only loaded for reflection then CreateInstance will throw an exception. If you know that you only want to read some metadata from an assembly but not execute it then you can use the ReflectionOnlyLoad method to save time loading it fully into the AppDomain.

View all posts on Reflection here.

Finding the user’s supported cultures using the CultureInfo class in .NET C#

The CultureInfo class has a static method to retrieve the supported locales on the user’s machine:

CultureInfo[] supportedCultures = CultureInfo.GetCultures(CultureTypes.AllCultures);

The GetCultures method accepts a CultureTypes enumeration:

  • AllCultures: show all cultures regardless of the type
  • FrameworkCultures: show all specific and neutral cultures that ship with .NET
  • InstalledWin32Cultures: all cultures installed on Windows
  • NeutralCultures: all language-specific, i.e. neutral cultures where the region which determines the specific culture is omitted
  • ReplacementCultures: custom cultures created by the user that replace an existing culture
  • SpecificCultures: the most precise culture type where both the language and regions are denoted
  • UserCustomCulture: custom cultures
  • WindowsOnlyCultures: deprecated, yields an array with 0 elements in .NET 4+

So in case you’d like to find all specific cultures and their names you can write as follows:

CultureInfo[] supportedCultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
List<CultureInfo> ordered = supportedCultures.OrderBy(c => c.Name).ToList();
foreach (CultureInfo ci in ordered)
{
	Console.WriteLine(string.Concat(ci.Name, ": ", ci.EnglishName));
}

However, if you’re only interested in the supported languages then the following will do:

CultureInfo[] supportedCultures = CultureInfo.GetCultures(CultureTypes.NeutralCultures);
List<CultureInfo> ordered = supportedCultures.OrderBy(c => c.Name).ToList();
foreach (CultureInfo ci in ordered)
{
	Console.WriteLine(string.Concat(ci.Name, ": ", ci.EnglishName));
}

Read all posts related to Globalisation in .NET here.

Externalising dependencies with Dependency Injection in .NET part 5: logging with log4net

Introduction

In the previous post we looked at how to hide the concrete implementation of the logging technology behind an abstraction. In fact we reached the original goal of showing how to rid the code of logging logic or at least how to make the code less dependent on it.

In the posts on caching and configuration we also looked at some real implementations of the abstractions that you can readily use in your project. However, with logging we only provided a simple Console based logging which is far from realistic in any non-trivial application. Therefore I’ve decided to extend the discussion on logging with a real powerhouse: log4net by Apache.

Log4net is a well-established, general purpose and widely used logging framework for .NET. You can set it up to send logging messages to multiple targets: console, file, database, a web service etc. In this post we’ll look at how to log to a file using log4net.

In a real-life large web-based application you would likely log to at least 2 sources: a file or a database and another, more advanced tool which helps you search among the messages in an efficient way. An example of such a tool is GrayLog, a web-based application where you can set up your channels and make very quick and efficient searches to track your messages.

The primary source of investigation in case of exception tracking will be this advanced tool. However, as in the case of GrayLog it may be down in which case the log messages are lost. As a backup you can then read the log messages from the log file. As mentioned above, we’ll be looking into file-based logging but if you’re looking for a more professional tool then I can recommend GrayLog.

NB: I’m not going to go through log4net specific details too much so be prepared to do your own search in some areas. A full description and demo of log4net would deserve its own series which is out of bounds in this case. However, the goal is to provide code that you can readily use in your project without much modification.

We’ll build upon the CommonInfrastructureDemo project we’ve been working with so far so have it open in Visual Studio.

Some basics

Let’s go through some preparations first. The log4net library is available through NuGet. Add the following NuGet package to the Infrastructure.Common project:

log4net NuGet

By the time you read this post the version may be higher but hopefully it won’t have any breaking changes.

As mentioned above, log4net can be configured to send the log messages to a variety of sources. Log4net will have one or more so-called appenders that will “append” the message to the defined source. Log4net can be configured in code or via a separate configuration file. The advantage of a configuration file is that you can modify the values on the deploy server without re-deploying the application. There are numerous examples on the internet showing snippets of log4net configurations. A very good starting point is the documentation on the log4net homepage available here.

In our case we’ll go for the RollingFileAppender. If the log file exceeds a certain limit then the oldest messages are erased to make room for the new ones. Add an Application Configuration File file called log4net.config to the root of the Console app, i.e. to the same level as the app.config file. Erase any default content in log4net.config and instead add the following XML content:

<?xml version="1.0"?>
<log4net>
	<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
		<file value="log.xml"/>
		<threshold value="INFO" />
		<appendToFile value="true" />
		<rollingStyle value="Size" />
		<maxSizeRollBackups value="30" />
		<maximumFileSize value="30MB" />
		<staticLogFileName value="true" />
		<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
		<layout type="log4net.Layout.XMLLayout" />
	</appender>

	<root>
		<level value="ALL" />
		<!-- Value of priority may be ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF -->
		<appender-ref ref="RollingFileAppender"/>
	</root>
</log4net>

You can find the full documentation of the rolling file appender here and here. The main thing to note that we want to log to a file called log.xml. In Solution Explorer right-click log4net.config and select Properties. Locate the “Copy to Output Directory” in the Properties window and select “Copy always”. This will put the config file to the bin folder when the application is compiled.

We’ll need to store the name of the log4net config file name in the application configuration file which we added in the post on configuration referred to above. Add the following app setting to app.config:

<add key="Log4NetSettingsFile" value="log4net.config"/>

The log4net implementation of ILoggingService will therefore need an IConfigurationRepository we saw before. It’s good that we have an implementation of IConfigurationRepository that reads from the app.config file so we’ll be able to use it.

However, we need something more. Whenever you’re trying to track down what exactly went wrong in the application based on a series of log messages you’ll need all sorts of contextual information: the user, the session, the user agent, the referrer, the exact version of the browser, the requested URL etc. Add a new folder to Infrastructure.Common called ContextProvider and insert an interface called IContextService into it:

public interface IContextService
{
	string GetContextualFullFilePath(string fileName);
	string GetUserName();
	ContextProperties GetContextProperties();
}

GetContextualFullFilePath will help us find the full path to a physical file after the deployment of the application. In our case we want to be able to find log4net.config. GetUserName is probably self-explanatory. All other context properties will be stored in the ContextProperties object. Add the following class to the ContextProvider folder:

public class ContextProperties
{
	private string _notAvailable = "N/A";

	public ContextProperties()
	{
		UserAgent = _notAvailable;
		RemoteHost = _notAvailable;
		Path = _notAvailable;
		Query = _notAvailable;
		Referrer = _notAvailable;
		RequestId = _notAvailable;
		SessionId = _notAvailable;
	}

	public string UserAgent { get; set; }
	public string RemoteHost { get; set; }
	public string Path { get; set; }
	public string Query { get; set; }
	public string Referrer { get; set; }
	public string RequestId { get; set; }
	public string SessionId { get; set; }
	public string Method { get; set; }
}

In a web-based application with a valid HttpContext object we can have the following implementation. Add the following class to the ContextProvider folder:

public class HttpContextService : IContextService
{
	public HttpContextService()
	{
		if (HttpContext.Current == null)
		{
			throw new ArgumentException("There's no available Http context.");
		}
	}

	public string GetContextualFullFilePath(string fileName)
	{
		return HttpContext.Current.Server.MapPath(string.Concat("~/", fileName));
	}

	public string GetUserName()
	{
		string userName = "<null>";
		try
		{
			if (HttpContext.Current != null && HttpContext.Current.User != null)
			{
				userName = (HttpContext.Current.User.Identity.IsAuthenticated
								? HttpContext.Current.User.Identity.Name
								: "<null>");
			}
		}
		catch
		{
		}
		return userName;
	}

	public ContextProperties GetContextProperties()
	{
		ContextProperties props = new ContextProperties();
		if (HttpContext.Current != null)
		{
			HttpRequest request = null;
			try
			{
				request = HttpContext.Current.Request;
			}
			catch (HttpException)
			{
			}
         		if (request != null)
			{
				props.UserAgent = request.Browser == null ? "" : request.Browser.Browser;
				props.RemoteHost = request.ServerVariables == null ? "" : request.ServerVariables["REMOTE_HOST"];
				props.Path = request.Url == null ? "" : request.Url.AbsolutePath;
				props.Query = request.Url == null ? "" : request.Url.Query;
				props.Referrer = request.UrlReferrer == null ? "" : request.UrlReferrer.ToString();
				props.Method = request.HttpMethod;
			}

			IDictionary items = HttpContext.Current.Items;
			if (items != null)
			{
				var requestId = items["RequestId"];
				if (requestId != null)
				{
					props.RequestId = items["RequestId"].ToString();
				}
			}

			var session = HttpContext.Current.Session;
			if (session != null)
			{
				var sessionId = session["SessionId"];
				if (sessionId != null)
				{
					props.SessionId = session["SessionId"].ToString();
				}
			}
		}

		return props;
	}
}

Most of this code is about extracting various data from the HTTP request/context.

In a non-HTTP based application we’ll go for a simpler implementation. Add a class called ThreadContextService to the ContextProvider folder:

public class ThreadContextService : IContextService
{
	public string GetContextualFullFilePath(string fileName)
	{
		string dir = Directory.GetCurrentDirectory();
		FileInfo resourceFileInfo = new FileInfo(Path.Combine(dir, fileName));
		return resourceFileInfo.FullName;
	}

	public string GetUserName()
	{
		string userName = "<null>";
		try
		{
			if (Thread.CurrentPrincipal != null)
			{
				userName = (Thread.CurrentPrincipal.Identity.IsAuthenticated
								? Thread.CurrentPrincipal.Identity.Name
								: "<null>");
			}
		}
		catch
		{
		}
		return userName;
	}

	public ContextProperties GetContextProperties()
	{
		return new ContextProperties();
	}
}

Now we have all the ingredients for the log4net implementation if ILoggingService. Add the following class called Log4NetLoggingService to the Logging folder:

public class Log4NetLoggingService : ILoggingService
{
	private readonly IConfigurationRepository _configurationRepository;
	private readonly IContextService _contextService;
	private string _log4netConfigFileName;

	public Log4NetLoggingService(IConfigurationRepository configurationRepository, IContextService contextService)
	{
		if (configurationRepository == null) throw new ArgumentNullException("ConfigurationRepository");
		if (contextService == null) throw new ArgumentNullException("ContextService");
		_configurationRepository = configurationRepository;
		_contextService = contextService;
		_log4netConfigFileName = _configurationRepository.GetConfigurationValue<string>("Log4NetSettingsFile");
		if (string.IsNullOrEmpty(_log4netConfigFileName))
		{
			throw new ApplicationException("Log4net settings file missing from the configuration source.");
		}
		SetupLogger();
	}

	private void SetupLogger()
	{
		FileInfo log4netSettingsFileInfo = new FileInfo(_contextService.GetContextualFullFilePath(_log4netConfigFileName));
		if (!log4netSettingsFileInfo.Exists)
		{
			throw new ApplicationException(string.Concat("Log4net settings file ", _log4netConfigFileName, " not found."));
		}
		log4net.Config.XmlConfigurator
			.ConfigureAndWatch(log4netSettingsFileInfo);
	}

	public void LogInfo(object logSource, string message, Exception exception = null)
	{
		LogMessageWithProperties(logSource, message, Level.Info, exception);
	}

	public void LogWarning(object logSource, string message, Exception exception = null)
	{
		LogMessageWithProperties(logSource, message, Level.Warn, exception);
	}

	public void LogError(object logSource, string message, Exception exception = null)
	{
		LogMessageWithProperties(logSource, message, Level.Error, exception);
	}

	public void LogFatal(object logSource, string message, Exception exception = null)
	{
		LogMessageWithProperties(logSource, message, Level.Fatal, exception);
	}

	private void LogMessageWithProperties(object logSource, string message, Level level, Exception exception)
	{
		var logger = LogManager.GetLogger(logSource.GetType());
			
		var loggingEvent = new LoggingEvent(logSource.GetType(), logger.Logger.Repository, logger.Logger.Name, level, message, null);
		AddProperties(logSource, exception, loggingEvent);
		try
		{
			logger.Logger.Log(loggingEvent);				
		}
		catch (AggregateException ae)
		{
			ae.Handle(x => { return true; });
		}
		catch (Exception) { }
	}

	private string GetUserName()
	{
		return _contextService.GetUserName();
	}

	private void AddProperties(object logSource, Exception exception, LoggingEvent loggingEvent)
	{
		loggingEvent.Properties["UserName"] = GetUserName();
		try
		{
			ContextProperties contextProperties = _contextService.GetContextProperties();
			if (contextProperties != null)
			{
				try
				{						
					loggingEvent.Properties["UserAgent"] = contextProperties.UserAgent;
					loggingEvent.Properties["RemoteHost"] = contextProperties.RemoteHost;
					loggingEvent.Properties["Path"] = contextProperties.Path;
					loggingEvent.Properties["Query"] = contextProperties.Query;
					loggingEvent.Properties["RefererUrl"] = contextProperties.Referrer;
					loggingEvent.Properties["RequestId"] = contextProperties.RequestId;
					loggingEvent.Properties["SessionId"] = contextProperties.SessionId;
				}
				catch (Exception)
				{
				}
			}
				
			loggingEvent.Properties["ExceptionType"] = exception == null ? "" : exception.GetType().ToString();
			loggingEvent.Properties["ExceptionMessage"] = exception == null ? "" : exception.Message;
			loggingEvent.Properties["ExceptionStackTrace"] = exception == null ? "" : exception.StackTrace;
			loggingEvent.Properties["LogSource"] = logSource.GetType().ToString();
		}
		catch (Exception ex)
		{
			var type = typeof(Log4NetLoggingService);
			var logger = LogManager.GetLogger(type);
			logger.Logger.Log(type, Level.Fatal, "Exception when extracting properties: " + ex.Message, ex);
		}
	}		
}

We inject two dependencies by way of constructor injection: IConfigurationRepository and IContextService. IConfigurationRepository will help us locate the name of the log4net configuration file. IContextService will provide contextual data to the log message. Log4net is set up in SetupLogger(). We check for the existence of the config file. We then call log4net.Config.XmlConfigurator.ConfigureAndWatch to let log4net read the configuration settings from an XML file and watch for any changes.

The implemented LogX messages all call upon LogMessageWithProperties where we simply wrap the log message in a LoggingEvent object along with all contextual data.

Originally we had the below code to instantiate a logged and cached ProductService to log to the console:

IProductService productService = new ProductService(new ProductRepository(), new ConfigFileConfigurationRepository());
IProductService cachedProductService = new CachedProductService(productService, new SystemRuntimeCacheStorage());
IProductService loggedCachedProductService = new LoggedProductService(cachedProductService, new ConsoleLoggingService());

We can easily change the logging mechanism by simply injecting the log4net implementation of ILoggingService into LoggedProductService:

IConfigurationRepository configurationRepository = new ConfigFileConfigurationRepository();
IProductService productService = new ProductService(new ProductRepository(), configurationRepository);
IProductService cachedProductService = new CachedProductService(productService, new SystemRuntimeCacheStorage());
ILoggingService loggingService = new Log4NetLoggingService(configurationRepository, new ThreadContextService());
IProductService loggedCachedProductService = new LoggedProductService(cachedProductService, loggingService);

Run Program.cs and if all went well then you’ll have a new file called log.xml in the …MyCompany.ProductConsole/bin/Debug folder with some XML entries. Here comes an excerpt:

<log4net:event logger="MyCompany.ProductConsole.Services.LoggedProductService" timestamp="2014-08-23T22:44:52.7591938+02:00" level="INFO" thread="9" domain="MyCompany.ProductConsole.vshost.exe" username="andras.nemes"><log4net:message>Starting GetProduct method</log4net:message><log4net:properties><log4net:data name="log4net:HostName" value="andras1" /><log4net:data name="Path" value="N/A" /><log4net:data name="SessionId" value="N/A" /><log4net:data name="log4net:UserName" value="andras.nemes" /><log4net:data name="Query" value="N/A" /><log4net:data name="ExceptionMessage" value="" /><log4net:data name="UserName" value="&lt;null&gt;" /><log4net:data name="RefererUrl" value="N/A" /><log4net:data name="LogSource" value="MyCompany.ProductConsole.Services.LoggedProductService" /><log4net:data name="RemoteHost" value="N/A" /><log4net:data name="ExceptionStackTrace" value="" /><log4net:data name="UserAgent" value="N/A" /><log4net:data name="ExceptionType" value="" /><log4net:data name="RequestId" value="N/A" /><log4net:data name="log4net:Identity" value="" /></log4net:properties></log4net:event>

So it took some time to implement the log4net version of ILoggingService but to switch from the console-based implementation was a breeze.

However, you may still see one log message logged to the console. That’s from the code line in ProductService.GetProduct:

LogProviderContext.Current.LogInfo(this, "Log message from the contextual log provider");

…where LogProviderContext returns a ConsoleLoggingService by default. However, it also allows us to set the implementation of ILoggingService. Insert the following code in Main…

LogProviderContext.Current = loggingService;

…just below…

ILoggingService loggingService = new Log4NetLoggingService(configurationRepository, new ThreadContextService());

Then you’ll see that even the previously mentioned log message ends up in log.xml:

<log4net:event logger="MyCompany.ProductConsole.Services.ProductService" timestamp="2014-08-23T22:56:19.411468+02:00" level="INFO" thread="8" domain="MyCompany.ProductConsole.vshost.exe" username="andras.nemes"><log4net:message>Log message from the contextual log provider</log4net:message><log4net:properties><log4net:data name="log4net:HostName" value="andras1" /><log4net:data name="Path" value="N/A" /><log4net:data name="SessionId" value="N/A" /><log4net:data name="log4net:UserName" value="andras.nemes" /><log4net:data name="Query" value="N/A" /><log4net:data name="ExceptionMessage" value="" /><log4net:data name="UserName" value="&lt;null&gt;" /><log4net:data name="RefererUrl" value="N/A" /><log4net:data name="LogSource" value="MyCompany.ProductConsole.Services.ProductService" /><log4net:data name="RemoteHost" value="N/A" /><log4net:data name="ExceptionStackTrace" value="" /><log4net:data name="UserAgent" value="N/A" /><log4net:data name="ExceptionType" value="" /><log4net:data name="RequestId" value="N/A" /><log4net:data name="log4net:Identity" value="" /></log4net:properties></log4net:event>

So that’s it about logging. We’ll continue with the file system in the next part.

View the list of posts on Architecture and Patterns here.

4 design patterns to learn with C# .NET

Here come 4 well-known design patterns that I think most developers will benefit from, even those that are by nature anti-designpattern. Note that the list is biased and only shows the ones that I personally use the most often in my work.

If you don’t find the solution to your design problem here then check out the full list of patterns discussed on this blog here.

  • Adapter: this pattern helps you hide the functionality of a class which is not under your control behind an abstraction
  • Strategy: this pattern will help you with cleaning up anti-SOLID code where you check for certain properties, especially the type of an object to tweak your code. You will end up with proper objects instead of brittle switch or if-else statements
  • Decorator: if you’d like to extend the functionality of a class without changing its implementation then this pattern is something to consider. You can build compound objects by nesting decorators where the individual elements are still standalone classes.
  • Factory: this pattern will help you build objects using parameters whose values are not known beforehand. E.g. if you don’t which concrete type of an abstract class to return then hide that build functionality behind an abstract factory

Externalising dependencies with Dependency Injection in .NET part 4: logging part 1

Introduction

In this post of this series we looked at ways to remove caching logic from our ProductService class. In the previous post we saw how to hide reading from a configuration file. We’ll follow in a similar fashion in this post which takes up logging. A lot of the techniques and motivations will be re-used and not explained again.

We’ll build upon the demo app we started on so have it ready in Visual Studio.

Logging

Logging is a wide area with several questions you need to consider. What needs to be logged? Where should we save the logs? How can the log messages be correlated? We’ll definitely not answer those questions here. Instead, we’ll look at techniques to call the logging implementation.

I’d like to go through 3 different ways to put logging into your application. For the demo we’ll first send the log messages to the Console window for an easy start. After that, we’ll propose a way of implementing logging with log4net. The material is too much for a single post so I’ve decided to divide this topic into 2 posts.

Starting point

If you ever had to log something in a professional .NET project then chances are that you used Log4Net. It’s a mature and widely used logging framework. However, it’s by far not the only choice. There’s e.g. NLog and probably many more.

If you recall the first solution for the caching problem we put the caching logic directly inside ProductService.GetProduct:

public GetProductResponse GetProduct(GetProductRequest getProductRequest)
{
	GetProductResponse response = new GetProductResponse();
	try
	{
		string storageKey = "GetProductById";
		ObjectCache cache = MemoryCache.Default;
		Product p = cache.Contains(storageKey) ? (Product)cache[storageKey] : null;
		if (p == null)
		{
			p = _productRepository.FindBy(getProductRequest.Id);
			CacheItemPolicy policy = new CacheItemPolicy() { AbsoluteExpiration = DateTime.Now.AddMinutes(5) };
			cache.Add(storageKey, p, policy);
		}
		response.Product = p;
		if (p != null)
		{
			response.Success = true;
		}
		else
		{
			response.Exception = "No such product.";
		}
	}
	catch (Exception ex)
	{
		response.Exception = ex.Message;
	}
	return response;
}

We then also discussed the disadvantages of such a solution, like diminished testability and flexibility. We could follow a similar solution for the logging with log4net with direct calls from ProductService like this:

var logger = logSource.GetLogger();
var loggingEvent = new LoggingEvent(logSource.GetType(), logger.Logger.Repository, logger.Logger.Name, Level.Info, "Code starting", null);
logger.Logger.Log(loggingEvent);

…which would probably be factored out to a different method but the strong dependency on and tight coupling to log4net won’t go away. We could have similar code for NLog and other logging technologies out there. Then some day the project leader says that the selected technology must change because the one they used on a different project is much more powerful. Then the developer tasked with changing the implementation at every possible place in the code won’t have a good day out.

The logging interface

As we saw in the previous post the key step towards an OOP solution is an abstraction which hides the concrete implementation. This is not always a straightforward step. In textbooks it always looks easy to create these interfaces because they always give you a variety of concrete implementations beforehand. Then you’ll know what’s common to them and you can put those common methods in an interface. In reality, however, you’ll always need to think carefully about the features that can be common across a variety of platforms: what should every decent logging framework be able to do at a minimum? What should a caching technology be able to do? Etc., you can ask similar questions about every dependency in your code that you’re trying to factor out. The interface should find the common features and not lean towards one specific implementation so that it becomes as future-proof as possible.

Normally any logging framework should be able to log messages, message levels – e.g. information or fatal – and possibly exceptions. Insert a new folder called Logging to the Infrastructure layer and add the following interface into it:

public interface ILoggingService
{
	void LogInfo(object logSource, string message, Exception exception = null);
	void LogWarning(object logSource, string message, Exception exception = null);
	void LogError(object logSource, string message, Exception exception = null);
	void LogFatal(object logSource, string message, Exception exception = null);
}

This should be enough for starters: the source where the logging happens, the message and an exception. The level is represented by the method names.

Logging to the console

As promised above, we’ll take it easy first and send the log messages directly to the console. So add the following implementation to the Logging folder:

public class ConsoleLoggingService : ILoggingService
{
	private ConsoleColor _defaultColor = ConsoleColor.Gray;

	public void LogInfo(object logSource, string message, Exception exception = null)
	{
		Console.ForegroundColor = ConsoleColor.Green;
		Console.WriteLine(string.Concat("Info from ", logSource.ToString(), ": ", message));
		PrintException(exception);
		ResetConsoleColor();
	}

	public void LogWarning(object logSource, string message, Exception exception = null)
	{
		Console.ForegroundColor = ConsoleColor.Yellow;
		Console.WriteLine(string.Concat("Warning from ", logSource.ToString(), ": ", message));
		PrintException(exception);
		ResetConsoleColor();
	}

	public void LogError(object logSource, string message, Exception exception = null)
	{
		Console.ForegroundColor = ConsoleColor.DarkMagenta;
		Console.WriteLine(string.Concat("Error from ", logSource.ToString(), ": ", message));
		PrintException(exception);
		ResetConsoleColor();
	}

	public void LogFatal(object logSource, string message, Exception exception = null)
	{
		Console.ForegroundColor = ConsoleColor.Red;
		Console.WriteLine(string.Concat("Fatal from ", logSource.ToString(), ": ", message));
		PrintException(exception);
		ResetConsoleColor();
	}

	private void ResetConsoleColor()
	{
		Console.ForegroundColor = _defaultColor;
	}

	private void PrintException(Exception exception)
	{
		if (exception != null)
		{
			Console.WriteLine(string.Concat("Exception logged: ", exception.Message));
		}
	}
}

That should be quite straightforward I believe.

Solution 1: decorator

We saw an example of the Decorator pattern in the post on caching referred to in the intro and we’ll build on that. We’ll extend the original ProductService implementation to include both caching and logging. Add the following decorator to the Services folder of the Console app layer:

public class LoggedProductService : IProductService
{
	private readonly IProductService _productService;
	private readonly ILoggingService _loggingService;

	public LoggedProductService(IProductService productService, ILoggingService loggingService)
	{
		if (productService == null) throw new ArgumentNullException("ProductService");
		if (loggingService == null) throw new ArgumentNullException("LoggingService");
		_productService = productService;
		_loggingService = loggingService;
	}

	public GetProductResponse GetProduct(GetProductRequest getProductRequest)
	{
		GetProductResponse response = new GetProductResponse();
		_loggingService.LogInfo(this, "Starting GetProduct method");
		try
		{
			response = _productService.GetProduct(getProductRequest);
			if (response.Success)
			{
				_loggingService.LogInfo(this, "GetProduct success!!!");
			}
			else
			{
				_loggingService.LogError(this, "GetProduct failure...", new Exception(response.Exception));
			}
		}
		catch (Exception ex)
		{
			response.Exception = ex.Message;
			_loggingService.LogError(this, "Exception in GetProduct!!!", ex);
		}
		return response;
	}
}

You’ll recall the structure from the Caching decorator. We hide both the product and logging service behind interfaces. We delegate the product retrieval to the product service and logging to the logging service. So if you’d like to add logging to the original ProductService class then you can have the following code in Main:

IProductService productService = new ProductService(new ProductRepository());
IProductService loggedProductService = new LoggedProductService(productService, new ConsoleLoggingService());
GetProductResponse getProductResponse = loggedProductService.GetProduct(new GetProductRequest() { Id = 2 });
if (getProductResponse.Success)
{
	Console.WriteLine(string.Concat("Product name: ", getProductResponse.Product.Name));
}
else
{
	Console.WriteLine(getProductResponse.Exception);
}

If you run this code then you’ll see an output similar to this:

Info messages from logging service

If you run the code with a non-existent product ID then you’ll see an exception as well:

Exception from logging service

If you’d then like to add both caching and logging to the plain ProductService class then you can have the following test code:

IProductService productService = new ProductService(new ProductRepository());
IProductService cachedProductService = new CachedProductService(productService, new SystemRuntimeCacheStorage());
IProductService loggedCachedProductService = new LoggedProductService(cachedProductService, new ConsoleLoggingService());
GetProductResponse getProductResponse = loggedCachedProductService.GetProduct(new GetProductRequest() { Id = 2 });
if (getProductResponse.Success)
{
	Console.WriteLine(string.Concat("Product name: ", getProductResponse.Product.Name));
}
else
{
	Console.WriteLine(getProductResponse.Exception);
}

getProductResponse = loggedCachedProductService.GetProduct(new GetProductRequest() { Id = 2 });
			
Console.ReadKey();

Notice how we build up the compound decorator loggedCachedProductService from productService and cachedProductService in the beginning of the code. You can step through the code and you’ll see how we print the log messages, check the cache and retrieve the product from ProductService if necessary.

Solution 2: ambient context

I think the above solution with dependency injection, interfaces and decorators follows SOLID principles quite well. We can build upon the ProductService class using the decorators, pass different implementations of the abstractions and test each component independently.

As discussed in the post on Interception – check the section called Interception using the Decorator pattern – this solution can have some practical limitations, such as writing a large number of tedious code. While you may not want to do caching in every single layer, logging is different. You may want to log from just about any layer of the application: UI, services, controllers, repositories. So you may need to write a LoggedController, LoggedRepository, LoggedService etc. for any component where you want to introduce logging.

In the post on patterns in dependency injection we discussed a technique called ambient context. I suggest you read that section if you don’t understand the term otherwise you may not understand the purpose of the code below. Also, you’ll find its advantages and disadvantages there as well.

Insert the following class into the Logging folder of the infrastructure project:

public abstract class LogProviderContext
{
	private static readonly string _nameDataSlot = "LogProvider";

	public static ILoggingService Current
	{
		get
		{
			ILoggingService logProviderContext = Thread.GetData(Thread.GetNamedDataSlot(_nameDataSlot)) as ILoggingService;
			if (logProviderContext == null)
			{
				logProviderContext = LogProviderContext.DefaultLogProviderContext;
				Thread.SetData(Thread.GetNamedDataSlot(_nameDataSlot), logProviderContext);
			}
			return logProviderContext;
		}
		set
		{
			Thread.SetData(Thread.GetNamedDataSlot(_nameDataSlot), value);
		}
	}

	public static ILoggingService DefaultLogProviderContext = new ConsoleLoggingService();
}

You can call this code from any other layer which has a reference to the infrastructure layer. E.g. you can have the following code directly in ProductService.GetProducts:

LogProviderContext.Current.LogInfo(this, "Log message from the contextual log provider");

Solution 3: injecting logging into ProductService

Another solution which lies somewhere between ambient context and the decorator is having ProductService depend upon an ILoggingService:

public ProductService(IProductRepository productRepository, ILoggingService loggingService)

You can then use the injected ILoggingService to log you messages. We saw a similar example in the post on caching and also in the post on Interception referred to above. Read the section called Dependency injection in the post on Interception to read more why this approach might be good or bad.

However, if you’re faced with such a constructor and still want to test ProductService in isolation you can use a Null Object version of ILoggingService. Add the following class to the Logging folder:

public class NoLogService : ILoggingService
{
	public void LogInfo(object logSource, string message, Exception exception = null)
	{}

	public void LogWarning(object logSource, string message, Exception exception = null)
	{}

	public void LogError(object logSource, string message, Exception exception = null)
	{}

	public void LogFatal(object logSource, string message, Exception exception = null)
	{}
}

In the next post we’ll continue with logging to show a more realistic implementation of ILoggingService with log4net.

View the list of posts on Architecture and Patterns here.

How to send emails in .NET part 11: credentials

In the previous part in this mini-series we looked at how to handle exceptions. We’ll briefly look at authentication in this post.

Some SMTP servers require you to provide a username and password in order to send emails.

You can set the default network credentials as follows:

string smtpServer = "mail.blahblah.com";
SmtpClient client = new SmtpClient(smtpServer);
client.UseDefaultCredentials = true;

Another way to achieve the same is the following:

client.Credentials = CredentialCache.DefaultNetworkCredentials;

…where CredentialCache is found in the System.Net namespace.

You can also set the username and password manually as follows:

client.Credentials = new NetworkCredential("name", "password");

Read all posts related to emailing in .NET here.

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.