public ActionResult PostBlog(PostDto Post) { Post.CreatedBy = Post.UpdatedBy = "Authorized user"; if (Post.PostId > 0) { var success = BlogQueries.UpdatePost(Post); if (success) TempData["Message"] = "Your post was successfully updated"; } else { var postId = BlogQueries.CreatePost(Post); Post.PostId = postId; if (postId > 0) TempData["Message"] = "Your post was successfully posted"; } return RedirectToAction("View", new {id = Post.PostId}); }
public static int CreatePost(PostDto post) { var id = 0; using (var conn = Connection.GetConnection()) { conn.Open(); var createCommand = "INSERT INTO Posts (Title,Body,CreatedOn,CreatedBy,UpdatedOn,UpdatedBy) VALUES ('" + post.Title.Replace("'", "''") + "', '" + post.Body.Replace("'", "''")+ "', '" + DateTime.Now.ToString("M/d/yyyy hh:mm:ss tt") + "', '" + post.CreatedBy + "', '" + DateTime.Now.ToString("M/d/yyyy hh:mm:ss tt") + "', '" + post.UpdatedBy + "'); SELECT SCOPE_IDENTITY()"; using (var cmd = new SqlCommand(createCommand, conn)) { cmd.CommandType = CommandType.Text; id = Convert.ToInt32(cmd.ExecuteScalar()); } conn.Close(); } return id; }
private static PostDto ReadPost(SqlDataReader dr) { var p = new PostDto { PostId = Convert.ToInt32(dr["PostId"]), Title = dr["Title"] != DBNull.Value ? dr["Title"].ToString() : string.Empty, Body = dr["Body"] != DBNull.Value ? HttpUtility.HtmlDecode(dr["Body"].ToString()) : string.Empty, CreatedBy = dr["CreatedBy"] != DBNull.Value ? dr["CreatedBy"].ToString() : string.Empty, UpdatedBy = dr["UpdatedBy"] != DBNull.Value ? dr["UpdatedBy"].ToString() : string.Empty, CreatedOn = dr["CreatedOn"] != DBNull.Value ? Convert.ToDateTime(dr["CreatedOn"].ToString()) : DateTime.MinValue, UpdatedOn = dr["UpdatedOn"] != DBNull.Value ? Convert.ToDateTime(dr["UpdatedOn"].ToString()) : DateTime.MinValue, CommentCount = dr["CommentsCount"] != DBNull.Value ? Convert.ToInt32(dr["CommentsCount"].ToString()) : 0 }; return p; }
public static bool UpdatePost(PostDto post) { var rowsAffected = 0; using (var conn = Connection.GetConnection()) { conn.Open(); var updateCommand = "UPDATE Posts SET Title = '" + post.Title.Replace("'", "''") + "',Body = '" + post.Body.Replace("'", "''") + "',UpdatedOn = '" + DateTime.Now.ToString("M/d/yyyy hh:mm:ss tt") + "',UpdatedBy = '" + post.UpdatedBy + "' WHERE PostId = " + post.PostId; using (var cmd = new SqlCommand(updateCommand, conn)) { cmd.CommandType = CommandType.Text; rowsAffected = cmd.ExecuteNonQuery(); } conn.Close(); } return rowsAffected > 0; }
public static PostDto GetPostById(int postId) { var post = new PostDto(); using (var conn = Connection.GetConnection()) { conn.Open(); using (var cmd = new SqlCommand("SELECT * FROM POSTS WHERE PostId = " + postId, conn)) { cmd.CommandType = CommandType.Text; var dr = cmd.ExecuteReader(); while (dr.Read()) { post = ReadPost(dr); } } conn.Close(); } return post; }
public BlogPostModel() { Post = new PostDto(); Comments = new List<CommentDto>(); NewComment = new CommentDto(); }