Esempio n. 1
0
        public async Task <IActionResult> Get(string distName)
        {
            ConfigurationSettings settings = FabricRuntime.GetActivationContext().GetConfigurationPackageObject("Config").Settings;
            KeyedCollection <string, ConfigurationProperty> serviceParameters = settings.Sections["MyConfigSection"].Parameters;
            string reverseProxyPort = serviceParameters["ReverseProxyPort"].Value;
            string dataServiceName  = serviceParameters["CityServiceName"].Value;
            string serviceUri       = string.Format($"{FabricRuntime.GetActivationContext().ApplicationName}/{dataServiceName}");
            long   partitionKey     = FnvHash.Hash(distName);
            string proxyUrl         =
                $"http://localhost:{reverseProxyPort}/{serviceUri.Replace("fabric:/", "")}/api/citydata/{distName}?PartitionKind=Int64Range&PartitionKey={partitionKey}";

            ServiceEventSource.Current.Message(proxyUrl);

            HttpResponseMessage response = await new HttpClient().GetAsync(proxyUrl);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return(this.StatusCode((int)response.StatusCode));
            }

            string distData = await response.Content.ReadAsStringAsync();

            var districtReport = JsonConvert.DeserializeObject <DistrictReport>(distData);

            return(this.Json(districtReport));
        }
        internal static GraphConnectionContext GetConnectionContext(KeyedCollection <string, ConfigParameter> configParameters)
        {
            logger.Info($"Setting up connection to {configParameters[ConfigParameterNames.TenantDomain].Value}");

            System.Net.ServicePointManager.DefaultConnectionLimit = MicrosoftTeamsMAConfigSection.Configuration.ConnectionLimit;
            GlobalSettings.ExportThreadCount = MicrosoftTeamsMAConfigSection.Configuration.ExportThreads;

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(configParameters[ConfigParameterNames.ClientId].Value)
                                                                           .WithTenantId(configParameters[ConfigParameterNames.TenantDomain].Value)
                                                                           .WithClientSecret(configParameters[ConfigParameterNames.Secret].SecureValue.ConvertToUnsecureString())
                                                                           .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            };

            var client     = new GraphServiceClient(authProvider);
            var betaClient = new Beta.GraphServiceClient(authProvider);

            return(new GraphConnectionContext()
            {
                Client = client,
                BetaClient = betaClient,
                UserFilter = new UserFilter(client, configParameters)
            });
        }
Esempio n. 3
0
        public Collection(Drawing.SpriteManager sprites, Animations.AnimationManager animations, Audio.SoundManager sounds, Drawing.FontMap fontmap)
        {
            if (sprites == null)
            {
                throw new ArgumentNullException("sprites");
            }
            if (animations == null)
            {
                throw new ArgumentNullException("animations");
            }
            if (sounds == null)
            {
                throw new ArgumentNullException("sounds");
            }
            if (fontmap == null)
            {
                throw new ArgumentNullException("fontmap");
            }

            m_elements         = new KeyedCollection <String, Elements.Base>(x => x.Name, StringComparer.OrdinalIgnoreCase);
            m_spritemanager    = sprites;
            m_animationmanager = animations;
            m_soundmanager     = sounds;
            m_fontmap          = fontmap;
        }
Esempio n. 4
0
		/// <summary>
		/// Initializes a new instance of this class.
		/// </summary>
		/// <param name="subsystems">Collection of subsystems to be used by this class.</param>
		public FileSystem(SubSystems subsystems)
			: base(subsystems)
		{
			m_textcache = new KeyedCollection<String, TextFile>(x => x.Filepath, StringComparer.OrdinalIgnoreCase);
			m_titleregex = new Regex(@"^\s*\[(.+?)\]\s*$", RegexOptions.IgnoreCase);
			m_parsedlineregex = new Regex(@"^\s*(.+?)\s*=\s*(.+?)\s*$", RegexOptions.IgnoreCase);
		}
        public ServersViewModel()
        {
            _serverList = new ServerList();
            _launcher = new Launcher();
            _popupService = new PopupService();
            _storage = new JSONStorage();
            if (_storage.Exists("config.json"))
                _configuration = _storage.Read<Configuration>("config.json");
            else
                _configuration = new Configuration();

            _servers = new KeyedCollection<String, ServerObservable>(SynchronizationContext.Current);
            _serversView = new ServersView(_servers);

            _refresh = new RelayCommand(_ => true, _ => DoRefresh());
            _pingAll = new RelayCommand(_ => true, _ => DoPingAll());
            _pingSelected = new RelayCommand(_ => _selectedServer != null, _ => DoPingOne(_selectedServer));
            _joinSelected = new RelayCommand(_ => _selectedServer != null, _ => DoJoin(_selectedServer));
            _copyAddressSelected = new RelayCommand(_ => _selectedServer != null, _ => CopyAddress(_selectedServer));

            Mapper.CreateMap<Server, ServerObservable>();
            Mapper.CreateMap<ServerSettings, ServerSettingsObservable>();
            Mapper.CreateMap<ServerObservable, ServerObservable>().ForMember(s => s.Latency, opt => opt.Ignore());
            Mapper.AssertConfigurationIsValid();

            DoRefresh();
            DoCheckUpdate();
        }
Esempio n. 6
0
        public IList <ConfigParameterDefinition> GetConfigParameters(KeyedCollection <string, ConfigParameter> configParameters, ConfigParameterPage page)
        {
            try
            {
                Logging.SetupLogger(configParameters);

                var configParameterDefinitions = new List <ConfigParameterDefinition>();
                Logging.AddBuiltInLoggingParameters(page, configParameterDefinitions);
                IConfigParametersProvider provider = InterfaceManager.GetProviderOrDefault <IConfigParametersProvider>();

                if (provider == null)
                {
                    var providerEx = InterfaceManager.GetProviderOrDefault <IConfigParametersProviderEx>();
                    providerEx?.GetConfigParametersEx(configParameters, configParameterDefinitions, page, 1);
                }
                else
                {
                    provider.GetConfigParameters(configParameters, configParameterDefinitions, page);
                }

                return(configParameterDefinitions);
            }
            catch (Exception ex)
            {
                logger.Error(ex.UnwrapIfSingleAggregateException(), "Could not get config parameters");
                throw;
            }
        }
        private void UpdateConfigSettings(ConfigurationSettings configSettings)
        {
            KeyedCollection <string, ConfigurationProperty> parameters = configSettings.Sections["HealthMetrics.DoctorActor.Settings"].Parameters;

            this.countyServiceInstanceUri    = new ServiceUriBuilder(parameters["CountyServiceInstanceName"].Value).ToUri();
            this.bandActorServiceInstanceUri = new ServiceUriBuilder(parameters["BandActorServiceInstanceName"].Value).ToUri();
        }
