Ejemplo n.º 1
0
        public async Task VotePostTest(KnownChains apiName)
        {
            var user = Users[apiName];

            // Load last created post
            var userPostsRequest = new PostsModel(PostType.New)
            {
                Login = user.Login
            };
            var userPostsResponse = await Api[apiName].GetPosts(userPostsRequest, CancellationToken.None);

            AssertResult(userPostsResponse);
            var lastPost = userPostsResponse.Result.Results.First(i => !i.Vote);

            // 4) Vote up
            var voteUpRequest = new VoteModel(user, lastPost, VoteType.Up)
            {
                VoteDelay = 0
            };
            var voteUpResponse = await Api[apiName].Vote(voteUpRequest, CancellationToken.None);

            AssertResult(voteUpResponse);
            Assert.That(voteUpResponse.IsSuccess, Is.True);
            //Assert.IsTrue(lastPost.TotalPayoutReward <= voteUpResponse.Result.NewTotalPayoutReward);

            // Wait for data to be writed into blockchain
            Thread.Sleep(TimeSpan.FromSeconds(15));
            userPostsRequest.Offset = lastPost.Url;
            var userPostsResponse2 = await Api[apiName].GetPosts(userPostsRequest, CancellationToken.None);

            // Check if last post was voted
            AssertResult(userPostsResponse2);
            var post = userPostsResponse2.Result.Results.FirstOrDefault(i => i.Url.EndsWith(lastPost.Url, StringComparison.OrdinalIgnoreCase));

            Assert.IsNotNull(post);
            Console.WriteLine("The server still updates the history");
            //Assert.That(post.Vote, Is.True);

            // 3) Vote down
            var voteDownRequest = new VoteModel(user, lastPost, VoteType.Down)
            {
                VoteDelay = 0
            };
            var voteDownResponse = await Api[apiName].Vote(voteDownRequest, CancellationToken.None);

            AssertResult(voteDownResponse);
            Assert.That(voteDownResponse.IsSuccess, Is.True);
            //Assert.IsTrue(lastPost.TotalPayoutReward >= voteDownResponse.Result.NewTotalPayoutReward);

            // Wait for data to be writed into blockchain
            Thread.Sleep(TimeSpan.FromSeconds(15));
            var userPostsResponse3 = await Api[apiName].GetPosts(userPostsRequest, CancellationToken.None);

            // Check if last post was voted
            AssertResult(userPostsResponse3);
            post = userPostsResponse3.Result.Results.FirstOrDefault(i => i.Url.Equals(lastPost.Url, StringComparison.OrdinalIgnoreCase));
            Assert.IsNotNull(post);
            Console.WriteLine("The server still updates the history");
            //Assert.That(post.Vote, Is.False);
        }
Ejemplo n.º 2
0
        public HttpResponseMessage EditPost(int id, [FromBody] PostsModel postModel)
        {
            try
            {
                using (var blogdb = new blogdbEntities())
                {
                    posts newPost = (from p in blogdb.posts
                                     where p.id == id && p.id_author == loginUserId
                                     select p).SingleOrDefault();
                    if (newPost != null)
                    {
                        newPost.content = postModel.content;

                        blogdb.Entry(newPost).State = EntityState.Modified;
                        blogdb.SaveChanges();

                        return(Request.CreateResponse(HttpStatusCode.OK, "The Post was updated successfully."));
                    }
                    else
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound,
                                                           "The Post with Id: " + id.ToString() + " not found to update"));
                    }
                }
            }
            catch (Exception e)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message));
            }
        }
