private static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            var queue = client.GetQueue<string>("queue-example");

            var producer = Task.Factory.StartNew(() =>
            {
                for (var i = 0; i < 100; i++)
                {
                    queue.Offer("value " + i);
                }
            });

            var consumer = Task.Factory.StartNew(() =>
            {
                var nConsumed = 0;
                string e;
                while (nConsumed++ < 100 && (e = queue.Take()) != null)
                {
                    Console.WriteLine("Consuming " + e);
                }
            });

            Task.WaitAll(producer, consumer);
            queue.Destroy();
            client.Shutdown();
        }
        public static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            var semaphore = client.GetSemaphore("example-semaphore");
            semaphore.Init(1);
            var i = 0;
            Action increment = () =>
            {
                for (var j = 0; j < 100; j++)
                {
                    semaphore.Acquire();
                    try
                    {
                        i++;
                    }
                    finally
                    {
                        semaphore.Release();
                    }
                }
            };

            var task1 = Task.Factory.StartNew(increment);
            var task2 = Task.Factory.StartNew(increment);

            Task.WaitAll(task1, task2);
            Console.WriteLine("Final value: " + i);
            semaphore.Destroy();
        }
        public static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            config.GetSerializationConfig()
                .AddDataSerializableFactory(ExampleDataSerializableFactory.FactoryId,
                    new ExampleDataSerializableFactory());

            var client = HazelcastClient.NewHazelcastClient(config);

            var map = client.GetMap<int, Employee>("identified-data-serializable-example");

            var employee = new Employee { Id = 1, Name = "the employee"};

            Console.WriteLine("Adding employee: " + employee);

            map.Put(employee.Id, employee);

            var e = map.Get(employee.Id);

            Console.WriteLine("Gotten employee: " + e);

            client.Shutdown();
        }
Пример #4
0
 public abstract void Sign(
     IRequest request,
     ClientConfig clientConfig,
     RequestMetrics metrics,
     string awsAccessKeyId,
     string awsSecretAccessKey,
     SecureString secureKey);
Пример #5
0
        /// <summary>
        /// Inspects the supplied evidence to return the signer appropriate for the operation
        /// </summary>
        /// <param name="useSigV4Setting">Global setting for the service</param>
        /// <param name="config">Configuration for the client</param>
        /// <returns>True if signature v4 request signing should be used</returns>
        protected static bool UseV4Signing(bool useSigV4Setting, ClientConfig config)
        {
            if (useSigV4Setting || config.SignatureVersion == "4")
                return true;

            // do a cascading series of checks to try and arrive at whether we have
            // a recognisable region; this is required to use the AWS4 signer
            RegionEndpoint r = null;
            if (!string.IsNullOrEmpty(config.AuthenticationRegion))
                r = RegionEndpoint.GetBySystemName(config.AuthenticationRegion);

            if (r == null && !string.IsNullOrEmpty(config.ServiceURL))
            {
                var parsedRegion = AWSSDKUtils.DetermineRegion(config.ServiceURL);
                if (!string.IsNullOrEmpty(parsedRegion))
                    r = RegionEndpoint.GetBySystemName(parsedRegion);
            }

            if (r == null && config.RegionEndpoint != null)
                r = config.RegionEndpoint;

            if (r != null)
            {
                var endpoint = r.GetEndpointForService(config.RegionEndpointServiceName);
                if (endpoint != null && endpoint.SignatureVersionOverride == "4")
                    return true;
            }

            return false;
        }
        public static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            var latch = client.GetCountDownLatch("countdown-latch-example");

            latch.TrySetCount(2);

            var task1 = Task.Factory.StartNew(() =>
            {
                //do some work
                Thread.Sleep(5000);
                latch.CountDown();
            });

            var task2 = Task.Factory.StartNew(() =>
            {
                //do some work
                Thread.Sleep(10000);
                latch.CountDown();
            });

            latch.Await(20, TimeUnit.Seconds);
            Console.WriteLine("Tasks completed");
            latch.Destroy();
        }
        private static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            var ringbuffer = client.GetRingbuffer<string>("ringbuffer-example");

            var writer = Task.Factory.StartNew(() =>
            {
                for (var i = 0; i < 100; i++)
                {
                    ringbuffer.Add("item " + i);
                }
            });

            var reader = Task.Factory.StartNew(() =>
            {
                var sequence = ringbuffer.HeadSequence();
                while (sequence < 100)
                {
                    var item = ringbuffer.ReadOne(sequence++);
                    Console.WriteLine("Reading value " + item);
                }
            });

            Task.WaitAll(reader, writer);
            ringbuffer.Destroy();
            client.Shutdown();
        }
        private static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            var topic = client.GetTopic<string>("topic-example");

            var countdown = new CountdownEvent(100);
            topic.AddMessageListener(m =>
            {
                Console.WriteLine("Got message: " + m.GetMessageObject());
                countdown.Signal();
            });

            var publisher = Task.Factory.StartNew(() =>
            {
                for (var i = 0; i < 100; i++)
                {
                    topic.Publish("Message " + i);
                }
            });

            countdown.Wait();

            topic.Destroy();
            client.Shutdown();
        }
        private static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            var map = client.GetMap<string, string>("simple-example");

            map.Put("key", "value");
            map.Put("key2", "value2");

            Console.WriteLine("Key: " + map.Get("key"));

            Console.WriteLine("Values : " + string.Join(", ", map.Values()));

            Console.WriteLine("KeySet: " + string.Join(", ", map.KeySet()));

            Console.WriteLine("Size: " + string.Join(", ", map.Size()));

            Console.WriteLine("EntrySet: " + string.Join(", ", map.EntrySet()));

            Console.WriteLine("ContainsKey: " + string.Join(", ", map.ContainsKey("key")));

            Console.WriteLine("ContainsValue: " + string.Join(", ", map.ContainsValue("value")));

            map.Destroy();
            client.Shutdown();
        }
Пример #10
0
        public async Task InvalidMerchantId()
        {
            var config = new ClientConfig().SetupForTesting();

            // modify password so it is now incorrect
            config.MerchantId = "!!!0099";

            var client = new PeriodicClient(config);

            try
            {
                await client.EchoAsync();
                Assert.Fail("Expected exception");
            }
            catch (SecurePayException ex)
            {
                Assert.AreEqual("504: Invalid merchant ID", ex.Message);
            }
            catch (Exception)
            {
                Console.WriteLine("Request:");
                Console.WriteLine(client.LastRequest);
                Console.WriteLine("Response:");
                Console.WriteLine(client.LastResponse);
                throw;
            }
        }
        private static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            var map = client.GetMap<string, string>("map-lock-example");

            map.Put("key", "value");

            map.Lock("key");
            var task = Task.Factory.StartNew(() =>
            {
                map.Put("key", "newValue");
                Console.WriteLine("Put new value");
            });
            try
            {
                var value = map.Get("key");
                //do something with the value..
                Thread.Sleep(5000);
            }
            finally
            {
                map.Unlock("key");
            }
            task.Wait();

            Console.WriteLine("New value: " + map.Get("key"));
        }
        public static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            var map = client.GetMap<string, string>("listener-example");

            var cdown = new CountdownEvent(2);
            map.AddEntryListener(new EntryAdapter<string, string>
            {
                Added = e =>
                {
                    Console.WriteLine("Key '{0}' with value ' {1}' was added.", e.GetKey(), e.GetValue());
                    cdown.Signal();
                },
                Removed = e =>
                {
                    Console.WriteLine("Key '{0}' with value ' {1}' was removed.", e.GetKey(), e.GetOldValue());
                    cdown.Signal();
                }
            }, true);

            map.Put("key", "value");
            map.Remove("key");

            cdown.Wait();
            map.Destroy();
        }
        private static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            var options = new TransactionOptions();
            options.SetTransactionType(TransactionOptions.TransactionType.OnePhase);
            var ctx = client.NewTransactionContext(options);
            ctx.BeginTransaction();
            try
            {
                var txMap = ctx.GetMap<string, string>("txn-map");
                txMap.Put("foo", "bar");
                ctx.CommitTransaction();
            }
            catch
            {
                ctx.RollbackTransaction();
            }

            var map = client.GetMap<string, string>("txn-map");
            Console.WriteLine("Value of foo is " + map.Get("key"));
            map.Destroy();
            client.Shutdown();
        }
        private static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            var list = client.GetList<string>("list-example");

            list.Add("item1");
            list.Add("item2");
            list.Add("item3");

            Console.WriteLine("Get: " + list[0]);

            Console.WriteLine("Enumerator : " + string.Join(", ", list));

            Console.WriteLine("Contains: " + string.Join(", ", list.Contains("item2")));

            Console.WriteLine("Count: " + string.Join(", ", list.Count));

            Console.WriteLine("Sublist: " + string.Join(", ", list.SubList(0, 2)));

            list.Destroy();
            client.Shutdown();
        }
        private static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            var list = client.GetList<string>("collection-listener-example");
            var cdown = new CountdownEvent(3);
            list.AddItemListener(new ItemListener<string>
            {
                OnItemAdded = e =>
                {
                    Console.WriteLine("Item added: " + e.GetItem());
                    cdown.Signal();
                },
                OnItemRemoved = e =>
                {
                    Console.WriteLine("Item removed: " + e.GetItem());
                    cdown.Signal();
                }
            }, true);

            list.Add("item1");
            list.Add("item2");
            list.Remove("item1");

            cdown.Wait();
            list.Destroy();
            client.Shutdown();
        }
Пример #16
0
        static void Main(string[] args)
        {
            try
            {
                if (!File.Exists(FileName))
                {
                    var newRegistry = ProjectGenerator.GenRegistry(3, 10);
                    newRegistry.Save(FileName);
                }

                var registry = XmlRegistry.Load(FileName);

                // Валидация реестра - урлы в проектах и словах
                XmlRegistry.ValidateRegistry(registry);

                //------

                var apiKey = ConfigurationManager.AppSettings["apikey"];
                if (string.IsNullOrEmpty(apiKey))
                {
                    throw new InvalidOperationException(
                        "Invalid 'apikey' setting in application config.");
                }

                var config = new ClientConfig(apiKey);
                var client = new ApiClient(config);

                var syncClient = new SyncClient(client);

                Console.Write("Project's data loading...");
                syncClient.LoadSyncObjects();

                Console.WriteLine();
                Console.Write("Project's synchronization...");
                syncClient.SyncProjects(registry.Projects);

                Console.WriteLine();
                Console.Write("Groups's synchronization...");
                syncClient.SyncGroups(registry.Projects);

                Console.WriteLine();
                Console.Write("Keywords's synchronization...");
                syncClient.SyncKeywords(registry.Projects);

                Console.WriteLine();
                Console.Write("Synchronization completed, press any key...");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine();
                Console.WriteLine("Error:");
                Console.WriteLine(ex.ToString());
                Console.ResetColor();

                Console.Write("Press any key...");
                Console.ReadKey();
            }
        }
        /// <summary>
        /// Creates a started client runner.
        /// </summary>
        public static IClientRunner CreateStarted(ClientConfig config)
        {
            Logger.Debug("ClientConfig: {0}", config);

            if (config.AsyncClientThreads != 0)
            {
                Logger.Warning("ClientConfig.AsyncClientThreads is not supported for C#. Ignoring the value");
            }
            if (config.CoreLimit != 0)
            {
                Logger.Warning("ClientConfig.CoreLimit is not supported for C#. Ignoring the value");
            }
            if (config.CoreList.Count > 0)
            {
                Logger.Warning("ClientConfig.CoreList is not supported for C#. Ignoring the value");
            }

            var channels = CreateChannels(config.ClientChannels, config.ServerTargets, config.SecurityParams);

            return new ClientRunnerImpl(channels,
                config.ClientType,
                config.RpcType,
                config.OutstandingRpcsPerChannel,
                config.LoadParams,
                config.PayloadConfig,
                config.HistogramParams,
                () => GetNextProfiler());
        }
Пример #18
0
        /// <summary>
        /// Inspects the supplied evidence to return the signer appropriate for the operation and
        /// precomputes the body hash for the request if AWS4 protocol is selected.
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        private AbstractAWSSigner SelectSigner(ClientConfig config)
        {
            if (UseV4Signing(_useSigV4, config))
                return AWS4SignerInstance;

            return this;
        }
        public static void Run(string[] args)
        {
            Environment.SetEnvironmentVariable("hazelcast.logging.level", "info");
            Environment.SetEnvironmentVariable("hazelcast.logging.type", "console");

            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            var generator = client.GetIdGenerator("example-id-generator");

            generator.Init(1000);

            Action generateId = () =>
            {
                for (var i = 0; i < 100; i++)
                {
                    Console.WriteLine("Generated id: " + generator.NewId());
                }
            };
            var task1 = Task.Factory.StartNew(generateId);
            var task2 = Task.Factory.StartNew(generateId);

            Task.WaitAll(task1, task2);
            generator.Destroy();
        }
Пример #20
0
        public LinccerTasks()
        {
            this._config = new ClientConfig("Windows Phone Hoccer Demo");
            this._config.UseProductionServers(); // enables communication to real Hoccer Clients (iOS & Android)

            this._linccer = new Linccer();
            this._linccer.Config = this._config;
        }
 public virtual void TestNearCacheConfigWildcard3()
 {
     NearCacheConfig nearCacheConfig = new NearCacheConfig().SetName("com.hazelcast.test.*");
     ClientConfig config = new ClientConfig();
     config.SetConfigPatternMatcher(new MatchingPointConfigPatternMatcher());
     config.AddNearCacheConfig(nearCacheConfig);
     Assert.AreEqual(nearCacheConfig, config.GetNearCacheConfig("com.hazelcast.test.myNearCache"));
 }
Пример #22
0
 /// <summary>
 /// Determines the appropriate signer and signs the request.
 /// </summary>
 /// <param name="awsAccessKeyId">The AWS public key</param>
 /// <param name="awsSecretAccessKey">The AWS secret key used to sign the request in clear text</param>
 /// <param name="metrics">Request metrics</param>
 /// <param name="clientConfig">The configuration that specifies which hashing algorithm to use</param>
 /// <param name="request">The request to have the signature compute for</param>
 /// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception>
 public override void Sign(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
 {
     var aws4Signer = SelectSigner(clientConfig) as AWS4Signer;
     if (aws4Signer != null)
         aws4Signer.Sign(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey);
     else
         base.Sign(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey);
 }
Пример #23
0
 public static void AbandonSettings()
 {
     client = null;
     config = null;
     appSettings = null;
     lastResponse = null;
     serverKey = null;
     clientKey = null;
 }
Пример #24
0
 /// <summary>
 /// Calculates and signs the specified request using the AWS4 signing protocol by using the
 /// AWS account credentials given in the method parameters. The resulting signature is added
 /// to the request headers as 'Authorization'. Parameters supplied in the request, either in
 /// the resource path as a query string or in the Parameters collection must not have been
 /// uri encoded. If they have, use the SignRequest method to obtain a signature.
 /// </summary>
 /// <param name="request">
 /// The request to compute the signature for. Additional headers mandated by the AWS4 protocol 
 /// ('host' and 'x-amz-date') will be added to the request before signing.
 /// </param>
 /// <param name="clientConfig">
 /// Client configuration data encompassing the service call (notably authentication
 /// region, endpoint and service name).
 /// </param>
 /// <param name="metrics">
 /// Metrics for the request
 /// </param>
 /// <param name="awsAccessKeyId">
 /// The AWS public key for the account making the service call.
 /// </param>
 /// <param name="awsSecretAccessKey">
 /// The AWS secret key for the account making the call, in clear text.
 /// </param>
 /// <exception cref="Amazon.Runtime.SignatureException">
 /// If any problems are encountered while signing the request.
 /// </exception>
 public override void Sign(IRequest request, 
                           ClientConfig clientConfig, 
                           RequestMetrics metrics, 
                           string awsAccessKeyId, 
                           string awsSecretAccessKey)
 {
     var signingResult = SignRequest(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey);
     request.Headers[HeaderKeys.AuthorizationHeader] = signingResult.ForAuthorizationHeader;
 }
 public static void SendMessage(ulong steamdId, bool oldCommunicationVersion, bool newCommunicationVersion, ClientConfig clientConfig)
 {
     ConnectionHelper.SendMessageToPlayer(steamdId, new MessageConnectionResponse
     {
         OldCommunicationVersion = oldCommunicationVersion,
         NewCommunicationVersion = newCommunicationVersion,
         ClientConfig = clientConfig
     });
 }
        //    static HazelcastInstance second;
        /// <exception cref="System.Exception"></exception>
        public static void Mainwq(string[] args)
        {
            var config = new ClientConfig();
            config.GetNetworkConfig().AddAddress("127.0.0.1");
            var client = HazelcastClient.NewHazelcastClient(config);

            q = client.GetQueue<object>("test");
            Test1();
        }
 public virtual void TestMapConfigWildcardMultipleAmbiguousConfigs()
 {
     NearCacheConfig nearCacheConfig1 = new NearCacheConfig().SetName("com.hazelcast*");
     NearCacheConfig nearCacheConfig2 = new NearCacheConfig().SetName("*com.hazelcast");
     ClientConfig config = new ClientConfig();
     config.SetConfigPatternMatcher(new MatchingPointConfigPatternMatcher());
     config.AddNearCacheConfig(nearCacheConfig1);
     config.AddNearCacheConfig(nearCacheConfig2);
     config.GetNearCacheConfig("com.hazelcast");
 }
Пример #28
0
        public void TestInitialize()
        {
            Config = new ClientConfig().SetupForTesting();
            Client = new PaymentClient(Config);

            PaymentAmount = 3000;
            CardNumber = "4444333322221111";
            Expires = new YearMonth(DateTime.Today.Year + 1, DateTime.Today.Month);
            Ccv = "123";
        }
Пример #29
0
        public static ApiClient GetRealApiClient()
        {
            if (_realApiClient == null)
            {
                var config = new ClientConfig(_debugApiKey);
                _realApiClient = new ApiClient(config);
            }

            return _realApiClient;
        }
Пример #30
0
 /// <summary>
 /// Signs the specified request with the AWS3 signing protocol by using the
 /// AWS account credentials given in the method parameters.
 /// </summary>
 /// <param name="awsAccessKeyId">The AWS public key</param>
 /// <param name="awsSecretAccessKey">The AWS secret key used to sign the request in clear text</param>
 /// <param name="metrics">Request metrics</param>
 /// <param name="clientConfig">The configuration that specifies which hashing algorithm to use</param>
 /// <param name="request">The request to have the signature compute for</param>
 /// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception>
 public override void Sign(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey) 
 {
     if (UseAws3Https)
     {
         SignHttps(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey);
     }
     else
     {
         SignHttp(request, metrics, awsAccessKeyId, awsSecretAccessKey);
     }
 }
Пример #31
0
        public void Check()
        {
            StatusReportList = new List <Report>();
            var clusters              = _setting.General.Kafka.Clusters;
            var connectionTimeoutSec  = _setting.General.Kafka.ConnectionTimeoutSec;
            var topicNameFromSettings = _setting.General.Kafka.TopicName;
            var certificateLocation   = _setting.General.Kafka.SslCertificateLocation;
            var certificateSubject    = _setting.General.Kafka.SslCertificateSubject;
            var date = DateTime.Now.ToString("dd.MM.yyyy.HH.m");


            if (File.Exists(certificateLocation))
            {
                // delete an old certificate
                File.Delete(certificateLocation);
            }

            var counter = 0;

            foreach (var cluster in clusters)
            {
                counter++;
                string topicName;
                var    kafkaStatus   = ReportStatus.Undefined;
                var    mongoDbStatus = ReportStatus.Undefined;
                var    statusReport  = new Report();
                statusReport.Number  = counter;
                statusReport.EnvName = cluster.Name;
                _logger.Info($" [{counter}] from [{clusters.Count}]. " +
                             $"Work with the '{cluster.Name}' cluster");

                // Check Mongo
                _logger.Info($"Checking Mongo DB:");
                var mongoDbHelper        = new MongoDbHelper();
                var mongoDbConnectionStr = cluster.MongoDb;
                mongoDbStatus = mongoDbHelper.Ping(mongoDbConnectionStr, connectionTimeoutSec);

                // Check Kafka
                _logger.Info("Checking Kafka:");
                var bootStrapServers = string.Join(",", cluster.BootstrapServers);
                _logger.Info($" bootstrap servers: {bootStrapServers}");
                var clientConfig = new ClientConfig
                {
                    BootstrapServers = bootStrapServers,
                    SocketTimeoutMs  = connectionTimeoutSec * 1000,
                };
                topicName = $"{topicNameFromSettings}.{date}";
                if (cluster.SslEnabled)
                {
                    _logger.Info("SSL connection is enabled for this cluster");
                    if (!File.Exists(certificateLocation))
                    {
                        try
                        {
                            var certificate = CertificateHelper.GetCertificate(certificateSubject);
                            CertificateHelper.ExportToPEMFile(certificate, certificateLocation);
                        }
                        catch (CertificateException ce)
                        {
                            _logger.Error(ce.Message);
                            kafkaStatus = ReportStatus.CertificateError;
                            _logger.Warn($" Kafka status - [{kafkaStatus}]");
                            WriteClusterStatus(cluster, statusReport, mongoDbStatus, kafkaStatus);
                            StatusReportList.Add(statusReport);
                            continue;
                        }
                    }
                    clientConfig.SslCaLocation    = certificateLocation;
                    clientConfig.SecurityProtocol = SecurityProtocol.Ssl;
                    clientConfig.Debug            = "security";
                    topicName = $"{topicNameFromSettings}.ssl.{date}";
                }
                var bootstrapServersCount = cluster.BootstrapServers.Count;
                var topicHelper           = new TopicHelper();
                var producerConsumer      = new ProducerConsumer();

                var connectionIsOk = topicHelper
                                     .CheckConnectivity(clientConfig,
                                                        bootstrapServersCount);

                if (connectionIsOk)
                {
                    var topicWasCreated = topicHelper
                                          .CreateTopic(clientConfig, bootstrapServersCount, topicName);
                    if (topicWasCreated)
                    {
                        _logger.Info(string.Empty);
                        var producedMessageCount = producerConsumer.Produce(clientConfig, topicName);
                        var consumedMessageCount = producerConsumer.Consume(clientConfig, topicName);

                        if (producedMessageCount == consumedMessageCount)
                        {
                            _logger.Info($" * Produced messages == consumed messages: '{consumedMessageCount}' - [ok]");
                            kafkaStatus = ReportStatus.Ok;
                        }
                        else
                        {
                            _logger.Error($" * Produced messages != consumed messages: '{consumedMessageCount}' - [error]");
                            kafkaStatus = ReportStatus.Error;
                        }
                    }
                }
                else
                {
                    kafkaStatus = ReportStatus.Error;
                }
                _logger.Info($" Kafka status - [{kafkaStatus}]");
                WriteClusterStatus(cluster, statusReport, mongoDbStatus, kafkaStatus);
                StatusReportList.Add(statusReport);
                _logger.Info(string.Empty);
            }
            new HtmlReportHelper().PopulateTemplate(StatusReportList);
        }
Пример #32
0
 /// <summary>
 /// Constructer
 /// </summary>
 public AuditClient(ClientConfig config, IOciSigner ociSigner) : base(config, ociSigner)
 {
     ServiceName = AuditServiceName;
 }
Пример #33
0
 /// <summary>
 /// Constructer
 /// </summary>
 public AuditClient(ClientConfig config) : base(config)
 {
     ServiceName = AuditServiceName;
 }
Пример #34
0
        /// <summary>
        ///     Attempt to connect to a server
        /// </summary>
        /// <param name="clientConfig">Client config params</param>
        /// <returns>True if the client is connected to the server, false if not</returns>
        public bool Connect(ClientConfig clientConfig)
        {
            // Let the user know that we are trying to connect to a server
            _logger.Info($"Attempting to connect to server at {clientConfig.HostAddress}:{clientConfig.Port}...");

            // if we are currently trying to connect, cancel
            // and try again.
            if (Status == ClientStatus.Connecting)
            {
                _logger.Info("Current status is 'connecting', attempting to disconnect first.");
                Disconnect();
            }

            // The client is already connected so we need to
            // disconnect.
            if (Status == ClientStatus.Connected)
            {
                _logger.Info("Current status is 'connected', attempting to disconnect first.");
                Disconnect();
            }

            // Set the configuration
            Config = clientConfig;

            // Start the client, if client setup fails, return out and
            // tell the user
            bool result = _netClient.Start();

            if (!result)
            {
                _logger.Error("The client failed to start.");
                ConnectionMessage = "The client failed to start.";
                Disconnect(); // make sure we are fully disconnected
                return(false);
            }

            _logger.Info("Set status to 'connecting'...");

            // Try connect to server, update the status to say that
            // we are trying to connect.
            try
            {
                _netClient.Connect(Config.HostAddress, Config.Port, "CSM");
            }
            catch (Exception ex)
            {
                ConnectionMessage = "Failed to connect.";
                _logger.Error(ex, $"Failed to connect to {Config.HostAddress}:{Config.Port}");
                ChatLogPanel.PrintGameMessage(ChatLogPanel.MessageType.Error, $"Failed to connect: {ex.Message}");
                Disconnect();
                return(false);
            }

            // Start processing networking
            Status   = ClientStatus.Connecting;
            ClientId = 0;

            // We need to wait in a loop for 30 seconds (waiting 500ms each time)
            // while we wait for a successful connection (Status = Connected) or a
            // failed connection (Status = Disconnected).
            Stopwatch waitWatch = new Stopwatch();

            waitWatch.Start();

            // Try connect for 30 seconds
            while (waitWatch.Elapsed < TimeSpan.FromSeconds(30))
            {
                // If we connect, exit the loop and return true
                if (Status == ClientStatus.Connected || Status == ClientStatus.Downloading || Status == ClientStatus.Loading)
                {
                    _logger.Info("Client has connected.");
                    return(true);
                }

                // The client cannot connect for some reason, the ConnectionMessage
                // variable will contain why.
                if (Status == ClientStatus.Disconnected)
                {
                    _logger.Warn("Client disconnected while in connecting loop.");
                    Disconnect(); // make sure we are fully disconnected
                    return(false);
                }

                // Wait 250ms
                Thread.Sleep(250);
            }

            // We have timed out
            ConnectionMessage = "Could not connect to server, timed out.";
            _logger.Warn("Connection timeout!");

            // Did not connect
            Disconnect(); // make sure we are fully disconnected
            return(false);
        }
Пример #35
0
        public bool SetMailBoxSettings(ClientConfig config, bool isUserData)
        {
            try
            {
                if (string.IsNullOrEmpty(config.EmailProvider.Id) ||
                    !config.EmailProvider.Domain.Any() ||
                    config.EmailProvider.IncomingServer == null ||
                    !config.EmailProvider.IncomingServer.Any() ||
                    config.EmailProvider.OutgoingServer == null ||
                    !config.EmailProvider.OutgoingServer.Any())
                {
                    throw new Exception("Incorrect config");
                }

                using (var daoFactory = new DaoFactory())
                {
                    using (var tx = daoFactory.DbManager.BeginTransaction())
                    {
                        var daoMbProvider = daoFactory.CreateMailboxProviderDao();

                        var provider = daoMbProvider.GetProvider(config.EmailProvider.Id);

                        if (provider == null)
                        {
                            provider = new MailboxProvider
                            {
                                Id               = 0,
                                Name             = config.EmailProvider.Id,
                                DisplayName      = config.EmailProvider.DisplayName,
                                DisplayShortName = config.EmailProvider.DisplayShortName,
                                Url              = config.EmailProvider.Documentation.Url
                            };

                            provider.Id = daoMbProvider.SaveProvider(provider);

                            if (provider.Id < 0)
                            {
                                tx.Rollback();
                                throw new Exception("id_provider not saved into DB");
                            }
                        }

                        var daoMbDomain = daoFactory.CreateMailboxDomainDao();

                        foreach (var domainName in config.EmailProvider.Domain)
                        {
                            var domain = daoMbDomain.GetDomain(domainName);

                            if (domain != null)
                            {
                                continue;
                            }

                            domain = new MailboxDomain
                            {
                                Id         = 0,
                                ProviderId = provider.Id,
                                Name       = domainName
                            };

                            domain.Id = daoMbDomain.SaveDomain(domain);

                            if (domain.Id < 0)
                            {
                                tx.Rollback();
                                throw new Exception("id_domain not saved into DB");
                            }
                        }

                        var daoMbServer = daoFactory.CreateMailboxServerDao();

                        var existingServers = daoMbServer.GetServers(provider.Id);

                        var newServers = config.EmailProvider
                                         .IncomingServer
                                         .ConvertAll(s => new MailboxServer
                        {
                            Id             = 0,
                            Username       = s.Username,
                            Type           = s.Type,
                            ProviderId     = provider.Id,
                            Hostname       = s.Hostname,
                            Port           = s.Port,
                            SocketType     = s.SocketType,
                            Authentication = s.Authentication,
                            IsUserData     = isUserData
                        });

                        newServers.AddRange(config.EmailProvider
                                            .OutgoingServer
                                            .ConvertAll(s => new MailboxServer
                        {
                            Id             = 0,
                            Username       = s.Username,
                            Type           = s.Type,
                            ProviderId     = provider.Id,
                            Hostname       = s.Hostname,
                            Port           = s.Port,
                            SocketType     = s.SocketType,
                            Authentication = s.Authentication,
                            IsUserData     = isUserData
                        }));

                        foreach (var s in newServers)
                        {
                            var existing =
                                existingServers.FirstOrDefault(
                                    es =>
                                    es.Type.Equals(s.Type) && es.Port == s.Port &&
                                    es.SocketType.Equals(s.SocketType));

                            if (existing != null)
                            {
                                if (existing.Equals(s))
                                {
                                    continue;
                                }

                                s.Id = existing.Id;
                            }

                            s.Id = daoMbServer.SaveServer(s);

                            if (s.Id < 0)
                            {
                                tx.Rollback();
                                throw new Exception("id_server not saved into DB");
                            }
                        }

                        tx.Commit();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("SetMailBoxSettings failed", ex);

                return(false);
            }

            return(true);
        }
Пример #36
0
 public KafkaSslConfigurator(ClientConfig clientConfig)
 {
     _clientConfig = clientConfig;
 }
Пример #37
0
 public BaiduAuthRequest(ClientConfig config, IAuthStateCache authStateCache)
     : base(config, new BaiduAuthSource(), authStateCache)
 {
 }
Пример #38
0
 public RenrenAuthRequest(ClientConfig config, IAuthStateCache authStateCache)
     : base(config, new RenrenAuthSource(), authStateCache)
 {
 }
Пример #39
0
 public RenrenAuthRequest(ClientConfig config) : base(config, new RenrenAuthSource())
 {
 }
Пример #40
0
 public UniversalClient(ClientConfig config) : base(new byte[8096], new byte[8096])
 {
     _config        = config;
     _User          = new UserInfo();
     _User.UserName = _config.UserName;
 }
Пример #41
0
 public AlipayMpAuthRequest(ClientConfig config, IAuthStateCache authStateCache) : base(config, new AlipayMPAuthSource(), authStateCache)
 {
     aopClient = new DefaultAopClient(source.AccessToken(), config.ClientId, config.ClientSecret, "json", "1.0", "RSA2", config.alipayPublicKey, "GBK", false);
 }
Пример #42
0
 /// <summary>
 /// Constructer
 /// </summary>
 public ObjectStorageClient(ClientConfig config) : base(config)
 {
     ServiceName = ObjectStorageServiceName;
 }
Пример #43
0
 /// <summary>
 /// Constructer
 /// </summary>
 public ObjectStorageClient(ClientConfig config, OciSigner ociSigner) : base(config, ociSigner)
 {
     ServiceName = ObjectStorageServiceName;
 }
Пример #44
0
 internal static Uri DetermineEndpoint(ClientConfig config, IRequest request)
 {
     return(request.AlternateEndpoint != null
          ? new Uri(ClientConfig.GetUrl(request.AlternateEndpoint, config.RegionEndpointServiceName, config.UseHttp))
          : new Uri(config.DetermineServiceURL()));
 }
Пример #45
0
 /// <summary>
 /// Constructer
 /// </summary>
 public MonitoringClient(ClientConfig config, IOciSigner ociSigner) : base(config, ociSigner)
 {
     ServiceName = monitaringServiceName;
 }
Пример #46
0
 public MessageHelper()
 {
     clientConfig = ClientConfig.Instance();
 }
Пример #47
0
 /// <summary>
 /// Constructer
 /// </summary>
 public MonitoringClient(ClientConfig config) : base(config)
 {
     ServiceName = monitaringServiceName;
 }
Пример #48
0
 public abstract void Sign(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey);
 public ClientGuideConf(ClientConfig m) : base(m)
 {
 }
Пример #50
0
 protected AbstractAWSSigner SelectSigner(IRequest request, ClientConfig config)
 {
     return(SelectSigner(this, useSigV4Setting: false, request: request, config: config));
 }
Пример #51
0
 public BaiduAuthRequest(ClientConfig config) : base(config, new BaiduAuthSource())
 {
 }
        /// <summary>
        /// Awaitable task to create a single topic by name, if it does not exist yet.
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="numPartitions"></param>
        /// <param name="replicationFactor"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static async Task CreateTopicIfNotExists(string topic, int numPartitions, short replicationFactor, ClientConfig configuration)
        {
            using (var adminClient = new AdminClientBuilder(configuration).Build())
            {
                try
                {
                    var topicSpecification = new TopicSpecification
                    {
                        Name              = topic,
                        NumPartitions     = numPartitions,
                        ReplicationFactor = replicationFactor
                    };

                    // CreateTopicAsync can take a list, but for here only a single topic is passed as input.
                    await adminClient.CreateTopicsAsync(new List <TopicSpecification> {
                        topicSpecification
                    });

                    Console.WriteLine($"Topic {topic} created.");
                }
                catch (CreateTopicsException ex)
                {
                    if (ex.Results[0].Error.Code != ErrorCode.TopicAlreadyExists)
                    {
                        Console.WriteLine($"An error occured creating topic {topic}: {ex.Results[0].Error.Reason}");
                    }
                    else
                    {
                        Console.WriteLine($"Topic {topic} already exists.");
                    }
                }
            }
        }
Пример #53
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Read environment Values
            string dbServer   = Configuration.GetValue <string>("DB_SERVER");
            string dbUser     = Configuration.GetValue <string>("DB_USER");
            string dbPassword = Configuration.GetValue <string>("DB_PASSWORD");

            string secretKey = Configuration.GetValue <string>("SECRET_KEY");

            string messagingBrokers = Configuration.GetValue <string>("MESSAGING_BROKERS");


            // Connection string from appsettings
            string connectionString = Configuration.GetConnectionString("AppDB");

            string dbConnectionString = connectionString.Replace("DB_SERVER", dbServer)
                                        .Replace("DB_USER", dbUser)
                                        .Replace("DB_PASSWORD", dbPassword);


            // DB Contexts
            // if env variables not set use connection string as it is
            services.AddDbContext <AppDbContext>(options =>
                                                 options.UseMySql(dbConnectionString, ServerVersion.AutoDetect(String.IsNullOrEmpty(dbServer) ? connectionString : dbConnectionString)));

            // Register the ConfigurationBuilder instance of AuthSettings
            var authSettings = Configuration.GetSection(nameof(AuthSettings));

            services.Configure <AuthSettings>(authSettings);


            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey + "" == "" ? authSettings[nameof(AuthSettings.SecretKey)] : secretKey));

            // jwt wire up
            // Get options from app settings
            var jwtAppSettingOptions = Configuration.GetSection("JwtIssuerOptions");

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer    = jwtAppSettingOptions["Issuer"],

                ValidateAudience = true,
                ValidAudience    = jwtAppSettingOptions["Audience"],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,

                RequireExpirationTime = false,
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(configureOptions =>
            {
                configureOptions.ClaimsIssuer = jwtAppSettingOptions["Issuer"];
                configureOptions.TokenValidationParameters = tokenValidationParameters;
                configureOptions.SaveToken = true;

                configureOptions.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("X-Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            });


            services.AddControllers()
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <BaseCommand>());

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "App.API", Version = "v1"
                });
            });


            //Kafka
            var messagingConfigs = Configuration.GetSection("Messaging");

            var clientConfig = new ClientConfig
            {
                BootstrapServers = String.IsNullOrEmpty(messagingBrokers) ? messagingConfigs["BootstrapServers"] : messagingBrokers
            };

            var consumerConfig = new ConsumerConfig(clientConfig)
            {
                GroupId              = "MessagesApp",
                EnableAutoCommit     = true,
                AutoOffsetReset      = AutoOffsetReset.Earliest,
                StatisticsIntervalMs = 5000,
                SessionTimeoutMs     = 6000
            };


            services.AddSingleton(consumerConfig);

            services.AddScoped(typeof(IMessageHandler <string, NotificationMessageDTO>), typeof(NotificationMessageHandler));
            services.AddSingleton(typeof(IMessageConsumer <,>), typeof(MessageConsumer <,>));
            services.AddHostedService <NotificationMessageConsumer>();

            services.AddTransient <IMachineDateTime, MachineDateTime>();
            services.AddTransient <IMachineLogger, MachineLogger>();

            services.AddTransient <IFileUtils, FileUtils>();
            services.AddTransient <IStringUtils, StringUtils>();
            services.AddTransient <IEmailService, EmailService>();

            //Add Mediator
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>));
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPerformanceBehaviour <,>));
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestValidationBehaviour <,>));
            services.AddMediatR(typeof(SeedDBCommand).GetTypeInfo().Assembly);


            //CORS
            services.ConfigureCors(Configuration);
        }
