git_bsmd/nsw/Source/bsmd.database/Extensions.cs

95 lines
2.9 KiB
C#

//
// Class: Extensions
// Current CLR: 4.0.30319.34209
// System: Microsoft Visual Studio 10.0
// Author: dani
// Created: 5/13/2015 7:37:03 PM
//
// Copyright (c) 2015 Informatikbüro Daniel Schick. All rights reserved.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using log4net;
namespace bsmd.database
{
/// <summary>
/// sensible helpers
/// </summary>
public static class Extensions
{
private static ILog _log = LogManager.GetLogger(typeof(Extensions));
public static bool IsNullOrEmpty(this String str)
{
if (str == null) return true;
if (str.Trim().Length == 0) return true;
if (str.Equals("00000000-0000-0000-0000-000000000000")) return true; // for null guids
return false;
}
public static bool IsNullOrEmpty<T>(this List<T> items)
{
return (items == null) || (items.Count == 0);
}
public static bool IsNullOrEmpty<T>(this Dictionary<T, T> items)
{
return (items == null) || (items.Count == 0);
}
public static bool IsNumber(this String str)
{
string pattern = @"^[1-9]\d*(\.\d+)?$";
if (str == null) return false;
if (str.Trim().Length == 0) return false;
return new Regex(pattern).IsMatch(str);
}
public static bool IsBoolean(this String str)
{
if (str == null) return false;
if (str.Trim().Length == 0) return false;
if (str.Trim().Equals("true", StringComparison.InvariantCultureIgnoreCase)) return true;
if (str.Trim().Equals("false", StringComparison.InvariantCultureIgnoreCase)) return true;
return false;
}
public static bool Contains(this string source, string toCheck, StringComparison comp)
{
return source.IndexOf(toCheck, comp) >= 0;
}
public static DateTime? TryParseDateTime(string text)
{
DateTime date;
if(DateTime.TryParse(text, DateTimeFormatInfo.InvariantInfo,DateTimeStyles.AssumeUniversal, out date))
{
return date;
}
else
{
_log.WarnFormat("{0} cannot be parsed as datetime", text);
return null;
}
}
public static double? TryParseDouble(string text)
{
double d;
if (Double.TryParse(text, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out d))
{
return d;
}
else
{
_log.WarnFormat("{0} cannot be parsed as double", text);
return null;
}
}
}
}