コード例 #1
0
        /// <summary>
        /// Gets the files to move based on the given configuration
        /// </summary>
        /// <param name="sourceDirectory">The directory to search for files to move</param>
        /// <param name="config">The <see cref="TemplateConfig"/></param>
        /// <param name="promptResults">A <see cref="IDictionary{TKey, TValue}"/> of values from the prompts, where the key is the <see cref="AbstractPrompt.Id"/> and Value is the prompt result</param>
        /// <returns>A <see cref="FileGroup"/> of all files and the required template variables</returns>
        /// <exception cref="ArgumentException"></exception>
        public static IEnumerable <FileGroup> GetFilesToMove(string sourceDirectory, TemplateConfig config, IDictionary <string, object> promptResults)
        {
            if (string.IsNullOrWhiteSpace(sourceDirectory))
            {
                throw new ArgumentException("Source directory cannot be null or empty string", nameof(sourceDirectory));
            }

            var filesToMove = new List <FileGroup>();
            var info        = new DirectoryInfoWrapper(new DirectoryInfo(sourceDirectory));

            foreach (var file in config.Files)
            {
                var matcher = new Matcher();
                matcher.AddInclude(file.Glob);
                var result = matcher.Execute(info);

                filesToMove.Add(
                    new FileGroup
                {
                    Files            = result.Files,
                    VariablesToApply =
                        promptResults
                        .Where(v => file.Variables.Contains(v.Key))
                        .ToDictionary(p => p.Key, p => p.Value)
                });
            }

            return(filesToMove);
        }
コード例 #2
0
 public SMTPService(SmtpConfig smtpConfig, TemplateConfig templateConfig, NotificationTemplateConfig notificationTemplateConfig, ILogger <SMTPService> logger)
 {
     this.SmtpConfig                 = smtpConfig;
     this.TemplateConfig             = templateConfig;
     this.NotificationTemplateConfig = notificationTemplateConfig;
     this.Logger = logger;
 }
コード例 #3
0
        public async Task GivenATemplateWithMultipleMatchingGlobs_AndValidFilesToMove_WhenGetFilesToMoveIsCalled_ThenAllTheFilesWillBeFound(int expectedAmount)
        {
            //arrange
            for (var i = 0; i < expectedAmount; i++)
            {
                var filename = $"test-file-{i}.html";
                await File.WriteAllTextAsync(Path.Join(TempPath, filename), string.Empty).ConfigureAwait(false);
            }

            var config = new TemplateConfig {
                Files = new List <TemplateFileConfig> {
                    new TemplateFileConfig {
                        Glob = "*.html"
                    }
                }
            };
            var prompts = new Dictionary <string, object>();

            //act
            var result = FileProcessor.GetFilesToMove(TempPath, config, prompts);

            //assert
            Assert.Single(result);
            Assert.Equal(expectedAmount, result.First().Files.Count());
        }
コード例 #4
0
        /// <summary>
        /// - Reads the template
        /// - Update wild card elements from data table with their values
        /// </summary>
        /// <param name="templateName">Template name</param>
        /// <param name="templateInfo">DataTable which contains wild card elements and their values</param>
        /// <returns></returns>
        public string GetTemplateData(string templateName, DataTable templateInfo)
        {
            string updatedTemplateData = null;

            if (templateConfigPath != null)
            {
                if (templateConfig == null)
                {
                    templateConfig = ConfigReader.Read(templateConfigPath, typeof(TemplateConfig)) as TemplateConfig;
                    if (templateConfig != null)
                    {
                        updatedTemplateData = GetUpdatedTemplateData(GetTemplateData(GetCurrentTemplatePath(templateName)), templateInfo);
                    }
                    else
                    {
                        throw new ApplicationException("Serialization of TemplateConfig.xml failed");
                    }
                }
            }
            else
            {
                throw new ApplicationException("TemplateConfig.xml path invalid");
            }

            return(updatedTemplateData);
        }
コード例 #5
0
 public async Task <bool> Change(TemplateConfig templateConfig)
 {
     return(await WithConnection(async (connection) =>
     {
         DynamicParameters parameters = new DynamicParameters();
         parameters.Add("@Id", templateConfig.Id, DbType.String);
         parameters.Add("@TemplateId", templateConfig.TemplateId, DbType.String);
         parameters.Add("@TemplatePositionCode", templateConfig.TemplatePositionCode, DbType.String);
         parameters.Add("@ComponentType", templateConfig.ComponentType.AsEnumToInt(), DbType.Int32);
         parameters.Add("@ComponentId", templateConfig.ComponentId, DbType.String);
         parameters.Add("@Status", templateConfig.Status.AsEnumToInt(), DbType.Int16);
         parameters.Add("@PathToView", templateConfig.PathToView, DbType.String);
         parameters.Add("@DataSource", templateConfig.DataSource, DbType.String);
         parameters.Add("@UpdatedDateUtc", templateConfig.UpdatedDateUtc, DbType.DateTime);
         parameters.Add("@UpdatedUid", templateConfig.UpdatedUid, DbType.String);
         var rowCount = 0;
         rowCount = await connection.ExecuteAsync(ProcName.TemplateConfig_Change, parameters, commandType: CommandType.StoredProcedure);
         if (rowCount != 0)
         {
             return true;
         }
         else
         {
             return false;
         }
     }));
 }
コード例 #6
0
        public async Task GivenAValidStringWithAVariableAndAnEmptyDictionary_WhenGetConfigFromStringIsCalled_ThenTheValueIsReturnedWithoutTheVariable()
        {
            //arrange
            var dictionary = new Dictionary <string, object>();
            var expected   = new TemplateConfig
            {
                Files = new List <TemplateFileConfig>
                {
                    new TemplateFileConfig
                    {
                        Glob = "/index.html"
                    }
                }
            };
            const string json = @"
{
	""files"": [
		{
			""glob"": ""{{projectName}}/index.html""
		}
	]
}";

            //act
            var result = await ConfigReader.GetConfigFromString(json, dictionary).ConfigureAwait(false);

            //assert
            Assert.Equal(expected.Files[0].Glob, result.Files[0].Glob);
        }
コード例 #7
0
        private static IImageEncoder GetEncoder(TemplateConfig.Template template, TemplateConfig config)
        {
            switch ((template.Format ?? config.TemplateDefaults.Format).ToUpperInvariant())
            {
            case "JPG":
            case "JPEG":
                return(new JpegEncoder()
                {
                    IgnoreMetadata = true,
                    Quality = template.Quality ?? config.TemplateDefaults.Quality ?? 90
                });

            case "PNG":
                return(new PngEncoder());

            case "BMP":
                return(new BmpEncoder());

            case "GIF":
                var gifQuantizer = template.GifQuantizer ?? config.TemplateDefaults.GifQuantizer;
                var paletteSize  = template.GifPaletteSize ?? config.TemplateDefaults.GifPaletteSize ?? 0;
                var quantizer    = CreateQuantizerFromString(gifQuantizer, paletteSize);
                return(new GifEncoder()
                {
                    IgnoreMetadata = true,
                    Quantizer = quantizer,
                });

            default:
                throw new ArgumentOutOfRangeException("format");
            }
        }
コード例 #8
0
        public void LoadTemplateTest()
        {
            var data = TemplateConfig.ReadDefaultTemplate();

            //output.WriteLine(JsonConvert.SerializeObject(data));
            Assert.True(data.Count > 0);
        }
コード例 #9
0
        public void GivenATemplateWithOneGlob_AndNoMatchingVariableInThePrompt_WhenGetFilesToMoveIsCalled_ThenOneFileWillBeFoundToMove_WithNoVariables()
        {
            //arrange
            var prompts = new Dictionary <string, object> {
                { "variable", true }
            };

            var config = new TemplateConfig
            {
                Files = new List <TemplateFileConfig>
                {
                    new TemplateFileConfig {
                        Glob      = "index.html",
                        Variables = new List <string> {
                            "test"
                        }
                    }
                }
            };

            //act
            var result = FileProcessor.GetFilesToMove(TempPath, config, prompts);

            //assert
            Assert.Single(result);
            Assert.Empty(result.First().VariablesToApply);
        }
コード例 #10
0
        public void GivenATemplateWithOneGlob_AndSomeMatchingVariablesInThePrompt_WhenGetFilesToMoveIsCalled_ThenOneFileWillBeFoundToMove_WithOnlyTheVariablesWithAMatchingKey()
        {
            //arrange
            var expectedVariable = new KeyValuePair <string, object>("test", "mystring");
            var prompts          = new Dictionary <string, object>
            {
                { expectedVariable.Key, expectedVariable.Value },
                { "variable", true }
            };

            var config = new TemplateConfig
            {
                Files = new List <TemplateFileConfig>
                {
                    new TemplateFileConfig
                    {
                        Glob      = "index.html",
                        Variables = new List <string> {
                            expectedVariable.Key
                        }
                    }
                }
            };

            //act
            var result = FileProcessor.GetFilesToMove(TempPath, config, prompts);

            //assert
            Assert.Single(result);
            Assert.True(result.First().VariablesToApply.ContainsKey(expectedVariable.Key));
            Assert.Equal(expectedVariable.Value, result.First().VariablesToApply[expectedVariable.Key]);
        }
