Thursday, May 10, 2007
by Thad Smith

This past Tuesday I did a small presentation on WCF at PDANUGHere are the files from that presentation.

Remember to sign up with PDANUG for information on events or subscribe to the RSS Feed.

Posted on Thursday, May 10, 2007 10:08:19 AM (Eastern Standard Time, UTC-05:00)  #   Comments [1] | Trackback
 Tuesday, May 08, 2007
by Thad Smith

I was working with a ORM system the other day and kept running into problems with the Nullable types when I called Convert.ChangeType().

[InvalidCastException: Invalid cast from 'System.DateTime' to ' System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'

A Quick Google search came up with a number of entries.  This is a known problem in the CLR.

Here a couple or other blogs on this and below is my version of the code:

Peter Johnson's Blog
The PumaCode.org Blog

        public static object ChangeType(object value, Type conversionType)
        {
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (value == null)
                    return null;

                NullableConverter nullableConverter = new NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }

            if (conversionType.IsEnum)
                return Enum.ToObject(conversionType, value);
            else
                return Convert.ChangeType(value, conversionType);
        }

Posted on Tuesday, May 08, 2007 10:08:17 AM (Eastern Standard Time, UTC-05:00)  #   Comments [0] | Trackback
 Tuesday, April 03, 2007
by Thad Smith

Saurah Gupta published an article comparing WCF with existing Distributed Communication Technologies

There are also a article on WF performance here.

Posted on Tuesday, April 03, 2007 9:33:59 AM (Eastern Standard Time, UTC-05:00)  #   Comments [0] | Trackback
 Tuesday, March 13, 2007
by Thad Smith

If you enjoy your music over the web, this should be of interest.  The Copyright Royalty Board has raised its rates on streaming broadcast.  A number of these companies would have to pay more than 100% of their total income.

Wired News

Here is a some information posted about the proposed pricing:


The new rates, just announced today, are retroactive to 2006, and increase rapidly each year. The rates per performance are as follows:

$0.0008 in 2006
$0.0011 in 2007
$0.0014 in 2008
$0.0018 in 2009

At first glance, those seem like fairly small numbers: eight ten-thousandths of a dollar, eleven ten-thousandths of a dollar, and so on. When you actually do the math, however, you see the truth revealed. The average radio station plays 16 songs in an hour. Under this system, that would be equivalent to 16 performances.

0.0011 x 16 = 0.0176

Still a fairly small number - under two cents. But now assume this station has 1000 listeners. That means that, in one hour, the station would be billed for 16,000 performances.

0.0011 x 16000 = 17.60

That’s $17.60 an hour. Now we’re starting to see how expensive this truly is. Multiply that by 24 hours a day.

17.60 * 24 = 422.40 


$422.40 a day. But there’s 365 days in a year.

422.40 * 365 = 154176

$154,176 for the year in performance royalties alone for a station with 1000 listeners. And that’s just for 2007: it gets even worse. In 2008, the cost rises to $193,536 for the year. In 2009, it goes up to $248,832. Even for a much smaller station, the royalties owed are huge.

Of course, these figures don’t include the other set of rights that Internet radio stations are required to purchase, which must be licensed separately from an agency like SESAC or ASCAP, or the cost of bandwidth and server capacity. When you add all these costs together, you can easily see why nobody, save perhaps a megacorporation like AOL or Yahoo, could afford to pay these rates.

Posted on Tuesday, March 13, 2007 9:20:59 AM (Eastern Standard Time, UTC-05:00)  #   Comments [1] | Trackback
 Monday, March 12, 2007
by Thad Smith

Source Code

This post is a repeat of the presentation I gave for the Pee Dee Area .NET User Group this past September.

Ever wanted to take some standard code and place it around a method, maybe a way to time the method, or use a database connection without creating one in each method.  Yes, you can use a try..catch..finally block and make calls to some other methods, but how is that on managing the connection?

So, how do we pull this off in .NET?  With the use of a few interfaces and classes from System.Runtime.Remoting and 4 custom classes we can accomplish our goal.  We start with our base class which we will descend from ContextBoundObject and decorate with our InjectionAttribute (descendant of ContextAttribute).  The ContextBoundObject will create a transparent-proxy which receives all the invocations of the target.  It then serializes the call stack and passes it to a real-proxy (which it also created).  This real-proxy calls an implementation of IMessageSink.

The following is a list and brief description of the class's responsibility:

InjectionAttribute: ContextAttribute
This attribute is used to decorate InjectionBase.  This attribute allows all methods and field-setters to be injected.  This attribute will be used to add an InjectionProperty to the context. 

InjectionProperty: IContextProperty, IContributeServerContextSink
This class is used to insert a new message in front of the current message chain and check the context.

InjectionSink: IMessageSink
This class is used to process the method invocations of the sink chain.  We limit our injection to only methods. When creating an instance of InjectionSink a reference to the next message sink is passed in so that all the sinks can be chained together.

[Injection]
InjectionBase: ContextBoundObject
The class where we bring everything back together.  This class contains the 4 abstract methods we will use to inject our code.  PressProcess, PostProcess, ProcessException, and ProcessSuccess.  These methods will be called from the ProcessMethod which is responsible to invoking the method.

We know create base class implementations of InjectionBase.  There are 2 included in the source, MyClass.cs that demonstrates the basic use and DBInjection.cs which implements a database connection.

The following is a create step-through of what occurs when creating and running a method.

