/// <inheritdoc/>
        public Task SetGroupConfigurationAsync(ScalingGroupId groupId, GroupConfiguration configuration, CancellationToken cancellationToken)
        {
            if (groupId == null)
            {
                throw new ArgumentNullException("groupId");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            UriTemplate template   = new UriTemplate("/groups/{groupId}/config");
            var         parameters = new Dictionary <string, string> {
                { "groupId", groupId.Value }
            };

            Func <Task <Tuple <IdentityToken, Uri> >, Task <HttpWebRequest> > prepareRequest =
                PrepareRequestAsyncFunc(HttpMethod.PUT, template, parameters, configuration);

            Func <Task <HttpWebRequest>, Task <string> > requestResource =
                GetResponseAsyncFunc(cancellationToken);

            return(AuthenticateServiceAsync(cancellationToken)
                   .Then(prepareRequest)
                   .Then(requestResource));
        }
        public static DeclarationService RebindGroupConnection(GroupConfiguration config)
        {
            if (config == null)
            {
                throw new InvalidOperationException("Configuration invalid!");
            }

            Kernel = new StandardKernel(new DeclarationModuleWin(config), new CoreModule());

            Kernel.Bind <AppConfiguration>()
            .ToSelf()
            .InSingletonScope();

            Kernel.Bind <IConfigurationRepository <GroupConfiguration> >()
            .To <GroupConfigurationRepository>()
            .InSingletonScope();

            // CnssModule.InitModule.Init();

            //Kernel.Bind<IConfigurationRepository<GroupConfiguration>>()
            //             .To<GroupConfigurationXmlRepository>()
            //             .InSingletonScope();
            Kernel.Bind(x => x.FromThisAssembly()
                        .SelectAllInterfaces()
                        .EndingWith("Factory")
                        .BindToFactory()
                        .Configure(c => c.InSingletonScope()));
            var connnectionProvider = Kernel.Get <IConnectionProvider>();

            connnectionProvider.ConnectionString = config.GetConnection();
            var groupConfig = Kernel.Get <IGroupContextManager>();

            groupConfig.ChangeGroupConfiguration(config);
            return(Kernel.Get <DeclarationService>());
        }
Example #3
0
 public EmailMassSendingTaskContext(string taskId, FileStream file, byte[] text,
                                    GroupConfiguration groupConfiguration)
 {
     TaskId             = taskId ?? throw new ArgumentNullException(nameof(taskId));
     File               = file ?? throw new ArgumentNullException(nameof(file));
     Text               = text;
     GroupConfiguration = groupConfiguration;
 }
Example #4
0
 private void btnConfigure_Click(object sender, EventArgs e)
 {
     if (GroupLoaded)
     {
         if (Constants.UseXaml)
         {
             GroupConfiguration grpConfig = new GroupConfiguration(MainLogic.Instance.Hotkeys);
             ElementHost.EnableModelessKeyboardInterop(grpConfig);
             grpConfig.ShowDialog();
         }
         else
         {
             HotkeyConfigurationForm configForm = new HotkeyConfigurationForm(MainLogic.Instance.Hotkeys);
             DialogResult            result     = configForm.ShowDialog();
         }
     }
 }
Example #5
0
        public static void Disconnect()
        {
            foreach (var client in StreamingHueClients)
            {
                client.LocalHueClient.SetStreamingAsync(_groupId, active: false);
            }

            EffectService.CancelAllEffects();
            if (_cts != null)
            {
                _cts.Cancel();
            }

            Layers = null;
            StreamingHueClients.Clear();
            StreamingGroups.Clear();
            CurrentConnection = null;
        }
        public override GroupConfiguration SelectGroupConfiguration(int groupLevel, CollectionViewGroup collectionViewGroup, GroupDescription groupDescription)
        {
            GroupConfiguration groupConfiguration = base.SelectGroupConfiguration(groupLevel, collectionViewGroup, groupDescription);

            if (groupConfiguration == null)
            {
                groupConfiguration = new GroupConfiguration();
                groupConfiguration.InitiallyExpanded = false;
            }

            if (collectionViewGroup != null)
            {
                groupConfiguration.InitiallyExpanded = (!collectionViewGroup.IsBottomLevel);
            }


            return(groupConfiguration);
        }
Example #7
0
        public static async Task SetupAndReturnGroupAsync(string groupName)
        {
            var configSection = await GetGroupConfigurationsAsync();

            var  currentGroup = configSection.Where(x => x.Name == groupName).FirstOrDefault();
            bool demoMode     = currentGroup.Name == "DEMO" || currentGroup.Connections.First().Key == "DEMO";
            bool useSimulator = demoMode ? true : currentGroup.Connections.First().UseSimulator;

            //Disconnect any current connections
            Disconnect();
            _cts = new CancellationTokenSource();

            List <Task> connectTasks = new List <Task>();

            foreach (var bridgeConfig in currentGroup.Connections)
            {
                connectTasks.Add(Connect(demoMode, useSimulator, bridgeConfig));
            }
            //Connect in parallel and wait for all tasks to finish
            await Task.WhenAll(connectTasks);

            var baseLayer   = GetNewLayer(isBaseLayer: true);
            var effectLayer = GetNewLayer(isBaseLayer: false);

            Layers = new List <EntertainmentLayer>()
            {
                baseLayer, effectLayer
            };
            CurrentConnection             = currentGroup;
            EffectSettings.LocationCenter = currentGroup.LocationCenter ?? new LightLocation()
            {
                0, 0, 0
            };

            //Optional: calculated effects that are placed on this layer
            baseLayer.AutoCalculateEffectUpdate(_cts.Token);
            effectLayer.AutoCalculateEffectUpdate(_cts.Token);
        }
Example #8
0
        public static List<GroupConfiguration> ReadGroups()
        {
            var result = new List<GroupConfiguration>();
            var panelConfigurations = GetPanelConfigurations();

            var groupingSettingsConfigurationFilePath = ApplicationSettings.GetString("GroupingSettingsFile");
            using (var reader = XmlReader.Create(groupingSettingsConfigurationFilePath))
            {
                while (reader.Read())
                {
                    if (reader.NodeType != XmlNodeType.Element) continue;
                    if (!reader.Name.Equals("group")) continue;

                    var element = XNode.ReadFrom(reader) as XElement;
                    if (element == null) continue;

                    var name = GetInnerElementValue(element, "name");
                    var id = GetInnerElementValue(element, "id");

                    var includedPanelConfigurations = new List<PanelConfiguration>();
                    var panelsElement = element.Descendants("panels").FirstOrDefault();
                    if (panelsElement != null)
                    {
                        includedPanelConfigurations.AddRange(from panelElement in panelsElement.Descendants("panel")
                                                                 let panelId = Convert.ToInt32(panelElement.Attribute("id").Value)
                                                                 let panelConfiguration = panelConfigurations.First(x => x.Id.Equals(panelId))
                                                                 select panelConfiguration);
                    }

                    var groupConfiguration = new GroupConfiguration { Id = Convert.ToInt32(id), Name = name, PanelConfigurations = includedPanelConfigurations };
                    result.Add(groupConfiguration);
                }
            }

            return result;
        }
 public InputBuilder()
 {
     _typeConfiguration  = new TypeConfiguration(this);
     _sizeConfiguration  = new InputSizeConfiguration(this);
     _groupConfiguration = new GroupConfiguration();
 }
Example #10
0
        private async Task <EmailMassSendingTaskContext> PrepareGroupOfTasksAsync(string groupId,
                                                                                  GroupConfiguration groupConfiguration, bool force, CancellationToken cancellationToken)
        {
            await using var file = new FileStream(groupConfiguration.PlainTextFileName, FileMode.Open, FileAccess.Read,
                                                  FileShare.None);

            var buffer = new byte[file.Length];

            await file.ReadAsync(buffer, 0, buffer.Length, cancellationToken);

            using var md5 = MD5.Create();

            var hex = Convert.ToHexString(md5.ComputeHash(buffer));

            var taskDir = _configuration.TasksPath ?? string.Empty;

            var taskId = $"{groupId}_{hex}.task";

            var taskPath = Path.Combine(taskDir, taskId);

            if (!Directory.Exists(taskDir))
            {
                Directory.CreateDirectory(taskDir);
            }
            else
            {
                if (_configuration.DeleteObsoleteTasks)
                {
                    var lifetime = _configuration.TaskFileLifetime ?? TimeSpan.FromDays(1);
                    foreach (var taskFileForDelete in Directory.GetFiles(taskDir, "*.task", SearchOption.TopDirectoryOnly))
                    {
                        var fi = new FileInfo(taskFileForDelete);
                        if (DateTime.Compare(fi.CreationTimeUtc.Add(lifetime), DateTime.UtcNow) < 0)
                        {
                            File.Delete(taskFileForDelete);
                            _logger.LogDebug($"Task file `{taskFileForDelete}` was deleted as obsolete.");
                        }
                    }
                }
            }

            if (File.Exists(taskPath))
            {
                if (!force)
                {
                    _logger.LogDebug($"Task `{taskId}` already exists. Reusing.");
                    var taskFs = new FileStream(taskPath, FileMode.Open, FileAccess.ReadWrite,
                                                FileShare.None);
                    return(new EmailMassSendingTaskContext(taskId, taskFs, buffer, groupConfiguration));
                }

                File.Delete(taskPath);
            }

            var newTask = new EmailMassSendingTask
            {
                TaskId = taskId,
                Items  = new List <EmailMassSendingTaskItem>()
            };

            if (groupConfiguration.Receivers == null)
            {
                _logger.LogWarning($"No receivers in group `{groupId}` specified.");
                return(null);
            }

            foreach (var receiver in groupConfiguration.Receivers.Distinct())
            {
                var newTaskItem = new EmailMassSendingTaskItem
                {
                    Receiver = receiver,
                    Failed   = false,
                    Failure  = null,
                    Lifetime =
                        new DateTimeOffset(DateTime.UtcNow.Add(groupConfiguration.Actuality ?? TimeSpan.FromHours(1)))
                };

                if (_configuration.RollUpStrategy.Enable)
                {
                    newTaskItem.AttemptsLeft = _configuration.RollUpStrategy.MaxCount;
                    newTaskItem.WaitFor      = DateTimeOffset.UtcNow;
                }

                newTask.Items.Add(newTaskItem);
            }

            var task2Fs = new FileStream(taskPath, FileMode.CreateNew, FileAccess.ReadWrite,
                                         FileShare.None);

            var taskFileBody = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(newTask));

            task2Fs.Position = 0;
            task2Fs.SetLength(taskFileBody.Length);

            await task2Fs.WriteAsync(taskFileBody, 0, taskFileBody.Length, cancellationToken);

            task2Fs.Position = 0;

            return(new EmailMassSendingTaskContext(taskId, task2Fs, buffer, groupConfiguration));
        }
