Three Project Releases Today

I've released updates to both Craig's Utility Library as well as HaterAide ORM. The utility library contains additions in functionality including:

  • Javascript minification
  • Image related classes:
    • Converter from an image to ASCII art
    • Ability to draw rounded rectangles
    • Take the negative of an image
    • Ability to get the blue, red, and green filters
    • Ability to adjust brightness, gamma, and contrast
    • Ability to add noise
    • Ability to And/Or/Xor images together
    • Ability to colorize black and white images
    • Simple motion detection class
    • Cellular map generator
  • Ability to make a shallow copy of an object in the Reflection class
  • SOAP serialization helper
  • Function to determine if something is a valid email address in the StringHelper class
Not to mention a couple of fixes and improvements to the various other classes. HaterAide on the other hand is simply a bunch of bug fixes, including some table/stored procedure naming issues, fixes to the SelectWhere function, a fix for ManyToMany/ManyToOne nested classes that are of the same type,  and a couple others. So if you've tried out the original version, definitely download this update.

On top of these two releases, I also released a new project that I'm calling YABOV (or Yet Another Business Object Validator). I know we don't need another one of these but I figured it might help someone out and it was a decent chunk of my current project that could be spun off and shared with everyone. Anyway, the various links are:

kick it on DotNetKicks.com   Shout it
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListEmail

Posted by: James Craig
Posted on: 7/29/2009 at 11:12 AM
Tags: , , ,
Categories: C#
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Shallow Copy of an Object Using Reflection

A couple days ago I was exterminating the French (Medieval 2: Total War), when I realized that there was a flaw in the caching scheme that I set up for the HaterAide ORM. Mainly when I save an item (an update, not an insert), I overwrite the object with whatever is passed in. This however could lead to an object being in there multiple times as it would save all of the current information, including objects. This could lead to a lot of information being out of sync... For instance if I have object A which holds object B and I save A, caching A. Then lets say that I update B and save B, caching B seperately. When I load A, because the ORM's caching system is dumb, it wont know that B has been updated and simply give us the out of date information.

So after a bit of thought, I came to the conclusion that I needed to make a copy. But really only a shallow copy, and actually it needed to be a shallow copy that ignored objects... So I came up with a couple functions to help me accomplish this:

        /// <summary>
        /// Makes a shallow copy of the object
        /// </summary>
        /// <param name="Object">Object to copy</param>
        /// <param name="SimpleTypesOnly">If true, it only copies simple types (no classes, only items like int, string, etc.), false copies everything.</param>
        /// <returns>A copy of the object</returns>
        public static object MakeShallowCopy(object Object,bool SimpleTypesOnly)
        {
            Type ObjectType = Object.GetType();
            PropertyInfo[] Properties = ObjectType.GetProperties();
            FieldInfo[] Fields = ObjectType.GetFields();
            object ClassInstance = Activator.CreateInstance(ObjectType);

            foreach (PropertyInfo Property in Properties)
            {
                try
                {
                    if (SimpleTypesOnly)
                    {
                        SetPropertyifSimpleType(Property, ClassInstance, Object);
                    }
                    else
                    {
                        SetProperty(Property, ClassInstance, Object);
                    }
                }
                catch { }
            }

            foreach (FieldInfo Field in Fields)
            {
                try
                {
                    if (SimpleTypesOnly)
                    {
                        SetFieldifSimpleType(Field, ClassInstance, Object);
                    }
                    else
                    {
                        SetField(Field, ClassInstance, Object);
                    }
                }
                catch { }
            }

            return ClassInstance;
        }

        /// <summary>
        /// Copies a field value
        /// </summary>
        /// <param name="Field">Field object</param>
        /// <param name="ClassInstance">Class to copy to</param>
        /// <param name="Object">Class to copy from</param>
        private static void SetField(FieldInfo Field, object ClassInstance, object Object)
        {
            try
            {
                if (Field.IsPublic)
                {
                    Field.SetValue(ClassInstance, Field.GetValue(Object));
                }
            }
            catch { }
        }

        /// <summary>
        /// Copies a field value
        /// </summary>
        /// <param name="Field">Field object</param>
        /// <param name="ClassInstance">Class to copy to</param>
        /// <param name="Object">Class to copy from</param>
        private static void SetFieldifSimpleType(FieldInfo Field, object ClassInstance, object Object)
        {
            Type FieldType = Field.FieldType;
            if(Field.FieldType.FullName.StartsWith("System.Collections.Generic.List", StringComparison.CurrentCultureIgnoreCase))
            {
                FieldType=Field.FieldType.GetGenericArguments()[0];
            }

            if (FieldType.FullName.StartsWith("System"))
            {
                SetField(Field, ClassInstance, Object);
            }
        }

        /// <summary>
        /// Copies a property value
        /// </summary>
        /// <param name="Property">Property object</param>
        /// <param name="ClassInstance">Class to copy to</param>
        /// <param name="Object">Class to copy from</param>
        private static void SetPropertyifSimpleType(PropertyInfo Property, object ClassInstance, object Object)
        {
            Type PropertyType = Property.PropertyType;
            if (Property.PropertyType.FullName.StartsWith("System.Collections.Generic.List", StringComparison.CurrentCultureIgnoreCase))
            {
                PropertyType = Property.PropertyType.GetGenericArguments()[0];
            }

            if (PropertyType.FullName.StartsWith("System"))
            {
                SetProperty(Property, ClassInstance, Object);
            }
        }

        /// <summary>
        /// Copies a property value
        /// </summary>
        /// <param name="Property">Property object</param>
        /// <param name="ClassInstance">Class to copy to</param>
        /// <param name="Object">Class to copy from</param>
        private static void SetProperty(PropertyInfo Property, object ClassInstance, object Object)
        {
            try
            {
                if (Property.GetSetMethod() != null && Property.GetGetMethod() != null)
                {
                    Property.SetValue(ClassInstance, Property.GetValue(Object, null), null);
                }
            }
            catch { }
        }