Пример #54
0
        public static ClientOrder GetSampleOrder()
        {
            ClientOrder client_order = new ClientOrder();

            ReportConfig report_config = new ReportConfig();

            report_config.disclaimer   = "We have made every effort to ensure the accuracy of this tax information.  However, due to the frequency with which municipalities revise their fees and other specifications, we cannot assume liability for any discrepancy in the taxes.  In the event that tax amounts have changed, please notify us so we can update our records.  Possible revenue bond charges for sewer and water pursuant to state statutes and local ordinances when connection to the system is made by the owner.  The exact current and continuing charges depend on all the facts.  Contact local officials for details.  This report is based on best available information at the time.  This is for informational purposes only and will not appear on title policy.\r\nPatent Pending ";
            client_order.report_config = report_config;

            ClientConfig client_config = new ClientConfig();

            client_config.base_path    = @"D:\Programming\0_crap\";
            client_config.report_name  = "Tax_Research.xlsx";
            client_config.logo         = @"D:\Programming\0_crap\logo.jpg";
            client_order.client_config = client_config;

            ParcelInformation parcel = new ParcelInformation();

            parcel.client_po_number   = "U NTN-ARS-12345";
            parcel.researcher         = "erice";
            parcel.owner_1            = "Buddy Rice";
            parcel.owner_2            = "Ashley Gonzalez";
            parcel.address            = "427 8th Ave N";
            parcel.city               = "Saint Petersburg";
            parcel.state              = "FL";
            parcel.zip_code           = "33701";
            parcel.county             = "PINELLAS";
            parcel.searched_address   = "427 8th Ave N";
            parcel.searched_city      = "Saint Petersburg";
            parcel.searched_state     = "FL";
            parcel.searched_zip_code  = "33701";
            parcel.assessed_owner_1   = "Buddy Rice";
            parcel.assessed_owner_2   = "Ashley Gonzalez";
            parcel.parcel_number      = "18-31-17-77814-001-0060";
            parcel.effective_date     = DateTime.Parse("2018-05-01");
            parcel.legal_desc         = "SAFFORD'S ADD REVISED BLK 1, E 75FT OF LOTS 6 AND 7";
            parcel.class_code         = "Apartments (10 units to 49 units)";
            parcel.assessed_valuation = 408980.00M;

            TaxAuthorityPaymentRecord payment_record = new TaxAuthorityPaymentRecord();

            payment_record.tax_type        = "County";
            payment_record.additional_data = "";
            payment_record.research_notes  = "";
            payment_record.lump_sum        = 1;
            payment_record.ex_homestead    = 0;
            payment_record.ex_disabled     = 0;
            payment_record.ex_veteran      = 1;
            payment_record.ex_mortgage     = 0;
            payment_record.ex_star         = 0;
            payment_record.ex_elderly      = 0;
            payment_record.ex_other        = string.Empty;
            payment_record.assessed_value  = 408980.00M;
            payment_record.land_value      = 225600.00M;
            payment_record.improved_value  = 45100.00M;
            payment_record.unincorporated  = 0;
            payment_record.lawsuit         = string.Empty;
            payment_record.lawsuit_case    = string.Empty;

            TaxAuthority tax_authority = new TaxAuthority();

            tax_authority.name               = "Pinellas County Tax Collector";
            tax_authority.payment_name       = "Pinellas County Tax Collector";
            tax_authority.current_tax_year   = "2018";
            tax_authority.discounts          = "N/A";
            tax_authority.duplicate_bill_fee = 5.00M;
            tax_authority.fiscal_year        = "2018";
            tax_authority.payment_address_1  = "1800 66th Street North";
            tax_authority.payment_address_2  = "suite ABC";
            tax_authority.payment_city       = "St.Petersburg";
            tax_authority.payment_state      = "FL";
            tax_authority.payment_zip        = "33710";
            tax_authority.payment_phone      = "(727)123-4567";
            tax_authority.payment_ext        = "9876";
            tax_authority.schedule           = "Annually";
            tax_authority.ta_other_notes     = "Pinellas County is the only taxing authority for this property.\n\nPinellas County collects annually due by 7/15 with an option to pay in installments due by 7/15, 10/15, 1/15 & 4/15.\n\nThere is a 10 day grace period for installment 1 only.\n\nPINELLAS COUNTY DOES NOT PROVIDE PAID DATES; PAYMENTS ARE PROCESSED AS PAID TIMELY BY THE DUE DATE.";
            payment_record.tax_authority     = tax_authority;

            TaxInformation tax_info = new TaxInformation();

            tax_info.jurisdiction_name = "Pinellas County Tax Collector";
            tax_info.jurisdiction_type = "County";
            tax_info.tax_rate          = 0.00M;
            tax_info.exemptions        = "Veterine Exemption";
            tax_info.milage_rate       = 22.0150M;
            tax_info.milage_next_due   = DateTime.Parse("2018-12-01");

            PaymentInstallment install_1 = new PaymentInstallment();

            install_1.amount_due        = 0.00M;
            install_1.paid              = 2459.89M;
            install_1.base_amount       = 2459.89M;
            install_1.date_due          = DateTime.Parse("2017-12-31");
            install_1.date_good_thru    = DateTime.Parse("2018-02-28");
            install_1.date_paid         = DateTime.Parse("2018-02-01");
            install_1.delinquent_amount = 0.00M;
            install_1.install           = 1;
            install_1.is_delinquent     = 0;
            install_1.is_estimate       = 0;
            install_1.is_exempt         = 0;
            install_1.is_partial        = 0;
            install_1.one_month         = 0.00M;
            install_1.two_month         = 0.00M;
            payment_record.installments.Add(install_1);

            PaymentInstallment install_2 = new PaymentInstallment();

            install_2.amount_due        = 0.00M;
            install_2.paid              = 2459.89M;
            install_2.base_amount       = 2459.89M;
            install_2.date_due          = DateTime.Parse("2017-12-31");
            install_2.date_good_thru    = DateTime.Parse("2018-02-01");
            install_2.date_paid         = DateTime.Parse("2018-02-01");
            install_2.delinquent_amount = 0.00M;
            install_2.install           = 2;
            install_2.is_delinquent     = 0;
            install_2.is_estimate       = 0;
            install_2.is_exempt         = 0;
            install_2.is_partial        = 0;
            install_2.one_month         = 0.00M;
            install_2.two_month         = 0.00M;
            payment_record.installments.Add(install_2);

            PaymentInstallment install_3 = new PaymentInstallment();

            install_3.amount_due        = 0.00M;
            install_3.paid              = 2459.89M;
            install_3.base_amount       = 2459.89M;
            install_3.date_due          = DateTime.Parse("2017-12-31");
            install_3.date_good_thru    = DateTime.Parse("2018-02-01");
            install_3.date_paid         = DateTime.Parse("2018-02-01");
            install_3.delinquent_amount = 0.00M;
            install_3.install           = 3;
            install_3.is_delinquent     = 0;
            install_3.is_estimate       = 0;
            install_3.is_exempt         = 0;
            install_3.is_partial        = 0;
            install_3.one_month         = 0.00M;
            install_3.two_month         = 0.00M;
            payment_record.installments.Add(install_3);

            PaymentInstallment install_4 = new PaymentInstallment();

            install_4.amount_due        = 2459.89M;
            install_4.base_amount       = 2459.89M;
            install_4.date_due          = DateTime.Parse("2017-12-31");
            install_4.date_good_thru    = DateTime.Parse("2018-02-01");
            install_4.date_paid         = DateTime.MinValue;
            install_4.delinquent_amount = 0.00M;
            install_4.install           = 4;
            install_4.is_delinquent     = 1;
            install_4.is_estimate       = 0;
            install_4.is_exempt         = 0;
            install_4.is_partial        = 0;
            install_4.one_month         = 0.00M;
            install_4.two_month         = 0.00M;
            payment_record.installments.Add(install_4);

            payment_record.tax_information = tax_info;
            parcel.payment_records.Add(payment_record);
            client_order.Parcels.Add(parcel);

            return(client_order);
        }
