diff --git a/Jenkinsfile b/Jenkinsfile index 4c0e973..bbd3d02 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -7,9 +7,9 @@ pipeline { steps { /* calcolo numero versione... diverso x branch MASTER/DEVELOP */ script { - withEnv(['NEXT_BUILD_NUMBER=80']) { - // env.versionNumber = VersionNumber(versionNumberString : '0.9.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2019-01-01', skipFailedBuilds: true) - env.versionNumber = VersionNumber(versionNumberString : '0.9.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2019-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}') + withEnv(['NEXT_BUILD_NUMBER=81']) { + // env.versionNumber = VersionNumber(versionNumberString : '1.1.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2019-01-01', skipFailedBuilds: true) + env.versionNumber = VersionNumber(versionNumberString : '1.1.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2019-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}') env.APP_NAME = 'LPA' } } diff --git a/LPA/utils.cs b/LPA/utils.cs index 3bbd090..7daf1ad 100644 --- a/LPA/utils.cs +++ b/LPA/utils.cs @@ -11,236 +11,262 @@ using System.Threading.Tasks; namespace LPA { - public class utils - { - /// - /// Client connessioni HTTP della classe - /// - private static readonly HttpClient cHttpClient = new HttpClient() { Timeout = TimeSpan.FromMinutes(10) }; - /// - /// Test ping x indirizzo indicato - /// - /// Hostname or Address - /// - public static bool pingAddress(string target) + public class utils { - 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) + + #region gestione log + + public static void lgInfo(string message) { - answ = true; + Log.Instance.Info(message); } - } - catch (Exception exc) - { - Log.Instance.Error($"EXC in pingAddress: {Environment.NewLine}{exc}"); - } - return answ; - } - /// - /// IP della macchina - /// - /// - public static string GetIP() - { - NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); - String sIpAddr = string.Empty; - try - { - foreach (NetworkInterface adapter in nics) + public static void lgWarn(string message) { - if (sIpAddr == String.Empty)// only return IP Address from first card - { - IPInterfaceProperties properties = adapter.GetIPProperties(); - foreach (var item in properties.UnicastAddresses) + Log.Instance.Warn(message); + } + public static void lgError(string message) + { + Log.Instance.Error(message); + } + public static void lgError(string message, Exception exc) + { + Log.Instance.Error($"{message}{Environment.NewLine}{exc}"); + } + public static void lgFatal(string message) + { + Log.Instance.Fatal(message); + } + + #endregion + + /// + /// Client connessioni HTTP della classe + /// + private static readonly HttpClient cHttpClient = new HttpClient() { Timeout = TimeSpan.FromMinutes(10) }; + /// + /// Test ping x indirizzo indicato + /// + /// Hostname or Address + /// + public static bool pingAddress(string target) + { + bool answ = false; + Ping pingSender = new Ping(); + try { - if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) - { - sIpAddr = item.Address.ToString(); - } + PingReply reply = pingSender.Send(target, 100); + // se passa il ping do OK... + if (reply.Status == IPStatus.Success) + { + answ = true; + } } - } - } - } - catch (Exception exc) - { - Log.Instance.Error($"EXC in GetIP: {Environment.NewLine}{exc}"); - } - return sIpAddr; - } - /// - /// Macaddress della macchina - /// - /// - 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) - { - Log.Instance.Error($"EXC in GetMACAddress: {Environment.NewLine}{exc}"); - } - return sMacAddress; - } - /// - /// Effettua download async della pagina indicata - /// - /// - /// - public static async Task getPageAsync(string pageURL) - { - string currUrl = pageURL; - if (currUrl.IndexOf("token") >= 0) - { - currUrl = currUrl.Substring(0, currUrl.IndexOf("token")); - } - // se contiene token --> TRIMMO... - Log.Instance.Info($"[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) - { - Log.Instance.Error($"EXC in getPageAsync: {Environment.NewLine}{exc}"); - } - return answ; - } - /// - /// Effettua download async della pagina indicata - /// - /// - public static async Task getPageAsync(string pageURL, string oauthToken) - { - Log.Instance.Info($"[getPageAsync]: Calling URL: {pageURL} | OAuth Token: OMISSIS"); - //Log.Instance.Info($"[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) - { - Log.Instance.Error($"EXC in getPageAsync: {Environment.NewLine}{exc}"); - } - return answ; - } - /// - /// Effettua PUT async della REST API indicata - /// - /// URI della chiamata - /// contenuto della chiamata - /// token da passare come bearer - public static async Task putAsync(Uri reqUri, HttpContent callCont, string oauthToken) - { - Log.Instance.Info($"[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) + catch (Exception exc) { - // tutto ok - answ = "204"; + lgError($"EXC in pingAddress: {Environment.NewLine}{exc}"); } - } + return answ; } - } - catch (Exception exc) - { - Log.Instance.Error(exc,"EXC in putAsync"); - } - return answ; - } - /// - /// Chiamata POST asyncrona - /// - /// URI della chiamata - /// contenuto della chiamata - /// - public static async Task postAsync(Uri reqUri, HttpContent callCont) - { - Log.Instance.Info($"[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) - { - Log.Instance.Error(exc, "EXC in postUriAsync"); - } - return response; - } - /// - /// Effettua download async dell'immagine - /// - /// path di base - /// path immagine (cui applicare encode) e a cui appendere alt=media... - public static async Task getImageAsync(string pageURL, string imagePath) - { - Log.Instance.Info($"[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)) + /// + /// IP della macchina + /// + /// + public static string GetIP() { - //if() - // ... lettura contenuto... - var memoryStream = new MemoryStream(); - await response.CopyToAsync(memoryStream); - answ = Image.FromStream(memoryStream); + 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; + } + /// + /// Macaddress della macchina + /// + /// + 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; + } + /// + /// Effettua download async della pagina indicata + /// + /// + /// + public static async Task 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; + } + /// + /// Effettua download async della pagina indicata + /// + /// + public static async Task 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; + } + /// + /// Effettua PUT async della REST API indicata + /// + /// URI della chiamata + /// contenuto della chiamata + /// token da passare come bearer + public static async Task 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; + } + /// + /// Chiamata POST asyncrona + /// + /// URI della chiamata + /// contenuto della chiamata + /// + public static async Task 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; + } + /// + /// Effettua download async dell'immagine + /// + /// path di base + /// path immagine (cui applicare encode) e a cui appendere alt=media... + public static async Task 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; } - } - catch (Exception exc) - { - Log.Instance.Error($"EXC in getImageAsync: {Environment.NewLine}{exc}"); - } - return answ; - } #if false /// @@ -254,7 +280,7 @@ namespace LPA { // test: user=scm, pwd=viaemilia_2019 string remoteFtpPath = @"ftp://fow.steamware.net/httpdocs/SCM/"; - Log.Instance.Info($"[ftpUploadAsync]: Calling FTP: {remoteFtpPath} | Remote Path {machineId} | local file name: {localFileName}"); + lgInfo($"[ftpUploadAsync]: Calling FTP: {remoteFtpPath} | Remote Path {machineId} | local file name: {localFileName}"); GatewayPayload rispo = new GatewayPayload() { @@ -291,138 +317,138 @@ namespace LPA } catch (Exception exc) { - Log.Instance.Error($"EXC in uploadAsync: {Environment.NewLine}{exc}"); + lgError($"EXC in uploadAsync: {Environment.NewLine}{exc}"); throw; } answ = JsonConvert.SerializeObject(rispo); return answ; } #endif - /// - /// Caricamento file come multipart in modalità async - /// - /// - /// - /// - /// - public static async Task uploadAsync(string pageUrl, string fileName, string filePath) - { - Log.Instance.Info($"[uploadAsync]: Calling pageUrl: {pageUrl} | fileName: {fileName}"); - string answ = ""; - using (FileStream fStream = File.OpenRead(filePath)) - { - try + /// + /// Caricamento file come multipart in modalità async + /// + /// + /// + /// + /// + public static async Task uploadAsync(string pageUrl, string fileName, string filePath) { - 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)) + lgInfo($"[uploadAsync]: Calling pageUrl: {pageUrl} | fileName: {fileName}"); + string answ = ""; + using (FileStream fStream = File.OpenRead(filePath)) { - var input = await message.Content.ReadAsStringAsync(); - answ = input; + 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; } - catch (Exception exc) + /// + /// Caricamento file come multipart in modalità async + /// + /// + /// + /// + /// + public static async Task uploadAsync(string pageUrl, string fileName, MemoryStream mStream) { - Log.Instance.Error($"EXC in uploadAsync: {Environment.NewLine}{exc}"); - throw; - } - } - //fStream.Close(); - return answ; - } - /// - /// Caricamento file come multipart in modalità async - /// - /// - /// - /// - /// - public static async Task uploadAsync(string pageUrl, string fileName, MemoryStream mStream) - { - Log.Instance.Info($"[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) - { - Log.Instance.Error($"EXC in uploadAsync: {Environment.NewLine}{exc}"); - throw; - } - return answ; - } - /// - /// Caricamento file come multipart in modalità async - /// - /// - /// - /// - /// - public static async Task uploadAsync(string pageUrl, string fileName, byte[] fileContent) - { - Log.Instance.Info($"[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)) + lgInfo($"[uploadAsync]: Calling pageUrl: {pageUrl} | fileName: {fileName}"); + string answ = ""; + try { - var input = await message.Content.ReadAsStringAsync(); - answ = input; - } - } - } - } - catch (Exception exc) - { - Log.Instance.Error($"EXC in uploadAsync: {Environment.NewLine}{exc}"); - } - return answ; - } - /// - /// Helper formattazione durata human readable - /// - /// - /// textMode = come linguaggio scritto - /// - public static string FormatTimeSpan(TimeSpan timeSpan, bool textMode = false) - { - if (textMode) - { - //Func, string> tupleFormatter = t => $"{t.Item1} {t.Item2}{(t.Item1 == 1 ? string.Empty : "s")}"; - //Func, string> tupleFormatter = t => $"{t.Item1}{t.Item2}"; - Func, string> tupleFormatter = t => $"{t.Item1} {(t.Item1 == 1 ? t.Item2 : t.Item2.Replace("giorno", "giorni").Replace("ora", "ore"))}"; - var components = new List> + 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; + } + /// + /// Caricamento file come multipart in modalità async + /// + /// + /// + /// + /// + public static async Task 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; + } + + /// + /// Helper formattazione durata human readable + /// + /// + /// textMode = come linguaggio scritto + /// + public static string FormatTimeSpan(TimeSpan timeSpan, bool textMode = false) + { + if (textMode) + { + //Func, string> tupleFormatter = t => $"{t.Item1} {t.Item2}{(t.Item1 == 1 ? string.Empty : "s")}"; + //Func, string> tupleFormatter = t => $"{t.Item1}{t.Item2}"; + Func, string> tupleFormatter = t => $"{t.Item1} {(t.Item1 == 1 ? t.Item2 : t.Item2.Replace("giorno", "giorni").Replace("ora", "ore"))}"; + var components = new List> { Tuple.Create((int) timeSpan.TotalDays, "giorno"), Tuple.Create(timeSpan.Hours, "ora"), @@ -430,25 +456,25 @@ namespace LPA Tuple.Create(timeSpan.Seconds, "sec"), }; - components.RemoveAll(i => i.Item1 == 0); + components.RemoveAll(i => i.Item1 == 0); - string extra = ""; + string extra = ""; - if (components.Count > 1) - { - var finalComponent = components[components.Count - 1]; - components.RemoveAt(components.Count - 1); - extra = $" e {tupleFormatter(finalComponent)}"; - } + 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, string> tupleFormatter = t => $"{t.Item1} {t.Item2}{(t.Item1 == 1 ? string.Empty : "s")}"; - //Func, string> tupleFormatter = t => $"{t.Item1}{t.Item2}"; - Func, string> tupleFormatter = t => $"{t.Item1:00}"; - var components = new List> + return $"{string.Join(", ", components.Select(tupleFormatter))}{extra}"; + } + else + { + //Func, string> tupleFormatter = t => $"{t.Item1} {t.Item2}{(t.Item1 == 1 ? string.Empty : "s")}"; + //Func, string> tupleFormatter = t => $"{t.Item1}{t.Item2}"; + Func, string> tupleFormatter = t => $"{t.Item1:00}"; + var components = new List> { Tuple.Create((int) timeSpan.TotalDays, "g"), Tuple.Create(timeSpan.Hours, ""), @@ -456,10 +482,10 @@ namespace LPA Tuple.Create(timeSpan.Seconds, ""), }; - //components.RemoveAll(i => i.Item1 == 0); + //components.RemoveAll(i => i.Item1 == 0); - return $"{string.Join(":", components.Select(tupleFormatter))}"; - } + return $"{string.Join(":", components.Select(tupleFormatter))}"; + } + } } - } }