コード例 #1
0
        /// <summary>
        /// Returns the content of the interface
        /// </summary>
        /// <param name="argReader">Information fetched from the command line arguments</param>
        /// <param name="metadata">Metadata about the model</param>
        /// <returns>The content of the interface</returns>
        private string GetInterfaceContent(ArgReader argReader, ModelMetadata metadata)
        {
            var builder = new StringBuilder();

            builder
            .AppendNestedLine(0, "using System;")
            .AppendNestedLine(0, "using System.Collections.Generic;")
            .AppendNestedLine(0, "using System.Threading.Tasks;")
            .AppendNestedLine(0, $"using {metadata.Namespace};")
            .AppendLine()
            .AppendNestedLine(0, $"namespace {argReader.Namespace}")
            .AppendNestedLine(0, "{")
            .AppendNestedLine(1, $"public interface I{metadata.Name}Service")
            .AppendNestedLine(1, "{")
            .AppendNestedLine(2, $"Task<ResultModel<{metadata.Name}>> CreateAsync({metadata.Name} entity);")
            .AppendNestedLine(2, $"Task<bool> DeleteAsync({metadata.KeyProperty.TypeName} key);")
            .AppendNestedLine(2, $"Task<{metadata.Name}> GetAsync({metadata.KeyProperty.TypeName} key);")
            .AppendNestedLine(2, $"Task<List<{metadata.Name}>> GetAllAsync();")
            .AppendNestedLine(2, $"Task<PageModel<{metadata.Name}>> GetAllAsync(int page, int pageSize, string sortField, bool asc);");

            if (metadata.Properties.Values.Any(a => a is StringProperty))
            {
                builder
                .AppendNestedLine(2, $"Task<List<{metadata.Name}>> SearchAsync(string term);")
                .AppendNestedLine(2, $"Task<PageModel<{metadata.Name}>> SearchAsync(string term, int page, int pageSize, string sortField, bool asc);");
            }

            builder
            .AppendNestedLine(2, $"Task<ResultModel<{metadata.Name}>> UpdateAsync({metadata.Name} entity);")
            .AppendNestedLine(1, "}")
            .AppendNestedLine(0, "}");

            return(builder.ToString());
        }
コード例 #2
0
        /// <summary>
        /// Returns the content of the class implementation
        /// </summary>
        /// <param name="argReader">Information fetched from the command line arguments</param>
        /// <returns>The content of the class implementation</returns>
        private string GetClassContent(ArgReader argReader)
        {
            var builder = new StringBuilder();

            return(builder
                   .AppendNestedLine(0, "using System;")
                   .AppendNestedLine(0, "using System.Collections;")
                   .AppendNestedLine(0, "using System.Collections.Generic;")
                   .AppendNestedLine(0, "using System.Linq;")
                   .AppendNestedLine(0, "using System.Threading.Tasks;")
                   .AppendNestedLine(0, "using Microsoft.EntityFrameworkCore;")
                   .AppendLine()
                   .AppendNestedLine(0, $"namespace {argReader.Namespace}")
                   .AppendNestedLine(0, "{")
                   .AppendNestedLine(1, "public class PageModel<T> : IPageModel, IEnumerable<T>")
                   .AppendNestedLine(1, "{")
                   .AppendNestedLine(2, "public IEnumerable<T> Collection { get; private set; }")
                   .AppendNestedLine(2, "public int TotalItems { get; private set; }")
                   .AppendNestedLine(2, "public int TotalPages { get; private set; }")
                   .AppendNestedLine(2, "public int Page { get; private set; }")
                   .AppendNestedLine(2, "public int PageSize { get; private set; }")
                   .AppendNestedLine(2, "public string SortField { get; private set; }")
                   .AppendNestedLine(2, "public bool IsAscending { get; private set; }")
                   .AppendLine()
                   .AppendNestedLine(2, "public bool IsFirstPage => Page == 1;")
                   .AppendNestedLine(2, "public bool IsLastPage => Page == TotalPages;")
                   .AppendLine()
                   .AppendNestedLine(2, "private PageModel()")
                   .AppendNestedLine(2, "{")
                   .AppendNestedLine(2, "}")
                   .AppendLine()
                   .AppendNestedLine(2, "public static async Task<PageModel<T>> CreateAsync(IQueryable<T> query, int page, int pageSize, string sortField, bool asc)")
                   .AppendNestedLine(2, "{")
                   .AppendNestedLine(3, "var pageModel = new PageModel<T>();")
                   .AppendLine()
                   .AppendNestedLine(3, "pageModel.SortField = sortField;")
                   .AppendNestedLine(3, "pageModel.IsAscending = asc;")
                   .AppendNestedLine(3, "pageModel.PageSize = pageSize;")
                   .AppendNestedLine(3, "pageModel.TotalItems = query.Count();")
                   .AppendNestedLine(3, "pageModel.TotalPages = (int)Math.Ceiling(pageModel.TotalItems / (double)pageModel.PageSize);")
                   .AppendNestedLine(3, "pageModel.Page = Math.Max(1, page);")
                   .AppendNestedLine(3, "pageModel.Page = Math.Min(pageModel.Page, pageModel.TotalPages);")
                   .AppendNestedLine(3, "pageModel.Collection = await query.Skip((pageModel.Page - 1) * pageModel.PageSize).Take(pageModel.PageSize).ToListAsync();")
                   .AppendLine()
                   .AppendNestedLine(3, "return pageModel;")
                   .AppendNestedLine(2, "}")
                   .AppendLine()
                   .AppendNestedLine(2, "public IEnumerator<T> GetEnumerator()")
                   .AppendNestedLine(2, "{")
                   .AppendNestedLine(3, "return Collection.GetEnumerator();")
                   .AppendNestedLine(2, "}")
                   .AppendLine()
                   .AppendNestedLine(2, "IEnumerator IEnumerable.GetEnumerator()")
                   .AppendNestedLine(2, "{")
                   .AppendNestedLine(3, "return Collection.GetEnumerator();")
                   .AppendNestedLine(2, "}")
                   .AppendNestedLine(1, "}")
                   .AppendNestedLine(0, "}")
                   .ToString());
        }
コード例 #3
0
        static LispReader()
        {
            _macros['"']  = new StringReader();
            _macros[';']  = new CommentReader();
            _macros['\''] = new WrappingReader(QUOTE);
            _macros['@']  = new WrappingReader(DEREF);//new DerefReader();
            _macros['^']  = new WrappingReader(META);
            _macros['`']  = new SyntaxQuoteReader();
            _macros['~']  = new UnquoteReader();
            _macros['(']  = new ListReader();
            _macros[')']  = new UnmatchedDelimiterReader();
            _macros['[']  = new VectorReader();
            _macros[']']  = new UnmatchedDelimiterReader();
            _macros['{']  = new MapReader();
            _macros['}']  = new UnmatchedDelimiterReader();
            ////	macros['|'] = new ArgVectorReader();
            _macros['\\'] = new CharacterReader();
            _macros['%']  = new ArgReader();
            _macros['#']  = new DispatchReader();


            _dispatchMacros['^']  = new MetaReader();
            _dispatchMacros['\''] = new VarReader();
            _dispatchMacros['"']  = new RegexReader();
            _dispatchMacros['(']  = new FnReader();
            _dispatchMacros['{']  = new SetReader();
            _dispatchMacros['=']  = new EvalReader();
            _dispatchMacros['!']  = new CommentReader();
            _dispatchMacros['<']  = new UnreadableReader();
            _dispatchMacros['_']  = new DiscardReader();
        }
コード例 #4
0
        /// <summary>
        /// Generates a page model
        /// </summary>
        /// <param name="argReader">Information fetched from the command line arguments</param>
        public void Generate(ArgReader argReader)
        {
            string interfaceContent = GetInterfaceContent(argReader);

            FileHelper.SaveToOutput(argReader.OutputFolder, "IPageModel.cs", interfaceContent);

            string classContent = GetClassContent(argReader);

            FileHelper.SaveToOutput(argReader.OutputFolder, "PageModel.cs", classContent);
        }
コード例 #5
0
        public void TestGenerator()
        {
            var args      = new string[] { "resultmodel", "-ns", "MinionSuite.Tests.Templates" };
            var argReader = new ArgReader(args);

            GeneratorFactory.GetGenerator(argReader).Generate(argReader);

            Assert.True(File.Exists("ResultModel.cs"));

            AssertHelper.AssertEqualFile("Templates/ResultModel/ResultModel.cs", "ResultModel.cs");
        }
コード例 #6
0
 /// <summary>
 /// Returns the appropriate generator
 /// </summary>
 /// <param name="argReader">Information fetched from the command line arguments</param>
 /// <returns>The generator</returns>
 public static IGenerator GetGenerator(ArgReader argReader)
 {
     return(argReader.Generator switch
     {
         "servicegen" => new ServiceGenerator(),
         "servicegen:test" => new ServiceTestGenerator(),
         "pagemodel" => new PageModelGenerator(),
         "resultmodel" => new ResultModelGenerator(),
         "mvccontroller" => new MvcControllerGenerator(),
         "mvccontroller:test" => new MvcControllerTestGenerator(),
         "apicontroller" => new ApiControllerGenerator(),
         _ => throw new ArgumentException($"{argReader.Generator} is an invalid generator."),
     });
コード例 #7
0
        /// <summary> Parses the individual arguments from the given input string. </summary>
        public static string[] Parse(string rawtext)
        {
            List <String> list = new List <string>();

            if (rawtext == null)
            {
                throw new ArgumentNullException("rawtext");
            }
            ArgReader characters = new ArgReader(rawtext.Trim());

            while (!characters.IsEOF)
            {
                if (characters.IsWhiteSpace)
                {
                    characters.MoveNext();
                    continue;
                }

                StringBuilder sb = new StringBuilder();

                if (characters.IsQuote)
                {                //quoted string
                    while (characters.MoveNext())
                    {
                        if (characters.IsQuote)
                        {
                            if (!characters.MoveNext() || characters.IsWhiteSpace)
                            {
                                break;
                            }
                        }
                        sb.Append(characters.Current);
                    }
                }
                else
                {
                    sb.Append(characters.Current);
                    while (characters.MoveNext())
                    {
                        if (characters.IsWhiteSpace)
                        {
                            break;
                        }
                        sb.Append(characters.Current);
                    }
                }

                list.Add(sb.ToString());
            }
            return(list.ToArray());
        }
コード例 #8
0
        /// <summary>
        /// Generates tests for the MVC controller of a model
        /// </summary>
        /// <param name="argReader">Information fetched from the command line arguments</param>
        public void Generate(ArgReader argReader)
        {
            var metadata = new ModelMetadata(argReader.ModelPath);

            if (argReader.GenerateWebApplicationFactory)
            {
                var factoryContent = GetWebApplicationFactoryContent(argReader, metadata);
                FileHelper.SaveToOutput(argReader.OutputFolder, "CustomWebApplicationFactory.cs", factoryContent);
            }

            var testClassContent = GetTestContent(argReader, metadata);

            FileHelper.SaveToOutput(argReader.OutputFolder, $"{metadata.PluralName}ControllerTests.cs", testClassContent);
        }
コード例 #9
0
        public void TestGenerator()
        {
            var args = new string[]
            {
                "mvccontroller", "-ns", "MinionSuite.Tests.Templates", "-m", "./Models/Post.cs"
            };
            var argReader = new ArgReader(args);

            GeneratorFactory.GetGenerator(argReader).Generate(argReader);

            Assert.True(File.Exists("PostsController.cs"));

            AssertHelper.AssertEqualFile("Templates/MvcController/PostsController.cs", "PostsController.cs");
        }
コード例 #10
0
        public void TestGenerator()
        {
            var args = new string[]
            {
                "servicegen:test", "-ns", "MinionSuite.Tests.Templates",
                "-m", "./Models/Post.cs", "-db", "ApplicationContext"
            };
            var argReader = new ArgReader(args);

            GeneratorFactory.GetGenerator(argReader).Generate(argReader);

            Assert.True(File.Exists("PostServiceTests.cs"));

            AssertHelper.AssertEqualFile("Templates/ServiceTest/PostServiceTests.cs", "PostServiceTests.cs");
        }
コード例 #11
0
        /// <summary>
        /// Generates a result model
        /// </summary>
        /// <param name="argReader">Information fetched from the command line arguments</param>
        public void Generate(ArgReader argReader)
        {
            var builder = new StringBuilder();

            builder
            .AppendNestedLine(0, "using System;")
            .AppendNestedLine(0, "using System.Collections.Generic;")
            .AppendNestedLine(0, "using System.Linq;")
            .AppendLine()
            .AppendNestedLine(0, $"namespace {argReader.Namespace}")
            .AppendNestedLine(0, "{")
            .AppendNestedLine(1, "public class ResultModel<T>")
            .AppendNestedLine(1, "{")
            .AppendNestedLine(2, "public T Result { get; private set; }")
            .AppendNestedLine(2, "public IEnumerable<string> Errors { get; private set; }")
            .AppendLine()
            .AppendNestedLine(2, "public bool IsSuccess => !Errors.Any();")
            .AppendLine()
            .AppendNestedLine(2, "public ResultModel(T result, IEnumerable<string> errors)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "Result = result;")
            .AppendNestedLine(3, "Errors = errors;")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "public ResultModel(T result)")
            .AppendNestedLine(3, ": this(result, new List<string>())")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "public ResultModel(IEnumerable<string> errors)")
            .AppendNestedLine(3, ": this(default, errors)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "public ResultModel(string error)")
            .AppendNestedLine(3, ": this(default, new List<string>() { error })")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(2, "}")
            .AppendNestedLine(1, "}")
            .AppendNestedLine(0, "}");

            FileHelper.SaveToOutput(argReader.OutputFolder, "ResultModel.cs", builder.ToString());
        }
コード例 #12
0
        /// <summary>
        /// Generates the service layer for a model
        /// </summary>
        /// <param name="argReader">Information fetched from the command line arguments</param>
        public void Generate(ArgReader argReader)
        {
            if (argReader.GeneratePageModel)
            {
                new PageModelGenerator().Generate(argReader);
            }
            if (argReader.GenerateResultModel)
            {
                new ResultModelGenerator().Generate(argReader);
            }

            var metadata = new ModelMetadata(argReader.ModelPath);

            string interfaceContent = GetInterfaceContent(argReader, metadata);

            FileHelper.SaveToOutput(argReader.OutputFolder, $"I{metadata.Name}Service.cs", interfaceContent);

            string classContent = GetClassContent(argReader, metadata);

            FileHelper.SaveToOutput(argReader.OutputFolder, $"{metadata.Name}Service.cs", classContent);
        }
コード例 #13
0
        private void init()
        {
            var lv = (args.Length == 0) ? null : util.getRegGroup(args[0], "(lv\\d+(,\\d+)*)");

            util.setLog(config, lv);

            if (args.Length > 0)
            {
                var ar = new ArgReader(args, config, this);
                ar.read();
                if (ar.isConcatMode)
                {
                    urlText.Text = string.Join("|", args);
                    rec.rec();
                }
                else
                {
                    if (ar.lvid != null)
                    {
                        urlText.Text = ar.lvid;
                    }
                    config.argConfig = ar.argConfig;
                    rec.argTsConfig  = ar.tsConfig;
                    rec.isRecording  = true;
//					rec.setArgConfig(args);
                    if (ar.isPlayMode)
                    {
                        player.play();
                    }
                    else
                    {
                        rec.rec();
                    }
                }
                if (bool.Parse(config.get("Isminimized")))
                {
                    this.WindowState = FormWindowState.Minimized;
                }
            }
        }
コード例 #14
0
        /// <summary>
        /// Returns the content of the web application factory
        /// </summary>
        /// <param name="argReader">Information fetched from the command line arguments</param>
        /// <param name="metadata">Metadata about the model</param>
        /// <returns>The content of the web application factory</returns>
        private string GetWebApplicationFactoryContent(ArgReader argReader, ModelMetadata metadata)
        {
            var builder = new StringBuilder();

            builder
            .AppendNestedLine(0, "using System;")
            .AppendNestedLine(0, "using Microsoft.AspNetCore.Hosting;")
            .AppendNestedLine(0, "using Microsoft.AspNetCore.Mvc.Testing;")
            .AppendLine()
            .AppendNestedLine(0, $"namespace {argReader.Namespace}")
            .AppendNestedLine(0, "{")
            .AppendNestedLine(1, "public class CustomWebApplicationFactory : WebApplicationFactory<Startup>")
            .AppendNestedLine(1, "{")
            .AppendNestedLine(2, "protected override void ConfigureWebHost(IWebHostBuilder builder)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "builder.UseEnvironment(\"Test\");")
            .AppendNestedLine(2, "}")
            .AppendNestedLine(1, "}")
            .AppendNestedLine(0, "}");

            return(builder.ToString());
        }
コード例 #15
0
        /// <summary>
        /// Returns the content of the interface
        /// </summary>
        /// <param name="argReader">Information fetched from the command line arguments</param>
        /// <returns>The content of the interface</returns>
        private string GetInterfaceContent(ArgReader argReader)
        {
            var builder = new StringBuilder();

            return(builder
                   .AppendNestedLine(0, "using System;")
                   .AppendLine()
                   .AppendNestedLine(0, $"namespace {argReader.Namespace}")
                   .AppendNestedLine(0, "{")
                   .AppendNestedLine(1, "public interface IPageModel")
                   .AppendNestedLine(1, "{")
                   .AppendNestedLine(2, "int TotalItems { get; }")
                   .AppendNestedLine(2, "int TotalPages { get; }")
                   .AppendNestedLine(2, "int Page { get; }")
                   .AppendNestedLine(2, "int PageSize { get; }")
                   .AppendNestedLine(2, "bool IsFirstPage { get; }")
                   .AppendNestedLine(2, "bool IsLastPage { get; }")
                   .AppendNestedLine(2, "string SortField { get; }")
                   .AppendNestedLine(2, "bool IsAscending { get; }")
                   .AppendNestedLine(1, "}")
                   .AppendNestedLine(0, "}")
                   .ToString());
        }
コード例 #16
0
        private void init()
        {
            if (args.Length > 0)
            {
                var ar = new ArgReader(args, config, this);
                ar.read();
                if (ar.isConcatMode)
                {
                    urlText.Text = string.Join("|", args);
                    rec.rec(false);
                }
                else
                {
                    if (ar.lvid != null)
                    {
                        urlText.Text = ar.lvid;
                    }
                    config.argConfig = ar.argConfig;
                    rec.argTsConfig  = ar.tsConfig;
                    rec.isRecording  = true;
//					rec.setArgConfig(args);
                    if (ar.isPlayMode)
                    {
                        player.play();
                    }
                    else
                    {
                        rec.rec(false);
                    }
                }
                if (bool.Parse(config.get("Isminimized")))
                {
                    this.WindowState = FormWindowState.Minimized;
                }
            }
        }
コード例 #17
0
ファイル: LispReader.cs プロジェクト: jlomax/clojure-clr
        static LispReader()
        {
            _macros['"'] = new StringReader();
            _macros[';'] = new CommentReader();
            _macros['\''] = new WrappingReader(QUOTE);
            _macros['@'] = new WrappingReader(DEREF);//new DerefReader();
            _macros['^'] = new WrappingReader(META);
            _macros['`'] = new SyntaxQuoteReader();
            _macros['~'] = new UnquoteReader();
            _macros['('] = new ListReader();
            _macros[')'] = new UnmatchedDelimiterReader();
            _macros['['] = new VectorReader();
            _macros[']'] = new UnmatchedDelimiterReader();
            _macros['{'] = new MapReader();
            _macros['}'] = new UnmatchedDelimiterReader();
            ////	macros['|'] = new ArgVectorReader();
            _macros['\\'] = new CharacterReader();
            _macros['%'] = new ArgReader();
            _macros['#'] = new DispatchReader();

            _dispatchMacros['^'] = new MetaReader();
            _dispatchMacros['\''] = new VarReader();
            _dispatchMacros['"'] = new RegexReader();
            _dispatchMacros['('] = new FnReader();
            _dispatchMacros['{'] = new SetReader();
            _dispatchMacros['='] = new EvalReader();
            _dispatchMacros['!'] = new CommentReader();
            _dispatchMacros['<'] = new UnreadableReader();
            _dispatchMacros['_'] = new DiscardReader();
        }
コード例 #18
0
        /// <summary>
        /// Generates tests for the service layer of a model
        /// </summary>
        /// <param name="argReader">Information fetched from the command line arguments</param>
        public void Generate(ArgReader argReader)
        {
            var metadata = new ModelMetadata(argReader.ModelPath);
            var builder  = new StringBuilder();

            string sequenceVariable = "_entitySequence";
            var    filledProperties = metadata.Properties
                                      .Where(w => w.Key != metadata.KeyName && w.Key != "CreatedAt" && w.Key != "UpdatedAt");
            var firstFilledProperty    = filledProperties.First();
            var filledStringProperties = filledProperties.Where(w => w.Value is StringProperty);

            builder
            .AppendNestedLine(0, "using System;")
            .AppendNestedLine(0, "using System.Linq;")
            .AppendNestedLine(0, "using System.Threading.Tasks;")
            .AppendNestedLine(0, "using Microsoft.EntityFrameworkCore;")
            .AppendNestedLine(0, $"using {metadata.Namespace};")
            .AppendNestedLine(0, "using Xunit;")
            .AppendLine()
            .AppendNestedLine(0, $"namespace {argReader.Namespace}")
            .AppendNestedLine(0, "{")
            .AppendNestedLine(1, $"public class {metadata.Name}ServiceTests : IDisposable")
            .AppendNestedLine(1, "{")
            .AppendNestedLine(2, $"private int {sequenceVariable} = 1;")
            .AppendLine()
            .AppendNestedLine(2, $"private {argReader.DbContext} _context;")
            .AppendNestedLine(2, $"private {metadata.Name}Service _service;")
            .AppendLine()
            .AppendNestedLine(2, $"public {metadata.Name}ServiceTests()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"var options = new DbContextOptionsBuilder<{argReader.DbContext}>()")
            .AppendNestedLine(4, $".UseInMemoryDatabase(\"{metadata.Name}Service\")")
            .AppendNestedLine(4, ".Options;")
            .AppendNestedLine(3, $"_context = new {argReader.DbContext}(options);")
            .AppendNestedLine(3, $"_service = new {metadata.Name}Service(_context);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "public void Dispose()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "_context.Database.EnsureDeleted();")
            .AppendNestedLine(3, "_context.Dispose();")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task TestCreateAndReturnEntities()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await CreateEntity();")
            .AppendNestedLine(3, "var entities = await _service.GetAllAsync();")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Single(entities);");
            foreach (var property in filledProperties)
            {
                builder
                .AppendNestedLine(3, $"Assert.Equal(entity.{property.Key}, entities[0].{property.Key});");
            }
            builder
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task TestUpdateEntity()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await CreateEntity();")
            .AppendLine()
            .AppendNestedLine(3, $"entity.{firstFilledProperty.Key} = {firstFilledProperty.Value.SequenceValue(sequenceVariable)};")
            .AppendNestedLine(3, "await _service.UpdateAsync(entity);")
            .AppendLine()
            .AppendNestedLine(3, $"entity = await _service.GetAsync(entity.{metadata.KeyName});")
            .AppendLine()
            .AppendNestedLine(3, "Assert.NotNull(entity);")
            .AppendNestedLine(3, $"Assert.Equal({firstFilledProperty.Value.SequenceValue(sequenceVariable)}, entity.{firstFilledProperty.Key});")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task TestUpdateNotExistingEntity()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"var entity = new {metadata.Name}()")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, $"{metadata.KeyName} = {metadata.KeyProperty.SequenceValue(sequenceVariable)}")
            .AppendNestedLine(3, "};")
            .AppendLine()
            .AppendNestedLine(3, "var result = await _service.UpdateAsync(entity);")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Null(result);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task TestDeleteEntity()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await CreateEntity();")
            .AppendNestedLine(3, $"await _service.DeleteAsync(entity.{metadata.KeyName});")
            .AppendLine()
            .AppendNestedLine(3, $"entity = await _service.GetAsync(entity.{metadata.KeyName});")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Null(entity);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task TestPagingAndSorting()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "await CreateEntity();")
            .AppendNestedLine(3, "var entity = await CreateEntity();")
            .AppendLine()
            .AppendNestedLine(3, $"var page = await _service.GetAllAsync(1, 1, \"{firstFilledProperty.Key}\", false);")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Equal(2, page.TotalItems);")
            .AppendNestedLine(3, "Assert.Equal(1, page.Page);")
            .AppendNestedLine(3, "Assert.Equal(1, page.PageSize);")
            .AppendNestedLine(3, $"Assert.Equal(\"{firstFilledProperty.Key}\", page.SortField);")
            .AppendNestedLine(3, "Assert.False(page.IsAscending);")
            .AppendNestedLine(3, "Assert.Equal(entity.Id, page.First().Id);")
            .AppendNestedLine(2, "}");
            if (filledStringProperties.Any())
            {
                builder
                .AppendLine()
                .AppendNestedLine(2, "[Fact]")
                .AppendNestedLine(2, "public async Task TestSearch()")
                .AppendNestedLine(2, "{")
                .AppendNestedLine(3, "await CreateEntity();")
                .AppendNestedLine(3, "var entity = await CreateEntity();")
                .AppendLine()
                .AppendNestedLine(3, $"var entities = await _service.SearchAsync(entity.{filledStringProperties.First().Key});")
                .AppendLine()
                .AppendNestedLine(3, "Assert.Single(entities);")
                .AppendNestedLine(3, "Assert.Equal(entity.Id, entities.First().Id);")
                .AppendNestedLine(2, "}")
                .AppendLine()
                .AppendNestedLine(2, "[Fact]")
                .AppendNestedLine(2, "public async Task TestSearchWithPagingAndSorting()")
                .AppendNestedLine(2, "{")
                .AppendNestedLine(3, "await CreateEntity();")
                .AppendNestedLine(3, "var entity = await CreateEntity();")
                .AppendLine()
                .AppendNestedLine(3, $"var page = await _service.SearchAsync(entity.{filledStringProperties.First().Key}, 1, 1, "
                                  + $"\"{metadata.KeyName}\", false);")
                .AppendLine()
                .AppendNestedLine(3, "Assert.Equal(1, page.TotalItems);")
                .AppendNestedLine(3, "Assert.Equal(1, page.Page);")
                .AppendNestedLine(3, "Assert.Equal(1, page.PageSize);")
                .AppendNestedLine(3, $"Assert.Equal(\"{metadata.KeyName}\", page.SortField);")
                .AppendNestedLine(3, "Assert.False(page.IsAscending);")
                .AppendNestedLine(3, "Assert.Equal(entity.Id, page.First().Id);")
                .AppendNestedLine(2, "}");
            }
            builder
            .AppendLine()
            .AppendNestedLine(2, $"private async Task<{metadata.Name}> CreateEntity()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"var entity = new {metadata.Name}()")
            .AppendNestedLine(3, "{");
            foreach (var property in filledProperties)
            {
                builder
                .AppendNestedLine(4, $"{property.Key} = {property.Value.SequenceValue(sequenceVariable)},");
            }
            builder
            .AppendNestedLine(3, "};")
            .AppendLine()
            .AppendNestedLine(3, "var result = await _service.CreateAsync(entity);")
            .AppendLine()
            .AppendNestedLine(3, $"{sequenceVariable}++;")
            .AppendLine()
            .AppendNestedLine(3, "return result.Result;")
            .AppendNestedLine(2, "}")
            .AppendNestedLine(1, "}")
            .AppendNestedLine(0, "}");

            FileHelper.SaveToOutput(argReader.OutputFolder, $"{metadata.Name}ServiceTests.cs", builder.ToString());
        }
コード例 #19
0
        /// <summary>
        /// Returns the content of the test class
        /// </summary>
        /// <param name="argReader">Information fetched from the command line arguments</param>
        /// <param name="metadata">Metadata about the model</param>
        /// <returns>The content of the test class</returns>
        private string GetTestContent(ArgReader argReader, ModelMetadata metadata)
        {
            var builder = new StringBuilder();

            var stringProperties = metadata.Properties.Values.Where(w => w is StringProperty);
            var filledProperties = metadata.Properties.Where(w => w.Key != metadata.KeyName && w.Key != "CreatedAt" && w.Key != "UpdatedAt");

            builder
            .AppendNestedLine(0, "using System;")
            .AppendNestedLine(0, "using System.Collections.Generic;")
            .AppendNestedLine(0, "using System.Net;")
            .AppendNestedLine(0, "using System.Net.Http;")
            .AppendNestedLine(0, "using System.Text.RegularExpressions;")
            .AppendNestedLine(0, "using System.Threading;")
            .AppendNestedLine(0, "using System.Threading.Tasks;")
            .AppendNestedLine(0, "using System.Web;")
            .AppendNestedLine(0, "using Microsoft.AspNetCore.Mvc.Testing;")
            .AppendNestedLine(0, "using Microsoft.Extensions.DependencyInjection;")
            .AppendNestedLine(0, "using Newtonsoft.Json;")
            .AppendNestedLine(0, "using Xunit;")
            .AppendLine()
            .AppendNestedLine(0, $"namespace {argReader.Namespace}")
            .AppendNestedLine(0, "{")
            .AppendNestedLine(1, $"public class {metadata.PluralName}ControllerTests : IClassFixture<CustomWebApplicationFactory>")
            .AppendNestedLine(1, "{")
            .AppendNestedLine(2, "private readonly CustomWebApplicationFactory _factory;")
            .AppendNestedLine(2, "private readonly HttpClient _client;")
            .AppendNestedLine(2, "private readonly IServiceScope _scope;")
            .AppendNestedLine(2, $"private readonly I{metadata.Name}Service _service;")
            .AppendLine()
            .AppendNestedLine(2, $"public {metadata.PluralName}ControllerTests(CustomWebApplicationFactory factory)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "_factory = factory;")
            .AppendNestedLine(3, "_client = _factory.CreateClient(new WebApplicationFactoryClientOptions")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "AllowAutoRedirect = false")
            .AppendNestedLine(3, "});")
            .AppendLine()
            .AppendNestedLine(3, "_scope = _factory.Services.CreateScope();")
            .AppendNestedLine(3, $"_service = _scope.ServiceProvider.GetRequiredService<I{metadata.Name}Service>();")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task Index_Get_Successful()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await BuildEntity(true);")
            .AppendLine()
            .AppendNestedLine(3, $"var response = await _client.GetAsync($\"/{metadata.PluralName}?asc=false\");")
            .AppendNestedLine(3, "var content = await response.Content.ReadAsStringAsync();")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Equal(HttpStatusCode.OK, response.StatusCode);")
            .AppendNestedLine(3, $"Assert.Contains($\"{metadata.PluralName}/Details/{{entity.{metadata.KeyName}}}\", content);")
            .AppendNestedLine(2, "}")
            .AppendLine();

            if (stringProperties.Any())
            {
                builder
                .AppendNestedLine(2, "[Fact]")
                .AppendNestedLine(2, "public async Task Index_Get_SearchSuccessful()")
                .AppendNestedLine(2, "{")
                .AppendNestedLine(3, "var firstEntity = await BuildEntity(true);")
                .AppendNestedLine(3, "var secondEntity = await BuildEntity(true);")
                .AppendLine()
                .AppendNestedLine(3, $"var response = await _client.GetAsync($\"/{metadata.PluralName}?term={{HttpUtility.UrlEncode(firstEntity.{stringProperties.First().Name})}}\");")
                .AppendNestedLine(3, "var content = await response.Content.ReadAsStringAsync();")
                .AppendLine()
                .AppendNestedLine(3, "Assert.Equal(HttpStatusCode.OK, response.StatusCode);")
                .AppendNestedLine(3, $"Assert.Contains($\"{metadata.PluralName}/Details/{{firstEntity.{metadata.KeyName}}}\", content);")
                .AppendNestedLine(3, $"Assert.DoesNotContain($\"{metadata.PluralName}/Details/{{secondEntity.{metadata.KeyName}}}\", content);")
                .AppendNestedLine(2, "}")
                .AppendLine();
            }

            builder
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task Details_Get_NotFound()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"var response = await _client.GetAsync(\"/{metadata.PluralName}/Details/0\");")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task Details_Get_Successful()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await BuildEntity(true);")
            .AppendNestedLine(3, $"var response = await _client.GetAsync($\"/{metadata.PluralName}/Details/{{entity.{metadata.KeyName}}}\");")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Equal(HttpStatusCode.OK, response.StatusCode);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task Create_Get_Successful()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"var response = await _client.GetAsync(\"/{metadata.PluralName}/Create\");")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Equal(HttpStatusCode.OK, response.StatusCode);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task Create_Post_Successful()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"var verificationToken = await GetVerificationTokenFromPage(\"/{metadata.PluralName}/Create\");")
            .AppendLine()
            .AppendNestedLine(3, "var entity = await BuildEntity(false);")
            .AppendNestedLine(3, "var dict = EntityToDictionary(entity);")
            .AppendNestedLine(3, "dict[\"__RequestVerificationToken\"] = verificationToken;")
            .AppendNestedLine(3, "var formContent = new FormUrlEncodedContent(dict);")
            .AppendLine()
            .AppendNestedLine(3, $"var response = await _client.PostAsync(\"/{metadata.PluralName}/Create\", formContent);")
            .AppendNestedLine(3, "var createdEntity = await FetchEntityFromDetailsUrl(response.Headers.Location.ToString());")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);")
            .AppendNestedLine(3, "Assert.NotNull(createdEntity);");

            foreach (var property in filledProperties)
            {
                builder.AppendNestedLine(3, $"Assert.Equal(entity.{property.Key}, createdEntity.{property.Key});");
            }

            builder
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task Edit_Get_NotFound()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"var response = await _client.GetAsync(\"/{metadata.PluralName}/Edit/0\");")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task Edit_Get_Successful()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await BuildEntity(true);")
            .AppendNestedLine(3, $"var response = await _client.GetAsync($\"/{metadata.PluralName}/Edit/{{entity.{metadata.KeyName}}}\");")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Equal(HttpStatusCode.OK, response.StatusCode);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task Edit_Post_Successful()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await BuildEntity(true);")
            .AppendNestedLine(3, $"var verificationToken = await GetVerificationTokenFromPage($\"/{metadata.PluralName}/Edit/{{entity.{metadata.KeyName}}}\");")
            .AppendLine()
            .AppendNestedLine(3, "var dict = EntityToDictionary(await BuildEntity(false));")
            .AppendNestedLine(3, $"dict[\"{metadata.KeyName}\"] = entity.{metadata.KeyName}.ToString();")
            .AppendNestedLine(3, "dict[\"__RequestVerificationToken\"] = verificationToken;")
            .AppendNestedLine(3, "var formContent = new FormUrlEncodedContent(dict);")
            .AppendLine()
            .AppendNestedLine(3, $"var response = await _client.PostAsync(\"/{metadata.PluralName}/Edit\", formContent);")
            .AppendNestedLine(3, $"var updatedEntity = await _service.GetAsync(entity.{metadata.KeyName});")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);")
            .AppendNestedLine(3, "Assert.NotNull(updatedEntity);");
            foreach (var property in filledProperties)
            {
                builder.AppendNestedLine(3, $"Assert.Equal(entity.{property.Key}, updatedEntity.{property.Key});");
            }
            builder
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task Delete_Get_NotFound()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"var response = await _client.GetAsync(\"/{metadata.PluralName}/Delete/0\");")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task Delete_Get_Successful()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await BuildEntity(true);")
            .AppendNestedLine(3, $"var response = await _client.GetAsync($\"/{metadata.PluralName}/Delete/{{entity.{metadata.KeyName}}}\");")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Equal(HttpStatusCode.OK, response.StatusCode);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[Fact]")
            .AppendNestedLine(2, "public async Task Delete_Post_Successful()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await BuildEntity(true);")
            .AppendNestedLine(3, $"var verificationToken = await GetVerificationTokenFromPage($\"/{metadata.PluralName}/Delete/{{entity.{metadata.KeyName}}}\");")
            .AppendLine()
            .AppendNestedLine(3, "var dict = new Dictionary<string, string>")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, $"[\"{metadata.KeyName}\"] = entity.{metadata.KeyName}.ToString(),")
            .AppendNestedLine(4, "[\"__RequestVerificationToken\"] = verificationToken")
            .AppendNestedLine(3, "};")
            .AppendNestedLine(3, "var formContent = new FormUrlEncodedContent(dict);")
            .AppendLine()
            .AppendNestedLine(3, $"var response = await _client.PostAsync(\"/{metadata.PluralName}/Delete\", formContent);")
            .AppendNestedLine(3, $"entity = await _service.GetAsync(entity.{metadata.KeyName});")
            .AppendLine()
            .AppendNestedLine(3, "Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);")
            .AppendNestedLine(3, "Assert.Null(entity);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, $"private async Task<{metadata.Name}> BuildEntity(bool save)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"var entity = new {metadata.Name}()")
            .AppendNestedLine(3, "{");

            foreach (var property in filledProperties)
            {
                builder.AppendNestedLine(4, $"{property.Key} = {property.Value.DefaultValue()},");
            }

            builder
            .AppendNestedLine(3, "};")
            .AppendLine()
            .AppendNestedLine(3, "if (save)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "var result = await _service.CreateAsync(entity);")
            .AppendNestedLine(4, "return result.Result;")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, "return entity;")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, $"private Dictionary<string, string> EntityToDictionary({metadata.Name} entity)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var jsonContent = JsonConvert.SerializeObject(entity);")
            .AppendNestedLine(3, "return JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonContent);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "private async Task<string> GetVerificationTokenFromPage(string pageUrl)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var response = await _client.GetAsync(pageUrl);")
            .AppendNestedLine(3, "var content = await response.Content.ReadAsStringAsync();")
            .AppendNestedLine(3, "var verificationTokenMatch = Regex.Match(content, \"name=\\\"__RequestVerificationToken\\\"(.*?)value=\\\"(.+?)\\\"\");")
            .AppendLine()
            .AppendNestedLine(3, "Assert.True(verificationTokenMatch.Success);")
            .AppendLine()
            .AppendNestedLine(3, "return verificationTokenMatch.Groups[2].Value;")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, $"private async Task<{metadata.Name}> FetchEntityFromDetailsUrl(string url)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"var match = Regex.Match(url, \"/{metadata.PluralName}/Details/(.+)\");")
            .AppendNestedLine(3, "if (!match.Success)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "return null;")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, "var key = int.Parse(match.Groups[1].Value);")
            .AppendNestedLine(3, "return await _service.GetAsync(key);")
            .AppendNestedLine(2, "}")
            .AppendNestedLine(1, "}")
            .AppendNestedLine(0, "}");

            return(builder.ToString());
        }
コード例 #20
0
        /// <summary>
        /// Returns the content of the class implementation
        /// </summary>
        /// <param name="argReader">Information fetched from the command line arguments</param>
        /// <param name="metadata">Metadata about the model</param>
        /// <returns>The content of the class implementation</returns>
        private string GetClassContent(ArgReader argReader, ModelMetadata metadata)
        {
            var builder = new StringBuilder();

            string searchQuery = string.Join(" || ", metadata.Properties.Values
                                             .Where(w => w is StringProperty)
                                             .Select(s => $"w.{s.Name}.Contains(term)"));

            builder
            .AppendNestedLine(0, "using System;")
            .AppendNestedLine(0, "using System.Collections.Generic;")
            .AppendNestedLine(0, "using System.Linq;")
            .AppendNestedLine(0, "using System.Threading.Tasks;")
            .AppendNestedLine(0, "using Microsoft.EntityFrameworkCore;")
            .AppendNestedLine(0, $"using {metadata.Namespace};")
            .AppendLine()
            .AppendNestedLine(0, $"namespace {argReader.Namespace}")
            .AppendNestedLine(0, "{")
            .AppendNestedLine(1, $"public class {metadata.Name}Service : I{metadata.Name}Service")
            .AppendNestedLine(1, "{")
            .AppendNestedLine(2, $"private readonly {argReader.DbContext} _context;")
            .AppendLine()
            .AppendNestedLine(2, $"public {metadata.Name}Service({argReader.DbContext} context)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "_context = context;")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, $"public virtual async Task<ResultModel<{metadata.Name}>> CreateAsync({metadata.Name} model)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"var newEntity = new {metadata.Name}();")
            .AppendLine();

            foreach (var property in metadata.Properties.Where(w => w.Key != metadata.KeyName && w.Key != "CreatedAt" && w.Key != "UpdatedAt"))
            {
                builder.AppendNestedLine(3, $"newEntity.{property.Key} = model.{property.Key};");
            }
            if (metadata.Properties.ContainsKey("CreatedAt"))
            {
                builder.AppendNestedLine(3, "newEntity.CreatedAt = DateTime.UtcNow;");
            }
            if (metadata.Properties.ContainsKey("UpdatedAt"))
            {
                builder.AppendNestedLine(3, "newEntity.UpdatedAt = DateTime.UtcNow;");
            }

            builder
            .AppendLine()
            .AppendNestedLine(3, $"_context.{metadata.PluralName}.Add(newEntity);")
            .AppendNestedLine(3, "await _context.SaveChangesAsync();")
            .AppendLine()
            .AppendNestedLine(3, $"return new ResultModel<{metadata.Name}>(newEntity);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, $"public virtual async Task<bool> DeleteAsync({metadata.KeyProperty.TypeName} key)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await GetAsync(key);")
            .AppendNestedLine(3, "if (entity == null)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "return false;")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, $"_context.{metadata.PluralName}.Remove(entity);")
            .AppendNestedLine(3, "await _context.SaveChangesAsync();")
            .AppendLine()
            .AppendNestedLine(3, "return true;")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, $"public virtual Task<{metadata.Name}> GetAsync({metadata.KeyProperty.TypeName} key)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"return _context.{metadata.PluralName}.FirstOrDefaultAsync(f => f.{metadata.KeyName} == key);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, $"public virtual Task<List<{metadata.Name}>> GetAllAsync()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"return _context.{metadata.PluralName}.AsNoTracking().ToListAsync();")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, $"public virtual Task<PageModel<{metadata.Name}>> GetAllAsync(int page, int pageSize, string sortField, bool asc)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"var query = _context.{metadata.PluralName}.AsNoTracking();")
            .AppendNestedLine(3, "query = GetSortedQuery(query, sortField, asc);")
            .AppendLine()
            .AppendNestedLine(3, $"return PageModel<{metadata.Name}>.CreateAsync(query, page, pageSize, sortField, asc);")
            .AppendNestedLine(2, "}");

            if (!string.IsNullOrEmpty(searchQuery))
            {
                builder
                .AppendLine()
                .AppendNestedLine(2, $"public virtual Task<List<{metadata.Name}>> SearchAsync(string term)")
                .AppendNestedLine(2, "{")
                .AppendNestedLine(3, $"return _context.{metadata.PluralName}.AsNoTracking().Where(w => {searchQuery}).ToListAsync();")
                .AppendNestedLine(2, "}")
                .AppendLine()
                .AppendNestedLine(2, $"public virtual Task<PageModel<{metadata.Name}>> SearchAsync(string term, int page, int pageSize, string sortField, bool asc)")
                .AppendNestedLine(2, "{")
                .AppendNestedLine(3, $"var query = _context.{metadata.PluralName}.AsNoTracking().Where(w => {searchQuery});")
                .AppendNestedLine(3, $"query = GetSortedQuery(query, sortField, asc);")
                .AppendLine()
                .AppendNestedLine(3, $"return PageModel<{metadata.Name}>.CreateAsync(query, page, pageSize, sortField, asc);")
                .AppendNestedLine(2, "}");
            }

            builder
            .AppendLine()
            .AppendNestedLine(2, $"public virtual async Task<ResultModel<{metadata.Name}>> UpdateAsync({metadata.Name} model)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, $"var existingEntity = await GetAsync(model.Id);")
            .AppendNestedLine(3, "if (existingEntity == null)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "return null;")
            .AppendNestedLine(3, "}")
            .AppendLine();

            foreach (var property in metadata.Properties.Where(w => w.Key != metadata.KeyName && w.Key != "CreatedAt" && w.Key != "UpdatedAt"))
            {
                builder.AppendNestedLine(3, $"existingEntity.{property.Key} = model.{property.Key};");
            }
            if (metadata.Properties.ContainsKey("UpdatedAt"))
            {
                builder.AppendNestedLine(3, "existingEntity.UpdatedAt = DateTime.UtcNow;");
            }

            builder
            .AppendLine()
            .AppendNestedLine(3, "await _context.SaveChangesAsync();")
            .AppendLine()
            .AppendNestedLine(3, $"return new ResultModel<{metadata.Name}>(existingEntity);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, $"protected virtual IQueryable<{metadata.Name}> GetSortedQuery(IQueryable<{metadata.Name}> query, string sortField, bool asc)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "switch (sortField)")
            .AppendNestedLine(3, "{");

            foreach (var property in metadata.Properties.Where(w => w.Key != metadata.KeyName))
            {
                builder
                .AppendNestedLine(4, $"case \"{property.Key}\":")
                .AppendNestedLine(5, $"return asc")
                .AppendNestedLine(6, "? query")
                .AppendNestedLine(7, $".OrderBy(o => o.{property.Key})")
                .AppendNestedLine(7, $".ThenBy(o => o.{metadata.KeyName})")
                .AppendNestedLine(6, ": query")
                .AppendNestedLine(7, $".OrderByDescending(o => o.{property.Key})")
                .AppendNestedLine(7, $".ThenBy(o => o.{metadata.KeyName});");
            }

            builder
            .AppendNestedLine(4, "default:")
            .AppendNestedLine(5, $"return asc")
            .AppendNestedLine(6, $"? query.OrderBy(o => o.{metadata.KeyName})")
            .AppendNestedLine(6, $": query.OrderByDescending(o => o.{metadata.KeyName});")
            .AppendNestedLine(3, "}")
            .AppendNestedLine(2, "}")
            .AppendNestedLine(1, "}")
            .AppendNestedLine(0, "}");

            return(builder.ToString());
        }
コード例 #21
0
        /// <summary>
        /// Generates an MVC controller with CRUD operations for a model
        /// </summary>
        /// <param name="argReader">Information fetched from the command line arguments</param>
        public void Generate(ArgReader argReader)
        {
            var metadata         = new ModelMetadata(argReader.ModelPath);
            var builder          = new StringBuilder();
            var filledProperties = metadata.Properties
                                   .Where(w => w.Key != metadata.KeyName && w.Key != "CreatedAt" && w.Key != "UpdatedAt");

            builder
            .AppendNestedLine(0, "using System;")
            .AppendNestedLine(0, "using System.Threading.Tasks;")
            .AppendNestedLine(0, "using Microsoft.AspNetCore.Mvc;")
            .AppendNestedLine(0, $"using {metadata.Namespace};")
            .AppendLine()
            .AppendNestedLine(0, $"namespace {argReader.Namespace}")
            .AppendNestedLine(0, "{")
            .AppendNestedLine(1, $"public class {metadata.PluralName}Controller : Controller")
            .AppendNestedLine(1, "{")
            .AppendNestedLine(2, "private const int PAGE_SIZE = 20;")
            .AppendLine()
            .AppendNestedLine(2, $"private readonly I{metadata.Name}Service _service;")
            .AppendLine()
            .AppendNestedLine(2, $"public {metadata.PluralName}Controller(I{metadata.Name}Service service)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "_service = service;")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "public async Task<IActionResult> Index(string term, int page = 1, string sortField = \"\", bool asc = true)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entities = string.IsNullOrWhiteSpace(term)")
            .AppendNestedLine(4, "? await _service.GetAllAsync(page, PAGE_SIZE, sortField, asc)")
            .AppendNestedLine(4, ": await _service.SearchAsync(term, page, PAGE_SIZE, sortField, asc);")
            .AppendLine()
            .AppendNestedLine(3, "return View(entities);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, $"public async Task<IActionResult> Details({metadata.KeyProperty.TypeName} id)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await _service.GetAsync(id);")
            .AppendNestedLine(3, "if (entity == null)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "return NotFound();")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, "return View(entity);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "public IActionResult Create()")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "return View();")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[HttpPost]")
            .AppendNestedLine(2, "[ValidateAntiForgeryToken]")
            .AppendNestedLine(2, $"public async Task<IActionResult> Create({metadata.Name} entity)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "if (!ModelState.IsValid)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "return View(entity);")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, "var result = await _service.CreateAsync(entity);")
            .AppendNestedLine(3, "if (!result.IsSuccess)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "foreach (var error in result.Errors)")
            .AppendNestedLine(4, "{")
            .AppendNestedLine(5, "ModelState.AddModelError(string.Empty, error);")
            .AppendNestedLine(4, "}")
            .AppendLine()
            .AppendNestedLine(4, "return View(entity);")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, $"return RedirectToAction(nameof(Details), new {{ id = result.Result.{metadata.KeyName} }});")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, $"public async Task<IActionResult> Edit({metadata.KeyProperty.TypeName} id)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await _service.GetAsync(id);")
            .AppendNestedLine(3, "if (entity == null)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "return NotFound();")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, "return View(entity);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[HttpPost]")
            .AppendNestedLine(2, "[ValidateAntiForgeryToken]")
            .AppendNestedLine(2, $"public async Task<IActionResult> Edit({metadata.Name} entity)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "if (!ModelState.IsValid)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "return View(entity);")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, "var result = await _service.UpdateAsync(entity);")
            .AppendNestedLine(3, "if (result == null)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "return NotFound();")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, "if (!result.IsSuccess)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "foreach (var error in result.Errors)")
            .AppendNestedLine(4, "{")
            .AppendNestedLine(5, "ModelState.AddModelError(string.Empty, error);")
            .AppendNestedLine(4, "}")
            .AppendLine()
            .AppendNestedLine(4, "return View(entity);")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, $"return RedirectToAction(nameof(Details), new {{ id = result.Result.{metadata.KeyName} }});")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, $"public async Task<IActionResult> Delete({metadata.KeyProperty.TypeName} id)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await _service.GetAsync(id);")
            .AppendNestedLine(3, "if (entity == null)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "return NotFound();")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, "return View(entity);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[HttpPost, ActionName(\"Delete\")]")
            .AppendNestedLine(2, "[ValidateAntiForgeryToken]")
            .AppendNestedLine(2, $"public async Task<IActionResult> DeleteConfirmed({metadata.KeyProperty.TypeName} id)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var result = await _service.DeleteAsync(id);")
            .AppendNestedLine(3, "if (result)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "return RedirectToAction(nameof(Index));")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, "return NotFound();")
            .AppendNestedLine(2, "}")
            .AppendNestedLine(1, "}")
            .AppendNestedLine(0, "}");

            FileHelper.SaveToOutput(argReader.OutputFolder, $"{metadata.PluralName}Controller.cs", builder.ToString());
        }
コード例 #22
0
        /// <summary>
        /// Generates an API controller with CRUD operations for a model
        /// </summary>
        /// <param name="argReader">Information fetched from the command line arguments</param>
        public void Generate(ArgReader argReader)
        {
            var metadata         = new ModelMetadata(argReader.ModelPath);
            var builder          = new StringBuilder();
            var filledProperties = metadata.Properties
                                   .Where(w => w.Key != metadata.KeyName && w.Key != "CreatedAt" && w.Key != "UpdatedAt");

            builder
            .AppendNestedLine(0, "using System;")
            .AppendNestedLine(0, "using System.Threading.Tasks;")
            .AppendNestedLine(0, "using Microsoft.AspNetCore.Mvc;")
            .AppendNestedLine(0, $"using {metadata.Namespace};")
            .AppendLine()
            .AppendNestedLine(0, $"namespace {argReader.Namespace}")
            .AppendNestedLine(0, "{")
            .AppendNestedLine(1, "[Route(\"api/[controller]\")]")
            .AppendNestedLine(1, "[ApiController]")
            .AppendNestedLine(1, $"public class {metadata.PluralName}Controller : ControllerBase")
            .AppendNestedLine(1, "{")
            .AppendNestedLine(2, "private const int PAGE_SIZE = 20;")
            .AppendLine()
            .AppendNestedLine(2, $"private readonly I{metadata.Name}Service _service;")
            .AppendLine()
            .AppendNestedLine(2, $"public {metadata.PluralName}Controller(I{metadata.Name}Service service)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "_service = service;")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[HttpGet]")
            .AppendNestedLine(2, "public async Task<IActionResult> GetAll(string term, int page = 1, string sortField = \"\", bool asc = true)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entities = string.IsNullOrWhiteSpace(term)")
            .AppendNestedLine(4, "? await _service.GetAllAsync(page, PAGE_SIZE, sortField, asc)")
            .AppendNestedLine(4, ": await _service.SearchAsync(term, page, PAGE_SIZE, sortField, asc);")
            .AppendLine()
            .AppendNestedLine(3, "return Ok(entities);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[HttpGet(\"{id}\")]")
            .AppendNestedLine(2, $"public async Task<IActionResult> Get({metadata.KeyProperty.TypeName} id)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var entity = await _service.GetAsync(id);")
            .AppendNestedLine(3, "if (entity == null)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "return NotFound();")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, "return Ok(entity);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[HttpPost]")
            .AppendNestedLine(2, $"public async Task<IActionResult> Create({metadata.Name} entity)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var result = await _service.CreateAsync(entity);")
            .AppendLine()
            .AppendNestedLine(3, "return Ok(result);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[HttpPut(\"{id}\")]")
            .AppendNestedLine(2, $"public async Task<IActionResult> Update({metadata.Name} entity)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var result = await _service.UpdateAsync(entity);")
            .AppendNestedLine(3, "if (result == null)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "return NotFound();")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, "return Ok(result);")
            .AppendNestedLine(2, "}")
            .AppendLine()
            .AppendNestedLine(2, "[HttpDelete(\"{id}\")]")
            .AppendNestedLine(2, $"public async Task<IActionResult> Delete({metadata.KeyProperty.TypeName} id)")
            .AppendNestedLine(2, "{")
            .AppendNestedLine(3, "var result = await _service.DeleteAsync(id);")
            .AppendNestedLine(3, "if (result)")
            .AppendNestedLine(3, "{")
            .AppendNestedLine(4, "return Ok();")
            .AppendNestedLine(3, "}")
            .AppendLine()
            .AppendNestedLine(3, "return NotFound();")
            .AppendNestedLine(2, "}")
            .AppendNestedLine(1, "}")
            .AppendNestedLine(0, "}");

            FileHelper.SaveToOutput(argReader.OutputFolder, $"{metadata.PluralName}Controller.cs", builder.ToString());
        }
コード例 #23
0
 public SoundBuildSettings(string path)
 {
     Path   = path;
     Reader = new ArgReader(' ', "-");
 }
コード例 #24
0
        void mainForm_Load(object sender, EventArgs e)
        {
            if (!util.isShowWindow)
            {
                return;
            }

            var a    = util.getJarPath();
            var desc = System.Diagnostics.FileVersionInfo.GetVersionInfo(util.getJarPath()[0] + "/websocket4net.dll");

            if (desc.FileDescription != "WebSocket4Net for .NET 4.5 gettable data bytes")
            {
                Invoke((MethodInvoker) delegate() {
                    System.Windows.Forms.MessageBox.Show("「WebSocket4Net.dll」をver0.86.9以降に同梱されているものと置き換えてください");
                });
            }



            //.net
            var ver = util.Get45PlusFromRegistry();

            if (ver < 4.52)
            {
                Task.Run(() => {
                    Invoke((MethodInvoker) delegate() {
                        var b = new DotNetMessageBox(ver);
                        b.Show(this);
//						System.Windows.Forms.MessageBox.Show("「動作には.NET 4.5.2以上が推奨です。現在は" + ver + "です。");
                    });
                });
            }

            if (args.Length > 0)
            {
                var ar = new ArgReader(args, config, this);
                ar.read();
                if (ar.isConcatMode)
                {
                    urlText.Text = string.Join("|", args);
                    rec.rec();
                }
                else
                {
                    config.argConfig = ar.argConfig;
                    rec.argTsConfig  = ar.tsConfig;
                    rec.isRecording  = true;
//					rec.setArgConfig(args);
                    if (ar.lvid != null || ar.wssUrl != null)
                    {
                        urlText.Text = ar.lvid != null ? ar.lvid : ar.wssUrl;
                        player.play();
                    }

                    //if (ar.isPlayMode) player.play();
                    //else rec.rec();
                }
                if (bool.Parse(config.get("Isminimized")))
                {
                    this.WindowState = FormWindowState.Minimized;
                }
            }
            setLatencyListText(config.get("latency"));

            startStdRead();
        }