0

Enterprise Library Walkthrough

Posted in .Net, C# at November 7th, 2008 by Ben / No Comments »

What is Enterprise Library?

Ent.Lib 4.1 - http://msdn.microsoft.com/en-us/library/dd203099.aspx

The Microsoft Enterprise Library is a collection of reusable software components (application blocks) designed to assist software developers with common enterprise development cross-cutting concerns (such as logging, validation, data access, exception handling, and many others).

The application blocks aim to encapsulate proven best-practice for enterprise .net development.

In total there are over 9 application blocks:

  • Caching
  • Cryptography
  • Data Access
  • Exception Handling
  • Logging
  • Policy Injection
  • Security
  • Unity - Dependency Injection (IoC) container
  • Validation

This article will address the Exception, Logging, Validation and Unity application block. The new Unity Application block encapsulates the Policy Injection block and as such will not be addressed in this article along with the Caching, Cryptography and Security blocks.

Download Ent. Library 4.1 here:
http://www.microsoft.com/downloads/details.aspx?FamilyId=1643758B-2986-47F7-B529-3E41584B6CE5&displaylang=en

Important:

This article is just a rehash of information easily found in the Ent.Library documentation and online websites. To get a comprehensive understanding of how the blocks work download the Sample Code I’ve created here.

Alternately, for further demonstrations on how these blocks work, load up the included QuickStart tutorials included with the Ent. Lib download.

Note:
The solution is works with VS 2008 Team System. It utilizes the seperate Unity Application block but works with Ent. Library 3.1 for all other App. Blocks due to 3rd party software we use that has a dependency on Ent. Lib 3.1.

