Пример #1
0
        private void OnStarted()
        {
            _logger.LogInformation("Hosted service OnStarted");

            //读取节点配置信息
            ConfigurationCache.SetNode(_configuration);
            //注册节点
            AppStart.NodeRegistry.Register();
            //加载缓存
            ConfigurationCache.Reload();
            //初始化日志管理器
            Core.Log.LogManager.Init();

            //初始化系统任务
            FluentScheduler.JobManager.Initialize(new AppStart.SystemSchedulerRegistry());
            FluentScheduler.JobManager.JobException += info => Core.Log.LogHelper.Error("An error just happened with a FluentScheduler job", info.Exception);
            //任务恢复
            using (var scope = _serviceProvider.CreateScope())
            {
                Core.Services.ScheduleService service  = new Core.Services.ScheduleService();
                AutowiredServiceProvider      provider = new AutowiredServiceProvider();
                provider.PropertyActivate(service, scope.ServiceProvider);
                service.RunningRecovery();
            }
        }
Пример #2
0
        private void OnStarted()
        {
            _logger.LogInformation("Hosted service OnStarted");

            string pluginBasePath = ConfigurationCache.PluginPathPrefix.ToPhysicalPath();

            if (!System.IO.Directory.Exists(pluginBasePath))
            {
                System.IO.Directory.CreateDirectory(pluginBasePath);
            }

            //加载全局缓存
            ConfigurationCache.Reload();
            //初始化日志管理器
            Core.Log.LogManager.Init();
            //判断是否要自动根据配置文件注册节点信息
            if (AppCommandResolver.IsAutoRegister())
            {
                _logger.LogInformation("enabled auto register...");
                //设置节点信息
                ConfigurationCache.SetNode(_configuration);
                //初始化Quartz
                Common.QuartzManager.InitScheduler().Wait();
                //初始化延时队列容器
                DelayedTask.DelayPlanManager.Init();
            }
        }
        private void StoreConfiguration(ConfigurationCache cache)
        {
            if (!_hostEnvironment.IsFullTrust)
            {
                return;
            }

            var pathName = GetPathName(_shellSettings.Name);

            try {
                var formatter = new BinaryFormatter();
                using (var stream = _appDataFolder.CreateFile(pathName)) {
                    formatter.Serialize(stream, cache.Hash);
                    formatter.Serialize(stream, cache.Configuration);
                }
            }
            catch (SerializationException e) {
                //Note: This can happen when multiple processes/AppDomains try to save
                //      the cached configuration at the same time. Only one concurrent
                //      writer will win, and it's harmless for the other ones to fail.
                for (Exception scan = e; scan != null; scan = scan.InnerException)
                {
                    Logger.Warning("Error storing new NHibernate cache configuration: {0}", scan.Message);
                }
            }
        }
Пример #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ConfigurationCache configurationCache)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Default}/{action=Index}/{id?}"
                    );

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            configurationCache.SetConfiguration();
        }
Пример #5
0
        public Configuration GetConfiguration(Func<Configuration> builder) {
            var hash = ComputeHash().Value;

            // if the current configuration is unchanged, return it
            if(_currentConfig != null && _currentConfig.Hash == hash) {
                return _currentConfig.Configuration;
            }

            // Return previous configuration if it exists and has the same hash as
            // the current blueprint.
            var previousConfig = ReadConfiguration(hash);
            if (previousConfig != null) {
                _currentConfig = previousConfig;
                return previousConfig.Configuration;
            }

            // Create cache and persist it
            _currentConfig = new ConfigurationCache {
                Hash = hash,
                Configuration = builder()
            };

            StoreConfiguration(_currentConfig);
            return _currentConfig.Configuration;
        }
Пример #6
0
        public Configuration GetConfiguration(Func <Configuration> builder)
        {
            if (Disabled)
            {
                return(builder());
            }

            var hash = ComputeHash().Value;

            // if the current configuration is unchanged, return it
            if (_currentConfig != null && _currentConfig.Hash == hash)
            {
                return(_currentConfig.Configuration);
            }

            // Return previous configuration if it exists and has the same hash as
            // the current blueprint.
            var previousConfig = ReadConfiguration(hash);

            if (previousConfig != null)
            {
                _currentConfig = previousConfig;
                return(previousConfig.Configuration);
            }

            // Create cache and persist it
            _currentConfig = new ConfigurationCache {
                Hash          = hash,
                Configuration = builder()
            };

            StoreConfiguration(_currentConfig);
            return(_currentConfig.Configuration);
        }
Пример #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="shellSettings"></param>
        public SessionConfigurationCache(
            ShellSettings shellSettings)
        {
            _shellSettings = shellSettings;
            _currentConfig = null;

            Logger = LoggerFactory.GetLog();
        }
Пример #8
0
 public SystemManagers(SystemProperties systemProperties, ConfigurationCache configurationCache, ACConfiguration configuration, IACAlarmRepository alarmRepository)
 {
     CommandManager          = new CommandManager(this, configurationCache);
     ConfigurationManager    = new ConfigurationManager(this, systemProperties, configurationCache, configuration);
     ConnectionManager       = new ConnectionManager(this, alarmRepository, systemProperties);
     CredentialHolderManager = new CredentialHolderManager(this, systemProperties);
     EventManager            = new EventManager(configurationCache);
     StateManager            = new StateManager(this, configurationCache);
 }
Пример #9
0
        public SessionConfigurationCache(ShellSettings shellSettings, ShellBlueprint shellBlueprint, IAppDataFolder appDataFolder)
        {
            _shellSettings  = shellSettings;
            _shellBlueprint = shellBlueprint;
            _appDataFolder  = appDataFolder;
            _currentConfig  = null;

            Logger = NullLogger.Instance;
        }
Пример #10
0
        public SessionConfigurationCache(ShellSettings shellSettings, IEnumerable<RecordBlueprint> records, IAppDataFolder appFolder, IEnumerable<ISessionConfigurationEvents> configurers)
        {
            _shellSettings = shellSettings;
            _records = records;
            _appDataFolder = appFolder;
            _configurers = configurers;
            _currentConfig = null;

            Logger = NullLogger.Instance;
        }
Пример #11
0
        public SessionConfigurationCache(ShellSettings shellSettings, IEnumerable <RecordBlueprint> records, IAppDataFolder appFolder, IEnumerable <ISessionConfigurationEvents> configurers)
        {
            _shellSettings = shellSettings;
            _records       = records;
            _appDataFolder = appFolder;
            _configurers   = configurers;
            _currentConfig = null;

            Logger = NullLogger.Instance;
        }
Пример #12
0
 public LoginController(ILogger <LoginController> logger, AuthService authService, IUserRepository userRepository, IMailerRepository mailer,
                        ConfigurationCache configuration, IRoleRepository roleRepository, IAccountRepository accountRepository)
 {
     this.authService       = authService;
     this.userRepository    = userRepository;
     this.mailer            = mailer;
     this.configuration     = configuration;
     this.roleRepository    = roleRepository;
     this.accountRepository = accountRepository;
 }
Пример #13
0
        public SessionConfigurationCache(ShellSettings shellSettings, ShellBlueprint shellBlueprint, IAppDataFolder appDataFolder, IHostEnvironment hostEnvironment, IEnumerable <ISessionConfigurationEvents> configurers)
        {
            _shellSettings   = shellSettings;
            _shellBlueprint  = shellBlueprint;
            _appDataFolder   = appDataFolder;
            _hostEnvironment = hostEnvironment;
            _configurers     = configurers;
            _currentConfig   = null;

            Logger = NullLogger.Instance;
        }
Пример #14
0
 public ConfigurationController(
     ISiteSettingRepository siteSettingRepository,
     IMailSettingRepository mailSettingRepository,
     ISSOSettingRepository ssoSettingRepository,
     ConfigurationCache configuration
     )
 {
     this._siteSettingRepository = siteSettingRepository;
     this._mailSettingRepository = mailSettingRepository;
     this._ssoSettingRepository  = ssoSettingRepository;
     this._configuration         = configuration;
 }