I know it's a bit of code but in order to use it, you simply call MakeShallowCopy, feeding it the object and whether or not you want it to copy simple types only (I should really call it System types...) or everything. It then gets the list of properties and fields from the object and procedes to copy that information to a newly created object which it then passes back. It's not perfect mind you, but it should do the job for my needs and hopefully can be of some use to someone else out there. Anyway, take a look, leave feedback, and happy coding.

kick it on DotNetKicks.com   Shout it
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListEmail

Posted by: James Craig
Posted on: 7/28/2009 at 7:50 AM
Tags: , , ,
Categories: C#
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Deserializing/Serializing SOAP Messages in C#

For those of you that don't know what SOAP is, SOAP is an XML based syntax that allows programs communicate with one another. In otherwords, just like RSS, etc. it is just another XML document with specific syntax. There really isn't much to it, but serializing/deserializing them can be a pain. Luckily for us .Net has a built in class for us. Specifically in the System.Runtime.Serialization.Formatters.Soap namespace (you may need to add a reference to it). So let's look at how to use this class:

        /// <summary>
        /// Converts a SOAP string to an object
        /// </summary>
        /// <typeparam name="T">Object type</typeparam>
        /// <param name="SOAP">SOAP string</param>
        /// <returns>The object of the specified type</returns>
        public static T SOAPToObject<T>(string SOAP)
        {
            if (string.IsNullOrEmpty(SOAP))
            {
                throw new ArgumentException("SOAP can not be null/empty");
            }
            try
            {
                using (MemoryStream Stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(SOAP)))
                {
                    SoapFormatter Formatter = new SoapFormatter();
                    return (T)Formatter.Deserialize(Stream);
                }
            }
            catch (Exception a)
            {
                throw a;
            }
        }

        /// <summary>
        /// Converts an object to a SOAP string
        /// </summary>
        /// <param name="Object">Object to serialize</param>
        /// <returns>The serialized string</returns>
        public static string ObjectToSOAP(object Object)
        {
            if (Object == null)
            {
                throw new ArgumentException("Object can not be null");
            }
            try
            {
                using (MemoryStream Stream = new MemoryStream())
                {
                    SoapFormatter Serializer = new SoapFormatter();
                    Serializer.Serialize(Stream, Object);
                    Stream.Flush();
                    return UTF8Encoding.UTF8.GetString(Stream.GetBuffer(), 0, (int)Stream.Position);
                }
            }
            catch (Exception a)
            {
                throw a;
            }
        }

It's pretty simple and if you've done XML or binary serialization in .Net, it's going to look fairly similar. Anyway, I can't believe how long it took me before I ran into a project that actually required SOAP. But I finally ran into one and decided to go about writing a couple of generic functions to help me out in serializing and deserializing the objects and will hopefully help you out as well. So try it out, leave feedback, and happy coding.

kick it on DotNetKicks.com   Shout it
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListEmail

Posted by: James Craig
Posted on: 7/24/2009 at 12:17 PM
Tags: , ,
Categories: C#
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed