DynamicObject

I ran across this the other day when looking at some code from the Internet.  I hadn’t heard of DynamicObject before, so I thought I’d investigate.  The definition from MSDN states that it “Provides a base class for specifying dynamic behavior at run time. This class must be inherited from; you cannot instantiate it directly.”

You can think of it as something similar to the .NET Object class, except that it enables you to define which methods or properties can be performed at run time.

For other classes, you will get a compile time error when you’ve written code against a nonexistent method.  Classes that inherit from DynamicObject will not, but will be instead evaluated at run time.  If the dynamic class hasn’t implemented the method or coded for nonexistent methods, then a run time error will be thrown.

Here’s an example:

using System;
using System.Dynamic;

namespace DynamicObjectExample
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic test = new MyDynamicClass();

            int result = test.MyAdder(1, 2);

            Console.WriteLine("Result: " + result);
            Console.ReadLine();
        }
    }

    class MyDynamicClass : DynamicObject
    {

    }
}

The MyDynamicClass inherits from DynamicObject and is completely empty.  However, the Main method is calling a method called MyAdder which sonds like it adds two integer arguments.  When this code is compiled, there’s no errors, but when we run we get a “RunTimeBinderException was unhandled error” which states that “‘DynamicObjectExample.MyDynamicClass’ does not contain a definition for ‘MyAdder’.”

To add logic for situations where a method is invoked which doesn’t exist, the TryInvokeMember method can be overridden.

using System;
using System.Dynamic;

namespace DynamicObjectExample
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic test = new MyDynamicClass();

            int result = test.MyAdder(1, 2);

            Console.WriteLine("Result: " + result);
            Console.ReadLine();
        }
    }

    class MyDynamicClass : DynamicObject
    {
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            Console.WriteLine(binder.Name + "  Method not present in this  class ");
            result = 0;
            return true;
        }
    }
}

The result of the above is

“MyAdder Method not present in this class

Result: 0”

with no exceptions.  Now let’s see what happens when we actually implement the MyAdder method on MyDynamicClass.

using System;
using System.Dynamic;

namespace DynamicObjectExample
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic test = new MyDynamicClass();

            int result = test.MyAdder(1, 2);

            Console.WriteLine("Result: " + result);
            Console.ReadLine();
        }
    }

    class MyDynamicClass : DynamicObject
    {
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            Console.WriteLine(binder.Name + "  Method not present in this  class ");
            result = 0;
            return true;
        }

        public int MyAdder(int x, int y)
        {
            return x + y;
        }
    }
}

The result of the above will be “Result: 3” which is what we expect :).

TryGetMember and TrySetMember are other virtual members on DynamicClass that allow you to add logic for getting and setting properties that do not exist.

Clean Code Tips #1-3: Methods Should be Small, Do Only 1 Thing, and 1 Level of Abstraction

#1:  Methods should be small.  Ideally, they should hardly ever be 20 lines long.  This forces the developer to create more methods that can shared and tested more easily.  Smaller methods will also result in less unit tests for each method since there’s less logic applied.

#2:  Keeping method small also helps to enforce the concept that methods should only do one thing.  The more logic that exists in a method will likely limit it’s ability to be shared and reused.  It also ensures that changes to the method will only affect the single purpose of the method.

#3:  One level of abstraction per method is also a good rule to follow.  This helps others understand what the method is doing which prevents bugs from getting into the software.

Following the above tips will result in more methods, but it doesn’t necessarily result in more code since methods can be shared more easily.

Most Used Enumerable(T) Methods

Here’s the Enumerable methods I use the most.  All of these are available in the .NET 4.0 Framework.

Enumerable.Any() – Determines whether a sequence contains any elements.

Enumerable.Empty<T>() – Returns an empty IEnumerable<T> that has the specified type argument.

Enumerable.Distinct() – Returns distinct elements from a sequence by using the default equality comparer to compare values.

Enumerable.FirstOrDefault() – Returns the first element of a sequence, or a default value if the sequence contains no elements.

Enumerable.Count() – Returns the number of elements in a sequence.

Enumerabel.LastOrDefault() – Returns the last element of a sequence, or a default value if the sequence contains no elements.

Enumerable.Max() – Returns the maximum value in a generic sequence.

Enumerable.Min() – Returns the minimum value in a generic sequence.

Enumerable.Select() – Projects each element of a sequence into a new form.

Enumerable.ToArray() – Creates an array from a IEnumerable<T>.

Enumerable.Where() – Filters a sequence of values based on a predicate.

Here’s a link to the MSDN site that lists all the available methods

Tuple

