Пример #1
0
        public static (Template, Event <TemplateCreated>) On(CreateTemplate request, Guid userId)
        {
            var template = new Template
            {
                Id            = Guid.NewGuid(),
                Key           = request.Key,
                Type          = request.Type,
                CorrelationId = request.CorrelationId,
                Title         = request.Title,
                Description   = request.Description,
                Tags          = request.Tags,
                Ratios        = request.Ratios,
                Created       = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                Updated       = 0,
                Deleted       = 0
            };

            return(template, new Event <TemplateCreated>
            {
                Type = "template-created",
                Version = 1,
                CorrelationId = request.CorrelationId,
                OccurredOn = template.Created,
                UserId = userId,
                Payload = new TemplateCreated
                {
                    TemplateId = template.Id
                }
            });
Пример #2
0
        public async Task <(Result, Template?)> CreateAsync(CreateTemplate request, Guid userId)
        {
            _logger.LogInformation($"Trying to create template {request.Title}");
            if (await _templates.CountDocumentsAsync(x => x.CorrelationId == request.CorrelationId) > 0)
            {
                return(Result.Conflict, null);
            }

            foreach (var tagName in request.Tags)
            {
                if (await _tags.CountDocumentsAsync(x => x.Key == tagName) == 0)
                {
                    await _tagService.CreateAsync(new CreateTag
                    {
                        CorrelationId = request.CorrelationId,
                        Key           = tagName,
                        Title         = new Dictionary <string, string> {
                            { "en", tagName }
                        }
                    }, userId);
                }
            }

            var(template, templateCreated) = Template.On(request, userId);

            await _templates.InsertOneAsync(template);

            await _eventService.PublishAsync(templateCreated);

            _logger.LogInformation($"Template {template.Id} created");

            return(Result.Successful, template);
        }
Пример #3
0
 public ActionResult Create(CreateTemplate viewModel, string[] coords)
 {
     try
     {
         Template newTemplate = new Template()
         {
             Title = viewModel.Title,
             Url   = viewModel.Url
         };
         int id = _templateRepo.Insert(newTemplate);
         foreach (var coord in coords)
         {
             var         xy         = coord.Split(',');
             double      x          = double.Parse(xy[0]);
             double      y          = double.Parse(xy[1]);
             Coordinates coordinate = new Coordinates()
             {
                 X          = x,
                 Y          = y,
                 TemplateId = id
             };
             _coordRepo.Insert(coordinate);
         }
         return(RedirectToAction("Create", "Home", new { id = id }));
     }
     catch {
     }
     return(View(viewModel));
 }
Пример #4
0
        public async Task <IActionResult> CreateTemplate([FromBody] CreateTemplate command)
        {
            await rules
            .NoDuplicateTemplateNames()
            .EnsureValidColumnName()
            .EnsureValidOperator()
            .Apply(command, ModelState);


            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var id = await elrService.Execute(command);

            var uri = Url.Action("GetTemplateDetails", new { id });

            return(Created(uri, new TemplateDetailsDto
            {
                TemplateID = id,
                TemplateName = command.TemplateName,
                TemplateType = command.TemplateType,
                Criteria = command.Criteria,
            }));
        }
Пример #5
0
        public void Should_validate_command_and_save_new_template()
        {
            var command = new CreateTemplate
            {
                Id          = Guid.NewGuid(),
                Name        = "Name",
                Description = "Description",
                ViewName    = "ViewName"
            };

            var templateRepositoryMock = new Mock <ITemplateRepository>();

            templateRepositoryMock.Setup(x => x.Create(It.IsAny <Template>()));

            var validatorMock = new Mock <IValidator <CreateTemplate> >();

            validatorMock.Setup(x => x.Validate(command)).Returns(new ValidationResult());

            var createTemplateHandler = new CreateTemplateHandler(templateRepositoryMock.Object, validatorMock.Object);

            createTemplateHandler.Handle(command);

            validatorMock.Verify(x => x.Validate(command));
            templateRepositoryMock.Verify(x => x.Create(It.IsAny <Template>()));
        }
Пример #6
0
        public ActionResult CreateTemplate(string path = "")
        {
            var model = new CreateTemplate {
                Path = path
            };

            return(View(model));
        }
Пример #7
0
 public Task <IActionResult> AddNewTemplate([FromBody] CreateTemplate request, CancellationToken cancellationToken)
 {
     return(SafeInvoke(async() =>
     {
         var templateId = Guid.NewGuid();
         await _templateManager.CreateTemplate(templateId, request.TemplateKindKey, request.TemplateLabel, request.Content, cancellationToken);
         return CreatedAtRoute("TemplateDetails", new { templateId }, null);
     }));
 }
Пример #8
0
        public ActionResult CreateTemplate(CreateTemplate model)
        {
            bool   success = false;
            string message = "";

            try
            {
                model.Path = model.Path == "/" ? "" : model.Path;
                if (!ModelState.IsValid)
                {
                    var errors = string.Join("<br/>", ModelState.SelectMany(x => x.Value.Errors).Select(x => x.ErrorMessage));
                    throw new Exception(errors);
                }
                string modelname   = "";
                var    isGenerated = false;

                if (!string.IsNullOrEmpty(model.TemplateModel))
                {
                    //var type = ApiHelper.GetType(model.TemplateModel);
                    var type = ApiHelper.GetTypeFromName(model.TemplateModel);
                    modelname   = type.FullName;
                    isGenerated = typeof(I_Generated).IsAssignableFrom(type);
                }
                var destPath    = PuckCache.TemplateDirectory + model.Path + model.Name + ".cshtml";
                var absDestPath = ApiHelper.MapPath(destPath);
                if (System.IO.File.Exists(absDestPath))
                {
                    throw new Exception("file with that name already exists");
                }

                var contents = "";
                if (!string.IsNullOrEmpty(modelname))
                {
                    if (isGenerated)
                    {
                        contents += string.Concat("@model dynamic\n@{/*", modelname, "*/}\n\n");
                    }
                    else
                    {
                        contents += string.Concat("@model ", modelname, "\n\n");
                    }
                }

                System.IO.File.WriteAllText(absDestPath,
                                            contents
                                            );

                success = true;
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return(Json(new { name = model.Path + model.Name + ".cshtml", message = message, success = success }));
        }
Пример #9
0
        private void SetSdkVersion()
        {
            SdkVersion.IsEnabled = true;

            //If no project is selected use the default SDK version or the first item in the list
            //If a project is selected use the same SDK version
            ComboBoxItem projectItem = (ComboBoxItem)ProjectList.SelectedItem;

            if (projectItem == null || string.IsNullOrEmpty(projectItem.Content.ToString()))
            {
                foreach (ComboBoxItem item in SdkVersion.Items)
                {
                    if (item.Content.ToString() == _defaultSdkVersion)
                    {
                        SdkVersion.SelectedItem = item;
                    }
                }

                if (SdkVersion.SelectedItem == null)
                {
                    SdkVersion.SelectedIndex = SdkVersion.Items.Count - 1;
                }

                CreateTemplate.Focus();
            }
            else
            {
                var tag = projectItem.Tag;
                if (tag == null)
                {
                    return;
                }

                string version = projectItem.Tag.ToString();
                if (string.IsNullOrEmpty(version))
                {
                    return;
                }

                foreach (ComboBoxItem item in SdkVersion.Items)
                {
                    if (item.Content.ToString() != version)
                    {
                        continue;
                    }

                    SdkVersion.SelectedItem = item;
                    SdkVersion.IsEnabled    = false;
                    CreateTemplate.Focus();
                    break;
                }
            }
        }
Пример #10
0
 private Template(CreateTemplate cmd) : base(cmd.Id)
 {
     AddEvent(new TemplateCreated
     {
         AggregateRootId = Id,
         Name            = cmd.Name,
         Description     = cmd.Description,
         ViewName        = cmd.ViewName,
         Status          = TemplateStatus.Hidden,
         Type            = cmd.Type
     });
 }
        public void CreateView_Template_Test()
        {
            var template = new CreateTemplate(new EntityInfo()
            {
                Id = _entityId
            }, ApplicationId);
            var output = template.TransformText();

            Assert.NotNull(output);
            Assert.NotEmpty(output);
            Assert.Contains($"@model {ApplicationId}.Backend.DataModels.{_entityId}", output);
        }
        public async Task <Template> Create([FromBody] CreateTemplate model)
        {
            var template = await _codeGenDbContext.Templates.AddAsync(new Domain.CodeGen.Template()
            {
                Id       = Guid.NewGuid(),
                MetaType = model.MetaType,
                Name     = model.Name,
                Value    = model.Value
            });

            _codeGenDbContext.SaveChanges();
            return(_mapper.Map <Template>(template.Entity));
        }
Пример #13
0
        public async Task <IActionResult> CreateAsync([FromBody] CreateTemplate request, CancellationToken cancellationToken)
        {
            var billingDate = _mapper.Map <Domain.Templates.BillingDate>(request.BillingDate);
            var timeZone    = _dateTimeZoneProvider[request.TimeZone];
            var template    = new Template(request.Name, request.Price, request.BillingModeId, billingDate, request.BillingPeriodMonth, request.BillingPeriodOffsetMonth, timeZone);

            _templateRepository.Add(template);
            await _templateRepository.UnitOfWork.SaveChangesAsync(cancellationToken);

            var vm = _mapper.Map <ViewTemplate>(template);

            return(CreatedAtAction(nameof(GetAsync), new { id = vm.Id }, vm));
        }
Пример #14
0
 public void Setup()
 {
     _command = new CreateTemplate
     {
         Id          = Guid.NewGuid(),
         Name        = "Name",
         Description = "Description",
         ViewName    = "ViewName"
     };
     _validatorMock = new Mock <IValidator <CreateTemplate> >();
     _validatorMock.Setup(x => x.Validate(_command)).Returns(new ValidationResult());
     _template = Template.CreateNew(_command, _validatorMock.Object);
     _event    = _template.Events.OfType <TemplateCreated>().SingleOrDefault();
 }
Пример #15
0
        public void Should_have_validation_error_when_template_name_is_empty()
        {
            var command = new CreateTemplate
            {
                Id          = Guid.NewGuid(),
                Name        = string.Empty,
                Description = "Description",
                ViewName    = "ViewName"
            };

            var templateRulesMock = new Mock <ITemplateRules>();
            var validator         = new CreateTemplateValidator(templateRulesMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.Name, command);
        }
Пример #16
0
        public async Task <int> Execute(CreateTemplate command)
        {
            ElrSearchTemplates template = new ElrSearchTemplates
            {
                CdType = command.TemplateType,
                DsName = command.TemplateName,
                JsData = JsonConvert.SerializeObject(command.Criteria),
            };

            await writeContext.ElrSearchTemplates.AddAsync(template);

            await writeContext.SaveChangesAsync();

            return(template.Id);
        }
        public async Task Post_TemplateDoesNotExistsAndItShouldBeCreated_MethodReturn201()
        {
            var command = new CreateTemplate()
            {
            };
            var templateServiceMock   = new Mock <ITemplateService>();
            var commandDispatcherMock = new Mock <ICommandDispatcher>();

            var templatesController = new TemplatesController(commandDispatcherMock.Object, templateServiceMock.Object);

            var response = await templatesController.Post(command);

            response.Should().NotBeNull();
            response.Should().BeOfType <CreatedResult>();
            (response as ObjectResult).StatusCode.Should().Be(201);
        }
        public async Task Produces_400BadRequest_On_ArgumentException()
        {
            var request = new CreateTemplate()
            {
                TemplateKindKey = "tk1",
                TemplateLabel   = "Lipsum",
                Content         = "Lorem ipsum, dolor sit amet"
            };
            var ct = CancellationToken.None;

            _templateManager.Setup(x => x.CreateTemplate(It.IsAny <Guid>(), request.TemplateKindKey, request.TemplateLabel, request.Content, ct))
            .Throws(new ArgumentException());

            var result = await _controller.AddNewTemplate(request, CancellationToken.None);

            result.Should().BeOfType(typeof(BadRequestResult));
        }
Пример #19
0
        private Template(CreateTemplate cmd)
            : base(cmd.Id)
        {
            Name        = cmd.Name;
            Description = cmd.Description;
            ViewName    = cmd.ViewName;
            Status      = TemplateStatus.Hidden;

            AddEvent(new TemplateCreated
            {
                AggregateRootId = Id,
                Name            = Name,
                Description     = Description,
                ViewName        = ViewName,
                Status          = Status
            });
        }
Пример #20
0
        public async Task HandleAsync_TemplateIdIsEmpty_MethodReturnOne(string id, int expectedResult)
        {
            var command = new CreateTemplate()
            {
                Id      = Guid.Parse(id),
                UserId  = "auth0|5c81a3686d3d732e6aa9e88f",
                Name    = "Foo template",
                Content = JObject.Parse("{\"foo\" : \"bar\"}")
            };
            var templateServiceMock   = new Mock <ITemplateService>();
            var busPublisherMock      = new Mock <IBusPublisher>();
            var createTemplateHandler = new CreateTemplateHandler(busPublisherMock.Object, templateServiceMock.Object);

            var result = await createTemplateHandler.HandleAsync(command);

            result.Should().Be(expectedResult);
        }
        public async Task Get_TemplateExistsAndShouldBeReturned_MethodReturnJson(List <TemplateDto> data)
        {
            var command = new CreateTemplate()
            {
            };
            var templateServiceMock = new Mock <ITemplateService>();

            templateServiceMock.Setup(x => x.GetAsync())
            .ReturnsAsync(data);
            var commandDispatcherMock = new Mock <ICommandDispatcher>();

            var templatesController = new TemplatesController(commandDispatcherMock.Object, templateServiceMock.Object);

            var response = await templatesController.Get();

            response.Should().NotBeNull();
            response.Should().BeOfType <JsonResult>();
        }
        public async Task Produces_500InternalServerError_When_TemplateCreationFailedException()
        {
            var request = new CreateTemplate()
            {
                TemplateKindKey = "tk1",
                TemplateLabel   = "Lipsum",
                Content         = "Lorem ipsum, dolor sit amet"
            };
            var ct = CancellationToken.None;

            _templateManager.Setup(x => x.CreateTemplate(It.IsAny <Guid>(), request.TemplateKindKey, request.TemplateLabel, request.Content, ct))
            .Throws(new TemplateCreationFailedException(request.TemplateKindKey, request.TemplateLabel, new Exception()));

            var result = await _controller.AddNewTemplate(request, CancellationToken.None);

            result.Should().BeOfType(typeof(StatusCodeResult));
            ((StatusCodeResult)result).StatusCode.Should().Be(500);
        }
Пример #23
0
        public void Should_have_validation_error_when_template_name_is_not_unique()
        {
            var command = new CreateTemplate
            {
                Id          = Guid.NewGuid(),
                Name        = "Name",
                Description = "Description",
                ViewName    = "ViewName"
            };

            var templateRulesMock = new Mock <ITemplateRules>();

            templateRulesMock.Setup(x => x.IsTemplateNameUnique(command.Name, Guid.Empty)).Returns(false);

            var validator = new CreateTemplateValidator(templateRulesMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.Name, command);
        }
Пример #24
0
        public void Should_have_validation_error_when_template_id_already_exists()
        {
            var command = new CreateTemplate
            {
                Id          = Guid.NewGuid(),
                Name        = "Name",
                Description = "Description",
                ViewName    = "ViewName"
            };

            var templateRulesMock = new Mock <ITemplateRules>();

            templateRulesMock.Setup(x => x.IsTemplateIdUnique(command.Id)).Returns(false);

            var siteRulesMock = new Mock <ISiteRules>();
            var validator     = new CreateTemplateValidator(templateRulesMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.Id, command);
        }
        private void TransformViews(SmartAppInfo manifest)
        {
            var enabledEntities = manifest.DataModel.Entities.Where(e => !e.IsAbstract);

            foreach (var entity in enabledEntities)
            {
                var applicationId = manifest.Id;

                var createTemplate = new CreateTemplate(entity, applicationId);
                var editTemplate   = new EditTemplate(entity, applicationId);
                var detailTemplate = new DetailsTemplate(entity, applicationId);
                var deleteTemplate = new DeleteTemplate(entity, applicationId);
                var indexTemplate  = new IndexTemplate(entity, applicationId);

                _writingService.WriteFile(Path.Combine(_context.BasePath, createTemplate.OutputPath, entity.Id, "Create.cshtml"), createTemplate.TransformText());
                _writingService.WriteFile(Path.Combine(_context.BasePath, editTemplate.OutputPath, entity.Id, "Edit.cshtml"), editTemplate.TransformText());
                _writingService.WriteFile(Path.Combine(_context.BasePath, deleteTemplate.OutputPath, entity.Id, "Delete.cshtml"), deleteTemplate.TransformText());
                _writingService.WriteFile(Path.Combine(_context.BasePath, detailTemplate.OutputPath, entity.Id, "Details.cshtml"), detailTemplate.TransformText());
                _writingService.WriteFile(Path.Combine(_context.BasePath, indexTemplate.OutputPath, entity.Id, "Index.cshtml"), indexTemplate.TransformText());
            }
        }
Пример #26
0
        public void Should_have_validation_error_when_template_name_is_too_long()
        {
            var name = "";

            for (int i = 0; i < 101; i++)
            {
                name += i;
            }

            var command = new CreateTemplate
            {
                Id          = Guid.NewGuid(),
                Name        = name,
                Description = "Description",
                ViewName    = "ViewName"
            };

            var templateRulesMock = new Mock <ITemplateRules>();
            var validator         = new CreateTemplateValidator(templateRulesMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.Name, command);
        }
Пример #27
0
        public void Should_have_validation_error_when_description_is_too_long()
        {
            var description = "";

            for (int i = 0; i < 251; i++)
            {
                description += i;
            }

            var command = new CreateTemplate
            {
                Id          = Guid.NewGuid(),
                Name        = "Name",
                Description = description,
                ViewName    = "ViewName"
            };

            var templateRulesMock = new Mock <ITemplateRules>();
            var validator         = new CreateTemplateValidator(templateRulesMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.Description, command);
        }
Пример #28
0
        public void Should_throw_validation_exception_when_validation_fails()
        {
            var command = new CreateTemplate
            {
                Id          = Guid.NewGuid(),
                Name        = "Name",
                Description = "Description",
                ViewName    = "ViewName"
            };

            var templateRepositoryMock = new Mock <ITemplateRepository>();

            var validatorMock = new Mock <IValidator <CreateTemplate> >();

            validatorMock.Setup(x => x.Validate(command)).Returns(new ValidationResult(new List <ValidationFailure> {
                new ValidationFailure("Id", "Id Error")
            }));

            var createTemplateHandler = new CreateTemplateHandler(templateRepositoryMock.Object, validatorMock.Object);

            Assert.Throws <ValidationException>(() => createTemplateHandler.Handle(command));
        }
        public async Task Produces_201Created()
        {
            var request = new CreateTemplate()
            {
                TemplateKindKey = "tk1",
                TemplateLabel   = "Lipsum",
                Content         = "Lorem ipsum, dolor sit amet"
            };
            var ct = CancellationToken.None;

            _templateManager.Setup(x => x.CreateTemplate(It.IsAny <Guid>(), request.TemplateKindKey, request.TemplateLabel, request.Content, ct))
            .Verifiable();

            var result = await _controller.AddNewTemplate(request, CancellationToken.None) as CreatedAtRouteResult;

            result.Should().NotBeNull();
            result.RouteName.Should().Be("TemplateDetails");

            var templateId = Guid.Parse(result.RouteValues["templateId"].ToString());

            _templateManager.Verify(x => x.CreateTemplate(templateId, request.TemplateKindKey, request.TemplateLabel, request.Content, ct));
        }
 public CreateTemplateTest()
 {
     this.dataStorage = Substitute.For <DataStorage>(Database.GetDatabase("master"));
     this.processor   = new CreateTemplate();
 }