コード例 #11
0
        public async Task GivenAValidFile_WithAVariable_AndADictionaryWithTheVariableEntry_WhenGetConfigFromFileIsCalled_ThenTheExpectedObjectIsReturned()
        {
            //arrange
            var dictionary = new Dictionary <string, object>()
            {
                { "projectName", "myProject" }
            };
            var expected = new TemplateConfig
            {
                Files = new List <TemplateFileConfig>
                {
                    new TemplateFileConfig
                    {
                        Glob = "myProject/index.html"
                    }
                }
            };
            const string json = @"
{
	""files"": [
		{
			""glob"": ""{{projectName}}/index.html""
		}
	]
}";
            await File.WriteAllTextAsync(TempFile, json).ConfigureAwait(false);

            //act
            var result = await ConfigReader.GetConfigFromFile(TempPath, dictionary).ConfigureAwait(false);

            //assert
            Assert.Equal(expected.Files[0].Glob, result.Files[0].Glob);
        }
コード例 #12
0
        /// <summary>
        /// 添加模板
        /// </summary>
        /// <param name="sqlconnect"></param>
        /// <returns></returns>
        public JsonResult AddTemp(TemplateConfig temp)
        {
            PageResponse reponse = new PageResponse();
            var          insert  = _sqliteFreeSql.Insert <TemplateConfig>();

            temp.Id = Guid.NewGuid().ToString();
            var res = insert.AppendData(temp);
            var i   = insert.ExecuteAffrows();

            _sqliteFreeSql.Dispose();
            if (i > 0)
            {
                reponse.code   = "200";
                reponse.status = 0;
                reponse.msg    = "添加成功!";
                reponse.data   = temp;
            }
            else
            {
                reponse.code   = "500";
                reponse.status = -1;
                reponse.msg    = "添加失败!";
            }
            return(Json(reponse));
        }
コード例 #13
0
 private void btn_add_Click(object sender, EventArgs e)
 {
     if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
     {
         TemplateConfig.AddPath(folderBrowserDialog1.SelectedPath);
         RefreshList();
     }
 }
コード例 #14
0
 private void btn_del_Click(object sender, EventArgs e)
 {
     if (listBox1.SelectedItem != null)
     {
         TemplateConfig.RemovePath(listBox1.SelectedIndex);
         RefreshList();
     }
 }
コード例 #15
0
        public void ItHasTemplateWritableProperty()
        {
            var expected = new TemplateConfig();

            _configuration.Template = expected;

            Assert.Equal(expected, _configuration.Template);
        }
コード例 #16
0
 private void CreateNew()
 {
     CurrentTemplateConfig = new TemplateConfig
     {
         Classify = Classify,
         Template = BaseTemplate
     };
     TabIndex = 0;
 }
コード例 #17
0
        /// <summary>
        /// 修改服务
        /// </summary>
        /// <param name="sqlconnect"></param>
        /// <returns></returns>
        public async Task <ActionResult> UpdateTemp(TemplateConfig temp)
        {
            PageResponse reponse = new PageResponse();
            var          update  = _sqliteFreeSql.Update <TemplateConfig>();
            var          i       = update.SetSource(temp).ExecuteAffrows();

            _sqliteFreeSql.Dispose();
            return(i > 0 ? Response(temp) : Response("添加失败"));
        }
コード例 #18
0
        /// <summary>
        ///     类型推导
        /// </summary>
        public static void Analyze(AnalyzeBlock root, TemplateConfig config)
        {
            var analyzer = new LuaTypeAnalyzer
            {
                Root   = root,
                Config = config
            };

            analyzer.DoAnalyze();
        }
コード例 #19
0
    public void ListCommand()
    {
        var templateConfig = new TemplateConfig();

        Console.WriteLine($"テンプレート名 : テンプレートへのパス");
        foreach (var template in templateConfig.ListTemplate())
        {
            Console.WriteLine($"{template.name} : {template.path}");
        }
    }
コード例 #20
0
        private void RefreshList()
        {
            listBox1.Items.Clear();
            List <String> paths = TemplateConfig.GetPaths();

            foreach (var p in paths)
            {
                listBox1.Items.Add(p);
            }
        }
