public ActionResult Create([Bind(Include = "TicketId")] TicketAttachment ticketAttachment, HttpPostedFileBase FilePath, string attachmentDescription)
        {
            ticketAttachment.Description = attachmentDescription;
            ticketAttachment.Created     = DateTime.Now;
            ticketAttachment.UserId      = User.Identity.GetUserId();


            if (ModelState.IsValid)
            {
                //Use Attachment Upload Validator to verify file
                if (ImageUploader.IsValidAttachment(FilePath))
                {
                    var fileName      = Path.GetFileName(FilePath.FileName);
                    var ext           = Path.GetExtension(FilePath.FileName);
                    var unique        = $"{fileName}-{DateTime.Now}";
                    var slug          = SlugHelper.CreateSlug(unique);
                    var formattedFile = $"{slug}{ext}";
                    FilePath.SaveAs(Path.Combine(Server.MapPath("~/Attachments/"), formattedFile));
                    ticketAttachment.FilePath = "/Attachments/" + formattedFile;
                }

                db.TicketAttachments.Add(ticketAttachment);
                db.SaveChanges();
                return(RedirectToAction("Dashboard", "Home"));
            }

            ViewBag.TicketId = new SelectList(db.Tickets, "Id", "Title", ticketAttachment.TicketId);
            ViewBag.UserId   = new SelectList(db.Users, "Id", "FirstName", ticketAttachment.UserId);
            return(View(ticketAttachment));
        }
示例#2
0
        public static Province Upsert(Province entity)
        {
            if (null == entity)
            {
                return(null);
            }
            else if (string.IsNullOrWhiteSpace(entity.Name))
            {
                return(null);
            }
            else if (string.IsNullOrWhiteSpace(entity.Slug))
            {
                SlugHelper slugger = new SlugHelper();
                entity.Slug = slugger.GenerateSlug(entity.Name);
            }

            Province province = Find(entity);

            if (null == province)
            {
                Insert(entity);
                return(entity);
            }
            else
            {
                Province.ShallowCopy(province, entity);
                Update(province);
            }

            return(province);
        }
示例#3
0
        public ActionResult Create(Blog blog)
        {
            if (!AuthorizeUser())
            {
                return(RedirectToAction("Login", "Accounts"));
            }

            try
            {
                SlugHelper slugHelper = new SlugHelper();

                blog.UserID   = int.Parse(Session["user_id"].ToString());
                blog.UrlField = slugHelper.GenerateSlug(blog.Title);
                repo.Insert(blog);
                return(RedirectToAction("Index"));
            }
            catch
            {
                var topicSelectList = new SelectList(topicRepo.GetAll(), "BlogTopicID", "Name", "1");
                ViewBag.topicSelectList = topicSelectList;

                ViewBag.Message = "Failed to create a new blog.";
                return(View());
            }
        }
示例#4
0
        public ActionResult Edit(int id, Blog blog)
        {
            if (!AuthorizeUser())
            {
                return(RedirectToAction("Login", "Accounts"));
            }

            try
            {
                SlugHelper slugHelper = new SlugHelper();

                Blog b = repo.Get(id);
                b.Title       = blog.Title;
                b.Description = blog.Description;
                b.UrlField    = slugHelper.GenerateSlug(blog.Title);
                b.TopicID     = blog.TopicID;
                b.Private     = blog.Private;

                repo.Update(b);
                return(RedirectToAction("Index"));
            }
            catch
            {
                var topicSelectList = new SelectList(topicRepo.GetAll(), "BlogTopicID", "Name", "1");
                ViewBag.topicSelectList = topicSelectList;

                return(View());
            }
        }
        public void ShouldProvideValidRepresentationOfTimeStampFromDate()
        {
            var targetDate = DateTime.UtcNow;
            var dateSlug   = SlugHelper.GenerateSlug(targetDate);

            Assert.IsNotNullOrEmpty(dateSlug);
        }
示例#6
0
        static Class()
        {
            var config = new SlugHelper.Config();

            config.StringReplacements[" "] = "_";
            _slugHelper = new SlugHelper(config);
        }
示例#7
0
        public ActionResult Create(PostViewModel viewModel)
        {
            PrepareDropdownList(viewModel);
            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }

            var post = new Post
            {
                DateCreated = DateTime.Now,
                Views       = 0,
                Slug        = SlugHelper.ToUnsignString(viewModel.Title)
            };

            post.Modify(viewModel.Title, viewModel.Descriptions,
                        viewModel.Content, viewModel.CategoryId,
                        viewModel.MetaDescription, viewModel.MetaKeyword, viewModel.IsPopularPost);

            _unitOfWork.Posts.Add(post);

            _unitOfWork.Complete();

            return(RedirectToAction("Index"));
        }
示例#8
0
        public ActionResult ChangeUserProfile([Bind(Include = "Id,FirstName,LastName,AvatarPath,Email")] UserProfileViewModel profile, HttpPostedFileBase AvatarPath)
        {
            if (ModelState.IsValid)
            {
                var currentUser = db.Users.Find(profile.Id);
                //Avatar Validator
                //profile picture setting
                if (ImageUploader.IsWebFriendlyImage(AvatarPath))
                {
                    var fileName = Path.GetFileName(AvatarPath.FileName);
                    var ext      = Path.GetExtension(AvatarPath.FileName);
                    //extended this to format the image file with an always unique title
                    var unique        = $"{fileName}-{DateTime.Now}";
                    var slug          = SlugHelper.CreateSlug(unique);
                    var formattedFile = $"{slug}{ext}";
                    AvatarPath.SaveAs(Path.Combine(Server.MapPath("~/Avatars/"), formattedFile));
                    //save formatted version to the register viewmodel
                    currentUser.AvatarPath = "/Avatars/" + formattedFile;
                }
                else
                {
                    currentUser.AvatarPath = profile.AvatarPath;
                }

                currentUser.FirstName = profile.FirstName;
                currentUser.LastName  = profile.LastName;
                currentUser.Email     = profile.Email;
                db.SaveChanges();
                return(RedirectToAction("Dashboard", "Home"));
            }
            else
            {
                return(RedirectToAction("ChangesNotSaved", "Home"));
            }
        }
示例#9
0
        public async Task <IActionResult> Create(Post post, int[] SelectedCategoryIds)
        {
            var rand = new Random();
            var slug = SlugHelper.GenerateSlug(post.Title);

            while (await context.Posts.AnyAsync(t => t.Slug == slug))
            {
                slug += rand.Next(1000, 9999);
            }
            post.Slug = slug;
            foreach (var selectedCatId in SelectedCategoryIds)
            {
                post.PostCategories.Add(new PostCategory {
                    CategoryId = selectedCatId
                });
            }
            if (!ModelState.IsValid)
            {
                return(View());
            }
            await context.AddAsync(post);

            await context.SaveChangesAsync();

            TempData["message.success"] = "Saved!";
            return(RedirectToAction(nameof(Index)));
        }
示例#10
0
        //// Tag Cloud using sparc.tagcloud (lemmatisation)
        //private List<TagCloudTag> GenerateTagCloud()
        //{
        //    var analyzer = new TagCloudAnalyzer();

        //    var blogPostTags = _blogDbContext
        //                       .Tags
        //                       .Select(t => t.DisplayName)
        //                       .ToList();

        //    // blogPosts is an IEnumerable<String>, loaded from
        //    // the database.
        //    var tags = analyzer.ComputeTagCloud(blogPostTags);

        //    // Shuffle the tags, if you like for a random
        //    // display
        //    tags = tags.Shuffle();

        //    return tags.ToList();
        //}

        // Tag Cloud and tag information generated without sparc.tagcloud
        private List <TagInfo> GenerateTagInfo()
        {
            var blogPostTags = _blogDbContext
                               .Tags
                               .Select(t => t.DisplayName)
                               .ToList();

            var groupTags = blogPostTags.GroupBy(t => t)
                            .OrderBy(t => t.Count());

            var maxTagCount = groupTags.Last().Count();

            var randomGroup = groupTags.OrderBy(a => Guid.NewGuid());

            var tagInfoList = new List <TagInfo>();

            foreach (var tag in randomGroup)
            {
                var helper  = new SlugHelper();
                var tagInfo = new TagInfo()
                {
                    DisplayName = tag.Key,
                    TagCount    = tag.Count(),
                    Category    = GenerateCategory(tag.Count(), maxTagCount),
                    UrlSlug     = helper.GenerateSlug(tag.Key)
                };

                tagInfoList.Add(tagInfo);
            }

            return(tagInfoList);
        }
示例#11
0
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new BlogDbContext(serviceProvider.GetRequiredService <DbContextOptions <BlogDbContext> >()))
            {
                SlugHelper helper = new SlugHelper();

                if (!context.Users.Any())
                {
                    context.Users.AddRange
                    (
                        new User
                    {
                        Id       = Guid.NewGuid(),
                        Email    = "*****@*****.**",
                        Username = "******",
                        Password = BCrypt.Net.BCrypt.HashPassword("Zoe1811")
                    },
                        new User
                    {
                        Id       = Guid.NewGuid(),
                        Email    = "*****@*****.**",
                        Username = "******",
                        Password = BCrypt.Net.BCrypt.HashPassword("Zoe1811")
                    }
                    );
                }
                context.SaveChanges();
            }
        }
示例#12
0
文件: Page.cs 项目: jeswin/AgileFx
        public static Page Create(string title, User author, string contentType, string contents, Template template, Category category, string[] tags, bool allowComments, PermissionSet permSet)
        {
            var page = new Page
            {
                Title           = title,
                Author          = author,
                DisplayTemplate = template,
                ContentType     = contentType,
                Category        = category,
                Tags            = string.Format("|{0}|", string.Join("|", tags)),
                AllowComments   = allowComments,
                DateTime        = DateTime.Now,
                Tenant          = category.Tenant,
                UniquePath      = category.UniquePath + SlugHelper.Generate(title) + "/",
                PermissionSet   = permSet
            };

            page.Revisions.Add(new Revision
            {
                Contents = contents,
                DateTime = DateTime.Now,
                Tenant   = category.Tenant
            });
            page.SetHtml();
            return(page);
        }
        public async Task <IActionResult> PutForum(int id, Forum forum)
        {
            if (id != forum.Id)
            {
                return(BadRequest());
            }

            var slugHelper = new SlugHelper();

            forum.Slug = slugHelper.GenerateSlug(forum.Title);

            _context.Entry(forum).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ForumExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
示例#14
0
        protected async Task <string> GenerateSlug(
            string name,
            int?id = null,
            CancellationToken cancellationToken = default)
        {
            // Though not compulsory, since multiple todo-items with the same name will probably be created but will have different execution day or time
            // In order to reduce the chance of collision with existing slugs, a random string is appended to the slug name.
            var randomString = RandomStringGenerator.Get(7);
            var slug         = new SlugHelper().GenerateSlug($"{name} ${randomString}");

            // Ensure uniqueness
            List <string> similarSlugs = await DbSet
                                         .Where(todoItem => todoItem.Id != id)
                                         .Where(todoItem => EF.Functions.Like(todoItem.Slug, $"{slug}%"))
                                         .Select(todoItem => todoItem.Slug).AsNoTracking().ToListAsync(cancellationToken);

            if (!similarSlugs.Contains(slug))
            {
                return(slug);
            }

            var alternativeSlug = "";
            var suffix          = 2;

            do
            {
                alternativeSlug = $"{slug}-{suffix}";
                suffix++;
            } while(similarSlugs.Contains(alternativeSlug));

            return(alternativeSlug);
        }
示例#15
0
        public static Country Upsert(Country entity)
        {
            if (null == entity)
            {
                return(null);
            }
            else if (string.IsNullOrWhiteSpace(entity.Name))
            {
                return(null);
            }
            else if (string.IsNullOrWhiteSpace(entity.Slug))
            {
                SlugHelper slugger = new SlugHelper();
                entity.Slug = slugger.GenerateSlug(entity.Name);
            }

            Country country = Find(entity);

            if (null == country)
            {
                Insert(entity);
                return(entity);
            }
            else
            {
                Country.ShallowCopy(country, entity);
                Update(country);
            }

            return(country);
        }
示例#16
0
 public PostViewModel()
 {
     if (Title != null)
     {
         Slug = SlugHelper.ToUnsignString(Title);
     }
 }
示例#17
0
        public void TestFullFunctionality()
        {
            SlugHelper helper = new SlugHelper();
            Dictionary <string, string> tests = new Dictionary <string, string>();

            tests.Add("E¢Ðƕtoy  mÚÄ´¨ss¨sïuy   !!!!!  Pingüiño",
                      "etoy-muasssiuy--pinguino");

            tests.Add("QWE dfrewf# $%&!! asd",
                      "qwe-dfrewf--asd");

            tests.Add("You can't have any pudding if you don't eat your meat!",
                      "you-cant-have-any-pudding-if-you-dont-eat-your-meat");

            tests.Add("El veloz murciélago hindú",
                      "el-veloz-murcielago-hindu");

            tests.Add("Médicos sin medicinas medican meditando",
                      "medicos-sin-medicinas-medican-meditando");

            foreach (KeyValuePair <string, string> test in tests)
            {
                Assert.AreEqual(test.Value, helper.GenerateSlug(test.Key));
            }
        }
示例#18
0
        public static District Upsert(District entity)
        {
            if (null == entity)
            {
                return(null);
            }
            else if (string.IsNullOrWhiteSpace(entity.Name))
            {
                return(null);
            }
            else if (string.IsNullOrWhiteSpace(entity.Slug))
            {
                SlugHelper slugger = new SlugHelper();
                entity.Slug = slugger.GenerateSlug(entity.Name);
            }

            District district = Find(entity);

            if (null == district)
            {
                Insert(entity);
                return(entity);
            }
            else
            {
                District.ShallowCopy(district, entity);
                Update(district);
            }

            return(district);
        }
        public IActionResult Create(PostCreateViewModel newspost, int[] SelectedCategoryIds, int[] SelectedTagIds)
        {
            var rand = new Random();
            var slug = SlugHelper.GenerateSlug(newspost.Name);

            while (_context.Posts.Any(t => t.Slug == slug))
            {
                slug += rand.Next(1000, 9999);
            }
            newspost.Slug = slug;


            foreach (var selectedCatId in SelectedCategoryIds)
            {
                newspost.PostCategories.Add(new PostCategory {
                    CategoryId = selectedCatId
                });
            }

            foreach (var selectedTagId in SelectedTagIds)
            {
                newspost.PostTags.Add(new PostTag {
                    TagId = selectedTagId
                });
            }



            string unique = fileUpload(newspost.Picture);



            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var user   = _context.Users.Single(u => u.Id == userId);

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

            var postModel = new Post
            {
                Content        = newspost.Content,
                Name           = newspost.Name,
                Categories     = newspost.Categories,
                Tags           = newspost.Tags,
                PostCategories = newspost.PostCategories,
                PostStatus     = newspost.PostStatus,
                Picture        = unique,
                PostTags       = newspost.PostTags,
                Slug           = newspost.Slug,
                AppUser        = user
            };

            _context.Add(postModel);
            _context.SaveChanges();

            return(RedirectToAction(nameof(Index)));
        }
示例#20
0
 public Topic(string title, string content, string categoryId, string authorId)
 {
     Title      = title;
     Content    = content;
     CategoryId = categoryId;
     AuthorId   = authorId;
     Slug       = SlugHelper.Create(Title);
 }
示例#21
0
        public string SlugifyTheTitle(string title)
        {
            SlugHelper slugHelper = new SlugHelper();
            string     slugfyed   = slugHelper.GenerateSlug(title);

            //check unique return reccomend
            return(slugfyed);
        }
示例#22
0
        public async Task <string> GetUniqueSlugAsync(string slug, Guid?bookId = null)
        {
            var booksWithSameSlugs = await _unitOfWork.BookRepository.FindByAsync(o => o.Id != bookId && o.Slug.StartsWith(slug));

            var existingSlugs = booksWithSameSlugs.Select(o => o.Slug);

            return(SlugHelper.GetUniqueSlug(slug, existingSlugs));
        }
示例#23
0
        public static string GenerateSlug(string text)
        {
            SlugHelper slugGenerator = new SlugHelper();

            var slug = slugGenerator.GenerateSlug(text);

            return(slug);
        }
示例#24
0
        public void TestWhiteSpaceCollapsing()
        {
            const string original = "a  b    \n  c   \t    d";
            const string expected = "a-b-c-d";

            var helper = new SlugHelper();

            Assert.Equal(expected, helper.GenerateSlug(original));
        }
示例#25
0
        public void TestLoweCaseEnforcement()
        {
            const string original = "AbCdE";
            const string expected = "abcde";

            var helper = new SlugHelper();

            Assert.Equal(expected, helper.GenerateSlug(original));
        }
示例#26
0
        public void TestConfigForCollapsingDashes()
        {
            const string original = "foo & bar";
            const string expected = "foo-bar";

            var helper = new SlugHelper();

            Assert.Equal(expected, helper.GenerateSlug(original));
        }
示例#27
0
        public void TestDiacriticRemoval()
        {
            const string withDiacritics    = "ñáîùëÓ";
            const string withoutDiacritics = "naiueo";

            var helper = new SlugHelper();

            Assert.Equal(withoutDiacritics, helper.GenerateSlug(withDiacritics));
        }
示例#28
0
        public void TestConfigForCollapsingDashesWithMoreThanTwoDashes()
        {
            const string original = "foo & bar & & & Jazz&&&&&&&&";
            const string expected = "foo-bar-jazz";

            var helper = new SlugHelper();

            Assert.Equal(expected, helper.GenerateSlug(original));
        }
示例#29
0
 private static long?Get(string name)
 {
     using (var ctx = new DatabaseContext(Config.DB_CONNECTION_STRING))
     {
         var slug = new SlugHelper().GenerateSlug(name);
         var term = ctx.WP_Terms.FirstOrDefault(x => x.slug == slug);
         return(term != null ? term.term_id : (long?)null);
     }
 }
示例#30
0
        public void TestDeniedCharacterDeletion()
        {
            const string original = "!#$%&/()=";
            const string expected = "";

            var helper = new SlugHelper();

            Assert.Equal(expected, helper.GenerateSlug(original));
        }
示例#31
0
        public static string SlugFromTitle(string title)
        {
            var slugGenerator = new SlugHelper();

            return slugGenerator.GenerateSlug(title);
        }