public async Task PostMarkupAsyncForOnlineApplication()
        {
            // Arrange
            var footerAndBodyRegions = new List <RegionModel> {
                defaultHeadRegion, defaultBodyRegion, defaultBodyFooterRegion
            };
            var fakeApplicationModel = new ApplicationModel {
                AppRegistrationModel = defaultAppRegistrationModel, Article = Article
            };

            fakeApplicationModel.AppRegistrationModel.Regions = footerAndBodyRegions;

            var pageModel = new PageViewModel();
            await mapper.Map(fakeApplicationModel, pageModel);

            var postResponse = new PostResponseModel
            {
                Html = BodyRegionContent,
            };

            A.CallTo(() => contentRetriever.PostContent($"{defaultBodyRegion.RegionEndpoint}/{Article}", fakeApplicationModel.AppRegistrationModel.Path, defaultBodyRegion, defaultFormPostParams, RequestBaseUrl)).Returns(postResponse);
            A.CallTo(() => contentRetriever.GetContent($"{defaultBodyFooterRegion.RegionEndpoint}/{Article}", fakeApplicationModel.AppRegistrationModel.Path, defaultBodyFooterRegion, A <bool> .Ignored, RequestBaseUrl, A <IHeaderDictionary> .Ignored)).Returns(BodyFooterRegionContent);

            // Act
            await applicationService.PostMarkupAsync(fakeApplicationModel, defaultFormPostParams, pageModel, string.Empty, new HeaderDictionary());

            //Assert
            Assert.Equal(footerAndBodyRegions.Count, pageModel.PageRegionContentModels.Count);
            Assert.Equal(BodyRegionContent, pageModel.PageRegionContentModels.First(x => x.PageRegionType == PageRegion.Body).Content.Value);
            Assert.Equal(BodyFooterRegionContent, pageModel.PageRegionContentModels.First(x => x.PageRegionType == PageRegion.BodyFooter).Content.Value);

            A.CallTo(() => contentRetriever.PostContent($"{defaultBodyRegion.RegionEndpoint}/{Article}", fakeApplicationModel.AppRegistrationModel.Path, defaultBodyRegion, defaultFormPostParams, RequestBaseUrl)).MustHaveHappenedOnceExactly();
            A.CallTo(() => contentRetriever.GetContent($"{defaultBodyFooterRegion.RegionEndpoint}/{Article}", fakeApplicationModel.AppRegistrationModel.Path, defaultBodyFooterRegion, A <bool> .Ignored, RequestBaseUrl, A <IHeaderDictionary> .Ignored)).MustHaveHappenedOnceExactly();
        }
Ejemplo n.º 2
0
        public async Task <PostResponseModel> Create(PostRequestModel model)
        {
            var currentPopilarity = await _unitOfWork.Repository <ApplicationUser>()
                                    .Get(u => u.Id == _userId)
                                    .Select(u => u.Popularity)
                                    .FirstOrDefaultAsync();

            var lessPopularUser = await _unitOfWork.Repository <ApplicationUser>()
                                  .Get(u => Stories.Select(s => s.AuthorId).Contains(u.Id) && u.Popularity < currentPopilarity || u.Popularity <= currentPopilarity)
                                  .FirstOrDefaultAsync();

            PostResponseModel response = null;

            response = await _story.Create(model);

            if (Stories.Count < 10)
            {
                Stories.Add(response);
            }
            else if (lessPopularUser != null)
            {
                Stories.Replace(Stories.OrderBy(s => s.CreationDate).FirstOrDefault(s => s.AuthorId == lessPopularUser.Id), response);
            }

            return(response);
        }
Ejemplo n.º 3
0
 internal void SetPostResponseModel(HttpMethodType type)
 {
     ResponseModel = new PostResponseModel
     {
         ModelValidation = new ModelValidationOutput {
             IsValid = true
         }
     };
     MethodType = type;
 }
