501 lines
19 KiB
C#
501 lines
19 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Drawing;
|
|
using System.Globalization;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Net.Http;
|
|
using System.Net.NetworkInformation;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace LPA
|
|
{
|
|
public class utils
|
|
{
|
|
|
|
|
|
#region gestione log
|
|
|
|
|
|
/// <summary>
|
|
/// Oggetto per moderazione scrittura log
|
|
/// </summary>
|
|
protected static Dictionary<string, logData> logDictionary = new Dictionary<string, logData>();
|
|
|
|
/// <summary>
|
|
/// Verifica necessità di registrare log (moderato ogni 30 sec...)
|
|
/// </summary>
|
|
/// <param name="message"></param>
|
|
/// <returns></returns>
|
|
private static int reportLog(string message)
|
|
{
|
|
int numLog = 0;
|
|
// verifico esistenza messaggio
|
|
if (logDictionary.ContainsKey(message))
|
|
{
|
|
// verifico primo evento --> limitazione ogni 30 sec...
|
|
if (logDictionary[message].dtFirst.AddSeconds(30) < DateTime.Now)
|
|
{
|
|
numLog = logDictionary[message].counter;
|
|
logDictionary[message] = new logData { message = message, counter = 1, dtFirst = DateTime.Now };
|
|
}
|
|
else
|
|
{
|
|
logDictionary[message].counter++;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
logDictionary.Add(message, new logData { message = message, counter = 1, dtFirst = DateTime.Now });
|
|
numLog = 1;
|
|
}
|
|
return numLog;
|
|
}
|
|
/// <summary>
|
|
/// Wrapper log INFO
|
|
/// </summary>
|
|
/// <param name="message"></param>
|
|
public static void lgInfo(string message)
|
|
{
|
|
int numLog = reportLog(message);
|
|
if (numLog > 0)
|
|
Log.Instance.Info($"{numLog} X {message}");
|
|
}
|
|
/// <summary>
|
|
/// Wrapper log WARN
|
|
/// </summary>
|
|
/// <param name="message"></param>
|
|
public static void lgWarn(string message)
|
|
{
|
|
int numLog = reportLog(message);
|
|
if (numLog > 0)
|
|
Log.Instance.Warn($"{numLog} X {message}");
|
|
}
|
|
/// <summary>
|
|
/// Wrapper log ERROR
|
|
/// </summary>
|
|
/// <param name="message"></param>
|
|
public static void lgError(string message)
|
|
{
|
|
int numLog = reportLog(message);
|
|
if (numLog > 0)
|
|
Log.Instance.Error($"{numLog} X {message}");
|
|
}
|
|
/// <summary>
|
|
/// Wrapper log ERROR + exception
|
|
/// </summary>
|
|
/// <param name="message"></param>
|
|
public static void lgError(string message, Exception exc)
|
|
{
|
|
int numLog = reportLog(message);
|
|
if (numLog > 0)
|
|
Log.Instance.Warn($"{numLog} X {message}{Environment.NewLine}{exc}");
|
|
}
|
|
/// <summary>
|
|
/// Wrapper log FATAL
|
|
/// </summary>
|
|
/// <param name="message"></param>
|
|
public static void lgFatal(string message)
|
|
{
|
|
int numLog = reportLog(message);
|
|
if (numLog > 0)
|
|
Log.Instance.Fatal($"{numLog} X {message}");
|
|
}
|
|
|
|
#endregion
|
|
|
|
/// <summary>
|
|
/// Client connessioni HTTP della classe
|
|
/// </summary>
|
|
private static readonly HttpClient cHttpClient = new HttpClient() { Timeout = TimeSpan.FromMinutes(10) };
|
|
/// <summary>
|
|
/// Test ping x indirizzo indicato
|
|
/// </summary>
|
|
/// <param name="address">Hostname or Address</param>
|
|
/// <returns></returns>
|
|
public static bool pingAddress(string target)
|
|
{
|
|
bool answ = false;
|
|
Ping pingSender = new Ping();
|
|
try
|
|
{
|
|
PingReply reply = pingSender.Send(target, 100);
|
|
// se passa il ping do OK...
|
|
if (reply.Status == IPStatus.Success)
|
|
{
|
|
answ = true;
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"EXC in pingAddress: {Environment.NewLine}{exc}");
|
|
}
|
|
return answ;
|
|
}
|
|
/// <summary>
|
|
/// IP della macchina
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public static string GetIP()
|
|
{
|
|
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
|
|
String sIpAddr = string.Empty;
|
|
try
|
|
{
|
|
foreach (NetworkInterface adapter in nics)
|
|
{
|
|
if (sIpAddr == String.Empty)// only return IP Address from first card
|
|
{
|
|
IPInterfaceProperties properties = adapter.GetIPProperties();
|
|
foreach (var item in properties.UnicastAddresses)
|
|
{
|
|
if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
|
|
{
|
|
sIpAddr = item.Address.ToString();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"EXC in GetIP: {Environment.NewLine}{exc}");
|
|
}
|
|
return sIpAddr;
|
|
}
|
|
/// <summary>
|
|
/// Macaddress della macchina
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public static string GetMACAddress()
|
|
{
|
|
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
|
|
String sMacAddress = string.Empty;
|
|
try
|
|
{
|
|
foreach (NetworkInterface adapter in nics)
|
|
{
|
|
if (sMacAddress == String.Empty)// only return MAC Address from first card
|
|
{
|
|
IPInterfaceProperties properties = adapter.GetIPProperties();
|
|
//sMacAddress = adapter.GetPhysicalAddress().ToString();
|
|
sMacAddress = string.Join(":", (from z in adapter.GetPhysicalAddress().GetAddressBytes() select z.ToString("X2")).ToArray());
|
|
}
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"EXC in GetMACAddress: {Environment.NewLine}{exc}");
|
|
}
|
|
return sMacAddress;
|
|
}
|
|
/// <summary>
|
|
/// Effettua download async della pagina indicata
|
|
/// </summary>
|
|
/// <param name="pageURL"></param>
|
|
/// <param name="doLog"></param>
|
|
public static async Task<string> getPageAsync(string pageURL)
|
|
{
|
|
string currUrl = pageURL;
|
|
if (currUrl.IndexOf("token") >= 0)
|
|
{
|
|
currUrl = currUrl.Substring(0, currUrl.IndexOf("token"));
|
|
}
|
|
// se contiene token --> TRIMMO...
|
|
lgInfo($"[getPageAsync]: Calling URL: {currUrl}");
|
|
string answ = "";
|
|
try
|
|
{
|
|
using (HttpResponseMessage response = await cHttpClient.GetAsync(pageURL))
|
|
using (HttpContent content = response.Content)
|
|
{
|
|
// ... lettura contenuto...
|
|
answ = await content.ReadAsStringAsync();
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"EXC in getPageAsync: {Environment.NewLine}{exc}");
|
|
}
|
|
return answ;
|
|
}
|
|
/// <summary>
|
|
/// Effettua download async della pagina indicata
|
|
/// </summary>
|
|
/// <param name="pageURL"></param>
|
|
public static async Task<string> getPageAsync(string pageURL, string oauthToken)
|
|
{
|
|
lgInfo($"[getPageAsync]: Calling URL: {pageURL} | OAuth Token: OMISSIS");
|
|
//lgInfo($"[getPageAsync]: Calling URL: {pageURL} | OAuth Token: {oauthToken}");
|
|
string answ = "";
|
|
try
|
|
{
|
|
// ... Use HttpClient.
|
|
using (HttpClient client = new HttpClient() { Timeout = TimeSpan.FromMinutes(2) })
|
|
{
|
|
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + oauthToken);
|
|
using (HttpResponseMessage response = await client.GetAsync(pageURL))
|
|
using (HttpContent content = response.Content)
|
|
{
|
|
// ... lettura contenuto...
|
|
answ = await content.ReadAsStringAsync();
|
|
}
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"EXC in getPageAsync: {Environment.NewLine}{exc}");
|
|
}
|
|
return answ;
|
|
}
|
|
/// <summary>
|
|
/// Effettua PUT async della REST API indicata
|
|
/// </summary>
|
|
/// <param name="reqUri">URI della chiamata</param>
|
|
/// <param name="callCont">contenuto della chiamata</param>
|
|
/// <param name="oauthToken">token da passare come bearer</param>
|
|
public static async Task<string> putAsync(Uri reqUri, HttpContent callCont, string oauthToken)
|
|
{
|
|
lgInfo($"[putAsync]: Calling reqUri: {reqUri} | callCont Token: {oauthToken} | callCont: {callCont}");
|
|
string answ = "";
|
|
try
|
|
{
|
|
// ... Use HttpClient.
|
|
using (HttpClient client = new HttpClient() { Timeout = TimeSpan.FromMinutes(2) })
|
|
{
|
|
if (oauthToken != "")
|
|
{
|
|
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + oauthToken);
|
|
}
|
|
using (HttpResponseMessage response = await client.PutAsync(reqUri, callCont))
|
|
{
|
|
if (response.StatusCode == System.Net.HttpStatusCode.NoContent)
|
|
{
|
|
// tutto ok
|
|
answ = "204";
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError("EXC in putAsync", exc);
|
|
}
|
|
return answ;
|
|
}
|
|
/// <summary>
|
|
/// Chiamata POST asyncrona
|
|
/// </summary>
|
|
/// <param name="reqUri">URI della chiamata</param>
|
|
/// <param name="callCont">contenuto della chiamata</param>
|
|
/// <returns></returns>
|
|
public static async Task<string> postAsync(Uri reqUri, HttpContent callCont)
|
|
{
|
|
lgInfo($"[postUriAsync]: Calling reqUri: {reqUri} | callCont: {callCont}");
|
|
var response = string.Empty;
|
|
try
|
|
{
|
|
HttpResponseMessage result = await cHttpClient.PostAsync(reqUri, callCont);
|
|
response = await result.Content.ReadAsStringAsync();
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError("EXC in postUriAsync", exc);
|
|
}
|
|
return response;
|
|
}
|
|
/// <summary>
|
|
/// Effettua download async dell'immagine
|
|
/// </summary>
|
|
/// <param name="pageURL">path di base</param>
|
|
/// <param name="imagePath">path immagine (cui applicare encode) e a cui appendere alt=media...</param>
|
|
public static async Task<Image> getImageAsync(string pageURL, string imagePath)
|
|
{
|
|
lgInfo($"[getImageAsync]: Calling URL: {pageURL} | imagePath: {imagePath}");
|
|
Image answ = null;
|
|
try
|
|
{
|
|
string imgEncoded = Uri.EscapeDataString(imagePath);
|
|
string fullImgPath = pageURL + imgEncoded + "?alt=media";
|
|
using (Stream response = await cHttpClient.GetStreamAsync(fullImgPath))
|
|
{
|
|
//if()
|
|
// ... lettura contenuto...
|
|
var memoryStream = new MemoryStream();
|
|
await response.CopyToAsync(memoryStream);
|
|
answ = Image.FromStream(memoryStream);
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"EXC in getImageAsync: {Environment.NewLine}{exc}");
|
|
}
|
|
return answ;
|
|
}
|
|
/// <summary>
|
|
/// Caricamento file come multipart in modalità async
|
|
/// </summary>
|
|
/// <param name="pageUrl"></param>
|
|
/// <param name="fileName"></param>
|
|
/// <param name="filePath"></param>
|
|
/// <returns></returns>
|
|
public static async Task<string> uploadAsync(string pageUrl, string fileName, string filePath)
|
|
{
|
|
lgInfo($"[uploadAsync]: Calling pageUrl: {pageUrl} | fileName: {fileName}");
|
|
string answ = "";
|
|
using (FileStream fStream = File.OpenRead(filePath))
|
|
{
|
|
try
|
|
{
|
|
using (var content =
|
|
new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
|
|
{
|
|
content.Add(new StreamContent(fStream), "file", fileName);
|
|
using (
|
|
var message =
|
|
await cHttpClient.PostAsync(pageUrl, content))
|
|
{
|
|
var input = await message.Content.ReadAsStringAsync();
|
|
answ = input;
|
|
}
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"EXC in uploadAsync: {Environment.NewLine}{exc}");
|
|
throw;
|
|
}
|
|
}
|
|
//fStream.Close();
|
|
return answ;
|
|
}
|
|
/// <summary>
|
|
/// Caricamento file come multipart in modalità async
|
|
/// </summary>
|
|
/// <param name="pageUrl"></param>
|
|
/// <param name="fileName"></param>
|
|
/// <param name="mStream"></param>
|
|
/// <returns></returns>
|
|
public static async Task<string> uploadAsync(string pageUrl, string fileName, MemoryStream mStream)
|
|
{
|
|
lgInfo($"[uploadAsync]: Calling pageUrl: {pageUrl} | fileName: {fileName}");
|
|
string answ = "";
|
|
try
|
|
{
|
|
|
|
using (var content =
|
|
new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
|
|
{
|
|
content.Add(new StreamContent(mStream), "file", fileName);
|
|
using (
|
|
var message =
|
|
await cHttpClient.PostAsync(pageUrl, content))
|
|
{
|
|
var input = await message.Content.ReadAsStringAsync();
|
|
answ = input;
|
|
}
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"EXC in uploadAsync: {Environment.NewLine}{exc}");
|
|
throw;
|
|
}
|
|
return answ;
|
|
}
|
|
/// <summary>
|
|
/// Caricamento file come multipart in modalità async
|
|
/// </summary>
|
|
/// <param name="pageUrl"></param>
|
|
/// <param name="fileName"></param>
|
|
/// <param name="fileContent"></param>
|
|
/// <returns></returns>
|
|
public static async Task<string> uploadAsync(string pageUrl, string fileName, byte[] fileContent)
|
|
{
|
|
lgInfo($"[uploadAsync]: Calling pageUrl: {pageUrl} | fileName: {fileName}");
|
|
string answ = "";
|
|
try
|
|
{
|
|
using (var client = new HttpClient())
|
|
{
|
|
// imposto a 15 minutiupload timeout!
|
|
TimeSpan ts = new TimeSpan(0, 15, 0);
|
|
client.Timeout = ts;
|
|
client.MaxResponseContentBufferSize = fileContent.Length + 1024;
|
|
using (var content =
|
|
new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
|
|
{
|
|
content.Add(new StreamContent(new MemoryStream(fileContent)), "file", fileName);
|
|
using (
|
|
var message =
|
|
await client.PostAsync(pageUrl, content))
|
|
{
|
|
var input = await message.Content.ReadAsStringAsync();
|
|
answ = input;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"EXC in uploadAsync: {Environment.NewLine}{exc}");
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Helper formattazione durata human readable
|
|
/// </summary>
|
|
/// <param name="timeSpan"></param>
|
|
/// <param name="textMode">textMode = come linguaggio scritto</param>
|
|
/// <returns></returns>
|
|
public static string FormatTimeSpan(TimeSpan timeSpan, bool textMode = false)
|
|
{
|
|
if (textMode)
|
|
{
|
|
//Func<Tuple<int, string>, string> tupleFormatter = t => $"{t.Item1} {t.Item2}{(t.Item1 == 1 ? string.Empty : "s")}";
|
|
//Func<Tuple<int, string>, string> tupleFormatter = t => $"{t.Item1}{t.Item2}";
|
|
Func<Tuple<int, string>, string> tupleFormatter = t => $"{t.Item1} {(t.Item1 == 1 ? t.Item2 : t.Item2.Replace("giorno", "giorni").Replace("ora", "ore"))}";
|
|
var components = new List<Tuple<int, string>>
|
|
{
|
|
Tuple.Create((int) timeSpan.TotalDays, "giorno"),
|
|
Tuple.Create(timeSpan.Hours, "ora"),
|
|
Tuple.Create(timeSpan.Minutes, "min"),
|
|
Tuple.Create(timeSpan.Seconds, "sec"),
|
|
};
|
|
|
|
components.RemoveAll(i => i.Item1 == 0);
|
|
|
|
string extra = "";
|
|
|
|
if (components.Count > 1)
|
|
{
|
|
var finalComponent = components[components.Count - 1];
|
|
components.RemoveAt(components.Count - 1);
|
|
extra = $" e {tupleFormatter(finalComponent)}";
|
|
}
|
|
|
|
return $"{string.Join(", ", components.Select(tupleFormatter))}{extra}";
|
|
}
|
|
else
|
|
{
|
|
//Func<Tuple<int, string>, string> tupleFormatter = t => $"{t.Item1} {t.Item2}{(t.Item1 == 1 ? string.Empty : "s")}";
|
|
//Func<Tuple<int, string>, string> tupleFormatter = t => $"{t.Item1}{t.Item2}";
|
|
Func<Tuple<int, string>, string> tupleFormatter = t => $"{t.Item1:00}";
|
|
var components = new List<Tuple<int, string>>
|
|
{
|
|
Tuple.Create((int) timeSpan.TotalDays, "g"),
|
|
Tuple.Create(timeSpan.Hours, ""),
|
|
Tuple.Create(timeSpan.Minutes, ""),
|
|
Tuple.Create(timeSpan.Seconds, ""),
|
|
};
|
|
|
|
//components.RemoveAll(i => i.Item1 == 0);
|
|
|
|
return $"{string.Join(":", components.Select(tupleFormatter))}";
|
|
}
|
|
}
|
|
}
|
|
}
|