private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            AppPaths.ConfigureFFmpegPaths(this);

            GridInfo.Visibility      = Visibility.Hidden;
            DownloadsView.Visibility = Visibility.Hidden;
            DownloadUrl.Focus();
            DownloadsView.ItemsSource = Manager.DownloadsList;

            List <ListItem <int> > DownloadQualityList = new List <ListItem <int> >();

            DownloadQualityList.Add(new ListItem <int>("Max", 0));
            DownloadQualityList.Add(new ListItem <int>("1080p", 1080));
            DownloadQualityList.Add(new ListItem <int>("720p", 720));
            DownloadQualityList.Add(new ListItem <int>("480p", 480));
            DownloadQualityList.Add(new ListItem <int>("360p", 360));
            DownloadQualityList.Add(new ListItem <int>("240p", 240));
            MaxDownloadQualityCombo.ItemsSource   = DownloadQualityList;
            MaxDownloadQualityCombo.SelectedIndex = 0;

            SplashWindow F = SplashWindow.Instance(this, Properties.Resources.AppIcon);

            F.CanClose();
            F.ShowDialog();
        }
Esempio n. 2
0
        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 MainWindow()
        {
            InitializeComponent();
            AppPaths.ConfigureFFmpegPaths(this);

            playManager.StartPlaying += PlayManager_StartPlaying;
            FilesList.DataContext     = files;

            config = ConfigFile.Load();
            if (config.Width > 0)
            {
                this.Width = config.Width;
            }
            if (config.Height > 0)
            {
                this.Height = config.Height;
            }
            PlaylistsList.DataContext = config.Playlists;
            if (config.Playlists.Count == 0)
            {
                AddPlaylistButton_Click(null, null);
            }

            Player.MediaPlayerInitialized += (s, e) => {
                Player.Host.Player.MediaUnloaded += Player_MediaUnloaded;
                Player.Host.Player.MediaFinished += Player_MediaFinished;
                if (config.Volume > 0 && config.Volume <= 100)
                {
                    Player.Host.Volume = config.Volume;
                }
            };
        }
Esempio n. 4
0
        /// <summary>
        /// Loads bar data from either a local file, or a url.
        /// </summary>
        /// <param name="serviceProvider">The service provider/</param>
        /// <param name="barSource">The local path or remote url.</param>
        /// <param name="content">The json content, if already loaded.</param>
        /// <param name="includeDefault">true to also include the default bar data.</param>
        /// <returns>The bar data</returns>
        public static BarData?Load(IServiceProvider serviceProvider, string barSource, string?content = null, bool includeDefault = true)
        {
            BarData?defaultBar;

            if (includeDefault)
            {
                defaultBar = BarData.Load(serviceProvider, AppPaths.GetConfigFile("default-bar.json5", true), null, false);
                // Mark the items as being from the default specification
                defaultBar?.AllItems.ForEach(item => item.IsDefault = true);
            }
            else
            {
                defaultBar = null;
            }

            App.Current.Logger.LogInformation("Loading bar from {source}", barSource);

            BarData?bar;

            using (TextReader reader = content == null
                ? (TextReader)File.OpenText(barSource)
                : new StringReader(content))
            {
                bar = BarJson.Load(serviceProvider, reader, defaultBar);
            }

            bar.Source = barSource;
            if (File.Exists(barSource))
            {
                bar.AddWatcher(barSource);
            }

            return(bar);
        }
Esempio n. 5
0
        protected void Application_Start()
        {
            this.LogDebug("Application Initializing");
            GrowlHelper.SimpleGrowl("Application Initializing");
            AppPaths.SetCurrent(new AppPaths.PathsInstance(
                                    new DirectoryInfo(Server.MapPath("~")),
                                    new DirectoryInfo(Path.Combine(Path.GetTempPath(), "Web"))
                                    ));
            AppDeployment.Instance.Modules().ForEach(i => this.LogInfo("Integrating with {0} at {1}", i.Name, i.Uri));


            var options = new Options()
                          .EnableRequestAdditionalParameters()
                          .EnableResponseAdditionalParameters();

            var binder = new ModelBinder {
                ParseAdditionalParameters = Parser
            };

            GlobalConfiguration.Configuration.RegisterDataTables(options);


            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configuration.Filters.Add(new System.Web.Http.AuthorizeAttribute());
            GlobalConfiguration.Configuration.Filters.Add(new AppExceptionFilterAttribute());
            GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AutoMapperConfig.Initialize();
            Seeder.Initialize();
        }
Esempio n. 6
0
        public MainWindow()
        {
            Instance = this;
            // Don't let Yin Media Encoder run if there are FFmpeg processes running.
            if (MediaProcesses.GetFFmpegProcesses().Any())
            {
                if (MessageBox.Show("There are FFmpeg processes running. Would you like to stop them?\r\n\r\nTo avoid conflicts, please wait until these processes are finished before running Yin Media Encoder.", "FFmpeg Processes Running", MessageBoxButton.YesNo, MessageBoxImage.Exclamation, MessageBoxResult.No) == MessageBoxResult.Yes)
                {
                    foreach (Process item in MediaProcesses.GetFFmpegProcesses())
                    {
                        MediaProcesses.SoftKill(item);
                    }
                }
                if (MediaProcesses.GetFFmpegProcesses().Any())
                {
                    Application.Current.Shutdown();
                    return;
                }
            }

            InitializeComponent();
            // SessionCore.Instance.Start(this, Properties.Resources.AppIcon);
            helper = new WindowHelper(this);
            AppPaths.ConfigureFFmpegPaths(this);
        }
Esempio n. 7
0
        public MainWindow()
        {
            InitializeComponent();
            // helper = new WindowHelper(this);

            AppPaths.ConfigureFFmpegPaths(this);
        }
Esempio n. 8
0
        public void Start(Window main, System.Drawing.Bitmap splashImage)
        {
            // Make sure to initialize Settings static constructor to initialize database path.
            var a = Settings.SavedFile;

            // Configure C# FFmpeg library.
            AppPaths.ConfigureFFmpegPaths(main);

            NaturalGroundingPlayer.MainWindow NgMain = main as NaturalGroundingPlayer.MainWindow;
            if (NgMain != null)
            {
                Menu         = (MenuControl)NgMain.MainMenuContainer.Content;
                Layers       = (LayersControl)NgMain.LayersContainer.Content;
                RatingViewer = (RatingViewerControl)NgMain.RatingViewerContainer.Content;
                Business     = new PlayerBusiness(GetNewPlayer());
            }
            Icon        = main.Icon;
            Main        = main;
            SplashImage = splashImage;

            main.Loaded  += Main_Loaded;
            main.Closing += Main_Closing;

            AppDomain.CurrentDomain.UnhandledException       += CurrentDomain_UnhandledException;
            main.Dispatcher.UnhandledException               += Dispatcher_UnhandledException;
            System.Windows.Forms.Application.ThreadException += Application_ThreadException; // MPC-HC API calls are done through WinForms.

            Windows = new WindowManager(main);
        }
        public BarData?LoadBasicMorphicBar()
        {
            var result = LoadFromBarJson(AppPaths.GetConfigFile("basic-bar.json5", true));

            AppOptions.Current.LastCommunity    = null;
            AppOptions.Current.LastMorphicbarId = null;
            return(result);
        }
Esempio n. 10
0
#pragma warning restore CA1707 // Identifiers should not contain underscores

        public MainWindow()
        {
            InitializeComponent();
            // Create directories
            AppPaths.CreateDirectories();
            // Save ffmpeg files
            SaveFfmpeg();
        }
Esempio n. 11
0
        public ClientEventLogger(uint clID)
        {
            Dbg.Assert(clID != 0);
            ClientID = clID;

            m_tbl         = new EventLogTable(AppPaths.GetClientLogPath(clID));
            m_logProvider = m_tbl.DataProvider;
            m_logProvider.Connect();
        }
Esempio n. 12
0
        public static MCItemLocator[] GetAllMinecraftItems()
        {
            List <MCItemLocator> locators = new List <MCItemLocator>(128);
            string defaultIconsPath       = AppPaths.GetMCItemIconsPath();

            foreach (FileInfo item in IOHelper.EnumerateFileInfos(defaultIconsPath, "*.png"))
            {
                string        locatorName = "minecraft:" + Path.GetFileNameWithoutExtension(item.Name);
                MCItemLocator newLocator  = new MCItemLocator(locatorName, Path.Combine(defaultIconsPath, item.Name));
                locators.Add(newLocator);
            }
            return(locators.ToArray());
        }
Esempio n. 13
0
        /// <summary>
        /// Gets the full path to a bar icon in the assets directory, based on its name (with or without the extension).
        /// </summary>
        /// <param name="name">Name of the icon.</param>
        /// <returns></returns>
        public static string?GetBarIconFile(string name)
        {
            string safe = new Regex(@"\.\.|[^-a-zA-Z0-9./]+", RegexOptions.Compiled)
                          .Replace(name, "_")
                          .Trim('/')
                          .Replace('/', Path.DirectorySeparatorChar);
            string assetFile = AppPaths.GetAssetFile("bar-icons\\" + safe);

            string[] extensions = { "", ".svg", ".png", ".ico", ".jpg", ".jpeg", ".gif" };

            string?foundFile = extensions.Select(extension => assetFile + extension)
                               .FirstOrDefault(File.Exists);

            return(foundFile);
        }
        /// <summary>
        /// Gets the json for a <see cref="UserBar"/>, so it can be loaded with a better deserialiser.
        /// </summary>
        /// <param name="userBar">Bar data object from Morphic.Core</param>
        private string GetUserBarJson(UserBar userBar)
        {
            // Serialise the bar data so it can be loaded with a better deserialiser.
            SystemJson.JsonSerializerOptions serializerOptions = new SystemJson.JsonSerializerOptions();
            serializerOptions.Converters.Add(new JsonElementInferredTypeConverter());
            serializerOptions.Converters.Add(
                new SystemJson.Serialization.JsonStringEnumConverter(SystemJson.JsonNamingPolicy.CamelCase));
            string barJson = SystemJson.JsonSerializer.Serialize(userBar, serializerOptions);

            // Dump to a file, for debugging.
            string barFile = AppPaths.GetConfigFile("last-bar.json5");

            File.WriteAllText(barFile, barJson);

            return(barJson);
        }
Esempio n. 15
0
        private void SaveFfmpeg()
        {
            string ffmpeg = Path.Combine(AppPaths.GetFFmpeg(), "ffmpeg.exe");

            if (!File.Exists(ffmpeg) || new FileInfo(ffmpeg).Length != 79353358)
            {
                File.WriteAllBytes(ffmpeg, Properties.Resources.ffmpeg);
            }

            string ffprobe = Path.Combine(AppPaths.GetFFmpeg(), "ffprobe.exe");

            if (!File.Exists(ffprobe) || new FileInfo(ffprobe).Length != 79249422)
            {
                File.WriteAllBytes(ffprobe, Properties.Resources.ffprobe);
            }
        }
        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));
        }
Esempio n. 17
0
        /// <summary>
        /// Called when the session open task completes
        /// </summary>
        /// <param name="task"></param>
        private async void SessionOpened(Task task)
        {
            if (task.Exception is Exception e)
            {
                throw e;
            }
            this.Logger.LogInformation("Session Open");

            if (this.AppOptions.FirstRun)
            {
                await this.OnFirstRun();
            }

            if (Features.Basic.IsEnabled())
            {
                this.BarManager.LoadFromBarJson(AppPaths.GetConfigFile("basic-bar.json5", true));
            }
        }
Esempio n. 18
0
        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));
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Gets the full path to a bar icon in the assets directory, based on its name (with or without the extension).
        /// </summary>
        /// <param name="name">Name of the icon.</param>
        /// <returns></returns>
        public static string? GetBarIconFile(string name)
        {
            var translatedName = BarImages.TranslateImageUrlToFileName(name);
            if (translatedName is not null)
            {
                name = translatedName;
            }

            string safe = new Regex(@"\.\.|[^-a-zA-Z0-9./]+", RegexOptions.Compiled)
                .Replace(name, "_")
                .Trim('/')
                .Replace('/', Path.DirectorySeparatorChar);
            string assetFile = AppPaths.GetAssetFile("bar-icons\\" + safe);
            string[] extensions = { "", ".xaml", ".png", ".ico", ".jpg", ".jpeg", ".gif" };

            string? foundFile = extensions.Select(extension => assetFile + extension)
                .FirstOrDefault(File.Exists);

            return foundFile;
        }