Ejemplo n.º 4
0
 public static PostResponseModel _GetRecord(PostInparamModel value)
 {
     try
     {
         using (ServiceInstance server = FrameCorex.RecoverService(value.Token, (c) => { Debug.WriteLine("Container Token not found Token: " + c); }))
         {
             //if (!FrameCorex.ServiceInstanceInfo(server).IsLogin)
             //{
             //    server.UserLogin(value.LID, value.PWD);
             //    FrameCorex.ServiceInstanceInfo(server).DisposeInfo = false;
             //}
             if (server.Info.User == null)
             {
                 return new PostResponseModel()
                        {
                            Message   = "登陆失败",
                            Result    = Enums.APIResult.Error,
                            ExtResult = { }
                        }
             }
             ;
             var user   = FrameCorex.ServiceInstanceInfo(server).User;
             var tarres = new PostResponseModel()
             {
                 Message        = "Excute record query success",
                 Result         = Enums.APIResult.Success,
                 UserLoginToken = FrameCorex.ServiceInstanceInfo(server).LoginHashToken,
                 ExtResult      = { }
             };
             if (value.Params != null && value.Params.Count != 0)
             {
                 foreach (var t in value.Params.Keys)
                 {
                     tarres.ExtResult.Add(t, user.Records[t]);
                 }
             }
             else
             {
                 foreach (var t in user.Records.GetAll())
                 {
                     tarres.ExtResult.Add(t.Key, t.Value);
                 }
             }
             return(tarres);
         }
     }
     catch (FPException ex)
     {
         return(new PostResponseModel()
         {
             Message = ex.Message,
             Result = Enums.APIResult.Error
         });
     }
 }
Ejemplo n.º 5
0
 public ActionResult <bool> Update(PostResponseModel requestModel)
 {
     try
     {
         postRepository.Update(requestModel);
         return(Ok("Güncellendi."));
     }
     catch (Exception ex)
     {
         return(BadRequest(ex));
     }
 }
        public async Task <PostResponseModel> RegisterVendor(RegisterVendorRequestModel vendorDetailsRequestModel)
        {
            PostResponseModel postResponseModel = new PostResponseModel();

            RegisterVendor registerUser = new RegisterVendor()
            {
                VendorName     = vendorDetailsRequestModel.VendorName,
                VendorEmail    = vendorDetailsRequestModel.VendorEmail,
                VendorMobile   = vendorDetailsRequestModel.VendorMobile,
                VendorLandline = vendorDetailsRequestModel.VendorLandline,
                AddressLine    = vendorDetailsRequestModel.AddressLine,
                City           = vendorDetailsRequestModel.City,
                State          = vendorDetailsRequestModel.State,
                PinCode        = vendorDetailsRequestModel.PinCode
            };

            var registerVendorResponse = await _vendorAuthenticationRepository.RegisterVendor(registerUser);

            postResponseModel.IsAlreadyExists = registerVendorResponse.IsUserExists;

            if (!postResponseModel.IsAlreadyExists && registerVendorResponse.Success)
            {
                var emailBody    = "Hello !!!";
                var emailSubject = "Vendor Register";

                var emailResponse = await _messageSenderUtility.SendEmail(emailBody, emailSubject, vendorDetailsRequestModel.VendorEmail);

                postResponseModel.Success = emailResponse.IsEmailSend;

                //Log email
                EmailLogs emailLogDetails = new EmailLogs()
                {
                    FromEmailAddress = emailResponse.FromEmailAddress,
                    ToEmailAddress   = emailResponse.ToEmailAddress,
                    Subject          = emailSubject,
                    Body             = emailBody,
                    IsProduction     = emailResponse.IsProductionEnvironment,
                    IsSend           = emailResponse.IsEmailSend,
                    ApplicationId    = (int)ApplicationType.Vendor,
                    FromUserType     = "System",
                    ToUserType       = "Vendor",
                    ToUserId         = registerVendorResponse.Content.VendorId
                };

                await _loggingRepository.LogEmailTransaction(emailLogDetails);
            }
            else
            {
                postResponseModel.Success = registerVendorResponse.Success;
            }

            return(postResponseModel);
        }
