public static IServiceProvider Configure(IServiceCollection services)
        {
            var assemblyPath = Directory.GetCurrentDirectory();
            var config       = new KeyValueConfiguration(Path.Combine(assemblyPath, "sir.ini"));

            services.Add(new ServiceDescriptor(typeof(IConfigurationProvider), config));

            var loggerFactory  = services.BuildServiceProvider().GetService <ILoggerFactory>();
            var logger         = loggerFactory.CreateLogger("Sir");
            var model          = new BagOfCharsModel();
            var sessionFactory = new SessionFactory(@"c:\data\resin", logger);
            var qp             = new QueryParser <string>(sessionFactory, model, logger);
            var httpParser     = new HttpQueryParser(qp);

            services.AddSingleton(typeof(IModel <string>), model);
            services.AddSingleton(typeof(ISessionFactory), sessionFactory);
            services.AddSingleton(typeof(SessionFactory), sessionFactory);
            services.AddSingleton(typeof(QueryParser <string>), qp);
            services.AddSingleton(typeof(HttpQueryParser), httpParser);
            services.AddSingleton(typeof(IHttpWriter), new HttpWriter(sessionFactory));
            services.AddSingleton(typeof(IHttpReader), new HttpReader(
                                      sessionFactory,
                                      httpParser,
                                      loggerFactory.CreateLogger <HttpReader>()));

            return(services.BuildServiceProvider());
        }
        public void TestConstructionWorks()
        {
            // builder
            KeyValueConfiguration kvc = new KeyValueConfiguration.KeyValueConfigurationBuilder()
                                        .WithName("bucketName")
                                        .WithMaxHistoryPerKey(44)
                                        .WithMaxBucketSize(555)
                                        .WithMaxValueSize(666)
                                        .WithTtl(Duration.OfMillis(777))
                                        .WithStorageType(StorageType.Memory)
                                        .WithReplicas(2)
                                        .Build();

            Validate(kvc);

            Validate(KeyValueConfiguration.Builder(kvc).Build());

            Validate(KeyValueConfiguration.Instance(kvc.BackingConfig.ToJsonNode().ToString()));

            kvc = KeyValueConfiguration.Builder()
                  .WithName("bucketName")
                  .Build();

            Assert.Equal(1, kvc.MaxHistoryPerKey);
        }
 private void Validate(KeyValueConfiguration bc)
 {
     Assert.Equal("bucketName", bc.BucketName);
     Assert.Equal(44, bc.MaxHistoryPerKey);
     Assert.Equal(555, bc.MaxBucketSize);
     Assert.Equal(666, bc.MaxValueSize);
     Assert.Equal(Duration.OfMillis(777), bc.Ttl);
     Assert.Equal(StorageType.Memory, bc.StorageType);
     Assert.Equal(2, bc.Replicas);
 }
Exemple #4
0
        /// <summary>
        /// Initializes a new instance of the DefaultKeyValueConsumer class
        /// </summary>
        /// <param name="source">the source KeyValueSource object that provides raw-key-value data</param>
        /// <param name="columnMode">the column-mode of this consumer</param>
        /// <param name="config">the Key-Value configuration used to configure this consumer</param>
        public DefaultDictionaryConsumer(IDictionarySource <TValue> source, ColumnNameMode columnMode,
                                         KeyValueConfiguration config) : base(source, config?.VirtualColumns ?? new ConstConfigurationCollection())
        {
            if (columnMode == ColumnNameMode.FromConfig && (config?.Columns?.Count ?? 0) == 0)
            {
                throw new ArgumentException("Columns required when the ColumnMode is set to 'FromConfig'!", nameof(config));
            }

            this.columnMode = columnMode;
            this.config     = config;
            if (config != null)
            {
                tableName = config.TableName;
            }
        }
Exemple #5
0
 public override async Task PersistAsync(ConfigurationPersistenceContext context)
 {
     if (this.scriptResults.Configuration != null)
     {
         foreach (var config in this.scriptResults.Configuration)
         {
             var keyValueConfig = new KeyValueConfiguration
             {
                 Type  = AH.CoalesceString(config.ConfigType, "PSConfig"),
                 Key   = config.ConfigKey,
                 Value = config.CurrentConfigValue.ToString()
             };
             await keyValueConfig.PersistAsync(context);
         }
     }
 }
