using System;
|
using System.Collections.Generic;
|
using System.IO;
|
using System.Linq;
|
using System.Net.Http;
|
using System.Reflection;
|
using System.Text;
|
using System.Threading.Tasks;
|
using System.Web;
|
using System.Windows.Controls;
|
using System.Windows.Documents;
|
using System.Windows.Media;
|
using System.Windows;
|
using Newtonsoft.Json;
|
|
namespace PdmAlert.Util
|
{
|
public class MaskAdorner : Adorner
|
{
|
private UIElement child;
|
private TextBox textBox;
|
|
public static readonly Dictionary<Visual, MaskAdorner> cache = new Dictionary<Visual, MaskAdorner>();
|
|
public MaskAdorner(UIElement adornedElement, string message = null) : base(adornedElement)
|
{
|
textBox = new TextBox
|
{
|
TextAlignment = TextAlignment.Center,
|
Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)),
|
Text = message,
|
BorderThickness = new Thickness(0),
|
BorderBrush = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0))
|
};
|
StackPanel stackPanel = new StackPanel()
|
{
|
HorizontalAlignment = HorizontalAlignment.Center,
|
VerticalAlignment = VerticalAlignment.Center,
|
Background = new SolidColorBrush(Color.FromArgb(0, 255, 255, 255)),
|
};
|
stackPanel.Children.Add(new ProgressBar
|
{
|
Width = 100,
|
Height = 20,
|
IsIndeterminate = true
|
});
|
stackPanel.Children.Add(textBox);
|
Child = new Border
|
{
|
Background = new SolidColorBrush(Color.FromArgb(100, 0, 0, 0)),
|
HorizontalAlignment = HorizontalAlignment.Stretch,
|
VerticalAlignment = VerticalAlignment.Stretch,
|
Child = stackPanel
|
};
|
}
|
//Adorner 直接继承自 FrameworkElement,
|
//没有Content和Child属性,
|
//自己添加一个,方便向其中添加我们的控件
|
public UIElement Child
|
{
|
get => child;
|
set
|
{
|
if (value == null)
|
{
|
RemoveVisualChild(child);
|
}
|
else
|
{
|
AddVisualChild(value);
|
}
|
child = value;
|
}
|
}
|
//重写VisualChildrenCount 表示此控件只有一个子控件
|
protected override int VisualChildrenCount => 1;
|
//控件计算大小的时候,我们在装饰层上添加的控件也计算一下大小
|
protected override Size ArrangeOverride(Size finalSize)
|
{
|
child?.Arrange(new Rect(finalSize));
|
return finalSize;
|
}
|
//重写GetVisualChild,返回我们添加的控件
|
protected override Visual GetVisualChild(int index)
|
{
|
if (index == 0 && child != null) return child;
|
return base.GetVisualChild(index);
|
}
|
|
public void ShowMessage(string message)
|
{
|
this.textBox.Text = message;
|
}
|
|
|
public static void ShowMask(Visual visual, string message = null)
|
{
|
var sb = cache;
|
if (cache.ContainsKey(visual))
|
{
|
return;
|
}
|
visual.Dispatcher.Invoke(() =>
|
{
|
AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(visual);
|
if (adornerLayer == null) return;
|
Adorner[] ads = adornerLayer.GetAdorners(adornerLayer);
|
if (ads != null)
|
{
|
foreach (Adorner ad in ads)
|
{
|
if (ad is MaskAdorner adorner)
|
{
|
return;
|
}
|
}
|
}
|
//创建我们定义的Adorner
|
MaskAdorner _adorner = new MaskAdorner(adornerLayer, message);
|
//添加到adornerLayer装饰层上
|
adornerLayer.Add(_adorner);
|
cache.Add(visual, _adorner);
|
});
|
}
|
|
public static void ShowMessage(Visual visual, string message)
|
{
|
if (!cache.ContainsKey(visual))
|
{
|
return;
|
}
|
visual.Dispatcher.Invoke(() =>
|
{
|
AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(visual);
|
MaskAdorner mask = cache[visual];
|
if (mask == null)
|
{
|
return;
|
}
|
mask.ShowMessage(message);
|
});
|
}
|
|
public static void HideMask(Visual visual)
|
{
|
if (!cache.ContainsKey(visual))
|
{
|
return;
|
}
|
visual.Dispatcher.Invoke(() =>
|
{
|
if (cache.ContainsKey(visual))
|
{
|
AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(visual);
|
adornerLayer.Remove(cache[visual]);
|
cache.Remove(visual);
|
}
|
});
|
}
|
}
|
|
[Serializable]
|
public class Result<T>
|
{
|
[JsonProperty("success")]
|
public bool success
|
{
|
get; set;
|
}
|
|
[JsonProperty("message")]
|
public string message
|
{
|
get; set;
|
}
|
|
[JsonProperty("code")]
|
public int code
|
{
|
get; set;
|
}
|
|
[JsonProperty("result")]
|
public T result
|
{
|
get; set;
|
}
|
}
|
|
public class Page<T>
|
{
|
public int pageNo { get; set; }
|
public int pageSize { get; set; }
|
public int total { get; set; }
|
public int current { get; set; }
|
public int size { get; set; }
|
public List<T> records { get; set; }
|
}
|
|
public static class ResultHandler
|
{
|
public static T HandleResult<T>(this Result<T> result)
|
{
|
if (result.success)
|
{
|
return result.result;
|
}
|
throw new CustomWebException(result.message);
|
}
|
}
|
|
/// <summary>
|
/// 自定义从Web返回的异常
|
/// </summary>
|
public class CustomWebException : Exception
|
{
|
public CustomWebException()
|
{
|
|
}
|
|
public CustomWebException(string message) : base(message)
|
{
|
|
}
|
|
public CustomWebException(string message, Exception inner) : base(message, inner)
|
{
|
|
}
|
}
|
|
public class JsonUtil
|
{
|
static readonly JsonSerializerSettings JsSetting = new JsonSerializerSettings()
|
{
|
NullValueHandling = NullValueHandling.Ignore
|
};
|
|
public static T Deserialize<T>(string jsonStr)
|
{
|
return JsonConvert.DeserializeObject<T>(jsonStr);
|
}
|
|
public static string Serialize(object obj)
|
{
|
return JsonConvert.SerializeObject(obj);
|
}
|
|
public static string Stringfiy(object obj)
|
{
|
return JsonConvert.SerializeObject(obj, Formatting.Indented, JsSetting);
|
}
|
|
}
|
|
public static class HttpUtil
|
{
|
|
/// <summary>
|
/// Http GET 同步获取对象
|
/// </summary>
|
/// <typeparam name="T">对象类型</typeparam>
|
/// <param name="client">客户端</param>
|
/// <param name="url">url</param>
|
/// <param name="models">参数</param>
|
/// <returns>Http返回结果</returns>
|
public static Result<T> GetSyncAction<T>(this HttpClient client, string url, params object[] models)
|
{
|
return JsonUtil.Deserialize<Result<T>>(GetSyncAction(client, url, models));
|
}
|
|
/// <summary>
|
/// Http GET 同步获取字符
|
/// </summary>
|
/// <param name="client">客户端</param>
|
/// <param name="url">url</param>
|
/// <param name="models">参数</param>
|
/// <returns>Http返回结果</returns>
|
public static string GetSyncAction(this HttpClient client, string url, params object[] models)
|
{
|
try
|
{
|
foreach (object model in models)
|
{
|
url = url.ModelToUriParam(model);
|
}
|
|
Task<string> task = client.GetStringAsync(url);
|
task.Wait();
|
return task.Result;
|
}
|
catch (Exception e)
|
{
|
throw new CustomWebException("请求异常", e);
|
}
|
}
|
|
/// <summary>
|
/// Http GET 异步获取对象
|
/// </summary>
|
/// <typeparam name="T">对象类型</typeparam>
|
/// <param name="client">客户端</param>
|
/// <param name="url">url</param>
|
/// <param name="models">参数</param>
|
/// <returns>异步Http返回结果</returns>
|
public static async Task<Result<T>> GetAsyncAction<T>(this HttpClient client, string url, params object[] models)
|
{
|
try
|
{
|
foreach (object model in models)
|
{
|
url = url.ModelToUriParam(model);
|
}
|
return JsonUtil.Deserialize<Result<T>>(await client.GetStringAsync(url));
|
}
|
catch (Exception e)
|
{
|
throw new CustomWebException("请求异常", e);
|
}
|
}
|
|
/// <summary>
|
/// Http POST 同步获取对象
|
/// </summary>
|
/// <typeparam name="T">对象类型</typeparam>
|
/// <param name="client">客户端</param>
|
/// <param name="url">url</param>
|
/// <param name="data">参数json字符</param>
|
/// <returns>Http返回结果</returns>
|
public static Result<T> PostSyncAction<T>(this HttpClient client, string url, string data)
|
{
|
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
|
Task<HttpResponseMessage> task = client.PostAsync(url, content);
|
task.Wait();
|
HttpResponseMessage response = task.Result;
|
response.EnsureSuccessStatusCode();
|
Task<string> task2 = response.Content.ReadAsStringAsync();
|
task2.Wait();
|
string responseBody = task2.Result;
|
return JsonUtil.Deserialize<Result<T>>(responseBody);
|
}
|
|
/// <summary>
|
/// Http POST 同步获取对象
|
/// </summary>
|
/// <typeparam name="T">对象类型</typeparam>
|
/// <param name="client">客户端</param>
|
/// <param name="url">url</param>
|
/// <param name="content">Http负载</param>
|
/// <returns>Http返回结果</returns>
|
public static Result<T> PostSyncAction<T>(this HttpClient client, string url, HttpContent content)
|
{
|
Task<HttpResponseMessage> task = client.PostAsync(url, content);
|
task.Wait();
|
HttpResponseMessage response = task.Result;
|
response.EnsureSuccessStatusCode();
|
Task<string> task2 = response.Content.ReadAsStringAsync();
|
task2.Wait();
|
return JsonUtil.Deserialize<Result<T>>(task2.Result);
|
}
|
|
/// <summary>
|
/// Http POST 同步获取对象
|
/// </summary>
|
/// <typeparam name="T">对象类型</typeparam>
|
/// <param name="client">客户端</param>
|
/// <param name="data">参数对象</param>
|
/// <param name="url">url</param>
|
/// <returns>Http返回结果</returns>
|
public static Result<T> PostSyncAction<T>(this HttpClient client, object data, string url)
|
{
|
string dataStr = JsonUtil.Serialize(data);
|
StringContent content = new StringContent(dataStr, Encoding.UTF8, "application/json");
|
Task<HttpResponseMessage> task = client.PostAsync(url, content);
|
task.Wait();
|
HttpResponseMessage response = task.Result;
|
response.EnsureSuccessStatusCode();
|
Task<string> task2 = response.Content.ReadAsStringAsync();
|
task2.Wait();
|
string responseBody = task2.Result;
|
return JsonUtil.Deserialize<Result<T>>(responseBody);
|
}
|
|
public static string PostSyncAction(this HttpClient client, string url, string data)
|
{
|
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
|
Task<HttpResponseMessage> task = client.PostAsync(url, content);
|
task.Wait();
|
HttpResponseMessage response = task.Result;
|
response.EnsureSuccessStatusCode();
|
Task<string> task2 = response.Content.ReadAsStringAsync();
|
task2.Wait();
|
return task2.Result;
|
}
|
|
public static Result<T> PutSyncAction<T>(this HttpClient client, string url, object data = null)
|
{
|
StringContent content;
|
if (data != null)
|
{
|
string dataStr = JsonUtil.Serialize(data);
|
content = new StringContent(dataStr, Encoding.UTF8, "application/json");
|
}
|
else
|
{
|
content = new StringContent("");
|
}
|
Task<HttpResponseMessage> task = client.PutAsync(url, content);
|
task.Wait();
|
HttpResponseMessage response = task.Result;
|
response.EnsureSuccessStatusCode();
|
Task<string> task2 = response.Content.ReadAsStringAsync();
|
task2.Wait();
|
return JsonUtil.Deserialize<Result<T>>(task2.Result);
|
}
|
|
public static async Task<T> PostAsyncAction<T>(this HttpClient client, string url, string data)
|
{
|
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
|
HttpResponseMessage response = await client.PostAsync(url, content);
|
_ = response.EnsureSuccessStatusCode();
|
return JsonUtil.Deserialize<T>(await response.Content.ReadAsStringAsync());
|
}
|
|
public static async Task<Result<T>> PostAsyncAction<T>(this HttpClient client, string url, object data)
|
{
|
string dataStr = JsonUtil.Serialize(data);
|
StringContent content = new StringContent(dataStr, Encoding.UTF8, "application/json");
|
HttpResponseMessage response = await client.PostAsync(url, content);
|
_ = response.EnsureSuccessStatusCode();
|
return JsonUtil.Deserialize<Result<T>>(await response.Content.ReadAsStringAsync());
|
}
|
|
public static async Task<Result<T>> PostAsyncAction<T>(this HttpClient client, string url, HttpContent content)
|
{
|
HttpResponseMessage response = await client.PostAsync(url, content);
|
_ = response.EnsureSuccessStatusCode();
|
return JsonUtil.Deserialize<Result<T>>(await response.Content.ReadAsStringAsync());
|
}
|
|
/// <summary>
|
/// 下载文件保存到绝对路径
|
/// </summary>
|
/// <param name="client"></param>
|
/// <param name="url"></param>
|
/// <param name="absolutePath"></param>
|
/// <param name="models"></param>
|
public static async Task GetDownload(this HttpClient client, string url, string absolutePath, params object[] models)
|
{
|
foreach (object model in models)
|
{
|
url = url.ModelToUriParam(model);
|
}
|
HttpResponseMessage response = await client.GetAsync(url);
|
int code = Convert.ToInt32(response.StatusCode);
|
if (code == 200)
|
{
|
using (Stream stream = await response.Content.ReadAsStreamAsync())
|
{
|
string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
|
using (FileStream fs = new FileStream(absolutePath, FileMode.OpenOrCreate))
|
{
|
byte[] buffer = new byte[1024];
|
int readLength = 0;
|
int length;
|
while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
|
{
|
readLength += length;
|
fs.Write(buffer, 0, length);
|
}
|
}
|
}
|
}
|
else
|
{
|
string error = "图纸下载失败";
|
if (response.Headers.TryGetValues("FileName", out IEnumerable<string> values))
|
{
|
error = values.First();
|
}
|
throw new CustomWebException(error);
|
}
|
}
|
|
/// <summary>
|
/// 下载文件保存到绝对路径
|
/// </summary>
|
/// <param name="client"></param>
|
/// <param name="url"></param>
|
/// <param name="absolutePath"></param>
|
/// <param name="models"></param>
|
public static void GetDownloadSync(this HttpClient client, string url, string absolutePath, params object[] models)
|
{
|
foreach (object model in models)
|
{
|
url = url.ModelToUriParam(model);
|
}
|
Task<HttpResponseMessage> task = client.GetAsync(url);
|
task.Wait();
|
HttpResponseMessage response = task.Result;
|
int code = Convert.ToInt32(response.StatusCode);
|
if (code == 200)
|
{
|
Task<Stream> task2 = response.Content.ReadAsStreamAsync();
|
task2.Wait();
|
using (Stream stream = task2.Result)
|
{
|
string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
|
using (FileStream fs = new FileStream(absolutePath, FileMode.OpenOrCreate))
|
{
|
byte[] buffer = new byte[1024];
|
int readLength = 0;
|
int length;
|
while ((length = stream.Read(buffer, 0, buffer.Length)) != 0)
|
{
|
readLength += length;
|
fs.Write(buffer, 0, length);
|
}
|
}
|
}
|
}
|
else
|
{
|
string error = "图纸下载失败";
|
if (response.Headers.TryGetValues("FileName", out IEnumerable<string> values))
|
{
|
error = HttpUtility.UrlDecode(values.First());
|
}
|
throw new CustomWebException(error);
|
}
|
}
|
|
/// <summary>
|
/// 下载文件到指定文件夹
|
/// </summary>
|
/// <param name="client"></param>
|
/// <param name="url"></param>
|
/// <param name="dir"></param>
|
/// <param name="fileName"></param>
|
/// <param name="models"></param>
|
public static async Task GetDownload(this HttpClient client, string url, string dir, string fileName, params object[] models)
|
{
|
foreach (object model in models)
|
{
|
url = url.ModelToUriParam(model);
|
}
|
HttpResponseMessage response = await client.GetAsync(url);
|
using (Stream stream = await response.Content.ReadAsStreamAsync())
|
{
|
string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
|
using (FileStream fs = new FileStream($"{dir}/{fileName}", FileMode.CreateNew))
|
{
|
byte[] buffer = new byte[1024];
|
int readLength = 0;
|
int length;
|
while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
|
{
|
readLength += length;
|
fs.Write(buffer, 0, length);
|
}
|
}
|
}
|
}
|
|
public static async void GetDownloadWithName(this HttpClient client, string url, string dir, params object[] models)
|
{
|
foreach (object model in models)
|
{
|
url = url.ModelToUriParam(model);
|
}
|
|
HttpResponseMessage response = await client.GetAsync(url);
|
string fileName = HttpUtility.UrlDecode(response.Headers.GetValues("FileName").FirstOrDefault());
|
using (Stream stream = await response.Content.ReadAsStreamAsync())
|
{
|
string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
|
using (FileStream fs = new FileStream($"{dir}/{fileName}", FileMode.CreateNew))
|
{
|
byte[] buffer = new byte[1024];
|
int readLength = 0;
|
int length;
|
while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
|
{
|
readLength += length;
|
fs.Write(buffer, 0, length);
|
}
|
}
|
}
|
}
|
|
public static string ModelToUriParam(this string url, object obj)
|
{
|
PropertyInfo[] properties = obj.GetType().GetProperties();
|
StringBuilder sb = new StringBuilder()
|
.Append(url).Append("?");
|
if (obj is Dictionary<string, string>)
|
{
|
Dictionary<string, string> dict = (Dictionary<string, string>)obj;
|
foreach (var item in dict)
|
{
|
if (item.Value == null || string.IsNullOrWhiteSpace(item.Value))
|
{
|
continue;
|
}
|
sb = sb.Append(item.Key)
|
.Append("=")
|
.Append(HttpUtility.UrlEncode(item.Value))
|
.Append("&");
|
}
|
}
|
else
|
{
|
foreach (PropertyInfo p in properties)
|
{
|
object v = p.GetValue(obj, null);
|
if (v == null || string.IsNullOrWhiteSpace(v.ToString()))
|
{
|
continue;
|
}
|
sb = sb.Append(p.Name)
|
.Append("=")
|
.Append(HttpUtility.UrlEncode(v.ToString()))
|
.Append("&");
|
}
|
}
|
sb = sb.Remove(sb.Length - 1, 1);
|
return sb.ToString();
|
}
|
}
|
}
|