private void UseConfiguration(ConfigurationPackage configPackage, string configurationSectionName)
 {
     if (!configPackage.Settings.Sections.Contains(configurationSectionName))
     {
         this.configurationProperties = null;
     }
     else
     {
         this.configurationProperties = configPackage.Settings.Sections[configurationSectionName].Parameters;
     }
 }
        public HealthIndexCalculator(ServiceContext serviceParamaters)
        {
            if (serviceParamaters.CodePackageActivationContext.GetConfigurationPackageNames().Contains("Config"))
            {
                ConfigurationPackage configPackage = serviceParamaters.CodePackageActivationContext.GetConfigurationPackageObject("Config");

                this.UpdateConfigSettings(configPackage.Settings);

                serviceParamaters.CodePackageActivationContext.ConfigurationPackageModifiedEvent
                    += this.CodePackageActivationContext_ConfigurationPackageModifiedEvent;
            }
            else
            {
                this.calculationMode = CalculationMode.Simple;
            }
        }
        private void LoadPackage(ConfigurationPackage config, bool reload = false)
        {
            if (reload)
            {
                // Rememove the old keys on re-load
                Data.Clear();
            }

            foreach (var section in config.Settings.Sections)
            {
                foreach (var param in section.Parameters)
                {
                    Data[$"{section.Name}:{param.Name}"] = param.IsEncrypted ? param.DecryptValue().ConvertToUnsecureString() : param.Value;
                }
            }
        }