Tuple is a new class in the .Net 4.0 framework which allows you to hold up to 8 components in a single class.  The alternative is creating a specific class with properties for each component.  This makes this class ideal for the following situations:

1.  Returning multiple values from a method without the use of out parameters

2.  Pass multiple values to a method using a single class.

3.  Collections of Tuples can be used to represent database information or array data.

4.  Easy access and manipulation of a data set.

Here’s an example using Tuple<T1, T2>

class Program
    {
        static void Main(string[] args)
        {
            int dividend, divisor;
            Tuple<int, int> result;

            dividend = 136945; divisor = 178;
            result = IntegerDivide(dividend, divisor);
            if (result != null)
                Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}",
                                  dividend, divisor, result.Item1, result.Item2);
            else
                Console.WriteLine(@"{0} \ {1} = <Error>", dividend, divisor);

            dividend = Int32.MaxValue; divisor = -2073;
            result = IntegerDivide(dividend, divisor);
            if (result != null)
                Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}",
                                  dividend, divisor, result.Item1, result.Item2);
            else
                Console.WriteLine(@"{0} \ {1} = <Error>", dividend, divisor);

            Console.ReadLine();

        }

        private static Tuple<int, int> IntegerDivide(int dividend, int divisor)
        {
            try
            {
                int remainder;
                int quotient = Math.DivRem(dividend, divisor, out remainder);
                return new Tuple<int, int>(quotient, remainder);
            }
            catch (DivideByZeroException)
            {
                return null;
            }
        }

    }

How to Add Icons to Blogroll Links

I figured out a tricky way to show a websites icon next to the link in your blog roll.  I’m using Firefox to do this.

1.  Go to website’s homepage.

2.  Right click in an empty space and select “View Page Info”.  It should be directly below “View Page Source”

3.  You should see a popup for something like this:

4.  Next, click on the “Media” tab and look for the line that ends with “…favicon.ico”.

5.  Now go to your blog dashboard and go to “Links”.

6.  Select or create the link for the website you want and scroll down to the Advanced section and paste the address in the first field for “Image Address”.

ThreadPool

I discovered this class the other day.  It’s actually been around for a while as part of the .NET 2.0 framework.  You can use it to run a method in a different thread.  Here’s a description from the MSDN site.

A thread pool is a collection of threads that can be used to perform a number of tasks in the background. (See Using Threading for background information.) This leaves the primary thread free to perform other tasks asynchronously.

Thread pools are often employed in server applications. Each incoming request is assigned to a thread from the thread pool, so the request can be processed asynchronously, without tying up the primary thread or delaying the processing of subsequent requests.

Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task.

Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are placed in queue until they can be serviced as threads become available.

Here’s a very simple example that illustrates how the main execution thread continues without waiting for the “DoSomething” thread to complete.  ≈

    class ThreadPoolExample
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Start");
            ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomething), args);

            Console.WriteLine("Finish");

            Console.ReadLine();
        }

        private static void DoSomething(object args)
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(100);
                Console.WriteLine(i);
            }
        }
    }

Here’s the output:

 

 

 

 

 

 

If we needed to know when the work was finished from Threadpool, then a ManualResetEvent could be passed into a WaitHandle like the example described here.

A Few .NET String Functions (Split, Join, IsNullOrEmpty, IsNullOrWhiteSpace)

Here’s some of my favorite String functions in .NET.

    class StringFunctions
    {
        static void Main(string[] args)
        {
            // Check for Null or Empty
            const string emptyString = "";
            if (String.IsNullOrEmpty(emptyString))
                Console.WriteLine("String is Empty or Null");

            // Join an array of integers together
            Collection array = new Collection() { 1, 2, 3 };
            Console.WriteLine(String.Join(",", array));

            // Split a string into an array
            ICollection fullStringArray = "The cat in the hat".Split(' ');
            foreach (var element in fullStringArray)
                Console.WriteLine(element);

            // Split ignoring emtpy spaces
            const string numberList = "1,2,3,4,,6";
            ICollection trimmedStringArray = numberList.Split(new[] { ',' }, numberList.Length, StringSplitOptions.RemoveEmptyEntries);
            foreach (var element in trimmedStringArray)
                Console.WriteLine(element);

            Console.ReadLine();
        }
    }

Output:

 

 

 

 

 

 

Here’s a link to an article with more examples for Split.

IsNullOrWhiteSpace is new in .NET 4.0. It’s similar to IsNullOrEmpty, but it also will catch strings that contain only empty spaces. In prior versions, you would have to trim the string prior to calling IsNullOrEmpty if you wanted to treat strings with only empty spaces as empty strings.