Files
cms_thermo_active/Client/View/OpeningForm.cs
T
2020-06-19 19:28:07 +02:00

415 lines
14 KiB
C#

using Client.Config;
using Client.Config.SubModels;
using Client.Utils;
using Microsoft.WindowsAPICodePack.Taskbar;
using Newtonsoft.Json;
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Active_Client.View
{
public partial class OpeningForm : MetroFramework.Forms.MetroForm
{
public const int TimerTest = 500;
private HttpWebRequest ConnTestRequest;
private HttpWebResponse ConnTestResponse;
private String ConnTestError;
private Task ConnTask;
private ushort WaitDot = 1;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#region WINDOW_START_&_BEHAVIOUR_METHOD
//Constructor
public OpeningForm()
{
InitializeComponent();
if (Config.ClientConfig.IsSCM)
{
LogoCMS.Visible = false;
LogoSCM.Visible = true;
this.Icon = Properties.Resources.MAESTRO_ACTIVE_ICON;
}
else
{
LogoCMS.Visible = true;
LogoSCM.Visible = false;
}
//Setup The Browser
if (!SetupBrowser())
return;
//Set window Position
this.Location = new Point((Screen.PrimaryScreen.Bounds.Width / 2) - (this.Width / 2), (Screen.PrimaryScreen.Bounds.Height / 2) - (this.Height / 2));
}
//OnLoad Method
private void LoadingForm_Load(object sender, EventArgs e)
{
//Force on Desktop 1
this.DesktopLocation = new Point((Screen.PrimaryScreen.Bounds.Width / 2) - (this.Width / 2), (Screen.PrimaryScreen.Bounds.Height / 2) - (this.Height / 2));
//Start Backgroud Task
ConnTask = Task.Run(() => BagroundWorker());
}
//Set the status & Messages Labels
private void setStatus(String status, String Error)
{
//Invoke method if is needed or call the method in STD mode
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate () { StatusLBL.Text = status; });
this.Invoke((MethodInvoker)delegate () { ErrorLBL.Text = Error; });
}
else
{
StatusLBL.Text = status;
ErrorLBL.Text = Error;
}
}
//Set Opacity of the Window
private void setOpacity(double opacity)
{
//Invoke method if is needed or call the method in STD mode
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate () { this.Opacity = opacity; });
}
else
{
this.Opacity = opacity;
}
}
//Close the Window
private void closeWindow()
{
//Invoke method if is needed or call the method in STD mode
if (this.InvokeRequired)
this.Invoke((MethodInvoker)delegate () { this.Close(); });
else
this.Close();
}
#endregion
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#region CONNECTING_TASK_METHOD
//Main Void of the background Task
private void BagroundWorker()
{
//Set App Opacity
setOpacity(1);
//Show the loading state on the app ICON
this.Invoke((MethodInvoker)delegate () { TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Indeterminate, this.Handle); });
//try to Request
if (!Config.ConnectionConfig.BypassReadConfiguration)
{
setStatus("Connecting to " + Config.ConnectionConfig.ServerUrl + ":" + Config.ConnectionConfig.ServerPort, "");
Boolean error = false;
do
{
if (error == true)
return;
} while (!testConnection(new Uri(Config.ConnectionConfig.ReadConfigUrl), out error));
}
//Set App Opacity (Only Siemens)
if (Config.VendorHmiConfig.Type == 2)
setOpacity(0.85);
//Open Nc Window
setStatus("Opening NC Window... ", "");
if (Config.VendorHmiConfig.Enabled)
if (!OpenNcWindow())
return;
//Open Nc Window
setStatus("Opening PROD Window... ", "");
if (Config.ProdSoftwareConfig.Enabled)
{
var exename = Path.GetFileNameWithoutExtension(Config.ProdSoftwareConfig.Path);
if (!OpenProdWindow(Config.ProdSoftwareConfig.Path, exename))
return;
}
//Set App Opacity
setOpacity(1);
//Close the Window
closeWindow();
}
//Sub-Method used to SetupThe Browser Environment
private bool SetupBrowser()
{
//Delete Browser Cache
try
{
if (Config.ConnectionConfig.DeleteCahceFolderOnStartup && Directory.Exists(Constants.BROWSER_CACHE_FOLDER))
{
setStatus("Deleting Browser Chache Folder...", "");
Directory.Delete(Constants.BROWSER_CACHE_FOLDER, true);
}
}
catch (Exception E)
{
setStatus("Close the application!", E.Message);
return false;
}
return true;
}
//Sub-Method used to test the connection
private bool testConnection(Uri url, out Boolean error)
{
Boolean Connected = false;
error = false;
//Try to connect
if (url.Scheme == Uri.UriSchemeHttps || url.Scheme == Uri.UriSchemeHttp)
{
try
{
ConnTestRequest = (HttpWebRequest)WebRequest.Create(url);
ConnTestRequest.Timeout = (int)(TimerTest);
ConnTestRequest.KeepAlive = false;
ConnTestResponse = (HttpWebResponse)ConnTestRequest.GetResponse();
ConnTestError = ConnTestResponse.StatusCode.ToString();
Connected = (ConnTestResponse.StatusCode == HttpStatusCode.OK) ? true : false;
}
catch (WebException ex)
{
Connected = false;
ConnTestError = ex.Status.ToString();
}
}
else
Connected = true;
//Check if it's connected
if (Connected)
{
// var jsonDefinition = new { ncVendor = "", showHMI = "", ncIp = "", ncPort = "", prodEnabled = "", prodPath = "", extPrograms = "" };
var jsonDefinition = new ServerConfigModel();
setStatus("Connected!", "");
//Read the configuration from Server
try
{
using (var reader = new StreamReader(ConnTestResponse.GetResponseStream()))
{
var ConfigResponse = JsonConvert.DeserializeAnonymousType(reader.ReadToEnd(), jsonDefinition);
if (!String.IsNullOrWhiteSpace(ConfigResponse.NcVendor) && !String.IsNullOrWhiteSpace(ConfigResponse.ShowHMI))
{
string ncVendorName = ConfigResponse.NcVendor.ToUpper();
string ncVendorHMI = ConfigResponse.ShowHMI.ToUpper();
Config.VendorHmiConfig.IpAddress = ConfigResponse.NcIp.ToUpper();
Config.VendorHmiConfig.Port = ConfigResponse.NcPort.ToUpper();
string ProdEnabled = ConfigResponse.ProdEnabled.ToUpper();
string ProdPath = ConfigResponse.ProdPath.ToUpper();
string Autorun = ConfigResponse.Autorun.ToUpper();
//Read the Server Type
if (ncVendorName.Equals("DEMO"))
Config.VendorHmiConfig.Type = 0;
else if (ncVendorName.Equals("FANUC"))
Config.VendorHmiConfig.Type = 1;
else if (ncVendorName.Equals("SIEMENS"))
Config.VendorHmiConfig.Type = 2;
else if (ncVendorName.Equals("OSAI"))
Config.VendorHmiConfig.Type = 3;
else if (ncVendorName.Equals("S7NET"))
Config.VendorHmiConfig.Type = 4;
else
{
setStatus("Close the application!", "Errror in configuration, from server");
error = true;
return false;
}
//Read if the HMI must be visible
if (ncVendorHMI.ToUpper().Equals("TRUE"))
Config.VendorHmiConfig.Enabled = true;
else
Config.VendorHmiConfig.Enabled = false;
//Autorun
if (Autorun.ToUpper().Equals("TRUE"))
Config.ClientConfig.Autorun = true;
else
Config.ClientConfig.Autorun = false;
//Read if the HMI must be visible
if (ProdEnabled.ToUpper().Equals("TRUE"))
Config.ProdSoftwareConfig.Enabled = true;
else
Config.ProdSoftwareConfig.Enabled = false;
// Paths
Config.ProdSoftwareConfig.Path = ProdPath;
Config.TextEditorPath = ConfigResponse.EditorPath;
if (ConfigResponse.ExtSoftwares != null)
Config.ExtSoftwaresConfig = ConfigResponse.ExtSoftwares.ToArray();
return true;
}
}
return true;
}
catch (Exception e)
{
setStatus("Error!", "Error While loading the configuration");
return false;
}
}
else
{
//Set the Dot string
String dot = "";
for (int i = 0; i < WaitDot; i++) dot += ".";
//Set the status
setStatus("Retry connection to " + Config.ConnectionConfig.ServerUrl + ":" + Config.ConnectionConfig.ServerPort + " " + dot, "Server not found (Error: " + ConnTestError + ")");
if (WaitDot < 3)
WaitDot++;
else
WaitDot = 0;
//Wait 500 ms
Thread.Sleep(500);
return false;
}
}
//Sub-Method used to open the NC Window
private bool OpenNcWindow()
{
switch (NcWindow.StartNcWindow())
{
case 0: return true;
case 1:
{
setStatus("Close the application!", "NC Path not found: " + NcWindow.ProcessPath);
return false;
};
case 2:
{
setStatus("Close the application!", "Unable to start the NC application: ");
return false;
};
}
return false;
}
//Sub-Method used to open the NC Window
private bool OpenProdWindow(string ExePath, string ExeName)
{
switch (NcWindow.StartProdWindow(ExePath, ExeName))
{
case 0: return true;
case 1:
{
setStatus("Close the application!", "PROD EXE Path not found: " + ExePath);
return false;
};
case 2:
{
setStatus("Close the application!", "Unable to start the PROD EXE application: ");
return false;
};
}
return false;
}
#endregion
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#region CLOSE_BUTTON_BEHAVIUR
//On click Method
private void CloseLabel_Click(object sender, EventArgs e)
{
//Force show Taskbar
NcWindow.ShowTaskBar();
//Exit
Environment.Exit(0);
}
//On Mouse Enter
private void CloseLabel_MouseEnter(object sender, EventArgs e)
{
CloseLabel.ForeColor = Color.DarkRed;
}
//On Mouse Leave
private void CloseLabel_MouseLeave(object sender, EventArgs e)
{
CloseLabel.ForeColor = Color.White;
}
#endregion
private void CloseLabel_MouseClick(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void CloseLabel_MouseClick(object sender, MouseEventArgs e)
{
}
}
}