Useful .NET Extension Methods

Below are some “essentials” that I keep handy whenever I start a new project. Some are here out of sheer laziness (ToTitleCase) and some are a bit more involved (ToViewModel). All of these have been utilized in some fashion in production environments.



/// 
<summary>
/// Converts a select list to a comma separated list, using either the text or the value.
/// </summary>
/// <param name="selectList">The select list.</param>
/// <param name="useText">if set to <c>true</c> [use text] else [use value].</param>
/// <returns>Comma separated string</returns>
public static string ToCommaSeparatedList(this List<SelectListItem> selectList, bool useText, string defaultIfEmpty = "")
{
    if (selectList == null || selectList.Count <= 0)
        return defaultIfEmpty;

    StringBuilder sb = new StringBuilder();
    selectList.ForEach(s =>
    {
        sb.AppendFormat("{0},", useText ? s.Text : s.Value);
    });
    sb = sb.Remove(sb.Length - 1, 1); // Trim last comma
    return sb.ToString();
}
/// 
<summary>
/// Reliably gets the source IP address of a request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>xxx.xxx.xxx.xxx</returns>
public static string GetIPAddress(this HttpRequestBase request)
{
    try
    {
        if (request == null)
            return string.Empty;
        string ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(ipAddress) || (ipAddress.ToLower() == "unknown"))
        {
            ipAddress = request.ServerVariables["REMOTE_ADDR"];
        }
        if (!string.IsNullOrEmpty(ipAddress))
        {
            if (ipAddress.IndexOf(',') > 0)
            {
                string[] ipAddresses = ipAddress.Split(',');
                ipAddress = ipAddresses[ipAddresses.Length - 1];
            }
        }
        return ipAddress;
    }
    catch // Lossy, don't block on failure
    {
        return "0.0.0.0";
    }
}
/// 
<summary>
/// Validates a string is a GUID
/// </summary>
/// <param name="candidate"/>The string to evaluate
/// <returns>True, if it's a guid</returns>
public static bool IsGuid(this string candidate)
{
    bool isValid = false;
    if (candidate != null)
    {
        Regex regexGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$&;", RegexOptions.Compiled);
        if (regexGuid.IsMatch(candidate))
            isValid = true;
    }
    return isValid;
}
/// 
<summary>
/// Maps a given type "S" to a view model of type "T". Maps ONLY public properties, does not perform a deep
/// copy or an object clone.
/// </summary>
/// <typeparam name="S">The source type</typeparam>
/// <typeparam name="T">The target type</typeparam>
/// <param name="source"/>The source.
/// <returns>T</returns>
public static T ToViewModel<S , T>(this S source, bool caseInsensitive = true)
    where S : class, new()
    where T : class, new()
{
    T target = new T();
    PropertyInfo[] sourceProps = source.GetType().GetProperties();
    PropertyInfo[] targetProps = target.GetType().GetProperties();
    // Enumerate over the source object to find matching properties
    for (int x = 0; x < sourceProps.Length; x++)
    {
        // Get a reference to the current source property
        PropertyInfo sourceProp = sourceProps&#91;x&#93;;

        // Remove underscores
        string sourcePropName = sourceProp.Name.Replace("_", string.Empty);

        // Match
        PropertyInfo targetProp = targetProps.FirstOrDefault(t => caseInsensitive ?
            (t.Name.ToLower() == sourcePropName.ToLower() && t.PropertyType == sourceProp.PropertyType) :
            (t.Name == sourcePropName && t.PropertyType == sourceProp.PropertyType));
        // Found a matching type & name
        if (targetProp != null)
        {
            targetProp.SetValue(target, sourceProp.GetValue(source, null), null);
        }
    }
    return target;
}
/// 
<summary>
/// Converts a string to title case.
/// </summary>
/// <param name="s"/>The s.
/// <returns></returns>
public static string ToTitleCase(this string s)
{
    return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
}
/// 
<summary>
/// Converts a list of ints to a comma separated list
/// </summary>
/// <param name="ints"/>The ints.
/// <returns></returns>
public static string ToCommaSeparatedList(this List<int> ints)
{
    return string.Join(",", Array.ConvertAll(ints.ToArray(), i => i.ToString()));
}
/// 
<summary>
/// When called on any object, validates that the object is not null
/// and of the given type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"/>The obj.
/// <returns>
///   <c>true</c> if not null and of the proper type; otherwise, <c>false</c>.
/// </returns>
public static bool Is<T>(this object obj)
{
    bool isValid = true;
    if (obj.GetType().Name != typeof(T).Name)
        isValid = false;
    if (obj == null)
        isValid = false;
    if (string.IsNullOrWhiteSpace(obj.ToString()))
        isValid = false;
    return isValid;
}
/// 
<summary>
/// Converts the current instance to XML by serializing it (if possible).
/// </summary>
/// <param name="instance"/>The instance to serialize to XML.
/// <returns>A string value containing the XML serialized representation of
/// this object instance.</returns>
public static string ToXml(this object instance)
{
    if (instance == null)
        return null;
    XmlSerializer xmlSer = new XmlSerializer(instance.GetType());
    using (MemoryStream mem = new MemoryStream())
    {
        xmlSer.Serialize(mem, instance);
        mem.Position = 0;
        using (StreamReader reader = new StreamReader(mem))
            return reader.ReadToEnd();
    } // using MemoryStream"
}
/// 
<summary>
/// Converts the current XML string to an instance of <c>T</c> by deserializing
/// the XML.
/// </summary>
/// <typeparam name="T">The type of instance expected after deserializing the
/// XML string <paramref name="xml"></paramref>.</typeparam>
/// <param name="xml"/>The XML to be deserialized.
/// <returns>An instance of <c>T</c> populated from the deserialized XML string.</returns>
public static T ToInstance<T>(this string xml) where T: class, new()
{
    if (string.IsNullOrWhiteSpace(xml))
        return default(T);
    XmlSerializer xmlSer = new XmlSerializer(typeof(T));
    using (MemoryStream mem = new MemoryStream())
    {
        using (StreamWriter writer = new StreamWriter(mem))
        {
            writer.Write(xml);
            mem.Position = 0;
            return xmlSer.Deserialize(mem) as T;
        } // using StreamWriter
    } // using MemoryStream
}

Leave a Reply