Ejemplo n.º 3
0
        public static PostsModel postsEntityToModel(PostsPics entity)
        {
            PostsModel posts = new PostsModel();

            posts.postsID       = entity.postsID;
            posts.postsContent  = entity.postsContent;
            posts.postsMaker    = entity.postsMaker;
            posts.postsLoved    = entity.postsLoved;
            posts.postsMakeDate = entity.postsMakeDate;
            posts.postsPicCount = entity.postsPicCount;
            posts.postsReaded   = entity.postsReaded;
            posts.postsPics     = entity.postsPics;
            posts.makerName     = entity.makerName;
            posts.picsSimpPath  = entity.picSimpPath;
            posts.whenPosts     = dateDiff(entity.postsMakeDate.GetValueOrDefault());
            posts.makerPhoto    = entity.makerPhoto;
            posts.makerID       = entity.openId;
            posts.postsLocation = entity.postsLocation;
            posts.latitude      = entity.latitude;
            posts.longitude     = entity.longitude;
            posts.postsType     = entity.postsType;
            posts.postsStatus   = entity.postsStatus.Value;
            posts.ifOfficial    = entity.ifOfficial;
            posts.picsRate      = entity.picsRate;
            posts.ifUserLoved   = entity.ifUserLoved > 0;
            posts.ifLY          = entity.ifLY;
            return(posts);
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> PutPostsModel(int id, PostsModel postsModel)
        {
            if (id != postsModel.ID)
            {
                return(BadRequest());
            }

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

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

            return(NoContent());
        }
Ejemplo n.º 5
0
        public async Task <ActionResult <PostsModel> > PostPostsModel(PostsModel postsModel)
        {
            _context.Posts.Add(postsModel);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetPostsModel", new { id = postsModel.ID }, postsModel));
        }
Ejemplo n.º 6
0
        protected override async Task OnParametersSetAsync()
        {
            var topicNode = await NodeService.GetAsync(Id);

            Topic         = Models.Topic.Create(topicNode);
            TopicUserName = !string.IsNullOrEmpty(topicNode.CreatedBy) ? await UserService.GetUserNameAsync(topicNode.CreatedBy) : string.Empty;

            var forumNode = await NodeService.GetAsync(Topic.ForumId);

            Forum = Models.Forum.Create(forumNode);
            Posts = new PostsModel(NodeService)
            {
                NodeSearch = new NodeSearch()
                {
                    Module   = Constants.ForumsModule,
                    Type     = Constants.PostType,
                    ParentId = Topic.Id,
                    OrderBy  = new string[]
                    {
                        OrderBy.Hot,
                        OrderBy.Latest
                    }
                }
            };
            await Posts.InitAsync();

            var loggedInUserId = (await AuthenticationStateTask).LoggedInUserId();

            CanEditTopic = await SecurityService.AllowedAsync(
                loggedInUserId,
                Topic.CreatedBy,
                Constants.ForumsModule,
                Constants.TopicType,
                Actions.Edit
                );

            CanDeleteTopic = await SecurityService.AllowedAsync(
                loggedInUserId,
                Topic.CreatedBy,
                Constants.ForumsModule,
                Constants.TopicType,
                Actions.Delete
                );

            CanAddPost = await SecurityService.AllowedAsync(
                loggedInUserId,
                null,
                Constants.ForumsModule,
                Constants.PostType,
                Actions.Add
                );

            CanVote = await SecurityService.AllowedAsync(
                loggedInUserId,
                null,
                Constants.ForumsModule,
                Constants.TopicType,
                Actions.Vote
                );
        }
Ejemplo n.º 7
0
        public JsonResult getPostsDetail(string postsId, string userId, int from, int count, DateTime refreshTime, string openId)
        {
            PostsHandler handler = new PostsHandler();

            handler.viewPosts(openId, postsId);
            PostsModel          result       = new PostsModel();
            bool                ifLoved      = false;
            List <RepliesModel> replies      = new List <RepliesModel>();
            List <PicsModel>    pics         = new List <PicsModel>();
            bool                ifFollowed   = false;
            string              lovedTimes   = "0";
            string              readCount    = string.Empty;
            bool                ifLegal      = handler.ifLegalPosts(postsId);
            List <RepliesModel> myReplies    = new List <RepliesModel>();
            string              repliesCount = string.Empty;
            string              shareCount   = string.Empty;


            pics         = handler.getAllPicsByPostsId(postsId);
            result       = handler.getPostsDetail(postsId);
            ifLoved      = handler.ifUserLoved(postsId, userId);
            repliesCount = handler.getRepliesCount(postsId);
            lovedTimes   = handler.postsLoved(postsId);
            myReplies    = handler.getMyReplies(postsId, from, count, refreshTime, openId);
            //replies = handler.getReplies(postsId, from, count, refreshTime, openId);
            ifFollowed = new UserHandler().ifFollowed(userId, postsId);
            readCount  = handler.getReadCount(postsId);
            ifLegal    = ifLegal && result.postsStatus != 1;
            shareCount = handler.getShareCount(postsId);
            bool ifMuted = new UserHandler().getConfigModel(openId).videoMuted == 1 ? true : false;

            return(Json(new { result = result, ifLoved = ifLoved, lovedTimes = lovedTimes, pics = pics, repliesCount = repliesCount, shareCount = shareCount, replies = replies, ifFollowed = ifFollowed, readCount = readCount, ifLegal = ifLegal, myReply = myReplies, ifMuted = ifMuted }));
        }
Ejemplo n.º 8
0
        public void PostsRequest(string method)
        {
            switch (method)
            {
            case "get":
                _statusCode = GetCodeStatus(_postsEndpoint);
                _jsonString = GetJsonString(_postsEndpoint);
                _postsList  = Posts.GetObject(_jsonString);
                break;

            case "post":
                _testObj = _postObject.GetTestObject("post");
                AddPostContent(GetJsonString(_testObj));
                _statusCode = GetCodeStatus(_postsEndpoint);
                break;

            case "put":
                _testObj = _postObject.GetTestObject("put");
                AddPostContent(GetJsonString(_testObj));
                _statusCode = GetCodeStatus(_postsEndpoint + "/8");
                break;

            case "delete":
                _statusCode = GetCodeStatus(_postsEndpoint + "/4");
                break;

            default:
                throw new ArgumentException($"The method {method} is not valid.");
            }
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> AddPost(PostsModel pm)
        {
            var claimsidentity = (ClaimsIdentity)this.User.Identity;
            var claims         = claimsidentity.FindFirst(ClaimTypes.NameIdentifier);

            if (ModelState.IsValid)
            {
                var files = HttpContext.Request.Form.Files;
                if (files.Count() > 0)
                {
                    byte[] pic = null;
                    using (var filestream = files[0].OpenReadStream())
                    {
                        using (var memorystream = new MemoryStream())
                        {
                            filestream.CopyTo(memorystream);
                            pic = memorystream.ToArray();
                        }
                    }
                    pm.Post = pic;
                }
                pm.UserId = claims.Value;
                _db.PostsModel.Add(pm);
                await _db.SaveChangesAsync();

                return(RedirectToAction(nameof(YourPosts)));
            }
            return(View(pm));
        }
Ejemplo n.º 10
0
        public void PostsValidations(string method)
        {
            switch (method)
            {
            case "get":
                _testObj = _postObject.GetTestObject("get");
                Assert.AreEqual(200, _statusCode);
                Assert.AreEqual(_testObj.Title,
                                _postsList.Find(x => x.id == 1).Title);
                Assert.AreEqual(_testObj.Author,
                                _postsList.Find(x => x.id == 1).Author);
                break;

            case "post":
                Assert.AreEqual(201, _statusCode);
                break;

            case "put":
                Assert.AreEqual(200, _statusCode);
                break;

            case "delete":
                Assert.AreEqual(200, _statusCode);
                break;

            default:
                throw new ArgumentException($"The method {method} is not valid.");
            }
        }
Ejemplo n.º 11
0
        public HttpResponseMessage CreatePost([FromBody] PostsModel postModel)
        {
            try
            {
                using (var blogdb = new blogdbEntities())
                {
                    int lastPostId = (!blogdb.posts.Any()) ? 0 : blogdb.posts.OrderByDescending(p => p.id).First().id;
                    int nextPostId = lastPostId + 1;

                    posts newPost = new posts
                    {
                        id        = nextPostId,
                        id_author = loginUserId,
                        content   = postModel.content
                    };

                    blogdb.Entry(newPost).State = EntityState.Added;
                    blogdb.SaveChanges();

                    return(Request.CreateResponse(HttpStatusCode.OK, "The Post was created successfully."));
                }
            }
            catch (Exception e)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message));
            }
        }