Example #11
0
        public static async Task <List <StreamingGroup> > SetupAndReturnGroupAsync(string groupName)
        {
            var  configSection = GetGroupConfigurations();
            var  currentGroup  = configSection.Where(x => x.Name == groupName).FirstOrDefault();
            bool demoMode      = currentGroup.Name == "DEMO";
            bool useSimulator  = demoMode ? true : currentGroup.Connections.First().UseSimulator;

            //Disconnect any current connections
            Disconnect();
            _cts = new CancellationTokenSource();

            foreach (var bridgeConfig in currentGroup.Connections)
            {
                //Initialize streaming client
                var client = new LightDJStreamingHueClient(bridgeConfig.Ip, bridgeConfig.Key, bridgeConfig.EntertainmentKey, demoMode);

                //Get the entertainment group
                Dictionary <string, LightLocation> locations = null;
                if (demoMode)
                {
                    string demoJson = await File.ReadAllTextAsync($"{bridgeConfig.Ip}_{bridgeConfig.GroupId}.json");

                    locations = JsonConvert.DeserializeObject <Dictionary <string, LightLocation> >(demoJson);
                    _groupId  = bridgeConfig.GroupId;
                }
                else
                {
                    var all = await client.LocalHueClient.GetEntertainmentGroups();

                    var group = all.Where(x => x.Id == bridgeConfig.GroupId).FirstOrDefault();

                    if (group == null)
                    {
                        throw new Exception($"No Entertainment Group found with id {bridgeConfig.GroupId}. Create one using the Philips Hue App or the Q42.HueApi.UniversalWindows.Sample");
                    }
                    else
                    {
                        Console.WriteLine($"Using Entertainment Group {group.Id}");
                        _groupId = group.Id;
                    }

                    locations = group.Locations;
                }

                //Create a streaming group
                var stream = new StreamingGroup(locations);
                stream.IsForSimulator = useSimulator;


                //Connect to the streaming group
                if (!demoMode)
                {
                    await client.Connect(_groupId, simulator : useSimulator);
                }

                //Start auto updating this entertainment group
                client.AutoUpdate(stream, _cts.Token, 50, onlySendDirtyStates: true);

                StreamingHueClients.Add(client);
                StreamingGroups.Add(stream);
            }

            var baseLayer   = GetNewLayer(isBaseLayer: true);
            var effectLayer = GetNewLayer(isBaseLayer: false);

            Layers = new List <EntertainmentLayer>()
            {
                baseLayer, effectLayer
            };
            CurrentConnection             = currentGroup;
            EffectSettings.LocationCenter = currentGroup.LocationCenter ?? new LightLocation()
            {
                0, 0, 0
            };

            //Optional: calculated effects that are placed on this layer
            baseLayer.AutoCalculateEffectUpdate(_cts.Token);
            effectLayer.AutoCalculateEffectUpdate(_cts.Token);

            return(StreamingGroups);
        }
        static void Main(string[] args)
        {
            //Dossier Application data
            var dossierName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                           Application.ProductName);

            if (!Directory.Exists(dossierName))
            {
                Directory.CreateDirectory(dossierName);
            }

            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr-FR");
            // Add the event handler for handling UI thread exceptions to the event.
            Application.ThreadException += ThreadException;
            // Set the unhandled exception mode to force all Windows Forms errors to go through our handler.
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            // Add the event handler for handling non-UI thread exceptions to the event.
            AppDomain.CurrentDomain.UnhandledException += UnhandledException;

            BonusSkins.Register();
            SkinManager.EnableFormSkins();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            string path = args.Length != 0 ? args[0] : string.Empty;


