Exemple #1
0
        protected override void When()
        {
            _okResponse = CreateBusyHereResponse();
            var c = new SipContextBuilder().WithResponse(_okResponse).Build();

            ClientDialog.ProcessResponse(new SipResponseEvent(c));
        }
Exemple #2
0
 protected override void When()
 {
     /*force it to go into early state*/
     ReceivedResponse = CreateRingingResponse();
     ClientDialog.SetLastResponse(ReceivedResponse);
     ClientDialog.State.Should().Be(DialogState.Early); /*required assertion*/
 }
        protected override void When()
        {
            var cb     = new SipContextBuilder().WithResponse(_okResponse).Build();
            var rEvent = new SipResponseEvent(cb);

            ClientDialog.ProcessResponse(rEvent);
        }
        private async void OnLoad(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            // Try to get Client Id from the Password Vault - if no
            // entry found put up a dialog box to request..
            var appCredentials = GetTokenFromVault(ClientIdResourceName);

            if (string.IsNullOrEmpty(appCredentials.Item1))
            {
                // Put up a UI prompting for the app IDs...
                var cdr = await ClientDialog.ShowAsync();

                if (cdr == ContentDialogResult.Primary)
                {
                    // Wipe out all other cached credentials
                    RemoveTokensFromVault();
                    FileList = new List <ItemViewModel>();

                    ClientId = ClientDialog.ClientId;
                    if (string.IsNullOrEmpty(ClientId))
                    {
                        return;
                    }
                    AddTokenToVault(ClientIdResourceName, ClientId, UserName);
                }
            }
            else
            {
                ClientId = appCredentials.Item1;
            }
        }
        protected override void When()
        {
            var request = ClientDialog.CreateRequest(SipMethods.Bye);

            _txMock = new Mock <ISipClientTransaction>();
            _txMock.Setup((p) => p.Request).Returns(request);
            ClientDialog.SendRequest(_txMock.Object);
        }
Exemple #6
0
 protected override void When()
 {
     /*force it to go into state*/
     ReceivedResponse = CreateOkResponse();
     ClientDialog.SetLastResponse(CreateRingingResponse());
     ClientDialog.SetLastResponse(CreateBusyHereResponse());
     ClientDialog.State.Should().Be(DialogState.Terminated); /*required assertion*/
 }
Exemple #7
0
        public void Expect_the_Id_of_the_dialog_to_be_CallId_FromTag_ToTag_concatenated()
        {
            string expectedId = InvitingRequest.CallId.Value;

            expectedId += ":" + InvitingRequest.From.Tag;
            expectedId += ":" + ReceivedResponse.To.Tag;
            ClientDialog.GetId().Should().Be(expectedId);
        }
Exemple #8
0
        protected override void GivenOverride()
        {
            /*force it to go into early state*/
            var ringingResponse = CreateRingingResponse();
            var c = new SipResponseEventBuilder().WithResponse(ringingResponse).WithClientTx(InviteCtx.Object).Build();

            ClientDialog.ProcessResponse(c);
            ClientDialog.State.Should().Be(DialogState.Early); /*required assertion*/
        }
 protected override void GivenOverride()
 {
     /*force it to go into confirmed state*/
     ReceivedResponse = CreateOkResponse();
     ClientDialog.SetLastResponse(CreateRingingResponse());
     ClientDialog.SetLastResponse(CreateOkResponse());
     ClientDialog.State.Should().Be(DialogState.Confirmed); /*required assertion*/
     _beforeSentSeqNr = ClientDialog.LocalSequenceNr;
 }
        protected override void GivenOverride()
        {
            /*force it to go into confirmed state*/
            _okResponse = CreateOkResponse();
            _rer        = new SipResponseEventBuilder().WithResponse(CreateRingingResponse()).WithClientTx(InviteCtx.Object).Build();
            _reo        = new SipResponseEventBuilder().WithResponse(_okResponse).WithClientTx(InviteCtx.Object).Build();
            ClientDialog.ProcessResponse(_rer);
            ClientDialog.ProcessResponse(_reo);
            ClientDialog.State.Should().Be(DialogState.Confirmed); /*required assertion*/

            _ackRequest = ClientDialog.CreateAck();
            ClientDialog.SendAck(_ackRequest);  /*sent an ack*/
            _beforeSentSeqNr = ClientDialog.LocalSequenceNr;
        }
        private async void SettingsClick(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            var cdr = await ClientDialog.ShowAsync();

            if (cdr == ContentDialogResult.Primary)
            {
                ClientId = ClientDialog.ClientId;
                if (string.IsNullOrEmpty(ClientId))
                {
                    return;
                }
                AddTokenToVault(ClientIdResourceName, ClientId, UserName);
            }
        }
        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));
        }
Exemple #13
0
        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);
        }
        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));
        }
        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));
        }
Exemple #16
0
        protected override void When()
        {
            var ringingResponse = CreateRingingResponse();

            ClientDialog.SetLastResponse(ringingResponse);
        }
 void IClientDialogViewModel.CDialog(ClientDialog clientDialog)
 {
     CDialog = clientDialog;
 }
Exemple #18
0
 public void Expect_the_dialog_GetId_to_be_empty()
 {
     ClientDialog.GetId().Should().BeEmpty();
 }
Exemple #19
0
 public void Expect_the_dialog_to_be_removed_from_table()
 {
     DialogTable.ContainsKey(ClientDialog.GetId()).Should().BeFalse();
 }
Exemple #20
0
        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));
            }
        }
Exemple #21
0
        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();
        }
Exemple #22
0
        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 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 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);
        }
        public void Execute(object parameter)
        {
            Log.Info("Employee saved his/hers new password.");
            string oldPassword = ChangePasswordViewModel.Instance.OldPassword();
            string newPassword = ChangePasswordViewModel.Instance.NewPassword();

            string username = ClientDialogViewModel.Instance.LogInUser().Username;

            Log.Debug("proxy poziv - ChangePassword");
            bool ret = ClientProxy.Instance.ChangePassword(username, oldPassword, newPassword);

            Log.Info("Successfully changed password");

            if (ret)
            {
                ClientDialogViewModel.Instance.LogInUser().Password = newPassword;
            }

            //omogucavanje normalnog prikaza nakon promene sifre
            Log.Debug("proxy poziv - GetEmployee");
            Employee signedUser = ClientProxy.Instance.GetEmployee(username, newPassword);

            if (signedUser == null)
            {
                Log.Warn("User with that username doesn't exists");
                return;
            }

            Log.Info("Successfully returned employee");
            signedUser.PasswordUpadateDate = DateTime.Today;

            Log.Debug("proxy poziv - UpdateEmployee");
            ClientProxy.Instance.UpdateEmployee(signedUser);
            Log.Info("Successfully updated employee");
            if (signedUser.Position.ToString().Equals("PO"))
            {
                ClientDialog cd = ClientDialogViewModel.Instance.CDialog();
                cd.addEmployBtn.Visibility   = Visibility.Collapsed;
                cd.sendReqCompBtn.Visibility = Visibility.Collapsed;
                cd.sendReqProjBtn.Visibility = Visibility.Collapsed;
                cd.editPosBtn.Visibility     = Visibility.Collapsed;
                cd.showProjBtn.IsEnabled     = true;
                cd.showEmployBtn.IsEnabled   = true;
                cd.editYDBtn.IsEnabled       = true;
                cd.timeTableBtn.IsEnabled    = true;
                cd.passChngBtn.IsEnabled     = true;
                cd.createProjBtn.IsEnabled   = true;
                cd.defUSBtn.IsEnabled        = true;
                cd.showCompBtn.IsEnabled     = true;
                cd.Show();
            }
            else if (signedUser.Position.ToString().Equals("HR"))
            {
                ClientDialog cd = ClientDialogViewModel.Instance.CDialog();
                cd.showProjBtn.Visibility    = Visibility.Collapsed;
                cd.sendReqCompBtn.Visibility = Visibility.Collapsed;
                cd.sendReqProjBtn.Visibility = Visibility.Collapsed;
                cd.defUSBtn.Visibility       = Visibility.Collapsed;
                cd.createProjBtn.Visibility  = Visibility.Collapsed;
                cd.showEmployBtn.IsEnabled   = true;
                cd.addEmployBtn.IsEnabled    = true;
                cd.editYDBtn.IsEnabled       = true;
                cd.timeTableBtn.IsEnabled    = true;
                cd.passChngBtn.IsEnabled     = true;
                cd.showCompBtn.IsEnabled     = true;
                cd.editPosBtn.IsEnabled      = true;
                cd.Show();
            }
            else if (signedUser.Position.ToString().Equals("CEO"))
            {
                ClientDialog cd = ClientDialogViewModel.Instance.CDialog();
                cd.defUSBtn.Visibility      = Visibility.Collapsed;
                cd.createProjBtn.Visibility = Visibility.Collapsed;
                cd.showProjBtn.IsEnabled    = true;
                cd.showEmployBtn.IsEnabled  = true;
                cd.addEmployBtn.IsEnabled   = true;
                cd.editYDBtn.IsEnabled      = true;
                cd.timeTableBtn.IsEnabled   = true;
                cd.passChngBtn.IsEnabled    = true;
                cd.sendReqCompBtn.IsEnabled = true;
                cd.sendReqProjBtn.IsEnabled = true;
                cd.showCompBtn.IsEnabled    = true;
                cd.editPosBtn.IsEnabled     = true;
                cd.Show();
            }
            else if (signedUser.Position.ToString().Equals("SM"))
            {
                ClientDialog cd = ClientDialogViewModel.Instance.CDialog();
                cd.sendReqCompBtn.Visibility = Visibility.Collapsed;
                cd.sendReqProjBtn.Visibility = Visibility.Collapsed;
                cd.addEmployBtn.Visibility   = Visibility.Collapsed;
                cd.defUSBtn.Visibility       = Visibility.Collapsed;
                cd.createProjBtn.Visibility  = Visibility.Collapsed;
                cd.editPosBtn.Visibility     = Visibility.Collapsed;
                cd.showProjBtn.IsEnabled     = true;
                cd.showEmployBtn.IsEnabled   = true;
                cd.editYDBtn.IsEnabled       = true;
                cd.timeTableBtn.IsEnabled    = true;
                cd.passChngBtn.IsEnabled     = true;
                cd.showCompBtn.IsEnabled     = true;
                cd.Show();
            }
        }