Пример #55
0
        private static ClientConfig GetStoredMailBoxSettings(string host)
        {
            using (var daoFactory = new DaoFactory())
            {
                var daoMbDomain = daoFactory.CreateMailboxDomainDao();

                var domain = daoMbDomain.GetDomain(host);

                if (domain == null)
                {
                    return(null);
                }

                var daoMbProvider = daoFactory.CreateMailboxProviderDao();

                var provider = daoMbProvider.GetProvider(domain.ProviderId);

                if (provider == null)
                {
                    return(null);
                }

                var daoMbServer = daoFactory.CreateMailboxServerDao();

                var existingServers = daoMbServer.GetServers(provider.Id);

                if (!existingServers.Any())
                {
                    return(null);
                }

                var config = new ClientConfig();

                config.EmailProvider.Domain.Add(host);
                config.EmailProvider.Id                = provider.Name;
                config.EmailProvider.DisplayName       = provider.DisplayName;
                config.EmailProvider.DisplayShortName  = provider.DisplayShortName;
                config.EmailProvider.Documentation.Url = provider.Url;

                existingServers.ForEach(serv =>
                {
                    if (serv.Type == "smtp")
                    {
                        config.EmailProvider.OutgoingServer.Add(
                            new ClientConfigEmailProviderOutgoingServer
                        {
                            Type           = serv.Type,
                            SocketType     = serv.SocketType,
                            Hostname       = serv.Hostname,
                            Port           = serv.Port,
                            Username       = serv.Username,
                            Authentication = serv.Authentication
                        });
                    }
                    else
                    {
                        config.EmailProvider.IncomingServer.Add(
                            new ClientConfigEmailProviderIncomingServer
                        {
                            Type           = serv.Type,
                            SocketType     = serv.SocketType,
                            Hostname       = serv.Hostname,
                            Port           = serv.Port,
                            Username       = serv.Username,
                            Authentication = serv.Authentication
                        });
                    }
                });

                if (!config.EmailProvider.IncomingServer.Any() || !config.EmailProvider.OutgoingServer.Any())
                {
                    return(null);
                }

                return(config);
            }
        }
Пример #56
0
 public AADTokenHelper(ClientConfig clientConfig, HostConfig hostConfig)
 {
     this.clientConfig = clientConfig;
     this.hostConfig   = hostConfig;
 }
Пример #57
0
        private MethodReturnResult PrintPrivate(LotCreateDetailViewModel model)
        {
            MethodReturnResult result = new MethodReturnResult();

            //不需要进行标签打印。
            if (model.PrintQty <= 0 ||
                string.IsNullOrEmpty(model.PrinterName) ||
                string.IsNullOrEmpty(model.PrintLabelCode))
            {
                return(result);
            }

            char splitChar = ',';

            //获取批次号值。
            string[] lotNumbers = Request["LotNumber"].ToUpper().Split(splitChar);

            //获取打印机名称
            ClientConfig printer = null;

            using (ClientConfigServiceClient client = new ClientConfigServiceClient())
            {
                MethodReturnResult <ClientConfig> rst = client.Get(model.PrinterName);
                if (rst.Code > 0)
                {
                    return(rst);
                }
                printer = rst.Data;
            }
            //获取打印条码内容
            PrintLabel label = null;

            using (PrintLabelServiceClient client = new PrintLabelServiceClient())
            {
                MethodReturnResult <PrintLabel> rst = client.Get(model.PrintLabelCode);
                if (rst.Code > 0)
                {
                    return(rst);
                }
                label = rst.Data;
            }
            //根据打印数量设置打印机模板。
            using (IPrintHelper helper = PrintHelperFactory.CreatePrintHelper(label.Content))
            {
                foreach (string lotNumber in lotNumbers)
                {
                    //打印动态内容。
                    dynamic d = new ExpandoObject();
                    d.LotNumber = lotNumber;
                    d.PrintQty  = model.PrintQty;
                    bool bSuccess = false;
                    //根据打印机类型,调用不同的打印方法。
                    if (printer.ClientType == EnumClientType.NetworkPrinter)
                    {
                        string[] vals = printer.IPAddress.Split(':');
                        string   port = "9100";
                        if (vals.Length > 1)
                        {
                            port = vals[1];
                        }
                        bSuccess = helper.NetworkPrint(vals[0], port, label.Content, d);
                    }
                    else if (printer.ClientType == EnumClientType.RawPrinter)
                    {
                        bSuccess = helper.RAWPrint(printer.IPAddress, label.Content, d);
                    }
                    else
                    {
                        result.Code    = 1001;
                        result.Message = "打印失败,打印机类型不正确。";
                        return(result);
                    }
                    //返回打印结果。
                    if (bSuccess == false)
                    {
                        result.Code    = 1001;
                        result.Message = "批次标签打印失败。";
                        return(result);
                    }
                }
            }
            return(result);
        }
Пример #58
0
        /// <summary>
        /// Configures a request as per the request context.
        /// </summary>
        /// <param name="requestContext">The request context.</param>
        public virtual void ConfigureRequest(IRequestContext requestContext)
        {
            // Set HttpWebRequest specific properties which are
            // not exposed in the IHttpRequest interface.

            var clientConfig    = requestContext.ClientConfig;
            var originalRequest = requestContext.OriginalRequest;

            // If System.Net.WebRequest.AllowAutoRedirect is set to true (default value),
            // redirects for GET requests are automatically followed and redirects for POST
            // requests are thrown back as exceptions.

            // If System.Net.WebRequest.AllowAutoRedirect is set to false (e.g. S3),
            // redirects are returned as responses.
            _request.AllowAutoRedirect = clientConfig.AllowAutoRedirect;

            // Configure timeouts.
            if (requestContext.Request.ContentStream != null)
            {
                _request.Timeout                   = int.MaxValue;
                _request.ReadWriteTimeout          = int.MaxValue;
                _request.AllowWriteStreamBuffering = false;
            }

            // Override the Timeout and ReadWriteTimeout values if set at the request or config level.
            // Public Timeout and ReadWriteTimeout properties are present on client config objects.
            var timeout          = ClientConfig.GetTimeoutValue(clientConfig.Timeout, originalRequest.TimeoutInternal);
            var readWriteTimeout = ClientConfig.GetTimeoutValue(clientConfig.ReadWriteTimeout, originalRequest.ReadWriteTimeoutInternal);

            if (timeout != null)
            {
                _request.Timeout = (int)timeout.Value.TotalMilliseconds;
            }
            if (readWriteTimeout != null)
            {
                _request.ReadWriteTimeout = (int)readWriteTimeout.Value.TotalMilliseconds;
            }

            // Set proxy related properties
            IWebProxy proxy = requestContext.ClientConfig.GetWebProxy();

            if (proxy != null)
            {
                requestContext.Metrics.AddProperty(Metric.ProxyHost, requestContext.ClientConfig.ProxyHost);
                requestContext.Metrics.AddProperty(Metric.ProxyPort, requestContext.ClientConfig.ProxyPort);
                _request.Proxy = proxy;
            }

            // Set service point properties.
            _request.ServicePoint.ConnectionLimit   = clientConfig.ConnectionLimit;
            _request.ServicePoint.UseNagleAlgorithm = clientConfig.UseNagleAlgorithm;
            _request.ServicePoint.MaxIdleTime       = clientConfig.MaxIdleTime;
            _request.ServicePoint.Expect100Continue = originalRequest.GetExpect100Continue();

            var tcpKeepAlive = clientConfig.TcpKeepAlive;

            _request.ServicePoint.SetTcpKeepAlive(
                tcpKeepAlive.Enabled,
                (int)tcpKeepAlive.Timeout.Value.TotalMilliseconds,
                (int)tcpKeepAlive.Interval.Value.TotalMilliseconds);
        }
Пример #59
0
        void LaunchMigration(
            string unityAccessToken,
            string projectPath,
            string organizationName,
            RepId repId,
            long changesetId,
            long branchId,
            Action afterWorkspaceMigratedAction,
            ProgressControlsForMigration progressControls)
        {
            string serverName = string.Format(
                "{0}@cloud", organizationName);

            TokenExchangeResponse tokenExchangeResponse = null;

            mWorkspaceInfo = null;

            CreateWorkspaceFromCollab.Progress progress = new CreateWorkspaceFromCollab.Progress();

            BuildProgressSpeedAndRemainingTime.ProgressData progressData =
                new BuildProgressSpeedAndRemainingTime.ProgressData(DateTime.Now);

            IThreadWaiter waiter = ThreadWaiter.GetWaiter(10);

            waiter.Execute(
                /*threadOperationDelegate*/
                delegate
            {
                // we just migrate a cloud project,
                // so let's assume we're going to use Cloud Edition
                SetupUnityEditionToken.CreateCloudEditionTokenIfNeeded();

                if (!ClientConfig.IsConfigured())
                {
                    AutoConfigClientConf.FromUnityAccessToken(
                        unityAccessToken, serverName, projectPath);
                }

                tokenExchangeResponse = WebRestApiClient.
                                        PlasticScm.TokenExchange(unityAccessToken);

                if (tokenExchangeResponse.Error != null)
                {
                    return;
                }

                CloudEditionWelcomeWindow.JoinCloudServer(
                    serverName,
                    tokenExchangeResponse.User,
                    tokenExchangeResponse.AccessToken);

                RepositoryInfo repInfo = new BaseCommandsImpl().
                                         GetRepositoryInfo(repId, serverName);

                if (repInfo == null)
                {
                    return;
                }

                repInfo.SetExplicitServer(serverName);

                mWorkspaceInfo = CreateWorkspaceFromCollab.Create(
                    projectPath, repInfo.Name, repInfo,
                    changesetId, branchId,
                    progress);
            },
                /*afterOperationDelegate*/
                delegate
            {
                progressControls.HideProgress();

                if (waiter.Exception != null)
                {
                    DisplayException(progressControls, waiter.Exception);
                    return;
                }

                if (tokenExchangeResponse.Error != null)
                {
                    mLog.ErrorFormat(
                        "Unable to get TokenExchangeResponse: {0} [code {1}]",
                        tokenExchangeResponse.Error.Message,
                        tokenExchangeResponse.Error.ErrorCode);
                }

                if (tokenExchangeResponse.Error != null ||
                    mWorkspaceInfo == null)
                {
                    progressControls.ShowError(
                        "Failed to convert your workspace to Plastic SCM");
                    return;
                }

                progressControls.ShowSuccess(
                    "Your workspace has been successfully converted to Plastic SCM");

                mIsMigrationCompleted = true;

                afterWorkspaceMigratedAction();
            },
                /*timerTickDelegate*/
                delegate
            {
                UpdateProgress(projectPath, progress, progressControls, progressData);
            });
        }
Пример #60
0
 public WebSocketClientImpl(ClientConfig clientConfig, IEventBus eventBus)
 {
     _clientConfig = clientConfig;
     _eventBus     = eventBus;
 }