Пример #15
0
 public ConfigurationController(
     ISiteSettingRepository siteSettingRepository,
     IMailSettingRepository mailSettingRepository,
     ISSOSettingRepository SSOSettingRepository,
     ConfigurationCache configuration
     )
 {
     this.siteSettingRepository = siteSettingRepository;
     this.mailSettingRepository = mailSettingRepository;
     this.SSOSettingRepository  = SSOSettingRepository;
     this.configuration         = configuration;
 }
Пример #16
0
        /// <summary>
        /// worker健康检查
        /// </summary>
        public void WorkerHealthCheck()
        {
            var workers = _repositoryFactory.ServerNodes.Where(x => x.NodeType == "worker" && x.Status != 0).ToList();

            if (!workers.Any())
            {
                return;
            }
            //允许最大失败次数
            int allowMaxFailed = ConfigurationCache.GetField <int>("System_WorkerUnHealthTimes");

            if (allowMaxFailed <= 0)
            {
                allowMaxFailed = 3;
            }
            //遍历处理
            workers.ForEach((w) =>
            {
                //初始化计数器
                ConfigurationCache.WorkerUnHealthCounter.TryAdd(w.NodeName, 0);
                //获取已失败次数
                int failedCount = ConfigurationCache.WorkerUnHealthCounter[w.NodeName];
                var success     = WorkerRequest(w, "health", "get", null);
                if (!success)
                {
                    System.Threading.Interlocked.Increment(ref failedCount);
                }
                if (failedCount >= allowMaxFailed)
                {
                    w.Status         = 0;//标记下线,实际上可能存在因为网络抖动等原因导致检查失败但worker进程还在运行的情况
                    w.LastUpdateTime = DateTime.Now;
                    _repositoryFactory.ServerNodes.Update(w);
                    //释放该节点占据的锁
                    _repositoryFactory.ScheduleLocks.UpdateBy(
                        x => x.LockedNode == w.NodeName && x.Status == 1
                        , x => new ScheduleLockEntity
                    {
                        Status     = 0,
                        LockedNode = null,
                        LockedTime = null
                    });
                    _unitOfWork.Commit();
                    //重置计数器
                    ConfigurationCache.WorkerUnHealthCounter[w.NodeName] = 0;
                }
                else
                {
                    ConfigurationCache.WorkerUnHealthCounter[w.NodeName] = failedCount;
                }
            });
        }
 /// <summary>
 /// 建立實體。
 /// </summary>
 /// <param name="provider"></param>
 public ConfigurationManager(IConfigurationProvider provider)
 {
     Provider = provider;
     Cache = new ConfigurationCache(Provider);
     Cache.ItemUpdated += delegate(object sender, ItemUpdatedEventArgs e)
     {
         if (ConfigurationUpdated != null)
         {
             ConfigurationUpdated(this, e);
             //BigEvent be = new BigEvent("ConfigurationUpdated", ConfigurationUpdated, this, e);
             //be.UIRaise();
         }
     };
 }
Пример #18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseCookiePolicy();
            //app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                //endpoints.MapControllers();
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Console}/{action=Index}/{id?}");
            });
            //加载全局缓存
            ConfigurationCache.RootServiceProvider = app.ApplicationServices;
            ConfigurationCache.SetNode(Configuration.GetSection("NodeSetting").Get <NodeSetting>());
            ConfigurationCache.Reload();
            //初始化日志管理器
            Core.Log.LogManager.Init();
            //注册节点
            AppStart.NodeRegistry.Register();
            //初始化系统任务
            FluentScheduler.JobManager.Initialize(new AppStart.SystemSchedulerRegistry());
            FluentScheduler.JobManager.JobException += info => Core.Log.LogHelper.Error("An error just happened with a FluentScheduler job", info.Exception);
            //任务恢复
            using (var scope = app.ApplicationServices.CreateScope())
            {
                Core.Services.ScheduleService service  = new Core.Services.ScheduleService();
                AutowiredServiceProvider      provider = new AutowiredServiceProvider();
                provider.PropertyActivate(service, scope.ServiceProvider);
                service.RunningRecovery();
            }
            appLifetime.ApplicationStopping.Register(OnStopping);
        }
