From 6a273efd08cccaaab58f3ec9fa95ad2e8a746182 Mon Sep 17 00:00:00 2001 From: TLRZ Christian Date: Fri, 7 Apr 2017 12:36:42 +0200 Subject: [PATCH] initial commit --- ActiveDirectoryExtensions.cs | 72 ++++++++++++++ BasicExtensions.cs | 22 +++++ Chrosey.Extensions.csproj | 67 +++++++++++++ CollectionExtensions.cs | 131 ++++++++++++++++++++++++++ ColorExtensions.cs | 41 ++++++++ Exceptions/NotFoundException.cs | 25 +++++ ImageExtensions.cs | 46 +++++++++ NumberExtensions.cs | 28 ++++++ Properties/AssemblyInfo.cs | 36 +++++++ StringExtensions.cs | 161 ++++++++++++++++++++++++++++++++ 10 files changed, 629 insertions(+) create mode 100644 ActiveDirectoryExtensions.cs create mode 100644 BasicExtensions.cs create mode 100644 Chrosey.Extensions.csproj create mode 100644 CollectionExtensions.cs create mode 100644 ColorExtensions.cs create mode 100644 Exceptions/NotFoundException.cs create mode 100644 ImageExtensions.cs create mode 100644 NumberExtensions.cs create mode 100644 Properties/AssemblyInfo.cs create mode 100644 StringExtensions.cs diff --git a/ActiveDirectoryExtensions.cs b/ActiveDirectoryExtensions.cs new file mode 100644 index 0000000..ac3c460 --- /dev/null +++ b/ActiveDirectoryExtensions.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.DirectoryServices; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Chrosey.Extensions +{ + public static class ActiveDirectoryExtensions + { + public static T Get(this DirectoryEntry entry, string propertyName) where T : class + { + if (string.IsNullOrWhiteSpace(propertyName)) throw new ArgumentNullException("propertyName darf nicht leer sein"); + if (!entry.Properties.PropertyNames.Cast().Contains(propertyName)) return null; + + return entry.Properties[propertyName].Value as T; + } + + public static string GetValue(this DirectoryEntry entry, string propertyName) + { + try + { + if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("Der PropertyName[" + propertyName + "] kann nicht null oder leer sein"); + if (null == entry) throw new ArgumentNullException("Kann keine Eigenschaft von null abrufen"); + if (!entry.Properties.Contains(propertyName)) return string.Empty; + + return entry.Properties[propertyName].Value.ToString(); + + } + catch (Exception e) + { + throw new FieldAccessException(string.Format("Fehler beim Lesen von {0}.{1}",entry.Name,propertyName), e); + } + } + public static byte[] Photo(this DirectoryEntry entry) + { + try + { + if (null == entry) throw new ArgumentNullException("Kann keine Eigenschaft von null abrufen"); + if (!entry.Properties.Contains("thumbnailPhoto")) return null; + + return entry.Properties["thumbnailPhoto"].Value as byte[]; + + } + catch (Exception e) + { + throw new FieldAccessException(string.Format("Fehler beim Lesen von {0}.{1}", entry.Name, "thumbnailPhoto"), e); + } + } + + public static string GetValue(this SearchResult sr, string propertyName) + { + if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("Der PropertyName[" + propertyName + "] kann nicht null oder leer sein"); + if (null == sr) throw new ArgumentNullException("Kann keine Eigenschaft von null abrufen"); + + try + { + var s = sr.Properties[propertyName.ToLower()]; + if (s.Count > 0) + { + return s[0].ToString(); + } + return string.Empty; + } + catch (Exception e) + { + throw new FieldAccessException(string.Format("Fehler beim Lesen von {0}.{1}", sr.Path, propertyName), e); + } + } + } +} diff --git a/BasicExtensions.cs b/BasicExtensions.cs new file mode 100644 index 0000000..2d742a5 --- /dev/null +++ b/BasicExtensions.cs @@ -0,0 +1,22 @@ +using System.Reflection; + +namespace Chrosey.Extensions +{ + public static class BasicExtensions + { + public static bool HasProperty(this object me, string propertyName) + { + return me.GetType().GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) != null; + } + + public static object GetPropertyValue(this object me, string propertyName) + { + if (!me.HasProperty(propertyName)) throw new NotFoundException("Property not found " + propertyName); + + return me + .GetType() + .GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) + .GetValue(me, null); + } + } +} diff --git a/Chrosey.Extensions.csproj b/Chrosey.Extensions.csproj new file mode 100644 index 0000000..36b61ba --- /dev/null +++ b/Chrosey.Extensions.csproj @@ -0,0 +1,67 @@ + + + + + Debug + AnyCPU + {802CC164-BD17-4837-B59E-1CF536E2D21D} + Library + Properties + Chrosey.Extensions + Chrosey.Extensions + v4.6 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/CollectionExtensions.cs b/CollectionExtensions.cs new file mode 100644 index 0000000..5eba64b --- /dev/null +++ b/CollectionExtensions.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Chrosey.Extensions +{ + public static class CollectionExtensions + { + public static string GetValue(this Dictionary dict,string key) + { + string value; + if (!dict.TryGetValue(key,out value)) + { + return string.Empty; + } + return value; + } + + + public static IEnumerable Filter(this IEnumerable collection, NameValueCollection query) where T : class + { + var props = typeof(T).GetProperties().Select(p => p.Name.ToLower()); + var commonProps = props.Intersect(query.AllKeys.Select(k => k.ToLower())); + + foreach (var condition in commonProps) + { + try + { + var value = query[condition].ToString(); + if (value.EndsWith("*") && value.StartsWith("*")) + { + collection = collection + .Where(m => m + .GetPropertyValue(condition) + .ToString() + .IndexOf(value.Trim('*'), StringComparison.CurrentCultureIgnoreCase) > -1); + } + else if (value.EndsWith("*")) + { + collection = collection + .Where(m => m + .GetPropertyValue(condition) + .ToString() + .StartsWith(value.Trim('*'), StringComparison.CurrentCultureIgnoreCase)); + } + else if (value.StartsWith("*")) + { + collection = collection + .Where(m => m + .GetPropertyValue(condition) + .ToString() + .EndsWith(value.Trim('*'), StringComparison.CurrentCultureIgnoreCase)); + } + else + { + collection = collection + .Where(m => m + .GetPropertyValue(condition) + .ToString() + .Equals(value, StringComparison.CurrentCultureIgnoreCase)); + } + } + catch (NotFoundException) + { + + } + + } + return collection; + } + public static IOrderedEnumerable Sort(this IEnumerable collection, NameValueCollection query) where T : class + { + + if (string.IsNullOrEmpty(query["sort"])) + { + return collection.OrderBy(i => i); + } + + var order = query["sort"].Split(','); + var sortProps = order.Select(o => o.Split(' ')[0].ToLower()); + var props = typeof(T).GetProperties().Select(p => p.Name.ToLower()); + + IOrderedEnumerable ordered = null; + foreach (var condition in sortProps.Intersect(props)) + { + var isDescending = order + .Single(c => c.StartsWith(condition, StringComparison.CurrentCultureIgnoreCase)) + .EndsWith("desc", StringComparison.CurrentCultureIgnoreCase); + if (ordered == null) + { + ordered = isDescending + ? collection.OrderByDescending(i => i.GetPropertyValue(condition)) + : collection.OrderBy(i => i.GetPropertyValue(condition)); + } + else + { + ordered = isDescending + ? ordered.ThenByDescending(i => i.GetPropertyValue(condition)) + : ordered.ThenBy(i => i.GetPropertyValue(condition)); + } + } + + return ordered; + } + public static IEnumerable> GroupBy(this IEnumerable collection, NameValueCollection query) where T : class + { + var props = typeof(T).GetProperties().Select(p => p.Name.ToLower()); + var groupBy = string.IsNullOrEmpty(query["groupby"])? "" : query["groupby"].ToLower(); + var entferneAb = string.IsNullOrEmpty(query["groupbynletters"]) ? 0 : int.Parse(query["groupbynletters"]); + + if (string.IsNullOrEmpty(groupBy) || !props.Contains(groupBy)) + { + return collection.GroupBy(i => "Alle " + typeof(T).ToString()); + } + + var grouped = entferneAb > 0 + ? collection.GroupBy(i => i.GetPropertyValue(groupBy).ToString().Remove(entferneAb)) + : collection.GroupBy(i => i.GetPropertyValue(groupBy)); + + return grouped; + } + + public static IEnumerable> Organize(this IEnumerable collection, NameValueCollection query) where T : class + { + return collection.Filter(query).Sort(query).GroupBy(query); + } + } +} diff --git a/ColorExtensions.cs b/ColorExtensions.cs new file mode 100644 index 0000000..dfde182 --- /dev/null +++ b/ColorExtensions.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Media; + +namespace Chrosey.Extensions +{ + public static class ColorExtensions + { + public static Color ToColor(this Brush brush) + { + var result = ColorConverter.ConvertFromString(brush.ToString()); + if (null != result) + { + return (Color)result; + } + return Colors.Transparent; + } + public static Color AsColor(this string colorString) + { + + var result = ColorConverter.ConvertFromString(colorString); + if (null != result) + { + return (Color)result; + } + return Colors.Transparent; + } + + public static System.Drawing.Color SignificantColor(this System.Drawing.Color input) + { + var shiftBits = 3; + var r = Convert.ToByte(input.R >> shiftBits); + var g = Convert.ToByte(input.G >> shiftBits); + var b = Convert.ToByte(input.B >> shiftBits); + return System.Drawing.Color.FromArgb(r << shiftBits, g << shiftBits, b << shiftBits); + } + } +} diff --git a/Exceptions/NotFoundException.cs b/Exceptions/NotFoundException.cs new file mode 100644 index 0000000..22ad741 --- /dev/null +++ b/Exceptions/NotFoundException.cs @@ -0,0 +1,25 @@ +using System; +using System.Runtime.Serialization; + +namespace Chrosey.Extensions +{ + [Serializable] + class NotFoundException : Exception + { + public NotFoundException() + { + } + + public NotFoundException(string message) : base(message) + { + } + + public NotFoundException(string message, Exception innerException) : base(message, innerException) + { + } + + protected NotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } + } +} \ No newline at end of file diff --git a/ImageExtensions.cs b/ImageExtensions.cs new file mode 100644 index 0000000..5863c03 --- /dev/null +++ b/ImageExtensions.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Chrosey.Extensions +{ + public static class ImageExtensions + { + + /// + /// Gibt eine Liste an Farben zurück, die für ein Quantisierungsverfahren geeignet sind. + /// + /// + /// + public static List Pixels(this Bitmap bitmap, int quality) + { + + var pixels = new List(); + var count = 0; + for (int x = 0; x < bitmap.Width; x++) + { + for (int y = 0; y < bitmap.Height; y++) + { + if (count % quality == 0) + { + count = 0; + var p = bitmap.GetPixel(x, y); + if (p.A >= 125) + { + if (!(p.R > 250 && p.G > 250 && p.B > 250)) + { + pixels.Add(p.SignificantColor()); + } + } + } + + count++; + } + } + return pixels; + } + } +} diff --git a/NumberExtensions.cs b/NumberExtensions.cs new file mode 100644 index 0000000..cdaa8fe --- /dev/null +++ b/NumberExtensions.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Chrosey.Extensions +{ + public static class NumberExtensions + { + public static string ToTimeSpanString(this int minutes, bool noNegative = false) + { + if (noNegative) + { + return string.Format("{0}:{1}" + , (Math.Abs(minutes / 60)).ToString().PadLeft(2) + , (Math.Abs(minutes % 60)).ToString().PadLeft(2, '0') + ); + } + + return string.Format("{2}{0}:{1}" + , (Math.Abs(minutes / 60)).ToString().PadLeft(3) + , (Math.Abs(minutes % 60)).ToString().PadLeft(2, '0') + , minutes < 0 ? "-" : " " + ); + } + } +} diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..03ec87f --- /dev/null +++ b/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Allgemeine Informationen über eine Assembly werden über die folgenden +// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, +// die einer Assembly zugeordnet sind. +[assembly: AssemblyTitle("Chrosey.Extensions")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Chrosey.Extensions")] +[assembly: AssemblyCopyright("Copyright © 2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar +// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von +// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. +[assembly: ComVisible(false)] + +// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird +[assembly: Guid("802cc164-bd17-4837-b59e-1cf536e2d21d")] + +// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: +// +// Hauptversion +// Nebenversion +// Buildnummer +// Revision +// +// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern +// übernehmen, indem Sie "*" eingeben: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/StringExtensions.cs b/StringExtensions.cs new file mode 100644 index 0000000..a955236 --- /dev/null +++ b/StringExtensions.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Chrosey.Extensions +{ + public static class StringExtensions + { + /// + /// Vergleicht 2 Strings Phonetisch und gibt wahr zurück, wenn sich der erste im zweiten befindet + /// + /// + /// + /// + public static bool ComparePhonetic(this string lookFor, string source) + { + if (string.IsNullOrEmpty(lookFor)) + { + return true; + } + if (string.IsNullOrEmpty(source)) + { + return false; + } + var a = lookFor.KoelnPhonetic(); + var b = source.KoelnPhonetic(); + + return b.IndexOf(a) >= 0; + } + + /// + /// Erstellt aus dem String die Kölner Phonetic Folge + /// + /// + /// + public static string KoelnPhonetic(this string input) + { + var trimmed = input.Trim(); + var lower = trimmed.ToLower(); + var replacedSpecialChars = lower + .Replace('ä', 'a') + .Replace('ö', 'o') + .Replace('u', 'u') + .Replace("ß", "ss") + .Replace('é', 'e') + .Replace('è', 'e') + .Replace('à', 'a'); + + var withMarkers = "#" + replacedSpecialChars + "#"; + + var codeh = new[] { "h" }; + var code0 = new[] { "a", "e", "i", "j", "o", "u", "y" }; + var code1 = new[] { "b", "p" }; + var code2 = new[] { "d", "t" }; + var code3 = new[] { "f", "v", "w" }; + var code4 = new[] { "g", "k", "q" }; + var code5 = new[] { "l" }; + var code6 = new[] { "m", "n" }; + var code7 = new[] { "r" }; + var code8 = new[] { "c", "s", "z" }; + var code48 = new[] { "x" }; + var code4combifirst = new[] { "a", "o", "u", "h", "k", "x", "q", "l", "r" }; + var code4combi = new[] { "a", "o", "u", "h", "k", "x", "q" }; + var code8combi = new[] { "c", "k", "q" }; + + var asNumber = string.Empty; + for (int i = 1; i < withMarkers.Length - 1; i++) + { + var prev = withMarkers[i - 1].ToString(); + var curr = withMarkers[i].ToString(); + var next = withMarkers[i + 1].ToString(); + + string number; + + if (i == 1) + { + if (code0.Contains(curr)) number = "0"; + else if (curr == "c" && code4combifirst.Contains(next)) number = "4"; + else if (code2.Contains(curr) && code8.Contains(next)) number = "8"; + else if (curr == "x") number = "48"; + else if (codeh.Contains(curr)) number = "-"; + else if (code1.Contains(curr)) number = "1"; + else if (code2.Contains(curr)) number = "2"; + else if (code3.Contains(curr)) number = "3"; + else if (code4.Contains(curr)) number = "4"; + else if (code5.Contains(curr)) number = "5"; + else if (code6.Contains(curr)) number = "6"; + else if (code7.Contains(curr)) number = "7"; + else if (code8.Contains(curr)) number = "8"; + else number = "?"; + } + else + { + if (code2.Contains(curr) && code8.Contains(next)) number = "8"; + else if (code8combi.Contains(prev) && code48.Contains(curr)) number = "8"; + else if (curr == "x") number = "48"; + else if (prev == "s" && (curr == "c" || curr == "z")) number = "8"; + else if (curr == "c" && code4combi.Contains(next)) number = "4"; + + else if (curr == "h") number = "-"; + else if (code0.Contains(curr)) number = "0"; + else if (code1.Contains(curr)) number = "1"; + else if (code2.Contains(curr)) number = "2"; + else if (code3.Contains(curr)) number = "3"; + else if (code4.Contains(curr)) number = "4"; + else if (code5.Contains(curr)) number = "5"; + else if (code6.Contains(curr)) number = "6"; + else if (code7.Contains(curr)) number = "7"; + else if (code8.Contains(curr)) number = "8"; + else number = "?"; + } + + asNumber += number; + } + + var withoutH = asNumber.Replace("-", ""); + var zerosRemoved = withoutH[0] + withoutH.Substring(1).Replace("0", ""); + + var duplicatesRemoved = zerosRemoved[0].ToString(); + for (int i = 1; i < zerosRemoved.Length; i++) + { + var curr = zerosRemoved[i].ToString(); + var prev = zerosRemoved[i - 1].ToString(); + if (curr != prev) + { + duplicatesRemoved += curr; + } + } + + return duplicatesRemoved; + } + + /// + /// Formatiert einen Eigenschaftsnamen mit Wert zum passenden Formatierten String + /// + /// der aktuelle String + /// der Wert der Eigenschaft + /// Das Format in dem die Rückgabe erfolgen soll + /// Normales Format "(propertyName=value) + public static string PropertyValueFormat(this string propertyName, object value, string format="({0}={1})") + { + return string.Format(format, propertyName, value.ToString()); + } + + public static string FirstUpper(this string me) + { + if (string.IsNullOrEmpty(me)) + { + return string.Empty; + } + return char.ToUpper(me[0]) + me.Substring(1); + } + + public static string AsFormat(this string format, params object[] args) + { + return string.Format(format, args); + } + } +}