コード例 #21
0
    public void CreateCommand([Option(0, "利用するテンプレート名")] string templateName, [Option(1, "作成するコンテスト名")] string contestName)
    {
        var templateConfig = new TemplateConfig();

        if (!templateConfig.IsInstalled(templateName))
        {
            Console.Error.WriteLine($"WA! {templateName} がテンプレート名に存在しません。");
            Console.Error.WriteLine($"    テンプレート一覧を確認してください。");

            Console.WriteLine($"テンプレート名 : テンプレートへのパス");
            foreach (var template in templateConfig.ListTemplate())
            {
                Console.WriteLine($"{template.name} : {template.path}");
            }
            return;
        }

        var invalidFileNameString = new string(Path.GetInvalidFileNameChars());

        if (invalidFileNameString.Any(invalidChar => contestName.Contains(invalidChar)))
        {
            Console.Error.WriteLine($"WA! 以下の文字は、コンテスト名に含むことができません。");
            Console.Error.WriteLine($"    {String.Join(" ", invalidFileNameString)}");
            return;
        }
        if (Directory.Exists(contestName) || File.Exists(contestName))
        {
            Console.Error.WriteLine($"WA! {contestName} はすでに存在しています。別のコンテスト名を使用してください。");
            return;
        }

        if (!templateConfig.IsInstalled(templateName))
        {
            var template = templateConfig.Get(templateName);
            Console.Error.WriteLine($"CE! テンプレート名 {template.name} のパス {template.path} に、テンプレートが存在しません。");
            Console.Error.WriteLine($"    install コマンドと -update オプションで、修正したテンプレートへのパスを上書き登録してください。");
            return;
        }

        Console.WriteLine("WJ... コンテスト名のディレクトリを作成します。");

        Directory.CreateDirectory(contestName);
        foreach (var problemName in new List <string> {
            "A", "B", "C", "D", "E", "F"
        })
        {
            Console.WriteLine($"WJ... {problemName} ディレクトリを作成します。");
            var template    = templateConfig.Get(templateName);
            var problemPath = Path.Combine(contestName, problemName);
            DirectoryEx.Copy(template.path, problemPath);
        }

        Console.WriteLine("AC! コンテスト用の各問題の作成が完了しました。");
    }
コード例 #22
0
        public void GivenAnEmptyDirectoryParameter_WhenGetFilesToMoveIsCalled_ThenAnArgumentExceptionWillBeThrown()
        {
            //arrange
            var config  = new TemplateConfig();
            var prompts = new Dictionary <string, object>();

            //act
            Assert.Throws <ArgumentException>(() => FileProcessor.GetFilesToMove("", config, prompts));

            //assert
        }
コード例 #23
0
        public string RunLua(TemplateConfig config)
        {
            var executer = new TemplateExecuter();
            var lua      = executer.InitLua(Context.SelectConfig);

            lua.DoString(CurrentTemplateConfig.Code);
            lua.DoString($"{config.Name}()");
            var code = executer.ResultCode;

            return(code != null?code.FromLuaChar() : string.Empty);
        }
コード例 #24
0
        /// <summary>
        /// 添加模板
        /// </summary>
        /// <param name="sqlconnect"></param>
        /// <returns></returns>
        public async Task <ActionResult> AddTemp(TemplateConfig temp)
        {
            var insert = _sqliteFreeSql.Insert <TemplateConfig>();

            temp.Id = Guid.NewGuid().ToString();
            var res = insert.AppendData(temp);
            var i   = insert.ExecuteAffrows();

            _sqliteFreeSql.Dispose();
            return(i > 0 ? Response(temp) : Response("添加失败"));
        }
コード例 #25
0
        public void GivenATemplateWithNoGlobs_WhenGetFilesToMoveIsCalled_ThenAnArgumentExceptionWillBeThrown()
        {
            //arrange
            var config  = new TemplateConfig();
            var prompts = new Dictionary <string, object>();

            //act
            var result = FileProcessor.GetFilesToMove(TempPath, config, prompts);

            //assert
            Assert.False(result.Any());
        }
コード例 #26
0
 public void DoAnalyze(List <AnalyzeElement> tElements, TemplateConfig config)
 {
     Config           = config;
     TemplateElements = tElements;
     OutcomeWords();
     MergeBlock();
     ConnectBlock(Root);
     MergeSimpleBlock(Root);
     MergeStatements(Root);
     ClearEmpty(Root);
     LuaTypeAnalyzer.Analyze(Root, Config);
     Release(Root);
 }
コード例 #27
0
        public string GetFontPath(TemplateConfig.Template template, TemplateConfig config)
        {
            if (template == null)
            {
                throw new ArgumentNullException(nameof(template));
            }
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            return(Path.Combine(_env.ContentRootPath, _options.Value.FontDirectory, template.Font ?? config.TemplateDefaults.Font));
        }
コード例 #28
0
    public void loadJSON()
    {
        config = null;
        menu.DirectoryCheck();

        //ファイルがない場合: 初期設定ファイルの生成
        if (!File.Exists(jsonPath))
        {
            config = new TemplateConfig();
            makeJSON();
        }

        //ファイルの読込を試行
        try
        {
            //ファイルの内容を一括読み出し
            string jsonString = File.ReadAllText(jsonPath, new UTF8Encoding(false));
            //設定クラスをJSONデコードして生成
            config = JsonUtility.FromJson <TemplateConfig>(jsonString);

            //ファイルのバージョンが古い場合は、デフォルト設定にして警告(nullの可能性も考慮してtry内)
            if (config.jsonVer != jsonVerMaster)
            {
                menu.ShowDialogOKCancel(LanguageManager.config.jsonloaders.OLD_CONFIG_HEAD, "" + jsonPath + LanguageManager.config.jsonloaders.OLD_CONFIG_BODY, 3f, () => {
                    //OK
                    makeJSON();
                }, () => {
                    //キャンセル
                });
                config = new TemplateConfig();
            }
        }
        catch (System.Exception e)
        {
            //JSONデコードに失敗した場合
            Debug.Log(e.ToString());
            config = null;
        }

        //デコード失敗した場合は、デフォルト設定にして警告
        if (config == null)
        {
            config = new TemplateConfig();
            menu.ShowDialogOKCancel(LanguageManager.config.jsonloaders.CORRUPT_CONFIG_HEAD, "" + jsonPath + LanguageManager.config.jsonloaders.CORRUPT_CONFIG_BODY, 3f, () => {
                //OK
                makeJSON();
            }, () => {
                //キャンセル
            });
        }
    }
コード例 #29
0
        public void GivenATemplateWithTwoGlobs_AndSomeMatchingVariablesInThePrompt_WhenGetFilesToMoveIsCalled_ThenTheResultWillOnlyContainTheVariablesWithAMatchingKey()
        {
            //arrange
            var expectedGlobOneVariable = new KeyValuePair <string, object>("globOneTest", "mystring");
            var expectedGlobTwoVariable = new KeyValuePair <string, object>("globTwoTest", 10);
            var prompts = new Dictionary <string, object>
            {
                { expectedGlobOneVariable.Key, expectedGlobOneVariable.Value },
                { expectedGlobTwoVariable.Key, expectedGlobTwoVariable.Value },
                { "noneTest", true }
            };

            var config = new TemplateConfig
            {
                Files = new List <TemplateFileConfig>
                {
                    new TemplateFileConfig
                    {
                        Glob      = "*.html",
                        Variables = new List <string> {
                            expectedGlobOneVariable.Key
                        }
                    },
                    new TemplateFileConfig
                    {
                        Glob      = "*.css",
                        Variables = new List <string> {
                            expectedGlobTwoVariable.Key
                        }
                    }
                }
            };

            //act
            var result = FileProcessor.GetFilesToMove(TempPath, config, prompts).ToList();

            //assert
            Assert.Equal(2, result.Count);

            Assert.True(result[0].VariablesToApply.ContainsKey(expectedGlobOneVariable.Key));
            Assert.Equal(
                expectedGlobOneVariable.Value,
                result[0].VariablesToApply[expectedGlobOneVariable.Key]);

            Assert.True(result[1].VariablesToApply.ContainsKey(expectedGlobTwoVariable.Key));
            Assert.Equal(
                expectedGlobTwoVariable.Value,
                result[1].VariablesToApply[expectedGlobTwoVariable.Key]);
        }
コード例 #30
0
 private void CheckTemplate(TemplateConfig template)
 {
     if (string.IsNullOrWhiteSpace(template.Template))
     {
         template.Template = File.ReadAllText(template.TemplatePath);
     }
     if (string.IsNullOrWhiteSpace(template.Code))
     {
         LuaTemplateParse parser = new LuaTemplateParse
         {
             Config = template
         };
         parser.Compile();
     }
 }