Пример #1
0
        /// <summary>
        /// 创建上一页、下一页链接
        /// </summary>
        /// <param name="postParameter"></param>
        /// <returns></returns>
        private string CreatePostUri(PostParameter postParameter, PaginationResourceUriType uriType)
        {
            switch (uriType)
            {
            case PaginationResourceUriType.PreviousPage:
                var previousParameters = new
                {
                    pageIndex = postParameter.PageIndex - 1,
                    pageSize  = postParameter.PageSize,
                    orderBy   = postParameter.OrderBy,
                    fields    = postParameter.Fields
                };
                return(this._urlHelper.Link("GetPosts", previousParameters));

            case PaginationResourceUriType.NextPage:
                var nextParameters = new
                {
                    pageIndex = postParameter.PageIndex + 1,
                    pageSize  = postParameter.PageSize,
                    orderBy   = postParameter.OrderBy,
                    fields    = postParameter.Fields
                };
                return(this._urlHelper.Link("GetPosts", nextParameters));

            default:
                var currentParameters = new
                {
                    pageIndex = postParameter.PageIndex,
                    pageSize  = postParameter.PageSize,
                    orderBy   = postParameter.OrderBy,
                    fields    = postParameter.Fields
                };
                return(this._urlHelper.Link("GetPosts", currentParameters));
            }
        }
Пример #2
0
        /// <summary>
        /// 为集合资源创建链接
        /// </summary>
        /// <param name="postResourceParameters"></param>
        /// <param name="hasPrevious"></param>
        /// <param name="hasNext"></param>
        /// <returns></returns>
        private IEnumerable <LinkResource> CreateLinksForPosts(PostParameter postResourceParameters,
                                                               bool hasPrevious, bool hasNext)
        {
            var links = new List <LinkResource>
            {
                new LinkResource(
                    CreatePostUri(postResourceParameters, PaginationResourceUriType.CurrentPage),
                    "self", "GET")
            };

            if (hasPrevious)
            {
                links.Add(
                    new LinkResource(
                        CreatePostUri(postResourceParameters, PaginationResourceUriType.PreviousPage),
                        "previous_page", "GET"));
            }

            if (hasNext)
            {
                links.Add(
                    new LinkResource(
                        CreatePostUri(postResourceParameters, PaginationResourceUriType.NextPage),
                        "next_page", "GET"));
            }

            return(links);
        }
Пример #3
0
        public async Task <IActionResult> Get(PostParameter postParameter)
        {
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostModel, Post>(postParameter.OrderBy))
            {
                return(BadRequest("can't find fields for sorting"));
            }
            if (!_typeHelperService.TypeHasProperties <PostModel>(postParameter.Fields))
            {
                return(BadRequest("Fields not exits"));
            }
            var posts = await _postBusiness.RetriveAllEntity(postParameter);

            var postModels       = _mapper.Map <IEnumerable <Post>, IEnumerable <PostModel> >(posts);
            var postsResult      = postModels.ToDynamicIEnumerable(postParameter.Fields);
            var previousPageLink = posts.HasPrevious ?
                                   CreatePostUri(postParameter, PaginationResourceUriType.PreviousPage) : null;

            var nextPageLink = posts.HasNext ?
                               CreatePostUri(postParameter, PaginationResourceUriType.NextPage) : null;
            var meta = new
            {
                posts.PageSize,
                posts.PageIndex,
                posts.TotalItemsCount,
                posts.PageCount,
                previousPageLink,
                nextPageLink
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
            }));
            return(Ok(postsResult));
        }
Пример #4
0
 // [Route("answers")]
 public async Task <ActionResult <IEnumerable <Post> > > GetAnswers([FromQuery] PostParameter postParameter)
 {
     return(await _context.PostsDB
            .OrderBy(a => a.Id)
            .Where(a => a.PostTypeId == 2)
            .Skip((postParameter.PageNumber - 1) * postParameter.PageSize)
            .Take(postParameter.PageSize)
            .ToListAsync());
 }
Пример #5
0
            private void HandlePost(StateObj State, string S, string location)
            {
                string URL = ProcessUrl(location).Replace(" ", String.Empty);
                Dictionary <string, string> PostParams = new Dictionary <string, string>();
                string Location = S.Substring(5, S.IndexOf(' ', S.IndexOf(' ') + 1) - 4);

                Console.WriteLine("Post");

                string Str = S.Substring(5);

                Console.WriteLine("Trimmed!");
                string[] Lines = Str.Split('\n');

                int i;

                for (i = 0; i < Lines.Length; i++)
                {
                    if (string.IsNullOrWhiteSpace(Lines[i]))
                    //if (lines[i].Length == 0)          //or maybe this suits better..
                    //if (lines[i].Equals(string.Empty)) //or this
                    {
                        //Console.WriteLine(i);
                        break;
                    }
                    //Console.WriteLine(i);
                }


                if (i != Lines.Length - 1)
                {
                    //Next Line should be the one with post data
                    Console.WriteLine(Lines[i + 1]);
                    Console.WriteLine("-----------");
                    string[] PostParameters = Lines[i + 1].Replace("+", " ").Split('&');

                    foreach (string PostParameter in PostParameters)
                    {
                        string[] KeyAndValue = PostParameter.Split('=');
                        PostParams.Add(KeyAndValue[0], KeyAndValue[1]);
                    }

                    foreach (KeyValuePair <string, string> kvp in PostParams)
                    {
                        Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
                    }
                    //Console.WriteLine(generateJSON(PostParams));
                    Console.WriteLine("URL:" + URL + " " + Virtdirs.ContainsKey(URL));
                    if (Virtdirs.ContainsKey(URL))
                    {
                        //returnText(State, CallVirtDir(ProcessUrl(cr.RawUrl), Hreq), "text/html");
                        PrevReq Hreq = new PrevReq(URL, State.Client.RemoteEndPoint.ToString(), State.S.ToString(), "POST", PostParams);
                        string  text = CallVirtDir(URL, Hreq);
                        SendText(State, GenerateHeader("HTTP/1.1 200 OK", "text/html", Encoding.ASCII.GetByteCount(text)) + text);
                    }
                }
            }
Пример #6
0
        // get info on uploaded file
        public override async Task <string> render(HttpServerRequest req)
        {
            PostParameter file = req.postParameters.Where(x => x.name == "upload").FirstOrDefault();

            if (file != null)
            {
                BasicProperties prop = await file.contentFile.GetBasicPropertiesAsync();

                req.html = req.html.Replace("<%FILEINFO%>", "File info:<br/>Name: " + Path.GetFileName(file.value) + "<br/>Size: " + (prop.Size / 1000) + "KB");
            }
            else
            {
                req.html = req.html.Replace("<%FILEINFO%>", "");
            }
            return(req.html);
        }
Пример #7
0
        public async Task <PaginatedList <Post> > RetriveAllEntityAsync(PostParameter postParameter)
        {
            var query = _context.Post.AsQueryable();

            if (!string.IsNullOrEmpty(postParameter.Title))
            {
                var title = postParameter.Title.ToLowerInvariant();
                query = query.Where(p => p.Title.ToLowerInvariant() == title);
            }

            query = query.ApplySort(postParameter.OrderBy, _propertyMappingContainer.Resolve <PostModel, Post>());
            var count = await query.CountAsync();

            var data = await query.Skip(postParameter.PageIndex *postParameter.PageSize)
                       .Take(postParameter.PageSize)
                       .ToListAsync();

            return(new PaginatedList <Post>(postParameter.PageIndex, postParameter.PageSize, count, data));
        }
Пример #8
0
        public async Task <IActionResult> Get(PostParameter postParameters)
        {
            if (!this._propertyMappingContainer.ValidateMappingExistsFor <PostResource, Post>(postParameters.OrderBy))
            {
                return(BadRequest("Can't find fields for sorting"));
            }
            if (!this._typeHelperService.TypeHasProperties <PostResource>(postParameters.Fields))
            {
                return(BadRequest("Fields not exist."));
            }

            var postList = await this._postRepository.GetAllPostsAsync(postParameters);

            var postResources = this._mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(postList);


            var shapedResources = postResources.ToDynamicIEnumerable(postParameters.Fields);

            var previousPageLink = postList.HasPrevious ?
                                   this.CreatePostUri(postParameters, PaginationResourceUriType.PreviousPage) : null;

            var nextPageLink = postList.HasNext ?
                               this.CreatePostUri(postParameters, PaginationResourceUriType.NextPage) : null;

            var meta = new
            {
                postList.PageIndex,
                postList.PageSize,
                postList.TotalItemsCount,
                postList.PageCount,
                previousPageLink,
                nextPageLink
            };

            Response.Headers.Add("X-Pagination",
                                 JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()    //设定返回数据属性首字母小写
            }));

            return(Ok(shapedResources));
        }
Пример #9
0
        /// <summary>
        /// 获取所有文章
        /// </summary>
        /// <returns></returns>
        public async Task <PaginatedList <Post> > GetAllPostsAsync(PostParameter postParameters)
        {
            var query = this._myContext.Posts.AsQueryable();

            if (!string.IsNullOrWhiteSpace(postParameters.Title))
            {
                var title = postParameters.Title.ToLowerInvariant();
                query = query.Where(x => x.Title.ToLowerInvariant().Contains(title));
            }

            //query = query.OrderBy(x => x.Id);

            query = query.ApplySort(postParameters.OrderBy, _propertyMappingContainer.Resolve <PostResource, Post>());

            var count = await query.CountAsync();

            var list = await query
                       .Skip((postParameters.PageIndex - 1) *postParameters.PageSize)
                       .Take(postParameters.PageSize)
                       .ToListAsync();

            return(new PaginatedList <Post>(postParameters.PageIndex, postParameters.PageSize, count, list));
        }
Пример #10
0
        /// <summary>
        /// 获取Post过来的参数和数据
        /// </summary>
        /// <returns></returns>
        private static List <PostParameter> ProcessPostRequest(HttpListenerContext context)
        {
            List <PostParameter> postValueList = new List <PostParameter>();

            try
            {
                if (context.Request.ContentType.Length > 20 && string.Compare(context.Request.ContentType.Substring(0, 20), "multipart/form-data;", true) == 0)
                {
                    //string[] HttpListenerPostValue = context.Request.ContentType.Split(';').Skip(1).ToArray();
                    //string boundary = string.Join(";", HttpListenerPostValue).Replace("boundary=", "").Trim();
                    int    splitStart    = context.Request.ContentType.IndexOf(";");
                    string contentRemain = context.Request.ContentType.Substring(splitStart + 1);
                    string boundary      = contentRemain.Replace("boundary=", "").Trim();

                    byte[]        ChunkBoundary = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
                    byte[]        EndBoundary   = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
                    Stream        SourceStream  = context.Request.InputStream;
                    var           resultStream  = new MemoryStream();
                    bool          CanMoveNext   = true;
                    PostParameter data          = null;
                    while (CanMoveNext)
                    {
                        byte[] currentChunk = ReadLineAsBytes(SourceStream);
                        if (!Encoding.UTF8.GetString(currentChunk).Equals("\r\n"))
                        {
                            resultStream.Write(currentChunk, 0, currentChunk.Length);
                        }
                        if (CompareBytes(ChunkBoundary, currentChunk))
                        {
                            byte[] result = new byte[resultStream.Length - ChunkBoundary.Length];
                            resultStream.Position = 0;
                            resultStream.Read(result, 0, result.Length);
                            CanMoveNext = true;
                            if (result.Length > 0)
                            {
                                data.datas = result;
                            }
                            data = new PostParameter();
                            postValueList.Add(data);
                            resultStream.Dispose();
                            resultStream = new MemoryStream();
                        }
                        else if (Encoding.UTF8.GetString(currentChunk).Contains("Content-Disposition"))
                        {
                            byte[] result = new byte[resultStream.Length - 2];
                            resultStream.Position = 0;
                            resultStream.Read(result, 0, result.Length);
                            CanMoveNext = true;
                            data.name   = Encoding.UTF8.GetString(result).Replace("Content-Disposition: form-data; name=\"", "").Replace("\"", "").Split(';')[0];
                            resultStream.Dispose();
                            resultStream = new MemoryStream();
                        }
                        else if (Encoding.UTF8.GetString(currentChunk).Contains("Content-Type"))
                        {
                            CanMoveNext = true;
                            data.type   = 1;
                            resultStream.Dispose();
                            resultStream = new MemoryStream();
                        }
                        else if (CompareBytes(EndBoundary, currentChunk))
                        {
                            byte[] result = new byte[resultStream.Length - EndBoundary.Length - 2];
                            resultStream.Position = 0;
                            resultStream.Read(result, 0, result.Length);
                            data.datas = result;
                            resultStream.Dispose();
                            CanMoveNext = false;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Process faild: " + e.Message);
            }

            return(postValueList);
        }
Пример #11
0
        // [Route("fullposts")]
        public async Task <ActionResult <IEnumerable <MultiplePosts> > > GetFullPosts([FromQuery] PostParameter postParameter)
        {
            var result = await _context.PostsDB
                         .OrderBy(a => a.Id)
                         .Where(a => a.PostTypeId == 1 && a.AcceptedAnswerId != null) // question
                         .Skip((postParameter.PageNumber - 1) * postParameter.PageSize)
                         .Take(postParameter.PageSize)
                         .Join(_context.PostsDB, // answer
                               question => question.AcceptedAnswerId,
                               answer => answer.Id,
                               (question, answer) => new MultiplePosts
            {
                Question = question,
                Answer   = answer
            }).ToListAsync();

            return(result);
        }
Пример #12
0
 /// <summary>
 ///     获取所有文章
 /// </summary>
 /// <returns></returns>
 public async Task <PaginatedList <Post> > RetriveAllEntity(PostParameter postParameter)
 {
     return(await _iPostRepository.RetriveAllEntityAsync(postParameter));
 }