18 Apr 2011 @ 10:00 PM 

Here’s a collection of xml extensions I wrote to help make using and navigating xml documents a lot easier.

public static XmlNode FindNode(this XmlDocument doc, string nodeName)
        {
            if (doc == null)
                return null;

            XmlNode node = doc.DocumentElement;
            return node.FindNode(nodeName);
        }

        public static XmlNode FindNode(this XmlNode parentNode, string name)
        {
            if (parentNode == null)
                return null;

            foreach (XmlNode node in parentNode.ChildNodes)
            {
                if (node.Name == name)
                    return node;

                XmlNode foundNode = FindNode(node, name);
                if (foundNode != null)
                    return foundNode;
            }

            return null;
        }

FindNode is a method I use a lot when I’m working with 3rd party api’s. It’s a recursive method that traverses the xml document looking for the first node matching the name specified. This way I can ignore a lot of levels of the document to find the property I’m looking for. For example I’ll skip parent objects to get to the children, hold onto the first node and search for a property on it. If I don’t find what I’m looking for I try the next sibling.

/// Reads an xml file and serializes it to the object specified
public static T FromXmlFile<T>(this string path)
        {
            T result;
            using (TextReader textReader = new StreamReader(path))
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                result = (T)xmlSerializer.Deserialize(textReader);
                textReader.Close();
            }
            return result;
        }

//Serializes the class into an xml file that can be retrieved later.
        public static void ToXmlFile<T>(this T obj, string path)
        {
            using (TextWriter textWriter = !File.Exists(path) ? File.CreateText(path) : new StreamWriter(path))
            {
                var serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(textWriter, obj);
                textWriter.Close();
            }
        }

These two methods I will use to store and retrieve a class from an XML file. It’s good for quick and dirty storage.

Posted By: Boyd
Last Edit: 14 Apr 2011 @ 10:09 PM

EmailPermalinkComments Off
Tags
Tags: , , ,
Categories: .Net, Programming
 14 Apr 2011 @ 9:59 PM 

Here is a quick extension method to sort a collection by a given property specified though generics. The extension method then uses a hashset to determine duplicates. This is excellent when paired with unique ids.

        public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
        {
            HashSet<TKey> knownKeys = new HashSet<TKey>();
            foreach (T element in source)
            {
                if (knownKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }
Posted By: Boyd
Last Edit: 14 Apr 2011 @ 10:31 PM

EmailPermalinkComments Off
Tags
Tags: , , ,
Categories: .Net, Programming
 06 Apr 2011 @ 10:30 PM 

Databinding is a huge part of any MVC or MVVM pattern. Usually this requires using a string representation of a property name in order to determine how a model is bound to its control. Using strings to control this databinding raises a couple key issues.

1.) Refactoring said property will not automatically update the control, nor will you be informed you’re ‘breaking’ the databind by renaming or removing a property.

2.) Finding usages of said property will also not inform you of the databinding. So if you’re wondering how/if a property is used, you might not find out about it until you break it.

These are headaches I prefer to avoid. It’s extra work to back out of changes, and it is also extra work to find and update these string references. I prefer to work less and accomplish more, which is why I looked into Linq for an answer to these issues.

Linq allows us to get the name of a property through an actual use of the property. So when I use resharper or visual studio to look up references, I can see the databinding.

        /// <summary>
        /// Determines the member name of a field or property in the form of a string, given a
        /// strongly-typed expression.
        /// </summary>
        /// <typeparam name="T">The type of the class containing the field or property.</typeparam>
        /// <param name="obj">The object containing the field or property.</param>
        /// <param name="expression">The expression that identifies the field or property.</param>
        /// <returns>The member name in the form of a string.</returns>
        public static string MemberName<T>(this T obj, Expression<Func<T, object>> expression)
        {
            MemberExpression memberExpression;

            if (expression.Body.NodeType == ExpressionType.Convert)
                memberExpression = expression.Body.To<UnaryExpression>().Operand.To<MemberExpression>();
            else
                memberExpression = expression.Body.To<MemberExpression>();

            return memberExpression.Member.Name;
        }