Example #4
0
        protected override IEnumerable <ServiceInstanceListener> CreateServiceInstanceListeners()
        {
            // get some configuration values from the service's config package (PackageRoot\Config\Settings.xml)
            ConfigurationPackage config  = this.ServiceInitializationParameters.CodePackageActivationContext.GetConfigurationPackageObject("Config");
            ConfigurationSection section = config.Settings.Sections["VisualObjectsBoxSettings"];

            int    numObjects  = int.Parse(section.Parameters["ObjectCount"].Value);
            string serviceName = section.Parameters["ServiceName"].Value;
            string appName     = this.ServiceInitializationParameters.CodePackageActivationContext.ApplicationName;

            return(new[]
            {
                new ServiceInstanceListener(
                    initParams => new WebCommunicationListener(new VisualObjectsBox(new Uri(appName + "/" + serviceName), numObjects), "visualobjects", "data", initParams))
            });
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="ServiceBusCommunicationListener" /> class.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="serviceBusConnectionString">The service bus connection string.</param>
 /// <param name="serviceBusQueueName">Name of the service bus queue.</param>
 private ServiceBusCommunicationListener(ServiceContext context, string serviceBusConnectionString, string serviceBusQueueName)
 {
     if (string.IsNullOrWhiteSpace(this.serviceBusConnectionString) || string.IsNullOrWhiteSpace(this.serviceBusQueueName))
     {
         ICodePackageActivationContext codePackageContext = context.CodePackageActivationContext;
         ConfigurationPackage          configPackage      = codePackageContext.GetConfigurationPackageObject("Config");
         ConfigurationSection          configSection      = configPackage.Settings.Sections["ServiceBusSettings"];
         this.serviceBusConnectionString = serviceBusConnectionString ?? configSection.Parameters["ServiceBusConnectionString"].Value;
         this.serviceBusQueueName        = serviceBusQueueName ?? configSection.Parameters["ServiceBusQueueName"].Value;
     }
     else
     {
         this.serviceBusConnectionString = serviceBusQueueName;
         this.serviceBusQueueName        = serviceBusQueueName;
     }
 }
        public KeyVaultSecretManager(
            ConfigurationPackage configurationPackage,
            AzureADConfiguration AzureAd,
            ILoggerFactory logFactory)
        {
            this.Logger  = logFactory.CreateLogger <StorageConfiguration>();
            this.AzureAD = AzureAd;

            var section = configurationPackage.Settings.Sections["AzureResourceManager"].Parameters;

            KeyVaultUrl = section["Azure.KeyVault.Uri"].Value;

            KeyVaultClient.AuthenticationCallback callback =
                (authority, resource, scope) => AzureAD.GetTokenFromClientSecret(authority, resource);

            Client = new KeyVaultClient(callback);
        }
Example #7
0
 /// <summary>
 /// Creates a configuration file for NT Service if NTServiceSettings section exists in Configuration Package
 /// </summary>
 /// <param name="package">configuration package object</param>
 /// <param name="filePath">file path where settings need to be stored</param>
 internal static void CreateConfigurationForNtService(ConfigurationPackage package, string filePath, FabricClient fabricClient, ServiceContext serviceContext)
 {
     if (package.Settings != null && package.Settings.Sections.Contains(NtServiceSectionName))
     {
         try
         {
             ValidateNTServiceSettings(package.Settings.Sections[NtServiceSectionName], fabricClient, serviceContext);
             ComposeSettingsXml(package.Settings.Sections[NtServiceSectionName], filePath);
             ServiceEventSource.Current.InfoMessage("Successfully stored new settings at {0}", filePath);
         }
         catch (Exception)
         {
             ServiceEventSource.Current.InfoMessage("Failed to save new settings at {0}", filePath);
             throw;
         }
     }
 }
Example #8
0
        public Service(StatelessServiceContext serviceContext) : base(serviceContext)
        {
            ServiceContext context = serviceContext;

            ConfigurationPackage config  = context.CodePackageActivationContext.GetConfigurationPackageObject("Config");
            ConfigurationSection section = config.Settings.Sections["VisualObjectsBoxSettings"];

            int    numObjects  = int.Parse(section.Parameters["ObjectCount"].Value);
            string serviceName = section.Parameters["ServiceName"].Value;
            string appName     = context.CodePackageActivationContext.ApplicationName;

            this.actorServiceUri = new Uri(appName + "/" + serviceName);

            this.objectBox = VisualObjectsBox.Current;

            this.actorIds = this.CreateVisualObjectActorIds(numObjects);
        }
        public ServiceConfigReader(string configPackageName)
        {
            var context = FabricRuntime.GetActivationContext();

            if (context.GetConfigurationPackageNames().Contains(configPackageName))
            {
                this.ConfigurationPackage = context.GetConfigurationPackageObject(configPackageName);

                this.UpdateConfigSettings();

                context.ConfigurationPackageModifiedEvent += ConfigPackageChangedEvent;
            }
            else
            {
                throw new ArgumentException("No Matching Config Package Found");
            }
        }
Example #10
0
        private static void UpdateEventFlowConfiguration()
        {
            string appInsightsKey = Environment.GetEnvironmentVariable("EventFlow:ApplicationInsightsKey");
            string logFilter      = Environment.GetEnvironmentVariable("EventFlow:LogFilter");

            CodePackageActivationContext activationContext = FabricRuntime.GetActivationContext();
            ConfigurationPackage         configPackage     = activationContext.GetConfigurationPackageObject("Config");
            string configFilePath = Path.Combine(configPackage.Path, "eventFlowConfig.json");
            string content        = File.ReadAllText(configFilePath);

            EventFlowOptions options = JsonConvert.DeserializeObject <EventFlowOptions>(content);

            options.Outputs[0].InstrumentationKey = appInsightsKey;
            options.Filters[0].Include            = logFilter;

            File.WriteAllText(configFilePath, JsonConvert.SerializeObject(options));
        }
        private string getSubscriptionId(ConfigurationPackage config)
        {
            if (!config.Settings.Sections.Contains("DataLake"))
            {
                throw new ArgumentException(string.Format(ParameterCannotBeNullFormat, "DataLake"), "DataLake");
            }

            var datalakeConfig = config.Settings.Sections["DataLake"];

            if (!datalakeConfig.Parameters.Contains("SubscriptionId"))
            {
                throw new ArgumentException(string.Format(ParameterCannotBeNullFormat, "SubscriptionId"),
                                            "SubscriptionId");
            }

            return(datalakeConfig.Parameters["SubscriptionId"].Value);
        }
        /// <summary>
        /// Called when the service is started
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override Task OnOpenAsync(CancellationToken cancellationToken)
        {
            // Get the configuration settings and monitor for changes.
            this.Context.CodePackageActivationContext.ConfigurationPackageModifiedEvent += this.CodePackageActivationContext_ConfigurationPackageModifiedEvent;

            ConfigurationPackage configPackage = this.Context.CodePackageActivationContext.GetConfigurationPackageObject("Config");

            if (null != configPackage)
            {
                lock (thisLock)
                {
                    this._logger = InitializeLogger(configPackage.Settings);
                }
            }

            return(base.OnOpenAsync(cancellationToken));
        }
Example #13
0
        /// <summary>
        /// Init setups in any configuration values
        /// </summary>
        private void Init()
        {
            ConfigurationPackage configPackage = this.Context.CodePackageActivationContext.GetConfigurationPackageObject("Config");
            String connectionString            = configPackage.Settings.Sections["DB"].Parameters["MongoConnectionString"].Value;

            bool.TryParse(configPackage.Settings.Sections["DB"].Parameters["MongoEnableSSL"].Value, out var enableSsl);
            try
            {
                tradeLogger = MongoDBTradeLogger.Create(connectionString, enableSsl, databaseName, collectionName);
            }
            catch (Exception ex)
            {
                ServiceEventSource.Current.ServiceMessage(this.Context, $"Error initializing connection to logger ${ex.Message}");
                BackOff(CancellationToken.None).GetAwaiter().GetResult();
                Init();
            }
        }
Example #14
0
        /// <summary>
        /// This method is used to create an instance of the AzureBlobBackupManager
        /// </summary>
        private void SetupBackupManager()
        {
            // change the logic here for your own partition scenario
            //
            string partitionId = this.Context.PartitionId.ToString("N");
            long   minKey      = ((Int64RangePartitionInformation)this.Partition.PartitionInfo).LowKey;
            long   maxKey      = ((Int64RangePartitionInformation)this.Partition.PartitionInfo).HighKey;

            if (this.Context.CodePackageActivationContext != null)
            {
                ICodePackageActivationContext codePackageContext =
                    this.Context.CodePackageActivationContext;

                ConfigurationPackage configPackage =
                    codePackageContext.GetConfigurationPackageObject("Config");

                // change the section name to match your service name
                ConfigurationSection configSection =
                    configPackage.Settings.Sections["Stateful1.Settings"];

                string backupSettingValue = configSection.Parameters["BackupMode"].Value;

                if (string.Equals(backupSettingValue, "none", StringComparison.InvariantCultureIgnoreCase))
                {
                    this.backupStorageType = BackupManagerType.None;
                }
                else if (string.Equals(backupSettingValue, "azure", StringComparison.InvariantCultureIgnoreCase))
                {
                    this.backupStorageType = BackupManagerType.Azure;

                    // change the section name to match your service name
                    ConfigurationSection azureBackupConfigSection =
                        configPackage.Settings.Sections["Stateful1.BackupSettings.Azure"];

                    this.backupManager = new AzureBlobBackupManager(azureBackupConfigSection,
                                                                    partitionId, minKey, maxKey, codePackageContext.TempDirectory);
                }
                else
                {
                    throw new ArgumentException("Unknown backup type");
                }

                ServiceEventSource.Current.ServiceMessage(this, "Backup Manager Set Up");
            }
        }
Example #15
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public static void ConfigureApp(IAppBuilder appBuilder)
        {
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) =>
            {
                string certThumbprint;

                using (var cert2 = new X509Certificate2(certificate))
                {
                    certThumbprint = cert2.Thumbprint;
                }

                using (var store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
                {
                    store.Open(OpenFlags.ReadOnly);
                    var matchedCerts = store.Certificates.Find(X509FindType.FindByThumbprint, certThumbprint, true);

                    if (matchedCerts.Count > 0)
                    {
                        return(true);
                    }
                }

                return(errors == SslPolicyErrors.None);
            };

            ConfigurationPackage configurationPackage = GetConfigurationPackage();

            var client                 = CreateHttpClient(configurationPackage);
            var maxRetryCount          = GetMaxRetries(configurationPackage);
            var defaultBackoffInterval = TimeSpan.Zero;
            var operationRetrySettings = new OperationRetrySettings(
                maxRetryBackoffIntervalOnTransientErrors: defaultBackoffInterval,
                maxRetryBackoffIntervalOnNonTransientErrors: defaultBackoffInterval,
                defaultMaxRetryCount: maxRetryCount);

            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

            config.MessageHandlers.Add(new TelemetryHandler(() => new ApplicationInsightsTelemetryLogger(
                                                                CreateTelemetryClient(configurationPackage),
                                                                configurationPackage.Settings.Sections["Telemetry"].Parameters["ServiceFabricEndpoint"].Value)));
            config.MessageHandlers.Add(new ProbeHandler());
            config.MessageHandlers.Add(new GatewayHandler(new ServiceDiscoveryClientProxy(client, new HttpExceptionHandler(), operationRetrySettings)));
            appBuilder.UseWebApi(config);
        }
        static void AddStorageProviders(ClusterConfiguration clusterConfig, ConfigurationPackage appConfig)
        {
            var storageSettings = appConfig.Settings.Sections["Storage"].Parameters;

            clusterConfig.Globals.DataConnectionString = storageSettings["SiloStorageConnectionString"].Value;

            clusterConfig.Globals.ReminderServiceType = GlobalConfiguration.ReminderServiceProviderType.AzureTable;
            clusterConfig.Globals.DataConnectionStringForReminders = storageSettings["RemindersStorageConnectionString"].Value;

            var useJson    = bool.Parse(storageSettings["GrainsUseJsonFormat"].Value);
            var indentJson = useJson && bool.Parse(storageSettings["GrainsUseIndentedJsonFormat"].Value);

            clusterConfig.AddAzureTableStorageProvider(
                providerName: "Default",
                connectionString: storageSettings["GrainStorageConnectionString"].Value,
                useJsonFormat: useJson,
                indentJson: indentJson);
        }
Example #17
0
        private void ConfigureService()
        {
            if (this.Context.CodePackageActivationContext != null)
            {
                ConfigurationPackage configPackage = this.Context.CodePackageActivationContext.GetConfigurationPackageObject("Config");
                DataPackage          dataPackage   = this.Context.CodePackageActivationContext.GetDataPackageObject("ApplicationPackages");

                this.UpdateSettings(configPackage.Settings);
                this.UpdateApplicationPackageConfig(configPackage.Path);
                this.UpdateApplicationPackageData(dataPackage.Path);

                this.Context.CodePackageActivationContext.DataPackageModifiedEvent +=
                    this.CodePackageActivationContext_DataPackageModifiedEvent;

                this.Context.CodePackageActivationContext.ConfigurationPackageModifiedEvent +=
                    this.CodePackageActivationContext_ConfigurationPackageModifiedEvent;
            }
        }
Example #18
0
        public HomeController(IConfiguration configuration, IServiceBusQueue serviceBusQueueHelper, ConfigurationPackage configurationPackage)
        {
            IValidationServiceStateful _validationService = ServiceProxy.Create <IValidationServiceStateful>(
                new Uri("fabric:/DCT.ILR.Processing.POC/DCT.ILR.VadationServiceStateful"),
                new ServicePartitionKey(0));

            ConfigurationPackage _configurationPackage = configurationPackage;
            ServiceProxyFactory  serviceProxyFactory   = new ServiceProxyFactory(
                (c) => new FabricTransportServiceRemotingClientFactory(
                    serializationProvider: new ServiceRemotingJsonSerializationProvider()));

            _validationResultsService = serviceProxyFactory.CreateServiceProxy <IValidationServiceResults>(
                new Uri("fabric:/DCT.ILR.Processing.POC/DCT.ILR.Data"),
                new ServicePartitionKey(0L), TargetReplicaSelector.PrimaryReplica, "dataServiceRemotingListener");

            _serviceBusQueueHelper = serviceBusQueueHelper;
            StorageAccountName     = _configurationPackage.Settings.Sections["StorageAccount"].Parameters["IlrFileStorageAccontName"].Value;
            StorageAccountKey      = _configurationPackage.Settings.Sections["StorageAccount"].Parameters["IlrFileStorageAccontKey"].Value;
        }
        public static void Register()
        {
            ServiceRuntime.RegisterServiceAsync(
                Naming.ServiceType <RestApi>(),
                (context) =>
            {
                ConfigurationPackage configPackage = context.CodePackageActivationContext.GetConfigurationPackageObject(@"Config");
                ILogger serilog = new LoggerConfiguration()
                                  .WriteTo.Seq(configPackage.Settings.Sections[@"ResourceSettings"].Parameters[@"seqLocation"].Value)
                                  .CreateLogger();
                Log.Logger = serilog;
                return(new RestApi(context, serilog.Enrich <RestApi>(context)));
            })
            .GetAwaiter().GetResult();

            ServiceEventSource.Current.ServiceTypeRegistered(
                Process.GetCurrentProcess().Id,
                Naming.ServiceType <RestApi>());
        }
        public ServiceBusTopicListener(StatefulServiceContext args, Action <ServiceMessage> messageCallback, Action <Exception> loggerAction, ServiceBusTopicReceiverType receiverType)
        {
            ICodePackageActivationContext codePackageContext = args.CodePackageActivationContext;
            ConfigurationPackage          configPackage      = codePackageContext.GetConfigurationPackageObject("Config");
            ConfigurationSection          configSection      = configPackage.Settings.Sections[Constants.SB_CONFIG_SECTION];

            _connectionString = (configSection.Parameters[Constants.SB_CONN_STRING]).Value;
            _topicName        = (configSection.Parameters[Constants.SB_TOPIC]).Value;
            _subscriptionName = (configSection.Parameters[Constants.SB_SUBSCRIPTION]).Value;

            if (receiverType == ServiceBusTopicReceiverType.Standard)
            {
                _sbTopicReceiver = new ServiceBusTopicReceiver(_connectionString, _topicName, _subscriptionName, messageCallback, loggerAction);
            }
            else
            {
                _sbTopicReceiver = new ServiceBusTopicReceiver2(_connectionString, _topicName, _subscriptionName, messageCallback, loggerAction);
            }
        }
        public override void Load()
        {
            // TODO: react to configuration changes by listening to ConfiugrationPackageActivationContext.ConfigurationPackageModifiedEvent

            CodePackageActivationContext activationContext = FabricRuntime.GetActivationContext();
            ConfigurationPackage         configPackage     = activationContext.GetConfigurationPackageObject(this.configurationPackageName);

            foreach (var configurationSection in configPackage.Settings.Sections)
            {
                foreach (var property in configurationSection.Parameters)
                {
                    // We omit encrypted values due to security concerns--if you need them, use Service Fabric APIs to access them
                    if (!property.IsEncrypted)
                    {
                        Data[ConfigurationPath.Combine(configurationSection.Name, property.Name)] = property.Value;
                    }
                }
            }
        }
Example #22
0
 public static string GetConfigValue(string sectionName, string key, string configName = null)
 {
     if (string.IsNullOrEmpty(configName))
     {
         configName = DefaultConfigName;
     }
     using (var activationContext = FabricRuntime.GetActivationContext())
     {
         ConfigurationPackage config = activationContext.GetConfigurationPackageObject(configName);
         if (config.Settings.Sections.Contains(sectionName))
         {
             if (config.Settings.Sections[sectionName].Parameters.Contains(key))
             {
                 return(config.Settings.Sections[sectionName].Parameters[key].Value);
             }
         }
         return(null);
     }
 }
Example #23
0
        public FabricConfigProvider(string configurationSectionName)
        {
            CodePackageActivationContext activationContext = FabricRuntime.GetActivationContext();
            ConfigurationPackage         configPackage     = activationContext.GetConfigurationPackageObject("Config");

            if (!configPackage.Settings.Sections.Contains(configurationSectionName))
            {
                throw new ApplicationException($"Configuration section {configurationSectionName} not found");
            }
            var section = configPackage.Settings.Sections[configurationSectionName];
            var obj     = new JObject();

            foreach (var setting in section.Parameters)
            {
                obj.Add(setting.Name, setting.Value);
            }

            Config = obj.ToObject <TConfig>();
        }
        public FabricSettings(ConfigurationPackage package)
        {
            Package = package;
            ConfigurationSettings = Package.Settings;

            //**************************************************************
            //* Author : Jacob Atchley
            //* Date   : 08:29:2018 04:01 PM
            //* Comment: Bound to ServiceFabricSample/ApplicationPackageRoot/ApplicationManifest.xml
            //**************************************************************
            if (ConfigurationSettings.Sections.TryGetValue("MyConfigSection", out var configSection))
            {
                MyConfigurationSection = configSection;

                Db = GetSettingString("DbConnectionString");

                if (string.IsNullOrWhiteSpace(Db))
                {
                    throw new Exception("Could not get db connection string from configuration package");
                }

                TableStorage = GetSettingString("TableStorageConnectionString");

                if (string.IsNullOrWhiteSpace(TableStorage))
                {
                    throw new Exception("Could not get table storage connection string from configuration package");
                }

                SignalRConnectionString = GetSettingString("SignalRConnectionString");

                if (string.IsNullOrWhiteSpace(SignalRConnectionString))
                {
                    throw new Exception("Could not get signal r connection string from configuration package");
                }

                IsLocal = bool.TryParse(GetSettingString("IsLocal"), out var isLocalBoolean) && isLocalBoolean;
            }
            else
            {
                throw new Exception("Could not get my configuration section");
            }
        }
Example #25
0
        void ProcessEventHubMessage(string package)
        {
            var message = JsonConvert.DeserializeObject <ServiceMessage>(package);

            EndWithHttpPost(message).GetAwaiter().GetResult();

            ConfigurationPackage configPackage = this.Context.CodePackageActivationContext.GetConfigurationPackageObject("Config");
            ConfigurationSection configSection = configPackage.Settings.Sections[Constants.EH_CONFIG_SECTION];
            var connString = (configSection.Parameters[Constants.EH_CONN_STRING]).Value;
            var path       = (configSection.Parameters[Constants.EH_SENDTO_HUB_PATH]).Value;

            try
            {
                new EventHubSender(connString, path).Send(message).GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                LogError(e);
            }
        }
        private void InitializeConfiguration(ConfigurationPackage package)
        {
            string settingsDestinationPath = this.GetLocalPathForApplication(package.Path) + NtServicePath + "Settings.xml";

            try
            {
                NtServiceConfigurationUtility.CreateConfigurationForNtService(package, settingsDestinationPath, this.fabricClient, this.Context);
                if (package.Settings != null && package.Settings.Sections.Contains(settingsSectionName))
                {
                    this.ModifySettings(package.Settings.Sections[settingsSectionName]);
                }
                string healthMessage = "Settings validation was successful.";
                HealthManagerHelper.PostServiceHealthReport(this.fabricClient, this.Context, SettingsValidationProperty, healthMessage, HealthState.Ok, 1);
            }
            catch (Exception ex)
            {
                ServiceEventSource.Current.ErrorMessage("InitializeConfiguration failed with exception: {0}", ex);
                this.Partition.ReportFault(FaultType.Permanent);
            }
        }
Example #27
0
        internal static ConfigurationPackage CreateConfigurationPackage(string path = null)
        {
            // new ConfigurationPackage
            ConfigurationPackage config = (ConfigurationPackage)Activator.CreateInstance(typeof(ConfigurationPackage), nonPublic: true);

            if (!string.IsNullOrEmpty(path))
            {
                // ConfigurationPackage.Path = path
                PropertyInfo pathProp = typeof(ConfigurationPackage).GetProperty("Path");
                pathProp.SetValue(config, path, BindingFlags.NonPublic, null, null, CultureInfo.InvariantCulture);
            }

            // settings = new ();
            System.Fabric.Description.ConfigurationSettings settings = (System.Fabric.Description.ConfigurationSettings)Activator.CreateInstance(typeof(System.Fabric.Description.ConfigurationSettings), nonPublic: true);

            // config.Settings = settings;
            typeof(ConfigurationPackage).GetProperty("Settings").SetValue(config, settings);

            return(config);
        }
Example #28
0
 private void LoadConfiguration()
 {
     // Get the Health Check Interval configuration value.
     ConfigurationPackage pkg = Context.CodePackageActivationContext.GetConfigurationPackageObject("Config"); if (null != pkg)
     {
         if (true == pkg.Settings?.Sections?.Contains("Health"))
         {
             ConfigurationSection settings = pkg.Settings.Sections["Health"];
             if (true == settings?.Parameters.Contains("HealthCheckIntervalSeconds"))
             {
                 long lValue = 0;
                 ConfigurationProperty prop = settings.Parameters["HealthCheckIntervalSeconds"]; if (long.TryParse(prop?.Value, out lValue))
                 {
                     _interval    = TimeSpan.FromSeconds(Math.Max(30, lValue)); _healthTimer?.Dispose();
                     _healthTimer = new Timer(ReportHealthAndLoad, null, _interval, _interval);
                 }
             }
         }
     }
 }
Example #29
0
        internal void InitializeSettingsFromConfigurationPackage(ConfigurationPackage configurationPackage)
        {
            //Guard.NotNull(configurationPackage, nameof(configurationPackage));

            if (configurationPackage.Settings?.Sections == null ||
                !configurationPackage.Settings.Sections.Contains(ConfigurationSectionName))
            {
                // fallback to default setup of LoggerFactory
                return;
            }

            KeyedCollection <string, ConfigurationProperty> configurationParameters =
                configurationPackage.Settings.Sections[ConfigurationSectionName].Parameters;

            if (!configurationParameters.Contains(LoggerKey))
            {
                return;
            }

            this.Logger = configurationParameters[LoggerKey].Value;
        }
        internal void InitializeSettingsFromConfigurationPackage(ConfigurationPackage configurationPackage)
        {
            //Guard.NotNull(configurationPackage, nameof(configurationPackage));

            if (configurationPackage.Settings?.Sections == null ||
                !configurationPackage.Settings.Sections.Contains(ConfigurationSectionName))
            {
                // fallback to default setup of LoggerFactory
                return;
            }

            KeyedCollection<string, ConfigurationProperty> configurationParameters =
                configurationPackage.Settings.Sections[ConfigurationSectionName].Parameters;

            if (!configurationParameters.Contains(LoggerKey))
            {
                return;
            }

            this.Logger = configurationParameters[LoggerKey].Value;
        }
Example #31
0
        public static StatefulServiceContext GetMockContext()
        {
            //build ConfigurationSectionCollection
            var configSections = new ConfigurationSectionCollection();

            //Build ConfigurationSettings
            var configSettings = CreateConfigurationSettings(configSections);

            ConfigurationSection userStoreConfig = CreateConfigurationSection("UserStoreConfig");

            configSections.Add(userStoreConfig);

            ConfigurationProperty appInsightsKey = CreateConfigurationSectionParameters("Admin_AppInsights_InstrumentationKey", "");

            userStoreConfig.Parameters.Add(appInsightsKey);

            ConfigurationProperty teamName = CreateConfigurationSectionParameters("TeamName", "");

            userStoreConfig.Parameters.Add(teamName);

            //Build ConfigurationPackage
            ConfigurationPackage configPackage = CreateConfigurationPackage(configSettings);
            var context = new MockCodePackageActivationContext(
                "fabric:/MockApp",
                "MockAppType",
                "Code",
                "1.0.0.0",
                Guid.NewGuid().ToString(),
                @"C:\logDirectory",
                @"C:\tempDirectory",
                @"C:\workDirectory",
                "ServiceManifestName",
                "1.0.0.0")
            {
                ConfigurationPackage = configPackage
            };

            return(MockStatefulServiceContextFactory.Create(context, "barry", new Uri("fabric:/barry/norman"), Guid.NewGuid(), 1));
        }
        public static void Register()
        {
            ServiceRuntime.RegisterServiceAsync(
                Naming.ServiceType <MembershipManager>(),
                (context) =>
            {
                ConfigurationPackage configPackage = context.CodePackageActivationContext.GetConfigurationPackageObject(@"Config");
                ILogger serilog = new LoggerConfiguration()
                                  .Enrich.FromServiceContext(context)
                                  .Enrich.FromLogProxy()
                                  .Destructure.UsingAttributes()
                                  .WriteTo.Seq(configPackage.Settings.Sections[@"ResourceSettings"].Parameters[@"seqLocation"].Value)
                                  .CreateLogger();
                Log.Logger = serilog;
                return(new MembershipManager(context, serilog));
            })
            .GetAwaiter().GetResult();

            ServiceEventSource.Current.ServiceTypeRegistered(
                Process.GetCurrentProcess().Id,
                Naming.ServiceType <MembershipManager>());
        }