Пример #19
0
        public ActionResult SaveConfig(IFormCollection form)
        {
            Dictionary <string, string> items = new Dictionary <string, string>();

            foreach (string key in form.Keys)
            {
                items.Add(key, form[key]);
            }
            bool result = _systemService.SaveConfig(items, CurrentAdmin.UserName);

            if (result)
            {
                ConfigurationCache.Reload();
                return(SuccessTip("保存成功!"));
            }
            return(DangerTip("保存失败!"));
        }
Пример #20
0
        /// <summary>
        /// 구성Vo조회
        /// </summary>
        /// <param name="configurationVo">구성Vo</param>
        /// <returns>구성Vo</returns>
        public ConfigurationVo selectConfigurationVo(ConfigurationVo configurationVo)
        {
            ConfigurationVo rtnConfigurationVo = new ConfigurationVo();

            using (ConfigurationCache configurationCache = new ConfigurationCache())
            {
                rtnConfigurationVo = configurationCache.selectConfigurationVo(configurationVo);

                if ((rtnConfigurationVo == null) || (rtnConfigurationVo.configuration == null) ||
                    (rtnConfigurationVo.configuration.configurationUsed == false))
                {
                    rtnConfigurationVo = null;
                }
            }

            return(rtnConfigurationVo);
        }
Пример #21
0
        private static async Task LoadPluginFile(ScheduleEntity model)
        {
            bool pull       = true;
            var  pluginPath = $"{ConfigurationCache.PluginPathPrefix}\\{model.Id}".ToPhysicalPath();
            //看一下拉取策略
            string policy = ConfigurationCache.GetField <string>("Assembly_ImagePullPolicy");

            if (policy == "IfNotPresent" && System.IO.Directory.Exists(pluginPath))
            {
                pull = false;
            }
            if (pull)
            {
                using (var scope = new ScopeDbContext())
                {
                    var master = scope.GetDbContext().ServerNodes.FirstOrDefault(x => x.NodeType == "master");
                    if (master == null)
                    {
                        throw new InvalidOperationException("master not found.");
                    }
                    var sourcePath = $"{master.AccessProtocol}://{master.Host}/static/downloadpluginfile?pluginname={model.AssemblyName}";
                    var zipPath    = $"{ConfigurationCache.PluginPathPrefix}\\{model.Id.ToString("n")}.zip".ToPhysicalPath();

                    try
                    {
                        //下载文件
                        var httpClient = scope.GetService <IHttpClientFactory>().CreateClient();
                        var array      = await httpClient.GetByteArrayAsync(sourcePath);

                        System.IO.FileStream fs = new System.IO.FileStream(zipPath, System.IO.FileMode.Create);
                        fs.Write(array, 0, array.Length);
                        fs.Close();
                        fs.Dispose();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Warn($"下载程序包异常,地址:{sourcePath}", model.Id);
                        throw ex.InnerException ?? ex;
                    }
                    //将指定 zip 存档中的所有文件都解压缩到各自对应的目录下
                    ZipFile.ExtractToDirectory(zipPath, pluginPath, true);
                    System.IO.File.Delete(zipPath);
                }
            }
        }
Пример #22
0
        private void OnStarted()
        {
            _logger.LogInformation("Hosted service OnStarted");

            //加载全局缓存
            ConfigurationCache.Reload();
            //初始化日志管理器
            Core.Log.LogManager.Init();
            //判断是否要自动根据配置文件注册节点信息
            if (AppCommandResolver.IsAutoRegister())
            {
                _logger.LogInformation("enabled auto register...");
                //设置节点信息
                ConfigurationCache.SetNode(_configuration);
                //初始化Quartz
                Common.QuartzManager.InitScheduler().Wait();
            }
        }
Пример #23
0
        private void StoreConfiguration(ConfigurationCache cache) {
            var pathName = GetPathName(_shellSettings.Name);

            try {
                var formatter = new BinaryFormatter();
                using (var stream = _appDataFolder.CreateFile(pathName)) {
                    formatter.Serialize(stream, cache.Hash);
                    formatter.Serialize(stream, cache.Configuration);
                }
            }
            catch (SerializationException e) {
                //Note: This can happen when multiple processes/AppDomains try to save
                //      the cached configuration at the same time. Only one concurrent
                //      writer will win, and it's harmless for the other ones to fail.
                for (Exception scan = e; scan != null; scan = scan.InnerException)
                    Logger.Warning("Error storing new NHibernate cache configuration: {0}", scan.Message);
            }
        }
