private void StartEngine()
 {
     Task.Run(() =>
     {
         try
         {
             this.starting = true;
             Application.Current.Dispatcher.Invoke(CommandManager.InvalidateRequerySuggested);
             ConfigClient c = App.GetDefaultConfigClient();
             c.GetEngineState();
             c.InvokeThenClose(x => x.StartAll());
         }
         catch (EndpointNotFoundException ex)
         {
             Trace.WriteLine(ex.ToString());
             MessageBox.Show($"Could not contact the AutoSync service", "AutoSync service unavailable", MessageBoxButton.OK, MessageBoxImage.Error);
         }
         catch (Exception ex)
         {
             Trace.WriteLine(ex);
             MessageBox.Show($"Error starting the management agents\n{ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
         }
         finally
         {
             this.starting = false;
         }
     }).ContinueWith(x => Application.Current.Dispatcher.Invoke(CommandManager.InvalidateRequerySuggested));
 }
Ejemplo n.º 2
0
 /// <summary>
 /// 刷新个人中心页面配置缓存
 /// </summary>
 /// <returns></returns>
 public bool RefreshMemberPageCache()
 {
     using (var client = new ConfigClient())
     {
         return(client.RefreshMemberPageCache().Result);
     }
 }
Ejemplo n.º 3
0
 protected override void ProcessRecord()
 {
     base.ProcessRecord();
     try
     {
         client?.Dispose();
         int timeout = GetPreferredTimeout();
         WriteDebug($"Cmdlet Timeout : {timeout} milliseconds.");
         client = new ConfigClient(AuthProvider, new Oci.Common.ClientConfiguration
         {
             RetryConfiguration = retryConfig,
             TimeoutMillis      = timeout,
             ClientUserAgent    = PSUserAgent
         });
         string region = GetPreferredRegion();
         if (region != null)
         {
             WriteDebug("Choosing Region:" + region);
             client.SetRegion(region);
         }
         if (Endpoint != null)
         {
             WriteDebug("Choosing Endpoint:" + Endpoint);
             client.SetEndpoint(Endpoint);
         }
     }
     catch (Exception ex)
     {
         TerminatingErrorDuringExecution(ex);
     }
 }
Ejemplo n.º 4
0
        public static IEnumerable <string> GetOrderTypeList()
        {
            List <string> orderTypeList = new List <string>();

            using (var client = new ConfigClient())
            {
                var dicKeys = new List <string> {
                    "OrderType"
                };
                var result = client.GetDictionariesByType(dicKeys);
                if (result != null && result.Result != null)
                {
                    var dictList = result.Result.Select(s => s.Value);
                    foreach (var dict in dictList)
                    {
                        foreach (var item in dict)
                        {
                            if (!orderTypeList.Contains(item.Key))
                            {
                                orderTypeList.Add(item.Key);
                            }
                        }
                    }
                }
            }
            return(orderTypeList);
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            //控制台、类库项目,不一定有appsettngs.json文件,所以使用ConfigClient的有参构造函数手动传入appid等参数
            //如果控制台项目同样建立了appsettings.json文件,那么同样可以跟mvc项目一样使用无参构造函数让Client自动读取appid等配置
            var appId  = "test_app";
            var secret = "";
            var nodes  = "http://agileconfig.xbaby.xyz:5000";
            //使用有参构造函数,手动传入appid等信息
            var client = new ConfigClient(appId, secret, nodes);

            Task.Run(async() =>
            {
                while (true)
                {
                    await Task.Delay(5000);
                    foreach (string key in client.Data.Keys)
                    {
                        var val = client[key];
                        Console.WriteLine("{0} : {1}", key, val);
                    }
                }
            });

            client.ConnectAsync();//如果不是mvc项目,不使用AddAgileConfig方法的话,需要手动调用ConnectAsync方法来跟服务器建立连接

            Console.WriteLine("Test started .");
            Console.Read();
        }
        public bool SelectABTestResult(string testGuid, string testName, string status, string testGroupId)
        {
            if (string.IsNullOrWhiteSpace(testGuid) ||
                string.IsNullOrWhiteSpace(testName) ||
                string.IsNullOrWhiteSpace(status) ||
                string.IsNullOrWhiteSpace(testGroupId))
            {
                return(false);
            }

            var result = dal.SelectABTestResult(testGuid, testGroupId);

            if (!result)
            {
                return(false);
            }
            else
            {
                List <string> input = new List <string>();
                input.Add(testName);
                using (var client = new ConfigClient())
                {
                    var deleteResult = client.UpdateABTestDetailCache(input);
                    if (!deleteResult.Success)
                    {
                        return(false);
                    }
                    else
                    {
                        result = deleteResult.Result;
                    }
                }
                return(result);
            }
        }
        public bool DeleteABTest(Guid testGuid, string testName)
        {
            if (string.IsNullOrWhiteSpace(testName) || testGuid == Guid.Empty)
            {
                return(false);
            }
            var result = dal.DeleteABTestByGuid(testGuid);

            if (!result)
            {
                return(false);
            }
            else
            {
                List <string> input = new List <string>();
                input.Add(testName);
                using (var client = new ConfigClient())
                {
                    var deleteResult = client.DeleteABTestDetailCache(input);
                    if (!deleteResult.Success)
                    {
                        return(false);
                    }
                    else
                    {
                        result = deleteResult.Result;
                    }
                }
                return(result);
            }
        }
Ejemplo n.º 8
0
 public AuthController(ILogger <AuthController> logger,
                       ConfigClient configClient,
                       CognitoService cognitoService)
 {
     this.logger         = logger;
     this.cognitoService = cognitoService;
 }
Ejemplo n.º 9
0
 public static IHostBuilder CreateHostBuilder(string[] args) =>
 Host.CreateDefaultBuilder(args)
 .ConfigureAppConfiguration((context, config) =>
 {
     //读取本地配置
     var localconfig = new ConfigurationBuilder()
                       .SetBasePath(Directory.GetCurrentDirectory())
                       .AddJsonFile("appsettings.json").Build();
     //从本地配置里读取AgileConfig的相关信息
     var appId  = localconfig["AgileConfig:appId"];
     var secret = localconfig["AgileConfig:secret"];
     var nodes  = localconfig["AgileConfig:nodes"];
     //new一个client实例
     var configClient = new ConfigClient(appId, secret, nodes);
     //使用AddAgileConfig配置一个新的IConfigurationSource
     config.AddAgileConfig(configClient);
     //找一个变量挂载client实例,以便其他地方可以直接使用实例访问配置
     ConfigClient = configClient;
     //注册配置项修改事件
     configClient.ConfigChanged += ConfigClient_ConfigChanged;
 })
 .ConfigureWebHostDefaults(webBuilder =>
 {
     webBuilder.UseStartup <Startup>();
 });
Ejemplo n.º 10
0
        /// <summary>
        /// 更新缓存
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateCache()
        {
            var result = new MJsonResult()
            {
                Status = true
            };

            try
            {
                // 更新缓存
                using (var client = new ConfigClient())
                {
                    var reVauel = client.RefreshCityAgingCacheAsync();
                    if (!reVauel.Success)
                    {
                        result.Status = false;
                        result.Msg    = "更新缓存失败!";
                    }
                }
            }
            catch (Exception e)
            {
                result.Status = false;
                result.Msg    = "异常:" + e.Message;
            }
            return(Json(result));
        }
Ejemplo n.º 11
0
 private static bool GetSwitchValue()
 {
     using (var client = new ConfigClient())
     {
         var result = client.GetOrSetRuntimeSwitch("UpdateProductStatisticsIsTest");
         return(result.Success ? result.Result.Value : false);
     }
 }
Ejemplo n.º 12
0
 private bool CheckSwitch()
 {
     using (var client = new ConfigClient())
     {
         var result = client.GetOrSetRuntimeSwitch("TaskBackup");
         return(result.Success && result.Result.Value);
     }
 }
Ejemplo n.º 13
0
        public IDictionary <string, string> GetAllInterpolated(
            string environment = null, string app = null, string appInstance = null)
        {
            var targetScope = ConfigSettingScope.Create(environment, app, appInstance);
            var ocs         = new ObjectConfigStore(_config);
            var client      = new ConfigClient(ocs, targetScope);

            return(client.GetAll());
        }
Ejemplo n.º 14
0
        public SyncthingClient(IConnection connection)
        {
            Ensure.ArgumentNotNull(connection, nameof(connection));

            Connection = connection;
            var apiConnection = new ApiConnection(connection);

            Config = new ConfigClient(apiConnection);
        }
Ejemplo n.º 15
0
 public static ConfigClient GetDefaultConfigClient()
 {
     if (string.Equals(UserSettings.AutoSyncServerHost, "localhost", StringComparison.OrdinalIgnoreCase))
     {
         return(ConfigClient.GetNamedPipesClient());
     }
     else
     {
         return(ConfigClient.GetNetTcpClient(UserSettings.AutoSyncServerHost, UserSettings.AutoSyncServerPort, UserSettings.AutoSyncServerIdentity));
     }
 }
Ejemplo n.º 16
0
 public static ConfigClient GetDefaultConfigClient()
 {
     if (App.IsConnectedToLocalhost())
     {
         return(ConfigClient.GetNamedPipesClient());
     }
     else
     {
         return(ConfigClient.GetNetTcpClient(UserSettings.AutoSyncServerHost, UserSettings.AutoSyncServerPort, UserSettings.AutoSyncServerIdentity));
     }
 }
Ejemplo n.º 17
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            //跟控制台项目一样,appid等信息取决于你如何获取。你可以写死,可以从配置文件读取,可以从别的web service读取。
            var appId  = "test_app";
            var secret = "";
            var nodes  = "http://agileconfig.xbaby.xyz:5000";

            ConfigClient      = new ConfigClient(appId, secret, nodes);
            ConfigClient.Name = "wpfconfigclient";
            ConfigClient.Tag  = "t1";
            ConfigClient.ConnectAsync().GetAwaiter();
        }
        public void Execute(IJobExecutionContext context)
        {
            List <MiniRegion> miniRegion = new List <MiniRegion>();

            try
            {
                logger.Info("开始刷新轮胎区域活动缓存");

                var allActivityId = GetAllActivityId();

                if (allActivityId != null && allActivityId.Any())
                {
                    using (var client = new RegionClient())
                    {
                        var data = client.GetAllMiniRegion();
                        data.ThrowIfException(true, "获取所有地区服务失败");
                        miniRegion = data.Result.ToList();
                    }

                    if (miniRegion != null && miniRegion.Any())
                    {
                        foreach (var activityId in allActivityId)
                        {
                            foreach (var region in miniRegion)
                            {
                                using (var client = new ConfigClient())
                                {
                                    var result = client.RefreshRegionMarketingCache(activityId, region.RegionId);
                                    result.ThrowIfException(true);
                                    if (!result.Result)
                                    {
                                        logger.Error("刷新轮胎区域活动失败");
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        logger.Info("未获取到地区");
                    }
                }
                else
                {
                    logger.Info("没有已配置的活动");
                }
            }
            catch (Exception ex)
            {
                logger.Error("刷新轮胎区域活动缓存Job异常", ex);
            }
            logger.Info("刷新轮胎区域活动缓存任务完成");
        }
Ejemplo n.º 19
0
 public ApplicationController(ConfigStoreContext context,
                              ConfigClient client,
                              DefaultDataInitializer defaultDataInitializer,
                              RenameModelActionHandler <Application> renameModelActionHandler,
                              CanAddModelActionHandler <Application> canAddModelActionHandler)
 {
     _context = context;
     _client  = client;
     _defaultDataInitializer   = defaultDataInitializer;
     _renameModelActionHandler = renameModelActionHandler;
     _canAddModelActionHandler = canAddModelActionHandler;
 }
Ejemplo n.º 20
0
 public EnvironmentController(ConfigStoreContext context,
                              ConfigClient client,
                              DefaultDataInitializer defaultDataInitializer,
                              RenameModelActionHandler <ServiceEnvironment> renameModelActionHandler,
                              CanAddModelActionHandler <ServiceEnvironment> canAddModelActionHandler)
 {
     _context = context;
     _client  = client;
     _defaultDataInitializer   = defaultDataInitializer;
     _renameModelActionHandler = renameModelActionHandler;
     _canAddModelActionHandler = canAddModelActionHandler;
 }
Ejemplo n.º 21
0
 public static IHostBuilder CreateHostBuilder(string[] args) =>
 Host.CreateDefaultBuilder(args)
 .ConfigureAppConfiguration((context, config) =>
 {
     //根据环境变量读取appsettings.{env}.json配置信息
     var envName      = context.HostingEnvironment.EnvironmentName;
     var configClient = new ConfigClient($"appsettings.{envName}.json");
     config.AddAgileConfig(configClient, arg => Console.WriteLine($"config changed , action:{arg.Action} key:{arg.Key}"));
 })
 .ConfigureWebHostDefaults(webBuilder =>
 {
     webBuilder.UseStartup <Startup>();
 });
Ejemplo n.º 22
0
        /// <summary>
        /// 获取开关
        /// </summary>
        /// <param name="switchName"></param>
        /// <returns></returns>
        public async static Task <OperationResult <RuntimeSwitchResponse> > GetOrSetRuntimeSwitchAsync(string switchName)
        {
            using (var client = new ConfigClient())
            {
                var result = await client.GetOrSetRuntimeSwitchAsync(switchName);

                if (!result.Success)
                {
                    Logger.Error($" GetOrSetRuntimeSwitchAsync fail => ErrorCode ={result.ErrorCode} & ErrorMessage ={result.ErrorMessage} ");
                }
                return(result);
            }
        }
Ejemplo n.º 23
0
        private static async Task InitializeDbAsync(IApplicationBuilder app)
        {
            using (IServiceScope serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope()) {
                ConfigStoreContext context = serviceScope.ServiceProvider.GetRequiredService <ConfigStoreContext>();
                context.Database.SetCommandTimeout(TimeSpan.FromMinutes(5));
                await context.Database.MigrateAsync();

                ConfigClient client = serviceScope.ServiceProvider.GetRequiredService <ConfigClient>();
                await client.ClearAsync();

                DbInitializer initializer = new DbInitializer(context, client);
                await initializer.SeedAsync();
            }
        }
        public void StartClientWithConfiguration()
        {
            using (var server = new ConfigServer())
            {
                server.SetupConfiguration();
                server.Start();

                using (var client = new ConfigClient())
                {
                    client.SetupConfiguration();
                    client.Connect();
                    client.Disconnect();
                }
            }
        }
Ejemplo n.º 25
0
        public void BasicReferencesTest()
        {
            var ocs = new ObjectConfigStore(() => new Config()
            {
                Settings = new[]
                {
                    new ConfigSetting("a", "1"),
                    new ConfigSetting("b", "2${a}")
                }
            });

            var globalClient = new ConfigClient(ocs, ConfigSettingScope.Global);

            Assert.AreEqual("21", globalClient.Get("b"));
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            Task.Run(async() =>
            {
                var serviceCollection = new ServiceCollection();
                ConfigureServices(serviceCollection);
                var serviceProvider = serviceCollection.BuildServiceProvider();

                var lf = serviceProvider.GetService <ILoggerFactory>();

                var appId = "0003";
                var seret = "";
                var host  = "http://localhost:5000";

                try
                {
                    var client            = new ConfigClient(appId, seret, host, lf.CreateLogger <ConfigClient>());
                    client.ConfigChanged += Client_ConfigChanged;
                    await client.ConnectAsync();
                    //var provider = new AgileConfigProvider(client);
                    //provider.Load();
                    await Task.Run(async() =>
                    {
                        while (true)
                        {
                            await Task.Delay(5000);
                            foreach (string key in client.Data.Keys)
                            {
                                var val = client[key];
                                //provider.TryGet(key, out string val);
                                Console.WriteLine("{0} : {1}", key, val);
                            }
                        }
                    });

                    Console.WriteLine("Test started .");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            });


            Console.ReadLine();
        }
Ejemplo n.º 27
0
        public void MultiLevelReferencesTest()
        {
            var ocs = new ObjectConfigStore(() => new Config()
            {
                Settings = new[]
                {
                    new ConfigSetting("a", "1"),
                    new ConfigSetting("b", "2${a}"),
                    new ConfigSetting("c", "${a}+${b}"),
                }
            });

            var globalClient = new ConfigClient(ocs, ConfigSettingScope.Global);

            Assert.AreEqual("1+21", globalClient.Get("c"));
        }
        public void StartClientWihtoutConfiguration()
        {
            using (var server = new ConfigServer())
            {
                server.SetupConfiguration();
                server.Start();

                using (var client = new ConfigClient())
                {
                    Exception ex = Assert.Throws <EtherConfigurationException>(() => client.Connect());
                    Assert.IsType <EtherConfigurationException>(ex);

                    client.Disconnect();
                }
            }
        }
 private void Start()
 {
     Task.Run(() =>
     {
         try
         {
             ConfigClient c = App.GetDefaultConfigClient();
             c.InvokeThenClose(x => x.Start(this.ManagementAgentID));
         }
         catch (Exception ex)
         {
             Trace.WriteLine(ex);
             MessageBox.Show($"Could not start the management agent\n{ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
         }
     });
 }
Ejemplo n.º 30
0
        private void NextButton_Click(object sender, RoutedEventArgs e)
        {
            StatusBlock.Text = "Creating account...";
            var user = new RegisterUser()
            {
                UserName        = EmailBox.Text,
                Password        = PasswordBox.Password,
                ConfirmPassword = VerifyPasswordBox.Password,
                Name            = NameBox.Text
            };

            WebServiceHelper.CreateAcccount(
                user,
                new WebServiceHelper.AccountDelegate((username) =>
            {
                Dispatcher.BeginInvoke((Action)(() =>
                {
                    StatusBlock.Text = "";
                    if (username == null)
                    {
                        StatusBlock.Text = "Account creation failed.  Please try again later.";
                    }
                    else
                    {
                        if (username.StartsWith("Error: "))
                        {
                            StatusBlock.Text = username;
                        }
                        else
                        {
                            // save the creds in config file
                            string credentials = string.Format("{0}:{1}", user.UserName, user.Password);
                            string encodedCreds = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(credentials));
                            ConfigClient.Write(ConfigClient.Credentials, encodedCreds);
                            ConfigClient.Write(ConfigClient.Email, username);
                            ConfigClient.Write(ConfigClient.Name, user.Name);
                            ConfigClient.Write(ConfigClient.DeviceName, ComputerNameBox.Text);

                            NavigationService.Navigate(new Done());
                        }
                    }
                }));
            }),
                null);
        }