HTMLWriter 1.5

I’ve updated this little utility library by simplifying some method overloads plus added a static method for getting escaped html special characters.

To make the code more maintainable for the special characters (like adding new ones in the future) I’ve added an enum that use some .Net ‘attributes’ so you can see, use and reference everything about these ‘things’ in one place. To do that I had to add a special helper class so the enum can carry some additional properties (like the actual strings for the special character and the escaped string). To do this I created a custom attribute class called ‘StringValueAttribute’ like this:

public class StringValueAttribute : Attribute
{

public string StringExpandedValue;
public string StringValue;

public StringValueAttribute(string value, string stringExpandedValue)
{

this.StringValue = value;
this.StringExpandedValue = stringExpandedValue;

}

}

To retrieve the associated values from an enum another static helper class is needed: StringValueAttributeUtil

internal static class StringValueAttributeUtil
{

public static string GetStringValue(Enum value)
{

// Get the type
Type type = value.GetType();

// Get fieldinfo for this type
System.Reflection.FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].StringValue : null;

}
public static string GetStringExpandedValue(Enum value)
{

// Get the type
Type type = value.GetType();

// Get fieldinfo for this type
System.Reflection.FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].StringExpandedValue : null;

}

}

 

Then to actually make use of this helper class you decorate the enum like this: (showing only part of it…)

public enum HTMLSpecialCharacter
{

[StringValue(“<“, “&amp;lt;”)]
LessThanSign,
[StringValue(“>”, “&amp;gt;”)]
GreaterThanSign,
[StringValue(“\””, “&amp;quot;”)]
DoubleQuote,
[StringValue(“‘”, “&amp;#39;”)]
SingleQuote,

}

Happy HTML’ing 🙂

Update: Version 1.6 has now been released since…

Leave a Reply

%d bloggers like this: