Example #1
0
        protected void InitResult()
        {
            var(Stream, Pusher) = ResultStream <TOut> .GetResultStream(this);

            _streamer = Pusher;
            _result   = Stream as ResultStream <TOut>;
        }
Example #2
0
        /// <summary>
        ///     重新构造相同的 HTTP 请求,用于重复当前请求。
        /// </summary>
        public HttpRequest RebuildRequest()
        {
            if (State == HttpRequestState.Connecting || State == HttpRequestState.Progressing)
            {
                throw new InvalidOperationException("不能对传输中的请求进行修改。");
            }

            var oldRequest = Request;

            Request = WebRequest.CreateHttp(oldRequest.RequestUri);

            Request?.Abort();
            ResultStream?.Dispose();

            Request.Accept = oldRequest.Accept;
            Request.AllowReadStreamBuffering = oldRequest.AllowReadStreamBuffering;
            Request.ContentType           = oldRequest.ContentType;
            Request.ContinueTimeout       = oldRequest.ContinueTimeout;
            Request.CookieContainer       = oldRequest.CookieContainer;
            Request.Credentials           = oldRequest.Credentials;
            Request.Headers               = oldRequest.Headers;
            Request.Method                = oldRequest.Method;
            Request.Proxy                 = oldRequest.Proxy;
            Request.UseDefaultCredentials = oldRequest.UseDefaultCredentials;

            State = HttpRequestState.NothingSpecial;

            return(this);
        }
Example #3
0
        void NetworkReadCallback(IAsyncResult ar)
        {
            var count = 0;

            try
            {
                count = AsyncData.Stream.EndRead(ar);
                if (count > 0)
                {
                    ResultStream.Write(_buffer, 0, count);
                }
            }
            catch (Exception exception)
            {
                AsyncData.Exception = exception;
                CompleteCallback();

                return;
            }

            if (count == 0)
            {
                ProcessFinalResponse();
                ResultStream.Seek(0, SeekOrigin.Begin);
                CompleteCallback();
            }
            else
            {
                AsyncData.Stream.BeginRead(_buffer, 0, _buffer.Length, NetworkReadCallback, this);
            }
        }
Example #4
0
 public Stream AsStream()
 {
     if (ResultStream.CanSeek)
     {
         ResultStream.Seek(0, SeekOrigin.Begin);
     }
     return(ResultStream);
 }
Example #5
0
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     lock (_lock)
     {
         _isDisposed = true;
         _waitHandle.Close();
         ResultStream?.Dispose();
     }
 }
Example #6
0
            public static IResultStream EvaluateTargetsToResults(IDictionary <IBookIndex, IBookTarget> targets, IProcessConfig config, IEngineProfile engine)
            {
                IResultStream emptyResults = ResultStream.CreateEmptyStream();

                var results = targets.Aggregate(emptyResults,
                                                (agr, target) => EvaluateTarget(agr, target.Value, config, engine));

                return(results);
            }
Example #7
0
        public string AsString()
        {
            if (ResultStream.CanSeek)
            {
                ResultStream.Seek(0, SeekOrigin.Begin);
            }
            var retv = Fi.StandardEncoding.GetString(AsBuffer());

            return(retv);
        }
Example #8
0
 public MemoryStream AsSeekableStream()
 {
     if (ResultStream.CanSeek)
     {
         ResultStream.Seek(0, SeekOrigin.Begin);
     }
     using (ResultStream) {
         var ms = new MemoryStream();
         ResultStream.CopyTo(ms);
         ResultStream.Flush();
         return(ms);
     }
 }
