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