Files
Chat/ChatController/Utilities/Utils.cs

463 lines
15 KiB
C#
Raw Normal View History

2019-04-02 13:43:30 +02:00
using System;
using System.Collections.Generic;
using System.Diagnostics;
2019-04-02 13:43:30 +02:00
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
2019-04-02 13:43:30 +02:00
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
2019-04-02 13:43:30 +02:00
using System.Windows.Media;
using System.Windows.Media.Imaging;
2020-04-17 13:01:23 +02:00
using RestSharp;
using MessageBox = System.Windows.MessageBox;
using PixelFormat = System.Drawing.Imaging.PixelFormat;
2019-04-02 13:43:30 +02:00
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);
2019-04-04 13:00:10 +02:00
public static ImageSource AvatarToImageSourceConverter(string pAvatarPath, bool pIsEmployee, bool pIsGroup)
2019-04-02 13:43:30 +02:00
{
return CreateImageSourceFromPath(pAvatarPath, pIsGroup, pIsEmployee);
2019-04-02 13:43:30 +02:00
}
public static Bitmap ConvertAvatarToBitmap(string linkToPicture, bool isEmployee, bool isGroup)
2019-04-02 13:43:30 +02:00
{
Bitmap bitmap = null;
if(!string.IsNullOrWhiteSpace(linkToPicture))
{
Debug.WriteLine("Lade Bitmap herunter...");
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<ImageSource> 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);
}
};
2019-04-02 13:43:30 +02:00
}
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;
}
2019-04-02 13:43:30 +02:00
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))
{
Debug.WriteLine("Lade Bild herunter...");
2020-04-17 13:01:23 +02:00
Bitmap bitmap = null;
var client = new RestClient(pPathToImageFile);
2020-04-17 13:01:23 +02:00
var request = new RestRequest(Method.GET)
2019-04-02 13:43:30 +02:00
{
2020-04-17 13:01:23 +02:00
ResponseWriter = stream =>
2019-04-02 13:43:30 +02:00
{
2020-04-17 13:01:23 +02:00
try
2019-04-02 13:43:30 +02:00
{
bitmap = new Bitmap(stream);
}
2020-04-17 13:01:23 +02:00
catch (ArgumentException)
2019-04-02 13:43:30 +02:00
{
2020-04-17 13:01:23 +02:00
bitmap = null;
2019-04-02 13:43:30 +02:00
}
}
2020-04-17 13:01:23 +02:00
};
request.AddHeader(Constants.Token, AuthToken);
request.AddHeader(Constants.CustomerId, Tenant);
2020-04-17 13:01:23 +02:00
client.DownloadData(request);
2019-04-02 13:43:30 +02:00
2020-04-17 13:01:23 +02:00
if (bitmap != null)
2019-04-02 13:43:30 +02:00
{
2020-04-17 13:01:23 +02:00
using (var memoryStream = new MemoryStream())
{
bitmap.Save(memoryStream, ImageFormat.Png);
2019-04-02 13:43:30 +02:00
2020-04-17 13:01:23 +02:00
memoryStream.Position = 0;
2019-04-02 13:43:30 +02:00
2020-04-17 13:01:23 +02:00
var bitmapImage = new BitmapImage();
2019-04-02 13:43:30 +02:00
2020-04-17 13:01:23 +02:00
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
2019-04-02 13:43:30 +02:00
2020-04-17 13:01:23 +02:00
return bitmapImage;
}
2019-04-02 13:43:30 +02:00
}
}
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<T> GetVisualChildCollection<T>(object parent) where T : Visual
{
var visualCollection = new List<T>();
GetVisualChildCollection(parent as DependencyObject, visualCollection);
return visualCollection;
}
public static void GetVisualChildCollection<T>(DependencyObject parent, ICollection<T> 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;
}
}
2019-04-02 13:43:30 +02:00
}
}