Exemple #6
0
        public static void Main(string[] args)
        {
            ArgumentHelper helper = new ArgumentHelperBuilder("KeyValueFull", args, Usage)
                                    .DefaultBucket("exampleBucket")
                                    .DefaultDescription("Example Description")
                                    .Build();

            try
            {
                using (IConnection c = new ConnectionFactory().CreateConnection(helper.MakeOptions()))
                {
                    // get the kv management context
                    IKeyValueManagement kvm = c.CreateKeyValueManagementContext();

                    // create the bucket
                    KeyValueConfiguration kvc = KeyValueConfiguration.Builder()
                                                .WithName(helper.Bucket)
                                                .WithDescription(helper.Description)
                                                .WithMaxHistoryPerKey(5)
                                                .WithStorageType(StorageType.Memory)
                                                .Build();

                    KeyValueStatus kvs = kvm.Create(kvc);
                    Console.WriteLine(kvs);

                    // get the kv context for the specific bucket
                    IKeyValue kv = c.CreateKeyValueContext(helper.Bucket);

                    // Put some keys. Each key is put in a subject in the bucket (stream)
                    // The put returns the revision number in the bucket (stream)
                    Console.WriteLine("\n1. Put");

                    ulong seq = kv.Put(ByteKey, Encoding.UTF8.GetBytes("Byte Value 1"));
                    Console.WriteLine("Revision number should be 1, got " + seq);

                    seq = kv.Put(StringKey, "String Value 1");
                    Console.WriteLine("Revision number should be 2, got " + seq);

                    seq = kv.Put(LongKey, 1);
                    Console.WriteLine("Revision number should be 3, got " + seq);

                    // retrieve the values. all types are stored as bytes
                    // so you can always get the bytes directly
                    Console.WriteLine("\n2. Get Value (Bytes)");

                    byte[] bvalue = kv.Get(ByteKey).Value;
                    Console.WriteLine(ByteKey + " from Value property: " + Encoding.UTF8.GetString(bvalue));

                    bvalue = kv.Get(StringKey).Value;
                    Console.WriteLine(StringKey + " from Value property: " + Encoding.UTF8.GetString(bvalue));

                    bvalue = kv.Get(LongKey).Value;
                    Console.WriteLine(LongKey + " from Value property: " + Encoding.UTF8.GetString(bvalue));

                    // if you know the value is not binary and can safely be read
                    // as a UTF-8 string, the ValueAsString function is ok to use
                    Console.WriteLine("\n3. Get String Value");

                    String svalue = kv.Get(ByteKey).ValueAsString();
                    Console.WriteLine(ByteKey + " from ValueAsString(): " + svalue);

                    svalue = kv.Get(StringKey).ValueAsString();
                    Console.WriteLine(StringKey + " from ValueAsString(): " + svalue);

                    svalue = kv.Get(LongKey).ValueAsString();
                    Console.WriteLine(LongKey + " from ValueAsString(): " + svalue);

                    // if you know the value is a long, you can use
                    // the getLongValue method
                    // if it's not a number a NumberFormatException is thrown
                    Console.WriteLine("\n4. Get Long Value");

                    long lvalue;
                    bool bLongGet = kv.Get(LongKey).TryGetLongValue(out lvalue);
                    Console.WriteLine(LongKey + " from getValueAsLong: " + lvalue);

                    bLongGet = kv.Get(StringKey).TryGetLongValue(out lvalue);
                    if (!bLongGet)
                    {
                        Console.WriteLine(StringKey + " value is not a long!");
                    }

                    // entry gives detail about latest record of the key
                    Console.WriteLine("\n5. Get Entry");

                    KeyValueEntry entry = kv.Get(ByteKey);
                    Console.WriteLine(ByteKey + " entry: " + entry);

                    entry = kv.Get(StringKey);
                    Console.WriteLine(StringKey + " entry: " + entry);

                    entry = kv.Get(LongKey);
                    Console.WriteLine(LongKey + " entry: " + entry);

                    // delete a key
                    Console.WriteLine("\n6. Delete a key");
                    kv.Delete(ByteKey);

                    // it's value is now null
                    // it's value is now null but there is a delete tombstone
                    KeyValueEntry kve = kv.Get(ByteKey);
                    Console.WriteLine("Delete tombstone entry: " + kve);
                    Console.WriteLine("Revision number should be 4, got " + kve.Revision);
                    Console.WriteLine("Deleted value should be null: " + (kve.Value == null));

                    // if the key does not exist there is no entry at all
                    Console.WriteLine("\n7.1 Keys does not exist");
                    kve = kv.Get(NotFound);
                    Console.WriteLine($"Entry for {NotFound} should be null: {kve == null}");

                    // if the key has been deleted there is an entry for it
                    // but the value will be null
                    Console.WriteLine("\n7.2 Keys not found");
                    bvalue = kv.Get(ByteKey).Value;
                    Console.WriteLine($"{ByteKey} byte value should be null: {bvalue == null}");

                    svalue = kv.Get(ByteKey).ValueAsString();
                    Console.WriteLine($"{ByteKey} string value should be null: " + (svalue == null));

                    bLongGet = kv.Get(ByteKey).TryGetLongValue(out lvalue);
                    if (!bLongGet)
                    {
                        Console.WriteLine(ByteKey + " value is not a long!");
                    }

                    // Update values. You can even update a deleted key
                    Console.WriteLine("\n8.1 Update values");
                    seq = kv.Put(ByteKey, Encoding.UTF8.GetBytes("Byte Value 2"));
                    Console.WriteLine("Revision number should be 5, got " + seq);

                    seq = kv.Put(StringKey, "String Value 2");
                    Console.WriteLine("Revision number should be 6, got " + seq);

                    seq = kv.Put(LongKey, 2);
                    Console.WriteLine("Revision number should be 7, got " + seq);

                    // values after updates
                    Console.WriteLine("\n8.2 Values after update");

                    svalue = kv.Get(ByteKey).ValueAsString();
                    Console.WriteLine(ByteKey + " from ValueAsString(): " + svalue);

                    svalue = kv.Get(StringKey).ValueAsString();
                    Console.WriteLine(StringKey + " from ValueAsString(): " + svalue);

                    bLongGet = kv.Get(LongKey).TryGetLongValue(out lvalue);
                    Console.WriteLine(LongKey + " from TryGetLongValue: " + lvalue);

                    // let's check the bucket info
                    Console.WriteLine("\n9.1 Bucket before update/delete");
                    kvs = kvm.GetBucketInfo(helper.Bucket);
                    Console.WriteLine(kvs);

                    kvc = KeyValueConfiguration.Builder(kvs.Config)
                          .WithDescription(helper.Description + "-changed")
                          .WithMaxHistoryPerKey(6)
                          .Build();
                    kvs = kvm.Update(kvc);
                    Console.WriteLine("\n9.2 Bucket after update");
                    Console.WriteLine(kvs);

                    // delete the bucket
                    Console.WriteLine("\n9.3 Delete");
                    kvm.Delete(helper.Bucket);

                    try {
                        kvm.GetBucketInfo(helper.Bucket);
                        Console.WriteLine("UH OH! Bucket should not have been found!");
                    }
                    catch (NATSJetStreamException) {
                        Console.WriteLine("Bucket was not found!");
                    }
                }
            }
            catch (Exception ex)
            {
                helper.ReportException(ex);
            }
        }
