Ejemplo n.º 1
0
        public void UpdateEntities(IDbSet <WTask> wTasks, IDbSet <WGroup> wGroups, ConfigDto config)
        {
            if (config == null || config.Groups == null || config.Tasks == null || wTasks == null || wGroups == null)
            {
                return;
            }

            foreach (var group in config.Groups)
            {
                var wGroupToUpdate = wGroups.Where(x => x.Id == group.Id).SingleOrDefault();
                if (wGroupToUpdate == null)
                {
                    wGroupToUpdate = new WGroup();
                    wGroups.Add(wGroupToUpdate);
                }
                wGroupToUpdate.WTasks = new List <WTask>();
                _conversionService.ConvertFromDto(wGroupToUpdate, group);
            }

            foreach (var task in config.Tasks)
            {
                var wTaskToUpdate = wTasks.Where(x => x.Id == task.Id).SingleOrDefault();
                if (wTaskToUpdate == null)
                {
                    wTaskToUpdate = new WTask();
                    wTasks.Add(wTaskToUpdate);
                }
                wTaskToUpdate.WGroups = new List <WGroup>();
                _conversionService.ConvertFromDto(wTaskToUpdate, task, wGroups, true);
            }
        }
Ejemplo n.º 2
0
        public BaseModel <String> EditConfig(ConfigDto dto)
        {
            BaseModel <String> baseModel = new BaseModel <String>();

            try
            {
                if (dto == null || String.IsNullOrWhiteSpace(dto.ConfigKey))
                {
                    baseModel.Failed("参数错误!");
                }
                else
                {
                    var setConfigResult = GloableCache.ZLClient.setServerConfig(dto.ConfigKey, dto.ConfigValue);
                    if (setConfigResult.code == 0 && setConfigResult.changed != 0)
                    {
                        baseModel.Success("修改配置[" + dto.ConfigKey + "]成功!");
                        GloableCache.ZLMediaServerConfig = GloableCache.ZLClient.getServerConfig().data.First();//刷新一遍配置
                        // GloableCache.ZLClient.addStreamProxy()
                    }
                    else
                    {
                        baseModel.Failed("修改配置[" + dto.ConfigKey + "]失败!");
                    }
                }
            }
            catch (Exception ex)
            {
                baseModel.Failed(ex.Message);
            }
            return(baseModel);
        }
Ejemplo n.º 3
0
        public async Task <DResult> Save(string module, [FromBody] object config, string env = null)
        {
            var envs = Enum.GetValues(typeof(ConfigEnv)).Cast <ConfigEnv>().Select(t => t.ToString().ToLower()).ToList();

            if (!string.IsNullOrWhiteSpace(env))
            {
                env = env.ToLower();
                if (!envs.Contains(env))
                {
                    return(DResult.Error($"不支持的配置模式:{env}"));
                }
            }
            var model = new ConfigDto
            {
                ProjectId = Project.Id,
                Name      = module,
                Mode      = env,
                Status    = (byte)ConfigStatus.Normal,
                Content   = JsonConvert.SerializeObject(config)
            };
            var result = await _contract.SaveAsync(model);

            if (result <= 0)
            {
                return(DResult.Error("保存配置失败"));
            }
            NotifyConfig(module, env, config);
            return(DResult.Success);
        }
Ejemplo n.º 4
0
        public void UpdateConfigDto(ConfigDto config, ICollection <GroupHolder> groups, ICollection <TaskHolder> tasks)
        {
            if (config.Groups == null)
            {
                config.Groups = new List <GroupDto>();
            }
            if (config.Tasks == null)
            {
                config.Tasks = new List <TaskDto>();
            }

            foreach (var group in groups)
            {
                var groupDtoToUpdate = config.Groups.Where(x => x.Id == group.Id).SingleOrDefault();
                if (groupDtoToUpdate == null)
                {
                    groupDtoToUpdate = new GroupDto();
                    config.Groups.Add(groupDtoToUpdate);
                }
                groupDtoToUpdate.Tasks = new List <TaskDto>();
                _holdersConversionService.ConvertToDto(groupDtoToUpdate, group);
            }

            foreach (var task in tasks)
            {
                var taskDtoToUpdate = config.Tasks.Where(x => x.Id == task.Id).SingleOrDefault();
                if (taskDtoToUpdate == null)
                {
                    taskDtoToUpdate = new TaskDto();
                    config.Tasks.Add(taskDtoToUpdate);
                }
                taskDtoToUpdate.Groups = new List <GroupDto>();
                _holdersConversionService.ConvertToDto(taskDtoToUpdate, task, config.Groups, true);
            }
        }
Ejemplo n.º 5
0
        public IActionResult Post([FromBody] ConfigDto config)
        {
            int tm = config.Timeout;

            backgroundTimer.GetDataDelay = tm;
            return(new OkObjectResult(tm));
        }
Ejemplo n.º 6
0
 public HttpResponseMessage Post(HttpRequestMessage request, ConfigDto dto)
 {
     return(CreateHttpResponse(request, () => {
         HttpResponseMessage response = null;
         var currentUser = this.userRepository.GetAllIncluding(x => x.Role).Where(x => x.Id == (int)this.CurrentUserId).FirstOrDefault();
         if (currentUser != null)
         {
             if (currentUser.Role.Description == "Administrador del sistema")
             {
                 if (dto.Id == 0)
                 {
                     this.configRepository.Add(Mapper.Map <ConfigDto, Config>(dto));
                     dto.Id = this.configRepository.GetLastInsertId();
                 }
                 else
                 {
                     this.configRepository.Edit(Mapper.Map <ConfigDto, Config>(dto));
                 }
                 this.unitOfWork.Commit();
                 response = request.CreateResponse(HttpStatusCode.OK, new { success = true });
             }
             else
             {
                 response = request.CreateErrorResponse(HttpStatusCode.Forbidden, "No posees permiso para editar esta configuración.");
             }
         }
         else
         {
             response = request.CreateErrorResponse(HttpStatusCode.Forbidden, "Debés estar logueado para realizar esta solicitud.");
         }
         return response;
     }));
 }
Ejemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //1.config MVC
            services.AddControllersWithViews()
            //view Localization
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            //use pascal for newtonSoft json
            .AddNewtonsoftJson(opts => { opts.UseMemberCasing(); })
            //use pascal for MVC json
            .AddJsonOptions(opts => { opts.JsonSerializerOptions.PropertyNamingPolicy = null; });

            //2.set Resources path
            services.AddLocalization(opts => opts.ResourcesPath = "Resources");

            //3.http context
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            //4.user info for base component
            services.AddSingleton <IBaseUserService, BaseUserService>();

            //5.ado.net for mssql
            services.AddTransient <DbConnection, SqlConnection>();
            services.AddTransient <DbCommand, SqlCommand>();

            //6.appSettings "FunConfig" section -> _Fun.Config
            var config = new ConfigDto();

            Configuration.GetSection("FunConfig").Bind(config);
            _Fun.Config = config;
        }
Ejemplo n.º 8
0
        private static bool TryLoadConfig()
        {
            string fileLocation = System.Reflection.Assembly.GetEntryAssembly().GetName().CodeBase;

            if (fileLocation.ToLower().StartsWith(@"file:///"))
            {
                fileLocation = fileLocation.Substring(@"file:///".Length);
            }

            string rootPath = new FileInfo(fileLocation).Directory.ToString() + "\\";
            string path     = new FileInfo(fileLocation).Directory.ToString() + "\\" + ConfigFileName;

            if (File.Exists(path))
            {
                try
                {
                    Config = JsonConvert.DeserializeObject <ConfigDto>(File.ReadAllText(path));
                }
                catch (Exception e)
                {
                    return(false);
                }

                return(true);
            }
            else
            {
                Config = new ConfigDto();
                string json = JsonConvert.SerializeObject(Config, Formatting.Indented);
                File.WriteAllText(path, json);
                return(false);
            }
        }
