Tag Archives: C#

An IoC Conundrum: Looking for feedback

Today at work, my boss and I were brainstorming on the best way to use IoC across all our code. During this, he proposed an idea for using IoC that at first made me feel uneasy with the way it was being used. But the more I think about it, the more I am amazed by its design. Let me set this up for you and the best way is with pictures.

Note: The code examples given here are not functional and just provided to give a rough idea of what is intended.

Explanation: 

  • The BaseLib is a library that contains all the interfaces we define. It also contains the CDepInjection class.
  • The CDepInjection class contains a static Register method that will find an assembly that corresponds to an interface and using Reflection, load it.
  • The Database library contains a CDatabase class with a static constructor that will be called from the previous step when the Database library is reflected and loaded. See image below.

Benefits:

  • By having all the interfaced in BaseLib, we are programming against an interface.
  • By having the CDepInjection class in BaseLib, there is only 1 place we need to update code and only 1 dll that we will need to deploy in production should changes be needed. (Note: We could have 100 servers running 100 application each and they may be windows services, web services, asp.net mvc apps, windows forms apps, console apps etc.).
  • By making a change in CDepInjection and telling it to map an interface name to the appropriate assembly and class and having the RegisterType be in the CDatabase class, we can create a new database class, CNoSqlDatabase in another assembly, deploy it, make a change to BaseLib by telling it to now map IDatabase to the CNoSqlDatabase and then deploy that to all our servers GAC. Now, everything will use the new CNoSQLDatabase.

Concerns I have:

  • Using a static constructor in CDatabase means that it will be called one per process and only when the assembly is loaded in the Register(..) method of CDepInjection. I’m not convinced that a static constructor would be the best thing to do. In essence, aren’t we just abstracting the mappings that would go in a config file and putting them into BaseLib instead of an app.config of BaseLib?
  • Resolving parent-child would necessitate having to call register in the ‘main’ method of all our applications. For instance, if CDatabase was going to need logging, it would have to call Register(“ILogging”) in the static constructor above the Container.RegisterType<IDatabase, CDatabase>() call.

I would very much appreciate a critique of this design. Thank you.

Tagged , , , , , , , ,

Poor Man’s Validation

Does your validation drive you crazy? Are you writing too much validator code? Have you lost your sense of humor?

image

Well, not to worry because now, there’s a little hack to make Validation easier.

Lets say I had a Company class as defined by:

    public class Company
    {
        public string Title
        {
            get;
            set;
        }
    }

Now, say I wanted to add validation to this so that the

  • Title is Required
  • Title must be up to 10 characters
  • Title can only be Alpha and space

In order to achieve this quickly, you can add the System.ComponentModel.DataAnnotations.dll file to your project (Make sure its the latest one from Codeplex). Then update your class definition as follows:

    public class Company
    {
        [Required]
        [StringLength(10)]
        [RegularExpression("[A-Za-z\\s]+")]
        public string Title
        {
            get;
            set;
        }
    }

Now you can run the following code to validate your class instance as follows:

    //
    // Test instantiation
    ValidationContext vc = null;
    bool bCanCreate = false;
    List<ValidationResult> validationResults = new List<ValidationResult>();
    Company _company = new Company();

    //
    // Test 1 : Acceptable test undeo 10 characters and alpha.
    _company.Title = "The Title";
    vc = new ValidationContext(_company, null, null);
    bCanCreate = Validator.TryValidateObject(_company, vc, validationResults, true);
    Debug.Assert(bCanCreate == true);

    //
    // Test 2: Failure test 
    _company.Title = "32 Pan";
    vc = new ValidationContext(_company, null, null);
    bCanCreate = Validator.TryValidateObject(_company, vc, validationResults, true);
    Debug.Assert(bCanCreate == false);

    //
    // Test 3: Failure test 
    _company.Title = "";
    vc = new ValidationContext(_company, null, null);
    bCanCreate = Validator.TryValidateObject(_company, vc, validationResults, true);
    Debug.Assert(bCanCreate == false);

    //
    // Test 4: Failure test 
    _company.Title = "abcdefghijklm nopqrstuvwxyz";
    vc = new ValidationContext(_company, null, null);
    bCanCreate = Validator.TryValidateObject(_company, vc, validationResults, true);
    Debug.Assert(bCanCreate == false);

