Showing posts from August, 2009

Strongly typed AppSettings with defaults

Very often I want configurable options for miscellaneous settings; but I hate to shift my focus from the code I'm working on to add a new AppSetting. Sometimes these settings are essential but more often than they are just options that I may need. So the solution I like to use is to make default values for such AppSettings. If the service you are writing needs to retry a database or web service call a few times, why not make that option configurable but use a default of 5. The method below will grab an AppSetting & try to convert it. If it fails, it uses the default. Plus the generic T can be a value or reference type. public static T GetAppSetting<T>(string key, T defaultValue) { if (String.IsNullOrEmpty(ConfigurationManager.AppSettings[key])) return defaultValue; try { return (T)Convert.ChangeType(ConfigurationManager.AppSettings[key], typeof(T)); } catch { } return defaultValue; } // Sample Usage public void DoSomething() { if(GetAppSetting("Shou

Stream was not readable

TL;DR - flush & reset, see: [Fact] public void BaseStream_Is_Not_Empty() { MemoryStream stream = new MemoryStream(); LogWriter logWriter = new LogWriter(stream); logWriter.WriteLine(new[] { DateTime.Now.ToString("yyyy-MM-dd"), "Log data" }); logWriter.BaseStream.AutoFlush = true; stream.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(stream)) { Assert.NotEmpty(sr.ReadToEnd()); } } I recently started writing some tests (in xUnit using Moq + StructureMap) for a service that calls a class -- let's call it LogWriter -- that simply writes formatted logging data to a Stream. After creating an interface for the logging class, ILogWriter, I wanted to write some tests on LogWriter to see if it was working as expected (before testing out my service which depends on ILogWriter). After the ILogWriter was done, I used StreamReader to check out it's input. The Stream I told it to write to was a MemoryStream (this is unit testin

Fluent NHibernate + Encrypting Values

I recently created two CLR User Defined Functions for SQL Server 2005 (written in C#) to decrypt & encrypt a given string (based on a hard-coded key). select dbo.EncryptString('Testing') -- Returns: Fjfds243qcm43fsdj2343== select dbo.DecryptString('Fjfds243qcm43fsdj2343==') -- Returns: Testing Pretty simple stuff. This will allow the user with enough access to pull encrypted data out of the database and provide the ability to restrict decryption to other SQL users. Now to implement this in code... Because it's awesome, Fluent NHibernate has a method called FormulasIs that assists in building out values using SQL. public class User { public virtual int Id { get; set; } public virtual DateTime DateOfBirth { get; set; } } public sealed class UserMap : ClassMap { public UserMap() { WithTable("dbo.[User]"); Id(x => x.Id, "[ID]"); Map(x => x.DateOfBirth, "DOB").FormulaIs("dbo.DecryptString(DOB)");