Ejemplo n.º 12
0
        public IActionResult Posts(string id)
        {
            PostsModel model = new PostsModel();

            model.Posts = blogService.GetById(id).Posts;
            return(PartialView("PostsPartialView", model));
        }
Ejemplo n.º 13
0
        public IActionResult Add([FromBody] PostsModel postModel)
        {
            var postCreated = this._postsRepository.Add(postModel);

            return(Created(new Uri($"{Request.Path}/{postCreated.Id}", UriKind.Relative), postCreated));
            //return CreatedAtAction("Add", new { postId = postCreated.Id }, postCreated);
        }
Ejemplo n.º 14
0
        private Post GetFirstPostWhere(StringBuilder sb, PostType postType, Func <Post, bool> func)
        {
            var  getPosts = new PostsModel(postType);
            Post testPost;

            do
            {
                var postsResp = _api.GetPosts(getPosts, CancellationToken.None)
                                .Result;

                if (!postsResp.IsSuccess)
                {
                    sb.AppendLine($"fail. Reason:{Environment.NewLine} {postsResp.Error.Message}");
                    return(null);
                }
                if (postsResp.Result.Results.Count == 0)
                {
                    sb.AppendLine("fail. Reason:{Environment.NewLine} There are no Posts!");
                    return(null);
                }

                testPost = postsResp.Result.Results.FirstOrDefault(func);
                if (testPost == null)
                {
                    getPosts.Offset = postsResp.Result.Results.Last().Url;
                }
            } while (testPost == null);
            return(testPost);
        }
Ejemplo n.º 15
0
        private void GetPostsTest(StringBuilder sb, int num)
        {
            sb.Append($"{num}) GetPostsTest : ");
            StepFinished?.Invoke(sb.ToString());

            var limit   = 3;
            var request = new PostsModel(PostType.New)
            {
                ShowNsfw = _user.IsNsfw, ShowLowRated = _user.IsLowRated, Limit = limit
            };
            var response = _api.GetPosts(request, CancellationToken.None).Result;

            if (IsError1(sb, limit, response, response.Result.Results.Count))
            {
                return;
            }

            request.Offset = response.Result.Results.Last().Url;
            response       = _api.GetPosts(request, CancellationToken.None).Result;

            if (IsError2(sb, limit, response, request.Offset))
            {
                return;
            }

            sb.AppendLine("pass.");
        }
Ejemplo n.º 16
0
        private void GetPostInfoTest(StringBuilder sb, int num)
        {
            sb.Append($"{num}) GetPostInfoTest : ");
            StepFinished?.Invoke(sb.ToString());

            var getPosts = new PostsModel(PostType.Top);

            var postsResp = _api.GetPosts(getPosts, CancellationToken.None)
                            .Result;

            if (!postsResp.IsSuccess)
            {
                sb.AppendLine($"fail. Reason:{Environment.NewLine} {postsResp.Error.Message}");
                return;
            }
            if (postsResp.Result.Results.Count == 0)
            {
                sb.AppendLine("fail. Reason:{Environment.NewLine} There are no Posts!");
                return;
            }

            var testPost = postsResp.Result.Results.First();


            var request  = new NamedInfoModel(testPost.Url);
            var response = _api.GetPostInfo(request, CancellationToken.None).Result;

            if (!response.IsSuccess)
            {
                sb.AppendLine($"fail. Reason:{Environment.NewLine} {postsResp.Error.Message}");
                return;
            }

            sb.AppendLine("pass.");
        }