//#if DEBUG
//            IsMultiSociete = true;
//#else
            // determinition code hardware du pc actuel
            var codePc = GeneratorCode.Value();

            // verification de la license
            try
            {
                var publicKey = File.ReadAllText("publicKey.xml");
                var validator = new LicenseValidator(publicKey, "lic.tvs", false);
                validator.AssertValidLicense();
                if (validator.Name != codePc)
                {
                    throw new ApplicationException("Licence invalide!");
                }
                var attribute = validator.LicenseAttributes;
                IsMultiSociete = attribute["MultiSocite"] == "0";
                IsCnss         = attribute["Cnss"] == "0";
                IsDecBc        = attribute["BcSuspension"] == "0";
                IsDecFc        = attribute["FcSuspension"] == "0";
                IsEmp          = attribute["Employeur"] == "0";
                IsVirement     = attribute["Virement"] == "0";
                Societe        = attribute["Societe"];
                DateExpiration = validator.ExpirationDate;
                IsLiasse       = attribute["Liasse"] == "0";
                // IsCovis = attribute["Covis"] == "0";
            }
            catch (LicenseFileNotFoundException e)
            {
                XtraMessageBox.Show("Fichier de licence introuvable");
                new FrmLicenceInvalide().ShowDialog();
                return;
            }
            catch (LicenseExpiredException e)
            {
                XtraMessageBox.Show("Licence expirée");
                new FrmLicenceInvalide().ShowDialog();
                return;
            }
            catch (Exception e)
            {
                XtraMessageBox.Show(e.Message);
                new FrmLicenceInvalide().ShowDialog();
                return;
            }
            //#endif


            // init Ninject dependencies resolver
            Kernel = new StandardKernel();
            Kernel.Bind <IUserControlFactory>().ToFactory().InSingletonScope();
            Kernel.Bind <IFormFactory>().ToFactory().InSingletonScope();

            Kernel.Bind <AppConfiguration>()
            .ToSelf()
            .InSingletonScope();


            Kernel.Bind <IConfigurationRepository <GroupConfiguration> >()
            .To <GroupConfigurationRepository>()
            .InSingletonScope();

            // check configs (connection ...)
            // get configs / connection to `Groupe`
            // should return a valid connection
            var appConfig = Kernel.Get <AppConfiguration>();
            GroupConfiguration groupeConfig = appConfig.Load(path);

            if (!string.IsNullOrEmpty(path))
            {
                try
                {
                    appConfig.Load(path);
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            if (groupeConfig == null)
            {
                XtraMessageBox.Show("Configuration invalide!");
                // demarrer la fenetre principale
                //var frm = new FrmNouveauFichier(appConfig);
                //frm.ShowDialog();
                return;
            }
            // RebindGroupConnection(groupeConfig);


            Application.SetCompatibleTextRenderingDefault(false);
            var main                = Kernel.Get <FrmMain>();
            var service             = GetService();
            var frmAuthentification = new FrmOuverture(service);

            if (frmAuthentification.ShowDialog() != DialogResult.Yes)
            {
                return;
            }
            Context = new CommandContext
            {
                MainForm           = main,
                Container          = InitializeContainer(),
                Exercice           = service.Exercice,
                Societe            = service.Societe,
                User               = service.User,
                ConnectionProvider = Kernel.Get <IConnectionProvider>()
            };

            // demarrer la fenetre principale
            Application.Run(Context.MainForm);
            //   Application.Run(new XtraForm1());
        }
Example #13
0
        /// <summary>
        /// Set the group configuration for a scaling group.
        /// </summary>
        /// <param name="service">The Auto Scale service instance.</param>
        /// <param name="groupId">The ID of the scaling group. This is obtained from <see cref="ScalingGroup.Id">ScalingGroup.Id</see>.</param>
        /// <param name="configuration">The new group configuration for the scaling group.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="service"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="groupId"/> is <see langword="null"/>.
        /// <para>-or-</para>
        /// <para>If <paramref name="configuration"/> is <see langword="null"/>.</para>
        /// </exception>
        /// <exception cref="WebException">If the REST request does not return successfully.</exception>
        /// <seealso href="http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/PUT_putGroupConfig_v1.0__tenantId__groups__groupId__config_Configurations.html">Update scaling group configuration (Rackspace Auto Scale Developer Guide - API v1.0)</seealso>
        public static void SetGroupConfiguration(this IAutoScaleService service, ScalingGroupId groupId, GroupConfiguration configuration)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }

            try
            {
                service.SetGroupConfigurationAsync(groupId, configuration, CancellationToken.None).Wait();
            }
            catch (AggregateException ex)
            {
                ReadOnlyCollection <Exception> innerExceptions = ex.Flatten().InnerExceptions;
                if (innerExceptions.Count == 1)
                {
                    throw innerExceptions[0];
                }

                throw;
            }
        }