// GET api/Posts?sessionKey=xxxxxxx
        public IQueryable<PostDetailsModel> GetAllPosts(string sessionKey)
        {
            return this.PerformOperationAndHandleExceptions(() =>
            {
                int userId = this.ValidateSessionKey(sessionKey);

                var context = new BlogEntities();
                if (context.Users.Find(userId) == null)
                {
                    throw new ArgumentException("Invalid session key - user not exists");
                }

                var query =
                    (from postEntity in context.Posts
                        select new PostDetailsModel()
                        {
                            Id = postEntity.PostId,
                            Title = postEntity.Title,
                            PostedBy = postEntity.User.DisplayName,
                            PostDate = postEntity.PostDate,
                            Text = postEntity.Text,
                            Tags = (from tagEntity in postEntity.Tags
                                    select tagEntity.TagName),
                            Comments = (from commentEntity in postEntity.Comments
                                        select new CommentDetailsModel()
                                        {
                                            Text = commentEntity.CommentText,
                                            CommentedBy = commentEntity.User.DisplayName,
                                            PostDate = commentEntity.PostDate
                                        })
                        });

                return query.OrderByDescending(p => p.PostDate);
            });
        }
Ejemplo n.º 2
0
 public ActionResult SignUp(tbl_blogger tbl_Blogger)
 {
     using (BlogEntities db = new BlogEntities())
     {
         var BloggerInfo = db.tbl_blogger.FirstOrDefault(x => x.Email == tbl_Blogger.Email);
         if (BloggerInfo == null)
         {
             db.tbl_blogger.Add(tbl_Blogger);
             db.SaveChanges();
             TempData["Success"] = "Your account create successful...";
         }
         else
         {
             TempData["Error"] = "The email is already registred...";
         }
     }
     return(RedirectToAction("Index", "Home"));
 }