To migrate to Ent. Lib 4.1 just change all references for 3.1 app blocks to 4.1 app blocks.
You will also be able to remove out the the ApplicationCode/CallHandlers/*.cs files and use the 4.1 PolicyInjection CallHandlers.

NOTE: Be sure to read the rest of this article by clicking the link below.

Read the rest of this entry »

6

Reader challenge!

Posted in C#, Daily Question at November 3rd, 2008 by Gerrod / 6 Comments »

It’s been a while since we’ve had a reader question, so here’s one for you all. It’s not that I can’t solve this problem; it’s more that I’m wondering if there’s a more elegant solution.

The Problem: Given two dates, what’s the easiest way of determining if they fall in the same week?

Please submit your answers as a comment!

0

Using Flagged Enums

Posted in .Net, C# at November 2nd, 2008 by Ben / No Comments »

Have you ever written or come across code where you have a series of boolean values that determine whether or not certain actions are allowed?

Example:


public class WorkDays
{
  public bool Sunday { get; set; }
  public bool Monday { get; set; }
  public bool Tuesday { get; set; }
  public bool Wednesday { get; set; }
  public bool Thursday { get; set; }
  public bool Friday { get; set; }
  public bool Saturday { get; set; }

  public bool Weekdays { get { return Monday && Tuesday && Wednesday && Thursday && Friday; } }
  public bool Weekends { get { return Sunday && Saturday; } }

  public int NumberOfDaysWorked
        {
            get
            {
                int numberOfDaysWorked = 0;

                if (CanWorkMonday) numberOfDaysWorked++;
                if (CanWorkTuesday) numberOfDaysWorked++;
                if (CanWorkWednesday) numberOfDaysWorked++;
                if (CanWorkThursday) numberOfDaysWorked++;
                if (CanWorkFriday) numberOfDaysWorked++;
                if (CanWorkSaturday) numberOfDaysWorked++;
                if (CanWorkSunday) numberOfDaysWorked++;

                return numberOfDaysWorked;
            }
        }
}

There’s a more elegant approach that is utilized through the standard .net framework that we too can mimic.

This scenario is a perfect candidate for using a flagged enum and the power of bit operations.



    [Flags]
    public enum Days
    {
        None = 0,
        Sunday = 1,
        Monday = 2,
        Tuesday = 4,
        Wednesday = 8,
        Thursday = 16,
        Friday = 32,
        Saturday = 64,
        MondayToFriday = Monday | Tuesday | Wednesday | Thursday | Friday,
        Weekend = Saturday | Sunday,
        All = MondayToFriday | Weekend,
    }

    public class WorkDays
    {
        public Days DaysWorked { get; set; }

        /// <summary>
        /// Get the Number of Days worked.
        /// NOTE: Uses bitwise and operation.
        /// </summary>
        public int NumberOfDaysWorked
        {
            get
            {
                Days days = DaysWorked;
                int numberOfDaysWorked = 0;
                for (; days != 0; numberOfDaysWorked++)
                {
                    days &= days - 1; // clear the least significant bit set
                }
                return numberOfDaysWorked;
            }
        }
    }

By defining an enum with each successive value a power of 2 greater (i.e. binary) you can then use the bitwise or (|) and bitwise (&) operations to group and determine which values are selected.


    [TestClass]
    public class ExampleTestClass
    {
        [TestMethod]
        public void Test()
        {
            var mondayToFriday = new WorkDays { DaysWorked = Days.MondayToFriday };
            Assert.IsFalse(Days.Sunday.In(mondayToFriday.DaysWorked));
            Assert.IsFalse(Days.Saturday.In(mondayToFriday.DaysWorked));
            Assert.IsTrue(Days.Wednesday.In(mondayToFriday.DaysWorked));
            Assert.AreEqual(5, mondayToFriday.NumberOfDaysWorked);

            var monday = new WorkDays { DaysWorked = Days.Monday };
            Assert.IsFalse(Days.Sunday.In(monday.DaysWorked));
            Assert.IsTrue(Days.Monday.In(monday.DaysWorked));
            Assert.AreEqual(1, monday.NumberOfDaysWorked);

            var mondayAndWednesday = new WorkDays { DaysWorked = Days.Monday | Days.Wednesday };
            Assert.IsFalse(Days.Tuesday.In(mondayAndWednesday.DaysWorked));
            Assert.IsTrue(Days.Monday.In(mondayAndWednesday.DaysWorked));
            Assert.IsTrue(Days.Wednesday.In(mondayAndWednesday.DaysWorked));
            Assert.AreEqual(2, mondayToFriday.NumberOfDaysWorked);

            var weekend = new WorkDays { DaysWorked = Days.Weekend};
            Assert.IsTrue(Days.Saturday.In(weekend.DaysWorked));
            Assert.IsTrue(Days.Sunday.In(weekend.DaysWorked));
            Assert.IsFalse(Days.MondayToFriday.In(weekend.DaysWorked));
            Assert.AreEqual(2, weekend.NumberOfDaysWorked);
        }
    }

    public static class Extensions
    {
        /// <summary>
        /// Is the specified enumeration value within the range of Enum values?
        /// </summary>
        /// <param name="value">the enum value to look for in the range</param>
        /// <param name="range">the range of enum values (eg. bitwise OR'd values)</param>
        /// <returns></returns>
        public static bool In(this Enum value, Enum range)
        {
            var valueNumber = (int) Enum.Parse(value.GetType(), value.ToString());
            var rangeNumber = (int) Enum.Parse(range.GetType(), range.ToString());
            return (valueNumber & rangeNumber) == valueNumber;
        }
    }

For further information check out the following resources:

If you’re gotten a bit rusty on your bitwise operations:
http://en.wikipedia.org/wiki/Bitwise_operation

Flagged Enum:
http://weblogs.asp.net/wim/archive/2004/04/07/109095.aspx

Short Cut Keys to Run Tests:

• Ctl R, T: Run Tests in Current context (namespace, class, and method – ie. Based on where your cursor is within a file it determines the tests to run)
• Ctl R, C: Run Tests in Current Test Class
• Ctl R, N: Run Tests in Current Namespace
• Ctl R, S: Run All Tests in Solution
• Ctl R, D: Run the Tests in the Last Test Run
• Ctl R, F: Run the Failed Tests of the Last Test Run

0

I’m back

Posted in .Net, Asp.Net, C#, Unit Testing at October 30th, 2008 by Ben / No Comments »

After having 9 months off from doing .net (travelling, bumming and then a 3 month contract role as an architect in a coldfusion shop) I finally got myself a role doing what I love doing best - playing with .net and c#.

In the last 4 weeks I’ve been researching and prototyping apps that use

It’s been awesome to have the time and resources to touch across all of these technologies to enjoy their benefits and to loath the limitations.

All in all I reckon all of the technologies are a great addition to the .net stack and look forward to seeing them mature with each new release.

I look forward to documenting my findings as I find time to re-work them into don’t-give-away-IP examples.

1

Using Enums for constant values

Posted in C# at October 13th, 2008 by Ben / 1 Comment »

Have you ever found yourself using c# const values to remove the risks associated with using copies of string literals throughout your code base?

Example:



public static class VehicleTypesConsts {
  public const string Car = "Car";
  public const string Motorbike = "Motorbike";
  public const string Truck = "Truck";
}

In a situation like this it’s quite easy to replace these const values with a C# enum and use the System.Enum.GetName static method to return Enum properties name.



public enum VehicleTypesEnum {
  Car,
  Motorbike,
  Truck,
}

Calling


Enum.GetName(typeof(VehicleTypesEnum), VehicleTypesEnum.Car)

will return the string value “Car”.

Looking at this syntax you could be forgiven for thinking why bother? It’s too much hassle and looks puss.

Well using C# 3.0 extension methods you can provide a convenience method to all Enums to return the enum string representation.



public static class EnumExtensions {
  static public string GetName(this Enum enumeration) {
    return Enum.GetName(enumeration.GetType(), enumeration);
  }
}

Now you can just write:


VehicleTypesEnum.Car.GetName()

and it will return the string “Car”.

The following test method shows illustrates the varying ways to achieve the same result:



        [TestMethod]
        public void Test()
        {
            string expected = "Car";
            Assert.AreEqual(expected, VehicleTypesConsts.Car);
            Assert.AreEqual(expected, Enum.GetName(typeof(VehicleTypesEnum), VehicleTypesEnum.Car));
            Assert.AreEqual(expected, VehicleTypesEnum.Car.GetName());
        }

3

SqlDependency and DateTime values

Posted in C#, Sql Server at September 22nd, 2008 by Gerrod / 3 Comments »

I ran into a problem today where I was trying to set up a SqlDependency against a table, with what I thought was a plain vanilla select statement:


private const string SqlCommandText =
    "Select ImportDate From dbo.Imports Where ImportDate = '{0:yyyyMMdd}'";

I was formatting this string with a date/time value at runtime, then passing that into my SqlCommand object, then attempting to register the dependency. Well guess what - it didn’t work! The SqlNotificationEventArgs class kept telling me that my statement was invalid. Checking the special considerations using query notifications, I couldn’t see anything wrong with my query, so I was a bit lost.

Anyway, I decided to axe the “Where” condition from my query, and sure enough, it worked! So, by process of elimination, I figured it was something to do with converting a date from a character string that was throwing it. Not sure why; this works fine when run as T-Sql, or within a normal query…

To get around this problem, I used the “best practice” approach of using a parameter in the SqlCommand object:


private const string SqlCommandText =
    "Select ImportDate From dbo.Imports Where ImportDate = @ImportDate";

protected SqlCommand CreateSqlCommand() {
    var command = new SqlCommand(SqlCommandText);
    command.Parameters.Add(new SqlParameter("ImportDate", SqlDbType.DateTime) {
        Value = PositionDate
    });

    return command;
}

To my surprise, this worked a treat! I guess in the end, it wasn’t all that surprising, however I for some reason thought that using a parameter would surely not work; hence the reason I was pre-formatting the date/time in the first place!

0

Extension methods on interfaces

Posted in .Net, C# at July 14th, 2008 by Gerrod / No Comments »

This is actually quite straightforward, but something that perhaps you may not have thought about.

On my current project, I have the concept of a “PerishableObject” - an object whose value is only valid between two particular dates. The interface for an IPerishable looks something like this:


public interface IPerishable {
    /// <summary>
    /// Get/Set the date that this component is valid from
    /// </summary>
    DateTime? ValidFrom { get; set; }

    /// <summary>
    /// Get/Set the date that this component is valid until
    /// </summary>
    DateTime? ValidTo { get; set; }
}

Now, logically, I wanted to create a helper method called “IsValidOn”, which could be passed a date, and would return true/false indicating if the component is valid on the supplied date. Obviously, I could define this in the interface, but that would leave me to either implement the method on every object which implements the interface, or to create a common base class which implemented that method, and then force all perishable objects to inherit from this base class. Both of these are not desirable!

Thankfully, extension methods in C# 3.0 provide a perfect solution for this:


/// <summary>
/// Determines if the perishable component is valid on the given reference date
/// </summary>
/// <param name="component">The component to be tested</param>
/// <param name="referenceDate">Reference date to test</param>
/// <returns><c>true</c> if the perishable component is valid on the given reference date</returns>
static internal bool IsValidOn(this IPerishable component, DateTime? referenceDate) {
    if (!referenceDate.HasValue) {
        return true;
    }

    return (!component.ValidFrom.HasValue || component.ValidFrom.Value <= referenceDate)
        && (!component.ValidTo.HasValue || component.ValidTo.Value >= referenceDate);
}

Defining extension methods against an interface is a great way of extending the interface without bulking it up.

2

Daily question: Fun with constructors

Posted in C#, Daily Question at July 10th, 2008 by Gerrod / 2 Comments »

It’s been a while since anyone has posted a daily question, but here’s one to get y’all in the mood…

Given the following code:


public class BaseClass {
    public BaseClass() : this("Base value") {
        Console.WriteLine("Base: Empty");
    }

    public BaseClass(object value) {
        Console.WriteLine("Base with value: {0}", value);
    }
}

public class DerivedClass : BaseClass {
    public DerivedClass() : this("Derived value") {
        Console.WriteLine("Derived: Empty");
    }

    public DerivedClass(object value) : base(value) {
        Console.WriteLine("Derived with value: {0}", value);
    }
}

What will be printed to the console when a new DerivedClass object is created using the default DerivedClass constructor:


    new DerivedClass();

First person to post the correct answer wins a prize consiting solely of that warm fuzzy feeling you get by being the first person to answer a question correctly.

If you want to run sql server scripts through code, you can’t just run a standard ExecuteNonQuery() with a SqlCommand. There’s problems with ExecuteNonQuery() recognizing multiple sql statements.

Don’t fear though, if you reference the Microsoft.SqlServer.Smo and Microsoft.SqlServer.ConnectionInfo assemblies you get access to some goodies that’ll help you on your way!


using System.Configuration;
using System.Data;
using System.Data.SqlClient;

using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBName"].ConnectionString);
Server server = new Server(new ServerConnection(connection));
server.ConnectionContext.ExecuteNonQuery(File.ReadAllText("SqlScript.sql"));