initial commit

This commit is contained in:
TLRZ Christian 2017-04-07 12:36:42 +02:00
parent d88743a4de
commit 6a273efd08
10 changed files with 629 additions and 0 deletions

View File

@ -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<T>(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<string>().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);
}
}
}
}

22
BasicExtensions.cs Normal file
View File

@ -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);
}
}
}

67
Chrosey.Extensions.csproj Normal file
View File

@ -0,0 +1,67 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{802CC164-BD17-4837-B59E-1CF536E2D21D}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Chrosey.Extensions</RootNamespace>
<AssemblyName>Chrosey.Extensions</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="PresentationCore" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.DirectoryServices" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="ActiveDirectoryExtensions.cs" />
<Compile Include="BasicExtensions.cs" />
<Compile Include="CollectionExtensions.cs" />
<Compile Include="ImageExtensions.cs" />
<Compile Include="Exceptions\NotFoundException.cs" />
<Compile Include="NumberExtensions.cs" />
<Compile Include="ColorExtensions.cs" />
<Compile Include="StringExtensions.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

131
CollectionExtensions.cs Normal file
View File

@ -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<string,string> dict,string key)
{
string value;
if (!dict.TryGetValue(key,out value))
{
return string.Empty;
}
return value;
}
public static IEnumerable<T> Filter<T>(this IEnumerable<T> 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<T> Sort<T>(this IEnumerable<T> 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<T> 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<IGrouping<object, T>> GroupBy<T>(this IEnumerable<T> 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<IGrouping<object, T>> Organize<T>(this IEnumerable<T> collection, NameValueCollection query) where T : class
{
return collection.Filter(query).Sort(query).GroupBy(query);
}
}
}

41
ColorExtensions.cs Normal file
View File

@ -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);
}
}
}

View File

@ -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)
{
}
}
}

46
ImageExtensions.cs Normal file
View File

@ -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
{
/// <summary>
/// Gibt eine Liste an Farben zurück, die für ein Quantisierungsverfahren geeignet sind.
/// </summary>
/// <param name="bitmap"></param>
/// <returns></returns>
public static List<Color> Pixels(this Bitmap bitmap, int quality)
{
var pixels = new List<Color>();
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;
}
}
}

28
NumberExtensions.cs Normal file
View File

@ -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 ? "-" : " "
);
}
}
}

View File

@ -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")]

161
StringExtensions.cs Normal file
View File

@ -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
{
/// <summary>
/// Vergleicht 2 Strings Phonetisch und gibt wahr zurück, wenn sich der erste im zweiten befindet
/// </summary>
/// <param name="lookFor"></param>
/// <param name="source"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Erstellt aus dem String die Kölner Phonetic Folge
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Formatiert einen Eigenschaftsnamen mit Wert zum passenden Formatierten String
/// </summary>
/// <param name="propertyName">der aktuelle String</param>
/// <param name="value">der Wert der Eigenschaft</param>
/// <param name="format" default="(propertyName=value)">Das Format in dem die Rückgabe erfolgen soll</param>
/// <returns>Normales Format "(propertyName=value)</returns>
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);
}
}
}