Example #1
0
        public MainWindow()
        {
            InitializeComponent();

            _connections = new BindingList <GeneratorConfig.Connection>();
            _tables      = new BindingList <string>();

            this.ConnectionsCombo.DataContext = _connections;
            this.DataContext = this;

            var configFilePath = GetConfigurationFilePath();

            config                     = JsonConfigHelper.LoadConfig <GeneratorConfig>(configFilePath);
            config.Connections         = config.Connections ?? new List <GeneratorConfig.Connection>();
            config.RemoveForeignFields = config.RemoveForeignFields ?? new List <string>();

            foreach (var connection in config.Connections)
            {
                _connections.Add(connection);
            }

            if (!config.WebProjectFile.IsEmptyOrNull())
            {
                var webConfig = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, config.WebProjectFile))), "web.config");
                AddConnectionsFromAppConfig(webConfig);
            }
        }
        public void ExportImportE2E()
        {
            string key           = "key1";
            var    config        = new SimpleTypedConfig <bool>(key, "", true);
            var    dataStore     = new MockDataStore();
            var    configManager = GetConfigManager(
                new InitSettings()
            {
                DataStore = dataStore
            },
                config);

            // update
            configManager.UpdateConfig(key, false, ConfigScope.CurrentUser);

            // exportconfig
            string path   = Path.GetRandomFileName();
            var    helper = new JsonConfigHelper(configManager.ConfigFilePath, dataStore);

            helper.ExportConfigFile(path);

            // clear
            configManager.ClearConfig(key, ConfigScope.CurrentUser);
            Assert.True(configManager.GetConfigValue <bool>(key));

            // import
            helper.ImportConfigFile(path);
            configManager.BuildConfig();
            Assert.False(configManager.GetConfigValue <bool>(key));
        }
Example #3
0
        /// <summary>
        /// Adds translations from JSON files at specified path. File names in this directory should be in format
        /// {anyprefix}.{languageID}.json where {languageID} is a language code like 'en', 'en-GB' etc.
        /// </summary>
        /// <param name="path">Path containing JSON files</param>
        public static void AddFromFilesInFolder(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (!Directory.Exists(path))
            {
                return;
            }

            var files = Directory.GetFiles(path, "*.json");

            Array.Sort(files);

            foreach (var file in files)
            {
                var texts  = JsonConfigHelper.LoadConfig <Dictionary <string, JToken> >(file);
                var langID = Path.GetFileNameWithoutExtension(Path.GetFileName(file));

                var idx = langID.LastIndexOf(".");
                if (idx >= 0)
                {
                    langID = langID.Substring(idx + 1);
                }

                if (langID.ToLowerInvariant() == "invariant")
                {
                    langID = "";
                }

                AddFromNestedDictionary(texts, "", langID);
            }
        }
Example #4
0
        public IActionResult GetRedisSecretConfigByCustomMethod()
        {
            // 读取自定义json文件
            RedisHostOptions redisOption = JsonConfigHelper.GetAppSettings <RedisHostOptions>("JsonFile/secret.json", "redis");

            return(Ok(redisOption));
        }
Example #5
0
        public static GeneratorConfig Load()
        {
            var configFilePath = GetConfigurationFilePath();
            var config         = JsonConfigHelper.LoadConfig <GeneratorConfig>(configFilePath);

            config.Connections         = config.Connections ?? new List <GeneratorConfig.Connection>();
            config.RemoveForeignFields = config.RemoveForeignFields ?? new List <string>();
            return(config);
        }
 public void LoadSetting()
 {
     if (_isSettingLoaded)
     {
         return;
     }
     _isSettingLoaded = true;
     //Load setting here
     JsonConfigHelper.ReadConfig(this, SettingFileName);
 }
Example #7
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            // 获取接口的Token值
            string token = context.HttpContext.Request.Headers["Authorization"].ToString();
            // 获取配置文件的权限码
            string fucCode = JsonConfigHelper.GetSectionValue("Token");

            if (token != fucCode || token == null)
            {
                throw new Exception("权限不足!");
            }
        }
Example #8
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     OptionConfigure(services);
     CustomOptionConfigure(services);
     services.AddEasyCaching(options =>
     {
         options.UseRedis(configure =>
         {
             RedisHostOptions redisOption = JsonConfigHelper.GetAppSettings <RedisHostOptions>("JsonFile/secret.json", "redis");
             configure.DBConfig.Endpoints.Add(new EasyCaching.Core.Configurations.ServerEndPoint(redisOption.host, redisOption.port));
             configure.DBConfig.AllowAdmin = true;
         }, "RedisExample");
     });
     services.AddControllers();
 }