Exemple #7
0
        public static IServiceProvider Configure(IServiceCollection services)
        {
            var assemblyPath = Directory.GetCurrentDirectory();
            var config       = new KeyValueConfiguration(Path.Combine(assemblyPath, "sir.ini"));

            // register config
            services.Add(new ServiceDescriptor(typeof(IConfigurationProvider), config));

            // register plugin startup and teardown handlers

#if DEBUG
            var frameworkVersion = AppContext.TargetFrameworkName.Substring(AppContext.TargetFrameworkName.IndexOf("=v") + 2);

            assemblyPath = Path.Combine(assemblyPath, "bin", "Debug", $"netcoreapp{frameworkVersion}");
#endif

            var files = Directory.GetFiles(assemblyPath, "*.plugin.dll");

            foreach (var assembly in files.Select(file => AssemblyLoadContext.Default.LoadFromAssemblyPath(file)))
            {
                foreach (var type in assembly.GetTypes())
                {
                    // search for concrete types
                    if (!type.IsInterface)
                    {
                        var interfaces = type.GetInterfaces();

                        if (interfaces.Contains(typeof(IPluginStop)))
                        {
                            services.Add(new ServiceDescriptor(typeof(IPluginStop), type, ServiceLifetime.Singleton));
                        }
                        else if (interfaces.Contains(typeof(IPluginStart)))
                        {
                            services.Add(new ServiceDescriptor(typeof(IPluginStart), type, ServiceLifetime.Singleton));
                        }
                    }
                }
            }

            var plugins = new PluginsCollection();

            services.Add(new ServiceDescriptor(typeof(PluginsCollection), plugins));

            var serviceProvider = services.BuildServiceProvider();

            // raise startup event
            foreach (var service in serviceProvider.GetServices <IPluginStart>())
            {
                service.OnApplicationStartup(services, serviceProvider, config);
            }

            // Fetch one instance each of all plugins and register them with the PluginCollection
            // so that they can be fetched at runtime by Content-Type and System.Type.

            foreach (var service in services.BuildServiceProvider().GetServices <IHttpWriter>())
            {
                plugins.Add(service.ContentType, service);
            }

            foreach (var service in services.BuildServiceProvider().GetServices <IHttpReader>())
            {
                plugins.Add(service.ContentType, service);
            }

            RegisterComponents(services, plugins, services.BuildServiceProvider());

            return(services.BuildServiceProvider());
        }