Esempio n. 8
0
        /// <summary>
        /// Configures the import session at the beginning of an import
        /// </summary>
        /// <param name="configParameters">The configuration parameters supplied to this management agent</param>
        /// <param name="types">The schema types that apply to this import run</param>
        /// <param name="importRunStep">The definition of the current run step</param>
        /// <returns>Results of the import setup</returns>
        public OpenImportConnectionResults OpenImportConnection(KeyedCollection <string, ConfigParameter> configParameters, Schema types, OpenImportConnectionRunStep importRunStep)
        {
            try
            {
                this.suppliedConfigParameters = configParameters;
                Logger.LogPath = this.LogPath;
                Logger.WriteSeparatorLine('*');
                Logger.WriteLine("Starting Import");
                Logger.WriteLine("Import data from sync engine: " + importRunStep.CustomData);

                this.client = new AcmaSyncServiceClient();
                this.client.Open();

                ImportStartRequest request = new ImportStartRequest();
                request.ImportType = importRunStep.ImportType;
                request.PageSize   = 0;
                request.Schema     = types;

                this.importResponse = this.client.ImportStart(request);

                this.importPageSize = importRunStep.PageSize;

                return(new OpenImportConnectionResults());
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex);
                throw;
            }
        }
Esempio n. 9
0
 private void UpdateConfigSettings(ConfigurationSettings configSettings)
 {
     lock (ConfigPackageLockObject)
     {
         this.configPackageSettings = configSettings.Sections[ConfigSectionName].Parameters;
     }
 }