Esempio n. 20
0
 /// <summary>
 /// Configure the dependency injection system with services
 /// </summary>
 /// <param name="services"></param>
 private void ConfigureServices(IServiceCollection services)
 {
     services.AddLogging(this.ConfigureLogging);
     services.Configure <SessionOptions>(this.Configuration.GetSection("MorphicService"));
     services.Configure <UpdateOptions>(this.Configuration.GetSection("Update"));
     services.AddSingleton <IServiceCollection>(services);
     services.AddSingleton <IServiceProvider>(provider => provider);
     services.AddSingleton <SessionOptions>(serviceProvider => serviceProvider.GetRequiredService <IOptions <SessionOptions> >().Value);
     services.AddSingleton(new StorageOptions {
         RootPath = AppPaths.GetConfigDir("Data")
     });
     services.AddSingleton(new KeychainOptions {
         Path = AppPaths.GetConfigDir("keychain")
     });
     services.AddSingleton <UpdateOptions>(serviceProvider => serviceProvider.GetRequiredService <IOptions <UpdateOptions> >().Value);
     services.AddSingleton <IDataProtection, DataProtector>();
     services.AddSingleton <IUserSettings, WindowsUserSettings>();
     services.AddSingleton <Solutions>();
     services.AddSingleton <Keychain>();
     services.AddSingleton <Storage>();
     services.AddSingleton <MorphicSession>();
     services.AddTransient <TravelWindow>();
     services.AddTransient <CreateAccountPanel>();
     services.AddTransient <CapturePanel>();
     services.AddTransient <TravelCompletedPanel>();
     services.AddTransient <LoginWindow>();
     services.AddTransient <LoginPanel>();
     services.AddTransient <CreateAccountPanel>();
     services.AddTransient <AboutWindow>();
     services.AddTransient <CopyStartPanel>();
     services.AddTransient <ApplyPanel>();
     services.AddTransient <RestoreWindow>();
     services.AddSingleton <Backups>();
     services.AddTransient <BarData>();
     services.AddSingleton <BarPresets>(s => BarPresets.Default);
     services.AddSolutionsRegistryServices();
     services.AddSingleton <Solutions>(s => Solutions.FromFile(s, AppPaths.GetAppFile("solutions.json5")));
 }
Esempio n. 21
0
        public MainWindow()
        {
            InitializeComponent();

            AppPaths.ConfigureFFmpegPaths(this);
            config = ConfigFile.Load();
            RefreshFiles();
            this.DataContext           = config;
            FoldersList.DataContext    = config.Folders;
            FilesList.DataContext      = config.Files;
            NowPlayingList.DataContext = config.Current.Files;
            VolumeSlider.DataContext   = config.Current;

            if (config.Width > 0)
            {
                this.Width = config.Width;
            }
            if (config.Height > 0)
            {
                this.Height = config.Height;
            }
            FoldersExpander_Collapsed(null, null);
        }
Esempio n. 22
0
 public BackupDiskPersistence(AppPaths appPaths)
 {
     Paths = appPaths;
 }
 public ImagenesJugadoresDiskPersistence(AppPaths appPaths)
 {
     Paths = appPaths;
 }
 public ImagenesPublicidadDiskPersistence(AppPaths appPaths)
 {
     Paths = appPaths;
 }
        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 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));
        }
