Archive

Archive for September, 2010

Generic Flags Enum Extension Method – Parse a Delimited String

September 30, 2010 Leave a comment

I am a big fan of extension methods.  It’s a great way to simply code and to allow developers to write in a more fluent way. 

I have a .Net application that exposes services to Flex.  Because Flex doesn’t have a native flags Enum type that we can pass across the wire, I have a property that converts a delimited string into an Enum of T.  The code to do this the non-generic way was too complex and prone to human error.

To solve the problem of converting a generic flags Enum, I created a generic extension method.  There is already a method to generically parse a string as an Enum, but not a delimited string.

One challenge with extending an Enum is that you can’t have an Enum value type on the constraint clause.  You can however have a struct in the constraint clause, which an Enum inherits from.  This should prevent misuse 99% of the time, after all who will try to parse a non-Enum struct type as a flags Enum?  Don’t answer that.

The extension method created allows us to write code like this:

 String delimitedEnum = "AccountLevel, OpportunityLevel, PackageLevel, None";
 ApplicationLevels applicationLevels = delimitedEnum.EnumParseDelimitedString<ApplicationLevels>();

 

That is much easier than the alternative.  If you want to try this at home, feel free to play with the code snippet below.  If you find any bugs or have improvements, please post them in the comment below.  I can’t claim credit for all of this.  There was already a blog detailing how to parse an Enum from a string with a single value, I simply went the next step with a flags Enum.  If you are using Byte values in your enums you’ll need to code for that, but this should get you most of the way there.  Happy coding!

 

Try this at home kids. . .

        public static T EnumParseDelimitedString<T>(this string value, char delimiter, bool ignoreCase)
            where T : struct
        {
            if (value.Length == 0)
            {
                throw new ArgumentException("Must specify valid information for parsing in the string.", "value");
            }
            if (!typeof(T).IsEnum)
            {
                throw new ArgumentException("Type provided must be an Enum.", "T");
            }

            //Split the string
            value = value.Trim();
            IList<string> values = value.Split(delimiter).ToList<string>();

            //Get the type of enum we are dealing with
            Type numberType = Enum.GetUnderlyingType(typeof(T));

            if (numberType.Equals(typeof(int)))
            {
                int newResult = 0;
                foreach (string val in values)
                {
                    int tempResult;
                    tempResult = (int)(Object)EnumParse<T>(val, ignoreCase);
                    newResult += tempResult;
                }
                return (T)(Object)newResult;
            }
            else
            {
                throw new ArgumentException("Unknown enum underlying type " + numberType.Name + ".");
            }

        }


        public static T EnumParse<T>(this string value, bool ignoreCase)
             where T : struct
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            value = value.Trim();
            if (value.Length == 0)
            {
                throw new ArgumentException("Must specify valid information for parsing in the string.", "value");
            }
            Type t = typeof(T);
            if (!t.IsEnum)
            {
                throw new ArgumentException("Type provided must be an Enum.", "T");
            }
            T enumType = (T)Enum.Parse(t, value, ignoreCase);
            return enumType;
        }
Advertisements

WCF RIA Services – Architecture, Validation, and Security Reference Sheet

September 28, 2010 Leave a comment

Microsoft_Silverlight Hello, I am Roy Lawson and glad to be blogging about Silverlight, WCF RIA Services, Application Architecture, and other development related topics.  If you are from Florida you may know me as the president of the Lakeland .Net User Group, or you may have heard me speak on a variety of topics including Silverlight, WCF RIA Services, TFS and Team System, .Net, BI, or as the presenter at Florida’s Microsoft Speaker Idol competition held earlier this year.

imageFor my first blog entry I am going to include something I consider of rather high value if you are doing WCF RIA Services development, which is a reference sheet that contains the most commonly used WCF RIA Services concepts.  This sheet was created to support a recent presentation I delivered to the Tampa Silverlight User Group last week.  As this sheet will continue to be updated, you can find the download on the silverteams codeplex site where I have started development on a new collaboration portal that can best be described as The Ladders meets Elance. 

I discovered that although there is a ton of information on WCF RIA Services, there is a whole lot to sort through until you find what you really need to know.  The reference sheet is the first in what will be three to four pages on the topic with authorization, validation, security, and general tips to come.  I am deliberately keeping it as short as possible and only including information that you will absolutely need.

I spent a good deal of time working out how to architect a Silverlight application in the Enterprise, or for an application where you want a clean separation between the layers.  Although it was a bit tricky in Silverlight 3 to separate the layers, I have found that Silverlight 4 is not really that complicated.  I had to develop some custom T4 templates to generate the domain service and metadata at the appropriate layers, but I am at a point where I can quickly crank out a working template.  I have been very fortunate to know and work with Oleg Sych here in Florida, who is in fact the T4 King.  If you want to know anything about code generation and especially T4, it all begins with Oleg.

We here in Florida had the great fortune to have John Papa amongst us – and I certainly enjoyed the times he spoke in Lakeland or at code camps.  Now that he is a Microsoft superstar and Silverlight evangelist he has been producing some really awesome content in the form of Silverlight TV.  If you are just starting with WCF RIA Services, check out John Papa’s hands on lab

Once you understand how WCF RIA Services fits together and you want to go another step, I would encourage you to participate (or at least download) the http://silverteams.codeplex.com/ application and rip it apart.  It is a real app still in design phase so you can watch as the foundation evolves. 

 

Technorati Tags: ,
Categories: Silverlight