//******************************************************************************************************
// EnumExtensions.cs - Gbtc
//
// Copyright © 2010, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://www.opensource.org/licenses/eclipse-1.0.php
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 12/21/2010 - Pinal C. Patel
// Generated original version of source code based on code from Tom Fischer.
// 12/30/2010 - J. Ritchie Carroll
// Corrections / additions.
// 12/30/2010 - Pinal C. Patel
// Renamed GetEnumFromDescription() to GetEnumValueByDescription() to avoid confusion.
// 10/8/2012 - Danyelle Gilliam
// Modified Header
//
//******************************************************************************************************
#region [ Contributor License Agreements ]
//******************************************************************************************************
//
// Copyright © 2010, Grid Protection Alliance. All Rights Reserved.
//
// The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://www.opensource.org/licenses/eclipse-1.0.php
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
//******************************************************************************************************
#endregion
using GSF.Reflection;
using System;
using System.ComponentModel;
using System.Reflection;
using System.Text;
namespace GSF
{
///
/// Defines extension methods related to enumerations.
///
public static class EnumExtensions
{
///
/// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
/// The return value indicates whether the conversion succeeded.
///
/// true if the parameter was converted successfully; otherwise, false.
/// to operate on.
/// The string representation of the enumeration name or underlying value to convert.
/// When this method returns, contains an object of type whose value is represented by . This parameter is passed uninitialized.
/// The enumeration type to which to convert .
/// type does not match type of .
public static bool TryParse(this Enum enumeration, string value, out TEnum result) where TEnum : struct
{
try
{
if (!(enumeration is TEnum))
throw new ArgumentException("Result enumeration type does not match source.");
result = (TEnum)Enum.Parse(typeof(TEnum), value);
return true;
}
catch
{
result = default(TEnum);
return false;
}
}
///
/// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
/// The return value indicates whether the conversion succeeded.
///
/// true if the parameter was converted successfully; otherwise, false.
/// to operate on.
/// The string representation of the enumeration name or underlying value to convert.
/// true to ignore case; false to consider case.
/// When this method returns, contains an object of type whose value is represented by . This parameter is passed uninitialized.
/// The enumeration type to which to convert .
/// type does not match type of .
public static bool TryParse(this Enum enumeration, string value, bool ignoreCase, out TEnum result) where TEnum : struct
{
try
{
if (!(enumeration is TEnum))
throw new ArgumentException("Result enumeration type does not match source.");
result = (TEnum)Enum.Parse(typeof(TEnum), value, ignoreCase);
return true;
}
catch
{
result = default(TEnum);
return false;
}
}
///
/// Retrieves the description of the value that this represents extracted from the , or the enumeration name
/// if no description is available.
///
/// to operate on.
/// Description of the if specified, otherwise the representation of this .
public static string GetDescription(this Enum enumeration)
{
string name = enumeration.ToString();
string description = enumeration.GetType().GetField(name).GetDescription();
if (!description.IsNullOrWhiteSpace())
return description;
return name;
}
///
/// Gets the enumeration of the specified whose description matches this .
///
/// Description to be used for lookup of the enumeration.
/// of the enumeration.
/// true to ignore case during the comparison; otherwise, false.
/// An enumeration of the specified if a match is found, otherwise null.
/// The is not an enumeration.
public static object GetEnumValueByDescription(this string description, Type type, bool ignoreCase)
{
if (!type.IsEnum)
throw new ArgumentException("Type must be an enum", "type");
foreach (object value in Enum.GetValues(type))
{
if (string.Compare(description, ((Enum)value).GetDescription(), ignoreCase) == 0)
return value;
}
return null;
}
///
/// Gets the enumeration value with the specified name.
///
/// Name to search for.
/// of the enumeration.
/// true to ignore case during the comparison; otherwise, false.
/// Specific value of the enumerated constant in terms of its underlying type associated with the specified , or null
/// if no macthing enumerated value was found.
public static object GetEnumValueByName(this string name, Type type, bool ignoreCase)
{
if (!type.IsEnum)
throw new ArgumentException("Type must be an enum", "type");
foreach (object value in Enum.GetValues(type))
{
if (string.Compare(name, ((Enum)value).ToString(), ignoreCase) == 0)
return value;
}
return null;
}
///
/// Retrieves a formatted name of the value that this represents for visual display.
///
/// to operate on.
/// Formatted enumeration name of the specified value for visual display.
public static string GetFormattedName(this Enum enumeration)
{
StringBuilder image = new StringBuilder();
char[] chars = enumeration.ToString().ToCharArray();
char letter;
for (int i = 0; i < chars.Length; i++)
{
letter = chars[i];
// Create word spaces at every capital letter
if (Char.IsUpper(letter) && image.Length > 0)
{
// Test for "ID" sequence exception
if (i < chars.Length - 1 && letter == 'I')
{
if (chars[i + 1] == 'D')
{
image.Append(" ID");
i++;
}
else
{
image.Append(' ');
image.Append(letter);
}
}
else
{
image.Append(' ');
image.Append(letter);
}
}
else
image.Append(letter);
}
return image.ToString();
}
// Internal extension to lookup description from DescriptionAttribute
private static string GetDescription(this FieldInfo value)
{
if ((object)value != null)
{
DescriptionAttribute descriptionAttribute;
if (value.TryGetAttribute(out descriptionAttribute))
return descriptionAttribute.Description;
}
return string.Empty;
}
}
}