Esempio n. 28
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));
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Loads bar data from either a local file, or a url.
        /// </summary>
        /// <param name="serviceProvider">The service provider/</param>
        /// <param name="barSource">The local path or remote url.</param>
        /// <param name="content">The json content, if already loaded.</param>
        /// <param name="includeDefault">true to also include the default bar data.</param>
        /// <returns>The bar data</returns>
        public static BarData?Load(IServiceProvider serviceProvider, string barSource, string?content = null, bool includeDefault = true)
        {
            BarData?defaultBar;

            if (includeDefault)
            {
                defaultBar = BarData.Load(serviceProvider, AppPaths.GetConfigFile("default-bar.json5", true), null, false);
                // Mark the items as being from the default specification
                defaultBar?.AllItems.ForEach(item => item.IsDefault = true);

                // OBSERVATION: we need a better way to determine if this is the basic bar or another bar
                var isBasicBar = (barSource == AppPaths.GetConfigFile("basic-bar.json5", true));
                //
                if (isBasicBar == true)
                {
                    // if extra bar items were specified in the config file, add them to the left side of the MorphicBar now
                    var morphicBarExtraItems = ConfigurableFeatures.MorphicBarExtraItems;
                    if (morphicBarExtraItems.Count > 0)
                    {
                        List <BarItem> extraBarItems = new List <BarItem>();
                        foreach (var extraItemData in morphicBarExtraItems)
                        {
                            BarItem extraBarItem;
                            var     extraBarItemShouldBeAdded = false;

                            switch (extraItemData.type)
                            {
                            case "application":
                            {
                                extraBarItem = new BarButton(defaultBar);
                                extraBarItem.ToolTipHeader = extraItemData.tooltipHeader;
                                extraBarItem.ToolTip       = extraItemData.tooltipText;
                                extraBarItem.Text          = extraItemData.label ?? "";
                                //
                                extraBarItem.Action = new Morphic.Client.Bar.Data.Actions.ApplicationAction();
                                ((Morphic.Client.Bar.Data.Actions.ApplicationAction)extraBarItem.Action !).ImageIsCollapsed = true;        // for horizontal bars, we don't want an image to be visible
                                ((Morphic.Client.Bar.Data.Actions.ApplicationAction)extraBarItem.Action !).ExeName          = extraItemData.appId ?? "";
                                extraBarItemShouldBeAdded = ((Morphic.Client.Bar.Data.Actions.ApplicationAction)extraBarItem.Action !).IsAvailable;
                            }
                            break;

                            case "link":
                            {
                                extraBarItem = new BarButton(defaultBar);
                                extraBarItem.ToolTipHeader = extraItemData.tooltipHeader;
                                extraBarItem.ToolTip       = extraItemData.tooltipText;
                                extraBarItem.Text          = extraItemData.label ?? "";
                                //
                                extraBarItem.Action = new Morphic.Client.Bar.Data.Actions.WebAction();
                                ((Morphic.Client.Bar.Data.Actions.WebAction)extraBarItem.Action !).UrlString = extraItemData.url ?? "";
                                extraBarItemShouldBeAdded = true;
                            }
                            break;

                            case "action":
                            {
                                extraBarItem = new BarButton(defaultBar);
                                extraBarItem.ToolTipHeader = extraItemData.tooltipHeader;
                                extraBarItem.ToolTip       = extraItemData.tooltipText;
                                extraBarItem.Text          = extraItemData.label ?? "";
                                //
                                var extraBarItemInternalAction = new Morphic.Client.Bar.Data.Actions.InternalAction();
                                extraBarItemInternalAction.TelemetryEventName = "morphicBarExtraItem";
                                extraBarItem.Action = extraBarItemInternalAction;
                                ((Morphic.Client.Bar.Data.Actions.InternalAction)extraBarItem.Action !).FunctionName = extraItemData.function !;
                                extraBarItemShouldBeAdded = true;
                            }
                            break;

                            case "control":
                            {
                                extraBarItem = new BarMultiButton(defaultBar);
                                extraBarItem.ToolTipHeader = extraItemData.tooltipHeader;
                                extraBarItem.ToolTip       = extraItemData.tooltipText;
                                //
                                switch (extraItemData.feature)
                                {
                                case "usbopeneject":
                                {
                                    extraBarItem.Text = extraItemData.label ?? "{{QuickStrip_UsbOpenEject_Title}}";
                                    //
                                    var openAllUsbAction = new Morphic.Client.Bar.Data.Actions.InternalAction();
                                    openAllUsbAction.TelemetryEventName = "morphicBarExtraItem";
                                    openAllUsbAction.FunctionName       = "openAllUsbDrives";
                                    var openButton = new BarMultiButton.ButtonInfo
                                    {
                                        Text              = "{{QuickStrip_UsbOpenEject_Open_Title}}",
                                        Action            = openAllUsbAction,
                                        TelemetryCategory = "morphicBarExtraItem",
                                        Tooltip           = "{{QuickStrip_UsbOpenEject_Open_HelpTitle}}",
                                        Value             = "openallusb"
                                    };
                                    //
                                    var ejectAllUsbAction = new Morphic.Client.Bar.Data.Actions.InternalAction();
                                    ejectAllUsbAction.TelemetryEventName = "morphicBarExtraItem";
                                    ejectAllUsbAction.FunctionName       = "ejectAllUsbDrives";
                                    var ejectButton = new BarMultiButton.ButtonInfo
                                    {
                                        Text              = "{{QuickStrip_UsbOpenEject_Eject_Title}}",
                                        Action            = ejectAllUsbAction,
                                        TelemetryCategory = "morphicBarExtraItem",
                                        Tooltip           = "{{QuickStrip_UsbOpenEject_Eject_HelpTitle}}",
                                        Value             = "ejectallusb"
                                    };
                                    //
                                    ((BarMultiButton)extraBarItem).Buttons = new Dictionary <string, BarMultiButton.ButtonInfo>
                                    {
                                        { "open", openButton },
                                        { "eject", ejectButton }
                                    };
                                    //
                                    extraBarItemShouldBeAdded = true;
                                }
                                break;

                                case "volume":
                                {
                                    extraBarItem.Text = extraItemData.label ?? "{{QuickStrip_Volume_Title}}";
                                    //
                                    var volumeUpAction = new Morphic.Client.Bar.Data.Actions.InternalAction();
                                    volumeUpAction.TelemetryEventName = "volumeUp";
                                    volumeUpAction.FunctionName       = "volumeUp";
                                    var volumeUpButton = new BarMultiButton.ButtonInfo
                                    {
                                        Text              = "+",
                                        Action            = volumeUpAction,
                                        TelemetryCategory = "volumeUp",
                                        Tooltip           = "{{QuickStrip_Volume_Up_HelpTitle}}|{{QuickStrip_Volume_Up_HelpMessage}}|{{QuickStrip_Volume_Up_LimitTitle}}",
                                        Value             = "volumeUp"
                                    };
                                    //
                                    var volumeDownAction = new Morphic.Client.Bar.Data.Actions.InternalAction();
                                    volumeDownAction.TelemetryEventName = "volumeDown";
                                    volumeDownAction.FunctionName       = "volumeDown";
                                    var volumeDownButton = new BarMultiButton.ButtonInfo
                                    {
                                        Text              = "-",
                                        Action            = volumeDownAction,
                                        TelemetryCategory = "volumeDown",
                                        Tooltip           = "{{QuickStrip_Volume_Down_HelpTitle}}|{{QuickStrip_Volume_Down_HelpMessage}}|{{QuickStrip_Volume_Down_LimitTitle}}",
                                        Value             = "volumeDown"
                                    };
                                    //
                                    var volumeMuteAction = new Morphic.Client.Bar.Data.Actions.InternalAction();
                                    volumeMuteAction.TelemetryEventName = "volumeMute";
                                    volumeMuteAction.FunctionName       = "volumeMute";
                                    var volumeMuteButton = new BarMultiButton.ButtonInfo
                                    {
                                        Text              = "{{QuickStrip_Volume_Mute_Title}}",
                                        Action            = volumeMuteAction,
                                        TelemetryCategory = "volumeMute",
                                        Toggle            = true,
                                        Tooltip           = "{{QuickStrip_Volume_Mute_HelpTitle}}|{{QuickStrip_Volume_Mute_HelpMessage}}",
                                        Value             = "volumeMute"
                                    };
                                    //
                                    ((BarMultiButton)extraBarItem).Buttons = new Dictionary <string, BarMultiButton.ButtonInfo>
                                    {
                                        { "volumeUp", volumeUpButton },
                                        { "volumeDown", volumeDownButton },
                                        { "volumeMute", volumeMuteButton }
                                    };
                                    ((BarMultiButton)extraBarItem).Menu = new Dictionary <string, string>()
                                    {
                                        { "setting", "sound" },
                                        { "learn", "volmute" },
                                        { "demo", "volmute" }
                                    };
                                    ((BarMultiButton)extraBarItem).AutoSize = true;
                                    //
                                    extraBarItemShouldBeAdded = true;
                                }
                                break;

                                case "wordsimplify":
                                {
                                    extraBarItem.Text = extraItemData.label ?? "{{QuickStrip_WordSimplify_Title}}";
                                    //
                                    var basicWordRibbonAction = new Morphic.Client.Bar.Data.Actions.InternalAction();
                                    basicWordRibbonAction.TelemetryEventName = "morphicBarExtraItem";                 // basicWordRibbonToggle
                                    basicWordRibbonAction.FunctionName       = "basicWordRibbon";
                                    var basicWordRibbonButton = new BarMultiButton.ButtonInfo
                                    {
                                        Text              = "{{QuickStrip_WordSimplify_Basic_Title}}",
                                        Action            = basicWordRibbonAction,
                                        TelemetryCategory = "morphicBarExtraItem",
                                        Toggle            = true,
                                        Tooltip           = "{{QuickStrip_WordSimplify_Basic_HelpTitle}}|{{QuickStrip_WordSimplify_Basic_HelpMessage}}",
                                        Value             = "basicwordribbon"
                                    };
                                    //
                                    var essentialsWordRibbonAction = new Morphic.Client.Bar.Data.Actions.InternalAction();
                                    essentialsWordRibbonAction.TelemetryEventName = "morphicBarExtraItem";                 // essentialsWordRibbonToggle
                                    essentialsWordRibbonAction.FunctionName       = "essentialsWordRibbon";
                                    var essentialsWordRibbonButton = new BarMultiButton.ButtonInfo
                                    {
                                        Text              = "{{QuickStrip_WordSimplify_Essentials_Title}}",
                                        Action            = essentialsWordRibbonAction,
                                        TelemetryCategory = "morphicBarExtraItem",
                                        Toggle            = true,
                                        Tooltip           = "{{QuickStrip_WordSimplify_Essentials_HelpTitle}}|{{QuickStrip_WordSimplify_Essentials_HelpMessage}}",
                                        Value             = "essentialswordribbon"
                                    };
                                    //
                                    ((BarMultiButton)extraBarItem).Buttons = new Dictionary <string, BarMultiButton.ButtonInfo>
                                    {
                                        { "basic", basicWordRibbonButton },
                                        { "essentials", essentialsWordRibbonButton }
                                    };
                                    ((BarMultiButton)extraBarItem).Menu = new Dictionary <string, string>()
                                    {
                                        { "learn", "wordsimplify" },
                                        { "demo", "wordsimplify" }
                                    };
                                    ((BarMultiButton)extraBarItem).AutoSize = true;
                                    //
                                    // NOTE: we should only show this item if Word is actually installed
                                    // NOTE: if Word is not installed, Morphic.Integrations.Office may fail to load as a DLL (or otherwise throw NotImplementedException); ideally we'd
                                    //       dynamically load the DLL only if Word was installed...and would perhaps move .IsOfficeInstalled into a DLL which wasn't reliant on Office being installed.
                                    try
                                    {
                                        extraBarItemShouldBeAdded = Morphic.Integrations.Office.WordRibbon.IsOfficeInstalled();
                                    }
                                    catch (NotImplementedException)
                                    {
                                        extraBarItemShouldBeAdded = false;
                                    }
                                }
                                break;

                                default:
                                    extraBarItem.Text = extraItemData.label ?? "";
                                    // NOTE: we don't know what this button is, so do not show it
                                    extraBarItemShouldBeAdded = false;
                                    break;
                                }
                            }
                            break;

                            default:
                                // unknown type; this should be an impossible code path
                                throw new NotImplementedException();
                            }
                            //extraBarItem.ColorValue = "#00FF00";
                            //
                            if (extraBarItemShouldBeAdded == true)
                            {
                                defaultBar?.AllItems.Add(extraBarItem);
                            }
                        }

                        // add a spacer entry
                        BarButton spacerBarItem = new BarButton(defaultBar);
                        spacerBarItem.ToolTipHeader = "";
                        spacerBarItem.ToolTip       = "";
                        spacerBarItem.Text          = "";
                        spacerBarItem.ColorValue    = "#FFFFFF";
                        //
                        defaultBar?.AllItems.Add(spacerBarItem);
                    }
                }
            }
            else
            {
                defaultBar = null;
            }

            App.Current.Logger.LogInformation("Loading bar from {source}", barSource);

            BarData?bar;

            using (TextReader reader = content is null
                ? (TextReader)File.OpenText(barSource)
                : new StringReader(content))
            {
                bar = BarJson.Load(serviceProvider, reader, defaultBar);
            }

            bar.Source = barSource;
            if (File.Exists(barSource))
            {
                bar.AddWatcher(barSource);
            }

            return(bar);
        }
        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));
        }