Esempio n. 10
0
        private void InitializeVariablesList()
        {
            Debug.Assert(this.FileHandle >= 0, "Must be working with an open file.");
            int initialSize;

            SpssException.ThrowOnFailure(SpssSafeWrapper.spssGetNumberofVariables(this.FileHandle, out initialSize), "spssGetNumberofVariables");
            this.variables       = new List <SpssVariable>(initialSize);
            this.variablesLookup = new SpssVariableKeyedCollection();

            string[]   varNames;
            int[]      varTypes;
            ReturnCode result = SpssException.ThrowOnFailure(SpssSafeWrapper.spssGetVarNames(this.FileHandle, out varNames, out varTypes), "spssGetVarNames", ReturnCode.SPSS_INVALID_FILE);

            if (result == ReturnCode.SPSS_INVALID_FILE)
            {
                // brand new file
                return;
            }

            Debug.Assert(varNames.Length == varTypes.Length);
            for (int i = 0; i < varNames.Length; i++)
            {
                this.Add(SpssVariable.LoadVariable(this, varNames[i], varTypes[i]));
            }
        }
        internal static void CopyFrom(KeyedCollection <string, ServiceLoadMetricDescription> source, KeyedCollection <string, ServiceLoadMetricDescription> target)
        {
            if (source != null)
            {
                target.Clear();

                source.ForEach(m =>
                {
                    ServiceLoadMetricDescription casted;

                    if (m is StatefulServiceLoadMetricDescription)
                    {
                        casted = new StatefulServiceLoadMetricDescription(m as StatefulServiceLoadMetricDescription);
                    }
                    else if (m is StatelessServiceLoadMetricDescription)
                    {
                        casted = new StatelessServiceLoadMetricDescription(m as StatelessServiceLoadMetricDescription);
                    }
                    else
                    {
                        casted = new ServiceLoadMetricDescription(m);
                    }

                    target.Add(casted);
                });
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Creates Animations from a xnaMugen.IO.TextFile.
        /// </summary>
        /// <param name="textfile">A textfile whose xnaMugen.IO.TextSection can be used to create Animations.</param>
        /// <returns>A collection of Animations created from the supplied textfile.</returns>
        public KeyedCollection <Int32, Animation> LoadAnimations(TextFile textfile)
        {
            if (textfile == null)
            {
                throw new ArgumentNullException("textfile");
            }

            KeyedCollection <Int32, Animation> animations = new KeyedCollection <Int32, Animation>(x => x.Number);

            foreach (TextSection section in textfile)
            {
                Animation animation = CreateAnimation(section);
                if (animation != null)
                {
                    if (animations.Contains(animation.Number) == false)
                    {
                        animations.Add(animation);
                    }
                    else
                    {
                        Log.Write(LogLevel.Warning, LogSystem.AnimationSystem, "Duplicate animation #{0}. Discarding duplicate.", animation.Number);
                    }
                }
            }

            return(animations);
        }
Esempio n. 13
0
        public Renderer(VideoSystem videosystem)
        {
            if (videosystem == null) throw new ArgumentNullException("videosystem");

            m_videosystem = videosystem;

            using (IO.File effectfile = m_videosystem.GetSubSystem<IO.FileSystem>().OpenFile("xnaMugen.data.Shader.fx"))
            {
                CompiledEffect compiled = Effect.CompileEffectFromSource(effectfile.ReadToEnd(), null, null, CompilerOptions.None, TargetPlatform.Windows);
                if (compiled.Success == false)
                {
                    throw new InvalidOperationException("Cannot successfully create shader.");
                }

                m_effect = new Effect(Device, compiled.GetEffectCode(), CompilerOptions.NotCloneable, null);
            }

            m_drawbuffer = new Vertex[500];
            m_parameters = new KeyedCollection<String, EffectParameter>(x => x.Name);

            m_nullpixels = m_videosystem.CreatePixelTexture(new Point(2, 2));
            m_nullpalette = m_videosystem.CreatePaletteTexture();

            Byte[] pixels = new Byte[] { 1, 2, 1, 2 };
            m_nullpixels.SetData<Byte>(pixels);

            Color[] paldata = new Color[256];
            paldata[1] = Color.White;
            paldata[2] = Color.Red;
            m_nullpalette.SetData<Color>(paldata);
        }
Esempio n. 14
0
        public IList <ConfigParameterDefinition> GetConfigParametersEx(KeyedCollection <string, ConfigParameter> configParameters, ConfigParameterPage page, int pageNumber)
        {
            IConfigParametersProviderEx provider = InterfaceManager.GetProviderOrDefault <IConfigParametersProviderEx>();

            if (provider == null)
            {
                if (pageNumber > 1)
                {
                    return(null);
                }

                return(this.GetConfigParameters(configParameters, page));
            }

            var configParameterDefinitions = new List <ConfigParameterDefinition>();

            if (pageNumber == 1)
            {
                Logging.AddBuiltInLoggingParameters(page, configParameterDefinitions);
            }

            provider.GetConfigParametersEx(configParameters, configParameterDefinitions, page, pageNumber);

            return(configParameterDefinitions);
        }
Esempio n. 15
0
 // Get Schema
 public Schema GetSchema(KeyedCollection <string, ConfigParameter> _configParameters)
 {
     utils.Logger(TraceEventType.Information,
                  ConstDefinition.ID0100_START_GETSCHEMA,
                  ConstDefinition.MSG0100_START_GETSCHEMA);
     try
     {
         SchemaType personType = SchemaType.Create("Person", false);
         personType.Attributes.Add(SchemaAttribute.CreateAnchorAttribute("Username", AttributeType.String));
         personType.Attributes.Add(SchemaAttribute.CreateSingleValuedAttribute("Alias", AttributeType.String));
         personType.Attributes.Add(SchemaAttribute.CreateSingleValuedAttribute("Email", AttributeType.String));
         personType.Attributes.Add(SchemaAttribute.CreateSingleValuedAttribute("LastName", AttributeType.String));
         personType.Attributes.Add(SchemaAttribute.CreateSingleValuedAttribute("EmailEncodingKey", AttributeType.String));
         personType.Attributes.Add(SchemaAttribute.CreateSingleValuedAttribute("LanguageLocaleKey", AttributeType.String));
         personType.Attributes.Add(SchemaAttribute.CreateSingleValuedAttribute("LocaleSidKey", AttributeType.String));
         personType.Attributes.Add(SchemaAttribute.CreateSingleValuedAttribute("ProfileId", AttributeType.String));
         personType.Attributes.Add(SchemaAttribute.CreateSingleValuedAttribute("TimeZoneSidKey", AttributeType.String));
         personType.Attributes.Add(SchemaAttribute.CreateSingleValuedAttribute("UserPermissionsOfflineUser", AttributeType.Boolean));
         personType.Attributes.Add(SchemaAttribute.CreateSingleValuedAttribute("UserPermissionsMarketingUser", AttributeType.Boolean));
         Schema schema = Schema.Create();
         schema.Types.Add(personType);
         return(schema);
     }
     catch (Exception ex)
     {
         utils.Logger(TraceEventType.Error,
                      ConstDefinition.ID0199_ERROR_GETSCHEMA,
                      ConstDefinition.MSG0199_ERROR_GETSCHEMA + ex.Message);
         throw new ExtensibleExtensionException(ConstDefinition.MSG0199_ERROR_GETSCHEMA + ex.Message);
     }
 }
Esempio n. 16
0
 /// <summary>
 /// Processes an attribute replace request on the specified CSEntryChange
 /// </summary>
 /// <param name="csentry">The CSEntryChange to process</param>
 /// <param name="attribute">The attribute associated with this request</param>
 /// <param name="value">The new value to assign to the attribute</param>
 public static void ReplaceAttribute(this KeyedCollection <string, AttributeChange> attributeChanges, ObjectModificationType objectModificationType, AcmaSchemaAttribute attribute, object value)
 {
     ReplaceAttribute(attributeChanges, objectModificationType, attribute, new List <object>()
     {
         value
     });
 }
Esempio n. 17
0
        /// <summary>
        /// Creates a new AttributeChange of type 'delete'
        /// </summary>
        /// <param name="csentry">The CSEntryChange to apply the AttributeChange to</param>
        /// <param name="attribute">The attribute to create the AttributeChange for</param>
        private static void CreateAttributeChangeDelete(this KeyedCollection <string, AttributeChange> attributeChanges, ObjectModificationType objectModificationType, AcmaSchemaAttribute attribute)
        {
            switch (objectModificationType)
            {
            case ObjectModificationType.Add:
                // This is a new object, so there is nothing to delete
                break;

            case ObjectModificationType.Delete:
                throw new DeletedObjectModificationException();

            case ObjectModificationType.Replace:
                // This object is being replaced, so the absence of an attribute add implies that any existing attribute values shall be deleted
                break;

            case ObjectModificationType.Update:
                attributeChanges.Add(AttributeChange.CreateAttributeDelete(attribute.Name));
                break;

            case ObjectModificationType.None:
            case ObjectModificationType.Unconfigured:
            default:
                throw new UnknownOrUnsupportedModificationTypeException(objectModificationType);
            }
        }
        private void UpdateConfigSettings(ConfigurationSettings settings)
        {
            KeyedCollection <string, ConfigurationProperty> parameters = settings.Sections["RecaptchaSettings"].Parameters;

            this.key       = parameters["Key"].DecryptValue();
            this.verifyUrl = new Uri(parameters["VerifyUrl"].Value);
        }
Esempio n. 19
0
        public ServersViewModel()
        {
            _serverList   = new ServerList();
            _launcher     = new Launcher();
            _popupService = new PopupService();
            _storage      = new JSONStorage();
            if (_storage.Exists("config.json"))
            {
                _configuration = _storage.Read <Configuration>("config.json");
            }
            else
            {
                _configuration = new Configuration();
            }

            _servers     = new KeyedCollection <String, ServerObservable>(SynchronizationContext.Current);
            _serversView = new ServersView(_servers);

            _refresh             = new RelayCommand(_ => true, _ => DoRefresh());
            _pingAll             = new RelayCommand(_ => true, _ => DoPingAll());
            _pingSelected        = new RelayCommand(_ => _selectedServer != null, _ => DoPingOne(_selectedServer));
            _joinSelected        = new RelayCommand(_ => _selectedServer != null, _ => DoJoin(_selectedServer));
            _copyAddressSelected = new RelayCommand(_ => _selectedServer != null, _ => CopyAddress(_selectedServer));

            Mapper.CreateMap <Server, ServerObservable>();
            Mapper.CreateMap <ServerSettings, ServerSettingsObservable>();
            Mapper.CreateMap <ServerObservable, ServerObservable>().ForMember(s => s.Latency, opt => opt.Ignore());
            Mapper.AssertConfigurationIsValid();

            DoRefresh();
            DoCheckUpdate();
        }
        /// <summary>
        /// This is the main entry point for your service instance.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service instance.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            await Task.Yield();

            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            // Get ServiceBus ConnectionString from configuration (Settings.xml)
            ConfigurationPackage configPackage = this.Context.CodePackageActivationContext.GetConfigurationPackageObject("Config");

            // Access Settings.xml
            KeyedCollection <string, ConfigurationProperty> parameters = configPackage.Settings.Sections["ConfigSection"].Parameters;

            // Make sure you provide the corresponding Service Bus connection information in the service configuration file.
            var serviceBusConnectionString = parameters["ServiceBus.ConnectionString"]?.Value;
            var topicName        = parameters["TopicName"]?.Value;
            var subscriptionName = parameters["SubscriptionName"]?.Value;

            this.queueManager = new QueueManager(serviceBusConnectionString, topicName);

            // create the subscriptions, one for each priority.
            await this.queueManager.SetupAsync(subscriptionName, priority : subscriptionName)
            .ConfigureAwait(false);

            this.queueManager.ReceiveMessages(subscriptionName, this.ProcessMessageAsync, cancellationToken);

            if (cancellationToken.WaitHandle.WaitOne())
            {
                await this.queueManager.StopReceiverAsync()
                .ConfigureAwait(false);
            }
        }
Esempio n. 21
0
        public static void AddItemsObject <TKey, TValue>(
            this KeyedCollection <TKey, TValue> collection,
            Func <TValue> generateItem,
            Func <TValue, TKey> getKey,
            int numItems,
            out TKey[] keys,
            out TValue[] items,
            out TValue[] itemsWithKeys)
        {
            items         = new TValue[numItems];
            keys          = new TKey[numItems];
            itemsWithKeys = new TValue[numItems];
            var keyIndex = 0;

            for (var i = 0; i < numItems; ++i)
            {
                TValue item = generateItem();
                TKey   key  = getKey(item);

                ((IList)collection).Add(item);
                items[i] = item;

                if (null != key)
                {
                    keys[keyIndex]          = key;
                    itemsWithKeys[keyIndex] = item;
                    ++keyIndex;
                }
            }

            keys          = keys.Slice(0, keyIndex);
            itemsWithKeys = itemsWithKeys.Slice(0, keyIndex);
        }
Esempio n. 22
0
        // Validate Parameters
        public ParameterValidationResult ValidateConfigParameters(KeyedCollection <string, ConfigParameter> _configParameters, ConfigParameterPage _page)
        {
            utils.Logger(TraceEventType.Information,
                         ConstDefinition.ID0300_START_VALIDATECONFIGPARAMETERS,
                         ConstDefinition.MSG0300_START_VALIDATECONFIGPARAMETERS);
            try
            {
                switch (_page)
                {
                case ConfigParameterPage.Connectivity:
                    break;

                case ConfigParameterPage.Global:
                    break;

                case ConfigParameterPage.Partition:
                    break;

                case ConfigParameterPage.RunStep:
                    break;

                case ConfigParameterPage.Schema:
                    break;
                }
                return(new ParameterValidationResult());
            }
            catch (Exception ex)
            {
                utils.Logger(TraceEventType.Error,
                             ConstDefinition.ID0399_ERROR_VALIDATECONFIGPARAMETERS,
                             ConstDefinition.MSG0300_START_VALIDATECONFIGPARAMETERS + ex.Message);
                throw new ExtensibleExtensionException(ConstDefinition.MSG0399_ERROR_VALIDATECONFIGPARAMETERS + ex.Message);
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Converts an AttributeChange of type 'delete' to a new AttributeChange of type 'update'
        /// </summary>
        /// <param name="csentry">The CSEntryChange to apply the AttributeChange to</param>
        /// <param name="attribute">The attribute to create the AttributeChange for</param>
        /// <param name="valueChanges">The value changes to apply</param>
        /// <param name="existingChange">The existing attribute change that was found on the CSEntryChange</param>
        private static void ConvertAttributeChangeUpdateFromDelete(this KeyedCollection <string, AttributeChange> attributeChanges, ObjectModificationType objectModificationType, AcmaSchemaAttribute attribute, IList <ValueChange> valueChanges, AttributeChange existingChange)
        {
            attributeChanges.Remove(existingChange);
            IList <object> valueAdds = valueChanges.Where(t => t.ModificationType == ValueModificationType.Add).Select(t => t.Value).ToList();

            switch (objectModificationType)
            {
            case ObjectModificationType.Add:
                throw new InvalidOperationException("The attribute change type is not valid for the object modification type");

            case ObjectModificationType.Delete:
                throw new DeletedObjectModificationException();

            case ObjectModificationType.Replace:
                throw new InvalidOperationException("The attribute change type is not valid for the object modification type");

            case ObjectModificationType.Update:
                attributeChanges.Add(AttributeChange.CreateAttributeReplace(attribute.Name, valueAdds));
                break;

            case ObjectModificationType.None:
            case ObjectModificationType.Unconfigured:
            default:
                throw new UnknownOrUnsupportedModificationTypeException(objectModificationType);
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Creates a new AttributeChange of type 'update'
        /// </summary>
        /// <param name="csentry">The CSEntryChange to apply the AttributeChange to</param>
        /// <param name="attribute">The attribute to create the AttributeChange for</param>
        /// <param name="valueChanges">The value changes to apply</param>
        private static void CreateAttributeChangeUpdate(this KeyedCollection <string, AttributeChange> attributeChanges, ObjectModificationType objectModificationType, AcmaSchemaAttribute attribute, IList <ValueChange> valueChanges)
        {
            switch (objectModificationType)
            {
            case ObjectModificationType.Add:
                attributeChanges.Add(AttributeChange.CreateAttributeAdd(attribute.Name, valueChanges.Where(t => t.ModificationType == ValueModificationType.Add).Select(t => t.Value).ToList <object>()));
                break;

            case ObjectModificationType.Delete:
                throw new DeletedObjectModificationException();

            case ObjectModificationType.Replace:
                attributeChanges.Add(AttributeChange.CreateAttributeAdd(attribute.Name, valueChanges.Where(t => t.ModificationType == ValueModificationType.Add).Select(t => t.Value).ToList <object>()));
                break;

            case ObjectModificationType.Update:
                attributeChanges.Add(AttributeChange.CreateAttributeUpdate(attribute.Name, valueChanges));
                break;

            case ObjectModificationType.Unconfigured:
            case ObjectModificationType.None:
            default:
                throw new UnknownOrUnsupportedModificationTypeException(objectModificationType);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Generate Home Assistant configuration file entries for the actuators in the provided device.
        /// </summary>
        /// <param name="definition">Device properties</param>
        /// <returns>Configuration file entries covering all actuators defined in the device</returns>
        public KeyedCollection <ConfigEntry> TransformConfig(DeviceDefinition definition)
        {
            if (definition.Actuators == null)
            {
                return(new KeyedCollection <ConfigEntry>());
            }

            if (string.IsNullOrWhiteSpace(definition.DeviceId))
            {
                throw new ValidationException($"{nameof(definition.DeviceId)} requires a value.");
            }

            var configs = new KeyedCollection <ConfigEntry>();

            foreach (var actuator in definition.Actuators)
            {
                var config = FormatActuatorDefinition(new ActuatorConfig
                {
                    Type     = actuator.Type,
                    Name     = definition.Name,
                    Platform = definition.Platform,
                    DeviceId = definition.DeviceId,
                    Icon     = actuator.Icon,
                });
                configs.Add(config.Key, config.Value);
            }

            return(configs);
        }
        public IList <ConfigParameterDefinition> GetConfigParameters(KeyedCollection <string, ConfigParameter> configParameters, ConfigParameterPage page)
        {
            List <ConfigParameterDefinition> configParametersDefinitions = new List <ConfigParameterDefinition>();

            switch (page)
            {
            case ConfigParameterPage.Connectivity:
                configParametersDefinitions.Add(ConfigParameterDefinition.CreateStringParameter(ConfigParameterNames.TenantUrl, string.Empty));
                configParametersDefinitions.Add(ConfigParameterDefinition.CreateEncryptedStringParameter(ConfigParameterNames.ApiKey, string.Empty));
                configParametersDefinitions.Add(ConfigParameterDefinition.CreateStringParameter(ConfigParameterNames.LogFileName, string.Empty));
                break;

            case ConfigParameterPage.Global:
                configParametersDefinitions.Add(ConfigParameterDefinition.CreateCheckBoxParameter(ConfigParameterNames.IncludeBuiltInGroups, false));
                configParametersDefinitions.Add(ConfigParameterDefinition.CreateCheckBoxParameter(ConfigParameterNames.IncludeAppGroups, false));
                configParametersDefinitions.Add(ConfigParameterDefinition.CreateDividerParameter());
                configParametersDefinitions.Add(ConfigParameterDefinition.CreateDropDownParameter(ConfigParameterNames.UserDeprovisioningAction, new string[] { "Delete", "Deactivate" }, false, "Deactivate"));
                configParametersDefinitions.Add(ConfigParameterDefinition.CreateCheckBoxParameter(ConfigParameterNames.ActivateNewUsers, false));
                configParametersDefinitions.Add(ConfigParameterDefinition.CreateCheckBoxParameter(ConfigParameterNames.SendActivationEmailToNewUsers, false));

                break;

            case ConfigParameterPage.Partition:
                break;

            case ConfigParameterPage.RunStep:
                break;
            }

            return(configParametersDefinitions);
        }
Esempio n. 27
0
        /// <summary>
        /// Gets the list of configuration parameters for the management agent
        /// </summary>
        /// <param name="configParameters">The list of configuration parameters</param>
        /// <param name="page">The page to get the configuration parameters for</param>
        /// <returns>A list of ConfigParameterDefinition objects</returns>
        public IList <ConfigParameterDefinition> GetConfigParameters(KeyedCollection <string, ConfigParameter> configParameters, ConfigParameterPage page)
        {
            List <ConfigParameterDefinition> configParametersDefinitions = new List <ConfigParameterDefinition>();

            switch (page)
            {
            case ConfigParameterPage.Connectivity:
                configParametersDefinitions.Add(ConfigParameterDefinition.CreateStringParameter(MAParameterNames.LogPath, string.Empty));
                break;

            case ConfigParameterPage.Global:
                break;

            case ConfigParameterPage.Partition:
                break;

            case ConfigParameterPage.RunStep:
                break;

            case ConfigParameterPage.Capabilities:
                break;
            }

            return(configParametersDefinitions);
        }
Esempio n. 28
0
 /// <summary>
 /// Initializes a new instance of this class.
 /// </summary>
 /// <param name="subsystems">Collection of subsystems to be used by this class.</param>
 public FileSystem(SubSystems subsystems)
     : base(subsystems)
 {
     m_textcache       = new KeyedCollection <String, TextFile>(x => x.Filepath, StringComparer.OrdinalIgnoreCase);
     m_titleregex      = new Regex(@"^\s*\[(.+?)\]\s*$", RegexOptions.IgnoreCase);
     m_parsedlineregex = new Regex(@"^\s*(.+?)\s*=\s*(.+?)\s*$", RegexOptions.IgnoreCase);
 }
Esempio n. 29
0
        /// <summary>
        /// Converts an existing AttributeChange to a new AttributeChange of type 'replace'
        /// </summary>
        /// <param name="csentry">The CSEntryChange to apply the AttributeChange to</param>
        /// <param name="attribute">The attribute to create the AttributeChange for</param>
        /// <param name="values">The values to assign</param>
        /// <param name="existingChange">The existing attribute change that was found on the CSEntryChange</param>
        private static void ConvertAttributeChangeToReplace(this KeyedCollection <string, AttributeChange> attributeChanges, ObjectModificationType objectModificationType, AcmaSchemaAttribute attribute, IList <object> values, AttributeChange existingChange)
        {
            TypeConverter.ThrowOnAnyInvalidDataType(values);

            attributeChanges.Remove(existingChange);

            switch (objectModificationType)
            {
            case ObjectModificationType.Add:
                attributeChanges.Add(AttributeChange.CreateAttributeAdd(attribute.Name, values));
                break;

            case ObjectModificationType.Delete:
                throw new DeletedObjectModificationException();

            case ObjectModificationType.Replace:
                attributeChanges.Add(AttributeChange.CreateAttributeAdd(attribute.Name, values));
                break;

            case ObjectModificationType.Update:
                attributeChanges.Add(AttributeChange.CreateAttributeReplace(attribute.Name, values));
                break;

            case ObjectModificationType.Unconfigured:
            case ObjectModificationType.None:
            default:
                break;
            }
        }
Esempio n. 30
0
        /// <summary>
        /// ConfigurationProvider for testing use only.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        /// <param name="path">String containing the file path to load configuration from.</param>
        /// <param name="sections">ConfigurationSections.</param>
        internal ConfigurationProvider(Uri serviceName, string path, KeyedCollection <string, ConfigurationSection> sections)
        {
            _serviceNameUri = serviceName;
            _serviceName    = _serviceNameUri.Segments[_serviceNameUri.Segments.Length - 1];

            LoadConfiguration(path, sections);
        }
Esempio n. 31
0
        /// <summary>
        /// Converts an AttributeChange of type 'update' to a new AttributeChange of type 'update'
        /// </summary>
        /// <param name="csentry">The CSEntryChange to apply the AttributeChange to</param>
        /// <param name="attribute">The attribute to create the AttributeChange for</param>
        /// <param name="valueChanges">The value changes to apply</param>
        /// <param name="existingChange">The existing attribute change that was found on the CSEntryChange</param>
        private static void ConvertAttributeChangeUpdateFromUpdate(this KeyedCollection <string, AttributeChange> attributeChanges, ObjectModificationType objectModificationType, AcmaSchemaAttribute attribute, IList <ValueChange> valueChanges, AttributeChange existingChange)
        {
            IList <ValueChange> mergedList = MergeValueChangeLists(attribute, existingChange.ValueChanges, valueChanges);

            attributeChanges.Remove(existingChange);

            switch (objectModificationType)
            {
            case ObjectModificationType.Add:
                throw new InvalidOperationException("The attribute change type is not valid for the object modification type");

            case ObjectModificationType.Delete:
                throw new DeletedObjectModificationException();

            case ObjectModificationType.Replace:
                throw new InvalidOperationException("The attribute change type is not valid for the object modification type");

            case ObjectModificationType.Update:
                attributeChanges.Add(AttributeChange.CreateAttributeUpdate(attribute.Name, mergedList));
                break;

            case ObjectModificationType.None:
            case ObjectModificationType.Unconfigured:
            default:
                throw new UnknownOrUnsupportedModificationTypeException(objectModificationType);
            }
        }
Esempio n. 32
0
        public unsafe static KeyedCollection <TKey, TValue> CopyKeyedCollection <TKey, TValue>(
            KeyedCollection <TKey, TValue> src,
            KeyedCollection <TKey, TValue> dst)
        {
            object osrc = src;
            // pointer to a structure that is a template for the instance variables
            // of KeyedCollection<TKey, TValue>
            TKeyedCollection *psrc   = (TKeyedCollection *)(*((int *)&psrc + 1));
            object            odst   = dst;
            TKeyedCollection *pdst   = (TKeyedCollection *)(*((int *)&pdst + 1));
            object            srcObj = null;
            object            dstObj = null;
            int *i = (int *)&i; // helps me find the stack

            i[2]            = (int)psrc->_01_items;
            dstObj          = CopyList <TValue>(srcObj as List <TValue>);
            pdst->_01_items = (uint)i[1];
            // there is no dictionary if the # items < threshold
            if (psrc->_04_dict != 0)
            {
                i[2]           = (int)psrc->_04_dict;
                dstObj         = CopyDict <TKey, TValue>(srcObj as Dictionary <TKey, TValue>);
                pdst->_04_dict = (uint)i[1];
            }

            pdst->_03_comparer  = psrc->_03_comparer;
            pdst->_05_keyCount  = psrc->_05_keyCount;
            pdst->_06_threshold = psrc->_06_threshold;
            return(dst);
        }
Esempio n. 33
0
        public static IDictionary <TKey, TValue> GetDictionary
        <TKey, TValue>(
            this KeyedCollection <TKey, TValue> collection)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }
            MethodInfo propGet =
                typeof(KeyedCollection <TKey, TValue>).GetTypeInfo()
                .DeclaredProperties
                .Where(
                    f =>
                    f.Name
                    == "Dictionary")
                .Select(
                    f =>
                    f.GetMethod)
                .Where(
                    gm =>
                    gm != null)
                .FirstOrDefault(
                    gm =>
                    gm.IsFamily);

            if (propGet == null)
            {
                throw new InvalidOperationException(
                          "Could not get dictionary property from KeyedCollection");
            }
            object obj = propGet.Invoke(collection, new object[0]);

            return((IDictionary <TKey, TValue>)obj);
        }
Esempio n. 34
0
 public FilesCache(long maxBufferSize,long maxOverrideSize)
 {
     _maxBufferSize = maxBufferSize;
     _maxOverrideSize = maxOverrideSize;
     _files = new KeyedCollection<Stream>();
     _freeFiles = new LightCollection<string>();
     _isOnQuotaOverride = false;
 }
Esempio n. 35
0
		public SpriteSystem(SubSystems subsystems)
			: base(subsystems)
		{
			m_spritefiles = new KeyedCollection<String, SpriteFile>(x => x.Filepath, StringComparer.OrdinalIgnoreCase);
			m_palettefilecache = new Dictionary<String, Texture2D>(StringComparer.OrdinalIgnoreCase);
			m_fontcache = new KeyedCollection<String, Font>(x => x.Filepath, StringComparer.OrdinalIgnoreCase);
			m_fontlinemapregex = new Regex("(\\S+)\\s?(\\d+)?\\s?(\\d+)?", RegexOptions.IgnoreCase);
			m_loader = new PcxLoader(this);
		}
Esempio n. 36
0
 protected TeamObject(TeamObject copy)
     : base(copy)
 {
     Name = copy.Name;
     MapId = copy.MapId;
     PrimaryColor = copy.PrimaryColor;
     SecondaryColor = copy.SecondaryColor;
     points = ((MapComponentCollection<MapPoint>)copy.Points).Clone();
 }
Esempio n. 37
0
		public EvaluationSystem(SubSystems subsystems)
			: base(subsystems)
		{
			m_expressioncache = new KeyedCollection<String, Expression>(x => x.ToString(), StringComparer.OrdinalIgnoreCase);
			m_tokenizer = new Tokenizer();
			m_treebuilder = new TreeBuilder(this);
			m_compiler = new Compiler();

			//var exp = CreateExpression("0.0 = [-10, 10]");
			//var result = exp.Evaluate(null);
		}
Esempio n. 38
0
 protected MapObject(MapObject copy)
     : base(copy)
 {
     Name = copy.Name;
     Width = copy.Width;
     Height = copy.Height;
     Tech = copy.Tech;
     barriers = ((MapComponentCollection<MapComponent>)copy.Barriers).Clone();
     tables = ((MapComponentCollection<MapTables>)copy.Tables).Clone();
     beacons = ((MapComponentCollection<MapBeacon>)copy.Beacons).Clone();
 }
 private void UseConfiguration(ConfigurationPackage configPackage, string configurationSectionName)
 {
     if (!configPackage.Settings.Sections.Contains(configurationSectionName))
     {
         this.configurationProperties = null;
     }
     else
     {
         this.configurationProperties = configPackage.Settings.Sections[configurationSectionName].Parameters;
     }
 }
Esempio n. 40
0
		public Collection(Drawing.SpriteManager sprites, Animations.AnimationManager animations, Audio.SoundManager sounds, Drawing.FontMap fontmap)
		{
			if (sprites == null) throw new ArgumentNullException("sprites");
			if (animations == null) throw new ArgumentNullException("animations");
			if (sounds == null) throw new ArgumentNullException("sounds");
			if (fontmap == null) throw new ArgumentNullException("fontmap");

			m_elements = new KeyedCollection<String, Elements.Base>(x => x.Name, StringComparer.OrdinalIgnoreCase);
			m_spritemanager = sprites;
			m_animationmanager = animations;
			m_soundmanager = sounds;
			m_fontmap = fontmap;
		}
 private void ChooseMergeItem(string id, KeyedCollection<string, SubscriptionItem> previousAuxList, KeyedCollection<string, FeedItem> currentAuxList, MergeResult result)
 {
     var previous = previousAuxList.Take(id);
     var current = currentAuxList.Take(id);
     if (previous.LastUpdatedTime == current.LastUpdatedTime)
     {
         result.AddItem(previous, ItemMergeStatus.NoChangedItem);
     }
     else
     {
         previous.Update(current);
         result.AddItem(previous, ItemMergeStatus.UpdatedItem);
     }
 }
Esempio n. 42
0
		/// <summary>
		/// Initializes a new instance of this class.
		/// </summary>
		/// <param name="filepath">Path to the AIR file that the Animations were parsed out of.</param>
		/// <param name="animations">Collection of Animations that were parsed of the AIR file.</param>
		public AnimationManager(String filepath, KeyedCollection<Int32, Animation> animations)
		{
			if (filepath == null) throw new ArgumentNullException("filepath");
			if (animations == null) throw new ArgumentNullException("animations");

			m_filepath = filepath;
			m_animations = animations;
			m_foreignanimation = false;
			m_currentanimation = null;
			m_finishedanimation = false;
			m_animationinloop = false;
			m_animationtime = 0;
			m_elementswitchtime = 0;
		}
        public MergeResult Merge(IEnumerable<SubscriptionItem> previousItems, IEnumerable<FeedItem> currentItems)
        {
            var result = new MergeResult();
            var previousAuxList = new KeyedCollection<string, SubscriptionItem>(x => x.Id, previousItems);
            var currentAuxList = new KeyedCollection<string, FeedItem>(x => x.Id, currentItems);

            var previousIds = previousAuxList.Select(x => x.Id).ToArray();
            foreach (var id in previousIds)
            {
                if (!currentAuxList.Contains(id))
                    ChooseRemovedItem(id, previousAuxList, result);
                else
                    ChooseMergeItem(id, previousAuxList, currentAuxList, result);
            }

            var newIds = currentAuxList.Select(x => x.Id).ToArray();
            foreach (var id in newIds)
                ChooseNewItem(id, currentAuxList, result);

            return result;
        }
Esempio n. 44
0
        public StateManager CreateManager(Combat.Character character, ReadOnlyList<String> filepaths)
        {
            if (character == null) throw new ArgumentNullException("character");
            if (filepaths == null) throw new ArgumentNullException("filepaths");

            KeyedCollection<Int32, State> states = new KeyedCollection<Int32, State>(x => x.Number);

            foreach (String filepath in filepaths)
            {
                ReadOnlyKeyedCollection<Int32, State> loadedstates = GetStates(filepath);
                foreach (State state in loadedstates)
                {
                    if (states.Contains(state.Number) == true) states.Remove(state.Number);
                    states.Add(state);
                }
            }

            foreach (State state in m_internalstates)
            {
                if (states.Contains(state.Number) == false) states.Add(state);
            }

            return new StateManager(this, character, new ReadOnlyKeyedCollection<Int32, State>(states));
        }
Esempio n. 45
0
		/// <summary>
		/// Creates Animations from a xnaMugen.IO.TextFile.
		/// </summary>
		/// <param name="textfile">A textfile whose xnaMugen.IO.TextSection can be used to create Animations.</param>
		/// <returns>A collection of Animations created from the supplied textfile.</returns>
		public KeyedCollection<Int32, Animation> LoadAnimations(TextFile textfile)
		{
			if (textfile == null) throw new ArgumentNullException("textfile");

			KeyedCollection<Int32, Animation> animations = new KeyedCollection<Int32, Animation>(x => x.Number);

			foreach (TextSection section in textfile)
			{
				Animation animation = CreateAnimation(section);
				if (animation != null)
				{
					if (animations.Contains(animation.Number) == false)
					{
						animations.Add(animation);
					}
					else
					{
						Log.Write(LogLevel.Warning, LogSystem.AnimationSystem, "Duplicate animation #{0}. Discarding duplicate.", animation.Number);
					}
				}
			}

			return animations;
		}
Esempio n. 46
0
 public MapObject()
 {
     barriers = new MapComponentCollection<MapComponent>();
     tables = new MapComponentCollection<MapTables>();
     beacons = new MapComponentCollection<MapBeacon>();
 }
        /// <summary>
        /// Returns the endpoint description with the provided name, throwing an exception if it is not present.
        /// </summary>
        /// <param name="endpoints">The endpoint collection.</param>
        /// <param name="endpointName">the name of the endpoint to return.</param>
        /// <returns>The endpoint with the provided name.</returns>
        /// <exception cref="KeyNotFoundException">The endpoint with the provided name was not found.</exception>
        private static EndpointResourceDescription GetEndpoint(
            KeyedCollection<string, EndpointResourceDescription> endpoints,
            string endpointName)
        {
            if (!endpoints.Contains(endpointName))
            {
                throw new KeyNotFoundException(
                    $"Endpoint \"{endpointName}\" not found in service manifest. Ensure the service has a TCP endpoint with that name.");
            }

            return endpoints[endpointName];
        }
Esempio n. 48
0
 public override void EndInitialize(KeyedCollection<string, IShape> list)
 {
     Open = false;
 }
Esempio n. 49
0
 public PluginApplication()
 {
     _Objects = new KeyedCollection<IPluginObject>();
 }
Esempio n. 50
0
 public TeamObject()
 {
     PrimaryColor = new TeamColor(255, 255, 255, 255);
     SecondaryColor = new TeamColor(255, 255, 255, 255);
     points = new MapComponentCollection<MapPoint>();
 }
Esempio n. 51
0
		/// <summary>Computes the efficiency of a roster as a percentage of the possible total starting lineup spots that are filled over a period of time.</summary>
		/// <param name="startDate">The date computation should begin.</param>
		/// <param name="endDate">The date computation should end.</param>
		/// <param name="startingLineups">The starting lineups to use.</param>
		/// <returns>Returns the utilization as a percentage of available starting lineup spots that were filled.</returns>
		public double ComputeUtilization(DateTime startDate, DateTime endDate, KeyedCollection<DateTime, StartingLineup> startingLineups)
		{
			int availablePositions = this.startingLineupPositions.Count * this.GetGameDays(startDate, endDate).Count;
			int usedPositions = startingLineups.Sum(startingLineup => startingLineup.Assignments.Count);
			return (double)usedPositions / (double)availablePositions;
		}
Esempio n. 52
0
 public void EndInitialize(KeyedCollection<string, IShape> list)
 {
 }
Esempio n. 53
0
 public PluginManager()
 {
     _Assemblies = new KeyedCollection<Assembly>();
     _Plugins = new KeyedCollection<PluginLoadInfo>();
     _PluginsLoaded = new KeyedCollection<PluginBase>();
 }
Esempio n. 54
0
 public MessageParserPlugin()
 {
     Data = new KeyedCollection<String, MessageParserData>();
 }
Esempio n. 55
0
		public ChooseFdoProjectForm(ParatextLexiconPluginFdoUI ui, KeyedCollection<string, FdoCache> fdoCacheCache)
		{
			// This call is required by the Windows Form Designer.
			InitializeComponent();
			m_ui = ui;
			m_fdoCacheCache = fdoCacheCache;
			PopulateLanguageProjectsList(Dns.GetHostName(), true);
		}
Esempio n. 56
0
        ReadOnlyKeyedCollection<Int32, State> GetStates(String filepath)
        {
            if (filepath == null) throw new ArgumentNullException("filepath");

            if (m_statefiles.ContainsKey(filepath) == true) return m_statefiles[filepath];

            KeyedCollection<Int32, State> states = new KeyedCollection<Int32, State>(x => x.Number);
            TextFile textfile = GetSubSystem<IO.FileSystem>().OpenTextFile(filepath);

            TextSection laststatesection = null;
            List<StateController> controllers = null;

            foreach (TextSection textsection in textfile)
            {
                if (m_statertitleregex.IsMatch(textsection.Title) == true)
                {
                    if (laststatesection != null)
                    {
                        State newstate = CreateState(laststatesection, controllers);
                        if (newstate != null) AddStateToCollection(states, newstate);

                        laststatesection = null;
                        controllers = null;
                    }

                    laststatesection = textsection;
                    controllers = new List<StateController>();
                }
                else
                {
                    StateController controller = CreateController(textsection);
                    if (controller != null && controllers != null) controllers.Add(controller);
                }
            }

            if (laststatesection != null)
            {
                State newstate = CreateState(laststatesection, controllers);
                if (newstate != null) AddStateToCollection(states, newstate);

                laststatesection = null;
                controllers = null;
            }

            ReadOnlyKeyedCollection<Int32, State> ro_states = new ReadOnlyKeyedCollection<Int32, State>(states);
            m_statefiles.Add(filepath, ro_states);
            return ro_states;
        }
 private void ChooseRemovedItem(string id, KeyedCollection<string, SubscriptionItem> previousAuxList, MergeResult result)
 {
     result.AddItem(previousAuxList.Take(id), ItemMergeStatus.RemovedItem);
 }
 private void ChooseNewItem(string id, KeyedCollection<string, FeedItem> currentAuxList, MergeResult result)
 {
     result.AddItem(new SubscriptionItem(currentAuxList.Take(id)), ItemMergeStatus.NewItem);
 }
Esempio n. 59
0
 public AlertSender()
 {
     _TicketStati = new TicketStatusCollection();
 }
Esempio n. 60
-1
        static void AddStateToCollection(KeyedCollection<Int32, State> collection, State state)
        {
            if (collection == null) throw new ArgumentNullException("collection");
            if (state == null) throw new ArgumentNullException("state");

            if (collection.Contains(state.Number) == true)
            {
                Log.Write(LogLevel.Warning, LogSystem.StateSystem, "Duplicate state #{0}. Discarding duplicate", state.Number);
            }
            else
            {
                collection.Add(state);
            }
        }