using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; using RestSharp; using MessageBox = System.Windows.MessageBox; using PixelFormat = System.Drawing.Imaging.PixelFormat; namespace ChatController.Utilities { public class Utils { public static string AuthToken { get; set; } public static string Tenant { get; set; } public static DateTime DefaultDate = new DateTime(1, 1, 1); public static ImageSource AvatarToImageSourceConverter(string pAvatarPath, bool pIsEmployee, bool pIsGroup) { return CreateImageSourceFromPath(pAvatarPath, pIsGroup, pIsEmployee); } public static Bitmap ConvertAvatarToBitmap(string linkToPicture, bool isEmployee, bool isGroup) { Bitmap bitmap = null; if(!string.IsNullOrWhiteSpace(linkToPicture)) { var client = new RestClient(linkToPicture); var request = new RestRequest(Method.GET) { ResponseWriter = responseStream => { try { bitmap = new Bitmap(responseStream); } catch(Exception exception) { } } }; request.AddHeader(Constants.Token, AuthToken); request.AddHeader(Constants.CustomerId, Tenant); client.DownloadData(request); } if(bitmap != null) { return bitmap; } var defaultBitmap = (BitmapImage) GetDefaultImageSource(isGroup, isEmployee); using(var outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(defaultBitmap)); enc.Save(outStream); return new Bitmap(outStream); } } public static void DownloadProfilePictureAsync(string avatarPath, bool isEmployee, bool isGroup, Action callback) { var url = avatarPath; var client = new RestClient(url); var request = new RestRequest { ResponseWriter = stream => { var bitmap = new BitmapImage(); var localStream = new MemoryStream(); stream.CopyTo(localStream); localStream.Position = 0; bitmap.BeginInit(); bitmap.StreamSource = localStream; bitmap.EndInit(); bitmap.Freeze(); callback?.Invoke(bitmap); } }; } private static ImageSource GetDefaultImageSource(bool pIsGroup, bool pIsEmployee) { var defaultImage = Constants.EmployeeDefaultImagePath; if (pIsGroup) { defaultImage = pIsEmployee ? Constants.TeamDefaultImagePath : Constants.NormalGroupDefaultImagePath; } else if (!pIsEmployee) { defaultImage = Constants.CustomerDefaultImagePath; } var resultBitmapImage = new BitmapImage(); resultBitmapImage.BeginInit(); resultBitmapImage.UriSource = new Uri(defaultImage); resultBitmapImage.EndInit(); return resultBitmapImage; } public static ImageSource CreateImageSourceFromPath(string pPathToImageFile, bool pIsGroup = false, bool pIsEmployee = false) { if (!string.IsNullOrEmpty(pPathToImageFile)) { Bitmap bitmap = null; var client = new RestClient(pPathToImageFile); var request = new RestRequest(Method.GET) { ResponseWriter = stream => { try { bitmap = new Bitmap(stream); } catch (ArgumentException) { bitmap = null; } } }; request.AddHeader(Constants.Token, AuthToken); request.AddHeader(Constants.CustomerId, Tenant); client.DownloadData(request); if (bitmap != null) { using (var memoryStream = new MemoryStream()) { bitmap.Save(memoryStream, ImageFormat.Png); memoryStream.Position = 0; var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.StreamSource = memoryStream; bitmapImage.EndInit(); return bitmapImage; } } } return GetDefaultImageSource(pIsGroup, pIsEmployee); } public static string ReadStream(WebResponse response) { var dataStream = response.GetResponseStream(); if (dataStream == null) { return null; } var reader = new StreamReader(dataStream); var responseFromServer = reader.ReadToEnd(); dataStream.Dispose(); reader.Dispose(); dataStream.Close(); reader.Close(); return responseFromServer; } public static string GetAndCreateUserAppDataPath() { try { var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var companyFilePath = Path.Combine(localAppData, Resource.CompanyName); if (!Directory.Exists(companyFilePath)) { Directory.CreateDirectory(companyFilePath); } var bewoFilePath = Path.Combine(companyFilePath, Resource.ApplicationFolderName); if (!Directory.Exists(bewoFilePath)) { Directory.CreateDirectory(bewoFilePath); } return bewoFilePath; } catch (Exception exception) { MessageBox.Show("Fehler beim Anlegen des Anwendungsordners. Sie besitzen nicht die erforderlichen Rechte, bitte wenden Sie sich an Ihren Systemadministrator.\n" + exception.Message, "BeWoPlaner", MessageBoxButton.OK, MessageBoxImage.Exclamation); } return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } public static string GenerateTempName() { const int length = 6; const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var random = new Random(); var tempName = new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray()); return tempName; } public static byte[] ImageToByteArray(Image pImage) { try { using (var memoryStream = new MemoryStream()) { pImage.Save(memoryStream, ImageFormat.Bmp); return memoryStream.ToArray(); } } catch (Exception e) { MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK); return null; } } public static ImageSource GetImageSourceFromIcon(Icon pIcon) { var bitmap = new Bitmap(pIcon.Width, pIcon.Height); var graphics = Graphics.FromImage(bitmap); graphics.DrawIcon(pIcon, 0, 0); graphics.Dispose(); bitmap.Save("icon.ico", ImageFormat.Icon); var imageSource = ImageSourceForBitmap(bitmap); bitmap.Dispose(); return imageSource; } [DllImport("gdi32.dll", EntryPoint = "DeleteObject")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DeleteObject([In] IntPtr hObject); public static ImageSource ImageSourceForBitmap(Bitmap bmp) { var handle = bmp.GetHbitmap(); try { return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } finally { DeleteObject(handle); } } public static Icon ImageSourceToIcon(ImageSource pImageSource) { var bitmapSource = (BitmapSource) pImageSource; var width = bitmapSource.PixelWidth; var height = bitmapSource.PixelHeight; var newWidth = width; var newHeight = height; var x = 0; var y = 0; if(width < height) { newHeight = width; y = (height - width) / 2; } else { newWidth = height; x = (width - height) / 2; } var stride = width * ((bitmapSource.Format.BitsPerPixel + 7) / 8); var memoryBlockPointer = Marshal.AllocHGlobal(height * stride); bitmapSource.CopyPixels(new Int32Rect(x, y, newWidth, newHeight), memoryBlockPointer, newHeight * stride, stride); var bitmap = new Bitmap(newWidth, newHeight, stride, PixelFormat.Format32bppPArgb, memoryBlockPointer); return Icon.FromHandle(bitmap.GetHicon()); } public static byte[] ReadFully(Stream pStream) { using (var memStream = new MemoryStream()) { pStream.CopyTo(memStream); return memStream.ToArray(); } } public static RotateFlipType OrientationToFlipType(string orientation) { switch (int.Parse(orientation)) { case 1: return RotateFlipType.RotateNoneFlipNone; case 2: return RotateFlipType.RotateNoneFlipX; case 3: return RotateFlipType.Rotate180FlipNone; case 4: return RotateFlipType.Rotate180FlipX; case 5: return RotateFlipType.Rotate90FlipX; case 6: return RotateFlipType.Rotate90FlipNone; case 7: return RotateFlipType.Rotate270FlipX; case 8: return RotateFlipType.Rotate270FlipNone; default: return RotateFlipType.RotateNoneFlipNone; } } public static List GetVisualChildCollection(object parent) where T : Visual { var visualCollection = new List(); GetVisualChildCollection(parent as DependencyObject, visualCollection); return visualCollection; } public static void GetVisualChildCollection(DependencyObject parent, ICollection visualCollection) where T : Visual { var count = VisualTreeHelper.GetChildrenCount(parent); for(var i = 0; i < count; i++) { var child = VisualTreeHelper.GetChild(parent, i); if(child is T item) { visualCollection.Add(item); } else { GetVisualChildCollection(child, visualCollection); } } } /* * try { using (var form = new Form()) { using (var ms = new MemoryStream(e.Result)) { var image = System.Drawing.Image.FromStream(ms); using (var bitmap = new Bitmap(image)) { short orient = 0; const int orientationId = 0x0112; if (image.PropertyIdList.Contains(orientationId)) { var item = image.GetPropertyItem(orientationId); orient = BitConverter.ToInt16(item.Value, 0); bitmap.SetPropertyItem(item); } var flipType = Utils.OrientationToFlipType(orient.ToString()); bitmap.RotateFlip(flipType); form.StartPosition = FormStartPosition.CenterScreen; form.ClientSize = bitmap.Size; form.FormBorderStyle = FormBorderStyle.Sizable; form.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); using (var pictureBox = new PictureBox()) { pictureBox.Dock = DockStyle.Fill; pictureBox.Image = bitmap; pictureBox.SizeMode = PictureBoxSizeMode.Zoom; form.Controls.Add(pictureBox); downloadCompletedCallback?.Invoke(); form.ShowDialog(); } } } } */ public Bitmap ConvertStreamToBitmap(Stream imageStream) { try { var image = Image.FromStream(imageStream); return null; } catch(Exception exception) { throw exception; } } } }