Exemplo n.º 1
0
        public async Task <IActionResult> Create([Bind("Id,Title")] Category category, [FromQuery] string from = null)
        {
            if (ModelState.IsValid)
            {
                var existingCategory = await _context
                                       .Categories
                                       .SingleOrDefaultAsync(c => c.Title.Equals(category.Title, StringComparison.OrdinalIgnoreCase));

                if (existingCategory.IsNotNull())
                {
                    ModelState.AddModelError("Error", $"A category with the title \"{category.Title}\" already exists.");
                    return(View(existingCategory));
                }

                category.Url = CustomUrlHelper.URLFriendly(category.Title);

                _context.Categories.Add(category);

                await _context.SaveChangesAsync();

                await _context.SaveChangesAsync();

                return(RedirectToAction("Details", new { Id = category.Id, from }));
            }
            ViewData["from"] = from;
            return(View(category));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Category,Title,Description,Tags")] PolicyViewModel policyVM)
        {
            if (id != policyVM?.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                var entity = await _context.Policies
                             .Include(f => f.Category)
                             .SingleOrDefaultAsync(c => c.Id == id);

                if (entity.IsNull())
                {
                    return(NotFound());
                }

                if (!entity.Category.Title.Equals(policyVM.Category.Title, StringComparison.OrdinalIgnoreCase))
                {
                    var category = await _context.Categories.SingleOrDefaultAsync(c => c.Title.Equals(policyVM.Category.Title, StringComparison.OrdinalIgnoreCase));

                    if (category.IsNotNull())
                    {
                        entity.Category = category;
                    }
                    else
                    {
                        entity.Category = new Category
                        {
                            Title = policyVM.Category.Title,
                            Url   = CustomUrlHelper.URLFriendly(policyVM.Category.Title),
                        };
                    }
                }

                entity.Title       = policyVM.Title;
                entity.Description = policyVM.Description;

                var file = Request.Form.Files.SingleOrDefault();

                if (file.IsNotNull())
                {
                    var filename = await _fileStorageService.SetBlobAsync(file);

                    entity.FileUrl = filename;
                }

                var tags           = TagHelpers.GetTagsFromString(policyVM.Tags);
                var allTagEntities = GetAllTagEntitiesInternal(policyVM, tags);
                TagHelpers.SetTags <Policy, PolicyTag>(tags, entity, allTagEntities);

                await _context.SaveChangesAsync();

                return(RedirectToAction("Details", new { Id = entity.Id }));
            }
            return(View(policyVM));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Create([Bind("Id,Category,Title,Description,Tags")] PolicyViewModel policyVM)
        {
            if (ModelState.IsValid)
            {
                var category = await _context
                               .Categories
                               .SingleOrDefaultAsync(c => c.Title.Equals(policyVM.Category.Title, StringComparison.OrdinalIgnoreCase));

                if (category.IsNotNull())
                {
                    policyVM.Category = category;
                }
                else
                {
                    policyVM.Category = new Category
                    {
                        Title = policyVM.Category.Title,
                        Url   = CustomUrlHelper.URLFriendly(policyVM.Category.Title),
                    };
                }

                var policy = new Policy
                {
                    Category    = policyVM.Category,
                    Description = policyVM.Description,
                    FileUrl     = policyVM.FileUrl,
                    Title       = policyVM.Title,
                    Url         = CustomUrlHelper.URLFriendly(policyVM.Title),
                };

                var file = Request.Form.Files.SingleOrDefault();

                if (file.IsNotNull())
                {
                    var filename = await _fileStorageService.SetBlobAsync(file);

                    policy.FileUrl = filename;
                }

                var tags           = TagHelpers.GetTagsFromString(policyVM.Tags);
                var allTagEntities = GetAllTagEntitiesInternal(policyVM, tags);
                TagHelpers.SetTags <Policy, PolicyTag>(tags, policy, allTagEntities);

                await _context.AddAsync(policy);

                await _context.SaveChangesAsync();

                return(RedirectToAction("Details", new { Id = policy.Id }));
            }
            ViewData["Categories"] = new SelectList(_context.Categories, nameof(Category.Id), nameof(Category.Title));
            return(View(policyVM));
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Category,Question,Answer,Url")] FaqViewModel faqVM)
        {
            if (id != faqVM?.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                var entity = await _context.Faqs
                             .Include(f => f.Category)
                             .SingleOrDefaultAsync(c => c.Id == id);

                if (entity.IsNull())
                {
                    return(NotFound());
                }

                if (!entity.Category.Title.Equals(faqVM.Category.Title, StringComparison.OrdinalIgnoreCase))
                {
                    var category = await _context.Categories.SingleOrDefaultAsync(c => c.Title.Equals(faqVM.Category.Title, StringComparison.OrdinalIgnoreCase));

                    if (category.IsNotNull())
                    {
                        entity.Category = category;
                    }
                    else
                    {
                        entity.Category = new Category
                        {
                            Title = faqVM.Category.Title,
                            Url   = CustomUrlHelper.URLFriendly(faqVM.Category.Title),
                        };
                    }
                }

                entity.Answer   = faqVM.Answer;
                entity.Question = faqVM.Question;

                var tags           = TagHelpers.GetTagsFromString(faqVM.Tags);
                var allTagEntities = GetAllTagEntitiesInternal(faqVM, tags);
                TagHelpers.SetTags <Faq, FaqTag>(tags, entity, allTagEntities);

                await _context.SaveChangesAsync();

                return(RedirectToAction("Details", new { Id = entity.Id }));
            }
            return(View(faqVM));
        }
Exemplo n.º 5
0
        public async Task <IActionResult> Create([Bind("Category,Question,Answer,Tags")] FaqViewModel faqVM)
        {
            if (ModelState.IsValid)
            {
                var category = await _context
                               .Categories
                               .SingleOrDefaultAsync(c => c.Title.Equals(faqVM.Category.Title, StringComparison.OrdinalIgnoreCase));

                if (category.IsNotNull())
                {
                    faqVM.Category = category;
                }
                else
                {
                    faqVM.Category = new Category
                    {
                        Title = faqVM.Category.Title,
                        Url   = CustomUrlHelper.URLFriendly(faqVM.Category.Title),
                    };
                }

                var faq = new Faq
                {
                    Answer   = faqVM.Answer,
                    Category = faqVM.Category,
                    Question = faqVM.Question,
                    Url      = CustomUrlHelper.URLFriendly(faqVM.Question),
                };

                var tags           = TagHelpers.GetTagsFromString(faqVM.Tags);
                var allTagEntities = GetAllTagEntitiesInternal(faqVM, tags);
                TagHelpers.SetTags <Faq, FaqTag>(tags, faq, allTagEntities);

                await _context.AddAsync(faq);

                await _context.SaveChangesAsync();

                return(RedirectToAction("Details", new { Id = faq.Id }));
            }
            ViewData["Categories"] = new SelectList(_context.Categories, nameof(Category.Id), nameof(Category.Title));
            return(View(faqVM));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Create([Bind("Title,Text,Published,HeaderImage,Tags")] NewsViewModel news)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View(news));
                }

                var image = Request.Form.Files.SingleOrDefault(f => f.ContentType.Contains("image"));

                if (image.IsNotNull())
                {
                    var filename = await _fileStorageService.SetImageAsync(image);

                    news.HeaderImage = new Image {
                        FileName = filename
                    };
                }

                var username    = HttpContext.User.GetUsername();
                var displayName = HttpContext.User.GetDisplayName();

                if (_context.Users.Find(username) == null)
                {
                    var user = new User
                    {
                        Username    = username,
                        DisplayName = displayName,
                    };

                    _context.Users.Add(user);
                }

                var newNews = new News
                {
                    Title     = news.Title,
                    Text      = news.Text,
                    UserId    = username,
                    Published = news.Published,
                    Url       = CustomUrlHelper.URLFriendly(news.Title),
                };

                if (!String.IsNullOrWhiteSpace(news.HeaderImage?.FileName))
                {
                    newNews.HeaderImage = new Image
                    {
                        FileName = news.HeaderImage.FileName
                    };
                }

                newNews.Created = _dateTimeFactory.DateTimeOffsetUtc;

                var isTitleAndDateUniqe = !_context.News.Any(n => n.Created.Date == newNews.Created.Date && n.Url == newNews.Url);

                if (!isTitleAndDateUniqe)
                {
                    ModelState.AddModelError("error", "There has already been created a news with that title today!");
                    HttpContext.Response.StatusCode = StatusCodes.Status422UnprocessableEntity;
                    return(View(news));
                }

                var tags           = TagHelpers.GetTagsFromString(news.Tags);
                var allTagEntities = GetAllTagEntitiesInternal(news, tags);
                TagHelpers.SetTags <News, NewsTag>(tags, newNews, allTagEntities);

                _context.News.Add(newNews);
                await _context.SaveChangesAsync();

                var newsViewModel = new NewsViewModel(newNews);

                return(RedirectToAction("Details", new { id = newNews.Id }));
            }
            catch (Exception)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Exemplo n.º 7
0
        // TODO: Add tests
        /// <summary>
        /// Adds tags to <paramref name="entity"/> based on <paramref name="tags"/>.
        /// </summary>
        /// <param name="tags"></param>
        /// <param name="entity"></param>
        /// <param name="allTagEntities"></param>
        public static void SetTags <TEntity, TRelation>(IEnumerable <string> tags, TEntity entity, ICollection <Tag> allTagEntities)
            where TEntity : IHasTags
            where TRelation : class, ITagRelation
        {
            if (tags.IsNull())
            {
                return;
            }

            var nameOfEntity          = entity.GetType().Name;
            var nameOfJoiningProperty = $"{nameOfEntity}{nameof(Tag)}s";                                                 // ie NewsTags

            var joiningTableType = typeof(Tag).GetProperty(nameOfJoiningProperty).PropertyType.GetGenericArguments()[0]; // ie NewsTag

            // Get all tag entities that already is created
            var exisitingTagEntities = allTagEntities?
                                       .Where(k => tags.Contains(k.Name, StringComparer.OrdinalIgnoreCase))
                                       ?? new List <Tag>();

            // Get a list of all tags that is already attached to the entity to avoid duplicates etc
            var alreadyAttachedTagEntities = exisitingTagEntities?
                                             .Where(k =>
                                                    GetJoiningCollectionInternal <TRelation>(k, nameOfJoiningProperty)?
                                                    .Any(jt => GetEntityInternal <TEntity>(jt, nameOfEntity).Id == entity.Id) == true
                                                    );

            // Get all joining tables, ie NewsTag, that is already attached
            var alreadyAttachedJoiningTagEntities = exisitingTagEntities?
                                                    .SelectMany(k => GetJoiningCollectionInternal <TRelation>(k, nameOfJoiningProperty))?
                                                    .Where(jt => GetEntityInternal <TEntity>(jt, nameOfEntity).Id == entity.Id) ?? new List <TRelation>();

            // Get all existing tags as strings compare them to the param to avoid creating them again
            var existingTags = exisitingTagEntities?
                               .Select(k => k.Name) ?? new List <string>();

            // Finally we have a list of all tags we have to create
            var newTags = tags?.Except(existingTags);

            // Create entities
            var newTagEntities = newTags?
                                 .Select(name => new Tag
            {
                Name = name,
                Url  = CustomUrlHelper.URLFriendly(name),
            });

            // Get a list of all tag entities that have be attached to the entity
            var allTagEntitiesToBeAttached = exisitingTagEntities
                                             .Except(alreadyAttachedTagEntities)
                                             .Concat(newTagEntities ?? new List <Tag>());

            // Create new relations between the tag entities and the entity (many-to-many)
            var joiningTagEntities = allTagEntitiesToBeAttached?
                                     .Select(k => Activator.CreateInstance(joiningTableType, k))?
                                     // Add all old entities that is already attached (meaning there already exists entities for them)
                                     .Concat(alreadyAttachedJoiningTagEntities)?
                                     .Select(k => k as TRelation)?
                                     .ToList();

            // Set the new list of relationship entities to the correct property of the entity
            entity.GetType().GetProperty(nameOfJoiningProperty).SetValue(entity, joiningTagEntities);
        }