using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Windows.Forms; using System.Xml.Serialization; using System.Xml.Linq; using System.Data; using Excel = Microsoft.Office.Interop.Excel; using Microsoft.AspNet.SignalR.Client; using Ionic.Utils.Zip; using System.Reflection; using System.Threading.Tasks; namespace Fuel01 { public partial class Main : Form { private IHubProxy myHubproxy; private HubConnection myHubCnx; private string mySignalRiD; DataSet1.tb_epreuveDataTable tb_epr = new DataSet1.tb_epreuveDataTable(); DataSet1.tb_stationDataTable tb_station = new DataSet1.tb_stationDataTable(); #region Main Form public Main() { InitializeComponent(); System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone(); customCulture.NumberFormat.NumberDecimalSeparator = "."; System.Threading.Thread.CurrentThread.CurrentCulture = customCulture; } private void Main_Load(object sender, EventArgs e) { toolStripStatusLabel1_TextChanged(sender, null); // on force l'affichage de l'état Program.folder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\AsoFuel"; if (!Directory.Exists(Program.folder)) Directory.CreateDirectory(Program.folder); if (!Directory.Exists(Program.folder + @"\param")) Directory.CreateDirectory(Program.folder + @"\param"); if (!Directory.Exists(Program.folder + @"\In")) Directory.CreateDirectory(Program.folder + @"\in"); Directory.CreateDirectory(Program.folder); if (!Directory.Exists(Program.folder + @"\tmp")) Directory.CreateDirectory(Program.folder + @"\tmp"); if (!Directory.Exists(Program.folder)) { MessageBox.Show("Application mal installée, dossier " + Program.folder + " Non Créé, Abandon!"); Application.Exit(); } try { Excel.Application xlApp = new Excel.Application(); xlApp.Quit(); Program.isExcel = true; mnu_vehi_imp.Enabled = Program.isExcel; } catch (Exception ex) { MessageBox.Show("Application Excel non installée certaines fonctions ne seront pas disponibles!"); Program.traces(Program.folder + @"\tmp\traces.txt", DateTime.Now.ToString() + "Excel non installé " + ex.Message); } if (Properties.Settings.Default.key_ope != "") { Program.key_ope = Properties.Settings.Default.key_ope; Program.nom_ope = Properties.Settings.Default.nom_ope; Program.abrev_ope = Properties.Settings.Default.abrev_ope; mnu_vehi_dow.Enabled = true; mnu_sta.Enabled = true; mnu_param.Enabled = true; mnu_saisie.Enabled = true; } tbepreuveBindingSource.DataSource = tb_epr; refreshData(1); tbepreuveBindingSource.PositionChanged += new System.EventHandler(this.tbepreuveBindingSource_PositionChanged); //PGER init_signalR(); if (tb_epr.Rows.Count >= 1) { tbepreuveBindingSource.MoveLast(); tbepreuveBindingSource.MoveFirst(); } mnu_vehi_imp.Enabled = Program.isExcel = true ; spy(); } private void Main_Activated(object sender, EventArgs e) { if (Program.key_ope != (string)this.Tag) { this.Tag = Program.key_ope; refreshData(1); } } private void Main_FormClosing(object sender, FormClosingEventArgs e) { Properties.Settings.Default.key_ope = Program.key_ope; Properties.Settings.Default.nom_ope = Program.nom_ope; Properties.Settings.Default.abrev_ope = Program.abrev_ope; Properties.Settings.Default.Save(); e.Cancel = false; } private void toolStripStatusLabel1_TextChanged(object sender, EventArgs e) { if (toolStripStatusLabel1.Text == "OK") toolStripStatusLabel1.Image = global::Fuel01.Properties.Resources.green; else toolStripStatusLabel1.Image = global::Fuel01.Properties.Resources.red; //toolStripStatusLabel1.Visible = (toolStripStatusLabel1.Text == "OK"); } #endregion Main Form #region Menu Principal #region operations private void opérationToolStripMenuItem_Click(object sender, EventArgs e) { } private void mnu_ope_Click(object sender, EventArgs e) { f_epreuve fepr = new f_epreuve(tb_epr); fepr.ShowDialog(); mnu_vehi_dow.Enabled = true; mnu_sta.Enabled = true; } #endregion #region vehicules private void mnh_vehi_acc_Click(object sender, EventArgs e) { f_vehi fvehi = new f_vehi(); fvehi.ShowDialog(); } private void mnu_vehi_imp_parc_Click(object sender, EventArgs e) { f_impvehi fvehi = new f_impvehi("parc"); fvehi.ShowDialog(); } private void mnu_vehi_imp_tdf_Click(object sender, EventArgs e) { f_impvehi fvehi = new f_impvehi("tdf"); fvehi.ShowDialog(); } #endregion vehicules #region Stations f_station fsta; private void mnu_sta_Click(object sender, EventArgs e) { DataSet1.tb_stationRow mydata = null; DataRowView myrow = tbstationBindingSource.Current as DataRowView; if (myrow != null) { mydata = myrow.Row as DataSet1.tb_stationRow; fsta = new f_station(tb_station, mydata.key_sta); } else fsta = new f_station(tb_station, null); fsta.ShowDialog(); } #endregion Stations #region Saisie private void mnu_saisie_Click(object sender, EventArgs e) { if (dg_sta.SelectedRows.Count != 1) return; Program.key_sta = dg_sta.SelectedRows[0].Cells[0].Value.ToString(); f_saisie2 fsaisie = new f_saisie2(); fsaisie.ShowDialog(); } #endregion #region Gestion private void mnu_gest_Click(object sender, EventArgs e) { f_tools ftools = new f_tools(); ftools.ShowDialog(); } #endregion #region Paramètres private void mnu_param_Click(object sender, EventArgs e) { f_param fparam = new f_param(); fparam.ShowDialog(); } #endregion Paramètres #region Apropos private void mnu_about_Click(object sender, EventArgs e) { f_about fabout = new f_about(); fabout.ShowDialog(); } #endregion #endregion menu #region SIgnaR private async Task init_signalR() { await Task.CompletedTask; string hostname = ""; string srv = ""; try { try { hostname = Dns.GetHostName(); } catch (Exception ex) { hostname = "inconnu"; } if (Program.site != 1) return; Dictionary queryStringData = new Dictionary(); mySignalRiD = DateTime.Now.Ticks.ToString(); mySignalRiD= mySignalRiD.Substring(mySignalRiD.Length-5); mySignalRiD = hostname + "__" + mySignalRiD; queryStringData.Add("Login", mySignalRiD); try { myHubCnx = new HubConnection(Properties.Settings.Default.server_signalr, queryStringData); srv = Properties.Settings.Default.server_signalr; } catch (Exception ee) { Program.traces(Program.folder + @"\tmp\traces.txt", DateTime.Now.ToString() + " Connexion Secours " + srv + " impossible " + ee.Message); myHubCnx = new HubConnection("http://www.aformatix.com/SignalR/srv/", queryStringData); srv = @"http://www.aformatix.com/SignalR/srv/"; } myHubproxy = myHubCnx.CreateHubProxy("PatoHub"); myHubproxy.On("SendNewMessage", msg => getMsg(msg)); myHubCnx.StateChanged += myHubCnx_StateChanged; try { await myHubCnx.Start(); Program.okSignalR = true; toolStripStatusLabel1.Text = "OK"; } catch (Exception ee) { Program.traces(Program.folder + @"\tmp\traces.txt", DateTime.Now.ToString() + " Connexion à " + srv+ " impossible " + ee.Message); myHubproxy = null; Program.okSignalR = false; toolStripStatusLabel1.Text = "NOK"; } } catch (Exception eee) { Program.traces(Program.folder + @"\tmp\traces.txt", DateTime.Now.ToString() + " Connexion à " + srv + " impossible " + eee.Message); } } void myHubCnx_StateChanged(StateChange obj) { if (obj.NewState != Microsoft.AspNet.SignalR.Client.ConnectionState.Connected) { Program.okSignalR = false; toolStripStatusLabel1.Text = "NOK"; } else { Program.okSignalR = true; toolStripStatusLabel1.Text = "OK"; } Program.traces(Program.folder + @"\tmp\traces.txt", DateTime.Now.ToString() + " de " + obj.OldState.ToString() + " à " + obj.NewState.ToString() ); } private void getMsg(HubMessage hubmsg) { switch (hubmsg.Action) { case "maj": break; case "msg": string msg = hubmsg.Source + "/" + hubmsg.Action + "/" + hubmsg.Description + "/" + hubmsg.Valeur; if (hubmsg.Description == "send") { if (hubmsg.Source != mySignalRiD) sendFile(hubmsg.Valeur); } else MessageBox.Show(String.Format("Message de {0} \r\n {1} \r\n \r\n {2}", hubmsg.Source, hubmsg.Valeur, hubmsg.Date.ToString()), "SMS ", MessageBoxButtons.OK, MessageBoxIcon.Information); break; case "cnx": //majusers(hubmsg.Valeur); //MessageBox.Show(hubmsg.Valeur); break; } //makeTdo(); } private void send_msg(string action, string valeur, string description, string[] destinataire) { try { if (!Program.okSignalR) return; //ACTION UPDATE /MESSAGE //DESCRIPTION alarme mce investigation fiche sardatas //Valeur texte du message //Destinataire = dest? HubMessage mymsg = new HubMessage { Action = action, Valeur = valeur, Description = description, Destinataires = destinataire, Date = DateTime.UtcNow.ToString("dd/MM/yy hh:mm:ss") }; //new string[]{"admin"} myHubproxy.Invoke("DispatchMessage", mymsg); myHubproxy.Invoke("GetClients"); } catch (Exception ex) { Program.traces(Program.folder + @"\tmp\traces.txt", DateTime.Now.ToString() + " Send_msg Action:"+action+" Valeur:"+valeur+" Desc:"+description+" "+ex.Message); } } #endregion SignalR #region Datas private void tbepreuveBindingSource_PositionChanged(object sender, EventArgs e) { tb_station.Clear(); DataSet1.tb_epreuveRow mydata = null; DataRowView myrow = tbepreuveBindingSource.Current as DataRowView; if (myrow != null) { mydata = myrow.Row as DataSet1.tb_epreuveRow; Program.nom_ope = mydata.nom_epr; Program.key_ope = mydata.key_epr; Program.abrev_ope = mydata.abrev_epr; this.Text = Program.nom_ope; Program.subfolder = Program.folder + @"\" + Program.key_ope; if (!Directory.Exists(Program.subfolder)) Directory.CreateDirectory(Program.subfolder); else { if (File.Exists(Program.subfolder + @"\station.json")) { tb_station = DbUtil.LoadFromJson(Program.subfolder + @"\station.json", tb_station); tbstationBindingSource.DataSource = tb_station; Console.WriteLine(tb_station.Count); } //tb_station.ReadXml(Program.subfolder + @"\station.xml"); } //tbstationBindingSource.DataSource = tb_station; eprstat.Text = mydata.key_epr + "-" + mydata.abrev_epr + "-" + mydata.nom_epr; } else eprstat.Text = "null"; } private void refreshData(int indice) { if (indice == 1) { tb_epr=DbUtil.LoadFromJson(Program.folder + @"\epreuve.json", tb_epr); tbepreuveBindingSource.DataSource = tb_epr; Console.WriteLine(tb_epr.Count); if (string.IsNullOrEmpty(Program.key_ope)) { tbepreuveBindingSource.MoveFirst(); DataRowView firstRow = tbepreuveBindingSource.Current as DataRowView; Program.key_ope = firstRow["key_epr"].ToString(); } DataSet1.tb_epreuveRow myrow = tb_epr.FindBykey_epr(Program.key_ope); if (myrow != null) { Program.nom_ope = myrow.nom_epr; Program.key_ope = myrow.key_epr; Program.abrev_ope = myrow.abrev_epr; this.Text = Program.nom_ope; this.Tag = Program.key_ope; tbepreuveBindingSource.MoveFirst(); DataRowView myRow2 = tbepreuveBindingSource.Current as DataRowView; if (myRow2 != null) while (myRow2 != null && myRow2.Row["key_epr"].ToString() != myrow["key_epr"].ToString()) { tbepreuveBindingSource.MoveNext(); myRow2 = myRow2 = tbepreuveBindingSource.Current as DataRowView; } } tbepreuveBindingSource.PositionChanged += new System.EventHandler(this.tbepreuveBindingSource_PositionChanged); Program.subfolder = Program.folder + @"\" + Program.key_ope; tb_station.Clear(); if (!Directory.Exists(Program.subfolder)) Directory.CreateDirectory(Program.subfolder); else { if (File.Exists(Program.subfolder + @"\station.json")) { tb_station = DbUtil.LoadFromJson(Program.subfolder + @"\station.json", tb_station); } } tbstationBindingSource.DataSource = tb_station; } } private void dg_epr_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { mnu_ope_Click(dg_epr, null); } private void dg_sta_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { mnu_sta_Click(dg_sta, null); } #endregion private void bt_fact_Click(object sender, EventArgs e) { DataSet1.tb_stationRow mydata = null; DataRowView myrow = tbstationBindingSource.Current as DataRowView; if (myrow != null) { mydata = myrow.Row as DataSet1.tb_stationRow; f_facture ffac = new f_facture(mydata.key_sta); ffac.ShowDialog(); } else MessageBox.Show("Pas de station séléctionée!"); } private void spy() { string chemin = Properties.Settings.Default.chemin_copie_locale; try { FileSystemWatcher fw = new FileSystemWatcher(chemin, "*.xml"); fw.Changed += Fw_Spy; fw.Created += Fw_Spy; fw.Deleted += Fw_Spy; fw.Renamed += Fw_Spy; fw.EnableRaisingEvents = true; } catch (Exception ex) { tslbl1.Text = " Surveillance du répertoire de réception impossible !!!"; } } int nbSpy = 0; string lastSpy = ""; private void Fw_Spy(object sender, FileSystemEventArgs e) { if (e.ChangeType == WatcherChangeTypes.Created) { nbSpy++; FileInfo fi = new FileInfo(e.FullPath); lastSpy = fi.CreationTime.ToString("HH:mm:ss"); } tslbl1.Text = String.Format("- {0} fichier{1} créé{1} - Dernière création à {2}", nbSpy, nbSpy > 1 ? "s" : "", lastSpy); } private void button1_Click(object sender, EventArgs e) { send_msg("msg", @"C:\ProgramData\ASOFuel\7516\vehicule.xml", "send", null); send_msg("msg", @"C:\ProgramData\ASOFuel\7516\station.xml", "send", null); } private void button2_Click(object sender, EventArgs e) { if (!Program.okSignalR) init_signalR(); } int timerCount = 0; int sigRCount = 0; private void timerSigR_Tick(object sender, EventArgs e) { timerSigR.Interval = 60000; if (!Program.okSignalR) init_signalR(); if ( checkVersion_activated && timerCount%5==0) checkVersion(); timerCount++; } private void sendFile(string fileName) { string chaine = @"http://www.aformatix.com/stationservice/api/FileUpLoad/upLoadFiles"; WebClient client = new WebClient(); //fileName = @"C:\ProgramData\ASOFuel\7516\" + fileName; client.UploadFileAsync(new Uri(chaine), "POST", fileName); } private void splitContainer3_Panel2_MouseDoubleClick(object sender, MouseEventArgs e) { bool isVis = !bt_do.Visible; bt_retry.Visible = isVis; bt_do.Visible = isVis; bt_test.Visible = isVis; bt_doAll.Visible = isVis; text_file.Visible = isVis; toolStripStatusLabel1.Visible = isVis; } private void bt_do_Click(object sender, EventArgs e) { send_msg("msg", text_file.Text, "send", null); } private void actZip(string seek) { string path = ""; string mask=""; try { path = seek.Substring(0, seek.LastIndexOf("\\")); mask = seek.Substring(seek.LastIndexOf("\\") + 1); DateTime dt = DateTime.Now; string filename = Program.folder + @"\tmp\zip_" + dt.ToString("yy_MM_dd_hh_mm_ss") + ".txt"; StreamWriter writer = File.CreateText(filename); var zip = new ZipFile(Program.folder + @"\tmp\zip_" + dt.ToString("yy_MM_dd_hh_mm_ss") + ".zip", writer); string tmpDir = Path.GetTempPath(); if (!Directory.Exists(tmpDir)) tmpDir = Environment.GetEnvironmentVariable("temp"); if (!Directory.Exists(tmpDir)) tmpDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); zip.TempFileFolder = tmpDir; DirectoryInfo di = new DirectoryInfo(path); foreach (FileInfo fi in di.GetFiles(mask)) { zip.AddFile(fi.FullName); } zip.Save(); writer.Close(); send_msg("msg", zip.Name, "send", null); } catch (Exception ex) { Program.traces(Program.folder + @"\tmp\traces.txt", DateTime.Now.ToString() + " Err Make zip - seek:" + seek + " Path:" + path +" Mask:"+mask+"\r\n"+ex.Message); } } private void bt_doAll_Click(object sender, EventArgs e) { actZip(text_file.Text); } bool checkVersion_activated = true; private void checkVersion() { string[] strVersion = AssemblyVersion.Split('.'); double version = Convert.ToDouble(strVersion[0]) * 100000 + Convert.ToDouble(strVersion[1]) * 1000 + Convert.ToDouble(strVersion[2]) + Convert.ToDouble(strVersion[3]) / 10000; WebRequest request = WebRequest.Create(Properties.Settings.Default.server_adress_bin + ".txt"); try { WebResponse response = request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.ASCII); string retour = sr.ReadToEnd(); sr.Close(); double baseVersion = 0; if (double.TryParse(retour, out baseVersion)) if (baseVersion > version) if (MessageBox.Show("Veuillez lancer la mise à jour depuis le bouton MAJ\r\nde la fenêtre A Propos.\r\n Pour ne plus voir ce message, cliquer sur Annuler.", "Nouvelle version disponible", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.Cancel) checkVersion_activated = false; ; } catch (Exception e) { Program.traces(Program.folder + @"\tmp\traces.txt", DateTime.Now.ToString() +"Check Version "+ e.Message); } } public string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } private void mnu_verif_Click(object sender, EventArgs e) { f_verif verif = new f_verif(); verif.ShowDialog(); } private void parisNice17ToolStripMenuItem_Click(object sender, EventArgs e) { f_impvehi fvehi = new f_impvehi("nice17"); fvehi.ShowDialog(); } private void tbepreuveBindingSource_CurrentChanged(object sender, EventArgs e) { } } }