コード例 #1
0
        /// <summary>
        /// Add {OnChange} listener for the IOptionMonitor.
        /// </summary>
        /// <typeparam name="SettingsClass">{Class} The setting class.</typeparam>
        /// <param name="self">{OptionMonitor}</param>
        /// <param name="provider">{ServiceProvider}</param>
        /// <param name="config">{Iconfiguration}</param>
        /// <returns>{OptionMonitor} the new value.</returns>
        private static IOptionsMonitor <SettingsClass> AddOnChangeToMonitor <SettingsClass>(this IOptionsMonitor <SettingsClass> self, IServiceProvider provider, IConfiguration config)
            where SettingsClass : class, new()
        {
            self.OnChange(settings =>
            {
                try
                {
                    // Make sure that every time when the settings file changes, it will be validated.
                    if (typeof(SettingsClass).Name.Equals(nameof(CassandraOptions)))
                    {
                        var option = CassandraSettings.Convert(self.CurrentValue as CassandraOptions); // config.GetConfigurationInstance<CassandraSettings>(typeof(CassandraSettings).Name);
                        ValidateSettings <CassandraSettings>(option);
                    }
                    else
                    {
                        ValidateSettings <SettingsClass>(self.CurrentValue);
                    }
                }
                catch (Exception ex)
                {
                    // Normaly we should have a logger istead of Debug.
                    Debug.WriteLine($"Fatal : [{ex.Message}]");
                    var appLifeTime = provider.GetService <IApplicationLifetime>();
                    appLifeTime.StopApplication();
                }
            });

            return(self);
        }
コード例 #2
0
        /// <summary>
        /// Setup and build the cassandra Cluster.
        /// </summary>
        /// <param name="self">The Cassandra settings.</param>
        /// <param name="keyspace">The Database name space.</param>
        /// <returns>Cassandra Cluster.</returns>
        private static ISession BuildClusterAndConnect(this CassandraSettings self, string keyspace = default)
        {
            var username = self.Credentials.Username;
            var password = self.Credentials.Password;

            keyspace = string.IsNullOrWhiteSpace(keyspace) ? self.DefaultKeyspace : keyspace;

            var consistentyQueryOption = new QueryOptions().SetConsistencyLevel((ConsistencyLevel)self.Query.ConsistencyLevel);
            var heartbeat = new PoolingOptions().SetHeartBeatInterval(self.Query.HeartBeat);

            if (self.Replication["class"].ToLower() == "SimpleStrategy".ToLower())
            {
                self.Replication.Remove("datacenter");
            }
            else if (self.Replication["class"].ToLower() == "NetworkTopologyStrategy".ToLower())
            {
                self.Replication.Remove("replication_factor");
            }

            return(Cluster.Builder()
                   .AddContactPoints(self.ContactPoints)
                   .WithPort(self.Port)
                   .WithCredentials(username, password)
                   .WithCompression(CompressionType.Snappy)
                   .WithQueryOptions(consistentyQueryOption)
                   .WithLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy()))
                   .WithPoolingOptions(heartbeat)
                   .WithDefaultKeyspace(keyspace)
                   .Build()
                   .ConnectAndCreateDefaultKeyspaceIfNotExists(self.Replication));
        }
コード例 #3
0
        /// <summary>
        /// Convert the specified configuration section into an object.
        /// </summary>
        /// <param name="self">The Configuration Object.</param>
        /// <param name="section">The desired section that we want to convert into an object.</param>
        /// <returns>New Cassandra setitngs instance.</returns>
        private static CassandraSettings GetConfigInstance(this IConfiguration self, string section)
        {
            var instance = new CassandraSettings();

            self.Bind(section, instance);
            return(instance);
        }