Пример #24
0
        protected virtual async Task <FileContainerConfiguration> GetConfigurationInternal(string name)
        {
            var configuration = await ConfigurationCache.GetAsync(name);

            if (configuration == null)
            {
                //Read from db
                var container = await FileStoringContainerRepository.FindAsync(name);

                if (container != null)
                {
                    configuration = FileContainerConfigurationConverter.ToConfiguration(container);
                    await ConfigurationCache.SetAsync(name, configuration);
                }
            }

            return(configuration);
        }
Пример #25
0
        /// <summary>
        ///发送邮件
        /// </summary>
        /// <param name="toAddressList">接收人</param>
        /// <param name="title">标题</param>
        /// <param name="content">内容</param>
        /// <param name="attachments">附件</param>
        /// <returns></returns>
        public static void SendMail(List <KeyValuePair <string, string> > toAddressList, string title, string content, List <KeyValuePair <string, byte[]> > attachments = null, Guid?sid = null, Guid?traceId = null)
        {
            LogHelper.Info($"发送邮件开始:{title}\r\n收件人{string.Join(",",toAddressList)}\r\n", sid ?? Guid.Empty, traceId ?? Guid.Empty);
            try
            {
                string server  = ConfigurationCache.GetField <string>(ConfigurationCache.Email_SmtpServer);
                int    port    = ConfigurationCache.GetField <int>(ConfigurationCache.Email_SmtpPort);
                string account = ConfigurationCache.GetField <string>(ConfigurationCache.Email_FromAccount);
                string pwd     = ConfigurationCache.GetField <string>(ConfigurationCache.Email_FromAccountPwd);

                var mailMessage     = new MimeMessage();
                var fromMailAddress = new MailboxAddress("ScheduleMaster", account);
                mailMessage.From.Add(fromMailAddress);
                var toMailAddress = toAddressList.Select(x => new MailboxAddress(x.Key, x.Value));
                mailMessage.To.AddRange(toMailAddress);

                var bodyBuilder = new BodyBuilder()
                {
                    HtmlBody = content
                };
                if (attachments != null)
                {
                    foreach (var item in attachments)
                    {
                        bodyBuilder.Attachments.Add(item.Key, item.Value);
                    }
                }
                mailMessage.Body    = bodyBuilder.ToMessageBody();
                mailMessage.Subject = title;
                using (var smtpClient = new MailKit.Net.Smtp.SmtpClient())
                {
                    smtpClient.Timeout = 10 * 1000;                                              //设置超时时间
                    smtpClient.Connect(server, port, MailKit.Security.SecureSocketOptions.Auto); //连接到远程smtp服务器
                    smtpClient.Authenticate(account, pwd);
                    smtpClient.Send(mailMessage);                                                //发送邮件
                    smtpClient.Disconnect(true);
                }
                LogHelper.Info($"发送邮件结束", sid ?? Guid.Empty, traceId ?? Guid.Empty);
            }
            catch (Exception eaf) {
                LogHelper.Error($"发送邮件异常:{title}", eaf, sid ?? Guid.Empty, traceId ?? Guid.Empty);
            }
        }
        /// <summary>
        /// Called when a step of this type is executed in the workflow.
        /// </summary>
        /// <param name="JobID">ID of the job being executed</param>
        /// <param name="StepID">ID of the step being executed</param>
        /// <param name="argv">Array of arguments passed into the step's execution</param>
        /// <param name="ipFeedback">Feedback object to return status messages and files</param>
        /// <returns>Return code of execution for workflow path traversal</returns>
        public int Execute(int JobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback)
        {
            System.Diagnostics.Debug.Assert(m_ipDatabase != null);

            if (!ConfigurationCache.IsInitialized)
            {
                ConfigurationCache.InitializeCache(m_ipDatabase);
            }

            IJTXJobManager jobMan      = m_ipDatabase.JobManager;
            IJTXJob2       m_ParentJob = (IJTXJob2)jobMan.GetJob(JobID);

            if (!GetInputParams(argv))
            {
                return(0);
            }

            return(CreateJobs(m_ParentJob));
        }
        protected virtual Cfg.Configuration GetOrBuildConfiguration(string configKey, Func <Cfg.Configuration> buildConfiguration)
        {
            if (ConfigurationCache == null)
            {
                return(buildConfiguration());
            }

            var configuration = ConfigurationCache.LoadConfiguration(configKey, CacheDependencyFilePaths);

            if (configuration != null)
            {
                return(configuration);
            }

            configuration = buildConfiguration();
            ConfigurationCache.SaveConfiguration(configKey, configuration);

            return(configuration);
        }
