Exemplo n.º 1
0
        static void CreateEmployee(AdminClient adminClient)
        {
            Prompt createEmployeePrompt = new Prompt($"Create new employee?", new string[] { "Y", "n" });

            createEmployeePrompt.Answered += (sender, e) => {
                if (e.answer == "Y")
                {
                    new Task(async() => {
                        var employee = await adminClient.CreateEmployee(new FunBankLib.Models.Employee()
                        {
                            Id       = null,
                            Hash     = null,
                            Username = new Prompt("username:"******"first name:").Execute(),
                                Last  = new Prompt("last name:").Execute()
                            },
                            PasswordHash = new Prompt("password:").Execute()
                        });

                        createEmployeePrompt.Execute();
                    }).Start();
                }
                else
                {
                    CreateATM(adminClient);
                }
            };
            createEmployeePrompt.Execute();
        }
Exemplo n.º 2
0
        private static void CreateTopic(IConfigurationRoot config)
        {
            var adminClientConfig = new AdminClientConfig
            {
                BootstrapServers = config["BootstrapServers"]
            };

            var adminClient = new AdminClient(adminClientConfig);

            var topic    = config["TopicName"];
            var metadata = adminClient.GetMetadata(TimeSpan.FromSeconds(10));

            if (metadata.Topics.Any(x => x.Topic == topic))
            {
                return;
            }

            var topicConfig = config.GetSection("TopicConfig").GetChildren().AsEnumerable()
                              .ToDictionary(x => x.Key, x => x.Value);

            adminClient.CreateTopicsAsync(new[]
            {
                new TopicSpecification
                {
                    Name              = topic,
                    NumPartitions     = int.Parse(config["NumPartitions"]),
                    ReplicationFactor = short.Parse(config["ReplicationFactor"]),
                    Configs           = topicConfig
                }
            }).Wait();
        }
Exemplo n.º 3
0
        public async Task GetUserRole_SuccessStatusCode()
        {
            var request  = $"{_baseUrl}/{DefaultValues.MemberId}/role";
            var response = await AdminClient.GetAsync(request);

            response.EnsureSuccessStatusCode();
        }
Exemplo n.º 4
0
        public static void Metadata(string bootstrapServers, string singlePartitionTopic, string partitionedTopic)
        {
            LogToFile("start Metadata");

            var config = new AdminClientConfig {
                BootstrapServers = bootstrapServers
            };

            using (var adminClient = new AdminClient(config))
            {
                var metadata = adminClient.GetMetadata(TimeSpan.FromSeconds(10));
                Assert.NotNull(metadata.Brokers);
                Assert.True(metadata.Brokers.Count > 0);

                var metadataAsJson = metadata.ToString();
                var deserialized   = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(metadataAsJson);

                Assert.Equal(deserialized.Value <int>("OriginatingBrokerId"), metadata.OriginatingBrokerId);
                Assert.Equal(deserialized.Value <string>("OriginatingBrokerName"), metadata.OriginatingBrokerName);
                var topics = new List <JToken>(deserialized["Topics"].Children());
                Assert.Equal(metadata.Topics.Count, topics.Count);
                for (int i = 0; i < metadata.Topics.Count; ++i)
                {
                    Assert.Equal(topics[i].Value <string>("Error"), metadata.Topics[i].Error.Code.ToString());
                    Assert.Equal(topics[i].Value <string>("Topic"), metadata.Topics[i].Topic);
                    var partitions = new List <JToken>(topics[i]["Partitions"].Children());
                    Assert.Equal(partitions.Count, metadata.Topics[i].Partitions.Count);
                    for (int j = 0; j < metadata.Topics[i].Partitions.Count; ++j)
                    {
                        Assert.Equal(partitions[j].Value <string>("Error"), metadata.Topics[i].Partitions[j].Error.Code.ToString());
                        Assert.Equal(partitions[j].Value <int>("Leader"), metadata.Topics[i].Partitions[j].Leader);
                        Assert.Equal(partitions[j].Value <int>("PartitionId"), metadata.Topics[i].Partitions[j].PartitionId);
                        var replicas = new List <JToken>(partitions[j]["Replicas"].Children());
                        Assert.Equal(replicas.Count, metadata.Topics[i].Partitions[j].Replicas.Length);
                        for (int k = 0; k < metadata.Topics[i].Partitions[j].Replicas.Length; ++k)
                        {
                            Assert.Equal(replicas[k].Value <int>(), metadata.Topics[i].Partitions[j].Replicas[k]);
                        }
                        var inSyncReplicas = new List <JToken>(partitions[j]["InSyncReplicas"].Children());
                        Assert.Equal(inSyncReplicas.Count, metadata.Topics[i].Partitions[j].InSyncReplicas.Length);
                        for (int k = 0; k < metadata.Topics[i].Partitions[j].InSyncReplicas.Length; ++k)
                        {
                            Assert.Equal(inSyncReplicas[k].Value <int>(), metadata.Topics[i].Partitions[j].InSyncReplicas[k]);
                        }
                    }
                }

                var brokers = new List <JToken>(deserialized["Brokers"].Children());
                Assert.Equal(metadata.Brokers.Count, brokers.Count);
                for (int i = 0; i < metadata.Brokers.Count; ++i)
                {
                    Assert.Equal(metadata.Brokers[i].BrokerId, brokers[i].Value <int>("BrokerId"));
                    Assert.Equal(metadata.Brokers[i].Host, brokers[i].Value <string>("Host"));
                    Assert.Equal(metadata.Brokers[i].Port, brokers[i].Value <int>("Port"));
                }
            }

            Assert.Equal(0, Library.HandleCount);
            LogToFile("end   Metadata");
        }
Exemplo n.º 5
0
        public MisskeyClient(Credential credential, HttpClientHandler innerHandler = null) : base(credential, new MisskeyAuthenticationHandler(innerHandler), RequestMode.Json)
        {
            BinaryParameters = new List <string> {
                "file"
            };

            Aggregation   = new AggregationClient(this);
            Ap            = new ApClient(this);
            Admin         = new AdminClient(this);
            App           = new MisskeyAppClient(this);
            Auth          = new AuthClient(this);
            Blocking      = new BlockingClient(this);
            Charts        = new ChartsClient(this);
            Drive         = new DriveClient(this);
            Federation    = new FederationClient(this);
            Following     = new FollowingClient(this);
            Hashtags      = new HashtagsClient(this);
            I             = new IClient(this);
            Messaging     = new MessagingClient(this);
            Mute          = new MuteClient(this);
            My            = new MyClient(this);
            Notes         = new NotesClient(this);
            Notifications = new NotificationsClient(this);
            Streaming     = new StreamingClient(this);
            Username      = new UsernameClient(this);
            Users         = new UsersClient(this);
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            AdminClient admin = new AdminClient();

            Client client = new Client(1429,
                                       "Vova", "O", "+380667577145", "-1");

            Console.WriteLine(
                admin.RegisterClient(client)
                );

            Console.WriteLine(
                admin.AddAccount(client, new Account("12345678", "2228", AccountType.CreditAccount))
                );


            //Client cl = admin.GetClient(1429, "-1");

            //Console.WriteLine(
            //    admin.AddAccount(cl, new Account("12345677", "2222", AccountType.BonusAccount))
            //);

            ATMClient atm = new ATMClient();

            Account ac = atm.LoginAccount("12345677", "2222");

            Console.WriteLine(
                atm.AddTransaction(ac, "2222", "12345678", 200, DateTime.Now)
                //atm.WithdrawMoney(ac, "2222", 100)
                );

            Console.Read();
        }
        static async Task Main(string[] args)
        {
            var config = new AdminClientConfig
            {
                BootstrapServers = "127.0.0.1:9092"
            };

            string topic = "test_topic";

            using (var adminClient = new AdminClient(config))
            {
                // won't throw if topic doesn't exist.
                await adminClient.DeleteTopicMaybeAsync("topic_that_doesnt_exist");

                // only create topic if it doesn't exist already.
                await adminClient.CreateTopicMaybeAsync(topic, 1, 1, null);

                // topic may take some time to be created.
                await Task.Delay(1000);

                // a simplified describe topics method.
                var configs = await adminClient.DescribeTopicAsync(topic);

                foreach (var c in configs)
                {
                    Console.WriteLine($"{c.Key}: {c.Value.Value}");
                }

                // delete the topic (if it doesn't exist, considered an error).
                await adminClient.DeleteTopicAsync(topic);
            }
        }
Exemplo n.º 8
0
        private static bool TopicExists(string topicName)
        {
            var config = new AdminClientConfig()
            {
                BootstrapServers = _server
            };

            using (var client = new AdminClient(config))
            {
                // Which call auto-creates the topic?
                var metaBroker = client.GetMetadata(TimeSpan.FromSeconds(3));
                var metaTopic  = client.GetMetadata(_topicName, TimeSpan.FromSeconds(3));   // Auto-creates topic. Broker setting?

                var resources = new List <ConfigResource>()
                {
                    new ConfigResource()
                    {
                        Name = _topicName, Type = ResourceType.Topic
                    }
                };
                var options = new DescribeConfigsOptions()
                {
                    RequestTimeout = TimeSpan.FromSeconds(3)
                };

                var configTask    = client.DescribeConfigsAsync(resources, options);
                var configResults = configTask.Result;
            }

            return(false);
        }
Exemplo n.º 9
0
        public async Task GetRoles_SuccessStatusCode()
        {
            var request  = $"{_baseUrl}/roles";
            var response = await AdminClient.GetAsync(request);

            response.EnsureSuccessStatusCode();
        }
Exemplo n.º 10
0
        public async Task GetAllUsers_SuccessStatusCode()
        {
            var request  = _baseUrl;
            var response = await AdminClient.GetAsync(request);

            response.EnsureSuccessStatusCode();
        }
 public TriggerCallbackThread(IOptions <JobExecutorOption> executorOption, ILoggerFactory loggerFactory, AdminClient adminClient, HandleCallbackParamRepository paramRepository)
 {
     _executorOption    = executorOption.Value;
     _queueHasDataEvent = new AutoResetEvent(false);
     _logger            = loggerFactory.CreateLogger <TriggerCallbackThread>();
     _adminClient       = adminClient;
     _paramRepository   = paramRepository;
 }
Exemplo n.º 12
0
 public Form2(Korisnik k)
 {
     ulogovan   = k;
     proxy      = new AdminClient();
     knjige     = new BindingList <Knjiga>();
     korisnici  = new BindingList <Korisnik>();
     porudzbine = new BindingList <Porudzbina>();
     InitializeComponent();
 }
 static void deleteTopics(string brokerList, IEnumerable <string> topicNameList)
 {
     using (var adminClient = new AdminClient(new AdminClientConfig {
         BootstrapServers = brokerList
     }))
     {
         adminClient.DeleteTopicsAsync(topicNameList, null);
     }
 }
Exemplo n.º 14
0
        public MainWindow()
        {
            InitializeComponent();

            _adminClient = new AdminClient
            {
                CreatedCanvasIdHandler = HandleCanvasIdUpdate,
                DeleteCanvasHandler    = HandleCanvasDelete
            };
        }
Exemplo n.º 15
0
        public async Task ChangeRole_SuccessStatusCode()
        {
            var role = new UserJsonDataBuilder()
                       .WithDefaultRoleId()
                       .Build();
            var request  = $"{_baseUrl}/{DefaultValues.MemberId}/role";
            var response = await AdminClient.PostAsync(request, role);

            response.EnsureSuccessStatusCode();
        }
Exemplo n.º 16
0
        public async Task Like_SuccessStatusCode()
        {
            // Arrange
            var request = $"{ _baseUrl}/like/{_newsId}";

            // Act
            var response = await AdminClient.PutAsync(request, null);

            // Assert
            response.EnsureSuccessStatusCode();
        }
Exemplo n.º 17
0
        public async Task Remove_SuccessStatusCode()
        {
            // Arrange
            var request = $"{_baseUrl}/{_newsId}";

            // Act
            var response = await AdminClient.DeleteAsync(request);

            // Assert
            response.EnsureSuccessStatusCode();
        }
Exemplo n.º 18
0
 public frmAdministrator()
 {
     InitializeComponent();
     klijentJavni       = new JavniClient();
     klijentSistem      = new SistemClient();
     klijentLogin       = new LogInClient();
     klijentAdmin       = new AdminClient();
     knjige             = klijentJavni.PrikazKnjiga();
     nalozi             = klijentLogin.VratiSveNaloge();
     porudzbine         = klijentSistem.PregledPorudzbina();
     this.StartPosition = FormStartPosition.CenterScreen;
 }
Exemplo n.º 19
0
        public CallbackTaskQueue(AdminClient adminClient, IJobLogger jobLogger, IOptions <XxlJobExecutorOptions> optionsAccessor
                                 , ILoggerFactory loggerFactory)
        {
            this._adminClient = adminClient;
            this._jobLogger   = jobLogger;

            this._retryQueue = new RetryCallbackTaskQueue(optionsAccessor.Value.LogPath,
                                                          Push,
                                                          loggerFactory.CreateLogger <RetryCallbackTaskQueue>());

            this._logger = loggerFactory.CreateLogger <CallbackTaskQueue>();
        }