Exemple #8
0
 public CsvDictionaryConsumer(IDictionarySource <CsvDataRecord> source, ColumnNameMode columnMode, KeyValueConfiguration config) : base(source, columnMode, config)
 {
 }
        /// <summary>
        /// 实现基类方法
        /// </summary>
        public override void InitConnecton()
        {
            int ii = 0;

            while (!this.IsAvailableConnection && ii <= 3)
            {
                Trace.WriteLine(string.Format("正在尝试第{0}次连接……", ii + 1));
                try
                {
                    //this.ChatServiceInfo = LoadBalancer.GetServiceInfo(CfgAppType.CFGChatServer, "Resources");
                    //if (this.ChatServiceInfo == null) continue;

                    //Trace.WriteLine(string.Format("已分配到服务器。(别名:{0}   地址:{1}:{2})"
                    //    , this.ChatServiceInfo.Alias, this.ChatServiceInfo.Host, this.ChatServiceInfo.Port));

                    //Uri chatRoomURI = new Uri(string.Format("tcp://{0}:{1}", this.ChatServiceInfo.Host, this.ChatServiceInfo.Port));
                    Uri       chatRoomURI  = new Uri("tcp://10.99.36.115:4801");
                    Endpoint  chatEndPoint = new Endpoint(chatRoomURI);
                    ChatParty user         = new ChatParty();
                    user.DisplayName  = this.Customer.DisplayName;
                    user.ChatProtocol = new BasicChatProtocol(chatEndPoint);
                    user.ChatProtocol.AutoRegister = true;
                    user.ChatProtocol.UserType     = UserType.Client;
                    user.ChatProtocol.UserNickname = this.Customer.DisplayName;
                    if (this.Customer.ChatProtocol != null)
                    {
                        user.ChatProtocol.UserData = this.Customer.ChatProtocol.UserData;
                    }
                    // 打开聊天服务
                    try
                    {
                        string        logName = "testLog";
                        Log4NetLogger logger  = new Log4NetLogger(log, logName);
                        user.ThreadInvoker = new SingleThreadInvoker("EventReceivingBrokerService-1", logger);
                        user.ThreadInvoker.EnableLogging(logger);
                        user.EventBroker = new EventReceivingBrokerService(user.ThreadInvoker);
                        user.EventBroker.EnableLogging(logger);
                        user.EventBroker.Register(this.ChatEventsHandler, new MessageFilter(user.ChatProtocol.ProtocolId));
                        user.ChatProtocol.SetReceiver(user.EventBroker);

                        var isOpend = false;
                        lock (ChatLock.LOCK_OPEN)
                        {
                            try
                            {
                                user.ChatProtocol.Open();
                                isOpend = true;
                                System.Threading.Thread.Sleep(50);
                            }
                            catch { }
                        }
                        if (!isOpend)
                        {
                            throw new Exception("连接ChatServer异常,稍候重试。");
                        }

                        this.customer = user;

                        this.InitRoom();
                        this.Room.Partys.Add(this.customer);

                        // 日志
                        ChatLog.GetInstance().LogEvent(ChatEvent.NewClient, this.customer.DisplayName);

                        // 若使用TLS协议
                        if (this.ChatServiceInfo != null &&
                            this.ChatServiceInfo.IsWebApiPortSecured)
                        {
                            KeyValueCollection kvs = new KeyValueCollection();
                            kvs[CommonConnection.TlsKey]          = 1;
                            kvs[CommonConnection.BlockingModeKey] = "true";
                            KeyValueConfiguration cfg = new KeyValueConfiguration(kvs);
                            this.customer.ChatProtocol.Configure(cfg);
                        }
                    }
                    catch (Exception)
                    {
                        if (user.EventBroker != null)
                        {
                            user.EventBroker.Unregister(this.ChatEventsHandler);
                        }
                        this.PartyDispose(user);
                    }
                }
                catch (LoadBalancerException ex)
                {
                    Trace.WriteLine("负载异常:" + ex.Message);
                    ii++;
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    ChatLog.GetInstance().LogException(ex);
                    ii++;
                }
            }
        }