Usage:

<%= Html.TextBox(Model.MemberName(x => x.Name)%>
Posted By: boyd21
Last Edit: 14 Apr 2011 @ 10:28 PM

EmailPermalinkComments Off
Tags
Tags: , , , ,
Categories: .Net, Programming
 08 Dec 2010 @ 1:30 PM 

Here is a static class used to get the name of one of the properties on your class.

public static class MemberName<T>
    {
        public static string Of(Expression<Func<T, object>> expression)
        {
            MemberExpression memberExpression;

            if (expression.Body.NodeType == ExpressionType.Convert)
                memberExpression = expression.Body.To<UnaryExpression>().Operand.To<MemberExpression>();
            else
                memberExpression = expression.Body.To<MemberExpression>();

            return memberExpression.Member.Name;
        }
    }

You can call the class as follows:

string heightPropertyName = MemberName<Person>.Of(x => x.Height);

This allows us to stop using ‘magic’ strings that are not tightly coupled with the actual property. If you change the name of your property, using this class you can always get the new string value of that property. This is most useful when you’re databinding, or passing the name of the property to nhibernate.

This code uses an extension method call To. Which is used to cleanup up your type casting and rearranges the logic to make it easier to follow. The extension method is as follows:

        public static T To<T>(this object obj)
        {
            return (T)obj;
        }

Without the extension method line 8 becomes the following:

memberExpression = (MemberExpression)((UnaryExpression)expression.Body).Operand;
Posted By: boyd21
Last Edit: 14 Apr 2011 @ 09:51 PM

EmailPermalinkComments Off
Tags
Tags: , ,
Categories: .Net, Programming
 21 Oct 2010 @ 10:15 AM 

Here are a couple real handy enum exntensions to have around. This first one returns all the vaues of the enum in a list. This is perfect for generating dropdown lists or selections. The important aspect to note here is that the list will always contain the latest additions to the enum. So you don’t have to go back and rewrite your dropdowns for the enum, it does it for you.

public static IEnumerable<T> GetEnumValues<T>(this Enum obj)
{
        IList<T> values = new List<T>();
        foreach (var val in Enum.GetValues(typeof(T)).Cast<T>())
        {
                values.Add(val);
        }
        return values;
}

This next one turns the enum value into a more readable form. Automatically parsing out camel casing into spaces. This particular regex statement requires a preceeding and following lower case letter to space. The regex is followed by simple extension methods, for both string replacement and enum replacement.

private const string RegExEnglishPattern = "(?<!^)([A-Z][a-z]|(?<=[a-z])[A-Z])";

/// <summary>
/// Correctly spaces the enumeration value to make it english-like.
/// </summary>
/// <param name="e">The enumeration.</param>
/// <returns>The english-like form of the enumeration value.</returns>
public static string ToEnglish(this Enum e)
{
        return Regex.Replace(e.ToString(), RegExEnglishPattern, " $1");
}

public static string ToEnglish(this string value)
{
        return Regex.Replace(value, RegExEnglishPattern, " $1", RegexOptions.Compiled).Trim();
}
Posted By: boyd21
Last Edit: 14 Apr 2011 @ 09:54 PM

EmailPermalinkComments Off
Tags
Tags: , , ,
Categories: .Net, Programming
 11 Mar 2009 @ 10:31 PM 

This is a simple extension method that can be added to retrieve a bitmap of any control. It can be as specific as a text box, or image viewer, or as general as your entire application.


public static Bitmap GetImage(this Control obj)
{
obj.CreateGraphics();
var bmp = new Bitmap(obj.Width, obj.Height);
obj.DrawToBitmap(bmp, new Rectangle(0, 0, obj.Width, obj.Height));
return bmp;
}

Posted By: boyd21
Last Edit: 11 Mar 2009 @ 10:31 PM

EmailPermalinkComments (699)
Tags
Tags: , , ,
Categories: .Net, Programming

 Last 50 Posts
Change Theme...
  • Users » 3
  • Posts/Pages » 30
  • Comments » 0
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

GeekPub



    No Child Pages.