Skip to content

Instantly share code, notes, and snippets.

@karno
Created March 26, 2010 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karno/344844 to your computer and use it in GitHub Desktop.
Save karno/344844 to your computer and use it in GitHub Desktop.
using System;
using System.Drawing;
using System.Xml.Linq;
namespace Std.Util
public static class LinqConverter
{
public static string ParseString(this XElement e)
{
return e == null ? null : e.Value.Replace("&lt;", "<").Replace("&gt;", ">");
}
public static bool ParseBool(this XElement e)
{
return ParseBool(e, false);
}
public static bool ParseBool(this XElement e, bool def)
{
return ParseBool(e == null ? null : e.Value, def);
}
public static bool ParseBool(this string s, bool def)
{
if (s == null)
{
return def;
}
return def ? s.ToLower() != "false" : s.ToLower() == "true";
}
public static long ParseLong(this XElement e)
{
return ParseLong(e == null ? null : e.Value);
}
public static long ParseLong(string s)
{
long v;
return long.TryParse(s, out v) ? v : -1;
}
public static DateTime ParseDateTime(this XElement e)
{
return ParseDateTime(e == null ? null : e.Value);
}
public static DateTime ParseDateTime(this string s)
{
return DateTime.Parse(s);
}
public static DateTime ParseDateTime(this XElement e, string format)
{
return ParseDateTime(e == null ? null : e.Value, format);
}
public static DateTime ParseDateTime(this string s, string format)
{
return DateTime.ParseExact(s,
format,
System.Globalization.DateTimeFormatInfo.InvariantInfo,
System.Globalization.DateTimeStyles.None);
}
public static TimeSpan ParseUtcOffset(this XElement e)
{
return ParseUtcOffset(e == null ? null : e.Value);
}
public static TimeSpan ParseUtcOffset(this string s)
{
int seconds;
int.TryParse(s, out seconds);
return new TimeSpan(0, 0, seconds);
}
public static Color ParseColor(this XElement e)
{
return ParseColor(e == null ? null : e.Value);
}
public static Color ParseColor(this string s)
{
if (s == null || s.Length != 6)
{
return Color.Transparent;
}
int v, r, g, b;
v = Convert.ToInt32(s, 16);
r = v >> 16;
g = (v >> 8) & 0xFF;
b = v & 0xFF;
return Color.FromArgb(r, g, b);
}
public static Uri ParseUri(this XElement e)
{
var uri = e.ParseString();
try
{
if (String.IsNullOrEmpty(uri))
return null;
else
return new Uri(uri);
}
catch (UriFormatException)
{
return null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment