예제 #1
0
        public async Task <IActionResult> PostContent(string app, string name, [FromBody] NamedContentData request, [FromQuery] bool publish = false)
        {
            await contentQuery.ThrowIfSchemaNotExistsAsync(App, name);

            var command = new CreateContent {
                ContentId = Guid.NewGuid(), Data = request.ToCleaned(), Publish = publish
            };

            var context = await CommandBus.PublishAsync(command);

            var result   = context.Result <EntityCreatedResult <NamedContentData> >();
            var response = ContentDto.FromCommand(command, result);

            return(CreatedAtAction(nameof(GetContent), new { id = command.ContentId }, response));
        }
예제 #2
0
        public async Task <IActionResult> GetContentVersion(string app, string name, Guid id, int version)
        {
            var content = await contentQuery.FindContentAsync(Context, name, id, version);

            var response = ContentDto.FromContent(Context, content, this);

            if (controllerOptions.EnableSurrogateKeys)
            {
                Response.Headers["Surrogate-Key"] = content.ToSurrogateKey();
            }

            Response.Headers[HeaderNames.ETag] = content.ToEtag();

            return(Ok(response.Data));
        }
예제 #3
0
        private ContentDto BuildContentDto(IMember entity)
        {
            var contentDto = new ContentDto
            {
                NodeId        = entity.Id,
                ContentTypeId = entity.ContentTypeId,
                NodeDto       = BuildNodeDto(entity)
            };

            if (_primaryKey > 0)
            {
                contentDto.PrimaryKey = _primaryKey;
            }

            return(contentDto);
        }
예제 #4
0
        public async Task <IActionResult> GetContent(string app, string name, Guid id)
        {
            var context = Context();
            var content = await contentQuery.FindContentAsync(context, name, id);

            var response = ContentDto.FromContent(content, context);

            if (controllerOptions.Value.EnableSurrogateKeys)
            {
                Response.Headers["Surrogate-Key"] = content.Id.ToString();
            }

            Response.Headers["ETag"] = content.Version.ToString();

            return(Ok(response));
        }
예제 #5
0
        public void UpdateContents(int id, ContentDto contentDto)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            var contentindb = _content.Contents.SingleOrDefault(m => m.ID == id);

            if (contentindb == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            Mapper.Map <ContentDto, Content>(contentDto, contentindb);

            _content.SaveChanges();
        }
예제 #6
0
        // always build the current / VersionPk dto
        // we're never going to build / save old versions (which are immutable)
        private static ContentVersionDto BuildContentVersionDto(IContentBase entity, ContentDto contentDto)
        {
            var dto = new ContentVersionDto
            {
                Id          = entity.VersionId,
                NodeId      = entity.Id,
                VersionDate = entity.UpdateDate,
                UserId      = entity.WriterId,
                Current     = true, // always building the current one
                Text        = entity.Name,

                ContentDto = contentDto
            };

            return(dto);
        }
예제 #7
0
        public void GetFolderContent_Method_Test_GetContent_Call_Once_Return_Not_Null_Result()
        {
            // Arrange
            var returnModel = new ContentDto();

            _contentService.Setup(f => f.GetContent(null)).Returns(returnModel);

            var controller = new FolderController(_contentService.Object, _mapper);

            // Act
            var result = controller.GetFolderContent();

            // Assert
            Assert.IsNotNull(result);
            _contentService.Verify(f => f.GetContent(null), Times.Once);
        }
예제 #8
0
        public async Task <IActionResult> GetContent(string app, string schema, DomainId id)
        {
            var content = await contentQuery.FindAsync(Context, schema, id, ct : HttpContext.RequestAborted);

            if (content == null)
            {
                return(NotFound());
            }

            var response = Deferred.Response(() =>
            {
                return(ContentDto.FromDomain(content, Resources));
            });

            return(Ok(response));
        }
예제 #9
0
        public async Task <IActionResult> GetContentVersion(string app, string name, Guid id, int version)
        {
            var context = Context().WithSchemaName(name);
            var content = await contentQuery.FindContentAsync(context, id, version);

            var response = ContentDto.FromContent(content, context.Base);

            Response.Headers["ETag"] = content.Version.ToString();

            if (controllerOptions.Value.EnableSurrogateKeys)
            {
                Response.Headers["Surrogate-Key"] = content.Id.ToString();
            }

            return(Ok(response.Data));
        }