コード例 #4
0
        public static void StringTopic(
            [KafkaTrigger("KAFKA_BROKER_AUTH", IConstants.Topic,
                          ConsumerGroup = IConstants.ConsumerGroup,
                          Protocol = BrokerProtocol.SaslPlaintext,
                          AuthenticationMode = BrokerAuthenticationMode.Plain,
                          Username = "******",
                          Password = "******"
                          )] KafkaEventData <string>[] kafkaEvents,
            ILogger logger)
        {
            if (_personRepository == null)
            {
                var configuration = new ConfigurationBuilder()
                                    .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                    .AddEnvironmentVariables()
                                    .Build();
                var cassandraSettings          = new CassandraSettings(configuration);
                var cassandraConnectionFactory = new CassandraConnectionFactory(logger, cassandraSettings);
                _personRepository = new PersonRepository(cassandraConnectionFactory.Session);
            }

            foreach (var kafkaEvent in kafkaEvents)
            {
                Person person = JsonConvert.DeserializeObject <Person>(kafkaEvent.Value);
                _personRepository.Save(person);
                logger.LogInformation($"Person:[{person}] persisted with success");
            }
        }
コード例 #5
0
        public static IServiceCollection SetupCassieCustard(this IServiceCollection svc, IConfiguration config)
        {
            CassandraSettings noSqlDb = new CassandraSettings()
            {
                CassandraPort         = 10350,
                CassandraContactPoint = config.GetSection("CassandraContactPoint_ModuleName").Value,
                KeySpaceName          = config.GetSection("KeySpaceName_ModuleName").Value,
                Password = config.GetSection("Password_Cassandra_ModuleName").Value,
                UserName = config.GetSection("UserName_Cassandra_ModuleName").Value
            };

            svc.AddScoped(noSqldb => new SampleModuleContext(noSqlDb));
            return(svc);
        }
コード例 #6
0
        /// <summary>
        /// Validate the Cassandra Configuration file.
        /// </summary>
        /// <param name="self">The Cassandra configuration Instance.</param>
        /// <returns>Self if valid.</returns>
        private static CassandraSettings ValidateConfiguration(this CassandraSettings self)
        {
            var argumentNullExceptionMessage = "The configuration [{0}] section is invalid";

            if (self.ContactPoints is null || self.ContactPoints.Count == 0)
            {
                throw new ArgumentNullException(string.Format(argumentNullExceptionMessage, "Contact Point"));
            }

            if (self.Port == 0)
            {
                throw new ArgumentNullException(string.Format(argumentNullExceptionMessage, "Port"));
            }

            if (self.Credentials is null || string.IsNullOrWhiteSpace(self.Credentials.Username) || string.IsNullOrWhiteSpace(self.Credentials.Password))
            {
                throw new ArgumentNullException(string.Format(argumentNullExceptionMessage, "Credentials"));
            }

            if (string.IsNullOrWhiteSpace(self.DefaultKeyspace))
            {
                throw new ArgumentNullException(string.Format(argumentNullExceptionMessage, "Default Keyspace"));
            }

            if (self.Replication is null || string.IsNullOrWhiteSpace(self.Replication["class"]))
            {
                throw new ArgumentNullException(string.Format(argumentNullExceptionMessage, "Replication"));
            }

            if (self.Replication["class"].ToLower() == "NetworkTopologyStrategy".ToLower() && string.IsNullOrWhiteSpace(self.Replication["datacenter"]))
            {
                throw new ArgumentNullException(string.Format(argumentNullExceptionMessage, "Replication: datacenter"));
            }

            if (self.Replication["class"].ToLower() == "SimpleStrategy".ToLower() && string.IsNullOrWhiteSpace(self.Replication["replication_factor"]))
            {
                throw new ArgumentNullException(string.Format(argumentNullExceptionMessage, "Replication: replication_factor"));
            }

            if (self.Query is null || self.Query.HeartBeat == 0)
            {
                throw new ArgumentNullException(string.Format(argumentNullExceptionMessage, "Query"));
            }

            return(self);
        }
コード例 #7
0
 public SampleModuleContext(CassandraSettings settings) : base(settings)
 {
 }
コード例 #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HelloContext" /> class.
 /// </summary>
 /// <param name="settings">The settings.</param>
 /// <param name="loggerFactory">The logger factory.</param>
 public HelloContext(IOptions <CassandraSettings> settings, ILoggerFactory loggerFactory)
 {
     this.settings      = settings.Value;
     this.loggerFactory = loggerFactory;
 }
コード例 #9
0
 public TransactionsRepository(IConnection connection, CassandraSettings settings)
 {
     this.connection = connection;
     this.settings   = settings;
 }