Wednesday 22 August 2012

Text template: Attribute writer

Here’s a function I wrote that can take an attribute as a parameter and return its string equivalence into a text template. This is useful if you need to generate data annotations attributes for your metadata class but will work anywhere you need to output an attribute instance.
private static string AttributeToString(Attribute obj)
        {
            Type attrType;
            StringBuilder sb_AttrParts;
            StringBuilder sb_Attributes = new StringBuilder();

            sb_AttrParts = new StringBuilder();
            attrType = obj.GetType();

            PropertyInfo[] props = attrType.GetProperties();

            sb_AttrParts.Append("[");
            sb_AttrParts.Append(attrType.Name);
            sb_AttrParts.Append("(");

            bool first = true;
            foreach (PropertyInfo pi in props)
            {
                try
                {
                    if (pi.Name == "TypeId")
                        continue;

                    object value = pi.GetValue(obj, null);

                    if (value == null)
                        continue;

                    if (!first)
                        sb_AttrParts.Append(",");
                    else
                        first = false;

                    sb_AttrParts.Append(pi.Name);
                    sb_AttrParts.Append("=");

                    if (value != null)
                    {
                        if (value.GetType() == typeof(string))
                            sb_AttrParts.Append("\"" + value.ToString() + "\"");
                        else if (value.GetType() == typeof(bool))
                        {
                            if ((bool)value)
                                sb_AttrParts.Append("true");
                            else
                                sb_AttrParts.Append("false");
                        }
                        else
                            sb_AttrParts.Append(value.ToString());
                    }
                }
                catch { continue; }
            }
            sb_AttrParts.Append(")");
            sb_AttrParts.Append("]");

            sb_Attributes.Append(sb_AttrParts);
            return sb_Attributes.ToString();
        }

No comments:

Post a Comment