예제 #10
0
        private static MediaVersionDto BuildMediaVersionDto(IMedia entity, ContentDto contentDto)
        {
            // try to get a path from the string being stored for media
            // fixme - only considering umbracoFile ?!

            TryMatch(entity.GetValue <string>("umbracoFile"), out var path);

            var dto = new MediaVersionDto
            {
                Id   = entity.VersionId,
                Path = path,

                ContentVersionDto = BuildContentVersionDto(entity, contentDto)
            };

            return(dto);
        }
예제 #11
0
        public async Task <IActionResult> UpdateContent([FromBody] ContentDto contentToUpdate)
        {
            var existingContent = await _contentService.ContentExistAsync(contentToUpdate.ContentName);

            if (existingContent)
            {
                return(NotFound("Requested resource not found."));
            }

            var updateResult = await _contentService.UpdateContentAsync(contentToUpdate);

            if (!updateResult)
            {
                return(BadRequest("An error occured during the updating resource."));
            }

            return(Ok());
        }
예제 #12
0
        private IMedia MapDtoToContent(ContentDto dto)
        {
            var contentType = _mediaTypeRepository.Get(dto.ContentTypeId);
            var media       = ContentBaseFactory.BuildEntity(dto, contentType);

            // get properties - indexed by version id
            var versionId  = dto.ContentVersionDto.Id;
            var temp       = new TempContent <Core.Models.Media>(dto.NodeId, versionId, 0, contentType);
            var properties = GetPropertyCollections(new List <TempContent <Core.Models.Media> > {
                temp
            });

            media.Properties = properties[versionId];

            // reset dirty initial properties (U4-1946)
            media.ResetDirtyProperties(false);
            return(media);
        }
예제 #13
0
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="dictionary"></param>
        public void Add(ContentDto entity, Dictionary <string, object> dictionary)
        {
            var content = AutoMapperHelper.Signle <ContentDto, Content>(entity);

            using (_unitOfWork)
            {
                var repository      = _unitOfWork.Repository <Content>();
                var modelRepository = _unitOfWork.Repository <Model>();

                Expression <Func <Model, bool> > where = w => w.ModelId == entity.ModelId;
                var model = modelRepository.Get(where, "ModelFields");

                BuildContentField(content, model, dictionary);

                repository.Add(content);

                _unitOfWork.Commit();
            }
        }
예제 #14
0
        public async Task <NewsItemSource> GetNewsById(int id)
        {
            ContentDto news = await _oDataClient.For <ContentDto>("Contents")
                              .Function("GetNewsById")
                              .Set(new { newsId = id })
                              .FindEntryAsync();

            return(new NewsItemSource
            {
                Date = news.Date,
                Text = news.Text,
                Id = news.Id,
                NewsID = news.NewsID,
                Photo = news.Photo,
                Likes = news.Likes,
                Visits = news.Visits,
                Title = news.Title,
                YourLike = news.YourLike
            });
        }
예제 #15
0
        public void GetFolderContent_Method_Test_GetContent_Call_Once_With_Not_Null_Parameter_Return_Not_Null_Result()
        {
            // Arrange
            var model = new GetFolderContentViewModel()
            {
                FolderPath = "test"
            };
            var returnModel = new ContentDto();

            _contentService.Setup(f => f.GetContent(model.FolderPath)).Returns(returnModel);

            var controller = new FolderController(_contentService.Object, _mapper);

            // Act
            var result = controller.GetFolderContent();

            // Assert
            Assert.IsNotNull(result);
            _contentService.Verify(f => f.GetContent(model.FolderPath), Times.Once);
        }
예제 #16
0
        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="contentDto"></param>
        /// <param name="saveState"></param>
        /// <param name="dictionary"></param>
        public void HttpPostSave(ContentDto contentDto, SaveState saveState, Dictionary <string, object> dictionary)
        {
            switch (saveState.OperationState)
            {
            case OperationState.Add:
                _contentService.Add(contentDto, dictionary);
                break;

            case OperationState.Update:
                _contentService.Update(contentDto, dictionary);
                break;

            case OperationState.Remove:
                _contentService.Remove(saveState.Key);
                break;

            default:
                break;
            }
        }
        public void Add_Content_Return_Same_Content()
        {
            //Arrange
            var createCommand = new ContentCommand
            {
                ContentName   = "Foo:Posts",
                ContentFields = new Dictionary <string, string>
                {
                    { "Article", "Hello World" },
                    { "Body", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor" }
                }
            };
            var readQuery = new ContentQuery
            {
                ContentName = "Foo:Posts"
            };

            var expectedContent = new ContentDto
            {
                ContentName   = "Foo:Posts",
                ContentFields = new Dictionary <string, string>
                {
                    { "Article", "Hello World" },
                    { "Body", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor" }
                }
            };

            var contentService = GetContentService();
            var compareLogic   = new CompareLogic();

            //Act
            contentService.CreateContentAsync(createCommand).Wait();

            var retrievedContent = contentService.GetContentAsync(readQuery).Result;

            //Assert
            var compareResult = compareLogic.Compare(expectedContent, retrievedContent);

            Assert.IsTrue(compareResult.AreEqual,
                          $"Added and retrieved roles aren't identical differences are {string.Join(",", compareResult.Differences)}");
        }
        public void UpdateContent(ContentDto contentDto)
        {
            ContentDE content = _context.tbl_content.Where(x => x.ContentId == contentDto.ContentId).FirstOrDefault();

            if (content == null)
            {
                throw new AppException("ContentId does not exist");
            }

            if (!String.IsNullOrEmpty(contentDto.FileName) && String.IsNullOrEmpty(contentDto.Url))
            {
                throw new AppException("Url is empty for " + contentDto.FileName);
            }

            if (contentDto.Datetime > DateTime.MinValue)
            {
                content.Datetime = contentDto.Datetime;
            }

            if (!String.IsNullOrEmpty(contentDto.Title))
            {
                content.Title = contentDto.Title;
            }

            if (!String.IsNullOrEmpty(contentDto.Description))
            {
                content.Description = contentDto.Description;
            }

            if (!String.IsNullOrEmpty(contentDto.FileName))
            {
                content.FileName = contentDto.FileName;
            }

            if (!String.IsNullOrEmpty(contentDto.Url))
            {
                content.url = contentDto.Url;
            }

            _context.tbl_content.Update(content);
        }
        public ContentDto AddNewContent(ContentDto input)
        {
            using (var db = GetConnection())
            {
                db.Open();
                var result = db.Execute(@"Insert into Content 
                                                        ([Title]
                                                        ,[WebsiteDescription]
                                                        ,[Url])
                                                    Values
                                                        (@title
                                                        ,@WebsiteDescription
                                                        ,@url)", input);

                var createdContent = db.QueryFirstOrDefault <ContentDto>(@"select
                                                        top 1 *
                                                        from Content
                                                        order by Id DESC");
                return(createdContent);
            }
        }
예제 #20
0
        public async Task <IActionResult> GetContents(string app, string name, [FromQuery] bool archived = false, [FromQuery] string ids = null)
        {
            var context = Context().WithArchived(archived);

            var result = await contentQuery.QueryAsync(context, name, Q.Empty.WithIds(ids).WithODataQuery(Request.QueryString.ToString()));

            var response = new ContentsDto
            {
                Total = result.Total,
                Items = result.Take(200).Select(x => ContentDto.FromContent(x, context)).ToArray()
            };

            if (controllerOptions.Value.EnableSurrogateKeys && response.Items.Length <= controllerOptions.Value.MaxItemsForSurrogateKeys)
            {
                Response.Headers["Surrogate-Key"] = response.Items.ToSurrogateKeys();
            }

            Response.Headers["ETag"] = response.Items.ToManyEtag(response.Total);

            return(Ok(response));
        }
예제 #21
0
        public async Task <IActionResult> GetAllContents(string app, [FromQuery] string ids, [FromQuery] string status = null)
        {
            var context = Context().WithFrontendStatus(status);

            var result = await contentQuery.QueryAsync(context, Q.Empty.WithIds(ids).Ids);

            var response = new ContentsDto
            {
                Total = result.Count,
                Items = result.Take(200).Select(x => ContentDto.FromContent(x, context)).ToArray()
            };

            if (controllerOptions.Value.EnableSurrogateKeys && response.Items.Length <= controllerOptions.Value.MaxItemsForSurrogateKeys)
            {
                Response.Headers["Surrogate-Key"] = response.Items.ToSurrogateKeys();
            }

            Response.Headers[HeaderNames.ETag] = response.Items.ToManyEtag();

            return(Ok(response));
        }
예제 #22
0
        public async Task <IActionResult> GetContents(string app, string name, [FromQuery] bool archived = false, [FromQuery] string ids = null)
        {
            var context = Context().WithArchived(archived).WithSchemaName(name);

            var result = await contentQuery.QueryAsync(context, Query.Empty.WithIds(ids).WithODataQuery(Request.QueryString.ToString()));

            var response = new ContentsDto
            {
                Total = result.Total,
                Items = result.Take(200).Select(x => ContentDto.FromContent(x, context.Base)).ToArray()
            };

            var options = controllerOptions.Value;

            if (options.EnableSurrogateKeys && response.Items.Length <= options.MaxItemsForSurrogateKeys)
            {
                Response.Headers["Surrogate-Key"] = string.Join(" ", response.Items.Select(x => x.Id));
            }

            return(Ok(response));
        }
예제 #23
0
        public async Task <IActionResult> PostContent(string app, string name, [FromBody] NamedContentData request, [FromQuery] bool publish = false)
        {
            await contentQuery.ThrowIfSchemaNotExistsAsync(Context(), name);

            var publishPermission = Permissions.ForApp(Permissions.AppContentsPublish, app, name);

            if (publish && !User.Permissions().Includes(publishPermission))
            {
                return(new StatusCodeResult(123));
            }

            var command = new CreateContent {
                ContentId = Guid.NewGuid(), Data = request.ToCleaned(), Publish = publish
            };

            var context = await CommandBus.PublishAsync(command);

            var result   = context.Result <EntityCreatedResult <NamedContentData> >();
            var response = ContentDto.FromCommand(command, result);

            return(CreatedAtAction(nameof(GetContent), new { id = command.ContentId }, response));
        }
예제 #24
0
        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="saveState"></param>
        /// <returns></returns>
        public ContentDto HttpGetSave(SaveState saveState)
        {
            var contentDto = new ContentDto();

            switch (saveState.OperationState)
            {
            case OperationState.Add:
                break;

            case OperationState.Update:
                contentDto = _contentService.Query(saveState.Key);
                break;

            case OperationState.Remove:
                _contentService.Remove(saveState.Key);
                break;

            default:
                break;
            }
            return(contentDto);
        }
        public async Task <MContentResult <ContentDto> > AddAsync(ContentDto contentDto)
        {
            //Validate
            var validationResult = await _validationService.ValidateAdd(contentDto);

            if (!validationResult.IsValid)
            {
                return(validationResult.ConvertFromValidationResult <ContentDto>());
            }
            //Map to domain object
            var entityForDb = _mapper.Map <Content>(contentDto);
            var addedEntity = await _repository.AddAsync(entityForDb);

            var retrievedEntity = await _repository.GetByIdAsync(addedEntity.Id);

            //Map to dto
            var resultEntity = _mapper.Map <ContentDto>(retrievedEntity);

            ResultDto.Data       = resultEntity;
            ResultDto.StatusCode = (int)StatusCodes.Created;
            return(ResultDto);
        }
예제 #26
0
        public async Task <IActionResult> GetContents(string app, string name, [FromQuery] bool archived = false, [FromQuery] string ids = null)
        {
            HashSet <Guid> idsList = null;

            if (!string.IsNullOrWhiteSpace(ids))
            {
                idsList = new HashSet <Guid>();

                foreach (var id in ids.Split(','))
                {
                    if (Guid.TryParse(id, out var guid))
                    {
                        idsList.Add(guid);
                    }
                }
            }

            var context = Context().WithSchemaName(name).WithArchived(archived);

            var result =
                idsList?.Count > 0 ?
                await contentQuery.QueryAsync(context, idsList) :
                await contentQuery.QueryAsync(context, Request.QueryString.ToString());

            var response = new ContentsDto
            {
                Total = result.Total,
                Items = result.Take(200).Select(x => ContentDto.FromContent(x, context)).ToArray()
            };

            var options = controllerOptions.Value;

            if (options.EnableSurrogateKeys && response.Items.Length <= options.MaxItemsForSurrogateKeys)
            {
                Response.Headers["Surrogate-Key"] = string.Join(" ", response.Items.Select(x => x.Id));
            }

            return(Ok(response));
        }
예제 #27
0
        public IActionResult AddContent([FromBody] ContentDto contentDto)
        {
            if (!ModelState.IsValid)
            {
                // return 422
                return(new Helpers.UnprocessableEntityObjectResult(ModelState));
            }

            try
            {
                // save
                var contentFromRepo = _contentRepository.AddContent(contentDto);

                var contentToReturn = _mapper.Map <ContentDto>(contentFromRepo);

                return(Ok(contentToReturn));
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return(BadRequest(new { message = ex.Message }));
            }
        }
예제 #28
0
        /// <summary>
        /// Builds an IMedia item from a dto and content type.
        /// </summary>
        public static Core.Models.Media BuildEntity(ContentDto dto, IMediaType contentType)
        {
            var nodeDto           = dto.NodeDto;
            var contentVersionDto = dto.ContentVersionDto;

            var content = new Core.Models.Media(nodeDto.Text, nodeDto.ParentId, contentType);

            try
            {
                content.DisableChangeTracking();

                content.Id        = dto.NodeId;
                content.Key       = nodeDto.UniqueId;
                content.VersionId = contentVersionDto.Id;

                // TODO: missing names?

                content.Path      = nodeDto.Path;
                content.Level     = nodeDto.Level;
                content.ParentId  = nodeDto.ParentId;
                content.SortOrder = nodeDto.SortOrder;
                content.Trashed   = nodeDto.Trashed;

                content.CreatorId  = nodeDto.UserId ?? Cms.Core.Constants.Security.UnknownUserId;
                content.WriterId   = contentVersionDto.UserId ?? Cms.Core.Constants.Security.UnknownUserId;
                content.CreateDate = nodeDto.CreateDate;
                content.UpdateDate = contentVersionDto.VersionDate;

                // reset dirty initial properties (U4-1946)
                content.ResetDirtyProperties(false);
                return(content);
            }
            finally
            {
                content.EnableChangeTracking();
            }
        }
        public async Task <MContentValidationResult> ValidateAdd(ContentDto contentDto)
        {
            //Retrive data for validation
            var contentWithSimilarId = await _contentRepository.GetByIdAsync(contentDto.Id);//тут можно в запросе для валидации использовать Any(), чтобы не возврашать сущность, она все равно тут не нужна

            Content contentWithSimilarTitle = null;
            var     isParsable = EnumUtils.TryParseWithMemberName <ContentType>(contentDto.Type, out _);

            if (isParsable)
            {
                var parsedType = EnumUtils.GetEnumValueOrDefault <ContentType>(contentDto.Type);
                contentWithSimilarTitle = await _contentRepository.GetByTitleAndType(contentDto.Title, parsedType);
            }
            // смотри выше
            var correnspondingAuthorsInDb = await GetCorrespondingAuthorsAsync(contentDto.Authors);

            ValidationResult.Errors = new List <string>
            {
                _contentRules.ValidateGuidIfDefault(contentDto.Id),
                _contentRules.ValidateIfNullOrEmpty(contentDto.Id.ToString()),
                _contentRules.ValidateUniqueContentId(contentWithSimilarId),
                _contentRules.ValidateIfNullOrEmpty(contentDto.Title),
                _contentRules.ValidateUniqueTitleOfItsType(contentWithSimilarTitle),
                _contentRules.ValidateIfNullOrEmpty(contentDto.Type.ToString()),
                _contentRules.ValidateTypeRange(contentDto.Type),
                _authorRules.ValidateIfAnyAuthorExists(contentDto.Authors),
                _authorRules.ValidateMatchingAuthors(correnspondingAuthorsInDb, contentDto.Authors),
                _authorRules.ValidateAgainstDuplicates(contentDto.Authors)
            }.Where(e => !string.IsNullOrEmpty(e)).ToList();

            if (!ValidationResult.IsValid)
            {
                ValidationResult.StatusCode = (int)StatusCodes.BadRequest;
            }
            return(ValidationResult);
        }
예제 #30
0
        public IActionResult UpdateContent([FromBody] ContentDto contentDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    // return 422
                    return(new Helpers.UnprocessableEntityObjectResult(ModelState));
                }

                _contentRepository.UpdateContent(contentDto);

                if (!_contentRepository.Save())
                {
                    throw new AppException("Updating content failed on save.");
                }

                return(Ok());
            }
            catch (AppException ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }