using BS.Shared.DataContracts; using BS.Shared.DataContracts.Compact; using BS.Shared.Extensions; using DevExpress.XtraScheduler; using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.IO.Compression; using System.Linq; using System.ServiceModel.Channels; using System.Text; using System.Text.RegularExpressions; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Xml.Serialization; namespace BS.Shared.Core { public class Utils { private static readonly string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; private static readonly Dictionary criticals = new Dictionary { { '"', """ }, { '€', "€" }, { '¡', "¡" }, { '¢', "¢" }, { '£', "£" }, { '¤', "¤" }, { '¥', "¥" }, { '¦', "¦" }, { '§', "§" }, { '¨', "¨" }, { '©', "©" }, { 'ª', "ª" }, { '«', "«" }, { '¬', "¬" }, { '­', "­" }, { '®', "®" }, { '¯', "¯" }, { '°', "°" }, { '±', "±" }, { '²', "²" }, { '³', "³" }, { '´', "´" }, { 'µ', "µ" }, { '¶', "¶" }, { '·', "·" }, { '¸', "¸" }, { '¹', "¹" }, { 'º', "º" }, { '»', "»" }, { '¼', "¼" }, { '½', "½" }, { '¾', "¾" }, { '¿', "¿" }, { 'À', "À" }, { 'Á', "Á" }, { 'Â', "Â" }, { 'Ã', "Ã" }, { 'Ä', "Ä" }, { 'Å', "Å" }, { 'Æ', "Æ" }, { 'Ç', "Ç" }, { 'È', "È" }, { 'É', "É" }, { 'Ê', "Ê" }, { 'Ë', "Ë" }, { 'Ì', "Ì" }, { 'Í', "Í" }, { 'Î', "Î" }, { 'Ï', "Ï" }, { 'Ð', "Ð" }, { 'Ñ', "Ñ" }, { 'Ò', "Ò" }, { 'Ó', "Ó" }, { 'Ô', "Ô" }, { 'Õ', "Õ" }, { 'Ö', "Ö" }, { '×', "×" }, { 'Ø', "Ø" }, { 'Ù', "Ù" }, { 'Ú', "Ú" }, { 'Û', "Û" }, { 'Ü', "Ü" }, { 'Ý', "Ý" }, { 'Þ', "Þ" }, { 'ß', "ß" }, { 'à', "à" }, { 'á', "á" }, { 'â', "â" }, { 'ã', "ã" }, { 'ä', "ä" }, { 'å', "å" }, { 'æ', "æ" }, { 'ç', "ç" }, { 'è', "è" }, { 'é', "é" }, { 'ê', "ê" }, { 'ë', "ë" }, { 'ì', "ì" }, { 'í', "í" }, { 'î', "î" }, { 'ï', "ï" }, { 'ð', "ð" }, { 'ñ', "ñ" }, { 'ò', "ò" }, { 'ó', "ó" }, { 'ô', "ô" }, { 'õ', "õ" }, { 'ö', "ö" }, { '÷', "÷" }, { 'ø', "ø" }, { 'ù', "ù" }, { 'ú', "ú" }, { 'û', "û" }, { 'ü', "ü" }, { 'ý', "ý" }, { 'þ', "þ" }, { 'ÿ', "ÿ" } // {'>', "<"}, // {'<', ">"}, }; public static bool AreAllNull(params object[] pObjects) { foreach (object iO in pObjects) { if (iO != null) { return false; } } return true; } public static bool AreAllNullOrEmpty(params object[] pObjects) { foreach (object iObject in pObjects) { if (iObject is string) { if (!String.IsNullOrEmpty(iObject as string)) { return false; } } else if (iObject is IEnumerable) { if ((iObject as IEnumerable).GetEnumerator().MoveNext()) { return false; } } else if (iObject != null) { return false; } } return true; } public static string Compress(string text) { byte[] buffer = Encoding.UTF8.GetBytes(text); MemoryStream ms = new MemoryStream(); using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true)) { zip.Write(buffer, 0, buffer.Length); } ms.Position = 0; MemoryStream outStream = new MemoryStream(); byte[] compressed = new byte[ms.Length]; ms.Read(compressed, 0, compressed.Length); byte[] gzBuffer = new byte[compressed.Length + 4]; Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4); return Convert.ToBase64String(gzBuffer); } public static string Decompress(string compressedText) { byte[] gzBuffer = Convert.FromBase64String(compressedText); using (MemoryStream ms = new MemoryStream()) { int msgLength = BitConverter.ToInt32(gzBuffer, 0); ms.Write(gzBuffer, 4, gzBuffer.Length - 4); byte[] buffer = new byte[msgLength]; ms.Position = 0; using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress)) { zip.Read(buffer, 0, buffer.Length); } return Encoding.UTF8.GetString(buffer); } } public static string EnumName(T pObject) { return Enum.GetName(typeof(T), pObject); } public static T EnumParse(string pValue) { return (T)Enum.Parse(typeof(T), pValue); } public static IEnumerable GetAllEnumValues() { return Enum.GetValues(typeof(T)).Cast(); } public static List GetDayOfWeeks(DayOfWeek lFirst) { var lResult = new List(); DateTime lStart = DateTime.Now; while (lStart.DayOfWeek != lFirst) { lStart = lStart.AddDays(1); } for (int i = 1; i < 8; i++) { lResult.Add(lStart.DayOfWeek); lStart = lStart.AddDays(1); } return lResult; } public static int GetWholeWorkWeekCount(DateTime pStart, DateTime pEnd) { return GetWholeWorkWeeks(pStart, pEnd).Count(); } public static List GetWholeWorkWeeks(DateTime pStart, DateTime pEnd) { while (pStart.DayOfWeek != DayOfWeek.Monday) { pStart = pStart.AddDays(1); } List lResult = new List(); while ((pStart = pStart.AddDays(4)) <= pEnd.Date) { lResult.Add(new DateTimeSpan { StartDateTime = pStart.AddDays(-4), EndDateTime = pStart.AddDays(1).AddMilliseconds(-1) }); pStart = pStart.AddDays(3); } return lResult; } public static bool IsAnyNull(params object[] pObjects) { foreach (object iO in pObjects) { if (iO == null) { return true; } } return false; } public static bool IsAnyNullOrEmpty(params string[] pStrings) { foreach (string iString in pStrings) { if (String.IsNullOrEmpty(iString)) { return true; } } return false; } public static Queue MakeQueue(params T[] items) { return new Queue(items); } public static string MyHtmlEncode(string pString) { StringBuilder htmlk = new StringBuilder(); int ia = 0; for (int i = 0; i < pString.Length; i++) { char c = pString[i]; if (criticals.ContainsKey(c)) { htmlk.Append(pString.Substring(ia, i - ia)); htmlk.Append(criticals[c]); ia = i + 1; } } htmlk.Append(pString.Substring(ia)); return htmlk.ToString(); } public static NullCompareResult NullCompare(object pO1, object pO2) { NullCompareResult lResult = new NullCompareResult(); lResult.Different = (pO1 == null && pO2 != null) || (pO1 != null && pO2 == null); lResult.BothNotNull = pO1 != null && pO2 != null; return lResult; } public static byte[] ReadFully(Stream stream) { byte[] buffer = new byte[32768]; using (MemoryStream ms = new MemoryStream()) { while (true) { int read = stream.Read(buffer, 0, buffer.Length); if (read <= 0) { return ms.ToArray(); } ms.Write(buffer, 0, read); } } } public static void ReadWriteStream(Stream readStream, Stream writeStream) { int Length = 256; byte[] buffer = new byte[Length]; int bytesRead = readStream.Read(buffer, 0, Length); while (bytesRead > 0) { writeStream.Write(buffer, 0, bytesRead); bytesRead = readStream.Read(buffer, 0, Length); } readStream.Close(); writeStream.Close(); } public static T XMLDeserialize(string pPath) { T lResult = default(T); using (var uFS = File.Open(pPath, FileMode.Open)) { var lSerialzer = new XmlSerializer(typeof(T)); lResult = (T)lSerialzer.Deserialize(uFS); } return lResult; } public static T XMLDeserializeFromString(string serializedXML) { T lResult = default(T); if (!String.IsNullOrEmpty(serializedXML)) { var lSerialzer = new XmlSerializer(typeof(T)); StringReader r = new StringReader(serializedXML); lResult = (T)lSerialzer.Deserialize(r); } return lResult; } public static object XMLDeserializeFromString(string serializedXML, Type type) { object lResult = null; if (!String.IsNullOrEmpty(serializedXML)) { var lSerialzer = new XmlSerializer(type); StringReader r = new StringReader(serializedXML); lResult = lSerialzer.Deserialize(r); } return lResult; } public static void XMLSerialize(string pPath, T pObject) { if (!Directory.Exists(Path.GetDirectoryName(pPath))) { Directory.CreateDirectory(Path.GetDirectoryName(pPath)); } using (var uFS = File.Create(pPath)) { var lSerialzer = new XmlSerializer(typeof(T)); lSerialzer.Serialize(uFS, pObject); } } public static string XMLSerializeToString(object pObject) { var lSerialzer = new XmlSerializer(pObject.GetType()); StringWriter strw = new StringWriter(); lSerialzer.Serialize(strw, pObject); string str = strw.ToString(); int test = str.Length; return str; } public static void SaveExceptionAsTextFile(string pPath, Exception e) { #if DEBUG var directoryName = Path.GetDirectoryName(pPath); if (directoryName != null) { if (!Directory.Exists(directoryName)) return; } var innerException = e.InnerException; var sw = new StreamWriter(pPath, true); sw.WriteLine(e.Message); sw.WriteLine(e.StackTrace + "\n"); while (innerException != null) { sw.WriteLine(innerException.Message); sw.WriteLine(innerException.StackTrace + "\n"); innerException = innerException.InnerException; } sw.Flush(); sw.Close(); #endif } public static int ToInt(T e) where T : struct, IComparable, IFormattable, IConvertible // where T : Enum is not possible { return (int)(Object)e; } public static byte[] ErstelleThumbnail(byte[] data, int width, int height) { var imageOriginal = CreateImageFromByteArray(data); if (imageOriginal == null) { return null; } var originalW = imageOriginal.Width; var originalH = imageOriginal.Height; DateTime? originRecordDateTime; var smallImage = ResizeImage(imageOriginal, new Size(width, height)); var smallData = CreateByteArrayFromImage(smallImage); smallImage.Dispose(); return smallData; } public static Image CreateImageFromByteArray(byte[] data) { try { using (var ms = new MemoryStream(data)) { ms.Position = 0; var image = Image.FromStream(ms); return image; } } catch (Exception) { return null; } } public static BitmapImage CreateBitmapImageFromByteArray(byte[] array) { try { using (var ms = new MemoryStream(array)) { var image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; // here image.StreamSource = ms; image.EndInit(); return image; } } catch (Exception) { return null; } } public static byte[] CreateByteArrayFromImageSource(ImageSource imageSource) { byte[] bytes = null; var bitmapSource = imageSource as BitmapSource; if (bitmapSource != null) { var encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); using (var stream = new MemoryStream()) { encoder.Save(stream); bytes = stream.ToArray(); } } return bytes; } public static Image ResizeImage(Image original, Size size) { var newSize = CalcSize(original.Width, original.Height, size.Width, size.Height); var newImage = new Bitmap(newSize.Width, newSize.Height); using (var graphicsHandle = Graphics.FromImage(newImage)) { graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic; graphicsHandle.DrawImage(original, 0, 0, newSize.Width, newSize.Height); } return newImage; } public static byte[] CreateByteArrayFromImage(Image image) { if (image != null) { using (var memoryStream = new MemoryStream()) { image.Save(memoryStream, ImageFormat.Jpeg); return memoryStream.ToArray(); } } return null; } public static Bitmap CropImage(Image image) { var originalBitmap = new Bitmap(image); var min = new Point(int.MaxValue, int.MaxValue); var max = new Point(int.MinValue, int.MinValue); for(var x = 0; x < originalBitmap.Width; ++x) { for(var y = 0; y < originalBitmap.Height; ++y) { var pixelColor = originalBitmap.GetPixel(x, y); if (!(pixelColor.R == 255 && pixelColor.G == 255 && pixelColor.B == 255) && pixelColor.A > 0) { if (x < min.X) min.X = x; if (y < min.Y) min.Y = y; if (x > max.X) max.X = x; if (y > max.Y) max.Y = y; } } } // Create a new bitmap from the crop rectangleig if (min.X < int.MaxValue && min.Y < int.MaxValue && max.X > int.MinValue && max.Y > int.MinValue) { var cropRectangle = new Rectangle(min.X, min.Y, max.X - min.X, max.Y - min.Y); if (cropRectangle.Width > 0 && cropRectangle.Height > 0) { var newBitmap = new Bitmap(cropRectangle.Width, cropRectangle.Height); using (var graphics = Graphics.FromImage(newBitmap)) { graphics.DrawImage(originalBitmap, 0, 0, cropRectangle, GraphicsUnit.Pixel); } return newBitmap; } } return originalBitmap; } private static Size CalcSize(int originalWidth, int originalHeight, int desiredWidth, int desiredHeight) { var percentWidth = desiredWidth / (float)originalWidth; var percentHeight = desiredHeight / (float)originalHeight; var percent = percentHeight < percentWidth ? percentHeight : percentWidth; var width = (int)Math.Round(originalWidth * percent, MidpointRounding.AwayFromZero); var height = (int)Math.Round(originalHeight * percent, MidpointRounding.AwayFromZero); if (width == 0) { width = 1; } if (height == 0) { height = 1; } return new Size(width, height); } public static List GetParentTextModules(List childTextModules) { _Parents.Clear(); foreach(var textModule in childTextModules) { GetParentTextModule(textModule); } return _Parents; } private static readonly List _Parents = new List(); private static void GetParentTextModule(TextModuleDC textModule) { if (textModule.Parent != null) { _Parents.AddIfNotIn(textModule.Parent); GetParentTextModule(textModule.Parent); } } public static string CollectionToString(string pSeperator, IEnumerable pCollection) { pSeperator += " "; var result = ""; var enumerator = pCollection.GetEnumerator(); while(enumerator.MoveNext()) { var currentString = enumerator.Current?.ToString(); result += currentString + pSeperator; } return result.Trim(pSeperator?.ToCharArray()); } public static long? ParseObjectToNullableLong(object object2Parse) { if(object2Parse == null) { return null; } var wasSuccessful = Int64.TryParse(object2Parse.ToString(), out var output); if(wasSuccessful) { return output; } return null; } public static bool CheckSchedulerRights(List pCustomerList, List pResourceList, List pEmployeeList, CompactEmployeeDC pOriginator, bool pIsNew, SchedulerRightsCheckType pCheckType, UserDC pLoggedOnUser, List teamMemberCustomerOids, bool ignoreViewEditCreateAllRights = false) { var loggedInEmployee = pLoggedOnUser.Employee; var isAllowedToViewEverything = !ignoreViewEditCreateAllRights && pLoggedOnUser.HasRight(UserRightType.ViewAll); var isAllowedToEditEverything = !ignoreViewEditCreateAllRights && pLoggedOnUser.HasRight(UserRightType.EditAll); var isAllowedToCreateEverything = !ignoreViewEditCreateAllRights && pLoggedOnUser.HasRight(UserRightType.CreateAll); var isAllowedToViewCustomers = pLoggedOnUser.HasRight(UserRightType.CustomerView_View); var isAllowedToViewMyTeamsCustomers = pLoggedOnUser.HasRight(UserRightType.Customer_ViewMyTeams); var isAllowedToViewOwnCustomers = pLoggedOnUser.HasRight(UserRightType.Customer_ViewMyCustomers); var isAllowedToViewAllCustomerAppointments = pLoggedOnUser.HasRight(UserRightType.KalenderKliententermineAlleAnsehen); var isAllowedToCreateCustomerAppointments = pLoggedOnUser.HasRight(UserRightType.KalenderKliententermineAnlegen); var isAllowedToEditCustomerAppointments = pLoggedOnUser.HasRight(UserRightType.KalenderKliententermineAendern); var isAllowedToViewEmployeeAppointments = pLoggedOnUser.HasRight(UserRightType.KalenderMitarbeitertermineAnsehen); var isAllowedToCreateEmployeeAppointments = pLoggedOnUser.HasRight(UserRightType.KalenderMitarbeitertermineAnlegen); var isAllowedToEditEmployeeAppointments = pLoggedOnUser.HasRight(UserRightType.KalenderMitarbeitertermineAendern); var isAllowedToViewResourceAppointments = pLoggedOnUser.HasRight(UserRightType.KalenderRessourcentermineAnsehen); var isAllowedToCreateResourceAppointments = pLoggedOnUser.HasRight(UserRightType.KalenderRessourcentermineAnlegen); var isAllowedToEditResourceAppointments = pLoggedOnUser.HasRight(UserRightType.KalenderRessourcentermineAendern); var isAllowedToEditOtherEmployeesResourceAppointments = pLoggedOnUser.HasRight(UserRightType.KalenderRessourcentermineAndererAendern); var hasEmployees = pEmployeeList?.Count > 0; var hasCustomers = pCustomerList?.Count > 0; var hasResources = pResourceList?.Count > 0; // Prüfen, ob die Klienten alle in der Liste des Employees sind! var relatedCustomerOids = new List(loggedInEmployee.RelatedCustomerOIDList); relatedCustomerOids.AddRangeIfElementsNotIn(teamMemberCustomerOids); var hasOnlyOwnCustomers = pCustomerList?.All(c => loggedInEmployee.RelatedCustomerOIDList.Contains(c.CustomerOid)) ?? false; var hasOnlyTeamMembersCustomers = pCustomerList?.All(c => teamMemberCustomerOids.Contains(c.CustomerOid)) ?? false; var isOwnAppointment = Equals(pOriginator, loggedInEmployee); var employeeListOnlyContainsEmployee = pEmployeeList?.Count == 1 && pEmployeeList[0].Employee.Equals(loggedInEmployee); var employeeIsInList = pEmployeeList?.Any(a => Equals(loggedInEmployee, a.Employee)) ?? false; var result = true; switch(pCheckType) { case SchedulerRightsCheckType.View: if(isAllowedToViewEverything || employeeIsInList) { return true; } if(hasEmployees) { if(!employeeListOnlyContainsEmployee) { result = isAllowedToViewEmployeeAppointments; } } if(!result) { return false; } if(hasCustomers) { if(isAllowedToViewAllCustomerAppointments && isAllowedToViewCustomers) { return true; } if(isAllowedToViewMyTeamsCustomers && hasOnlyTeamMembersCustomers) { return true; } return isAllowedToViewOwnCustomers && hasOnlyOwnCustomers; } if(!result) { return false; } if(hasResources) { result = isOwnAppointment ? isAllowedToViewResourceAppointments : isAllowedToViewEmployeeAppointments && isAllowedToViewResourceAppointments; } break; case SchedulerRightsCheckType.Create: if(isAllowedToCreateEverything) { return true; } if(hasEmployees) { result = isAllowedToCreateEmployeeAppointments; if(!result) { return false; } } if(hasCustomers) { result = !hasOnlyOwnCustomers ? isAllowedToViewAllCustomerAppointments : isAllowedToCreateCustomerAppointments; if(!result) { return false; } } if(hasResources) { result = isAllowedToCreateResourceAppointments; } break; case SchedulerRightsCheckType.Edit: if(isAllowedToEditEverything) { return true; } if(!isOwnAppointment || hasEmployees && !employeeListOnlyContainsEmployee) { result = isAllowedToEditEmployeeAppointments; if(hasResources) { result = isAllowedToEditResourceAppointments; } if(!result) { return false; } } if(hasCustomers) { result = isAllowedToEditCustomerAppointments; if(!result) { return false; } } if(hasResources) { // ToDo: Hier beachten, ob employeeListOnlyContainsEmployee true ist if(employeeListOnlyContainsEmployee) { return isAllowedToEditResourceAppointments; } result = hasEmployees ? isAllowedToEditOtherEmployeesResourceAppointments : isAllowedToEditResourceAppointments; } break; default: return false; } return result; } public static bool CheckSchedulerRights(SchedulerAppointmentDC pAppointment, SchedulerRightsCheckType pCheckType, UserDC pLoggedOnUser, List teamMemberCustomerOids, bool ignoreViewEditCreateAllRights = false) { return CheckSchedulerRights(pAppointment.CustomerList, pAppointment.ResourceList, pAppointment.EmployeeList, pAppointment.Originator, !pAppointment.SchedulerAppointmentOid.HasValue, pCheckType, pLoggedOnUser, teamMemberCustomerOids, ignoreViewEditCreateAllRights); } public static bool IsPowerOfTwo(int number) { return ((number - 1) & number) == 0; } public static int FindClosestPowerOfTwo(int number) { if (IsPowerOfTwo(number)) { return number; } while (!IsPowerOfTwo(number)) { number--; } return number; } public static List GetWeekDaysFromNumber(int number) { var weekDays = new List(); if (number % 2 != 0) { number--; weekDays.Add(DayOfWeek.Sunday); } var closestPowerOfTwo = FindClosestPowerOfTwo(number); var rest = number - closestPowerOfTwo; weekDays.Add(DateTimeUtils.ConvertWeekDaysToDayOfWeek(DateTimeUtils.GetWeekDays(closestPowerOfTwo))); if (rest > 0) { do { closestPowerOfTwo = FindClosestPowerOfTwo(rest); rest -= closestPowerOfTwo; weekDays.Add(DateTimeUtils.ConvertWeekDaysToDayOfWeek(DateTimeUtils.GetWeekDays(closestPowerOfTwo))); } while (!IsPowerOfTwo(rest) || rest > 0); } return weekDays.OrderBy(day => (int)day).ToList(); } public static DateTime GetNextDateTime(DateTime pDate, DayOfWeek pDayOfWeek, int pPeriodicity, RecurrenceType pType) { var dow = pDate.DayOfWeek; if (dow > pDayOfWeek) { var date = pDate; do { date = date.AddDays(1); } while (date.DayOfWeek != pDayOfWeek); return CalculateNextDateTime(pType, date, pType == RecurrenceType.Weekly ? 7 * pPeriodicity - 1 : pPeriodicity - 1); } return CalculateNextDateTime(pType, pDate, pDayOfWeek - dow); } private static DateTime CalculateNextDateTime(RecurrenceType recurrenceType, DateTime date, int timeToAdd) { switch(recurrenceType) { case RecurrenceType.Daily: return date.AddDays(timeToAdd); case RecurrenceType.Weekly: return date.AddDays(timeToAdd); case RecurrenceType.Monthly: return date.AddMonths(timeToAdd); default: return date.AddYears(timeToAdd); } } public static readonly string TestAppointmentNotice = "k9Rx2mU4y"; public static string GetSexAbbrevation(Sex? sex) { switch(sex) { case Sex.Male: return "m"; case Sex.Female: return "w"; case Sex.Divers: return "d"; default: return string.Empty; } } public static string GetSexTranslation(Sex? sex, bool lowerCase = false) { string result; switch (sex) { case Sex.Male: result = "Männlich"; break; case Sex.Female: result = "Weiblich"; break; case Sex.Divers: result = "Divers"; break; default: result = string.Empty; break; } return lowerCase ? result.ToLowerInvariant() : result; } public static bool ContainsKey(string[] array, string key) { return array.Any(keyEntry => keyEntry.Equals(key)); } public static RecurrenceInformation GetOccurrenceId(string pRecurrenceInfoString) { var regex = new Regex("Index=\"[0-9]+\""); var match = regex.Match(pRecurrenceInfoString); var recurrenceInfo = new RecurrenceInfo(); recurrenceInfo.FromXml(pRecurrenceInfoString); var index = 0; if(!match.Value.IsNullOrEmpty()) { index = int.Parse(match.Value.Split('"')[1]); } return new RecurrenceInformation(recurrenceInfo.Id.ToString(), index); } public static string CreateSavePath(string tempPath, string filename) { var saveFilename = filename.Replace("..", "") .Replace("\"", "") .Replace("/", "") .Replace(":", "") .Replace(";", ""); return Path.Combine(tempPath, saveFilename); } /// /// Vergleicht die Elemente zweier Listen. Diese müssen vorher sortiert werden! /// /// Typ. Muss gleich sein /// Die erste Liste /// Die Liste mit der die erste Liste verglichen wird /// True, wenn die Elemente beider Listen gleich sind public static bool ListsEqual(IEnumerable a, IEnumerable b) { if(a == null && b == null) { return true; } if(a == null || b == null) { return false; } var x = a.ToArray(); var y = b.ToArray(); if(x.Length != y.Length) { return false; } for(var i = 0; i < x.Length; i++) { var obj1 = x[i]; var obj2 = y[i]; if(!(obj1?.Equals(obj2) ?? false)) { return false; } } return true; } public static string GetSpecificValueFromRecurrenceInfo(string recurrenecInfoString, int startIndex) { var valueBuilder = new StringBuilder(); for(; startIndex < recurrenecInfoString.Length; startIndex++) { var cr = recurrenecInfoString[startIndex]; if(cr.Equals('"')) { break; } valueBuilder.Append(cr); } return valueBuilder.ToString(); } public static Guid? GetRecurrenceIdFromRecurrenceInfo(string recurrenceInfo) { if(recurrenceInfo?.Length > 0) { var idString = GetSpecificValueFromRecurrenceInfo(recurrenceInfo, recurrenceInfo.IndexOf("Id=\"", StringComparison.InvariantCulture) + 4); if(Guid.TryParse(idString, out var recurrenceId)) { return recurrenceId; } } return null; } public static int GetRecurrenceIndexFromRecurrenceInfo(string recurrenceInfo) { if(recurrenceInfo?.Length > 0) { var indexString = GetSpecificValueFromRecurrenceInfo(recurrenceInfo, recurrenceInfo.IndexOf("Index=\"", StringComparison.InvariantCulture) + 7); if(int.TryParse(indexString, out var index)) { return index; } } return 0; } public static void WriteToTextFileOnDesktop(string fileName, string text) { #if DEBUG var path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); using(var fileStream = new FileStream($"{path}/{fileName}", FileMode.Append, FileAccess.Write)) { using(var streamWriter = new StreamWriter(fileStream)) { streamWriter.WriteLine(text); } } #endif } public static string SizeSuffix(Int64 value, int decimalPlaces = 1) { if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); } int i = 0; decimal dValue = (decimal)value; while (Math.Round(dValue, decimalPlaces) >= 1000) { dValue /= 1024; i++; } return string.Format("{0:n" + decimalPlaces + "} {1}", dValue, SizeSuffixes[i]); } public static int GetAge(DateTime birthday) => GetAge(birthday, DateTime.Today); public static int GetAge(DateTime birthday, DateTime compareTo) { if (compareTo <= birthday) return -1; // https://stackoverflow.com/a/1595311 int age = compareTo.Year - birthday.Year; // For leap years we need this if (birthday > compareTo.AddYears(-age)) age--; // Don't use: // if (birthDate.AddYears(age) > now) // age--; return age; } public static NameValueCollection ToNameValueCollection(T dynamicObject) { var nameValueCollection = new NameValueCollection(); foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(dynamicObject)) { string value = propertyDescriptor.GetValue(dynamicObject).ToString(); nameValueCollection.Add(propertyDescriptor.Name, value); } return nameValueCollection; } public static bool TryParseISO8601(string iso8601String, out DateTime date) { return DateTime.TryParse(iso8601String, out date); } public static string ConvertToISO88591(string input) { Encoding iso = Encoding.GetEncoding("ISO-8859-1"); Encoding utf8 = Encoding.UTF8; byte[] utfBytes = utf8.GetBytes(input); byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes); string msg = iso.GetString(isoBytes); return msg; } public static string ConvertToISO88591(byte[] utfBytes) { Encoding iso = Encoding.GetEncoding("ISO-8859-1"); Encoding utf8 = Encoding.UTF8; byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes); string msg = iso.GetString(isoBytes); return msg; } /// /// Wandelt einen JSON-String in ein Wörterbuch vom Typ Dictionary um. /// /// Die serialisierte Map /// Dictionary vom Typ Dictionary. public static Dictionary JsonMap2Dictionary(string json) { var dictionary = new Dictionary(); var pairs = JsonConvert.DeserializeObject>>(json); foreach(var pair in pairs) { if(pair.Count >= 2 && pair[0].HasValue) { dictionary[pair[0].Value] = pair[1]; } } return dictionary; } public static List ConvertCharSeparatedValuesToLongList(string csv, char separatorChar) { var split = csv.Split(separatorChar); var result = new List(); foreach(var splitValue in split) { result.Add(long.Parse(splitValue.Trim())); } return result; } } public struct NullCompareResult { public bool BothNotNull; public bool Different; } public struct ArbeitszeitEintragDateTimeObject { public DateTime Start { get; set; } public DateTime End { get; set; } public ArbeitszeitEintragDateTimeObject(DateTime start, DateTime end) { Start = start; End = end; } } }