Ejemplo n.º 9
0
        public void Update(ConfigDto config)
        {
            var entity = _configRepository.GetById(config.ConfigID);

            entity = config.ToEntity(entity);
            _configRepository.Update(entity);
        }
Ejemplo n.º 10
0
        public void SaveChanges()
        {
            var config = new ConfigDto();

            _holdersService.UpdateConfigDto(config, _groups, _tasks);
            _configurationService.SaveConfig(config);
        }
Ejemplo n.º 11
0
        public IActionResult Get([FromBody] ConfigDto config)
        {
            _operationService.Deserialize(config)
            .ActivateRepository()
            .SaveConfig();

            return(Ok());
        }
Ejemplo n.º 12
0
        public ConfigDto Index()
        {
            ConfigDto configDto = new ConfigDto {
                ApiServerUrl = config["ApiServer:SchemeAndHost"]
            };

            return(configDto);
        }
Ejemplo n.º 13
0
 public void SaveConfig(ConfigDto config)
 {
     using (var db = _wContextFactory.Create())
     {
         _entitiesService.UpdateEntities(db.WTasks, db.WGroups, config);
         _entitiesService.PrepareConfigToSave(db.WTasks, db.WGroups);
         db.SaveChanges();
     }
 }
Ejemplo n.º 14
0
        public ConfigDto GetConfig()
        {
            ConfigDto dto = new ConfigDto();

            using (var db = _wContextFactory.Create())
            {
                _entitiesService.UpdateDto(dto, db.WTasks.Where(x => !x.Archivized), db.WGroups.Where(x => !x.Archivized));
            }
            return(dto);
        }
Ejemplo n.º 15
0
 public ValidnatorXsdTest()
 {
     paramNotValid = new ConfigDto
     {
         SeparatorColumn = EnumsValidnatorXsd.SeparatorColumn.Semicolon,
         PathFile        = $"{path}fileTestError.csv",
         TypeFile        = EnumsValidnatorXsd.TypeFile.Txt,
         QuantityColumns = 7,
         //QuantityRows = 15,
         ShemaReader = new XmlTextReader($"{path}XMLSchemaTest.xsd")
     };
 }
        public static object Return(ConfigDto config)
        {
            try
            {
                return(JsonConvert.DeserializeObject(config.ConfigJson, Type.GetType(config.TypeName)));
            }
            catch (Exception c)
            {
                Console.WriteLine(c);
            }

            return(null);
        }
