using MP.Models;
using SteamWare;
using System;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using ZXing;
using ZXing.QrCode;
namespace MP.Controllers
{
public class HomeController : Controller
{
#region Protected Fields
///
/// Controller versioni e download autenticato
///
protected UpdateMan updManAuth = new UpdateMan("SWDownloader", "viaD@nte16");
#endregion Protected Fields
#region Private Methods
private int downloadAll(int done)
{
done += UpdateMan.obj.downloadLatest(updateUrl("ADM"), localDownloadPath("ADM"), "ADM");
done += UpdateMan.obj.downloadLatest(updateUrl("IO"), localDownloadPath("IO"), "IO");
done += UpdateMan.obj.downloadLatest(updateUrl("LAND"), localDownloadPath("LAND"), "LAND");
done += UpdateMan.obj.downloadLatest(updateUrl("MON"), localDownloadPath("MON"), "MON");
done += UpdateMan.obj.downloadLatest(updateUrl("SITE"), localDownloadPath("SITE"), "SITE");
done += UpdateMan.obj.downloadLatest(updateUrl("TAB"), localDownloadPath("TAB"), "TAB");
done += UpdateMan.obj.downloadLatest(updateUrl("CTRACK"), localDownloadPath("CTRACK"), "CTRACK");
done += UpdateMan.obj.downloadLatest(updateUrl("MAG"), localDownloadPath("MAG"), "MAG");
done += updManAuth.downloadLatest(updateUrlAuth("MP-STATS"), localDownloadPath("STATS"), "STATS");
return done;
}
#endregion Private Methods
#region Protected Methods
///
/// recupera da DB chiave AVK
///
///
///
protected string getAKV(string key)
{
string answ = "";
using (MoonProEntities ctx = new MoonProEntities())
{
try
{
var rawData = ctx.stp_AKV_getByKey(key).ToList();
if (rawData.Count > 0)
{
answ = rawData[0].valString;
}
}
catch (Exception exc)
{
SteamWare.Logger.Logging.Instance.Error($"Exception on getAKV:{Environment.NewLine}{exc}");
}
}
return answ;
}
///
/// Path locale dove scaricare gli installer
///
protected string localDownloadPath(string package)
{
return string.Format(@"{0}{1}\{2}", memLayer.ML.CRS("downloadPath"), package, memLayer.ML.CRS("appVers")).Replace("MP-", "");
}
///
/// URL stringa di UPDATE...
///
protected string updateUrl(string package)
{
return string.Format("https://nexus.steamware.net/repository/SWS/{0}/{1}/manifest.xml", package, memLayer.ML.CRS("appVers"));
}
///
/// URL stringa di UPDATE su area che richiede Auth (nexus.steamware.net)...
///
protected string updateUrlAuth(string package)
{
return string.Format("http://nexus.steamware.net/repository/SWS/{0}/{1}/0/manifest.xml", package, memLayer.ML.CRS("appVers"));
}
///
/// Costruzione URL da base path + URL specifico finale
///
///
///
protected string urlTgt(string key)
{
string answ = "";
var currUrl = Request.Url;
try
{
string currTgt = getAKV(key);
answ = $"{currUrl.Scheme}://{currUrl.Authority}/{currTgt}";
}
catch (Exception exc)
{
SteamWare.Logger.Logging.Instance.Error($"Exception on urlTgt:{Environment.NewLine}{exc}");
}
return answ;
}
#endregion Protected Methods
#region Public Methods
///
/// info steamware
///
///
public ActionResult About()
{
ViewBag.Title = "MES | SCADA | IOT";
ViewBag.Message = "Soluzione integrata per la gestione della produzione";
return View();
}
///
/// Gestione configurazioni applicativi (DB)
///
///
///
public ActionResult ConfigMan(string sorgente)
{
ViewBag.Title = "Steamware's MAPO Suite - Configurations";
// cerco file se disponibile...
string filePath = Path.Combine(Server.MapPath("~/FileUpload"), "web.config");
bool fileExist = (fileMover.obj.fileExist(Server.MapPath("~/FileUpload"), "web.config"));
if (fileExist)
{
ViewBag.Message = "File web.config presente";
// leggo il file di conf caricato...
System.Configuration.Configuration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("~/FileUpload/web.config");
if (sorgente != "" && sorgente != null)
{
// resetto tab import
memLayer.ML.taConfigTmp.reset(sorgente);
// carico dati!
var settings = rootWebConfig.AppSettings.Settings;
foreach (var item in settings.AllKeys)
{
memLayer.ML.taConfigTmp.insertQuery(sorgente, item, settings[item].Value, string.Format("{0}|{1}", sorgente, item));
}
// salvo in viewbag gli elenchi 0/1/2 (tutte, nuove, modificate)
using (var ctx = new MoonProEntities())
{
try
{
// esegue stored procedure come function, recuperando chiave desiderata...
var elConfig = ctx.ConfigTmp.ToList();
ViewBag.elConfig = elConfig;
}
catch
{ }
}
ViewBag.keyList = "CARICATO!";
}
}
else
{
ViewBag.Message = "Attenzione: nessun file presente!";
}
// VIEW!
return View((object)ViewBag.elConfig);
}
///
/// contatti
///
///
public ActionResult Contact()
{
ViewBag.Title = "MAPO";
ViewBag.Message = "Per contattarci";
return View();
}
// GET: Home/Download/Caller (ALL|ADM|IO|LAND|MON|SITE|TAB|CTRACK)
public ActionResult Download(string caller)
{
string resultsMsg = "";
// in base al caller scarico il file installazione richiesto...
if (caller == null)
{
caller = "ALL";
}
// ora verifico COSA devo scaricare...
if (updateUrl(caller) != "")
{
// se è ALL scarico tuttoi...
if (caller == "ALL")
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
int done = 0;
// scarico TUTTI...
done = downloadAll(done);
stopWatch.Stop();
// calcolo elapsed time come TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
resultsMsg = string.Format("OK: {0} Package downloaded, {1:0.000} sec", done, ts.TotalSeconds);
}
else
{
// scarico singolo target...
UpdateMan.obj.downloadLatest(updateUrl(caller), localDownloadPath(caller), caller);
resultsMsg = string.Format("OK: {0} DOWNLOADED | {1} --> {2}", caller, updateUrl(caller), localDownloadPath(caller));
}
}
// ...chiamo action
return RedirectToAction("Packages", "Home", new { results = resultsMsg });
}
// GET: Home/DownloadAuth/Caller (ALL|STATS)
public ActionResult DownloadAuth(string caller)
{
string resultsMsg = "";
// in base al caller scarico il file installazione richiesto...
if (caller == null)
{
caller = "ALL";
}
// ora verifico COSA devo scaricare...
if (updateUrl(caller) != "")
{
// se è ALL scarico tuttoi...
if (caller == "ALL")
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
int done = 0;
// scarico TUTTI...
done = downloadAll(done);
stopWatch.Stop();
// calcolo elapsed time come TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
resultsMsg = string.Format("OK: {0} Package downloaded, {1:0.000} sec", done, ts.TotalSeconds);
}
else
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// scarico singolo target...
string remoteUrl = updateUrlAuth(caller);
string localPath = localDownloadPath(caller);
string localName = caller.Replace("MP-", "");
updManAuth.downloadLatest(remoteUrl, localPath, localName);
stopWatch.Stop();
// calcolo elapsed time come TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
resultsMsg = string.Format("OK: {0} DOWNLOADED | {1} --> {2}, {3:0.000} sec", caller, remoteUrl, localPath, ts.TotalSeconds);
}
}
// ...chiamo action
return RedirectToAction("Packages", "Home", new { results = resultsMsg });
}
public ActionResult Index()
{
ViewBag.Title = "MAPO";
// x sicurezza leggo da web.config
ViewBag.Environment = WebConfigurationManager.AppSettings["Environment"];
try
{
// esegue stored procedure come function, recuperando chiave desiderata...
ViewBag.Environment = getAKV("Environment");
// imposto URL dei vari siti
ViewBag.UrlMpSite = urlTgt("UrlMpSite");
ViewBag.UrlMpAdmin = urlTgt("UrlMpAdmin");
ViewBag.UrlMpIO = urlTgt("UrlMpIO");
ViewBag.UrlMpMON = urlTgt("UrlMpMON");
ViewBag.UrlMpTAB = urlTgt("UrlMpTAB");
ViewBag.UrlMpCTrack = urlTgt("UrlMpCTrack");
ViewBag.UrlMpMag = urlTgt("UrlMpMag");
ViewBag.UrlMpStats = urlTgt("UrlMpStats");
// importo verifica abilitazione CTrack - !!!FARE!!! vero check key auth!
ViewBag.MAG_Enb = string.IsNullOrEmpty(getAKV("MAG")) ? false : true;
ViewBag.CTrack_Enb = string.IsNullOrEmpty(getAKV("CTRACK")) ? false : true;
ViewBag.Stats_Enb = string.IsNullOrEmpty(getAKV("STATS")) ? false : true;
}
catch (Exception exc)
{
logger.lg.scriviLog(string.Format("Eccezione in composizione HOME page LAND:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION);
}
return View();
}
///
/// Gestione download aggiornamenti
///
///
///
public ActionResult Packages(string results)
{
ViewBag.Title = "Steamware's MAPO Suite";
ViewBag.Message = "Ultime release applicazioni";
UpdateInfoEventArgs updArgs = new UpdateInfoEventArgs();
// Recupero info ADM...
updArgs = UpdateMan.obj.getUpdateInfo(updateUrl("ADM"));
if (updArgs.IsUpdateAvailable)
{
ViewBag.VersMpAdmin = updArgs.CurrentVersion;
}
else
{
ViewBag.VersMpAdmin = "ND";
ViewBag.AdmDisabled = "disabled";
}
// Recupero info IO...
updArgs = UpdateMan.obj.getUpdateInfo(updateUrl("IO"));
if (updArgs.IsUpdateAvailable)
{
ViewBag.VersMpIO = updArgs.CurrentVersion;
}
else
{
ViewBag.VersMpIO = "ND";
ViewBag.IODisabled = "disabled";
}
// Recupero info LAND...
updArgs = UpdateMan.obj.getUpdateInfo(updateUrl("LAND"));
if (updArgs.IsUpdateAvailable)
{
ViewBag.VersMpLand = updArgs.CurrentVersion;
}
else
{
ViewBag.VersMpLand = "ND";
ViewBag.LandDisabled = "disabled";
}
// Recupero info MON...
updArgs = UpdateMan.obj.getUpdateInfo(updateUrl("MON"));
if (updArgs.IsUpdateAvailable)
{
ViewBag.VersMpMon = updArgs.CurrentVersion;
}
else
{
ViewBag.VersMpMon = "ND";
ViewBag.MonDisabled = "disabled";
}
// Recupero info SITE...
updArgs = UpdateMan.obj.getUpdateInfo(updateUrl("SITE"));
if (updArgs.IsUpdateAvailable)
{
ViewBag.VersMpSite = updArgs.CurrentVersion;
}
else
{
ViewBag.VersMpSite = "ND";
ViewBag.SiteDisabled = "disabled";
}
// Recupero info TAB...
updArgs = UpdateMan.obj.getUpdateInfo(updateUrl("TAB"));
if (updArgs.IsUpdateAvailable)
{
ViewBag.VersMpTab = updArgs.CurrentVersion;
}
else
{
ViewBag.VersMpTab = "ND";
ViewBag.TabDisabled = "disabled";
}
// Recupero info CTRACK...
updArgs = UpdateMan.obj.getUpdateInfo(updateUrl("CTRACK"));
if (updArgs.IsUpdateAvailable)
{
ViewBag.VersMpCTrack = updArgs.CurrentVersion;
}
else
{
ViewBag.VersMpCTrack = "ND";
ViewBag.CTrackDisabled = "disabled";
}
// Recupero info CTRACK...
updArgs = UpdateMan.obj.getUpdateInfo(updateUrl("MAG"));
if (updArgs.IsUpdateAvailable)
{
ViewBag.VersMpMag = updArgs.CurrentVersion;
}
else
{
ViewBag.VersMpMag = "ND";
ViewBag.MagDisabled = "disabled";
}
// Recupero info CTRACK...
updArgs = updManAuth.getUpdateInfo(updateUrlAuth("MP-STATS"));
if (updArgs.IsUpdateAvailable)
{
ViewBag.VersMpStats = updArgs.CurrentVersion;
}
else
{
ViewBag.VersMpStats = "ND";
ViewBag.StatsDisabled = "disabled";
}
// salvo risultati...
ViewBag.Results = results;
using (var ctx = new MoonProEntities())
{
System.Collections.Generic.List rawData = null;
// fix visibilità CTrack
try
{
// importo verifica abilitazione CTrack - !!!FARE!!! vero check key auth!
ViewBag.CTrack_Enb = string.IsNullOrEmpty(getAKV("CTRACK")) ? false : true;
#if false
rawData = ctx.stp_AKV_getByKey("CTRACK").ToList();
if (rawData.Count > 0)
{
ViewBag.CTrack_Enb = (rawData[0].valString != "");
}
else
{
ViewBag.CTrack_Enb = false;
}
#endif
}
catch (Exception exc)
{
SteamWare.Logger.Logging.Instance.Error($"Exception on check auth CTRACK:{Environment.NewLine}{exc}");
ViewBag.CTrack_Enb = false;
}
// fix visibilità MAG
try
{
// importo verifica abilitazione MAG - !!!FARE!!! vero check key auth!
ViewBag.MAG_Enb = string.IsNullOrEmpty(getAKV("MAG")) ? false : true;
#if false
rawData = ctx.stp_AKV_getByKey("MAG").ToList();
if (rawData.Count > 0)
{
ViewBag.MAG_Enb = (ctx.stp_AKV_getByKey("MAG").ToList()[0].valString != "");
}
else
{
ViewBag.MAG_Enb = false;
}
#endif
}
catch (Exception exc)
{
SteamWare.Logger.Logging.Instance.Error($"Exception on check auth MAG:{Environment.NewLine}{exc}");
ViewBag.MAG_Enb = false;
}
// fix visibilità STATS
try
{
// importo verifica abilitazione MAG - !!!FARE!!! vero check key auth!
ViewBag.Stats_Enb = string.IsNullOrEmpty(getAKV("STATS")) ? false : true;
#if false
rawData = ctx.stp_AKV_getByKey("STATS").ToList();
if (rawData.Count > 0)
{
ViewBag.Stats_Enb = (ctx.stp_AKV_getByKey("STATS").ToList()[0].valString != "");
}
else
{
ViewBag.Stats_Enb = false;
}
#endif
}
catch (Exception exc)
{
SteamWare.Logger.Logging.Instance.Error($"Exception on check auth STATS:{Environment.NewLine}{exc}");
ViewBag.Stats_Enb = false;
}
}
// VIEW!
return View();
}
///
/// Restituisce un QR code dato valore
///
///
///
public ActionResult QR(string valore)
{
QrCodeEncodingOptions options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 600,
Height = 600,
Margin = 0
};
var writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
writer.Options = options;
// scrivo bitmap
var pixelData = writer.Write(valore);
// Return Image
MemoryStream ms = new MemoryStream();
pixelData.Save(ms, ImageFormat.Png);
ms.Position = 0;
return new FileStreamResult(ms, "image/png");
}
///
/// System INFO
///
///
public ActionResult SystemInfo()
{
ViewBag.Title = "MAPO System Info";
ViewBag.Message = "HW & SW details";
// imposto i vari dati da mostrare a video senza indicare come bypassare...
string connStr = memLayer.ML.confReadString("DbConfConnectionString");
var currHwSwInfo = HwSwInfo.man(System.Reflection.Assembly.GetExecutingAssembly());
ViewBag.DbNameExample = connStr.Substring(0, connStr.IndexOf(";Persist Security"));
ViewBag.CodModulo = memLayer.ML.confReadString("CodModulo");
ViewBag.HwSwInfo = currHwSwInfo;
return View();
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file, string sorgente)
{
if (file != null && file.ContentLength > 0 && sorgente != "")
{
try
{
// forzo nome SEMPRE a web.config
//string path = Path.Combine(Server.MapPath("~/FileUpload"), Path.GetFileName(file.FileName).ToLower());
string path = Path.Combine(Server.MapPath("~/FileUpload"), "web.config");
file.SaveAs(path);
ViewBag.Message = "File Caricato!";
// ora processo import del sorgente selezionato...
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
}
else
{
ViewBag.Message = "Non è stato selezionato alcun file.";
}
return RedirectToAction("ConfigMan", "Home", new { sorgente });
}
///
/// Gestione QRCode utenti TAB
///
///
public ActionResult UserListQR(string id, string From, string Lenght)
{
int lenght = 0;
int from = 0;
int.TryParse(Lenght, out lenght);
int.TryParse(From, out from);
ViewBag.Title = "QR link";
ViewBag.Message = WebConfigurationManager.AppSettings["Cliente"];
ViewBag.BaseUrl = WebConfigurationManager.AppSettings["baseAuthUrl"];
ViewBag.Environment = WebConfigurationManager.AppSettings["Environment"];
using (var ctx = new MoonProEntities())
{
try
{
// esegue stored procedure come function, recuperando chiave desiderata...
var elOperatori = ctx.AnagraficaOperatori.ToList();
if (from + lenght > 0)
{
// seleziono sottoelenco SE ammissibile...
int numRec = elOperatori.Count;
lenght = lenght == 0 ? numRec : lenght;
from = from > numRec ? 0 : from;
if (from < numRec)
{
lenght = from + lenght < numRec ? lenght : numRec - from;
elOperatori = elOperatori.GetRange(from, lenght);
}
}
ViewBag.elOperatori = elOperatori;
}
catch
{ }
}
return View((object)ViewBag.elOperatori);
}
#endregion Public Methods
}
}