Ejemplo n.º 17
0
        public override void Run()
        {
            var client = new HttpClient {
                BaseAddress = new Uri(BaseUlr)
            };
            PostsModel request = new PostsModel(postsUserId, postsTitle, postsBody);

            string json = JsonConvert.SerializeObject(request, Formatting.Indented, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            Reporter.LogInfo("Request: " + json);

            StringContent       content  = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = client.PostAsync("posts", content).Result;

            PostsModel parsedResponse = JsonConvert.DeserializeObject <PostsModel>(response.Content.ReadAsStringAsync().Result);

            Assert.Multiple(() =>
            {
                Assert.IsTrue(response.IsSuccessStatusCode, $"Current status code is {response.StatusCode.ToString()}");
                Assert.AreEqual(101, parsedResponse.Id);
            });
        }
Ejemplo n.º 18
0
 public bool Delete(PostsModel model)
 {
     try
     {
         using (var db = new PORTALEntities())
         {
             var item = (from c in db.CmsPosts
                         where c.PostId == model.PostId
                         select c).FirstOrDefault();
             if (item == null)
             {
                 return(false);
             }
             item.IsDelete   = true;
             item.DeleteDate = model.UpdateDate;
             item.DeleteUid  = model.UpdateUid;
             db.SaveChanges();
             return(true);
         }
     }
     catch (Exception ex)
     {
         LogHelper.Error("PostsRepository Delete: " + ex.Message + " Inner exception: " + ex.InnerException.Message);
         return(false);
     }
 }
Ejemplo n.º 19
0
        public IActionResult Create(PostsModel model)
        {
            if (!this.User.IsAuthenticated)
            {
                return(this.RedirectToLogin());
            }

            if (!this.IsValidModel(model))
            {
                this.ShowError(CreateError);
                return(this.View());
            }

            this.post.Create(
                model.Title,
                model.Content,
                this.Profile.Id);

            if (this.IsAdmin)
            {
                this.Log(LogType.CreatePost, model.Title);
            }

            return(this.RedirectToHome());
        }
Ejemplo n.º 20
0
        //
        // GET: /Post/

        public ActionResult Index()
        {
            IEnumerable <Post>       listPosts      = PostDAO.GetAllPosts();
            IEnumerable <PostsModel> listModelPosts = PostsModel.GetListPosts(listPosts);

            return(View(listModelPosts));
        }
Ejemplo n.º 21
0
        public async Task GetPostsTest(KnownChains apiName)
        {
            var request = new PostsModel(PostType.Top);

            var result = await Gateway[apiName].GetPosts(request, CancellationToken.None);

            Assert.IsTrue(result.IsSuccess, result.Error?.Message);
        }
        public IActionResult ViewPostDetails(int postID)
        {
            // return Content("ViewPostDetails");
            PostsModel foundPost = _context.postsList.Include(p => p.postSteps).FirstOrDefault(p => p.id == postID);

            return(View(foundPost));
            // return Content($"{foundPost.title} and {foundPost.postBody}");
        }
Ejemplo n.º 23
0
 public PostsModel Add(PostsModel post)
 {
     lock (lockObject)
     {
         post.Id = this._posts.Count <= 0 ? 1 : this._posts.Max(p => p.Id) + 1;
         _posts.Add(post);
         return(post);
     }
 }
Ejemplo n.º 24
0
        private void FollowTest(StringBuilder sb, int num)
        {
            sb.Append($"{num}) FollowTest : ");
            StepFinished?.Invoke(sb.ToString());
            // Load last created post
            var getPosts = new PostsModel(PostType.New)
            {
                Login = _user.Login
            };

            var postsResp = _api.GetPosts(getPosts, CancellationToken.None)
                            .Result;

            if (!postsResp.IsSuccess)
            {
                sb.AppendLine($"fail. Reason:{Environment.NewLine} {postsResp.Error.Message}");
                return;
            }
            if (postsResp.Result.Results.Count == 0)
            {
                sb.AppendLine("fail. Reason:{Environment.NewLine} There are no Posts to Follow!");
                return;
            }

            var testPost = postsResp.Result.Results.First();

            var votereq = new FollowModel(_user, FollowType.Follow, testPost.Author);
            var rez     = _api.Follow(votereq, CancellationToken.None)
                          .Result;

            if (!rez.IsSuccess)
            {
                sb.AppendLine($"fail. Reason:{Environment.NewLine} {rez.Error.Message}");
                return;
            }

            Task.Delay(10000);

            var userFriendsReq = new UserFriendsModel(_user.Login, FriendsType.Followers)
            {
                Login = _user.Login, Offset = testPost.Author, Limit = 1
            };
            var verifyResp = _api.GetUserFriends(userFriendsReq, CancellationToken.None).Result;

            if (!verifyResp.IsSuccess)
            {
                sb.AppendLine($"fail. Reason:{Environment.NewLine} {verifyResp.Error.Message}");
                return;
            }
            if (verifyResp.Result.Results.Count != 1)
            {
                sb.AppendLine($"fail. Reason:{Environment.NewLine} user ({testPost.Author}) not found!");
                return;
            }
            sb.AppendLine("pass.");
        }
Ejemplo n.º 25
0
        public async Task Posts_Top_Limit_Default(KnownChains apiName)
        {
            // Arrange
            var request = new PostsModel(PostType.Top);

            // Act
            var response = await Api[apiName].GetPosts(request, CancellationToken.None);

            // Assert
            AssertResult(response);
        }
Ejemplo n.º 26
0
 public void Update(int postId, PostsModel post)
 {
     lock (lockObject)
     {
         var currentPost = this.GetPostById(postId);
         if (currentPost != null)
         {
             currentPost.Title       = post.Title;
             currentPost.Description = post.Description;
         }
     }
 }
Ejemplo n.º 27
0
        public string Update(PostsModel model)
        {
            //model.Id = Guid.NewGuid();
            model.CreateUid  = User.GetClaimValue(ClaimTypes.PrimarySid);
            model.CreateDate = System.DateTime.Now;

            if ((new PostsRepository()).UpdateFaq(model))
            {
                return("OK");
            }
            return("Error");
        }
Ejemplo n.º 28
0
        public void InsertPhotoPost(PostsModel photoPost)
        {
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@USERID", photoPost.UserId),
                new SqlParameter("@IMAGEURL", photoPost.PostedImage),
                new SqlParameter("@FILTER", photoPost.Filter),
                new SqlParameter("@GUID", photoPost.Guid),
            };

            ExecuteSPNonReturnData("InsertPhotoPost", parameters);
        }
Ejemplo n.º 29
0
        public ActionResult Delete(int id)
        {
            var model = new PostsModel()
            {
                PostId     = id,
                UpdateUid  = User.GetClaimValue(ClaimTypes.PrimarySid),
                UpdateDate = DateTime.Now
            };
            var repository = new PostsRepository();

            return(Json(repository.Delete(model) ? new { result = "OK" } : new { result = "ERROR" }));
        }
Ejemplo n.º 30
0
        public ActionResult Insert()
        {
            var controllerId = this.ControllerContext.RouteData.Values["controller"].ToString() + "Controller";

            ViewBag.Rights = (new AuthorizationRepository()).GetRights(controllerId, User.GetClaimValue(ClaimTypes.Role));
            var model = new PostsModel()
            {
                IsActive = true
            };

            return(View(model));
        }
        public async Task Posts_New(KnownChains apiName)
        {
            // Arrange
            var request = new PostsModel(PostType.New);

            // Act
            var response = await Api[apiName].GetPosts(request, CancellationToken.None);

            // Assert
            AssertResult(response);
            Assert.That(response.Result.Results, Is.Not.Empty);
        }
Ejemplo n.º 32
0
        public void UpdatePhotoPost(PostsModel photoPost)
        {
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@USERID", photoPost.UserId),
                new SqlParameter("@SHORTCOMMENT", photoPost.SmallComment),
                new SqlParameter("@COMMENT", photoPost.BigComment),
                new SqlParameter("@LOCATION", photoPost.Location),
                new SqlParameter("@GUID", photoPost.Guid),
            };

            ExecuteSPNonReturnData("UpdateUserPost", parameters);
        }
Ejemplo n.º 33
0
        public PostsModel InsertPost(PostsModel sentPost)
        {
            string[] sampleFoods = new string[] { "burger.jpg", "coffee.jpg", "nuggets.jpg", "dogfood.jpg" };
            string imageURL = "http://ugoforweb.azurewebsites.net/www/img/" + sampleFoods[new Random(Guid.NewGuid().GetHashCode()).Next(0,4)];

            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@USERID", sentPost.UserId),
                new SqlParameter("@SHORTCOMMENT", sentPost.SmallComment),
                new SqlParameter("@IMAGEURL", imageURL),
                new SqlParameter("@COMMENT", sentPost.BigComment),
                new SqlParameter("@LOCATION", sentPost.Location),
            };

            var postedUser = ExecuteSPReturnData<PostsModel>("InsertUserPost", parameters).First();

            return new PostsModel { ProfilePicURL = postedUser.ProfilePicURL,
                                    SmallComment = sentPost.SmallComment,
                                    TimePosted = "1s",
                                    PostedImage = imageURL,
                                    BigComment = sentPost.BigComment,
                                    Username = postedUser.Username
                                  };
        }
Ejemplo n.º 34
0
        public override Task ExecutePostProcessingAsync()
        {
            //Calling this method for new registration
            SignUpModel signUp = new SignUpModel();
            PostsModel newPost = new PostsModel();

            bool isASignUp = false;
            bool isAPhotoPost = false;

            // NOTE: FileData is a property of MultipartFileStreamProvider and is a list of multipart
            // files that have been uploaded and saved to disk in the Path.GetTempPath() location.

            foreach (var fileData in FileData)
            {

                if (fileData.Headers.ContentDisposition.FileName == null)
                {
                    //do something here with the form data
                    var pair = fileData.Headers.ContentDisposition.Name.Trim('"').Split('-');
                    switch (pair[0])
                    {
                        case("uname"):
                            signUp.Username = pair[1];
                            isASignUp = true;
                            break;
                        case("email"):
                            signUp.Email = pair[1];
                            isASignUp = true;
                            break;
                        case("pass"):
                            signUp.Password = pair[1];
                            isASignUp = true;
                            break;
                        case ("userid"):
                            newPost.UserId = Convert.ToInt32(pair[1]);
                            isAPhotoPost = true;
                            break;
                        case ("filtername"):
                            newPost.Filter = pair[1];
                            isAPhotoPost = true;
                            break;
                        case ("guid"):
                            newPost.Guid = pair[1];
                            isAPhotoPost = true;
                            break;
                    }
                    continue;
                }
                
                // Sometimes the filename has a leading and trailing double-quote character
                // when uploaded, so we trim it; otherwise, we get an illegal character exception
                var fileName = Path.GetFileName(fileData.Headers.ContentDisposition.FileName.Trim('"'));

                //signUp.Password = pair[1];

                // Retrieve reference to a blob
                var blobContainer = BlobHelper.GetBlobContainer();
                var blob = blobContainer.GetBlockBlobReference(fileName);

                // Set the blob content type
                blob.Properties.ContentType = fileData.Headers.ContentType.MediaType;

                // Upload file into blob storage, basically copying it from local disk into Azure
                using (var fs = File.OpenRead(fileData.LocalFileName))
                {
                    //APPLY FILTERS HERE 
                    string passedFilter = string.IsNullOrEmpty(newPost.Filter) ? "" : newPost.Filter;

                    //convert stream into image, and apply filter                    
                    Image filterApplied = UGoFilters.ApplyFilter(passedFilter, Image.FromStream(fs));

                    //convert image to stream and upload
                    blob.UploadFromStream(Compression.ToStream(filterApplied, 75));
                }

                // Delete local file from disk
                File.Delete(fileData.LocalFileName);

                //Adding New User
                int id = 0;
                if (isASignUp)
                { 
                    signUp.ProfilePicURL = blob.Uri.AbsoluteUri;
                    id = new SignUpModel().InsertNewUser(signUp);
                }
                //Adding a New Post
                else if (isAPhotoPost)
                {
                    newPost.PostedImage = blob.Uri.AbsoluteUri;
                    new PostsModel().InsertPhotoPost(newPost);
                }

                // Create blob upload model with properties from blob info
                var blobUpload = new BlobUploadModel
                {
                    FileName = blob.Name,
                    FileUrl = blob.Uri.AbsoluteUri,
                    FileSizeInBytes = blob.Properties.Length,
                    CustomData = id.ToString()
                };


                // Add uploaded blob to the list
                Uploads.Add(blobUpload);
            }

            return base.ExecutePostProcessingAsync();
        }
Ejemplo n.º 35
0
 // POST: api/Posts
 public void Post(PostsModel sentPost)
 {
     new PostsModel().UpdatePhotoPost(sentPost);
 }