Exemple #26
0
 protected override void When()
 {
     _okResponse = CreateOkResponse();
     ClientDialog.SetLastResponse(_okResponse);
 }
        public void Execute(object parameter)
        {
            Log.Info("Employee started logging in.");
            string username = ClientDialogViewModel.Instance.LogInUser().Username;
            string password = ClientDialogViewModel.Instance.LogInUser().Password;

            if (username.Trim().Equals("") || username.Equals(null) ||
                password.Trim().Equals("") || password.Equals(null))
            {
                ClientDialogViewModel.Instance.ErrorMessage("Niste popunili sva polja!");
            }
            else
            {
                Log.Debug("proxy poziv - GetEmployee ");
                Employee outValue = ClientProxy.Instance.GetEmployee(username, password);
                Log.Info("successfully returned employee.");

                if (outValue != null)
                {
                    Log.Debug("proxy poziv - EmployeeLogIn ");
                    ClientProxy.Instance.EmployeeLogIn(username);
                    Log.Info("successfully logged in employee.");
                    //IContextChannel cc = ClientProxy.Instance as IContextChannel;
                    //Console.WriteLine(cc.State);
                    //cc.Faulted += Cc_Faulted;
                    //cc.Closing += Cc_Closing;
                    //cc.Closed += Cc_Closed;

                    if (outValue.Position.ToString().Equals("PO"))
                    {
                        if (outValue.PasswordUpadateDate.AddMonths(6) < DateTime.Now)
                        {
                            Application.Current.MainWindow.Hide();
                            ClientDialog cd = new ClientDialog();
                            cd.addEmployBtn.Visibility   = Visibility.Collapsed;
                            cd.sendReqCompBtn.Visibility = Visibility.Collapsed;
                            cd.sendReqProjBtn.Visibility = Visibility.Collapsed;
                            cd.editPosBtn.Visibility     = Visibility.Collapsed;
                            cd.markProjBtn.IsEnabled     = false;
                            cd.showProjBtn.IsEnabled     = false;
                            cd.showEmployBtn.IsEnabled   = false;
                            cd.editYDBtn.IsEnabled       = false;
                            cd.timeTableBtn.IsEnabled    = false;
                            cd.passChngBtn.IsEnabled     = true;
                            cd.createProjBtn.IsEnabled   = false;
                            cd.defUSBtn.IsEnabled        = false;
                            cd.showCompBtn.IsEnabled     = false;
                            cd.Show();
                        }
                        else
                        {
                            //((Window)parameters[2]).Hide();
                            Application.Current.MainWindow.Hide();
                            ClientDialog cd = new ClientDialog();
                            cd.addEmployBtn.Visibility   = Visibility.Collapsed;
                            cd.sendReqCompBtn.Visibility = Visibility.Collapsed;
                            cd.sendReqProjBtn.Visibility = Visibility.Collapsed;
                            cd.editPosBtn.Visibility     = Visibility.Collapsed;
                            cd.markProjBtn.IsEnabled     = true;
                            cd.showProjBtn.IsEnabled     = true;
                            cd.showEmployBtn.IsEnabled   = true;
                            cd.editYDBtn.IsEnabled       = true;
                            cd.timeTableBtn.IsEnabled    = true;
                            cd.passChngBtn.IsEnabled     = true;
                            cd.createProjBtn.IsEnabled   = true;
                            cd.defUSBtn.IsEnabled        = true;
                            cd.showCompBtn.IsEnabled     = true;
                            cd.Show();
                        }
                    }
                    else if (outValue.Position.ToString().Equals("HR"))
                    {
                        if (outValue.PasswordUpadateDate.AddMonths(6) < DateTime.Now)
                        {
                            //((Window)parameters[2]).Hide();
                            Application.Current.MainWindow.Hide();
                            ClientDialog cd = new ClientDialog();
                            cd.showProjBtn.Visibility    = Visibility.Collapsed;
                            cd.sendReqCompBtn.Visibility = Visibility.Collapsed;
                            cd.sendReqProjBtn.Visibility = Visibility.Collapsed;
                            cd.defUSBtn.Visibility       = Visibility.Collapsed;
                            cd.createProjBtn.Visibility  = Visibility.Collapsed;
                            cd.markProjBtn.Visibility    = Visibility.Collapsed;
                            cd.showEmployBtn.IsEnabled   = false;
                            cd.addEmployBtn.IsEnabled    = false;
                            cd.editYDBtn.IsEnabled       = false;
                            cd.timeTableBtn.IsEnabled    = false;
                            cd.passChngBtn.IsEnabled     = true;
                            cd.showCompBtn.IsEnabled     = false;
                            cd.editPosBtn.IsEnabled      = false;
                            cd.Show();
                        }
                        else
                        {
                            //((Window)parameters[2]).Hide();
                            Application.Current.MainWindow.Hide();
                            ClientDialog cd = new ClientDialog();
                            cd.showProjBtn.Visibility    = Visibility.Collapsed;
                            cd.sendReqCompBtn.Visibility = Visibility.Collapsed;
                            cd.sendReqProjBtn.Visibility = Visibility.Collapsed;
                            cd.defUSBtn.Visibility       = Visibility.Collapsed;
                            cd.createProjBtn.Visibility  = Visibility.Collapsed;
                            cd.markProjBtn.Visibility    = Visibility.Collapsed;
                            cd.showEmployBtn.IsEnabled   = true;
                            cd.addEmployBtn.IsEnabled    = true;
                            cd.editYDBtn.IsEnabled       = true;
                            cd.timeTableBtn.IsEnabled    = true;
                            cd.passChngBtn.IsEnabled     = true;
                            cd.showCompBtn.IsEnabled     = true;
                            cd.editPosBtn.IsEnabled      = true;
                            cd.Show();
                        }
                    }
                    else if (outValue.Position.ToString().Equals("CEO"))
                    {
                        if (outValue.PasswordUpadateDate.AddMonths(6) < DateTime.Now)
                        {
                            //((Window)parameters[2]).Hide();
                            Application.Current.MainWindow.Hide();
                            ClientDialog cd = new ClientDialog();
                            cd.defUSBtn.Visibility      = Visibility.Collapsed;
                            cd.createProjBtn.Visibility = Visibility.Collapsed;
                            cd.markProjBtn.Visibility   = Visibility.Collapsed;
                            cd.showProjBtn.IsEnabled    = false;
                            cd.showEmployBtn.IsEnabled  = false;
                            cd.addEmployBtn.IsEnabled   = false;
                            cd.editYDBtn.IsEnabled      = false;
                            cd.timeTableBtn.IsEnabled   = false;
                            cd.passChngBtn.IsEnabled    = true;
                            cd.sendReqCompBtn.IsEnabled = false;
                            cd.sendReqProjBtn.IsEnabled = false;
                            cd.showCompBtn.IsEnabled    = false;
                            cd.editPosBtn.IsEnabled     = false;
                            cd.Show();
                        }
                        else
                        {
                            //((Window)parameters[2]).Hide();
                            Application.Current.MainWindow.Hide();
                            ClientDialog cd = new ClientDialog();
                            cd.defUSBtn.Visibility      = Visibility.Collapsed;
                            cd.createProjBtn.Visibility = Visibility.Collapsed;
                            cd.markProjBtn.Visibility   = Visibility.Collapsed;
                            cd.showProjBtn.IsEnabled    = true;
                            cd.showEmployBtn.IsEnabled  = true;
                            cd.addEmployBtn.IsEnabled   = true;
                            cd.editYDBtn.IsEnabled      = true;
                            cd.timeTableBtn.IsEnabled   = true;
                            cd.passChngBtn.IsEnabled    = true;
                            cd.sendReqCompBtn.IsEnabled = true;
                            cd.sendReqProjBtn.IsEnabled = true;
                            cd.showCompBtn.IsEnabled    = true;
                            cd.editPosBtn.IsEnabled     = true;
                            cd.Show();
                        }
                    }
                    else if (outValue.Position.ToString().Equals("SM"))
                    {
                        if (outValue.PasswordUpadateDate.AddMonths(6) < DateTime.Now)
                        {
                            //((Window)parameters[2]).Hide();
                            Application.Current.MainWindow.Hide();
                            ClientDialog cd = new ClientDialog();
                            cd.sendReqCompBtn.Visibility = Visibility.Collapsed;
                            cd.sendReqProjBtn.Visibility = Visibility.Collapsed;
                            cd.addEmployBtn.Visibility   = Visibility.Collapsed;
                            cd.defUSBtn.Visibility       = Visibility.Collapsed;
                            cd.createProjBtn.Visibility  = Visibility.Collapsed;
                            cd.editPosBtn.Visibility     = Visibility.Collapsed;
                            cd.markProjBtn.Visibility    = Visibility.Collapsed;
                            cd.showProjBtn.IsEnabled     = false;
                            cd.showEmployBtn.IsEnabled   = false;
                            cd.editYDBtn.IsEnabled       = false;
                            cd.timeTableBtn.IsEnabled    = false;
                            cd.passChngBtn.IsEnabled     = true;
                            cd.showCompBtn.IsEnabled     = false;
                            cd.Show();
                        }
                        else
                        {
                            //((Window)parameters[2]).Hide();
                            Application.Current.MainWindow.Hide();
                            ClientDialog cd = new ClientDialog();
                            cd.sendReqCompBtn.Visibility = Visibility.Collapsed;
                            cd.sendReqProjBtn.Visibility = Visibility.Collapsed;
                            cd.addEmployBtn.Visibility   = Visibility.Collapsed;
                            cd.defUSBtn.Visibility       = Visibility.Collapsed;
                            cd.createProjBtn.Visibility  = Visibility.Collapsed;
                            cd.editPosBtn.Visibility     = Visibility.Collapsed;
                            cd.markProjBtn.Visibility    = Visibility.Collapsed;
                            cd.showProjBtn.IsEnabled     = true;
                            cd.showEmployBtn.IsEnabled   = true;
                            cd.editYDBtn.IsEnabled       = true;
                            cd.timeTableBtn.IsEnabled    = true;
                            cd.passChngBtn.IsEnabled     = true;
                            cd.showCompBtn.IsEnabled     = true;
                            cd.Show();
                        }
                    }
                    else
                    {
                        Log.Error("Uneli ste nevalidne podatke. Pokušajte ponovo!");
                    }
                }
                else
                {
                    ClientDialogViewModel.Instance.ErrorMessage("Uneli ste nevalidne podatke. Pokušajte ponovo!");
                    Log.Error(ClientDialogViewModel.Instance.LogInUser().Username.ToString());
                }
            }
        }