Example #9
0
        public ListResponse <TranslationItem> List(TranslationListRequest request)
        {
            var result = new ListResponse <TranslationItem>();

            var availableKeys    = GetAllAvailableLocalTextKeys();
            var targetLanguageID = request.TargetLanguageID.TrimToNull();

            var customTranslations = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            var textsFilePath = GetUserTextsFilePath(targetLanguageID);

            if (File.Exists(textsFilePath))
            {
                var json = JsonConfigHelper.LoadConfig <Dictionary <string, JToken> >(textsFilePath);
                JsonLocalTextRegistration.ProcessNestedDictionary(json, "", customTranslations);
                foreach (var key in customTranslations.Keys)
                {
                    availableKeys.Add(key);
                }
            }

            var sorted = new string[availableKeys.Count];

            availableKeys.CopyTo(sorted);
            Array.Sort(sorted);

            var registry = Dependency.Resolve <ILocalTextRegistry>();

            targetLanguageID = targetLanguageID ?? "";
            var sourceLanguageID = request.SourceLanguageID.TrimToEmpty();

            result.Entities = new List <TranslationItem>();

            Func <string, string> effective = delegate(string key)
            {
                if (key.StartsWith("Navigation."))
                {
                    key = key.Substring("Navigation.".Length);
                    return(key.Split(new char[] { '/' }).Last());
                }
                else if (key.StartsWith("Forms.") && key.Contains(".Categories."))
                {
                    return(key.Split(new char[] { '.' }).Last().TrimToNull());
                }

                return(key);
            };

            foreach (var key in sorted)
            {
                string customText;
                if (!customTranslations.TryGetValue(key, out customText))
                {
                    customText = null;
                }

                result.Entities.Add(new TranslationItem
                {
                    Key        = key,
                    SourceText = registry.TryGet(sourceLanguageID, key) ?? effective(key),
                    TargetText = registry.TryGet(targetLanguageID, key) ?? effective(key),
                    CustomText = customText
                });
            }

            return(result);
        }
        private void DoAdNewModule(BackgroundWorker backgroundWorker, string fileName)
        {
            var step = 0;
            //1.Verify the Zip file.
            //- The zip file is existed.
            //- The zip file contains the files.
            //2. Verify file contents.
            //- At least 1 dll file should be in the zip file.
            //- The Module.json config file should be found.
            //- The Module is valid and Name is not empty.
            ZipArchive   zip = null;
            ModuleConfig newModule;

            try
            {
                backgroundWorker.ReportProgress(++step, "Verify the zip file.");

                #region Verify the zip file

                if (!File.Exists(fileName))
                {
                    backgroundWorker.ReportProgress(++step,
                                                    "Error: Zip file is not existed. Please check the file location.");
                    return;
                }

                try
                {
                    zip = ZipFile.OpenRead(fileName);
                }
                catch (Exception ex)
                {
                    backgroundWorker.ReportProgress(++step, $"Error: {ex.Message}");
                    Logger.Exception(ex);
                    return;
                }

                #endregion Verify the zip file

                backgroundWorker.ReportProgress(++step, "Verify the file contents.");

                #region Verify the file contents

                if (zip.Entries.Count <= 1)
                {
                    backgroundWorker.ReportProgress(++step, "Error: Zip file is empty.");
                    return;
                }

                var jsonFile = zip.Entries.FirstOrDefault(f => f.Name.StartsWith("Module", StringComparison.Ordinal) &&
                                                          f.Name.EndsWith(".json", StringComparison.Ordinal));

                if (jsonFile.IsNull())
                {
                    backgroundWorker.ReportProgress(++step, "Error: The module json config file is not found.");
                    return;
                }

                var dll = zip.Entries.FirstOrDefault(f => f.Name.EndsWith(".dll", StringComparison.Ordinal));

                if (dll.IsNull())
                {
                    backgroundWorker.ReportProgress(++step, "Error: The module doesn't have any binary file.");
                    return;
                }

                #endregion Verify the file contents

                backgroundWorker.ReportProgress(++step, "Verify the config file.");

                #region Verify the config file

                try
                {
                    // ReSharper disable once PossibleNullReferenceException
                    var tmpFileName = Path.Combine(Path.GetTempPath(), jsonFile.Name);
                    jsonFile.ExtractToFile(tmpFileName, true);
                    newModule = JsonConfigHelper.ReadConfig <ModuleConfig>(tmpFileName);
                    File.Delete(tmpFileName);

                    if (newModule.Name.IsNullOrEmpty())
                    {
                        backgroundWorker.ReportProgress(++step, "Error: Module Name is empty.");
                        return;
                    }

                    if (newModule.Version.IsNullOrEmpty())
                    {
                        backgroundWorker.ReportProgress(++step, "Error: Module Version is empty.");
                        return;
                    }
                    //Verify the binaries if have
                    if (newModule.AssemplyFiles.Count > 0)
                    {
                        var notfounds =
                            newModule.AssemplyFiles.Where(a => !zip.Entries.Any(t => t.Name.EndsWith(a))).ToList();
                        if (notfounds.Any())
                        {
                            backgroundWorker.ReportProgress(++step,
                                                            $"Error: Binaries are not found '{string.Join(",", notfounds)}'.");
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    backgroundWorker.ReportProgress(++step, $"Error: {ex.Message}");
                    Logger.Exception(ex);
                    return;
                }

                #endregion Verify the config file

                //Check duplicate module. if existing module then update the existing one.
                backgroundWorker.ReportProgress(++step, "Check Module duplicating.");

                #region Check Module duplicating

                var oldModule = ShellConfigManager.Modules.FirstOrDefault(m => m.Name.EqualsIgnoreCase(newModule.Name));
                if (oldModule != null)
                {
                    backgroundWorker.ReportProgress(++step,
                                                    $"The module '{oldModule.Name}' is an existing module with version '{oldModule.Version}'.");

                    //Compare the version on both Modules.
                    if (
                        MessageBoxService.ConfirmDialog(this,
                                                        $"Do you want to overwrite module:\n- '{oldModule.Name}' version '{oldModule.Version}' with version '{newModule.Version}'?")
                        .Result != MessageBoxResult.Yes)
                    {
                        backgroundWorker.ReportProgress(++step, "The module importing had been canceled by user.");
                        return;
                    }

                    if (oldModule.IsEnabled)
                    {
                        backgroundWorker.ReportProgress(++step,
                                                        $"The old module '{oldModule.Name}' cannot be overwritten because it is enabled. Please disable it and restart the application in order to overwrite the module '{newModule.Name}'.");
                        return;
                    }

                    if (!oldModule.AllowToManage)
                    {
                        backgroundWorker.ReportProgress(++step,
                                                        $"The old module '{oldModule.Name}' is not allow to be overwritten as allow to manage is disabled.");
                        return;
                    }

                    Directory.CreateDirectory(ShellConfigManager.ShellConfig.BackupModulePath);
                    var backupFileName = Path.Combine(ShellConfigManager.ShellConfig.BackupModulePath,
                                                      new DirectoryInfo(oldModule.Directory).Name + "_" + DateTime.Now.ToString("yyyy.mm.dd-hh.mm.ss") +
                                                      ".zip");

                    ZipFile.CreateFromDirectory(oldModule.Directory, backupFileName, CompressionLevel.Optimal, false);
                    backgroundWorker.ReportProgress(++step,
                                                    $"Backup the old module '{oldModule.Name}' to {backupFileName}.");

                    Directory.Delete(oldModule.Directory, true);
                }

                #endregion Check Module duplicating

                backgroundWorker.ReportProgress(++step, "Extract zip file to Module folder.");

                #region Extract zip file to Module folder.

                // ReSharper disable once AssignNullToNotNullAttribute
                var extractFolderName = Path.Combine(ShellConfigManager.ShellConfig.ModulePath,
                                                     Path.GetFileNameWithoutExtension(fileName));
                zip.ExtractToDirectory(extractFolderName);
                //Check if the extracted folder had only 1 sub-folder and the same is exactly the same with parent folder.
                //Then move all files and folders to the parent then delete sub-folder.
                var extractDirectory = new DirectoryInfo(extractFolderName);
                if (extractDirectory.GetDirectories().Length == 1)
                {
                    var sub = extractDirectory.GetDirectories().First();
                    if (sub.Name.EqualsIgnoreCase(extractDirectory.Name))
                    {
                        sub.MoveAllFilesAndFoldersTo(extractDirectory.FullName);
                    }
                }

                #endregion Extract zip file to Module folder.

                backgroundWorker.ReportProgress(++step,
                                                "New module had been imported. Please restart the application to use the new module.");
            }
            catch (Exception ex)
            {
                backgroundWorker.ReportProgress(++step, $"Error: {ex.Message}");
                backgroundWorker.ReportProgress(++step,
                                                "Import module failed. Please re-start the application and try again.");
                Logger.Exception(ex);
            }
            finally
            {
                //Close the zip file
                zip?.Dispose();
                //Write info to log.
                Logger.Info(TextLog);
            }
        }
Example #11
0
        public ScriptBundleManager()
        {
            var settings = Config.Get <ScriptBundlingSettings>();

            var bundles = JsonConfigHelper.LoadConfig <Dictionary <string, string[]> >(
                HostingEnvironment.MapPath("~/Scripts/site/ScriptBundles.json"));

            bundleIncludes = BundleUtils.ExpandBundleIncludes(bundles, "dynamic://Bundle.", "script");

            if (bundles.Count == 0 ||
                settings.Enabled != true)
            {
                return;
            }

            bundleKeyBySourceUrl  = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            bundleKeysBySourceUrl = new Dictionary <string, HashSet <string> >(StringComparer.OrdinalIgnoreCase);
            bundleByKey           = new Dictionary <string, ConcatenatedScript>(StringComparer.OrdinalIgnoreCase);

            bool minimize   = settings.Minimize == true;
            var  noMinimize = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            if (settings.NoMinimize != null)
            {
                noMinimize.AddRange(settings.NoMinimize);
            }

            foreach (var pair in bundles)
            {
                var sourceFiles = pair.Value;
                if (sourceFiles == null ||
                    sourceFiles.Length == 0)
                {
                    continue;
                }

                var bundleKey   = pair.Key;
                var bundleName  = "Bundle." + bundleKey;
                var bundleParts = new List <Func <string> >();
                var scriptNames = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                Action <string> registerInBundle = delegate(string sourceFile)
                {
                    if (bundleKey.IndexOf('/') < 0 && !bundleKeyBySourceUrl.ContainsKey(sourceFile))
                    {
                        bundleKeyBySourceUrl[sourceFile] = bundleKey;
                    }

                    HashSet <string> bundleKeys;
                    if (!bundleKeysBySourceUrl.TryGetValue(sourceFile, out bundleKeys))
                    {
                        bundleKeys = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                        bundleKeysBySourceUrl[sourceFile] = new HashSet <string>();
                    }

                    bundleKeys.Add(bundleKey);
                };

                foreach (var sourceFile in sourceFiles)
                {
                    if (sourceFile.IsNullOrEmpty())
                    {
                        continue;
                    }

                    if (sourceFile.StartsWith("dynamic://", StringComparison.OrdinalIgnoreCase))
                    {
                        registerInBundle(sourceFile);

                        var scriptName = sourceFile.Substring(10);
                        scriptNames.Add(scriptName);
                        bundleParts.Add(() =>
                        {
                            if (recursionCheck != null)
                            {
                                if (recursionCheck.Contains(scriptName) || recursionCheck.Count > 100)
                                {
                                    return(String.Format(errorLines,
                                                         String.Format("Caught infinite recursion with dynamic scripts '{0}'!",
                                                                       String.Join(", ", recursionCheck))));
                                }
                            }
                            else
                            {
                                recursionCheck = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                            }

                            recursionCheck.Add(scriptName);
                            try
                            {
                                var code = DynamicScriptManager.GetScriptText(scriptName);
                                if (code == null)
                                {
                                    return(String.Format(errorLines,
                                                         String.Format("Dynamic script with name '{0}' is not found!", scriptName)));
                                }

                                if (minimize &&
                                    !scriptName.StartsWith("Bundle.", StringComparison.OrdinalIgnoreCase))
                                {
                                    try
                                    {
                                        var result = NUglify.Uglify.Js(code);
                                        if (!result.HasErrors)
                                        {
                                            code = result.Code;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        ex.Log();
                                    }
                                }

                                return(code);
                            }
                            finally
                            {
                                recursionCheck.Remove(scriptName);
                            }
                        });

                        continue;
                    }

                    string sourceUrl = BundleUtils.ExpandVersionVariable(sourceFile);
                    sourceUrl = VirtualPathUtility.ToAbsolute(sourceUrl);

                    if (sourceUrl.IsNullOrEmpty())
                    {
                        continue;
                    }

                    registerInBundle(sourceUrl);

                    bundleParts.Add(() =>
                    {
                        var sourcePath = HostingEnvironment.MapPath(sourceUrl);
                        if (!File.Exists(sourcePath))
                        {
                            return(String.Format(errorLines, String.Format("File {0} is not found!", sourcePath)));
                        }

                        if (minimize && !noMinimize.Contains(sourceFile))
                        {
                            if (settings.UseMinJS == true)
                            {
                                var minPath = Path.ChangeExtension(sourcePath, ".min.js");
                                if (File.Exists(minPath))
                                {
                                    sourcePath = minPath;
                                    using (StreamReader sr = new StreamReader(File.OpenRead(sourcePath)))
                                        return(sr.ReadToEnd());
                                }
                            }

                            string code;
                            using (StreamReader sr = new StreamReader(File.OpenRead(sourcePath)))
                                code = sr.ReadToEnd();

                            try
                            {
                                var result = NUglify.Uglify.Js(code);
                                if (result.HasErrors)
                                {
                                    return(code);
                                }
                                return(result.Code);
                            }
                            catch (Exception ex)
                            {
                                ex.Log();
                                return(code);
                            }
                        }

                        using (StreamReader sr = new StreamReader(File.OpenRead(sourcePath)))
                            return(sr.ReadToEnd());
                    });
                }

                var bundle = new ConcatenatedScript(bundleParts, checkRights: () =>
                {
                    foreach (var scriptName in scriptNames)
                    {
                        if (recursionCheck != null)
                        {
                            if (recursionCheck.Contains(scriptName) || recursionCheck.Count > 100)
                            {
                                throw new InvalidOperationException(String.Format(
                                                                        "Caught infinite recursion with dynamic scripts '{0}'!",
                                                                        String.Join(", ", recursionCheck)));
                            }
                        }
                        else
                        {
                            recursionCheck = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                        }

                        recursionCheck.Add(scriptName);
                        try
                        {
                            DynamicScriptManager.CheckScriptRights(scriptName);
                        }
                        finally
                        {
                            recursionCheck.Remove(scriptName);
                        }
                    }
                });

                DynamicScriptManager.Register(bundleName, bundle);
                bundleByKey[bundleKey] = bundle;
            }

            isEnabled = true;
        }
 public void SaveSetting() => JsonConfigHelper.SaveConfig(this, SettingFileName);
Example #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(option => option.AddPolicy("cors",
                                                        policy => policy.AllowAnyHeader()
                                                        .AllowAnyMethod()
                                                        .AllowCredentials()
                                                        .AllowAnyOrigin()));

            services.AddSession(config =>
            {
                config.IdleTimeout        = TimeSpan.FromSeconds(10);
                config.Cookie.HttpOnly    = true;
                config.Cookie.IsEssential = true;
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(ErrorFilterAttribute));
                options.Filters.Add(typeof(GlobalFilterAttribute));
                options.RespectBrowserAcceptHeader = true;
            });//.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddMvc();


            var jObject = new JsonConfigHelper("BomSetting.json").jObject;

            SqlSugarBase.DB_ConnectionString           = jObject.SelectToken("主数据库连接").ToString();    //为数据库连接字符串赋值
            SqlSugarBase.DB_ConnectionStringFormatOnDB = jObject.SelectToken("帐套数据库连接格式").ToString(); //为数据库连接字符串赋值
            BomService.BomConflictHandleWay            = jObject.SelectToken("货号存在多BOM").ToString() == "取最新"
                                                    ? EnumBomConflictWay.GetLastest : EnumBomConflictWay.Error;
            //"ERP系统序列号:": "GAD12012",
            //"层级类型": "带点号", //或 纯数字
            //"ERP系统": "T8", //或 "SUNLIKE"
            //LoginService.SYS_NUMBER = jObject.SelectToken("ERP系统序列号").ToString();
            BomService.BomLevelWay = jObject.SelectToken("层级类型").ToString() == "带点号" ? BomLevelWay.Split : BomLevelWay.Number;
            LoginService.SYS_MODEL = jObject.SelectToken("ERP系统").ToString() == "T8" ? SysModel.T8 : SysModel.SUNLIKE;


            BomService.DefaultBomHeaderSection = new Dictionary <string, string>();
            BomService.DefaultBomBodySection   = new Dictionary <string, string>();
            BomService.DefaultPrdtSection      = new Dictionary <string, string>();


            var jToken = jObject.SelectToken("T8默认值");

            if (jToken != null)
            {
                var jTokenBomHeader = jToken.SelectToken("BOM表头");
                if (jTokenBomHeader != null)
                {
                    foreach (JProperty item in jTokenBomHeader.Children())
                    {
                        BomService.DefaultBomHeaderSection.Add(item.Name, item.Value.ToString());
                    }
                }

                var jTokenBomBody = jToken.SelectToken("BOM表身");
                if (jTokenBomBody != null)
                {
                    foreach (JProperty item in jTokenBomBody.Children())
                    {
                        BomService.DefaultBomBodySection.Add(item.Name, item.Value.ToString());
                    }
                }

                var jTokenPrdt = jToken.SelectToken("货号资料");
                if (jTokenPrdt != null)
                {
                    foreach (JProperty item in jTokenPrdt.Children())
                    {
                        BomService.DefaultPrdtSection.Add(item.Name, item.Value.ToString());
                    }
                }
            }

            //// //层级类型
            //// //
        }