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(); }
//private: void Initialize() { AppContext.LogManager.LogSysActivity("Démarrage de la réinitialisation des fichiers sur le serveur", true); string reqFilePath = AppPaths.ConnectionReqPath; DialogEngin.WriteConnectionsReq(reqFilePath, Enumerable.Empty <Message>()); string respFilePath = AppPaths.ConnectionRespPath; DialogEngin.WriteConnectionsResp(respFilePath, Enumerable.Empty <Message>()); try { var netEngin = new NetEngin(AppContext.Settings.NetworkSettings); netEngin.Upload(Urls.ConnectionReqURL, reqFilePath); netEngin.Upload(Urls.ConnectionRespURL, respFilePath); m_initializationDone = true; AppContext.LogManager.LogSysActivity("Réinitialisation des fichiers sur le serveur terminée", true); } catch (Exception ex) { AppContext.LogManager.LogSysError("Une erreur est survenue lors de l’initialisation du serveur: " + ex.Message, true); } }
//private: void PostReqAsync() { Action upload = () => { var msg = new Message(++m_lastMsgID, 0, Message_t.Resume, BitConverter.GetBytes(m_clientID)); IEnumerable <Message> msgs = DialogEngin.ReadConnectionsReq(m_cxnReqFile); DialogEngin.WriteConnectionsReq(m_cxnReqFile, msgs.Add(msg)); var netEngin = new NetEngin(Program.NetworkSettings); try { netEngin.Upload(Urls.ConnectionReqURL, m_cxnReqFile, true); m_timer.Change(TIMER_INTERVALL, TIMER_INTERVALL); } catch (Exception ex) { Dbg.Log(ex.Message); m_callback(Result_t.Error); m_callback = null; } }; new Task(upload, TaskCreationOptions.LongRunning).Start(); }
void ProcessDialog(uint clientID, IEnumerable <Message> msgs) { ActiveClientsQueue.IClientData clData = m_onlineClients.Get(clientID); if (clData == null) { return; } uint lastClMsgID = clData.LastClientMessageID; var seq = from msg in msgs where msg.ID > lastClMsgID select msg; if (seq.Any()) { uint lastSrvMsgID = clData.LastSrvMessageID; var respList = new List <Message>(seq.Count()); var clStatus = m_ndxerClientsStatus.Get(clientID) as ClientStatus; clStatus.LastSeen = DateTime.Now; clData.TimeToLive = ActiveClientsQueue.InitTimeToLive; clData.LastClientMessageID = seq.Max(m => m.ID); foreach (Message msg in seq) { Dbg.Log($"Processing dialog msg {msg.ID}: {msg.MessageCode}..."); if (m_msgProcessors.ContainsKey(msg.MessageCode)) { Message resp = m_msgProcessors[msg.MessageCode](msg, clientID); if (resp != null) { respList.Add(resp); } } } if (respList.Count > 0) { DialogEngin.AppendSrvDialog(AppPaths.GetSrvDialogFilePath(clientID), respList); AddUpload(Names.GetSrvDialogFile(clientID)); } Dbg.Assert(clData.LastClientMessageID >= lastClMsgID); clStatus.SentMsgCount += clData.LastClientMessageID - lastClMsgID; Dbg.Assert(clData.LastSrvMessageID >= lastSrvMsgID); clStatus.ReceivedMsgCount += clData.LastSrvMessageID - lastSrvMsgID; m_ndxerClientsStatus.Source.Replace(m_ndxerClientsStatus.IndexOf(clientID), clStatus); } }
public uint SendMessage(Message_t msgCode, byte[] data = null, uint reqID = 0) { Message msg; lock (m_lock) msg = new Message(++m_clientLastMsgID, reqID, msgCode, data); try { string dest = SettingsManager.GetClientDialogURL(m_clInfo.ClientID); string src = SettingsManager.GetClientDialogFilePath(m_clInfo.ClientID); DialogEngin.AppendHubDialog(src, m_clInfo.ClientID, msg); new NetEngin(Program.NetworkSettings).Upload(dest, src); return(msg.ID); } catch (Exception ex) { Dbg.Log(ex.Message); } return(0); }
void ProcessConnectionReq(IEnumerable <Message> messages) { uint id = m_lastCxnReqMsgID; IEnumerable <Message> reqs = messages.Where(m => m.ID > id); if (reqs.Any()) { var respList = new List <Message>(); m_lastCxnReqMsgID = reqs.Max(m => m.ID); foreach (Message req in reqs) { Dbg.Log($"Processing connection msg {req.ID} ..."); Message resp = m_cxnReqProcessors[req.MessageCode](req); if (resp != null) { respList.Add(resp); } } string respFile = AppPaths.ConnectionRespPath; DialogEngin.AppendConnectionsResp(respFile, respList); AddUpload(Names.ConnectionRespFile); } }
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; } } } }
public void PostMessage(Message_t msgCode, byte[] data = null, uint reqID = 0) { lock (m_lock) { Message msg = new Message(++m_clientLastMsgID, reqID, msgCode, data); DialogEngin.AppendHubDialog(SettingsManager.GetClientDialogFilePath(m_clInfo.ClientID), m_clInfo.ClientID, msg); m_needUpload = true; } }
void ProcessProfilesChange() { AppContext.LogManager.LogSysActivity("Lancement de la mise à jour des profils sur serveur", true); string filePath = AppPaths.ProfilesPath; var seq = from UserProfile usrPro in m_ndxerProfiles.Source.Enumerate().Cast <ProfileRow>() select new ProfileInfo(usrPro.ID, usrPro.Name, usrPro.Privilege); DialogEngin.WriteProfiles(filePath, seq); AddUpload(Names.ProfilesFile); }
//protected: protected override void OnLoad(EventArgs e) { ClientInfo clInfo = Program.Settings.ClientInfo; if (clInfo != null) { m_tbContact.Text = clInfo.ContactName; m_tbEmail.Text = clInfo.ContaclEMail; m_tbPhone.Text = clInfo.ContactPhone; Func <string> dlProfile = () => { string tmpFile = Path.GetTempFileName(); try { new NetEngin(Program.NetworkSettings).Download(tmpFile, Urls.ProfilesURL); ProfileInfo pi = DialogEngin.ReadProfiles(tmpFile).SingleOrDefault(p => p.ProfileID == clInfo.ProfileID); return(pi?.ProfileName); } catch { } finally { File.Delete(tmpFile); } return(null); }; Action <Task <string> > onSucces = t => { m_lblProfile.Text = t.Result; }; var task = new Task <string>(dlProfile, TaskCreationOptions.LongRunning); task.OnSuccess(onSucces); task.Start(); } base.OnLoad(e); }
Message ProcessSetInfoMessage(Message msg, uint clID) { Dbg.Assert(msg.MessageCode == Message_t.SetInfo); AppContext.LogManager.LogSysActivity($"Réception d’une mise à jour des informations Utilisateur du client {ClientStrID(clID)}", true); int ndx = m_ndxerClients.IndexOf(clID); if (ndx < 0) { AppContext.LogManager.LogSysActivity("Mise à jour des information utilisateur d'un client inexistant. Réinitialisation du client.", true); //maj du fichier gov string srvDlgFile = AppPaths.GetSrvDialogFilePath(clID); //le client n'existe pas => son fichier gov n'existe pas var clDlg = new ClientDialog(clID, ClientStatus_t.Reseted, Enumerable.Empty <Message>()); DialogEngin.WriteSrvDialog(srvDlgFile, clDlg); AddUpload(Path.GetFileName(srvDlgFile)); return(null); } //maj le client ClientInfo clInfo = new ClientInfo(); clInfo.SetBytes(msg.Data); var client = new HubClient(clInfo.ClientID, clInfo.ProfileID) { ContaclEMail = clInfo.ContaclEMail, ContactName = clInfo.ContactName, ContactPhone = clInfo.ContactPhone, }; m_ndxerClients.Source.Replace(ndx, client); ActiveClientsQueue.IClientData clData = m_onlineClients.Get(clID); uint msgID = clData == null ? 1 : ++clData.LastClientMessageID; return(msg.CreateResponse(msgID, Message_t.Ok)); }
void PostCloseMessage() { Dbg.Log("Posting closing notification..."); var req = new Message(++m_clientLastMsgID, 0, Message_t.Close); string dlgFile = SettingsManager.GetClientDialogFilePath(m_clInfo.ClientID); DialogEngin.AppendHubDialog(dlgFile, m_clInfo.ClientID, req); try { new NetEngin(Program.NetworkSettings).Upload(SettingsManager.GetClientDialogURL(m_clInfo.ClientID), dlgFile); } catch (Exception ex) { Dbg.Log("PostCloseMessage: " + ex.Message); } }
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 ProcessRunningClients() { var deadClients = new List <uint>(); foreach (uint clID in m_onlineClients.ClientsID) { ActiveClientsQueue.IClientData clData = m_onlineClients.Get(clID); if (clData == null) { continue; } if (--clData.TimeToLive <= TTL_DIE) { deadClients.Add(clID); } else if (clData.TimeToLive <= 0) { AppContext.LogManager.LogSysActivity($"Envoi d'un message de synchronisation au client {ClientStrID(clID)}", true); var msg = new Message(++clData.LastSrvMessageID, 0, Message_t.Sync); //delegate status update to processdialog method DialogEngin.AppendSrvDialog(AppPaths.GetSrvDialogFilePath(clID), msg); AddUpload(Names.GetSrvDialogFile(clID)); } } foreach (uint id in deadClients) { AppContext.LogManager.LogSysActivity($"Client {ClientStrID(id)} présumé déconnecté", true); m_onlineClients.Remove(id); AppContext.LogManager.CloseLogger(id); ClientClosed?.Invoke(id); } foreach (uint clID in m_onlineClients.ClientsID) { AddDownload(Names.GetClientDialogFile(clID)); } }
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); } }
public Message ReceiveMessage(uint reqID) { string tmpFile = Path.GetTempFileName(); string src = SettingsManager.GetServerDialogURL(m_clInfo.ClientID); try { new NetEngin(Program.NetworkSettings).Download(tmpFile, src); ClientDialog clDlg = DialogEngin.ReadSrvDialog(tmpFile); Message msg = clDlg.Messages.SingleOrDefault(m => m.ReqID == reqID); return(msg); } catch (Exception ex) { Dbg.Log(ex.Message); } finally { File.Delete(tmpFile); } return(null); }
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); }
bool RegisterClient() { var busyDlg = new BusyDialog(); busyDlg.Message = "Initialisation..."; Action <Task <IEnumerable <ProfileInfo> > > onSuccess = t => busyDlg.Dispose(); Action <Task> onErr = t => { busyDlg.Dispose(); //System.Windows.Forms.MessageBox.Show(t.Exception.InnerException.Message , null); }; IEnumerable <ProfileInfo> profiles = null; var task = new Task <IEnumerable <ProfileInfo> >(() => profiles = Program.DialogManager.Profiles, TaskCreationOptions.LongRunning); task.OnSuccess(onSuccess); task.OnError(onErr); task.Start(); busyDlg.ShowDialog(); if (profiles == null || !profiles.Any()) { System.Windows.Forms.MessageBox.Show("Aucune réponse du serveur. Veuillez réessayer ultérieurement.", AppText.APP_NAME, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); Exit(); return(false); } ClientInfo clInfo; using (var dlg = new ProfileDialog(profiles)) { if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK) { Exit(); } clInfo = ClientInfo.CreateClient(dlg.SelectedProfile.ProfileID); clInfo.ContaclEMail = dlg.ContactEMail; clInfo.ContactName = dlg.Contact; clInfo.ContactPhone = dlg.ContactPhone; } using (var dlg = new ConnectionDialog(clInfo)) { dlg.ShowDialog(); if (!dlg.IsRegistered) { Exit(); return(false); } m_clInfo = Program.Settings.ClientInfo; DialogEngin.WriteHubDialog(SettingsManager.GetClientDialogFilePath(m_clInfo.ClientID), m_clInfo.ClientID, Enumerable.Empty <Message>()); } return(true); }
void ProcessDialogTimer() { if (!m_dialogTimer.IsDisposed) { m_dialogTimer.Stop(); } Dbg.Log("Processing dialog timer..."); string srvDlgURI = SettingsManager.GetServerDialogURL(m_clInfo.ClientID); string tmpFile = Path.GetTempFileName(); LogEngin.PushFlash("Interrogation du serveur..."); try { new NetEngin(Program.NetworkSettings).Download(tmpFile, srvDlgURI, true); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); LogEngin.PushFlash(ex.Message); m_dialogTimer.Start(); return; } try { ClientDialog clDlg = DialogEngin.ReadSrvDialog(tmpFile); if (m_clStatus != clDlg.ClientStatus) { switch (clDlg.ClientStatus) { case ClientStatus_t.Enabled: m_updateTimer.Start(true); break; case ClientStatus_t.Disabled: if (m_clStatus == ClientStatus_t.Enabled) { m_updateTimer.Stop(); } return; case ClientStatus_t.Banned: m_updateTimer.Stop(); foreach (IDBTable tbl in Program.TablesManager.Tables) { tbl.Clear(); } System.Windows.Forms.MessageBox.Show(AppText.ERR_BANNED, AppText.APP_NAME, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); Exit(); return; case ClientStatus_t.Reseted: ResetRegistration(); return; default: Dbg.Assert(false); break; } m_clStatus = clDlg.ClientStatus; } Dbg.Assert(m_clStatus == ClientStatus_t.Enabled); uint id = m_srvLastMsgID; var msgs = from msg in clDlg.Messages where msg.ID > id select msg; if (msgs.Any()) { m_srvLastMsgID = msgs.Max(m => m.ID); Action <Message> msgHandler; foreach (Message msg in msgs) { if (m_msgHandlersTable.TryGetValue(msg.MessageCode, out msgHandler)) { msgHandler.Invoke(msg); } } m_timeToLive = TTL_MAX; } if (m_needUpload) { string clFilePath = SettingsManager.GetClientDialogFilePath(m_clInfo.ClientID); new NetEngin(Program.NetworkSettings).Upload(SettingsManager.GetClientDialogURL(m_clInfo.ClientID), clFilePath, true); m_needUpload = false; } if (--m_timeToLive <= 0) { PostSyncMessage(); } if (!m_dialogTimer.IsDisposed) { m_dialogTimer.Start(); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); if (!m_dialogTimer.IsDisposed) { m_dialogTimer.Start(); } } }
Message ProcessSyncMessage(Message msg) { Dbg.Assert(msg.MessageCode == Message_t.Sync); var ms = new MemoryStream(msg.Data); var reader = new RawDataReader(ms, Encoding.UTF8); uint clID = reader.ReadUInt(); uint srvMsgID = reader.ReadUInt(); uint clMsgId = reader.ReadUInt(); AppContext.LogManager.LogSysActivity($"Reception d'un message de synchronisation du client {ClientStrID(clID)}", true); ActiveClientsQueue.IClientData clData = m_onlineClients.Get(clID); if (clData != null) { clData.TimeToLive = ActiveClientsQueue.InitTimeToLive; var resp = new Message(++clData.LastSrvMessageID, 0, Message_t.Null); DialogEngin.AppendSrvDialog(AppPaths.GetSrvDialogFilePath(clID), resp); AddUpload(Names.GetSrvDialogFile(clID)); //maj status var clStatus = m_ndxerClientsStatus.Get(clID) as ClientStatus; clStatus.LastSeen = DateTime.Now; ++clStatus.ReceivedMsgCount; m_ndxerClientsStatus.Source.Replace(m_ndxerClientsStatus.IndexOf(clID), clStatus); return(null); } var client = m_ndxerClients.Get(clID) as HubClient; if (client == null) { AppContext.LogManager.LogSysActivity("Réception d’une demande de synchronisation " + $"de la part d’un client inexistant ({ClientStrID(clID)}). Réinitialisation du client", true); //maj du fichier gov string srvDlgFile = AppPaths.GetSrvDialogFilePath(clID); //le client n'existe pas => son fichier gov n'existe pas var clDlg = new ClientDialog(clID, ClientStatus_t.Reseted, Enumerable.Empty <Message>()); DialogEngin.WriteSrvDialog(srvDlgFile, clDlg); AddUpload(Path.GetFileName(srvDlgFile)); return(null); } var status = m_ndxerClientsStatus.Get(clID) as ClientStatus; var respMsg = new Message(++srvMsgID, 0, Message_t.Null); var dlg = new ClientDialog(clID, status.Status, new Message[] { respMsg }); DialogEngin.WriteSrvDialog(AppPaths.GetSrvDialogFilePath(clID), dlg); AddUpload(Names.GetSrvDialogFile(clID)); if (status.Status == ClientStatus_t.Enabled) { ActiveClientsQueue.IClientData clientData = m_onlineClients.Add(clID); clientData.LastClientMessageID = clMsgId; clientData.LastSrvMessageID = srvMsgID; AppContext.LogManager.StartLogger(clID); } return(null); }
Message ProcessStartMessage(Message msg) { Dbg.Assert(msg.MessageCode == Message_t.Start); var reader = new RawDataReader(new MemoryStream(msg.Data), Encoding.UTF8); uint clID = reader.ReadUInt(); ClientEnvironment clEnv = ClientEnvironment.Load(reader); DateTime dtStart = reader.ReadTime(); var client = m_ndxerClients.Get(clID) as HubClient; if (client == null) { AppContext.LogManager.LogSysActivity("Réception d’une notification de démarrage " + $"de la part d’un client inexistant ({ClientStrID(clID)}). Réinitialisation du client", true); //maj du fichier gov string srvDlgFile = AppPaths.GetSrvDialogFilePath(clID); //le client n'existe pas => son fichier gov n'existe pas var clDlg = new ClientDialog(clID, ClientStatus_t.Reseted, Enumerable.Empty <Message>()); DialogEngin.WriteSrvDialog(srvDlgFile, clDlg); AddUpload(Path.GetFileName(srvDlgFile)); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Rejected, msg.Data)); } AppContext.LogManager.LogSysActivity("Réception d’une notification de démarrage " + $"de la part du client {ClientStrID(clID)}", true); //verifier le statut du client var clStatus = m_ndxerClientsStatus.Get(clID) as ClientStatus; if (clStatus.Status != ClientStatus_t.Enabled) { AppContext.LogManager.LogSysActivity($"Démmarage du Client { ClientStrID(clID)} non autorisé. Requête rejetée", true); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Rejected, msg.Data)); } //reset dlg files DialogEngin.WriteHubDialog(AppPaths.GetClientDilogFilePath(clID), clID, Enumerable.Empty <Message>()); DialogEngin.WriteSrvDialog(AppPaths.GetSrvDialogFilePath(clID), new ClientDialog(clID, clStatus.Status, Enumerable.Empty <Message>())); try { new NetEngin(AppContext.Settings.NetworkSettings).Upload(Urls.DialogDirURL, new string[] { AppPaths.GetClientDilogFilePath(clID), AppPaths.GetSrvDialogFilePath(clID) }); } catch (Exception ex) { AppContext.LogManager.LogSysError($"Traitement de la requête de démarrage du client {ClientStrID(clID)}: " + $"{ ex.Message}. demande ignorée, laisser le client reformuler la requête.", true); return(null); // let the cleint retry req. } AppContext.LogManager.LogSysActivity($"Client {ClientStrID(clID)} démarré le { dtStart.Date.ToShortDateString()} " + $"à { dtStart.ToLongTimeString()}", true); //verifier si l'env du client a changé UpdateClientEnvironment(clID, clEnv); //ajouter client dans running liste m_onlineClients.Add(clID, dtStart); AppContext.LogManager.StartLogger(clID); AppContext.LogManager.LogClientActivity(clID, "Démarrage"); //maj du last seen clStatus.LastSeen = dtStart; m_ndxerClientsStatus.Source.Replace(m_ndxerClientsStatus.IndexOf(clID), clStatus); ClientStarted?.Invoke(clID); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Ok, msg.Data)); }
Message ProcessNewConnectionReq(Message msg) { Dbg.Assert(msg.MessageCode == Message_t.NewConnection); //TextLogger.Info("Réception d’une nouvelle requête d’inscription."); var ms = new MemoryStream(msg.Data); var reader = new RawDataReader(ms, Encoding.UTF8); ClientInfo clInfo = ClientInfo.LoadClientInfo(reader); ClientEnvironment clEnv = ClientEnvironment.Load(reader); byte[] data = BitConverter.GetBytes(clInfo.ClientID); var profile = m_ndxerProfiles.Get(clInfo.ProfileID) as UserProfile; string reqLog = $"Réception d'une demande d’inscription émanant de {clInfo.ContactName}" + $"(ID = {ClientStrID(clInfo.ClientID)}) pour " + (profile == null ? "un profil inexistant." : $"le profil {profile.Name}."); AppContext.LogManager.LogSysActivity(reqLog, true); //verifier que le profil existe if (profile == null) { AppContext.LogManager.LogSysActivity("Lancement de la procédure d’actualisation " + "de la liste des profils sur le serveur", true); ProcessProfilesChange(); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.InvalidProfile, data)); } //verifier que ClientID n'existe pas var clSameID = m_ndxerClients.Get(clInfo.ClientID) as HubClient; if (clSameID != null) { AppContext.LogManager.LogSysActivity("Collision d’identifiants: " + $"un client portant le même ID est déjà enregistré ({clSameID.ContactName}). " + "Exiger au client de reformuler son inscription avec un nouvel ID", true); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.InvalidID, data)); } //verifier que le profile est en mode auto ManagementMode_t prfMgmntMode = GetProfileManagementMode(clInfo.ProfileID); if (prfMgmntMode == ManagementMode_t.Manual) { AppContext.LogManager.LogSysActivity("Profil en gestion manuelle, inscription rejetée.", true); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Rejected, data)); } TextLogger.Info("Profil en gestion automatique."); TextLogger.Info("Enregistrement du client..."); //desactiver l'ancien client actif si il existe var oldClient = GetProfileEnabledClient(clInfo.ProfileID); if (oldClient != null) { if (IsClientRunning(oldClient.ID)) { //rejeter l'inscription AppContext.LogManager.LogSysActivity($"Un client pour le profil {profile.Name} est déjà en cours d’exécution. " + "Inscription rejetée", true); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Rejected, data)); } AppContext.LogManager.LogSysActivity($"Désactivation du client {ClientStrID(oldClient.ID)}", true); //maj la table des status clients var oldClStatus = m_ndxerClientsStatus.Get(oldClient.ID) as ClientStatus; oldClStatus.Status = ClientStatus_t.Disabled; int ndx = m_ndxerClientsStatus.IndexOf(oldClStatus.ID); m_ndxerClientsStatus.Source.Replace(ndx, oldClStatus); //maj des fichiers de dialogue de old client string filePath = AppPaths.GetSrvDialogFilePath(oldClient.ID); ClientDialog clDlg = new ClientDialog(oldClient.ID, ClientStatus_t.Disabled, Enumerable.Empty <Message>()); DialogEngin.WriteSrvDialog(filePath, clDlg); AddUpload(Names.GetSrvDialogFile(oldClient.ID)); } //creer le fichier dialogue string srvDlgPath = AppPaths.GetSrvDialogFilePath(clInfo.ClientID); DialogEngin.WriteSrvDialog(srvDlgPath, new ClientDialog(clInfo.ClientID, ClientStatus_t.Enabled, Enumerable.Empty <Message>())); DialogEngin.WriteHubDialog(AppPaths.GetClientDilogFilePath(clInfo.ClientID), clInfo.ClientID, Enumerable.Empty <Message>()); try { new NetEngin(AppContext.Settings.NetworkSettings).Upload(Urls.DialogDirURL, new string[] { AppPaths.GetClientDilogFilePath(clInfo.ClientID), AppPaths.GetSrvDialogFilePath(clInfo.ClientID) }); } catch (Exception ex) { AppContext.LogManager.LogSysError($"Traitement de la requête d'inscription du client {ClientStrID(clInfo.ClientID)}: " + $"{ ex.Message}. demande ignorée, laisser le client reformuler la requête", true); return(null); // let the cleint retry req. } //maj la table des clients var hClient = new HubClient(clInfo.ClientID, clInfo.ProfileID) { ContaclEMail = clInfo.ContaclEMail, ContactName = clInfo.ContactName, ContactPhone = clInfo.ContactPhone, }; m_ndxerClients.Source.Insert(hClient); //maj du status client var clStatus = new ClientStatus(clInfo.ClientID, ClientStatus_t.Enabled); m_ndxerClientsStatus.Source.Insert(clStatus); //maj du client env UpdateClientEnvironment(clInfo.ClientID, clEnv); //maj du dict des clients actifs m_onlineClients.Add(clInfo.ClientID); AppContext.LogManager.StartLogger(clInfo.ClientID); AppContext.LogManager.LogClientActivity(clInfo.ClientID, "Inscription"); ClientStarted?.Invoke(clInfo.ClientID); AppContext.LogManager.LogSysActivity($"Inscription du client {clInfo.ClientID} terminée", true); TextLogger.Info("Inscription réussie. :-)"); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Ok, data)); }
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); } }
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..."); } } }
public void SetClientStatus(HubClient client, ClientStatus_t status) { //basculer le mode de gestion des profil vers manuel //SetProfileManagementMode(client.ProfileID , ManagementMode_t.Manual); //desactiver le client HubClient oldClient = GetProfileEnabledClient(client.ProfileID); if (status == ClientStatus_t.Enabled && oldClient != null && oldClient.ID != client.ID) { AppContext.LogManager.LogSysActivity($"Désactivation du client {ClientStrID(oldClient.ID)}", true); //maj la table des status clients var oldClStatus = m_ndxerClientsStatus.Get(oldClient.ID) as ClientStatus; int ndx = m_ndxerClientsStatus.IndexOf(oldClient.ID); oldClStatus.Status = ClientStatus_t.Disabled; m_ndxerClientsStatus.Source.Replace(ndx, oldClStatus); string oldClFilePath = AppPaths.GetSrvDialogFilePath(oldClient.ID); try { ClientDialog oldClDlg = DialogEngin.ReadSrvDialog(oldClFilePath); oldClDlg.ClientStatus = ClientStatus_t.Disabled; DialogEngin.WriteSrvDialog(oldClFilePath, oldClDlg); } catch (Exception ex) { AppContext.LogManager.LogSysError($"Lecture du fichier dialogue du client {ClientStrID(oldClient.ID)}" + ex.Message); DialogEngin.WriteSrvDialog(oldClFilePath, new ClientDialog(oldClient.ID, ClientStatus_t.Disabled, Enumerable.Empty <Message>())); } finally { AddUpload(Names.GetSrvDialogFile(oldClient.ID)); } } //maj la table des statuts clients int ndxStatus = m_ndxerClientsStatus.IndexOf(client.ID); var clStatus = m_ndxerClientsStatus.Get(client.ID) as ClientStatus; clStatus.Status = status; m_ndxerClientsStatus.Source.Replace(ndxStatus, clStatus); string filePath = AppPaths.GetSrvDialogFilePath(client.ID); try { ClientDialog clDlg = DialogEngin.ReadSrvDialog(filePath); clDlg.ClientStatus = status; DialogEngin.WriteSrvDialog(filePath, clDlg); } catch (Exception ex) { AppContext.LogManager.LogSysError($"Lecture du fichier dialogue du client {ClientStrID(client.ID)}" + ex.Message); DialogEngin.WriteSrvDialog(filePath, new ClientDialog(client.ID, status, Enumerable.Empty <Message>())); } finally { AddUpload(Names.GetSrvDialogFile(client.ID)); } }
Message ProcessResumeConnectionReq(Message msg) { Dbg.Assert(msg.MessageCode == Message_t.Resume); //verfier que le client existe uint clID = BitConverter.ToUInt32(msg.Data, 0); var client = m_ndxerClients.Get(clID) as HubClient; if (client == null) { AppContext.LogManager.LogSysActivity("Réception d’une requête de reprise émanant d’un client non enregistré. Réinitialisation du client.", true); //maj du fichier gov string srvDlgFile = AppPaths.GetSrvDialogFilePath(clID); //le client n'existe pas => son fichier gov n'existe pas var clDlg = new ClientDialog(clID, ClientStatus_t.Reseted, Enumerable.Empty <Message>()); DialogEngin.WriteSrvDialog(srvDlgFile, clDlg); AddUpload(Path.GetFileName(srvDlgFile)); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Rejected, BitConverter.GetBytes(clID))); } var prf = m_ndxerProfiles.Get(client.ProfileID) as UserProfile; AppContext.LogManager.LogSysActivity($"Requête de reprise émanant de {ClientStrID(clID)} pour le profil " + $"{prf.Name}, inscrit le {client.CreationTime}", true); //verifier que le profil est en mode auto if ((m_ndxerProfilesMgmnt.Get(prf.ID) as ProfileManagementMode).ManagementMode == ManagementMode_t.Manual) { AppContext.LogManager.LogSysActivity($"Le profil {prf.Name} est en gestion manuelle. Requête de reprise rejetée", true); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Rejected, msg.Data)); } //appliquer l'alog. de selction du client // si date inscription client actif <= date inscription client en pause // rejeter le demande //sinon // bannir le client actif // acvtiver le client en pause var curClient = GetProfileEnabledClient(prf.ID) as HubClient; if (curClient != null) { if (curClient.CreationTime <= client.CreationTime) { AppContext.LogManager.LogSysActivity($"Le client actif {ClientStrID(curClient.ID)} inscrit le " + $"{curClient.CreationTime}. Le client actif est plus ancien. Requête de reprise rejetée", true); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Rejected, msg.Data)); } //bannissemnt du client actif AppContext.LogManager.LogSysActivity($"Le client actif {ClientStrID(curClient.ID)} inscrit le " + $"{curClient.CreationTime}. Le client demandeur de reprise est plus ancien. Bannissement du client actif", true); //maj de la table des statuts var curClStatus = m_ndxerClientsStatus.Get(curClient.ID) as ClientStatus; curClStatus.Status = ClientStatus_t.Banned; int ndxCurClient = m_ndxerClientsStatus.IndexOf(curClStatus.ID); m_ndxerClientsStatus.Source.Replace(ndxCurClient, curClStatus); //maj du fichier distant g string curClFilePath = AppPaths.GetSrvDialogFilePath(curClient.ID); var curClDlg = new ClientDialog(curClient.ID, ClientStatus_t.Banned, Enumerable.Empty <Message>()); DialogEngin.WriteSrvDialog(curClFilePath, curClDlg); AddUpload(Names.GetSrvDialogFile(curClient.ID)); } //activation du client demandeur //reset dlg files DialogEngin.WriteHubDialog(AppPaths.GetClientDilogFilePath(clID), clID, Enumerable.Empty <Message>()); DialogEngin.WriteSrvDialog(AppPaths.GetSrvDialogFilePath(clID), new ClientDialog(clID, ClientStatus_t.Enabled, Enumerable.Empty <Message>())); try { new NetEngin(AppContext.Settings.NetworkSettings).Upload(Urls.DialogDirURL, new string[] { AppPaths.GetClientDilogFilePath(clID), AppPaths.GetSrvDialogFilePath(clID) }); } catch (Exception ex) { AppContext.LogManager.LogSysError($"Traitement de la requête de reprise du client {ClientStrID(clID)}: " + $"{ ex.Message}. demande ignorée, laisser le client reformuler la requête", true); return(null); // let the cleint retry req. } //maj de la table des statuts var clStatus = m_ndxerClientsStatus.Get(clID) as ClientStatus; clStatus.Status = ClientStatus_t.Enabled; int ndxClient = m_ndxerClientsStatus.IndexOf(clID); m_ndxerClientsStatus.Source.Replace(ndxClient, clStatus); //maj du dic des clients actifs m_onlineClients.Add(clID); AppContext.LogManager.StartLogger(clID); AppContext.LogManager.LogClientActivity(clID, "Reprise."); ClientStarted?.Invoke(clID); AppContext.LogManager.LogSysActivity($"Demande de reprise du client {ClientStrID(clID)} acceptée", true); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Ok, msg.Data)); }
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(); }