public void Start() { m_cxnReqFile = Path.GetTempFileName(); //maj du ID req Action init = () => { var netEngin = new NetEngin(Program.NetworkSettings); netEngin.Download(m_cxnReqFile, Urls.ConnectionReqURL, true); IEnumerable <Message> msgs = DialogEngin.ReadConnectionsReq(m_cxnReqFile); if (msgs.Count() > 0) { m_lastMsgID = msgs.Max(msg => msg.ID); } }; Action <Task> onErr = t => { File.Delete(m_cxnReqFile); Dbg.Log(t.Exception.InnerException.Message); m_callback(Result_t.Error); m_callback = null; }; var task = new Task(init, TaskCreationOptions.LongRunning); task.OnSuccess(PostReqAsync); task.OnError(onErr); task.Start(); }
void PostReq() { Dbg.Log("Sending connection request."); string tmpFile = Path.GetTempFileName(); m_exHandler = ReqExceptionHandler; using (new AutoReleaser(() => File.Delete(tmpFile))) { var netEngin = new NetEngin(Program.NetworkSettings); SetProgressMessage("Envoi des données au serveur..."); netEngin.Download(tmpFile, Urls.ConnectionReqURL, true); List <HubCore.DLG.Message> msgs = DialogEngin.ReadConnectionsReq(tmpFile).ToList(); m_msgID = msgs.Count == 0 ? 1 : msgs.Max(m => m.ID) + 1; var ms = new MemoryStream(); byte[] ciBytes = m_clInfo.GetBytes(); byte[] ceBytes = GetEnvironment().GetBytes(); ms.Write(ciBytes, 0, ciBytes.Length); ms.Write(ceBytes, 0, ceBytes.Length); var msg = new HubCore.DLG.Message(m_msgID, 0, Message_t.NewConnection, ms.ToArray()); msgs.Add(msg); DialogEngin.WriteConnectionsReq(tmpFile, msgs); netEngin.Upload(Urls.ConnectionReqURL, tmpFile, true); StartTimer(); SetProgressMessage("Attente de la réponse du serveur..."); } }
void ProcessTimer(object unused) { m_timer.Change(Timeout.Infinite, Timeout.Infinite); var netEngin = new NetEngin(Program.NetworkSettings); string tmpFile = Path.GetTempFileName(); netEngin.Download(tmpFile, Urls.ConnectionRespURL, true); var seq = from msg in DialogEngin.ReadConnectionsResp(tmpFile) where msg.ReqID >= m_lastMsgID select msg; if (!seq.Any()) { m_timer.Change(Timeout.Infinite, Timeout.Infinite); } else { Message resp = (from msg in seq where msg.ReqID == m_lastMsgID select msg).SingleOrDefault(); if (resp == null) { PostReqAsync(); } else { switch (resp.MessageCode) { case Message_t.Ok: //reset dlg file try { string dlgFile = SettingsManager.GetClientDialogFilePath(m_clientID); DialogEngin.WriteHubDialog(dlgFile, m_clientID, Enumerable.Empty <Message>()); netEngin.Upload(SettingsManager.GetClientDialogURL(m_clientID), dlgFile, true); m_callback(Result_t.Ok); } catch (Exception ex) { Dbg.Log(ex.Message); PostReqAsync(); } break; case Message_t.InvalidID: case Message_t.Rejected: m_callback(Result_t.Rejected); break; default: Dbg.Assert(false); break; } } } }
void PostSyncMessage() { Action post = () => { var netEngin = new NetEngin(Program.NetworkSettings); string tmpFile = Path.GetTempFileName(); var ms = new MemoryStream(); var writer = new RawDataWriter(ms, Encoding.UTF8); writer.Write(m_clInfo.ClientID); writer.Write(m_srvLastMsgID); writer.Write(m_clientLastMsgID); byte[] msgData = ms.ToArray(); try { netEngin.Download(tmpFile, Urls.ConnectionReqURL); var seq = DialogEngin.ReadConnectionsReq(tmpFile); uint msgID = 0; if (seq.Any()) { msgID = seq.Max(m => m.ID); } var msg = new Message(msgID + 1, 0, Message_t.Sync, msgData); DialogEngin.AppendConnectionsReq(tmpFile, new Message[] { msg }); netEngin.Upload(Urls.ConnectionReqURL, tmpFile); } catch (Exception ex) { Dbg.Log("PostSyncMessage: " + ex.Message); } finally { File.Delete(tmpFile); } }; var task = new Task(post, TaskCreationOptions.LongRunning); task.Start(); }
void PostReq() { Dbg.Log("Posting start msg..."); //posting to cnx file string tmpFile = Path.GetTempFileName(); var netEngin = new NetEngin(Program.NetworkSettings); try { netEngin.Download(tmpFile, Urls.ConnectionReqURL, true); IEnumerable <Message> msgsCnx = DialogEngin.ReadConnectionsReq(tmpFile); if (msgsCnx.Any()) { m_reqID = msgsCnx.Max(m => m.ID); } else { m_reqID = 0; } Message req = new Message(++m_reqID, 0, Message_t.Start, m_msgData); DialogEngin.WriteConnectionsReq(tmpFile, msgsCnx.Add(req)); netEngin.Upload(Urls.ConnectionReqURL, tmpFile, true); m_cnxAttempts = 0; Dbg.Log("Posting start msg done."); } catch (Exception ex) { Dbg.Log(ex.Message); } finally { m_timer.Start(); File.Delete(tmpFile); } }
void ProcessResp() { StopTimer(); string tmpFile = Path.GetTempFileName(); Dbg.Log($"Processing Response, attempts = {m_attemptsCount + 1}."); m_exHandler = RespExceptionHandler; var netEngin = new NetEngin(Program.NetworkSettings); using (new AutoReleaser(() => File.Delete(tmpFile))) { SetProgressMessage("Réception des données à partir du serveur..."); try { netEngin.Download(tmpFile, Urls.ConnectionRespURL, true); } catch (Exception ex) { Dbg.Log(ex.Message); DialogEngin.WriteConnectionsResp(tmpFile, Enumerable.Empty <HubCore.DLG.Message>()); } IEnumerable <HubCore.DLG.Message> messages = DialogEngin.ReadConnectionsResp(tmpFile); HubCore.DLG.Message[] msgs = (from resp in messages where resp.ReqID >= m_msgID select resp).ToArray(); HubCore.DLG.Message msg = msgs.Where(m => m.ReqID == m_msgID).SingleOrDefault(); uint clID = msg == null ? 0 : BitConverter.ToUInt32(msg.Data, 0); if (msg != null && clID == m_clInfo.ClientID) { switch (msg.MessageCode) { case Message_t.InvalidID: Dbg.Log($"Got invalid ID! (ClientID = {m_clInfo.ClientID})."); ClientInfo clInfo = ClientInfo.CreateClient(m_clInfo.ProfileID); clInfo.ContaclEMail = m_clInfo.ContaclEMail; clInfo.ContactName = m_clInfo.ContactName; clInfo.ContactPhone = m_clInfo.ContactPhone; m_clInfo = clInfo; if (++m_attemptsCount >= SettingsManager.MaxConnectAttemps) { if (ShowMessage(MAX_ATTEMPTS_ERROR, MessageBoxButtons.YesNo) != DialogResult.Yes) { CloseDialog(); return; } else { m_attemptsCount = 0; } } PostReq(); break; case Message_t.Ok: Dbg.Log("Client registered :-)!"); Program.Settings.ClientInfo = m_clInfo; SetProgressMessage("Enregistrement terminé."); //creation des fichier dlg string dlgFile = SettingsManager.GetClientDialogFilePath(clID); DialogEngin.WriteHubDialog(dlgFile, clID, Enumerable.Empty <HubCore.DLG.Message>()); try { netEngin.Upload(SettingsManager.GetClientDialogURL(clID), dlgFile, true); } catch (Exception ex) { Dbg.Log(ex.Message); } ShowMessage("Votre enregistrement est maintenant terminé. " + "Vous pouvez commencer à utiliser l’application."); IsRegistered = true; CloseDialog(); break; case Message_t.InvalidProfile: Dbg.Log($"Got invalid Profile! (ProfileID: = {m_clInfo.ProfileID})."); ShowMessage(SRV_ERROR); CloseDialog(); return; case Message_t.Rejected: Dbg.Log("Got reject connection!"); ShowMessage(REJECT_CONNCTION_ERROR); CloseDialog(); return; default: Dbg.Log("Got invalid response!!!!"); Dbg.Assert(false); break; } } else if (msgs.Length > 0) { Dbg.Log("Request message lost."); if (++m_attemptsCount >= SettingsManager.MaxConnectAttemps) { if (ShowMessage(MAX_ATTEMPTS_ERROR, MessageBoxButtons.YesNo) != DialogResult.Yes) { CloseDialog(); return; } else { m_attemptsCount = 0; } } PostReq(); } else if (++m_attemptsCount >= SettingsManager.MaxConnectAttemps) { Dbg.Log("Timeout."); if (ShowMessage(MAX_ATTEMPTS_ERROR, MessageBoxButtons.YesNo) == DialogResult.Yes) { StartTimer(); m_attemptsCount = 0; PostReq(); } else { CloseDialog(); } } else { StartTimer(); SetProgressMessage("Attente de la réponse du serveur..."); } } }
void ProcessDownloads() { List <string> files = null; lock (m_pendingDownloads) if (m_pendingDownloads.Count > 0) { files = m_pendingDownloads.ToList(); m_pendingDownloads.Clear(); } if (files != null) { string localDlgFolder = AppPaths.DialogFolderPath; string cxnReqFile = Names.ConnectionReqFile; var netEngin = new NetEngin(AppContext.Settings.NetworkSettings); for (int i = files.Count - 1; i >= 0; --i) { string fileName = files[i]; string destPath = Path.Combine(localDlgFolder, fileName); string srcURL = Urls.DialogDirURL + fileName; try { netEngin.Download(destPath, srcURL); } catch (Exception ex) { AppContext.LogManager.LogSysError("Traitement des transferts à partir du serveur: " + ex.Message, true); continue; } if (string.Compare(fileName, cxnReqFile, true) == 0) { try { ProcessConnectionReq(DialogEngin.ReadConnectionsReq(AppPaths.ConnectionReqPath)); } catch (Exception ex) { TextLogger.Warning(ex.Message); } } else { uint clID = uint.Parse(Path.GetFileNameWithoutExtension(fileName), System.Globalization.NumberStyles.AllowHexSpecifier); try { ProcessDialog(clID, DialogEngin.ReadHubDialog(Path.Combine(localDlgFolder, fileName), clID)); } catch (Exception ex) { AppContext.LogManager.LogSysError("Traitement des transferts à partir du serveur: " + ex.Message, true); continue; } } files.RemoveAt(i); } foreach (string file in files) { AddDownload(file); } } //allways need to be downlaoded AddDownload(Names.ConnectionReqFile); }
public static bool UpdateData() { /* * telecharger le fichier manifest * si DataGeneration > manifest.DataGeneration * signaler l'erreur a HubGovernor * sortir * si DataGeneration < manifest.DataGeneration * telecharger manifest.data * pour chaque entrées E dans manifest.data et tant que DataGeneration < manifest.DataGeneration * si DataGeneration == E.PreDataGeneration * Appliquer les maj des tables * mettre a jours DataGeneration */ string manifest = Path.GetTempFileName(); using (new AutoReleaser(() => File.Delete(manifest))) try { var netEngin = new NetEngin(Program.NetworkSettings); netEngin.Download(manifest, Urls.ManifestURL); IUpdateManifest updateManifest = UpdateEngin.ReadUpdateManifest(manifest); string log = "Recherche de mise à jour des données. Version actulle des données: " + $"{Program.Settings.DataGeneration}. "; if (updateManifest.DataGeneration == Program.Settings.DataGeneration) { Program.DialogManager.PostLog(log + " Les données sont à jour", false); return(true); } if (Program.Settings.UpdateKey != updateManifest.UpdateKey) { if (Program.Settings.UpdateKey == 0) { Program.Settings.UpdateKey = updateManifest.UpdateKey; } else { Log.LogEngin.PushFlash(AppText.ERR_UPDATEKEY); Dbg.Log("Update key mismatch!"); Program.DialogManager.PostLog(log + AppText.ERR_UPDATEKEY, true); return(false); } } //TODO: signaler l'erreur si DataGeneration < manifest.DataGeneration string dataManifest = Path.GetTempFileName(); using (Log.LogEngin.PushMessage("Installation des mises à jour...")) using (new AutoReleaser(() => File.Delete(dataManifest))) { netEngin.Download(dataManifest, Urls.DataManifestURL); var uris = new List <UpdateURI>(UpdateEngin.ReadDataManifest(dataManifest, Program.Settings.DataGeneration)); foreach (UpdateURI uu in uris.OrderBy(u => u.DataPreGeneration)) { if (uu.DataPreGeneration == Program.Settings.DataGeneration) { string updateFile = Path.GetTempFileName(); using (new AutoReleaser(() => File.Delete(updateFile))) { netEngin.Download(updateFile, Urls.DataUpdateDirURL + uu.FileURI); ApplyUpdate(updateFile); Program.Settings.DataGeneration = uu.DataPostGeneration; } } } DataUpdated?.Invoke(); } Program.DialogManager.PostLog(log + "Mises à jour installées. " + $"Nouvelle version des données: {Program.Settings.DataGeneration}", false); Assert(Program.Settings.DataGeneration == updateManifest.DataGeneration); } catch (Exception ex) { Dbg.Log("Data update: " + ex.Message); } return(true); }
public static void UpdateApp() { //dl global manifest Log.LogEngin.PushFlash("Rechercher d'une mise à jour de l'application..."); const string logTxt = "Rechercher d'une mise à jour de l'application. "; string tmpFile = Path.GetTempFileName(); using (new AutoReleaser(() => File.Delete(tmpFile))) try { var netEngin = new NetEngin(Program.NetworkSettings); netEngin.Download(tmpFile, Urls.ManifestURL); IUpdateManifest updateManifest = UpdateEngin.ReadUpdateManifest(tmpFile); Version curVer = Assembly.GetExecutingAssembly().GetName().Version; Version ver = updateManifest.GetAppVersion(Program.AppArchitecture); if (ver == null || curVer.CompareTo(ver) >= 0) { Log.LogEngin.PushFlash("Vous disposez déjà de la dernière version de l’application."); Program.DialogManager.PostLog(logTxt + "Pas de nouvelle mise à jour", false); return; } Log.LogEngin.PushFlash($"Une nouvelle version de l'application est disponible ({ver})."); Program.DialogManager.PostLog(logTxt + $"Une nouvelle version de l'application est disponible, version: ({ver})", false); const string setupTxtLog = "L'utilsateur a refuser d'installer la nouvelle version du HUB"; if (CanDownlaodAppUpdate?.Invoke() != true) { Program.DialogManager.PostLog(setupTxtLog, false); return; } Log.LogEngin.PushFlash($"Téléchargement de la mise à jour..."); //dl app manifest netEngin.Download(tmpFile, Urls.AppManifestURL); Dictionary <AppArchitecture_t, string> upFiles = UpdateEngin.ReadAppManifest(tmpFile); string fileName = upFiles[Program.AppArchitecture]; //dl update file var url = Urls.AppUpdateDirURL + fileName; netEngin.Download(tmpFile, url); if (CanRunAppUpdate?.Invoke() != true) { Program.DialogManager.PostLog(setupTxtLog, false); return; } string tmpDir = Path.GetTempPath(); new FilesBag().Decompress(tmpFile, tmpDir); System.Diagnostics.Process.Start(Path.Combine(tmpDir, "setup.exe")); Program.DialogManager.PostLog("Lancement du programme d'installation de la mise à jour du HUB", false); System.Windows.Forms.Application.Exit(); } catch (Exception ex) { Dbg.Log("App update: " + ex.Message); } }
public void Start() { Dbg.Assert(IsRunning == false); IsRunning = true; Opts.SettingsView.ClientInfoChanged += SettingsView_ClientInfoChaned; //client enregistre? m_clInfo = Program.Settings.ClientInfo; if (m_clInfo == null) { if (RegisterClient()) { m_clStatus = ClientStatus_t.Enabled; m_dialogTimer.Start(); m_updateTimer.Start(); m_dialogRunning = true; var updateTask = new Task(AutoUpdater.Update, TaskCreationOptions.LongRunning); updateTask.Start(); } return; } DialogEngin.WriteHubDialog(SettingsManager.GetClientDialogFilePath(m_clInfo.ClientID), m_clInfo.ClientID, Enumerable.Empty <Message>()); //process only status part of the g file string tmpFile = Path.GetTempFileName(); Action start = () => { var netEngin = new NetEngin(Program.NetworkSettings); netEngin.Download(tmpFile, SettingsManager.GetServerDialogURL(m_clInfo.ClientID), true); }; Action onSuccess = () => { ClientDialog clDlg = DialogEngin.ReadSrvDialog(tmpFile); m_clStatus = clDlg.ClientStatus; if (m_clStatus == ClientStatus_t.Enabled) { new StartHandler(m_clInfo.ClientID, StartResp).Start(); } else if (m_clStatus == ClientStatus_t.Banned) { foreach (IDBTable tbl in Program.TablesManager.CriticalTables) { tbl.Clear(); Program.Settings.DataGeneration = 0; } System.Windows.Forms.MessageBox.Show(AppText.ERR_BANNED, AppText.APP_NAME, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); Exit(); return; } else if (m_clStatus == ClientStatus_t.Disabled) { new ResumeHandler(ResumeResp, m_clInfo.ClientID).Start(); } else { ResetRegistration(); } File.Delete(tmpFile); }; Action <Task> onErr = t => { Dbg.Log(t.Exception.InnerException.Message); //assume client enabled m_clStatus = ClientStatus_t.Enabled; new StartHandler(m_clInfo.ClientID, StartResp).Start(); }; var task = new Task(start, TaskCreationOptions.LongRunning); task.OnSuccess(onSuccess); task.OnError(onErr); task.Start(); }
void ProcessResp() { m_timer.Stop(); Dbg.Log("Processing start notification resp..."); string tmpFile = Path.GetTempFileName(); var netEngin = new NetEngin(Program.NetworkSettings); try { netEngin.Download(tmpFile, Urls.ConnectionRespURL, true); IEnumerable <Message> resps = from msg in DialogEngin.ReadConnectionsResp(tmpFile) where msg.ReqID >= m_reqID select msg; if (resps.Any()) { Message resp = resps.SingleOrDefault(m => m.ReqID == m_reqID); if (resp != null) { var ms = new MemoryStream(resp.Data); var reader = new RawDataReader(ms, Encoding.UTF8); uint clID = reader.ReadUInt(); if (clID == m_clID) { switch (resp.MessageCode) { case Message_t.Ok: m_callBack.Invoke(true); Dbg.Log("Starting notification done. :-)"); return; case Message_t.Rejected: m_callBack.Invoke(false); Dbg.Log("Starting rejected. :-("); return; } } } Dbg.Log("Starting msg lost. Reposting..."); PostReq(); } else if (++m_cnxAttempts >= MAX_ATTEMPTS) { Dbg.Log("Starting msg lost. Reposting..."); PostReq(); } else { m_timer.Start(); } } catch (Exception ex) { Dbg.Log(ex.Message); m_timer.Start(); } finally { File.Delete(tmpFile); } }