Exemplo n.º 20
0
 public TemporaryTopic(string bootstrapServers, int numPartitions)
 {
     Name        = Guid.NewGuid().ToString();
     adminClient = new AdminClientBuilder(new AdminClientConfig {
         BootstrapServers = bootstrapServers
     }).Build();
     adminClient.CreateTopicsAsync(
         new List <TopicSpecification> {
         new TopicSpecification {
             Name = Name, NumPartitions = numPartitions, ReplicationFactor = 1
         }
     }).Wait();
 }
 private void CreatePartition()
 {
     if (PartitionOptions != null)
     {
         TopicPartitionCache = new ConcurrentDictionary <string, TopicPartition>();
         if (PartitionOptions.Partition > 1)
         {
             using (var adminClient = new AdminClient(Producer.Handle))
             {
                 try
                 {
                     adminClient.CreateTopicsAsync(new TopicSpecification[] { new TopicSpecification {
                                                                                  Name = TopicName, NumPartitions = 1, ReplicationFactor = 1
                                                                              } }).Wait();
                 }
                 catch (AggregateException ex)
                 {
                     //{Confluent.Kafka.Admin.CreateTopicsException: An error occurred creating topics: [jt809]: [Topic 'jt809' already exists.].}
                     if (ex.InnerException is Confluent.Kafka.Admin.CreateTopicsException exception)
                     {
                     }
                     else
                     {
                         //记录日志
                         //throw ex.InnerException;
                     }
                 }
                 try
                 {
                     //topic IncreaseTo 只增不减
                     adminClient.CreatePartitionsAsync(
                         new List <PartitionsSpecification>
                     {
                         new PartitionsSpecification
                         {
                             IncreaseTo = PartitionOptions.Partition,
                             Topic      = TopicName
                         }
                     }
                         ).Wait();
                 }
                 catch (AggregateException ex)
                 {
                     //记录日志
                     // throw ex.InnerException;
                 }
             }
         }
     }
 }
        public void WatermarkOffsets(string bootstrapServers)
        {
            LogToFile("start WatermarkOffsets");

            var producerConfig = new ProducerConfig {
                BootstrapServers = bootstrapServers
            };

            var testString = "hello world";

            DeliveryResult <Null, string> dr;

            using (var producer = new ProducerBuilder <Null, string>(producerConfig).Build())
                using (var adminClient = new AdminClient(producer.Handle))
                {
                    dr = producer.ProduceAsync(singlePartitionTopic, new Message <Null, string> {
                        Value = testString
                    }).Result;
                    Assert.Equal(0, producer.Flush(TimeSpan.FromSeconds(10))); // this isn't necessary.
                }

            var consumerConfig = new ConsumerConfig
            {
                GroupId          = Guid.NewGuid().ToString(),
                BootstrapServers = bootstrapServers,
                SessionTimeoutMs = 6000
            };

            using (var consumer = new ConsumerBuilder <byte[], byte[]>(consumerConfig).Build())
            {
                consumer.Assign(new List <TopicPartitionOffset>()
                {
                    dr.TopicPartitionOffset
                });
                var record = consumer.Consume(TimeSpan.FromSeconds(10));
                Assert.NotNull(record.Message);

                var getOffsets = consumer.GetWatermarkOffsets(dr.TopicPartition);
                Assert.Equal(getOffsets.Low, Offset.Unset);
                // the offset of the next message to be read.
                Assert.Equal(getOffsets.High, dr.Offset + 1);

                var queryOffsets = consumer.QueryWatermarkOffsets(dr.TopicPartition, TimeSpan.FromSeconds(20));
                Assert.NotEqual(queryOffsets.Low, Offset.Unset);
                Assert.Equal(getOffsets.High, queryOffsets.High);
            }

            Assert.Equal(0, Library.HandleCount);
            LogToFile("end   WatermarkOffsets");
        }
Exemplo n.º 23
0
        public async Task Post_SuccessStatusCode()
        {
            // Arrange
            var news = new NewsFormDataBuilder()
                       .WithDefaultTitle()
                       .WithDefaultText()
                       .WithDefaultImage("MainImage")
                       .Build();
            var request = _baseUrl;

            // Act
            var response = await AdminClient.PostAsync(request, news);

            // Assert
            response.EnsureSuccessStatusCode();
        }
Exemplo n.º 24
0
 private static void CreateTopic()
 {
     using (var producer = new Producer <Null, string>(GetConfig()))
     {
         using (var adminClient = new AdminClient(producer.Handle))
         {
             adminClient.CreateTopicsAsync(new TopicSpecification[] { new TopicSpecification {
                                                                          Name = TOPIC, NumPartitions = 5, ReplicationFactor = 1
                                                                      } }).Wait();
             adminClient.CreatePartitionsAsync(new List <PartitionsSpecification> {
                 new PartitionsSpecification {
                     Topic = TOPIC, IncreaseTo = 6
                 }
             }).Wait();
         }
     }
 }