Ejemplo n.º 3
0
        public HttpResponseMessage saveBlogInfo([FromBody] Blog blogFM)
        {
            using (BlogEntities entities = new BlogEntities())
            {
                if (blogFM.id == 0)
                {
                    entities.Blogs.Add(blogFM);
                }
                else
                {
                    entities.Entry(blogFM).State = EntityState.Modified;
                }

                entities.SaveChanges();
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Ejemplo n.º 4
0
    public static IQueryable <video> getVideoIdByName(string tit)
    {
        BlogEntities       be = new BlogEntities();
        IQueryable <video> qry;

        try
        {
            qry = from vid in be.videos
                  where vid.Title.Contains(tit)
                  select vid;
        }
        catch
        {
            throw new UnableToAccessVideo();
        }

        return(qry);
    }
Ejemplo n.º 5
0
        public ActionResult Login(tbl_blogger tbl_Blogger)
        {
            using (BlogEntities db = new BlogEntities())
            {
                var BloggerInfo = db.tbl_blogger.FirstOrDefault(x => x.Email == tbl_Blogger.Email && x.Password == tbl_Blogger.Password);

                if (BloggerInfo == null)
                {
                    TempData["Error"] = "Wrong email or password...";
                }
                else
                {
                    Session["Blogger"] = BloggerInfo;
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
        public ActionResult Login(tbl_admin tbl_Admin)
        {
            using (BlogEntities db = new BlogEntities())
            {
                var AdminInfo = db.tbl_admin.FirstOrDefault(x => x.Email == tbl_Admin.Email && x.Password == tbl_Admin.Password);

                if (AdminInfo == null)
                {
                    ViewBag.Error = "Wrong Information";
                }
                else
                {
                    Session["Admin"] = AdminInfo;
                    return(RedirectToAction("Dashboard"));
                }
            }

            return(View());
        }
 public override IEnumerable <DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
 {
     // BlogEntities would be your entity framework context class
     // or repository.
     using (var entities = new BlogEntities())
     {
         // Create a node for each blog post
         foreach (var blogPost in entities.BlogPosts)
         {
             DynamicNode dynamicNode = new DynamicNode();
             dynamicNode.Title     = blogPost.Title;
             dynamicNode.ParentKey = "Blog";
             dynamicNode.Key       = "BlogPost_" + blogPost.Id;
             dynamicNode.RouteValues.Add("id", blogPost.Id);
             dynamicNode.RouteValues.Add("seoName", blogPost.SeoName);
             yield return(dynamicNode);
         }
     }
 }
Ejemplo n.º 8
0
        //[ValidateAntiForgeryToken]
        public ActionResult AllPost()
        {
            int?                 from      = 1;
            int?                 to        = 5;
            BlogEntities         db        = new BlogEntities();
            List <PostViewModel> viewModel = new List <PostViewModel>();

            string sql = string.Format(@"SELECT * FROM ( 
                             SELECT 
                                  ROW_NUMBER() OVER (ORDER BY id desc) AS row, p.*
                             FROM POST p
                        ) AS a WHERE row BETWEEN {0} AND {1}", from == null ? 1 : from, to == null ? 5 : to);

            viewModel = db.POSTs.SqlQuery(sql).Select(c => new PostViewModel {
                TITLE = c.TITLE, IMAGE_COVER = c.IMAGE_COVER, SLUG = c.SLUG, CREATED_DATE = c.CREATED_DATE, CREATED_USER = c.CREATED_USER, MAIN_TAG = c.MAIN_TAG, META_DESC = c.META_DESC
            }).ToList();

            return(PartialView(viewModel));
        }
Ejemplo n.º 9
0
        public override OperationResult Execute(BlogEntities entities)
        {
            IEnumerable <CommentDto> ieComments = from com in entities.Comments
                                                  where com.post_id == Dto.PostId
                                                  select new CommentDto
            {
                Id          = com.comment_id,
                Content     = com.content,
                DateCreated = com.date_created,
                UserId      = com.user_id,
                UserName    = com.AspNetUser.UserName,
                PostId      = com.post_id
            };
            OperationResult result = new OperationResult();

            result.Items  = ieComments.ToArray();
            result.Status = true;
            return(result);
        }
Ejemplo n.º 10
0
        // GET: Articol
        public ActionResult Index(int pagina = 1)
        {
            BlogEntities          db    = new BlogEntities();
            ArticolIndexViewModel model = new ArticolIndexViewModel();

            model.ListaArticole = db.Postares.Where(a => a.Publicata).Include(p => p.Pozas)
                                  .OrderByDescending(p => p.DataCreare)
                                  .Skip(model.Paginare.ItemsPerPage * (pagina - 1))
                                  .Take(model.Paginare.ItemsPerPage)
                                  .Select(p => new ArticolViewModel
            {
                Id         = p.Id,
                Titlu      = p.Titlu,
                DataCreare = p.DataCreare,
                Text       = p.Text.Length > 250 ? p.Text.Remove(250) : p.Text,
                ListaPoze  = p.Pozas.OrderByDescending(l => l.CalePoza).Take(1).ToList()
            }).ToList();
            return(View(model));
        }
Ejemplo n.º 11
0
        public ActionResult Random()
        {
            using (var database = new BlogEntities())
            {
                // Get count articles from database
                var countArticles = database.Articles.Count();


                // Get random article from article list
                Random random    = new Random();
                int    randomNum = random.Next(1, countArticles - 2);

                OpArticleSelect op       = new OpArticleSelect();
                OperationResult result   = OperationManager.Singleton.ExecuteOperation(op);
                var             articles = result.Items.Cast <ArticleDto>().OrderBy(a => a.Id).Skip(randomNum).Take(4).ToList();

                return(View(articles));
            }
        }
Ejemplo n.º 12
0
        public ActionResult Details(int id)
        {
            BlogEntities     db    = new BlogEntities();
            ArticolViewModel model = db.Postares.OrderByDescending(p => p.DataCreare).Include(a => a.Pozas)
                                     .Include(p => p.Comentarius)
                                     .Select((p => new ArticolViewModel
            {
                Id = p.Id,
                Titlu = p.Titlu,
                DataCreare = p.DataCreare,
                Text = p.Text,
                ListaComentarii = p.Comentarius.Where(a => a.Aprobat).OrderByDescending(s => s.DataCreare).ToList(),
                ListaPoze = p.Pozas
            }))
                                     .FirstOrDefault(p => p.Id == id);

            model.LoggedUser = User.Identity.Name;
            return(View(model));
        }
Ejemplo n.º 13
0
        public override OperationResult Execute(BlogEntities entities)
        {
            IEnumerable <AuthorDto> ieAuthor = from author in entities.Authors
                                               select new AuthorDto
            {
                Content = author.content,
                Name    = author.name,
                Picture = (from pic in entities.Pictures
                           join a in entities.Authors on pic.picture_id equals a.picture_id
                           select new PictureDto
                {
                    Alt = pic.alt,
                    Src = pic.src
                }).ToList()
            };
            OperationResult result = new OperationResult();

            result.Status = true;
            result.Items  = ieAuthor.ToArray();
            return(result);
        }
Ejemplo n.º 14
0
        public override OperationResult Execute(BlogEntities entities)
        {
            Article article = entities.Articles.Where(a => a.Id == Article.Id).FirstOrDefault();

            if (article != null)
            {
                article.Id        = this.Article.Id;
                article.Title     = this.Article.Title;
                article.Content   = this.Article.Content;
                article.ImagePath = this.Article.ImagePath;

                entities.SaveChanges();
                return(base.Execute(entities));
            }

            OperationResult result = new OperationResult();

            result.Status  = false;
            result.Message = "Article does not exist";
            return(result);
        }
        public HttpResponseMessage PostLoginUser(UserModel model)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
              () =>
              {
                  var context = new BlogEntities();
                  using (context)
                  {
                      this.ValidateUsername(model.Username);
                      this.ValidateAuthCode(model.AuthCode);
                      var usernameToLower = model.Username.ToLower();
                      var user = context.Users.FirstOrDefault(
                          usr => usr.Username == usernameToLower
                          && usr.AuthCode == model.AuthCode);

                      if (user == null)
                      {
                          throw new InvalidOperationException("Invalid username or password");
                      }
                      if (user.SessionKey == null)
                      {
                          user.SessionKey = this.GenerateSessionKey(user.UserId);
                          context.SaveChanges();
                      }

                      var loggedModel = new LoggedUserModel()
                      {
                          DisplayName = user.DisplayName,
                          SessionKey = user.SessionKey
                      };

                      var response =
                          this.Request.CreateResponse(HttpStatusCode.Created,
                                          loggedModel);
                      return response;
                  }
              });

            return responseMsg;
        }
        private IQueryable <Article> _GetQuery(BlogEntities db)
        {
            string queryText = FtsSearch.Query(
                dbContext: db,
                ftsEnum: FtsEnum.CONTAINS,
                tableQuery: typeof(Article),
                tableFts: typeof(FTS_Int),
                search: "text");

            var queryFts = db.FTS_Int.Where(n => n.Query.Contains(queryText));

            return(db.Article
                   .Where(n => n.Active)
                   .Join(queryFts, article => article.Id, fts => fts.Key, (article, fts) => new
            {
                article,
                fts.Rank,
            })
                   .OrderByDescending(n => n.Rank)
                   .Take(10)
                   .Select(n => n.article));
        }
Ejemplo n.º 17
0
        public override OperationResult Execute(BlogEntities entities)
        {
            AspNetUser user = new AspNetUser
            {
                Email        = this.Dto.Email,
                UserName     = this.Dto.Username,
                PasswordHash = this.Dto.Password
            };

            foreach (var role in Dto.Role)
            {
                AspNetRole r = new AspNetRole
                {
                    Name = role.Name
                };
                user.AspNetRoles.Add(r);
            }

            entities.AspNetUsers.Add(user);
            entities.SaveChanges();
            return(base.Execute(entities));
        }
Ejemplo n.º 18
0
        public List <BlogViewModel> getAllBlogPosts()
        {
            using (BlogEntities entities = new BlogEntities())
            {
                var resultList = from blog in entities.Blogs.ToList()
                                 select new BlogViewModel
                {
                    id            = blog.id,
                    title         = blog.title,
                    body          = blog.body,
                    user_id       = blog.user_id,
                    publish_date  = blog.publish_date.Value,
                    allow_publish = blog.allow_publish.Value,
                    created       = blog.created.Value,
                    updated       = blog.updated.Value
                };

                var vm = resultList.ToList();

                return(vm);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 添加博客
        /// </summary>
        /// <param name="article"></param>
        /// <returns></returns>
        public static int AddArticle(Article article)
        {
            var articleTemp = article;

            using (BlogEntities blogEntities = new BlogEntities())
            {
                var ArticleLabelList = article.ArticleLabel;
                article.ArticleLabel = null;
                var newlabelList = new List <ArticleLabel>();
                foreach (var label in ArticleLabelList)
                {
                    var labelFromDb = (from l in blogEntities.ArticleLabel where l.Id == label.Id select l).FirstOrDefault();

                    newlabelList.Add(labelFromDb);
                }
                article.ArticleLabel = newlabelList;
                blogEntities.Article.Add(article);
                blogEntities.SaveChanges();
                articleTemp = article;
            }
            return(articleTemp.Id);
        }
Ejemplo n.º 20
0
    public static string getMimeType(int bid)
    {
        string       ContentType = string.Empty;
        BlogEntities be          = new BlogEntities();

        try
        {
            IQueryable <binary> qry = from vid in be.binaries
                                      where vid.binID == bid
                                      select vid;
            foreach (var m in qry)
            {
                ContentType = m.MimeType;
            }
        }
        catch
        {
            throw new UnableToAccessImage();
        }

        return(ContentType);
    }
Ejemplo n.º 21
0
        public List <UserViewModel> getAllUsers()
        {
            using (BlogEntities entities = new BlogEntities())
            {
                var UserList = from user in entities.users.ToList()
                               select new UserViewModel
                {
                    id        = user.id,
                    name      = user.name,
                    lastname  = user.lastname,
                    birthdate = user.birthdate,
                    created   = user.created,
                    updated   = user.updated,
                    status    = user.status,
                    email     = user.email
                };

                var vm = UserList.ToList();

                return(vm);
            }
        }
Ejemplo n.º 22
0
    /* public static void InsertPost(post pt)
     * {
     *
     *
     *
     *  string query = "INSERT INTO [int422_121b07].[dbo].[posts](author, title,content,created,comments,cat_id)" +
     *          "VALUES('" + pt.author + "','" + pt.title + "','" + pt.content + "'," + pt.created.ToString() +
     *          ",0 ,'" + pt.cat_id + "')";
     *  //var con = BlogManager.getConString();
     *  //var cstr = con.ConnectionString;
     *  SqlConnection sconn = new SqlConnection(BlogManager.getConString());
     *  //StringBuilder sb = new StringBuilder();
     *  try
     *  {
     *
     *      // 1. Instantiate a new command with a query and connection
     *      //           SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);
     *
     *      // 2. Call Execute reader to get query results
     *      //        SqlDataReader rdr = cmd.ExecuteReader();
     *
     *      sconn.Open();
     *      SqlCommand cmd = new SqlCommand(query, sconn);
     *      //SqlDataReader reader = cmd.ExecuteReader();
     *      cmd.ExecuteNonQuery();
     *
     *  }
     *  catch (Exception)
     *  {
     *
     *  }
     *  finally
     *  {
     *
     *      sconn.Close();
     *  }
     *
     *
     * }
     */
    #endregion


    /*************************************************************
     *  @type: Print an array of articles by searching linq query for post id
     *  @usage: just pass in a post_id
     *  @return: it will return a string which contains the div that will be displayed on the blog.
     *
     **************************************************************/



    public string[] PrintArticle(int post_id)
    {
        string[]      strb = new string[] { };
        StringBuilder sb   = new StringBuilder();

        try
        {
            using (BlogEntities be = new BlogEntities())
            {
                IQueryable <post> qry = from z in be.posts
                                        where z.post_id == post_id
                                        select z;
                blogDiv(qry, ref strb, false);
            }
        }
        catch
        {
            throw new UnableToAccessBlogEntry();
        }

        return(strb);
    }
        public ActionResult AdminUpdate(int id, string btn, tbl_admin tbl_Admin)
        {
            using (BlogEntities db = new BlogEntities())
            {
                var admin   = db.tbl_admin.FirstOrDefault(x => x.ID == id);
                var session = (tbl_admin)Session["Admin"];

                if (btn == "name")
                {
                    admin.Name   = tbl_Admin.Name;
                    session.Name = admin.Name;
                }

                else if (btn == "email")
                {
                    admin.Email   = tbl_Admin.Email;
                    session.Email = admin.Email;
                }

                else
                {
                    if (admin.Password == Request["OldPassword"])
                    {
                        admin.Password = Request["NewPassword"];
                        db.SaveChanges();

                        return(RedirectToAction("Logout"));
                    }
                    else
                    {
                        TempData["PassError"] = "Current Password Not Match..";
                        return(RedirectToAction("Setting"));
                    }
                }

                db.SaveChanges();
            }
            return(RedirectToAction("Setting"));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 按条件检索博客
        /// </summary>
        /// <param name="selectArticleRequest"></param>
        /// <returns></returns>
        public static List <Article> SelectArticleList(SelectArticleRequest selectArticleRequest)
        {
            List <Article> list = null;

            using (BlogEntities blogEntities = new BlogEntities())
            {
                if (String.IsNullOrEmpty(selectArticleRequest.Title))
                {
                    selectArticleRequest.Title = "";
                }
                if (selectArticleRequest.BeginPublicationTime == null)
                {
                    selectArticleRequest.BeginPublicationTime = DateTime.MinValue;
                }
                if (selectArticleRequest.EndPublicationTime == null)
                {
                    selectArticleRequest.EndPublicationTime = DateTime.MaxValue;
                }
                if (selectArticleRequest.Page == 0)
                {
                    selectArticleRequest.Page = 1;
                }
                if (selectArticleRequest.CountPerPage == 0)
                {
                    selectArticleRequest.CountPerPage = int.MaxValue;
                }
                var articles = (from article in blogEntities.Article.Include("ArticleLabel")
                                where article.Title.Contains(selectArticleRequest.Title) &&
                                article.PublicationTime >= selectArticleRequest.BeginPublicationTime &&
                                article.PublicationTime <= selectArticleRequest.EndPublicationTime
                                orderby article.PublicationTime descending
                                select article)
                               .Skip((selectArticleRequest.Page - 1) * selectArticleRequest.CountPerPage)
                               .Take(selectArticleRequest.CountPerPage);
                list = new List <Article>(articles.ToArray());
            }
            return(list);
        }
Ejemplo n.º 25
0
        public LoginViewModel IsCorrectLogin(string username, string password)
        {
            using (BlogEntities entities = new BlogEntities())
            {
                var            tmpUserLogin = entities.userLogins.Where(x => (x.username == username) && (x.password == password)).FirstOrDefault();
                LoginViewModel vm           = new LoginViewModel();

                if (tmpUserLogin == null)
                {
                    vm.IsCorrectLogin = false;
                    vm.successLogin   = false;
                }
                else
                {
                    vm.IsCorrectLogin = true;
                    vm.successLogin   = true;
                    vm.userName       = tmpUserLogin.username;
                    vm.passWord       = tmpUserLogin.password;
                    vm.userID         = tmpUserLogin.user_id;
                }
                return(vm);
            }
        }
Ejemplo n.º 26
0
        public override OperationResult Execute(BlogEntities entiteti)
        {
            int num = (from votes in entiteti.PollVotes
                       join answer in entiteti.PollAnswers on votes.idAnswer equals answer.idPollAnswer
                       where Vote.IpAddress == votes.ipAddress && Vote.IdQuestion == answer.idPollQuestion
                       select votes).Count();
            OperationResult result = new OperationResult()
            {
                Message = "Inserting poll vote"
            };

            if (num == 0)
            {
                entiteti.spInsertPollVote(Vote.IpAddress, Vote.IdAnswer);
                result.Status = true;
            }
            else
            {
                result.Status = false;
            }

            return(result);
        }
        // GET api/Tags
        public IQueryable<TagModel> GetTags(string sessionKey)
        {
            return this.PerformOperationAndHandleExceptions(() =>
            {
                int userId = this.ValidateSessionKey(sessionKey);

                var context = new BlogEntities();
                if (context.Users.Find(userId) == null)
                {
                    throw new ArgumentException("Invalid session key - user not exists");
                }

                var query = (from tagEntity in context.Tags
                                select new TagModel()
                                {
                                    Id = tagEntity.TagId,
                                    Name = tagEntity.TagName,
                                    Posts = tagEntity.Posts.Count()
                                }).AsQueryable();

                return query.OrderBy(t => t.Id);
            });
        }
Ejemplo n.º 28
0
        /// <summary>
        /// 更新博客
        /// </summary>
        /// <param name="article"></param>
        /// <returns></returns>
        public static int UpdateArticle(Article article)
        {
            using (BlogEntities blogEntities = new BlogEntities())
            {
                var changeArticle = blogEntities.Article.First(a => a.Id == article.Id);

                //changeArticle.PublicationTime = article.PublicationTime;
                changeArticle.Title   = article.Title;
                changeArticle.Content = article.Content;
                var ArticleLabelList = article.ArticleLabel;
                var newLabelList     = new List <ArticleLabel>();
                var oldLabelList     = new List <ArticleLabel>(changeArticle.ArticleLabel);
                foreach (var label in ArticleLabelList)
                {
                    var labelFromDb = (from l in blogEntities.ArticleLabel where l.Id == label.Id select l).FirstOrDefault();
                    newLabelList.Add(labelFromDb);
                }

                foreach (var label in newLabelList)
                {
                    if (!changeArticle.ArticleLabel.Contains(label))
                    {
                        changeArticle.ArticleLabel.Add(label);
                    }
                }

                foreach (var label in oldLabelList)
                {
                    if (!newLabelList.Contains(label))
                    {
                        changeArticle.ArticleLabel.Remove(label);
                    }
                }
                blogEntities.SaveChanges();
            }
            return(article.Id);
        }
        public void Query_Default()
        {
            using (BlogEntities db = new BlogEntities())
            {
                string queryResult = _GetQuery(db).ToString();

                Assert.Equal(@"SELECT TOP (10) 
    [Project1].[Id] AS [Id], 
    [Project1].[Date] AS [Date], 
    [Project1].[Text] AS [Text], 
    [Project1].[Active] AS [Active]
    FROM ( SELECT 
        [Extent1].[Id] AS [Id], 
        [Extent1].[Date] AS [Date], 
        [Extent1].[Text] AS [Text], 
        [Extent1].[Active] AS [Active], 
        [Extent2].[Rank] AS [Rank]
        FROM  [dbo].[Article] AS [Extent1]
        INNER JOIN [dbo].[FTS_Int] AS [Extent2] ON [Extent1].[Id] = [Extent2].[Key]
        WHERE ([Extent1].[Active] = 1) AND ([Extent2].[Query] LIKE @p__linq__0 ESCAPE N'~')
    )  AS [Project1]
    ORDER BY [Project1].[Rank] DESC", queryResult);
            }
        }
Ejemplo n.º 30
0
 public BaseRepository()
 {
     ce = new BlogEntities();
 }
        public HttpResponseMessage PostRegisterUser(UserModel model)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
                () =>
                {
                    var context = new BlogEntities();
                    using (context)
                    {
                        this.ValidateUsername(model.Username);
                        this.ValidateDisplayName(model.DisplayName);
                        this.ValidateAuthCode(model.AuthCode);
                        var usernameToLower = model.Username.ToLower();
                        var displaynameToLower = model.DisplayName.ToLower();
                        var user = context.Users.FirstOrDefault(
                            usr => usr.Username == usernameToLower
                            || usr.DisplayName.ToLower() == displaynameToLower);

                        if (user != null)
                        {
                            throw new InvalidOperationException("User exists");
                        }

                        user = new User()
                        {
                            Username = usernameToLower,
                            DisplayName = model.DisplayName,
                            AuthCode = model.AuthCode
                        };

                        context.Users.Add(user);
                        context.SaveChanges();

                        user.SessionKey = this.GenerateSessionKey(user.UserId);
                        context.SaveChanges();

                        var loggedModel = new LoggedUserModel()
                        {
                            DisplayName = user.DisplayName,
                            SessionKey = user.SessionKey
                        };

                        var response =
                            this.Request.CreateResponse(HttpStatusCode.Created,
                                            loggedModel);
                        return response;
                    }
                });

            return responseMsg;
        }
Ejemplo n.º 32
0
 public HomeController()
 {
     db = new BlogEntities();
 }
        public HttpResponseMessage PutLogoutUser(string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
              () =>
              {
                  var context = new BlogEntities();
                  using (context)
                  {
                      int UserId = this.ValidateSessionKey(sessionKey);
                      var user = context.Users.Find(UserId);

                      if (user == null)
                      {
                          throw new InvalidOperationException("Invalid Session Key");
                      }
                      user.SessionKey = null;
                      context.SaveChanges();

                      var response = this.Request.CreateResponse(HttpStatusCode.OK);
                      return response;
                  }
              });

            return responseMsg;
        }
Ejemplo n.º 34
0
 public PostRepository(BlogEntities db)
 {
     this._db = db;
 }
Ejemplo n.º 35
0
 public AdminCPController()
 {
     db = new BlogEntities();
 }
Ejemplo n.º 36
0
        public ActionResult DetailBlog(string slug)
        {
            DetailBlogViewModel viewModel = new DetailBlogViewModel();
            BlogEntities        db        = new BlogEntities();

            POST content = new POST();

            content = db.POSTs.FirstOrDefault(c => c.SLUG.Equals(slug) && c.IS_ACTIVE.Equals("1"));

            //CAN'T FIND POST, REDIRECT TO 404 PAGE
            if (content == null)
            {
                return(RedirectToAction("NotFound"));
            }

            viewModel.Post = content;

            //GET POST'S TAG
            viewModel.Tags = db.TAGs.SqlQuery(string.Format("SELECT TB2.* FROM POST TB1, TAG TB2, POST_TAG TB3 WHERE TB1.ID=TB3.POST_ID AND TB3.TAG_ID=TB2.ID AND TB1.ID={0}", content.ID)).ToList <TAG>();

            //GET POST'S AUTHOR
            viewModel.Author = db.PAGE_USER.FirstOrDefault(c => c.USERNAME.Equals(content.CREATED_USER));

            //GET PREV AND NEXT POSTs
            try
            {
                string   sql      = string.Format(@"SELECT CONVERT(nvarchar,ISNULL( K.PREV,0))+'#'+CONVERT(nvarchar,ISNULL( K.NEXT,0)) 
                                         FROM(
	                                          SELECT LAG(P.ID) OVER(ORDER BY P.ID) PREV,
			                                         P.ID,
			                                         LEAD(P.ID) OVER(ORDER BY P.ID) NEXT
	                                          FROM	POST P
	                                          WHERE	P.ID<=({0}*2) AND IS_ACTIVE='1' ) K
                                         WHERE ID={1}", content.ID <= 1 ? 2 : content.ID, content.ID);
                string[] nearById = db.Database.SqlQuery <string>(sql).ToList().FirstOrDefault().Split('#');
                //GET PREV_ID#NEXT_ID
                int prevId = Convert.ToInt32(nearById[0]);
                int nextId = Convert.ToInt32(nearById[1]);

                viewModel.PrevPost = db.POSTs.Where(c => c.ID.Equals(prevId)).Select(c => new PostViewModel {
                    TITLE = c.TITLE, IMAGE_COVER = c.IMAGE_COVER, SLUG = c.SLUG
                }).FirstOrDefault();
                viewModel.NextPost = db.POSTs.Where(c => c.ID.Equals(nextId)).Select(c => new PostViewModel {
                    TITLE = c.TITLE, IMAGE_COVER = c.IMAGE_COVER, SLUG = c.SLUG
                }).FirstOrDefault();

                if (viewModel.PrevPost == null)
                {
                    viewModel.PrevPost = new PostViewModel()
                    {
                        SLUG = "/", TITLE = "Trang chủ"
                    };
                }
                if (viewModel.NextPost == null)
                {
                    viewModel.NextPost = new PostViewModel()
                    {
                        SLUG = "/", TITLE = "Trang chủ"
                    };
                }
            }
            catch (Exception ex)
            {
                viewModel.PrevPost = new PostViewModel()
                {
                    SLUG = "/", TITLE = "Trang chủ"
                };
                viewModel.NextPost = new PostViewModel()
                {
                    SLUG = "/", TITLE = "Trang chủ"
                };
            }

            //GET 3 RELATED POST
            if (viewModel.Tags != null)
            {
                viewModel.RelatedPosts = new List <PostViewModel>();
                foreach (TAG tag in viewModel.Tags)
                {
                    PostViewModel pV = db.POSTs.SqlQuery(string.Format("SELECT TB1.* FROM POST TB1, TAG TB2, POST_TAG TB3 WHERE TB1.ID=TB3.POST_ID AND TB3.TAG_ID=TB2.ID AND TB2.ID={0} AND TB1.ID <> {1}", tag.ID, content.ID)).Select(c => new PostViewModel {
                        TITLE = c.TITLE, IMAGE_COVER = c.IMAGE_COVER, SLUG = c.SLUG, CREATED_DATE = c.CREATED_DATE, CREATED_USER = c.CREATED_USER
                    }).FirstOrDefault();
                    if (pV != null)
                    {
                        pV.MAIN_TAG = tag.NAME;
                        viewModel.RelatedPosts.Add(pV);
                        if (viewModel.RelatedPosts.Count >= 3)
                        {
                            break;
                        }
                    }
                }
            }


            //SETTING VIEWBAG
            ViewBag.Title = content.TITLE;
            return(View(viewModel));
        }
Ejemplo n.º 37
0
 public BlogEntities Init()
 {
     return entities ?? (entities = new BlogEntities());
 }
Ejemplo n.º 38
0
 public UserRepository(BlogEntities entities) : base(entities)
 {
 }
        public HttpResponseMessage PutComment(int Id, [FromUri] string sessionKey, CommentSimpleModel comment)
        {
            return this.PerformOperationAndHandleExceptions(() =>
            {
                if (!ModelState.IsValid)
                {
                    throw new ArgumentException("Invalid model binding state");
                    // return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                }

                int userId = this.ValidateSessionKey(sessionKey);

                if (comment.Text.Length == 0)
                {
                    throw new ArgumentException("Comment text should not be empty");
                }

                using (var context = new BlogEntities())
                {
                    var currentUser = context.Users.Find(userId);
                    if (currentUser == null)
                    {
                        throw new ArgumentException("Invalid session key - user not exists");
                    }

                    using (var scope = new System.Transactions.TransactionScope())
                    {
                        var selectedPost = context.Posts.Find(Id);
                        if (selectedPost == null)
                        {
                            throw new ArgumentException("Invalid post Id - post not exists");
                        }

                        var newComment = new Comment()
                        {
                            CommentText = comment.Text,
                            PostDate = DateTime.Now,
                            Post = selectedPost,
                            User = currentUser
                        };

                        context.Comments.Add(newComment);
                        context.SaveChanges();
                        scope.Complete();

                        return Request.CreateResponse(HttpStatusCode.OK);
                    }
                }
            });
        }
Ejemplo n.º 40
0
 public PostsController()
 {
     db = new BlogEntities();
 }
        // POST api/Posts
        public HttpResponseMessage PostPost([FromUri] string sessionKey, [FromBody] PostModel post)
        {
            return this.PerformOperationAndHandleExceptions(() =>
            {
                if (!ModelState.IsValid)
                {
                    throw new ArgumentException("Invalid model binding state");
                    // return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                }

                int userId = this.ValidateSessionKey(sessionKey);

                if (post.Title.Length == 0 || post.Text.Length == 0)
                {
                    throw new ArgumentException("Post Title and Text should not be empty");
                }

                // Add title tags to the existing list of tags
                string[] titleTags = post.Title.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var tag in titleTags)
                {
                    if (!post.Tags.Contains(tag))
                    {
                        post.Tags.Add(tag);
                    }
                }

                using (var context = new BlogEntities())
                {
                    if (context.Users.Find(userId) == null)
                    {
                        throw new ArgumentException("Invalid session key - user not exists");
                    }

                    using (var scope = new System.Transactions.TransactionScope())
                    {
                        var newPost = new Post()
                        {
                            Title = post.Title,
                            Text = post.Text,
                            User = context.Users.Find(userId),
                            PostDate = DateTime.Now
                        };

                        foreach (var tag in post.Tags)
                        {
                            var tagToLower = tag.ToLower();
                            var newTag = context.Tags.FirstOrDefault(t => t.TagName == tagToLower);
                            if (newTag == null)
                            {
                                newTag = new Tag() { TagName = tagToLower };
                                context.Tags.Add(newTag);
                            }

                            newPost.Tags.Add(newTag);
                        }

                        context.Posts.Add(newPost);
                        context.SaveChanges();
                        scope.Complete();

                        return Request.CreateResponse(HttpStatusCode.Created, new
                        {
                            Title = newPost.Title,
                            Id = newPost.PostId
                        });
                    }
                }
            });
        }