public IEnumerable<TagModel> GetAll(
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))]string sessionKey)
        {
            var allTagModels = this.PerformOperation(() =>
            {
                UserValidator.ValidateSessionKey(sessionKey);

                var context = new BloggingSystemContext();
                using (context)
                {
                    var loggedUserEntity = context.Users.FirstOrDefault<User>(u => u.SessionKey == sessionKey);
                    if (loggedUserEntity == null)
                    {
                        throw new InvalidOperationException("Invalid user or pasword!");
                    }

                    var tagModels = new List<TagModel>();
                    var tagEntities = context.Tags.Include("Posts").OrderBy(t => t.Name);
                    foreach (var tagEntity in tagEntities)
                    {
                        tagModels.Add(TagsMapper.ToModel(tagEntity));
                    }

                    return tagModels;
                }
            });

            return allTagModels;
        }
        public HttpResponseMessage Get(string sessionKey)
        {
            try
            {
                this.VerifySessionKey(sessionKey);
            }
            catch (Exception e)
            {
                var errorResponse = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message);
                return errorResponse;
            }

            var context = new BloggingSystemContext();

            var tagsResult = from tag in context.Tags
                             orderby tag.Text
                             select new SimpleTagModel()
                             {
                                 Id = tag.TagId,
                                 Name = tag.Text,
                                 PostsCount = tag.Posts.Count
                             };

            var response = this.Request.CreateResponse(HttpStatusCode.OK, tagsResult);

            return response;
        }
        public IQueryable<PostModel> GetAll(
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))]string sessionKey)
        {
            IQueryable<PostModel> allPostModels = this.PerformOperation(() =>
            {
                UserValidator.ValidateSessionKey(sessionKey);

                var context = new BloggingSystemContext();
                using (context)
                {
                    var loggedUserEntity = context.Users.FirstOrDefault<User>(u => u.SessionKey == sessionKey);
                    if (loggedUserEntity == null)
                    {
                        throw new InvalidOperationException("Invalid user or pasword!");
                    }

                    var postModels = new List<PostModel>();

                    var postEntities = context.Posts
                        .Include("Comments").Include("Tags")
                        .OrderByDescending(p => p.PostDate);
                    foreach (var postEntity in postEntities.ToList())
                    {
                        postModels.Add(PostsMapper.ToModel(postEntity));
                    }

                    return postModels.AsQueryable<PostModel>();
                }
            });

            return allPostModels;
        }
Exemplo n.º 4
0
        public IOrderedQueryable<TagDto> GetAll()
        {
            try
            {
                var sessionKey = ApiControllerHelper.GetHeaderValue(Request.Headers, "X-SessionKey");
                if (sessionKey == null)
                {
                    throw new ArgumentNullException("No session key provided in the request header!");
                }

                var context = new BloggingSystemContext();

                var user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);

                if (user == null)
                {
                    throw new InvalidOperationException("Invalid username or password.");
                }

                var tags = context.Tags.Include(t => t.Posts).AsQueryable();

                var tagDtos = GetAllTagDtos(tags);
                return tagDtos.OrderBy(t => t.Name);
            }
            catch (Exception ex)
            {
                var errorResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
                throw new HttpResponseException(errorResponse);
            }
        }
        public IQueryable<TagModel> GetAll(
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))]
            string sessionKey)
        {
            var responseMsg = this.ExceptionHandling(
                () =>
                {
                    var context = new BloggingSystemContext();

                    var user = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);

                    if (user == null)
                    {
                        throw new InvalidOperationException("Invalid username or password!");
                    }

                    var tagsEntities = context.Tags;
                    var models =
                        (from tagEntity in tagsEntities
                         select new TagModel()
                         {
                             Id = tagEntity.Id,
                             Name = tagEntity.Name,
                             NumberOfPosts = tagEntity.Post.Tags.Count
                         });
                    return models.OrderBy(t => t.Name);
                });
            return responseMsg;
        }
Exemplo n.º 6
0
        public IOrderedQueryable<PostDto> FilterByKeyword(string keyword)
        {
            try
            {
                var sessionKey = ApiControllerHelper.GetHeaderValue(Request.Headers, "X-SessionKey");
                if (sessionKey == null)
                {
                    throw new ArgumentNullException("No session key provided in the request header!");
                }

                var context = new BloggingSystemContext();

                var user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);

                if (user == null)
                {
                    throw new InvalidOperationException("Invalid username or password.");
                }

                var posts = context.Posts
                    .Include(p => p.Tags)
                    .Include(p => p.Comments)
                    .Where(p => p.Title.ToLower().IndexOf(keyword.ToLower()) >= 0);

                var postDtos = GetAllPostDtos(posts);
                return postDtos.OrderByDescending(p => p.PostDate);
            }
            catch (Exception ex)
            {
                var errorResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
                throw new HttpResponseException(errorResponse);
            }
        }
        public static Post CreateNewEntity(PostModel postModel, User author, BloggingSystemContext context)
        {
            Post postEntity = new Post()
            {
                Title = postModel.Title,
                Author = author,
                PostDate = DateTime.Now,
                Text = postModel.Text
            };

            foreach (var tagName in postModel.Tags)
            {
                postEntity.Tags.Add(Extensions.CreateOrLoadTag(tagName.ToLower(), context));
            }

            var titleTags = postModel.Title.Split(WordSeparators, StringSplitOptions.RemoveEmptyEntries);
            foreach (var titleTagName in titleTags)
            {
                if (titleTagName.Length > 1)
                {
                    postEntity.Tags.Add(Extensions.CreateOrLoadTag(titleTagName.ToLower(), context));
                }
            }

            return postEntity;
        }
        public IQueryable<TagModel> GetTagsById(int tagId,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))]
            string sessionKey)
        {
            var responseMsg = this.ExceptionHandling(
                () =>
                {
                    var context = new BloggingSystemContext();

                    var entityTags = context.Tags.FirstOrDefault(x => x.Id == tagId).Post.Tags;
                    var tagModels = new List<TagModel>();
                    foreach (var entityTag in entityTags)
                    {
                        tagModels.Add(new TagModel()
                        {
                            Name = entityTag.Name,
                            Id = entityTag.Id,
                            NumberOfPosts = entityTag.Post.Tags.Count,
                            PostDate = entityTag.Post.PostDate
                        });
                    }
                    return tagModels.OrderByDescending(t => t.PostDate);
                });

            return responseMsg.AsQueryable();
        }
        public HttpResponseMessage LoginUser([FromBody]UserLoginModel user)
        {
            HttpResponseMessage responseMessage = this.PerformOperation(() =>
            {
                UserValidator.ValidateAuthenticationCode(user.AuthCode);
                UserValidator.ValidateUsername(user.Username);

                var context = new BloggingSystemContext();
                using (context)
                {
                    var userEntity = context.Users.FirstOrDefault(
                        u => u.AuthCode == user.AuthCode && u.Username == user.Username.ToLower());
                    if (userEntity == null)
                    {
                        throw new InvalidOperationException("User not registered!");
                    }

                    userEntity.SessionKey = UserValidator.GenerateSessionKey(userEntity.ID);
                    context.SaveChanges();

                    UserLoggedModel loggedUser = UsersMapper.ToModel(userEntity);
                    return this.Request.CreateResponse(HttpStatusCode.Created, loggedUser);
                }
            });

            return responseMessage;
        }
        public HttpResponseMessage RegisterUser([FromBody]UserRegisterModel user)
        {
            HttpResponseMessage responseMessage = this.PerformOperation(() =>
            {
                UserValidator.ValidateAuthenticationCode(user.AuthCode);
                UserValidator.ValidateDisplayName(user.DisplayName);
                UserValidator.ValidateUsername(user.Username);

                var context = new BloggingSystemContext();
                using (context)
                {
                    User exstingUserEntity = context.Users.FirstOrDefault<User>(
                        u => u.Username == user.Username.ToLower() || u.DisplayName.ToLower() == user.DisplayName.ToLower());
                    if (exstingUserEntity != null)
                    {
                        throw new InvalidOperationException("User already exists!");
                    }

                    User newUserEntity = UsersMapper.ToEntity(user);
                    context.Users.Add(newUserEntity);
                    context.SaveChanges();

                    newUserEntity.SessionKey = UserValidator.GenerateSessionKey(newUserEntity.ID);
                    context.SaveChanges();

                    UserLoggedModel loggedUser = UsersMapper.ToModel(newUserEntity);
                    return this.Request.CreateResponse(HttpStatusCode.Created, loggedUser);
                }
            });

            return responseMessage;
        }
Exemplo n.º 11
0
        private User GetAndValidateUser(string sessionKey, BloggingSystemContext context)
        {
            var user = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);
            if (user == null)
            {
                throw new InvalidOperationException("Invalid username or password!");
            }

            return user;
        }
Exemplo n.º 12
0
        public static void VerifySessionKey(string sessionKey)
        {
            var context = new BloggingSystemContext();

            var user = context.Users.FirstOrDefault(
                usr => usr.SessionKey == sessionKey);

            if (user == null)
            {
                throw new ArgumentOutOfRangeException("You must be logged in to see this content");
            }
        }
Exemplo n.º 13
0
        private static void Main()
        {
            // Run the console client first in order to create the database

            Database.SetInitializer<BloggingSystemContext>(new DatabaseInitializer());

            using (var dbContext = new BloggingSystemContext())
            {
                dbContext.Database.Initialize(true);

                Console.WriteLine(dbContext.Users.Count());
            }
        }
        public HttpResponseMessage PostRegisterUser(UserModel model)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BloggingSystemContext();
                using (context)
                {
                    this.ValidateUsername(model.Username);
                    this.ValidateNickname(model.DisplayName);
                    this.ValidateAuthCode(model.AuthCode);

                    var usernameLower = model.Username.ToLower();
                    var nicknameLower = model.DisplayName.ToLower();

                    var user = context.Users
                        .FirstOrDefault(usr => usr.Username == usernameLower ||
                            usr.DisplayName == nicknameLower);

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

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

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

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

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

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

                    return response;
                }
            });

            return responseMsg;
        }
        public static Tag CreateOrLoadTag(string tagName, BloggingSystemContext context)
        {
            Tag exstingTag = context.Tags.FirstOrDefault<Tag>(t => t.Name == tagName);
            if (exstingTag != null)
            {
                return exstingTag;
            }

            Tag newTag = new Tag() { Name = tagName };
            context.Tags.Add(newTag);
            context.SaveChanges();

            return newTag;
        }
Exemplo n.º 16
0
        public IQueryable<PostModel> GetPostsForTag(int tagId,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BloggingSystemContext();
                var user = GetAndValidateUser(sessionKey, context);
                var postEntities = context.Posts.Where(p => p.Tags.Any(t => t.Id == tagId)).AsQueryable();
                var models = PostsController.GetPostModelsFromEntities(postEntities);

                return models.OrderByDescending(p => p.PostDate);
            });

            return responseMsg;
        }
Exemplo n.º 17
0
        public IQueryable<TagModel> GetAll(
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BloggingSystemContext();
                var user = GetAndValidateUser(sessionKey, context);
                var tagsEntities = context.Tags;
                var models = GetTagsModelsFromEntities(tagsEntities);

                return models.OrderBy(t => t.Name);
            });

            return responseMsg;
        }
Exemplo n.º 18
0
        public IQueryable<PostModel> GetAll(
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BloggingSystemContext();
                var user = GetAndValidateUser(sessionKey, context);
                var postsEntities = context.Posts;
                var models = GetPostModelsFromEntities(postsEntities);

                return models.OrderByDescending(p => p.PostDate);
            });

            return responseMsg;
        }
        public HttpResponseMessage GetPosts(int tagId, string sessionKey)
        {
            var context = new BloggingSystemContext();
            var tag = context.Tags.FirstOrDefault(t => t.TagId == tagId);

            try
            {
                this.VerifySessionKey(sessionKey);

                if (tag == null)
                {
                    throw new ArgumentOutOfRangeException("Tag not found");
                }
            }
            catch (Exception e)
            {
                var errorResponse = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message);
                return errorResponse;
            }

            var posts = tag.Posts;

            var postsResult =
                (from post in posts
                 orderby post.PostDate descending
                 select new PostModel()
                 {
                     Id = post.PostId,
                     Title = post.Title,
                     Text = post.Text,
                     PostDate = post.PostDate,
                     PostedBy = post.User.DisplayName,
                     Tags = (from t in post.Tags
                             select t.Text),
                     Comments = (from comment in post.Comments
                                 orderby comment.PostDate descending
                                 select new CommentModel()
                                 {
                                     Text = comment.Text,
                                     CommentedBy = comment.User.DisplayName,
                                     PostDate = comment.PostDate
                                 })
                 });

            var response = this.Request.CreateResponse(HttpStatusCode.Created, postsResult);

            return response;
        }
Exemplo n.º 20
0
        private User GetValidUser(string sessionKey)
        {
            var context = new BloggingSystemContext();

            using (context)
            {
                var user = context.Users.FirstOrDefault(ur => ur.SessionKey == sessionKey);

                if (user == null)
                {
                    throw new InvalidOperationException("You are not logged in.");
                }

                return user;
            }
        }
        public HttpResponseMessage PostLoginUser(UserModel model)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BloggingSystemContext();
                using (context)
                {
                    this.ValidateUsername(model.Username);
                    this.ValidateAuthCode(model.AuthCode);

                    var usernameLower = model.Username.ToLower();
                    var nicknameLower = model.DisplayName.ToLower();

                    var user = context.Users
                        .FirstOrDefault(
                        usr => usr.Username == usernameLower &&
                            usr.AuthCode == model.AuthCode);

                    if (user == null)
                    {
                        throw new InvalidOperationException("Invalid name or password");
                    }

                    if (string.IsNullOrWhiteSpace(user.SessionKey))
                    {
                        var sesKey = this.GenerateSessionKey(user.Id);
                        ValidateSessionKey(sesKey);
                        user.SessionKey = sesKey;
                        context.SaveChanges();
                    }

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

                    var response = this.Request.CreateResponse(
                        HttpStatusCode.OK, loggedModel);

                    return response;
                }
            });

            return responseMsg;
        }
Exemplo n.º 22
0
        public HttpResponseMessage AddComment(int postId, CommentModel comment,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BloggingSystemContext();
                var user = GetAndValidateUser(sessionKey, context);
                var postEntity = context.Posts.FirstOrDefault(p => p.Id == postId);
                var commentEntity = new Comment() { PostDate = DateTime.Now, Text = comment.Text, User = user };
                postEntity.Comments.Add(commentEntity);
                context.SaveChanges();

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

            return responseMsg;
        }
        public HttpResponseMessage LogoutUser(string sessionKey)
        {
            var context = new BloggingSystemContext();

            var user = context.Users.FirstOrDefault(
                usr => usr.SessionKey == sessionKey);

            if (user != null)
            {
                user.SessionKey = null;
                context.SaveChanges();

                var response = this.Request.CreateResponse(HttpStatusCode.OK);
                return response;
            }
            else
            {
                var response = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Wrong session");
                return response;
            }
        }
        public HttpResponseMessage Login(UserModel model)
        {
            var responseMsg = this.ExceptionHandling(
              () =>
              {
                  var context = new BloggingSystemContext();
                  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.Id);
                          context.SaveChanges();
                      }

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

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

            return responseMsg;
        }
        public IQueryable<PostModel> GetAll(
             [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.ExceptionHandling(
                () =>
                {
                    var context = new BloggingSystemContext();

                        var user = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);

                        if (user == null)
                        {
                            throw new InvalidOperationException("Invalid username or password!");
                        }

                        var postsEntities = context.Posts;
                        var models =
                            (from postEntity in postsEntities
                             select new PostModel()
                             {
                                 Id = postEntity.Id,
                                 Title = postEntity.Title,
                                 Text = postEntity.Text,
                                 PostDate = postEntity.PostDate,
                                 PostedBy = postEntity.User.Displayname,
                                 Comments = (from commentEntity in postEntity.Comments
                                             select new CommentModel()
                                             {
                                                 Text = commentEntity.Text,
                                                 PostDate = commentEntity.PostDate,
                                                 CommentedBy = commentEntity.User.Displayname
                                             }),
                                Tags = (from tagEntity in postEntity.Tags
                                        select tagEntity.Name)
                             });
                        return models.OrderByDescending(p => p.PostDate);
                });
            return responseMsg;
        }
        public HttpResponseMessage LoginUser(UserModel model)
        {
            var context = new BloggingSystemContext();
            var usernameLower = model.Username.ToLower();

            var user = context.Users.FirstOrDefault(
                usr => usr.Username == usernameLower ||
                       usr.AuthCode == model.AuthCode);

            try
            {
                if (user == null)
                {
                    throw new InvalidOperationException("Invalid username and/or password");
                }
            }
            catch (Exception e)
            {
                var errorResponse = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message);
                return errorResponse;
            }

            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;
        }
Exemplo n.º 27
0
        public IQueryable<GetPostModel> GetPostByTag(
            int tagId,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                this.GetValidUser(sessionKey);

                var context = new BloggingSystemContext();
                
                    var tag = context.Tags.Where(tg => tg.Id == tagId).FirstOrDefault();
                    var allModels = context.Posts.Where(ps => ps.Tags.Any(tg => tg.Id == tag.Id));

                    var filteredModels =
                        (from postEnt in allModels.ToList()
                        select new GetPostModel()
                        {
                            Id = postEnt.Id,
                            Title = postEnt.Title,
                            Text = postEnt.Text,
                            PostedBy = postEnt.User.DisplayName,
                            PostDate = postEnt.PostDate,
                            Tags = postEnt.Tags.Select(x => x.Title).ToArray(),
                            Comments =
                            from commentEnt in postEnt.Comments
                            select new CommentModel()
                            {
                                Text = commentEnt.Text,
                                PostDate = commentEnt.CommentDate,
                                CommentedBy = commentEnt.User.DisplayName
                            }
                        }).OrderByDescending(ps => ps.PostDate);

                    return filteredModels.AsQueryable();
            });

            return responseMsg;
        }
Exemplo n.º 28
0
        public IQueryable<TagModel> GetAllTags(
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                this.GetValidUser(sessionKey);

                var context = new BloggingSystemContext();

                var models =
                    (from tagEnt in context.Tags
                     select new TagModel()
                     {
                         Id = tagEnt.Id,
                         Name = tagEnt.Title,
                         Posts = tagEnt.Posts.Count
                     }).OrderBy(tg => tg.Name);

                return models;
            });

            return responseMsg;
        }
        public IEnumerable<PostModel> GetPosts(int tagID,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))]string sessionKey)
        {
            var tagPosts = this.PerformOperation(() =>
            {
                UserValidator.ValidateSessionKey(sessionKey);

                var context = new BloggingSystemContext();
                using (context)
                {
                    var loggedUserEntity = context.Users.FirstOrDefault<User>(u => u.SessionKey == sessionKey);
                    if (loggedUserEntity == null)
                    {
                        throw new InvalidOperationException("Invalid user or pasword!");
                    }

                    var tagEntity = context.Tags.Find(tagID);
                    if (tagEntity == null)
                    {
                        var errorResponse = this.Request.CreateErrorResponse(
                            HttpStatusCode.NotFound, "Tag with provided ID not found!");
                        throw new HttpResponseException(errorResponse);
                    }

                    var tagPostModels = new List<PostModel>();
                    var tagPostEntities = tagEntity.Posts.OrderByDescending(p => p.PostDate);
                    foreach (var tagPostEntity in tagPostEntities)
                    {
                        tagPostModels.Add(PostsMapper.ToModel(tagPostEntity));
                    }

                    return tagPostModels;
                }
            });

            return tagPosts;
        }
 private void ClearDatabase()
 {
     var context = new BloggingSystemContext();
     context.Database.ExecuteSqlCommand(@"
     EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'
     EXEC sp_MSForEachTable 'DELETE FROM ?'
     exec sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'");
 }