Ejemplo n.º 7
0
        public IActionResult CreatePost([FromBody] CreatePostRequestModel newPost)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var post = _posts.CreatePost(newPost);

            var url          = Url.Action("PostDetails", new { id = post.Id });
            var postResponse = new PostResponseModel(post);

            return(Created(url, postResponse));
        }
Ejemplo n.º 8
0
        public bool Create([FromBody] PostResponseModel model)
        {
            var post = new Posts();

            post.Title      = model.Post.Title;
            post.Content    = model.Post.Content;
            post.UserId     = model.Post.UserId;
            post.CategoryId = model.Category.Id;
            post.CreateDate = DateTime.Now;

            _domainContext.Posts.Add(post);
            _domainContext.SaveChanges();

            return(true);
        }
Ejemplo n.º 9
0
        public PostResponseModel GetByID(int id)
        {
            var post     = _domainContext.Posts.FirstOrDefault(p => p.Id == id);
            var response = new PostResponseModel();
            var model    = new PostViewModel();

            model.Id         = post.Id;
            model.Title      = post.Title;
            model.Content    = post.Content;
            model.UserId     = post.UserId;
            model.CategoryId = post.CategoryId;
            response.Post    = model;
            response.Token   = GenerateToken(model);
            return(response);
        }
Ejemplo n.º 10
0
        public async Task <PostResponseModel> ConfirmRegistration(int vendorId)
        {
            PostResponseModel postResponseModel = new PostResponseModel();

            var passwordSalt      = AuthenticateUtility.CreatePasswordSalt();
            var password          = AuthenticateUtility.GetRandomAlphanumericString(12);
            var encryptedPassword = AuthenticateUtility.GeneratePassword(password, passwordSalt);

            var registerVendorResponse = await _vendorRepository.ConfirmRegistration(vendorId, encryptedPassword, passwordSalt);

            postResponseModel.IsAlreadyExists = registerVendorResponse.IsUserExists;
            if (!postResponseModel.IsAlreadyExists && registerVendorResponse.Success)
            {
                var emailBody    = "Your password: "******"Confirm Your Registration";

                var emailResponse = await _messageSenderUtility.SendEmail(emailBody, emailSubject, registerVendorResponse.Content.VendorEmail);

                postResponseModel.Success = emailResponse.IsEmailSend;

                //Log email
                EmailLogs emailLogDetails = new EmailLogs()
                {
                    FromEmailAddress = emailResponse.FromEmailAddress,
                    ToEmailAddress   = emailResponse.ToEmailAddress,
                    Subject          = emailSubject,
                    Body             = emailBody,
                    IsProduction     = emailResponse.IsProductionEnvironment,
                    IsSend           = emailResponse.IsEmailSend,
                    ApplicationId    = (int)ApplicationType.Admin,
                    FromUserType     = "System",
                    ToUserType       = "Vendor",
                    ToUserId         = registerVendorResponse.Content.VendorId,
                    CreatedDate      = DateTime.Now
                };

                await _loggingRepository.LogEmailTransaction(emailLogDetails);
            }
            else
            {
                postResponseModel.Success = registerVendorResponse.Success;
            }

            return(postResponseModel);
        }
Ejemplo n.º 11
0
        public ActionResult Update(int id, PostResponseModel model)
        {
            var post = this.User;

            if (string.IsNullOrEmpty(model.Post.Title) || string.IsNullOrEmpty(model.Post.Content))
            {
                return(RedirectToAction("Update"));
            }
            var token = post.Claims.FirstOrDefault(p => p.Type == ClaimTypes.Sid).Value;
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Authorization", "Bearer " + token);

            var putUri = string.Format("{0}/{1}", apiUrl, "post/Update/" + id);
            var result = _apiService.PutMethod <bool>(model, putUri, headers);

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 12
0
        public ActionResult Create(PostResponseModel model)
        {
            if (string.IsNullOrEmpty(model.Post.Title) || string.IsNullOrEmpty(model.Post.Content))
            {
                return(RedirectToAction("Create"));
            }
            var post   = this.User;
            var token  = post.Claims.FirstOrDefault(p => p.Type == ClaimTypes.Sid).Value;
            var UserId = post.Claims.FirstOrDefault(p => p.Type == ClaimTypes.NameIdentifier).Value;
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Authorization", "Bearer " + token);

            model.Post.UserId = Convert.ToInt32(UserId);
            var postUri = string.Format("{0}/{1}", apiUrl, "post/create");
            var result  = _apiService.PostMethod <bool>(model, postUri, headers);

            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 13
0
        public bool Update(int id, [FromBody] PostResponseModel model)
        {
            var post = _domainContext.Posts.FirstOrDefault(p => p.Id == id);

            if (model == null)
            {
                return(false);
            }
            else
            {
                post.Title      = model.Post.Title;
                post.Content    = model.Post.Content;
                post.CategoryId = model.Category.Id;

                _domainContext.SaveChanges();
                _memoryCache.Remove(key);
                return(true);
            }
        }
Ejemplo n.º 14
0
            public static PostResponseModel _QueryMission(PostInparamModel value)
            {
                try
                {
                    using (ServiceInstance server = FrameCorex.RecoverService(value.Token, (c) => { Debug.WriteLine("Container Token not found Token: " + c); }))
                    {
                        if (!FrameCorex.ServiceInstanceInfo(server).IsLogin)
                        {
                            server.UserLogin(value.LID, value.PWD);
                            FrameCorex.ServiceInstanceInfo(server).DisposeInfo = false;
                        }
                        var user     = FrameCorex.ServiceInstanceInfo(server).User;
                        var missions = user.QueryMissions();
                        var result   = new PostResponseModel()
                        {
                            Message   = "获取任务集",
                            Result    = Enums.APIResult.Success,
                            ExtResult =
                            {
                            },
                            UserLoginToken = FrameCorex.ServiceInstanceInfo(server).LoginHashToken
                        };

                        foreach (var t in missions)
                        {
                            result.ExtResult.Add(t.ID + "", t.ConvertMission());
                        }

                        return(result);
                    }
                }
                catch (FPException ex)
                {
                    return(new PostResponseModel()
                    {
                        Message = ex.Message,
                        Result = Enums.APIResult.Error
                    });
                }
            }
Ejemplo n.º 15
0
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (!context.ModelState.IsValid)
     {
         SetValidationResult(context.ModelState);
         PostResponseModel.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
         var err = PostResponseModel.ModelValidation.Errors.FirstOrDefault();
         if (err != null && !string.IsNullOrEmpty(err.Error))
         {
             PostResponseModel.SetErrorMessage(err.Error);
         }
         else
         {
             PostResponseModel.SetErrorMessage("Validation failed.");
         }
         var result = new ObjectResult(PostResponseModel)
         {
             StatusCode = PostResponseModel.StatusCode
         };
         context.Result = result;
     }
     base.OnActionExecuting(context);
 }
Ejemplo n.º 16
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 public static PostResponseModel _GetAllUserState(AdminPostInparamModel value)
 {
     try
     {
         using (ServiceInstance server = FrameCorex.GetService())
         {
             server.UserLogin(value.LID, value.PWD, Enums.Permission.Administor);
             FrameCorex.ServiceInstanceInfo(server).DisposeInfo = false;
             var result = new PostResponseModel();
             result.ExtResult.Add("Current users", Dealdct(FrameCorex.CurrentUsers(server)));
             result.ExtResult.Add("Interrupt users", Dealdct(FrameCorex.InterruptUsers(server)));
             return(result);
         }
     }
     catch (Exceptions.FPException ex)
     {
         return(new PostResponseModel()
         {
             Message = ex.Message,
             Result = Enums.APIResult.Error
         });
     }
 }
Ejemplo n.º 17
0
        //The scraping takes place in this method and returns a concatanated list of posts
        public List <PostResponseModel> GetPosts(int pageNumber, int numberOfPostsRequested)
        {
            List <PostResponseModel> returnedPosts = new List <PostResponseModel>();

            //validate uri
            bool isValidUri = Utility.validateURI(_uri);

            if (isValidUri)
            {
                //download page as html document
                //easier to work with and more efficient than making continuous calls to the website
                HtmlDocument content = new HtmlWeb().Load(_uri + "?p=" + pageNumber);

                //check that the document matches the xpath posts pattern
                if (content.DocumentNode.SelectNodes(_xpathPostsNode) != null)
                {
                    int totalRows          = content.DocumentNode.SelectNodes(_xpathPostsNode).Count();
                    PostResponseModel post = new PostResponseModel();
                    int  rowCount          = 0;
                    bool gottenFullPost    = false;

                    //loop through rows
                    for (int row = 1; row <= totalRows; row++)
                    {
                        string currentRow = _xpathPostsNode + "[" + row + "]/td";

                        //needed to bypass the blank row that separates each post in the table
                        if (content.DocumentNode.SelectNodes(currentRow) != null)
                        {
                            rowCount++;

                            int totalElementsInRow = content.DocumentNode.SelectNodes(currentRow).Count();

                            //loop through elements in a row
                            for (int element = 1; element <= totalElementsInRow; element++)
                            {
                                string currentElement = currentRow + "[" + element + "]";

                                //get title and uri if element contains it - they're in the same element
                                if (content.DocumentNode.SelectSingleNode(currentElement + "//a[@class=\"storylink\"]") != null)
                                {
                                    post.title = content.DocumentNode.SelectSingleNode(currentElement + "//a[@class=\"storylink\"]").InnerText;

                                    //will only allow up to 256 character - anything beyond that is trimmed off
                                    if (post.title.Length > 256)
                                    {
                                        post.title = post.title.Substring(0, 256);
                                    }

                                    post.uri = content.DocumentNode.SelectSingleNode(currentElement + "//a[@class=\"storylink\"]").Attributes["href"].Value;
                                    if (!Utility.validateURI(_uri))
                                    {
                                        post.uri = "no valid uri";
                                    }

                                    if (post.uri.Contains("item?id="))
                                    {
                                        post.uri = _uri + post.uri;
                                    }
                                }

                                //get author if element contains it
                                if (content.DocumentNode.SelectSingleNode(currentElement + "//a[@class=\"hnuser\"]") != null)
                                {
                                    post.author = content.DocumentNode.SelectSingleNode(currentElement + "//a[@class=\"hnuser\"]").InnerText;

                                    //will only allow up to 256 character - anything beyond that is trimmed off
                                    if (post.author.Length > 256)
                                    {
                                        post.author = post.author.Substring(0, 256);
                                    }
                                }

                                //get points if element contains it
                                if (content.DocumentNode.SelectSingleNode(currentElement + "//span[@class=\"score\"]") != null)
                                {
                                    var points = content.DocumentNode.SelectSingleNode(currentElement + "//span[@class=\"score\"]").InnerText;

                                    //remove the word 'points'
                                    Regex replacePattern = new Regex(@"(?<=[0-9]\s)points");
                                    points = replacePattern.Replace(points, "");

                                    post.points = Int32.Parse(points);
                                }

                                //get comments if element contains it - the last set of <a> tags
                                if (content.DocumentNode.SelectSingleNode(currentElement + "//a[3]") != null)
                                {
                                    var comments = content.DocumentNode.SelectSingleNode(currentElement + "//a[3]").InnerText;

                                    //though not often, sometimes the word 'discuss' will appear instead if there aren't any comments
                                    if (comments == "discuss")
                                    {
                                        comments = "0";
                                    }

                                    //zero element is the number of comments only
                                    comments = comments.Split('&')[0];


                                    post.comments = Int32.Parse(comments);
                                }

                                //get rank if element contains it
                                if (content.DocumentNode.SelectSingleNode(currentElement + "//span[@class=\"rank\"]") != null)
                                {
                                    var rank = content.DocumentNode.SelectSingleNode(currentElement + "//span[@class=\"rank\"]").InnerText;
                                    post.rank = Int32.Parse(rank.Replace(".", ""));
                                }

                                //needed so that the both necessary rows have been included
                                if (rowCount == 2)
                                {
                                    gottenFullPost = true;
                                }
                            }

                            //if the nullable fields aren't null, then add the post to the list
                            if (gottenFullPost && post.title != null && post.uri != null && post.author != null)
                            {
                                returnedPosts.Add(post);

                                //needed to prevent duplicate data
                                post = new PostResponseModel();

                                //if the number of posts being returned matche the amount of posts requested, then exit the loop
                                if (returnedPosts.Count == numberOfPostsRequested)
                                {
                                    return(returnedPosts);
                                }
                            }
                        }
                        else
                        {
                            rowCount = 0;
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("ERROR: Non-valid URI given");
            }

            return(returnedPosts);
        }
Ejemplo n.º 18
0
        public void Update(PostResponseModel request)
        {
            string sQuery = "UPDATE Posts SET UpdateTime = GETDATE(), Title = @Title, Text= @Text WHERE Id = @Id";

            sqlGateway.Execute(sQuery, request);
        }
        public async Task <PostResponseModel> PostContent(string url, string path, RegionModel regionModel, IEnumerable <KeyValuePair <string, string> > formParameters, string requestBaseUrl)
        {
            _ = regionModel ?? throw new ArgumentNullException(nameof(regionModel));

            var results = new PostResponseModel();

            try
            {
                if (regionModel.IsHealthy)
                {
                    logger.LogInformation($"{nameof(PostContent)}: Posting child response from: {url}");

                    var request = new HttpRequestMessage(HttpMethod.Post, url)
                    {
                        Content = formParameters != null ? new FormUrlEncodedContent(formParameters) : null,
                    };

                    var httpClient = httpClientFactory.GetClientForRegionEndpoint(regionModel.RegionEndpoint);
                    var response   = await httpClient.SendAsync(request);

                    if (response.IsRedirectionStatus())
                    {
                        responseHandler.Process(response);

                        var redirectUrl = requestBaseUrl;

                        redirectUrl += response.Headers.Location.IsAbsoluteUri
                            ? response.Headers.Location.PathAndQuery.ToString(CultureInfo.InvariantCulture)
                            : response.Headers.Location.ToString();

                        throw new RedirectException(new Uri(url), new Uri(redirectUrl),
                                                    response.StatusCode == HttpStatusCode.PermanentRedirect);
                    }

                    if (!response.IsSuccessStatusCode)
                    {
                        throw new EnhancedHttpException(response.StatusCode, response.ReasonPhrase, url);
                    }

                    var mediaType = response.Content.Headers.ContentType.MediaType;
                    if (FileDownloadContentTypes.TryGetValue(mediaType, out var fileExtension))
                    {
                        results.FileDownloadModel = new FileDownloadModel
                        {
                            FileBytes       = await response.Content.ReadAsByteArrayAsync(),
                            FileContentType = mediaType,
                            FileName        = !string.IsNullOrWhiteSpace(response.Content.Headers.ContentDisposition.FileNameStar) ? response.Content.Headers.ContentDisposition.FileNameStar : $"NCS file download.{fileExtension}",
                        };
                    }
                    else
                    {
                        results.Html = await response.Content.ReadAsStringAsync();
                    }

                    logger.LogInformation($"{nameof(PostContent)}: Received child response from: {url}");
                }
                else
                {
                    results.Html = !string.IsNullOrWhiteSpace(regionModel.OfflineHtml)
                        ? regionModel.OfflineHtml
                        : markupMessages.GetRegionOfflineHtml(regionModel.PageRegion);
                }
            }
            catch (BrokenCircuitException ex)
            {
                logger.LogError(ex, $"{nameof(ContentRetriever)}: BrokenCircuit: {url} - {ex.Message}");

                if (regionModel.HealthCheckRequired)
                {
                    await appRegistryDataService.SetRegionHealthState(path, regionModel.PageRegion, false);
                }

                results.Html = !string.IsNullOrWhiteSpace(regionModel.OfflineHtml)
                    ? regionModel.OfflineHtml
                    : markupMessages.GetRegionOfflineHtml(regionModel.PageRegion);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"{nameof(PostContent)}: Received error response from: {url}. {ex.Message}");
                throw;
            }

            return(results);
        }