Exemple #28
0
        public MainViewModel(IClientRepository clientsRepo, IBuildingRepository buildingRepo, IContractRepository contractRepo)
        {
            // передача значений полю от переданного объекта клиенты
            this.clientsRepo  = clientsRepo;
            this.buildingRepo = buildingRepo;
            this.contractRepo = contractRepo;
            // заполенение свойства элементами дерева из БД
            ListClient   = new ObservableCollection <Client>(this.clientsRepo.GetAll());
            DayOfTheWeek = DateTime.Now.DayOfWeek.ToString();
            DispatcherTimer t = new DispatcherTimer(new TimeSpan(0, 0, 0, 0, 50), DispatcherPriority.Background, t_Tick, Dispatcher.CurrentDispatcher); t.IsEnabled = true;

            //установка выбранного объекта дерева в свойство
            SetSelectedItemCommand = new RelayCommand <object>(item =>
            {
                if (item is Client)
                {
                    SelectedClient     = item as Client;
                    SelectedBuilding   = null;
                    SelectedContract   = null;
                    SelectedName       = SelectedClient.Organization;
                    DynamicUserControl = new UserControlClients(SelectedClient);
                    ChartsUserControl  = new UserControlDiagram();
                    SelectedObject     = 1;
                    ParentClient       = null;
                    ParentContract     = null;
                }
                else if (item is Contract)
                {
                    SelectedContract   = item as Contract;
                    SelectedClient     = null;
                    SelectedBuilding   = null;
                    SelectedName       = SelectedContract.ContractNumber;
                    DynamicUserControl = new UserControlContracts(SelectedContract);
                    ChartsUserControl  = new UserControlDiagram(SelectedContract);
                    SelectedObject     = 2;
                    ParentClient       = ListClient.First(clnt => clnt.ClientID == SelectedContract.ClientID);
                    ParentContract     = null;
                }
                else if (item is Building)
                {
                    SelectedBuilding   = item as Building;
                    SelectedContract   = null;
                    SelectedClient     = null;
                    SelectedName       = SelectedBuilding.NameOfTheObject;
                    DynamicUserControl = new UserControlBuildings(SelectedBuilding);
                    ChartsUserControl  = new UserControlDiagram();
                    SelectedObject     = 3;
                    ParentContract     = contractRepo.GetContractById(SelectedBuilding);                                          //получили родительский контракт из БД
                    ParentClient       = ListClient.First(client => client.ClientID == ParentContract.ClientID);                  //получили родительского клиента из ListClient
                    ParentContract     = ParentClient.Contract.First(ctr => ctr.ContractNumber == ParentContract.ContractNumber); //переписали контракт на контракт из ListClient
                }
            });

            #region commands
            // удалить объект
            Action DeleteBuildingAction = () =>
            {
                Building bld = SelectedBuilding;
                buildingRepo.Delete(bld);

                ParentContract.Building.Remove(bld);
            };
            actions.Add(DeleteBuildingAction);

            DeleteBuildingCmd = new RelayCommand(DeleteBuildingAction, () => SelectedObject == 3);
            // редактировать объект
            UpdateBuildingCmd = new RelayCommand(() =>
            {
                if (SelectedBuilding != null)
                {
                    BuildingDialog buildDlg = new BuildingDialog(SelectedBuilding);
                    if (buildDlg.ShowDialog() == true)
                    {
                        buildingRepo.Update(buildDlg.NewBuilding);
                        SelectedBuilding = buildDlg.NewBuilding;
                    }
                }
            }, () => SelectedObject == 3);
            // добавить объект
            AddBuildingCmd = new RelayCommand(() =>
            {
                Building bld;
                BuildingDialog buildDlg = new BuildingDialog(SelectedContract);
                if (buildDlg.ShowDialog() == true)
                {
                    bld = buildDlg.NewBuilding;
                    buildingRepo.Add(ref bld);
                    if (SelectedContract.Building == null)
                    {
                        SelectedContract.Building = new ObservableCollection <Building>();
                    }
                    SelectedContract.Building.Add(bld);
                }
            }, () => SelectedObject == 2);
            // редактировать клиента
            UpdateClientCmd = new RelayCommand(() =>
            {
                Client clt;
                ClientDialog clntDlg = new ClientDialog(SelectedClient);
                if (clntDlg.ShowDialog() == true)
                {
                    clt = clntDlg.NewClient;
                    clientsRepo.Update(clntDlg.NewClient);
                }
            }, () => SelectedObject == 1);
            // добавить клиента
            AddClientCmd = new RelayCommand(() =>
            {
                Client clt;
                ClientDialog clntDlg = new ClientDialog();
                if (clntDlg.ShowDialog() == true)
                {
                    clt = clntDlg.NewClient;
                    clientsRepo.Add(ref clt);
                    ListClient.Add(clt);
                }
            }, () => SelectedObject == 1);
            // добавить контракт
            AddContractCmd = new RelayCommand(() =>
            {
                Contract contract;
                ContractDialog contractDialog = new ContractDialog(SelectedClient);
                if (contractDialog.ShowDialog() == true)
                {
                    contract          = contractDialog.NewContract;
                    contract.ClientID = SelectedClient.ClientID;
                    contractRepo.Add(ref contract);
                    if (SelectedClient.Contract == null)
                    {
                        SelectedClient.Contract = new ObservableCollection <Contract>();
                    }
                    SelectedClient.Contract.Add(contract);
                }
            }, () => SelectedObject == 1);
            // редактировать контракт
            UpdateContractCmd = new RelayCommand(() =>
            {
                Contract contract;
                ContractDialog contractDialog = new ContractDialog(SelectedContract);
                if (contractDialog.ShowDialog() == true)
                {
                    contract = contractDialog.NewContract;
                    contractRepo.Update(contractDialog.NewContract);
                }
            }, () => SelectedObject == 2);
            // удалить контракт
            DeleteContractCmd = new RelayCommand(() =>
            {
                Contract contract = SelectedContract;
                contractRepo.Delete(SelectedContract);
                if (SelectedContract.Building != null)
                {
                    SelectedContract.Building.Clear();
                }
                ParentClient.Contract.Remove(SelectedContract);
            }, () => SelectedObject == 2);
            // удалить клиента
            DeleteClientCmd = new RelayCommand(() =>
            {
                Client contract = SelectedClient;
                clientsRepo.Delete(SelectedClient);
                if (SelectedClient.Contract != null)
                {
                    SelectedClient.Contract.Clear();
                }
                ListClient.Remove(SelectedClient);
            }, () => SelectedObject == 1);
            // вывести сметы в XML
            BuildingToXmlCmd = new RelayCommand(() =>
            {
                XDocument BuildingsXML = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XComment("Lizzard #smiles #loveMVVM #IAmGoodStudent"),
                    new XElement("Buildings",
                                 buildingRepo.GetAll().Select(bld =>
                                                              new XElement("Building",
                                                                           new XAttribute("ID", bld.ObjectID),
                                                                           new XElement("Name", bld.NameOfTheObject),
                                                                           new XElement("Contract_Number", bld.ContractNumber),
                                                                           new XElement("Issue_Date", bld.IssueDate.ToLongDateString()),
                                                                           new XElement("Cost", bld.CostOfTheObject)
                                                                           )
                                                              )
                                 ));
                BuildingsXML.Save(@"Buildings.xml");
            });
            #endregion
        }
Exemple #29
0
 public void Expect_the_dialog_to_be_in_DialogTable()
 {
     DialogTable.ContainsKey(ClientDialog.GetId()).Should().BeTrue();
 }