Пример #28
0
        public static RESTServiceConfiguration GetCustomClientConfiguration(string restwebrefSSKey, int eSpaceId)
        {
            Func <RESTServiceConfiguration> fetchFromDb = () => {
                using (var tran = DatabaseAccess.ForSystemDatabase.GetReadOnlyTransaction()) {
                    using (IDataReader reader = GetCustomClientConfigFields(tran, restwebrefSSKey, eSpaceId)) {
                        if (reader.Read())
                        {
                            var traceErrors = reader.SafeGet <bool>("TraceErrors", false);
                            var traceAll    = reader.SafeGet <bool>("TraceAll", false);

                            return(new RESTServiceConfiguration(traceErrors, traceAll));
                        }
                        return(new RESTServiceConfiguration());
                    }
                }
            };

            return(ConfigurationCache.GetESpaceCachedValue(restwebrefSSKey, "RestConfigCache", eSpaceId, _ => fetchFromDb()));
        }
Пример #29
0
        public static RESTServiceConfiguration GetMobileLoggingLevelConfiguration(int eSpaceId)
        {
            Func <RESTServiceConfiguration> fetchLoggingLevelFromDb = () => {
                using (var tran = DatabaseAccess.ForSystemDatabase.GetReadOnlyTransaction()) {
                    using (IDataReader reader = GetLoggingLevelConfig(tran, eSpaceId)) {
                        if (reader.Read())
                        {
                            var traceErrors = reader.SafeGet <bool>("TraceErrors", false);
                            var traceAll    = reader.SafeGet <bool>("TraceAll", false);

                            return(new RESTServiceConfiguration(traceErrors, traceAll));
                        }
                        return(new RESTServiceConfiguration());
                    }
                }
            };

            return(ConfigurationCache.GetESpaceCachedValue("", "MobileLoggingLevelConfigCache", eSpaceId, _ => fetchLoggingLevelFromDb()));
        }
Пример #30
0
        public SessionConfigurationCache(IConfigurationService configurationService,
                                         ShellBlueprint shellBlueprint,
                                         IUserFolder userFolder)
        {
            ConfigurationService = configurationService;
            UserFolder           = userFolder;
            _shellBlueprint      = shellBlueprint;
            _currentConfig       = null;
            Logger = NullLogger.Instance;

            lock (syncRoot)
            {
                if (!HasBeenInitialized)
                {
                    DeleteCache();
                    HasBeenInitialized = true;
                }
            }
        }
        private IRestResponse DoRequest()
        {
            var client = new RestClient(HttpOption.RequestUrl);
            var request = new RestRequest(GetRestSharpMethod(HttpOption.Method));
            var headers = HosScheduleFactory.ConvertParamsJson(HttpOption.Headers);
            foreach (var (key, value) in headers)
            {
                request.AddHeader(key, value.ToString());
            }
            request.AddHeader("content-type", HttpOption.ContentType);
            request.Timeout = 10000;
            var config = ConfigurationCache.GetField<int>("Http_RequestTimeout");
            if (config > 0)
            {
                request.Timeout = config * 1000;
            }
            var requestBody = string.Empty;
            
            switch (HttpOption.ContentType)
            {
                case "application/json" when HttpOption.Body != null:
                    requestBody = HttpOption.Body.Replace("\r\n", "");
                    break;
                case "application/x-www-form-urlencoded" when HttpOption.Body != null:
                {
                    var formData = HosScheduleFactory.ConvertParamsJson(HttpOption.Body);
                    requestBody = string.Join('&', formData.Select(x => $"{x.Key}={System.Net.WebUtility.UrlEncode(x.Value.ToString())}"));
                    if (request.Method == Method.GET && formData.Count > 0)
                    {
                        client.BaseUrl = new Uri($"{HttpOption.RequestUrl}?{requestBody}");
                    }

                    break;
                }
            }
            if (request.Method != Method.GET)
            {
                request.AddParameter(HttpOption.ContentType, requestBody, ParameterType.RequestBody);
            }
            var response = client.Execute(request);
            return response;
        }