Exemplo n.º 25
0
        private static void DeleteTopic(IConfigurationRoot config)
        {
            var adminClientConfig = new AdminClientConfig
            {
                BootstrapServers = config["BootstrapServers"]
            };

            var adminClient = new AdminClient(adminClientConfig);

            var topic    = config["TopicName"];
            var metadata = adminClient.GetMetadata(TimeSpan.FromSeconds(10));

            if (metadata.Topics.Any(x => x.Topic == topic))
            {
                adminClient.DeleteTopicsAsync(new[] { topic }).Wait();
            }
        }
Exemplo n.º 26
0
        private static async Task WriteAsync(AdminClient client, Stream stream, CancellationToken cancellationToken)
        {
            var stringWriter = new StringWriter();
            await stringWriter.WriteLineAsync(string.Format("{0},{1},{2},{3},{4},{5}",
                                                            client.Id.ToCsvValue(),
                                                            client.Email.ToCsvValue(),
                                                            client.Name.ToCsvValue(),
                                                            client.Created.ToCsvValue(),
                                                            (client.Balance / 100).ToCsvValue(),
                                                            client.State.ToCsvValue()));

            byte[] bytes = Encoding.UTF8.GetBytes(stringWriter.ToString());

            await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken);

            await stream.FlushAsync(cancellationToken);
        }
Exemplo n.º 27
0
 public JT808_MsgId_Producer(
     IOptions <ProducerConfig> producerConfigAccessor)
 {
     producer = new Producer <string, byte[]>(producerConfigAccessor.Value);
     this.jT808ProducerPartitionFactory = new JT808MsgIdProducerPartitionFactoryImpl();
     using (var adminClient = new AdminClient(producer.Handle))
     {
         try
         {
             adminClient.CreateTopicsAsync(new TopicSpecification[] { new TopicSpecification {
                                                                          Name = TopicName, NumPartitions = 1, ReplicationFactor = 1
                                                                      } }).Wait();
         }
         catch (AggregateException ex)
         {
             //{Confluent.Kafka.Admin.CreateTopicsException: An error occurred creating topics: [jt808]: [Topic 'jt808' already exists.].}
             if (ex.InnerException is Confluent.Kafka.Admin.CreateTopicsException exception)
             {
             }
             else
             {
                 //记录日志
                 //throw ex.InnerException;
             }
         }
         try
         {
             //topic IncreaseTo 只增不减
             adminClient.CreatePartitionsAsync(
                 new List <PartitionsSpecification>
             {
                 new PartitionsSpecification
                 {
                     IncreaseTo = 8,
                     Topic      = TopicName
                 }
             }
                 ).Wait();
         }
         catch (AggregateException ex)
         {
             //记录日志
             // throw ex.InnerException;
         }
     }
 }
Exemplo n.º 28
0
        public override EventEat OnSay(AdminClient client, string message)
        {
            if (message.StartsWith("!guid"))
            {
                SayAll("GUIDServ", "your GUID is " + client.GUID.ToString("x16"));
                Log.Debug("your GUID is " + client.GUID.ToString("x16"));
                return(EventEat.EatGame);
            }

            if (message.StartsWith("!pm"))
            {
                SayTo(client, "PMServ", "hello there " + client.Name);
                return(EventEat.EatNone);
            }

            return(EventEat.EatNone);
        }
Exemplo n.º 29
0
        static void GetBaseUrl()
        {
            Prompt baseUrlPrompt = new Prompt("enter base url:", new string[0]);

            baseUrlPrompt.Answered += (sender, e) => {
                try {
                    Uri uri = new Uri(e.answer);

                    AdminClient adminClient = new AdminClient(uri.ToString());
                    Console.WriteLine("Login as Admin:");
                    adminClient.Login(new Prompt("Username:"******"Password:").Execute()).Wait();
                    CreateCustomer(adminClient);
                } catch (UriFormatException) {
                    e.invalid = true;
                }
            };
            baseUrlPrompt.Execute();
        }
Exemplo n.º 30
0
 private static void DeleteTopic()
 {
     using (var producer = new Producer <Null, string>(GetConfig()))
     {
         using (var adminClient = new AdminClient(producer.Handle))
         {
             try
             {
                 adminClient.DeleteTopicsAsync(new List <string> {
                     TOPIC
                 }).Wait();
             }
             catch (Exception ex)
             {
             }
         }
     }
 }