Ejemplo n.º 17
0
        public async Task <ActionResult> UpdateConfig([FromBody] ConfigDto configDto)
        {
            try
            {
                await _configService.UpdateConfigAsync(_mapper.Map <Config>(configDto));

                return(Ok());
            }
            catch (InvalidOperationException ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Ejemplo n.º 18
0
        public Config(string configfilename)
        {
            if (!File.Exists(configfilename))
            {
                throw new InvalidOperationException($"Missing config file: {configfilename}!");
            }

            var jsonData = File.ReadAllText(configfilename);

            var json = new JavaScriptSerializer();

            this.data = json.Deserialize <ConfigDto>(jsonData);
        }
Ejemplo n.º 19
0
        public async Task It_should_found()
        {
            using TestServer server = TestServer(UserRole.Administrator);
            using HttpClient client = server.CreateHttpClient();
            HttpResponseMessage result =
                await client.GetAsync(
                    $"features/application/{_env1.Application.Code}/environment/{_env1.Code}/config/conf1");

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            ConfigDto env = result.Deserialize <ConfigDto>();

            Assert.Equal("conf1", env.Code);
        }
        public void ReturnOkWhenConfigIsValid()
        {
            // the data I want to return to ServiceAgent.
            var mockedReturnConfig = new ConfigDto {
                ConfigSource = "ABC", ConfigData = "DEF"
            };

            // configure Moq to return that whenever someone calls `GetConfigData()'
            _mockConfigReader.Setup(c => c.GetConfigData()).Returns(mockedReturnConfig);

            var reportData = _unitUnderTest.RetrieveReport();

            Assert.That(reportData, Is.EqualTo(mockedReturnConfig.ConfigData));
        }
Ejemplo n.º 21
0
        public object GetConfigValue(string config)
        {
            ConfigDto configDto = GetConfig(config);

            if (configDto == null)
            {
                //LogHelper.Error.Write("GetConfigValue", string.Format("Config参数:{0}未找到", config));
                return(null);
            }
            if (!configDto.IsActive)
            {
                //LogHelper.Error.Write("GetConfigValue", string.Format("Config参数:{0}未启用", config));
                return(null);
            }
            return(configDto.ConfigValue);
        }
Ejemplo n.º 22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //use newtonSoft for json serialize for controller
            services.AddControllers()
            .AddNewtonsoftJson(options =>
            {
                //use pascal case json
                options.UseMemberCasing();
            });

            services.AddControllersWithViews()
            .AddJsonOptions(options =>
            {
                //use pascal case json
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            //locale & user info for base component
            services.AddSingleton <IBaseResService, BaseResService>();
            services.AddScoped <IBaseUserService, MyBaseUserService>();

            //session1(memory cache)
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                //options.IdleTimeout = TimeSpan.FromSeconds(10);
                options.Cookie.HttpOnly    = true;
                options.Cookie.IsEssential = true;
            });

            //appSettings "FunConfig" section -> _Fun.Config
            var config = new ConfigDto();

            Configuration.GetSection("FunConfig").Bind(config);
            _Fun.Config = config;

            //ado.net for mssql
            services.AddTransient <DbConnection, SqlConnection>();
            services.AddTransient <DbCommand, SqlCommand>();

            //initial _Fun by mssql
            IServiceProvider di = services.BuildServiceProvider();

            _Fun.Init(di, DbTypeEnum.MSSql, AuthTypeEnum.Ctrl);
        }
Ejemplo n.º 23
0
        private void RegisterActivationHotkey()
        {
            if (activationHotkey != null)
            {
                activationHotkey.HotKeyPressed -= Activation_HotKeyPressed;
                activationHotkey.Dispose();
            }

            for (int attempt = 1; attempt <= 3; attempt++)
            {
                ModifierKeys hotkeyModifiers = ModifierKeys.None;
                Keys         hotkeyKey       = Keys.None;

                var config = DataProvider.DataStore.Value.Config.Value.GetConfig();
                try
                {
                    if (config.HotkeyAlt)
                    {
                        hotkeyModifiers |= ModifierKeys.Alt;
                    }
                    if (config.HotkeyCtrl)
                    {
                        hotkeyModifiers |= ModifierKeys.Control;
                    }
                    if (config.HotkeyShift)
                    {
                        hotkeyModifiers |= ModifierKeys.Shift;
                    }

                    hotkeyKey        = (Keys)Enum.Parse(typeof(Keys), config.HotkeyKey, true);
                    activationHotkey = new HotKey(hotkeyModifiers, hotkeyKey, this);
                    activationHotkey.HotKeyPressed += Activation_HotKeyPressed;
                    break;
                }
                catch
                {
                    // Fallback to hardcoded default if we can't parse.
                    var defaultConfig = new ConfigDto();
                    config.HotkeyAlt   = defaultConfig.HotkeyAlt;
                    config.HotkeyCtrl  = defaultConfig.HotkeyCtrl;
                    config.HotkeyShift = defaultConfig.HotkeyShift;
                    config.HotkeyKey   = defaultConfig.HotkeyKey;
                    DataProvider.DataStore.Value.Config.Value.Update(config);
                }
            }
        }
Ejemplo n.º 24
0
        public void UpdateDto(ConfigDto dto, IEnumerable <WTask> wTasks, IEnumerable <WGroup> wGroups)
        {
            if (dto == null)
            {
                return;
            }

            if (dto.Groups == null)
            {
                dto.Groups = new List <GroupDto>();
            }
            if (dto.Tasks == null)
            {
                dto.Tasks = new List <TaskDto>();
            }

            if (wTasks == null || wGroups == null)
            {
                return;
            }

            foreach (var wGroup in wGroups)
            {
                var groupToUpdate = dto.Groups.Where(x => x.Id == wGroup.Id).SingleOrDefault();
                if (groupToUpdate == null)
                {
                    groupToUpdate = new GroupDto();
                    dto.Groups.Add(groupToUpdate);
                }
                groupToUpdate.Tasks = new List <TaskDto>();
                _conversionService.ConvertToDto(groupToUpdate, wGroup);
            }

            foreach (var wTask in wTasks)
            {
                var taskToUpdate = dto.Tasks.Where(x => x.Id == wTask.Id).SingleOrDefault();
                if (taskToUpdate == null)
                {
                    taskToUpdate = new TaskDto();
                    dto.Tasks.Add(taskToUpdate);
                }
                taskToUpdate.Groups = new List <GroupDto>();
                _conversionService.ConvertToDto(taskToUpdate, wTask, dto.Groups, true);
            }
        }
Ejemplo n.º 25
0
        public async Task It_should_create_with_version()
        {
            TestEntity testEntity = new TestEntity();

            using TestServer server = TestServer(UserRole.Administrator);
            using HttpClient client = server.CreateHttpClient();
            HttpResponseMessage result = await client.PostAsync($"features/application/{_env2.Application.Code}/environment/{_env2.Code}/config/createver?versionFrom=2.0.0", testEntity.Serialize());

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            HttpResponseMessage configFound =
                await client.GetAsync(
                    $"features/application/{_env2.Application.Code}/environment/{_env2.Code}/config/createver?versionFrom=2.0.0");

            Assert.Equal(HttpStatusCode.OK, configFound.StatusCode);
            ConfigDto confDevenition = result.Deserialize <ConfigDto>();

            Assert.Equal("createver", confDevenition.Code);
            Assert.Equal("2.0.0", confDevenition.VersionFrom);
        }
Ejemplo n.º 26
0
        public ConfigDto GetDeviceConfig(DeviceId deviceId)
        {
            var conf       = _configHandler.GetDeviceConfig(deviceId);
            var valueDefs  = _configHandler.GetValueSpecifications(conf.Values).ToList();
            var actionDefs = _configHandler.GetActions(conf.Actions);

            //Copy keys in the Component
//            valueDefs.ForEach(x => x.Component.Id = x.Name);
//            var valueSpecCopy = valueDefs.Select(x => x.Component).ToList();

            var uis = _configHandler.GetUiLayouts().ToList();

            // FIXME TODO Woraround für Newtonsoft.Json Bug
            // CamelCaseSerialization of Dictionaries

//            foreach (var def in valueDefs)
//            {
//                def.Component.AdditionalProperties = def.Component.AdditionalProperties.ConvertToLowerCamelCaseKeys();
//            }

            foreach (var ui in uis)
            {
                ui.AdditionalProperties = ui.AdditionalProperties.ConvertToLowerCamelCaseKeys();
            }

            var tabKeys = _configHandler.GetTabDefinitions();
            var tabs    = tabKeys.Where(x => conf.Tabs.Contains(x.Key)).ToList();

            var dto = new ConfigDto
            {
                DeviceId    = deviceId.FullId,
                DeviceName  = deviceId.DeviceName,
                User        = deviceId.User,
                Reconfigure = true,

                Info = conf.Info,
                Tabs = tabs
//                Tabs = GetDeviceTabs(deviceId)
            };

            return(dto);
        }
Ejemplo n.º 27
0
        public async Task SaveConfigAsync(Guid UserId, ConfigDto ConfigDto)
        {
            Config conf = await dbContext.Configs.FirstOrDefaultAsync(x => x.UserId == UserId);

            if (conf == null)
            {
                await dbContext.Configs.AddAsync(mapper.Map <Config>(ConfigDto));
            }
            else
            {
                conf.CPUId   = ConfigDto.CPUId;
                conf.RAM     = ConfigDto.RAM;
                conf.GPUId   = ConfigDto.GPUId;
                conf.GPUSize = ConfigDto.GPUSize;
                conf.OSId    = ConfigDto.OSId;
                conf.Others  = ConfigDto.others;
            }

            await dbContext.SaveChangesAsync();
        }
Ejemplo n.º 28
0
        public async Task <ConfigDto> GetConfigAsync(Int32 userId)
        {
            Check.IfNullOrZero(userId);

            var config = await CacheHelper.GetOrSetCacheAsync(new ConfigCacheKey(userId), () => _userContext.GetConfigAsync(userId));

            if (config == null)
            {
                throw new BusinessException("桌面配置信息获取失败");
            }
            var configDto = new ConfigDto
            {
                Id                   = config.Id,
                Skin                 = config.Skin,
                UserFace             = config.UserFace,
                AppSize              = config.AppSize,
                AppVerticalSpacing   = config.AppVerticalSpacing,
                AppHorizontalSpacing = config.AppHorizontalSpacing,
                DefaultDeskNumber    = config.DefaultDeskNumber,
                DefaultDeskCount     = config.DefaultDeskCount,
                IsModifyUserFace     = config.IsModifyUserFace,
                AppXy                = config.AppXy,
                DockPosition         = config.DockPosition,
                WallpaperMode        = config.WallpaperMode,
                IsBing               = config.IsBing,
                UserId               = config.UserId
            };

            if (!config.IsBing)
            {
                var wallpaper = await CacheHelper.GetOrSetCacheAsync(new WallpaperCacheKey(userId), () => _userContext.GetWallpaperAsync(config.WallpaperId));

                configDto.WallpaperUrl    = wallpaper.Url;
                configDto.WallpaperWidth  = wallpaper.Width;
                configDto.WallpaperHeigth = wallpaper.Height;
                configDto.WallpaperSource = wallpaper.Source;
            }

            return(configDto);
        }
        public HttpResponseMessage Get()
        {
            try
            {
                var configurationData = new ConfigDto();
                configurationData.DefaultFilters = _jsonserializer
                                                   .Deserialize <ConfigDto>
                                                       (System.IO.File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath("/ReportConfig.json")))
                                                   .DefaultFilters;

                if (configurationData == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.ServiceUnavailable,
                                                  string.Format("unable to find resource")));
                }
                return(Request.CreateResponse(HttpStatusCode.OK, configurationData.DefaultFilters));
            }
            catch (Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, "INTERNAL SERVER PROBLEM"));
            }
        }
Ejemplo n.º 30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //use newtonSoft for json serialize for controller
            services.AddControllers()
            .AddNewtonsoftJson(options =>
            {
                //use pascal case json
                options.UseMemberCasing();
            });

            services.AddControllersWithViews()
            .AddJsonOptions(options =>
            {
                //use pascal case json
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            //locale & user info for base component
            services.AddSingleton <IBaseResService, BaseResService>();
            services.AddSingleton <IBaseUserService, BaseUserService>();

            //appSettings "FunConfig" section -> _Fun.Config
            var config = new ConfigDto();

            Configuration.GetSection("FunConfig").Bind(config);
            _Fun.Config = config;

            //ado.net for mssql
            services.AddTransient <DbConnection, SqlConnection>();
            services.AddTransient <DbCommand, SqlCommand>();

            //initial _Fun by mssql
            IServiceProvider di = services.BuildServiceProvider();

            _Fun.Init(di, DbTypeEnum.MSSql);
        }