Example #9
0
        public void SubmitToStream(BuiltinReportDescriptor descriptor)
        {
            /* load the master template */
            var raw = LoadTemplate("builtinreport.ent", descriptor.m);

            /* do we need the JS libraries of amline? */
            if (NeedsAMJSLines)
            {
                var flashscript = LoadTemplate("am_embed_js.html", descriptor.m);
                raw.Set("flashscript", flashscript.ToString());
            }
            else
            {
                raw.Set("flashscript", String.Empty); /* added [dlatikay 20120202] */
            }
            /* perform the replacements */
            raw.Set("title", descriptor.ReportPageTitle);
            raw.Set("dqp", descriptor.DQP);                                                                          /* added [dlatikay 20120209] */
            raw.Set("onloadaction", descriptor.Outputformat == FileType.ft_html ? "window.print();" : String.Empty); /* added [dlatikay 20120209] */
            raw.Set("header", header == null ? String.Empty : header.ToString());
            raw.Set("meta", meta == null ? String.Empty : meta.ToString());
            var compositecontent = new StringBuilder();
            var partcounter      = 0;

            foreach (var part in parts)
            {
                compositecontent.AppendFormat("{1}{0}{2}", part.ToString(), (((++partcounter) <= 1) ? String.Empty : "<!-- section ruler -->"), Environment.NewLine);
            }
            raw.Set("rendition", compositecontent.ToString());
            raw.Set("footer", String.Format("<span id=\"builtinreport_footer\">{0}</span>", HttpUtility.HtmlEncode(String.Format(descriptor.m(3252), descriptor.Systemname, descriptor.Systemversion, descriptor.ReportCreationTimestamp)))); /* Created using en-software SHERM v2.1 */
            raw.Set("onafterprint", descriptor.Outputformat == dal.business.FileType.ft_pdf ? "JavaScript:window.location.href='about:blank';" : String.Empty);                                                                               /* when we are rendering a pdf, we will print it to the postscript printer. therefore we need this to allow the silent host browser to detect when printing has finished */

            /* [dlatikay 20111202] if we want html, we get html;
             * stream it out: */
            if (descriptor.Outputformat == dal.business.FileType.ft_html)
            {
                byte[] html = System.Text.UTF8Encoding.UTF8.GetBytes(raw.ToString());
                ResultStream.Write(html, 0, html.Length);
            }
            /* reset if can */
            if (ResultStream.CanSeek)
            {
                ResultStream.Seek(0, SeekOrigin.Begin);
            }
        }
Example #10
0
        /// <summary>
        ///     将 HTTP 请求结果以指定的代码页转换为字符串,并在结束后释放该次网络请求的资源,在该操作后内部的<see cref="ResultStream" />与<see cref="Response" />不再有效,但不会释放
        ///     <see cref="SetResultStream" />所设置的流。
        /// </summary>
        public String GetDataAsString(Encoding encoding)
        {
            if (State == HttpRequestState.Completed)
            {
                if (!ResultStream.CanRead)
                {
                    throw new ArgumentException("结果流不可读。", nameof(ResultStream));
                }

                if (ResultStream != null && ResultStream.Length > 0)
                {
                    byte[] data = new byte[ResultStream.Length];
                    ResultStream?.Read(data, 0, data.Length);
                    Dispose();
                    return(encoding.GetString(data));
                }
                return(null);
            }
            throw new InvalidOperationException("请在请求完成后调用 HttpRequest.GetDataAsString 方法。");
        }
Example #11
0
        //public Stream AsRawStream() {
        //    var rawStream = new MemoryStream();
        //    using (var writer = new StreamWriter(rawStream, new UTF8Encoding(), 8192, true)) {
        //        writer.WriteLine($"HTTP/1.1 {StatusCode} {StatusDescription}");
        //        lock (this.Headers) {
        //            this.Headers.ForEach(header => {
        //                writer.WriteLine();
        //            });
        //        }
        //        writer.WriteLine();
        //    }
        //    ResultStream.CopyTo(rawStream);
        //    rawStream.Seek(0, SeekOrigin.Begin);
        //    return rawStream;
        //}

        public byte[] AsBuffer()
        {
            if (ResultStream.CanSeek)
            {
                ResultStream.Seek(0, SeekOrigin.Begin);
            }
            byte[] bytes;
            if (ResultStream is MemoryStream rsms)
            {
                bytes = rsms.ToArray();
            }
            else
            {
                using (var ms = new MemoryStream()) {
                    ResultStream.CopyTo(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    bytes = ms.ToArray();
                }
            }
            return(bytes);
        }
Example #12
0
 public async Task SaveToFile(IFileSystem fs, string fileName)
 {
     ResultStream.Seek(0, SeekOrigin.Begin);
     await fs.Write(fileName, async stream => await ResultStream.CopyToAsync(stream));
 }
Example #13
0
 public byte[] AsDecodedBuffer(IEncryptionMethod method)
 {
     ResultStream.Seek(0, SeekOrigin.Begin);
     return(method.Decrypt(AsBuffer()));
 }
Example #14
0
        private async Task AssertResultsAsync(ResultStream stream, IEnumerable <PartialResultSet> expectedResults)
        {
            var ret = new List <PartialResultSet>();

            while (await stream.MoveNext(default))
Example #15
0
 private void OnResultStream(EventArgsT <object> e)
 {
     ResultStream?.Invoke(this, e);
 }
Example #16
0
        private void Start(int retryCount, Stream content = null)
        {
            _progressing = true;
            _progressWaitHandle.Reset();
            int retry = 0;

            Task.Run(async() =>
            {
                HttpRequestQueue.Current.Register(this);
                _queueWaitHandle.WaitOne();

                RETRY: //重试标签

                if (State == HttpRequestState.NothingSpecial)
                {
                    EventArgs <HttpRequestStats> progressInfo = null;

                    if (TransferProgressChanged != null)
                    {
                        progressInfo = new EventArgs <HttpRequestStats>(new HttpRequestStats());
                    }

                    try
                    {
                        State = HttpRequestState.Connecting;

                        if (TransferProgressChanged != null)
                        {
                            progressInfo.Value.Update();
                            TransferProgressChanged(this, progressInfo);
                        }

                        //数据上传过程,用于 Put 与 Post
                        if (content != null && (Request.Method == "PUT" || Request.Method == "POST"))
                        {
                            using (var requestStream = await Request.GetRequestStreamAsync())
                            {
                                State = HttpRequestState.Progressing;

                                if (TransferProgressChanged != null)
                                {
                                    progressInfo.Value.ProgressType = HttpRequestProgressType.Upload;
                                    progressInfo.Value.Update();
                                    progressInfo.Value.TotalBytes = content.Length;
                                    TransferProgressChanged(this, progressInfo);

                                    byte[] buffer = new byte[TransferBufferSize];
                                    int writeLength;

                                    while ((writeLength = content.Read(buffer, 0, buffer.Length)) != 0)
                                    {
                                        requestStream.Write(buffer, 0, writeLength);

                                        progressInfo.Value.Update(writeLength);
                                        TransferProgressChanged(this, progressInfo);
                                    }

                                    progressInfo = new EventArgs <HttpRequestStats>(new HttpRequestStats());
                                }
                                else
                                {
                                    content.CopyTo(requestStream);
                                }
                            }
                        }

                        //数据下载过程,用于 Post 与 Get
                        if (Request.Method == "GET" || Request.Method == "POST")
                        {
                            Response = (HttpWebResponse)await Request.GetResponseAsync();
                            State    = HttpRequestState.Progressing;

                            #region  载过程

                            using (var stream = Response.GetResponseStream())
                            {
                                State = HttpRequestState.Progressing;

                                if (_customStream == null)
                                {
                                    ResultStream =
                                        new MemoryStream((int)(Response.ContentLength > 0
                                            ? Response.ContentLength
                                            : 10 * TransferBufferSize));
                                }

                                if (TransferProgressChanged != null)
                                {
                                    progressInfo.Value.ProgressType = HttpRequestProgressType.Download;
                                    progressInfo.Value.TotalBytes   = Response.ContentLength > 0
                                        ? Response.ContentLength
                                        : 0;

                                    byte[] buffer = new byte[TransferBufferSize];

                                    long pos = 0;
                                    int readLength;
                                    if (ResultStream.CanSeek)
                                    {
                                        pos = ResultStream.Position;
                                    }

                                    while ((readLength = stream.Read(buffer, 0, buffer.Length)) != 0)
                                    {
                                        ResultStream.Write(buffer, 0, readLength);
                                        progressInfo.Value.Update(readLength);
                                        TransferProgressChanged(this, progressInfo);
                                    }

                                    if (ResultStream.CanSeek)
                                    {
                                        ResultStream.Position = pos;
                                    }
                                }
                                else
                                {
                                    long pos = 0;

                                    if (ResultStream.CanSeek)
                                    {
                                        pos = ResultStream.Position;
                                    }

                                    stream.CopyTo(ResultStream);

                                    if (ResultStream.CanSeek)
                                    {
                                        ResultStream.Position = pos;
                                    }
                                }
                            }

                            #endregion  载过程
                        }

                        State = HttpRequestState.Completed;
                        if (TransferProgressChanged != null)
                        {
                            progressInfo.Value.Update();
                            TransferProgressChanged(this, progressInfo);
                        }
                        _progressWaitHandle.Set();
                        _progressing = false;

                        return;
                    }
                    catch (WebException webException)
                    {
                        Exception = webException;
                        State     = HttpRequestState.ErrorOccurred;
                        if (TransferProgressChanged != null)
                        {
                            progressInfo.Value.Update();
                            TransferProgressChanged(this, progressInfo);
                        }
                    }
                    catch (Exception ex)
                    {
                        Exception = ex;
                        _progressWaitHandle.Set();
                        _progressing = false;

                        throw;
                    }
                }

                if (retry < retryCount)
                {
                    retry++;
                    RebuildRequest(); //重构请求

                    goto RETRY;       //重试请求
                }

                //取消等待
                _progressWaitHandle.Set();
                _progressing = false;
            });
        }
Example #17
0
 public void Dispose()
 {
     Response?.Dispose();
     ResultStream?.Dispose();
 }
Example #18
0
 public override void Output(HttpListenerResponse output)
 {
     output.StatusCode  = StatusCode;
     output.ContentType = ContentType;
     ResultStream.CopyTo(output.OutputStream);
 }
Example #19
0
 /// <summary>
 /// 请求处理最后的内容
 /// </summary>
 protected virtual void ProcessFinalResponse()
 {
     ResultStream.Seek(0, SeekOrigin.Begin);
 }