InjectionBase ib = new InjectionBase()
Before the class constructor is called the framework instantiates InjectionAttribute and calls the GetPropertiesForNewContext passing a reference to IConstructionCallMessage.  In this method an instance of InjectionProperty is created and added to the context.  Now InjectionProperty.Freeze and InjectionProperty.IsNewContextOK are called.  Finally, the contructor is called.

ib.DoSomeMethod(param)
Calls InjectionProperty.GetServerContextSink through the IContributeServerContextSink.  This returns a newly created instance of InjectionSink which is used to call InjectionSink.SyncProcessMessageInjectionSink.SyncProcessMessage fires the ProcessMessage on the InjectionBase which invokes our method and injection.

Posted on Monday, March 12, 2007 1:45:34 PM (Eastern Standard Time, UTC-05:00)  #   Comments [0] | Trackback
 Tuesday, February 13, 2007
by Thad Smith

I seem to use numerous Enumerated types and use these to fill in list boxes.  The problem is, a few of these types do not have a nice name for the user.  Problem solved, simply created a class that could decorate the enumeration and retun a text representation.

    [AttributeUsage(AttributeTargets.Field)]
    public class EnumTextAttribute : Attribute
    {
        private string text;
        public string Text
        {
            get { return text; }
        }

        public EnumTextAttribute(string text)
        {
             this.text = text;
        }
    }

    public static class EnumHelper
    {
        public static void IsEnumValid(Type enumType, object value)
        {
            if (!Enum.IsDefined(enumType, value))
                throw new Exception(value.ToString());
        }

        public static string GetText(Enum e)
        {
            FieldInfo fieldInfo = e.GetType().GetField(e.ToString());
            object[] attrs = fieldInfo.GetCustomAttributes(typeof(EnumTextAttribute), false);
            if (attrs.Length == 0)
                return e.ToString();
            else
                return ((EnumTextAttribute)attrs[0]).Text;
        }

        public static T GetValue<T>(string text)
        {
            MemberInfo[] members = typeof(T).GetMembers();
            foreach (MemberInfo mi in members)
            {
                object[] attrs = mi.GetCustomAttributes(typeof(EnumTextAttribute), false);
                if (attrs.Length == 1)
                {
                    if (((EnumTextAttribute)attrs[0]).Text == text)
                        return (T)Enum.Parse(typeof(T), mi.Name);
                }
                else
                {
                    if(mi.Name == text)
                        return (T)Enum.Parse(typeof(T), mi.Name);
                }
            }           
            throw new ArgumentOutOfRangeException("text", text, "The text passed does not correspond to an attributed enum value.");
        }
    }

 

With the above class I now define the enumeration as follows and use the EnumHelper class to translate between Text and Value.

    public enum DeliverByType
    {       
        None = 0,
        Mail,
        [EnumText("E-Mail")]
        Email, //E-Mail
       
[EnumText("Mail and E-Mail")]
        Both //Mail and E-mail
    }

Posted on Tuesday, February 13, 2007 10:19:32 AM (Eastern Standard Time, UTC-05:00)  #   Comments [0] | Trackback
 Wednesday, January 31, 2007
by Thad Smith

Working with some older code I found to make a connection and iterate through took a bit of repetitous code.  

    string sql = "SELECT * FROM Version WHERE [Field1] = @Field1 AND [Field2] = @Field2";
    using (SqlConnection connection = new SqlConnection(connectionStr))
    {
        connection.Open();
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = sql;
            command.CommandType = CommandType.Text;
            command.Parameters.AddWithValue("@Field1", "Value1");
            command.Parameters.AddWithValue("@Field2", "Value2");
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    //Read the Fields
                }
            }
        }
    }

 

As stated by a good friend: "Less Code, works better".  So it was decided (by me) to change this to a simple Sql Reader.  This new class implements IDisposable and creates the SqlConnection and SqlCommand on creation then disposes them when the instance is disposed.

    public class SimpleSqlReader: IDisposable
    {
        SqlConnection connection;
        SqlCommand command;
        SqlDataReader reader;

        public SimpleSqlReader(string connectionString, string commandText, bool isStoredProcedure)
        {           
            this.connection = new SqlConnection(connectionString);
            this.connection.Open();

            this.command = this.connection.CreateCommand();
            this.command.CommandText = commandText;
            if (isStoredProcedure)
                this.command.CommandType = CommandType.StoredProcedure;
            else
                this.command.CommandType = CommandType.Text;
        }

        public SimpleSqlReader AddParam(string parameterName, object value)
        {
            this.command.Parameters.AddWithValue(parameterName, value);           
            return this;
        }

        public void Execute()
        {
            reader = command.ExecuteReader();
        }

        public SqlDataReader Reader
        {
            get { return reader; }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (reader != null && !reader.IsClosed)
            {
                reader.Close();
                reader.Dispose();
            }
            command.Dispose();
            connection.Close();
            connection.Dispose();
        }

        #endregion
    }

OK so it may not be less code now, but over the course of the project it will be.

    using (SimpleSqlReader reader = new SimpleSqlReader(connectionStr, sql, false))
    {
        reader.AddParam("@Field1", "Value1")
            .AddParam("@Field2", "Value2")
            .Execute();
        while (reader.Reader.Read())
        {
            //Read the Fields
        }
    }

Posted on Wednesday, January 31, 2007 3:16:48 PM (Eastern Standard Time, UTC-05:00)  #   Comments [2] | Trackback