Пример #32
0
        public async Task <TrafficSegmentConfiguration> GetConfiguration()
        {
            _deviceConnectionString = ConfigurationCache.GetValue("deviceConnectionString");
            _deviceClient           = DeviceClient.CreateFromConnectionString(_deviceConnectionString);
            await _deviceClient.SetDesiredPropertyUpdateCallbackAsync(TwinPropertiesChanged, null);

            var iotHubOwnerConnectionString = _configurationReader.GetConfigValue <string>("IOTHUB_OWNER_CONNECTIONSTRING", true);

            try
            {
                var twin = await _deviceClient.GetTwinAsync();

                return(GetConfigurationFromTwin(twin.Properties.Desired));
            }
            catch (Exception e)
            {
                _logger.Error(e, $"An error occurred when trying read device on IoT Hub: {e.Message}");
                throw;
            }
        }
Пример #33
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ConfigurationCache configurationCache)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseRouting();
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor |
                                   ForwardedHeaders.XForwardedProto
            });
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseStaticFiles();
            app.UseSession();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Default}/{action=Index}/{id?}"
                    );

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapHub <ChatHub>("/chatHub");
                endpoints.MapHub <NotifyHub>("/NotifyHub");
                endpoints.MapHub <ChatDetailHub>("/chatDetailHub");
                endpoints.MapHub <RestaurantHub>("/restauranthub");
            });

            configurationCache.SetConfiguration();
        }
Пример #34
0
        private static async Task LoadPluginFile(ScheduleEntity model)
        {
            bool pull       = true;
            var  pluginPath = $"{ConfigurationCache.PluginPathPrefix}\\{model.Id}".ToPhysicalPath();
            //看一下拉取策略
            string policy = ConfigurationCache.GetField <string>("Assembly_ImagePullPolicy");

            if (policy == "IfNotPresent" && System.IO.Directory.Exists(pluginPath))
            {
                pull = false;
            }
            if (pull)
            {
                using (var scope = new ScopeDbContext())
                {
                    var master = scope.GetDbContext().ServerNodes.FirstOrDefault(x => x.NodeType == "master");
                    if (master == null)
                    {
                        throw new InvalidOperationException("master not found.");
                    }
                    var sourcePath = $"{master.AccessProtocol}://{master.Host}/static/downloadpluginfile?pluginname={model.AssemblyName}";
                    var zipPath    = $"{ConfigurationCache.PluginPathPrefix}\\{model.Id.ToString("n")}.zip".ToPhysicalPath();
                    using (WebClient client = new WebClient())
                    {
                        try
                        {
                            await client.DownloadFileTaskAsync(new Uri(sourcePath), zipPath);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Warn($"下载程序包异常,地址:{sourcePath}", model.Id);
                            throw ex;
                        }
                    }
                    //将指定 zip 存档中的所有文件都解压缩到各自对应的目录下
                    ZipFile.ExtractToDirectory(zipPath, pluginPath, true);
                    System.IO.File.Delete(zipPath);
                }
            }
        }
        public SessionConfigurationCache(ShellSettings shellSettings, ShellBlueprint shellBlueprint, IAppDataFolder appDataFolder, IHostEnvironment hostEnvironment) {
            _shellSettings = shellSettings;
            _shellBlueprint = shellBlueprint;
            _appDataFolder = appDataFolder;
            _hostEnvironment = hostEnvironment;
            _currentConfig = null;

            Logger = NullLogger.Instance;
        }