Tech Talk A software developer on all things tech, and then some

5Aug/140

Combining Objects in C#

There has been a few times I've need to copy models to view models, or very similar classes to each other, but wanted to clean up the code in the process. The result of that is a start to a helper method below to "combine" objects in C#. Code will stay static on this post. To retrieve updated code, visit via GitHub.

public static class ObjectJoin
    {
        /// <summary>
        /// Attempts to combine values from two different objects with the same property names into one object
        /// </summary>
        /// <param name="firstObject">The object in which we will return with combined values</param>
        /// <param name="secondObject">The object in which we will be pulling values from</param>
        /// <param name="sourceOverwrite">If we overwrite the value from the first object if one already exists (Default is true)</param>
        /// <returns>The first object with combined values from the second object</returns>
        public static object JoinObjects(object firstObject, object secondObject, bool sourceOverwrite = true)
        {
            if(firstObject == null || secondObject == null)
            {
                throw new ArgumentException("One of the objects passed to JoinObjects is null");
            }

            // Read in first object information
            var firstObjectHash = GetObjectPropertyHash(firstObject);

            // Read in the second object information
            var secondObjectHash = GetObjectPropertyHash(secondObject);

            foreach (var item in firstObjectHash)
            {
                if (secondObjectHash.ContainsKey(item.Key) && (secondObjectHash[item.Key] != null || sourceOverwrite))
                {
                    SetObjectProperty(ref firstObject, item.Key, secondObjectHash[item.Key]);
                }                
            }
            return firstObject;
        }

        /// <summary>
        /// Retrieves the parameter and value list of an inputed object
        /// </summary>
        /// <param name="obj">The object which to identify the properties and values</param>
        /// <returns>A dictionary of the parameter names as the key, and property values as values</returns>
        private static Dictionary<string,object> GetObjectPropertyHash(object obj)
        {
            Type objType = obj.GetType();
            Dictionary<string, object> hashTable = new Dictionary<string, object>();
            foreach (PropertyInfo property in objType.GetProperties())
            {
                hashTable.Add(property.Name, property.GetValue(obj, null));
            }
            return hashTable;
        }

        /// <summary>
        /// Attempts to set a value to a property dynamically 
        /// </summary>
        /// <param name="obj">The object which you are dynamically setting a property to</param>
        /// <param name="propertyName">The name of the objects property to assign the value to</param>
        /// <param name="value">The value to assign to the object's property</param>
        private static void SetObjectProperty(ref object obj, string propertyName, object value)
        {
            PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName);            
            if (propertyInfo != null && value != null && propertyInfo.GetSetMethod() != null)
            {
                try
                {
                    if (value.GetType().GetInterface("IConvertible") != null)
                    {
                        value = value.GetType().FullName == propertyInfo.PropertyType.FullName ? value : Convert.ChangeType(value, propertyInfo.PropertyType);
                        propertyInfo.SetValue(obj, value);
                    }
                }
                catch
                {
                    throw new Exception(string.Format("An error occurred when attempting to set the value of {0} of type {1}", propertyName, obj.ToString()));
                }
            }
        }
    }
Tagged as: , , No Comments
15May/130

.NET Decompilers

I needed a way to quick, free way to check what compiled in a DLL on something that built in a big project. It seemed like no matter how I built, it was getting some old code. So, I googled and some big names had some free decompilers already available. Telerik has JustDecompile, and JetBrains has dotPeek. While both were good, they had their differences.

Telerik's JustDecompile had asked me to install some trial versions of their other software during installation, so heads up you might want to uncheck everything besides JustDecompile since it's the only totally free item they offer in the installation. When I ran it, it was very smooth, and quick to decompile all the Dlls I threw at it. The code was well formatted and easy to transverse. 

JustDecompile

JetBrains' dotPeek installed quick and easy, and good to go within a minute. It was a little bit slower than Telerik's solution, but for the most part a lot faster than products I've seen in the  past. One downside I noticed right away navigating through my code is that the formatting was off. I got a lot of "ISSUE: reference to a compiler-generated field" and other similar error messages, while Telerik's seemed to handle everything correctly. The code that was decompiled however was closest to what I had written, which helped me recognize any errors relatively quickly vs Teleriks', which was off on quite of a few statements (logically was the same, just the code was slightly different... ie if statement logic).

JetBrains

Basically, I would suggest downloading both. They are both pretty lightweight for what they do and it's always nice to get a second set of tools to offer a different look. Both are done well and worth your time. Good luck and happy coding!

23Mar/110

Fixing A Blue Filled Checkbox in .Net

If you ever seen the above check mark, you are probably wondering what the heck is going on. First off it's not checked or checked, some in between state where it's just filled with a blue square. Second off you even, most likely, have a variable bound to it, and yet it still displays as this!

The issue is that the variable that you have it bound to is null. This is the default way to show null in a check box, not just an empty square like you would expect such as when the value is equal to false. There is a solution you can try. If you are binding to a database and using SQL, you can use the following code to set all the values to null, then add a default of zero to the column to prevent the blue box from showing up.


UPDATE tableName
SET columnName= 0
WHERE columnName= null

ALTER TABLE tableName
ADD DEFAULT 0 FOR columnName;

If you are not using SQL, then check in visual studio for what ever data object you are binding to, and set it's default value to zero. (I'm not going to give a tutorial on each way since there are a few).

Hope this helps, and happy coding!

   
%d bloggers like this: