コード例 #1
0
        /// <summary>
        /// Delete a blogpost from the DB
        /// </summary>
        /// <param name="blogpost">The Blogpost to delete from the DB</param>
        public async Task DeleteBlogpost(Blogpost blogpost)
        {
            #region Properties

            _timespan = Stopwatch.StartNew();

            #endregion

            Blogpost blogpostToDelete = await(from b in _dbContext.Blogposts
                                              where  b.BlogpostId == blogpost.BlogpostId &&
                                              b.RowVersion == blogpost.RowVersion
                                              select b).FirstOrDefaultAsync();
            #region Concurrency (null) Check

            if (blogpostToDelete == null)
            {
                throw new DbUpdateConcurrencyException();
            }

            #endregion

            _dbContext.Entry(blogpostToDelete).State = EntityState.Deleted;
            await Save();

            #region Logging

            _timespan.Stop();
            _log.TraceApi("Blogpost Service", "BlogpostRepository.DeleteBlogpost", _timespan.Elapsed, "Blogpost Id = {0}", blogpost.BlogpostId);
            _timespan.Reset();

            #endregion
        }
コード例 #2
0
ファイル: Delete.cshtml.cs プロジェクト: SeppPenner/Ogma
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            // Get logged in user
            var uid   = User.GetNumericId();
            var uname = User.GetUsername();

            if (uid == null || uname == null)
            {
                return(Unauthorized());
            }

            // Get post and make sure the user matches
            Blogpost = await _context.Blogposts
                       .Where(b => b.Id == id && b.AuthorId == uid)
                       .Include(b => b.CommentsThread)
                       .FirstOrDefaultAsync();

            if (Blogpost == null)
            {
                return(RedirectToPage("/User/Blog", new { name = uname }));
            }

            _context.Blogposts.Remove(Blogpost);
            await _context.SaveChangesAsync();

            return(RedirectToPage("/User/Blog", new { name = uname }));
        }
コード例 #3
0
        public async Task <IHttpActionResult> Edit(Blogpost model)
        {
            var cats = db.Categories;

            if (!cats.Any(c => c.Name == model.Category.Name))
            {
                var newCat = new Category()
                {
                    Name = model.Category.Name
                };
                db.Categories.Add(newCat);
                await db.SaveChangesAsync();

                model.Category.Id = newCat.Id;
            }
            else
            {
                model.Category.Id = model.Category.Id;
                model.Category    = null;
            }

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

            model.Updated         = DateTimeOffset.UtcNow;
            db.Entry(model).State = EntityState.Modified;
            await db.SaveChangesAsync();

            return(Ok());
        }
コード例 #4
0
        private static Document BlogpostToDocument(Blogpost blogpost)
        {
            var doc = new Document();

            var id         = blogpost.Id.ToString();
            var pageTitle  = blogpost.PageTitle;
            var categories = blogpost.Categories?.ToList();
            var excerpt    = blogpost.Excerpt;
            var url        = blogpost.Url;
            var createDate = blogpost.CreateDate;

            var dataObject = new BlogpostDataModel
            {
                Id         = id,
                Url        = url,
                Name       = pageTitle,
                Excerpt    = excerpt,
                Categories = categories,
                CreateDate = createDate
            };

            var data = JsonConvert.SerializeObject(dataObject, _jsonSerializerSettings);

            doc.Add(new Field("Id", id, Field.Store.NO, Field.Index.NOT_ANALYZED, Field.TermVector.NO));
            doc.Add(new Field("Data", data, Field.Store.YES, Field.Index.NO, Field.TermVector.NO));

            return(doc);
        }
コード例 #5
0
ファイル: App.cs プロジェクト: elinmj/AcceleratedLearning
        private void PageUpdateBlogPost()
        {
            Header("Uppdatera bloggpost");

            List <Blogpost> list = dataAccess.GetAllBlogPostsBrief();

            PrintAllBlogPostBrief(list);

            int index = ShowMenueChooseBloggpost();

            Blogpost blogpost = list[index - 1];

            WriteLine("Den nuvarande titeln är: " + blogpost.Title);

            WriteLine("Ange ny titel");

            string newTitle = Console.ReadLine();

            blogpost.Title = newTitle;

            dataAccess.UpdateBlogpost(blogpost);

            WriteLine("Bloggposten uppdaterad");
            Console.ReadKey();
            PageMainMenu();
        }
コード例 #6
0
    private void ParseBlogPost(XElement post)
    {
        var nodes = post
                    .Descendants()
                    .Where(node => node.Attribute("class") != null)
        ;

        Blogpost postData = new Blogpost();

        postData.header =
            nodes
            .Where(node => node.Attribute("class").Value == BLOG_HEADER_CLASS)
            .Select(node => node.Value)
            .FirstOrDefault()
        ;

        postData.imageURL =
            nodes
            .Where(node => node.Attribute("class").Value == BLOG_IMAGE_CLASS)
            .Select(node => node.Attribute("src").Value)
            .FirstOrDefault()
        ;

        postData.link =
            nodes
            .Where(node => node.Attribute("class").Value == BLOG_LINK_CLASS)
            .Select(node => node.Attribute("href").Value)
            .FirstOrDefault()
        ;

        Debug.Log(postData);
    }
コード例 #7
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Title,PublicationTime,Text")] Blogpost blogpost)
        {
            if (id != blogpost.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _blogpostRepository.Update(blogpost);
                    await _blogpostRepository.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!(await _blogpostRepository.BlogpostExists(blogpost.Id)))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(blogpost));
        }
コード例 #8
0
        public void Update(Blogpost value)
        {
            using (var scope = _dbContextScopeFactory.Create())
            {
                var dbContext = scope.DbContexts
                                .Get <ApplicationDbContext>();

                var existed = dbContext.Set <Blogpost>().SingleOrDefault(c => c.ID == value.ID);

                existed.Content       = value.Content;
                existed.IsPublished   = value.IsPublished;
                existed.Keywords      = value.Keywords;
                existed.Overview      = value.Overview;
                existed.PublishedDate = value.PublishedDate;
                existed.Title         = value.Title;
                existed.ServiceId     = value.ServiceId;

                //existed.Author = value.Author;
                //existed.Service = value.Service;

                //existed.ViewsCount = value.ViewsCount;
                //HandleFile(existed.Image, value.Image);

                scope.SaveChanges();
            }
        }
コード例 #9
0
        internal List <Blogpost> GetAllBlogPostsBrief()
        {
            var sql = @"SELECT BlogPostId, Author, Title
                        FROM BlogPost";

            using (SqlConnection connection = new SqlConnection(conString))
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    connection.Open();

                    SqlDataReader reader = command.ExecuteReader();

                    var list = new List <Blogpost>();

                    while (reader.Read())
                    {
                        var bp = new Blogpost
                        {
                            Id     = reader.GetSqlInt32(0).Value,
                            Author = reader.GetSqlString(1).Value,
                            Title  = reader.GetSqlString(2).Value,
                            //Created = reader.GetDateTime(3).Date
                        };

                        list.Add(bp);
                    }

                    return(list);
                }
        }
コード例 #10
0
        public async Task <ActionResult <Blogpost> > PostBlogpost(Blogpost blogpost)
        {
            _context.Blogpost.Add(blogpost);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetBlogpost", new { id = blogpost.Id }, blogpost));
        }
コード例 #11
0
        public async Task <ActionResult> Edit(int?id)
        {
            #region Bad Request (null) Check

            if (id == null || id == 0)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            #endregion

            Blogpost blogpost = await _blogpostRepository.GetBlogpostById(id);

            ViewBag.ModifiedOn = DateTime.Now.ToShortDateString();

            #region Not Found (null) Check

            if (blogpost == null)
            {
                return(HttpNotFound());
            }

            #endregion

            await PopulateTagsDropDownList(blogpost.TagId);

            return(View("~/Views/Blogpost/Edit.cshtml", blogpost));
        }
コード例 #12
0
        internal List <Blogpost> ShowComments(Blogpost blogpost)
        {
            var sql = @"SELECT Comment
                        FROM Comment
                        WHERE BlogPostId=@Id";

            using (SqlConnection connection = new SqlConnection(conString))
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    connection.Open();
                    command.Parameters.Add(new SqlParameter("Id", blogpost.Id));


                    SqlDataReader reader = command.ExecuteReader();

                    var list = new List <Blogpost>();

                    while (reader.Read())
                    {
                        var bp = new Blogpost
                        {
                            Comment = reader.GetSqlString(0).Value
                        };

                        list.Add(bp);
                    }

                    return(list);
                }
        }
コード例 #13
0
        internal List <Blogpost> GetAllTags()
        {
            var sql = @"SELECT Tag
                        FROM Tag";

            using (SqlConnection connection = new SqlConnection(conString))
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    connection.Open();

                    SqlDataReader reader = command.ExecuteReader();

                    var list = new List <Blogpost>();

                    while (reader.Read())
                    {
                        var bp = new Blogpost
                        {
                            Tag = reader.GetSqlString(0).Value
                        };

                        list.Add(bp);
                    }

                    return(list);
                }
        }
コード例 #14
0
        public ActionResult Create([Bind(Include = "Id,Created,Updated,Title,Slug,Body,MediaUrl,Published")] Blogpost blogpost, HttpPostedFileBase image)
        {
            if (ModelState.IsValid)
            {
                var Slug = StringUtilites.URLFriendly(blogpost.Title);
                if (String.IsNullOrWhiteSpace(Slug))
                {
                    ModelState.AddModelError("Title", "Invalid title");
                    return(View(blogpost));
                }

                if (ImageUploadValidator.IsWebFriendlyImage(image))
                {
                    var fileName = Path.GetFileName(image.FileName);
                    image.SaveAs(Path.Combine(Server.MapPath("~/Uploads/"), fileName));
                    blogpost.MediaUrl = "/Uploads/" + fileName;
                }

                if (db.Posts.Any(p => p.Slug == Slug))
                {
                    ModelState.AddModelError("Title", "The title must be unique");
                    return(View(blogpost));
                }

                blogpost.Slug    = Slug;
                blogpost.Created = DateTimeOffset.Now;
                db.Posts.Add(blogpost);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(blogpost));
        }
コード例 #15
0
        public IActionResult DisplayFullBlogPost(int id)
        {
            Blogpost Post = (from c in _BlogPostContext.Blogposts where c.BlogPostId == id select c).FirstOrDefault();

            if (Post != null)
            {
                User auther = (from c in _BlogPostContext.Users where c.UserId == Post.UserId select c).FirstOrDefault();
                if (auther != null)
                {
                    if (HttpContext.Session.GetInt32("userID") != null)
                    {
                        int  userid    = (int)HttpContext.Session.GetInt32("userID");
                        User logged_in = _BlogPostContext.Users.Where(a => a.UserId.Equals(userid)).FirstOrDefault();
                        if (logged_in != null)
                        {
                            ViewBag.logged_in = true;
                        }
                    }
                    List <Comment> comments = _BlogPostContext.Comments.Where(a => a.BlogPostId.Equals(id)).ToList();
                    ViewBag.Comments = comments;
                    ViewBag.Post     = Post;
                    ViewBag.auther   = auther;
                    setLayout();
                    return(View());
                }
            }

            return(RedirectToAction("Index"));
        }
コード例 #16
0
        public async Task <IActionResult> PutBlogpost(int id, Blogpost blogpost)
        {
            if (id != blogpost.Id)
            {
                return(BadRequest());
            }

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

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

            return(NoContent());
        }
コード例 #17
0
        private async Task <bool> TryBlockUnblockContent <T>(long itemId, string reason, long uid) where T : BaseModel, IBlockableContent
        {
            var modId = User.GetNumericId();

            if (modId is null)
            {
                return(false);
            }
            var luid = (long)modId;

            var item = await _context.Set <T>()
                       .Where(i => i.Id == itemId)
                       .Include(i => i.ContentBlock)
                       .FirstOrDefaultAsync();

            if (item is null)
            {
                return(false);
            }

            var title = item switch
            {
                Story s => s.Title,
                Chapter c => c.Title,
                Blogpost b => b.Title,
                _ => ""
            };

            if (item.ContentBlock is null)
            {
                item.ContentBlock = new Data.Models.ContentBlock
                {
                    Reason   = reason,
                    IssuerId = uid,
                    Type     = typeof(T).Name
                };

                // Log the action
                await _context.ModeratorActions.AddAsync(new ModeratorAction
                {
                    StaffMemberId = luid,
                    Description   = ModeratorActionTemplates.ContentBlocked(Type, title, itemId, User.GetUsername())
                });
            }
            else
            {
                _context.ContentBlocks.Remove(item.ContentBlock);

                await _context.ModeratorActions.AddAsync(new ModeratorAction
                {
                    StaffMemberId = luid,
                    Description   = ModeratorActionTemplates.ContentUnblocked(Type, title, itemId, User.GetUsername())
                });
            }

            await _context.SaveChangesAsync();

            return(true);
        }
コード例 #18
0
        public ActionResult DeleteConfirmed(int id)
        {
            Blogpost blogpost = db.Posts.Find(id);

            db.Posts.Remove(blogpost);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
コード例 #19
0
 public Blogpost ToEntity(Blogpost value)
 {
     return(new Blogpost
     {
         Id = value.Id,
         Post = value.Post,
     });
 }
コード例 #20
0
        static void AddOrUpdateTags(ApplicationDbContext context, string blogpostTitle, string tagName)
        {
            Blogpost blog = context.Blogposts.SingleOrDefault(b => b.Title == blogpostTitle);
            Tag      tag  = blog.Tags.SingleOrDefault(t => t.Name == tagName);

            if (tag == null)
            {
                blog.Tags.Add(context.Tags.Single(t => t.Name == tagName));
            }
        }
コード例 #21
0
 public ActionResult Edit([Bind(Include = "Id,Title,Body,Date")] Blogpost blogpost)
 {
     if (ModelState.IsValid)
     {
         db.Entry(blogpost).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(blogpost));
 }
コード例 #22
0
        public Blogpost GetBlogpostById(int id)
        {
            Blogpost blogpost = Blogposts.SingleOrDefault((Blogpost blogpost) => blogpost.Id == id);

            if (blogpost == null)
            {
                return(null);
            }
            return(blogpost);
        }
コード例 #23
0
        public ActionResult Create([Bind(Include = "Id,Title,Body,Date")] Blogpost blogpost)
        {
            if (ModelState.IsValid)
            {
                db.Blogposts.Add(blogpost);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(blogpost));
        }
コード例 #24
0
        public async Task <IActionResult> Create([Bind("Id,Title,PublicationTime,Text")] Blogpost blogpost)
        {
            if (ModelState.IsValid)
            {
                _blogpostRepository.Add(blogpost);
                await _blogpostRepository.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(blogpost));
        }
コード例 #25
0
        public void Insert(Blogpost value)
        {
            using (var scope = _dbContextScopeFactory.Create())
            {
                var dbContext = scope.DbContexts
                                .Get <ApplicationDbContext>();

                dbContext.Set <Blogpost>().Add(value);

                scope.SaveChanges();
            }
        }
コード例 #26
0
        public IActionResult UpdateBlogpost([FromBody] Blogpost value)
        {
            var data = _blogpostService.UpdateBlogpost(value);

            if (data.blogpost == null)
            {
                return(BadRequest("400"));
            }
            else
            {
                return(Ok(data));
            }
        }
コード例 #27
0
        internal void AddTag(Blogpost blogpost)
        {
            string sql = $@"INSERT INTO Tag (Tag) 
                         VALUES (@Tag)";

            using (SqlConnection connection = new SqlConnection(conString))
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    connection.Open();
                    command.Parameters.Add(new SqlParameter("Tag", blogpost.Tag));
                    command.ExecuteNonQuery();
                }
        }
コード例 #28
0
        // GET: BlogPosts/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Blogpost blogpost = db.Posts.Find(id);

            if (blogpost == null)
            {
                return(HttpNotFound());
            }
            return(View(blogpost));
        }
コード例 #29
0
        internal void DeleteTag(Blogpost blogpost)
        {
            var sql = @"DELETE FROM Tag
                        WHERE Tag=@Tag";


            using (SqlConnection connection = new SqlConnection(conString))
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    connection.Open();
                    command.Parameters.Add(new SqlParameter("Tag", blogpost.Tag));
                    command.ExecuteNonQuery();
                }
        }
コード例 #30
0
        internal void AddComment(Blogpost blogpost)
        {
            string sql = $@"INSERT INTO Comment (BlogPostId, Comment)
                         VALUES (@Id, @Comment)";

            using (SqlConnection connection = new SqlConnection(conString))
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    connection.Open();
                    command.Parameters.Add(new SqlParameter("Comment", blogpost.Comment));
                    command.Parameters.Add(new SqlParameter("Id", blogpost.Id));
                    command.ExecuteNonQuery();
                }
        }