So now you’re bound to be validator approved.

image

Tagged , , , , ,

Excelcification: Brain Teaser Code

Problem: Someone at work recently asked me how you would go about converting excel header rows into integers. In the image below, you see each column and its corresponding integer value.

 image

Thus, A = 0, B = 1, C = 2 and so on. Since I have no better word to describe this process, I’m going to call it Excelcification.

Def: Excelcification. The act of converting a alpha column into its numeric representation.

However, Excel cells go from A to Z and then become AA, AB, AC etc. So if Z = 25, AA = 26, AB = 27 and so on.

Your mission is to create a method that takes a string that corresponds to the excel column (don’t have to worry about spaces etc for now) and change that to its integer value.

 

In case you didn’t know, the largest column in Excel 2010 that I could see was XFD.

image

So what is the Excelcification of “XFD”?

 

[Jeopardy theme music plays…]

 

[Some time later…]

 

[Some more time later…]

 

Are you done? How did you do it?

 

My process was to recognize that this is going to be Base 26 arithmetic, also know as Hexavigesimal. But you didn’t need to know that. If you know how base 2 (binary) works, you can extrapolate it to work for base 26.  So how does base 2 work. If you remember your truth tables from high school/college, you would know that in binary:

01 = 2^0

10 = 2^1

11 = 2^1 + 2^0

 

Now extrapolate this for base 26 and realize that in binary, your digits are only 0 and 1 whereas in hexavigesimal, your digits are 0 through 25. (See the link there to A through Z).

Thus,

A = (26^0) * Numeric_Value(A)

B = (26^0) * Numeric_Value(B)

etc.

 

So if you create a method for this your code should be:

         public static class ExtensionMethods
    {
        /// <summary>
        /// Converts a string into its hexavigesical (base 26) representation.
        /// </summary>
        /// <param name="sxCol">Input string of letters.</param>
        /// <returns>-1 if input is null or empty, base 26 integer representation of input otherwise.</returns>
        public static int Excelcify(this string sxCol)
        {
            int result = -1;
            sxCol = sxCol.ToUpper();

            if (string.IsNullOrEmpty(sxCol))
                return result;


            for (int i = sxCol.Length; i > 0; i--)
            {
                char _c = sxCol[i-1];
                //
                // Function =>  (26 ^ reversed_char_index) * char_value
                //          A = 1 ------ Z = 26 ------ AA = 27 ------ AZ = 54
                // 64 because there 'A' starts at index 65 and we want to give 'A' the value 1.
                result += Math.Pow(26, sxCol.Length - i).ToSafeInt() *  (_c.ToSafeInt() - 64);
            }

            return result;
        }
    } 

And you would call your code as such:

 int iResult = “A”.Excelcify();
Debug.Assert(res == 0);
iResult = "Z".Excelcify();
Debug.Assert(res == 25);
iResult = "AA".Excelcify();
Debug.Assert(res == 26);

 

Thus “AAA” = 702, and “XFD” = 16383.

That is exactly 2^14 cells for those binary folk!

Tagged , , , , ,

Interesting Links

I recently came across this gem on Hatim’s Development Blog.  It’s a post titled 5 Very Useful C# Attributes.

I’m really impressed with his example of the DebuggerDisplayAttribute. Very useful if you don’t want to keep drilling down while debugging.

 

DebuggerDisplayAttribute

Namespace: System.Diagnostics

Usage: The DebuggerDisplayAttribute can be a sweet shortcut to avoid expanding the object to get to the value of a given property when debugging. All you have to do is mouse over the object and any property defined in the attribute will show up with it’s value.

image

Sample:

[DebuggerDisplay("ProductName = {ProductName},ProductSKU= {ProductSKU}")]
public class Product
{
    public string ProductName { get; set; }
    public string ProductSKU { get; set; } 
}

Tagged , ,

Property Copy in .Net

I came across a question on StackOverflow that asked how you can copy Properties from one class to the other assuming they had similar properties.

public class Student
{
    public int Id {get; set;}
    public string Name {get; set;}
    public IList<Course> Courses{ get; set;}
}

public class StudentDTO
{
    public int Id {get; set;}
    public string Name {get; set;}
    public IList<CourseDTO> Courses{ get; set;}
}

I would like to copy value from Student class to StudentDTO class:

var student = new Student();
StudentDTO studentDTO = student;

How can I do that by reflection or other solution?

The code someone posted on there linked to Miscellaneous Utility Library and that Property Copy was awesomely constructed. Have a gander at the result below and tell me it doesn’t blow your mind!!

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;
using System.Linq.Expressions;

namespace ConsoleApplication1
{
    class Program
    {
        public class Student
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public IList<int> Courses { get; set; }
            public static implicit operator Student(StudentDTO studentDTO)
            {
                return PropertyCopy<Student>.CopyFrom(studentDTO);
            }
        }

        public class StudentDTO
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public IList<int> Courses { get; set; }
            public static implicit operator StudentDTO(Student student)
            {
                return PropertyCopy<StudentDTO>.CopyFrom(student);
            }
        }


        static void Main(string[] args)
        {
            Student _student = new Student();
            _student.Id = 1;
            _student.Name = "Timmmmmmmmaaaahhhh";
            _student.Courses = new List<int>();
            _student.Courses.Add(101);
            _student.Courses.Add(121);

            StudentDTO itemT = _student;

            Console.WriteLine(itemT.Id);
            Console.WriteLine(itemT.Name);
            Console.WriteLine(itemT.Courses.Count);
        }


    }


    // COOLEST PIECE OF CODE FROM - http://www.yoda.arachsys.com/csharp/miscutil/

    /// <summary>
    /// Generic class which copies to its target type from a source
    /// type specified in the Copy method. The types are specified
    /// separately to take advantage of type inference on generic
    /// method arguments.
    /// </summary>
    public class PropertyCopy<TTarget> where TTarget : class, new()
    {
        /// <summary>
        /// Copies all readable properties from the source to a new instance
        /// of TTarget.
        /// </summary>
        public static TTarget CopyFrom<TSource>(TSource source) where TSource : class
        {
            return PropertyCopier<TSource>.Copy(source);
        }

        /// <summary>
        /// Static class to efficiently store the compiled delegate which can
        /// do the copying. We need a bit of work to ensure that exceptions are
        /// appropriately propagated, as the exception is generated at type initialization
        /// time, but we wish it to be thrown as an ArgumentException.
        /// </summary>
        private static class PropertyCopier<TSource> where TSource : class
        {
            private static readonly Func<TSource, TTarget> copier;
            private static readonly Exception initializationException;

            internal static TTarget Copy(TSource source)
            {
                if (initializationException != null)
                {
                    throw initializationException;
                }
                if (source == null)
                {
                    throw new ArgumentNullException("source");
                }
                return copier(source);
            }

            static PropertyCopier()
            {
                try
                {
                    copier = BuildCopier();
                    initializationException = null;
                }
                catch (Exception e)
                {
                    copier = null;
                    initializationException = e;
                }
            }

            private static Func<TSource, TTarget> BuildCopier()
            {
                ParameterExpression sourceParameter = Expression.Parameter(typeof(TSource), "source");
                var bindings = new List<MemberBinding>();
                foreach (PropertyInfo sourceProperty in typeof(TSource).GetProperties())
                {
                    if (!sourceProperty.CanRead)
                    {
                        continue;
                    }
                    PropertyInfo targetProperty = typeof(TTarget).GetProperty(sourceProperty.Name);
                    if (targetProperty == null)
                    {
                        throw new ArgumentException("Property " + sourceProperty.Name + " is not present and accessible in " + typeof(TTarget).FullName);
                    }
                    if (!targetProperty.CanWrite)
                    {
                        throw new ArgumentException("Property " + sourceProperty.Name + " is not writable in " + typeof(TTarget).FullName);
                    }
                    if (!targetProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
                    {
                        throw new ArgumentException("Property " + sourceProperty.Name + " has an incompatible type in " + typeof(TTarget).FullName);
                    }
                    bindings.Add(Expression.Bind(targetProperty, Expression.Property(sourceParameter, sourceProperty)));
                }
                Expression initializer = Expression.MemberInit(Expression.New(typeof(TTarget)), bindings);
                return Expression.Lambda<Func<TSource,TTarget>>(initializer, sourceParameter).Compile();
            }
        }
    }
}
Tagged , , , ,