public override void Process(IODataRequestMessage requestMessage, IODataResponseMessage responseMessage) { string asyncToken = this.QueryContext.AsyncToken; AsyncTask asyncTask = AsyncTask.GetTask(asyncToken); if (asyncTask == null) { // token is invalid or expired. throw Utility.BuildException(HttpStatusCode.NotFound); } else { if (!asyncTask.Ready) { ResponseWriter.WriteAsyncPendingResponse(responseMessage, asyncToken); } else { responseMessage.SetHeader(ServiceConstants.HttpHeaders.ContentType, "application/http"); responseMessage.SetHeader(ServiceConstants.HttpHeaders.ContentTransferEncoding, ServiceConstants.HttpHeaderValues.Binary); using (var messageWriter = this.CreateMessageWriter(responseMessage)) { var asyncWriter = messageWriter.CreateODataAsynchronousWriter(); var innerResponse = asyncWriter.CreateResponseMessage(); asyncTask.Execute(innerResponse); } } } }
private void ErrorPage(IRequest request, IResponse response, HttpException exception) { response.Status = exception.Code; response.Reason = exception.Message; response.Body.SetLength(0); var args = new ErrorPageEventArgs(HttpContext.Current, request, response); args.Exception = exception; ErrorPageRequested(this, args); // Add default error body. if (!args.IsHandled) { string htmlTemplate = "<html><head><title>{1}</title></head><body>Error {0}: {1}</body></html>"; byte[] body = Encoding.UTF8.GetBytes(string.Format(htmlTemplate, (int)response.Status, response.Reason)); response.Body.Write(body, 0, body.Length); } try { var generator = new ResponseWriter(); generator.Send(HttpContext.Current, response); } catch (Exception err) { #if DEBUG if (ExceptionThrown.GetInvocationList().Length == 1) { throw; } #endif ExceptionThrown(this, new ExceptionEventArgs(err)); } }
public virtual Stream ProcessAsynchronously(Stream requestStream) { DateTime now = DateTime.Now; string asyncToken = now.Ticks.ToString(CultureInfo.InvariantCulture); AsyncTask asyncTask = null; if (requestStream == null) { asyncTask = new AsyncTask(this, this.CreateRequestMessage(null), now.AddSeconds(AsyncTask.DefaultDuration)); } else { StreamPipe requestPipe = new StreamPipe(); using (requestPipe.WriteStream) { requestStream.CopyTo(requestPipe.WriteStream); // read the input stream to memory } var requestMessage = this.CreateRequestMessage(requestPipe.ReadStream); asyncTask = new AsyncTask(this, requestMessage, now.AddSeconds(AsyncTask.DefaultDuration)); } AsyncTask.AddTask(asyncToken, asyncTask); StreamPipe responsePipe = new StreamPipe(); var responseMessage = new ODataResponseMessage(responsePipe.WriteStream, 202); //202 Accepted responseMessage.PreferenceAppliedHeader().RespondAsync = true; ResponseWriter.WriteAsyncPendingResponse(responseMessage, asyncToken); return(responsePipe.ReadStream); }
public async Task RouteAsync(RouteContext context) { // Build a request model from the request IInputFormatter inputFormatter = new JsonInputFormatter(); IEnumerable <IValueParser> valueParsers = new List <IValueParser> { new RouteValueParser(context.RouteData) }; RequestModelActivator modelActivator = new RequestModelActivator( context.HttpContext, inputFormatter, valueParsers ); TRequest requestModel = await modelActivator.CreateRequestModelAsync <TRequest>(); // Run the request through our command pipeline IHandlerResult pipelineResult = _pipeline.Dispatch(context.HttpContext, requestModel); // If the request was handled by our pipeline then write the response out if (pipelineResult.IsHandled) { // Serialize the response model IOutputFormatter outputFormatter = new JsonOutputFormatter(); ResponseWriter responseWriter = new ResponseWriter(context.HttpContext, outputFormatter); await responseWriter.SerializeResponseAsync(pipelineResult); // Let OWIN know our middleware handled the request context.IsHandled = true; } }
private static void OnHttpMessageBegin( string requestHeaders, byte[] requestBody, string responseHeaders, byte[] responseBody, out ProxyNextAction nextAction, ResponseWriter responseWriter ) { Console.WriteLine("On message begin"); try { if (requestHeaders.IndexOf("yourgreenhomes.ca", StringComparison.OrdinalIgnoreCase) != -1) { if (responseHeaders != null && responseHeaders.IndexOf("/html") != -1) { var blockedResponse = GetBlockedResponse(); responseWriter(blockedResponse); nextAction = ProxyNextAction.DropConnection; return; } } } catch (Exception e) { while (e != null) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); e = e.InnerException; } } nextAction = ProxyNextAction.AllowAndIgnoreContent; }
public maxBytesReader(ResponseWriter w = default, io.ReadCloser r = default, long n = default, error err = default) { this.w = w; this.r = r; this.n = n; this.err = err; }
private void SendOk(RequestEventArgs e) { e.Response.Status = HttpStatusCode.OK; var generator = new ResponseWriter(); generator.SendHeaders(e.Context, e.Response); }
private void SendErrorPage(Exception exception) { var httpException = exception as HttpException; var response = HttpContext.Current.Response; response.Status = httpException != null ? httpException.Code : HttpStatusCode.InternalServerError; response.Reason = exception.Message; response.Body.SetLength(0); var args = new ErrorPageEventArgs(HttpContext.Current) { Exception = exception }; ErrorPageRequested(this, args); try { var generator = new ResponseWriter(); if (args.IsHandled) { generator.Send(HttpContext.Current, response); } else { generator.SendErrorPage(HttpContext.Current, response, exception); } } catch (Exception err) { _logger.Error("Failed to display error page", err); } }
private void ProcessDeleteLink(IODataResponseMessage responseMessage) { var segment = (NavigationPropertyLinkSegment)this.QueryContext.QueryPath.LastSegment; var propertyName = segment.NavigationProperty.Name; var parent = default(object); var target = default(object); if (this.QueryContext.QueryEntityIdSegment == null) { // single-valued navigation property parent = this.QueryContext.ResolveQuery(this.DataSource, this.QueryContext.QueryPath.Count - 2); } else { // collection-valued navigation property var queryUri = this.QueryContext.QueryUri; var parentUri = queryUri.AbsoluteUri.Substring(0, queryUri.AbsoluteUri.Length - queryUri.Query.Length); var parentContext = new QueryContext(this.ServiceRootUri, new Uri(parentUri, UriKind.Absolute), this.DataSource.Model); parent = parentContext.ResolveQuery(this.DataSource, parentContext.QueryPath.Count - 2); target = this.QueryContext.ResolveQuery(this.DataSource); } this.DataSource.UpdateProvider.DeleteLink(parent, propertyName, target); this.DataSource.UpdateProvider.SaveChanges(); ResponseWriter.WriteEmptyResponse(responseMessage); }
/// <summary> /// An error have occurred and we need to send a result pack to the client /// </summary> /// <param name="context">The context.</param> /// <param name="exception">The exception.</param> /// <remarks> /// Invoke base class (<see cref="Server"/>) to send the contents /// of <see cref="IHttpContext.Response"/>. /// </remarks> protected virtual void DisplayErrorPage(IHttpContext context, Exception exception) { var httpException = exception as HttpException; if (httpException != null) { context.Response.Reason = httpException.Code.ToString(); context.Response.Status = httpException.Code; } else { context.Response.Reason = "Internal Server Error"; context.Response.Status = HttpStatusCode.InternalServerError; } var args = new ErrorPageEventArgs(context) { Exception = exception }; ErrorPageRequested(this, args); ResponseWriter writer = HttpFactory.Current.Get <ResponseWriter>(); if (args.IsHandled) { writer.Send(context, context.Response); } else { writer.SendErrorPage(context, context.Response, exception); args.IsHandled = true; } }
async Task Execute( string query, string operation, IIncomingAttachments incomingAttachments, Inputs inputs, CancellationToken cancellation) { var executionOptions = new ExecutionOptions { Schema = schema, Query = query, OperationName = operation, Inputs = inputs, CancellationToken = cancellation, #if (DEBUG) ThrowOnUnhandledException = true, EnableMetrics = true, #endif }; #region ExecuteWithAttachments var result = await executer.ExecuteWithAttachments( executionOptions, incomingAttachments); #endregion #region ResponseWriter await ResponseWriter.WriteResult(Response, result, cancellation); #endregion }
private void listener_RequestReceived(object sender, RequestEventArgs e) { e.IsHandled = true; e.Response.Reason = string.Empty; string userAgent = string.Empty; IHeader uahead = e.Request.Headers.Where(h => string.Equals("User-Agent", h.Name, StringComparison.OrdinalIgnoreCase)). FirstOrDefault(); if (null != uahead) { userAgent = uahead.HeaderValue; } //Send to the correct handler if (userAgent.StartsWith("FAP")) { if (OnRequest(RequestType.FAP, e)) { return; } } if (OnRequest(RequestType.HTTP, e)) { return; } e.Response.Reason = "Handler error"; e.Response.Status = HttpStatusCode.InternalServerError; var generator = new ResponseWriter(); generator.SendHeaders(e.Context, e.Response); }
private void ProcessUpdateEntityReference(IODataRequestMessage requestMessage, IODataResponseMessage responseMessage, ODataPath odataPath) { // This is for change the reference in single-valued navigation property // PUT ~/Person(0)/Parent/$ref // { // "@odata.context": "http://host/service/$metadata#$ref", // "@odata.id": "Orders(10643)" // } if (this.HttpMethod == HttpMethod.PATCH) { throw Utility.BuildException(HttpStatusCode.MethodNotAllowed, "PATCH on a reference link is not supported.", null); } // Get the parent first var level = this.QueryContext.QueryPath.Count - 2; var parent = this.QueryContext.ResolveQuery(this.DataSource, level); var navigationPropertyName = ((NavigationPropertyLinkSegment)odataPath.LastSegment).NavigationProperty.Name; using (var messageReader = new ODataMessageReader(requestMessage, this.GetReaderSettings(), this.DataSource.Model)) { var referenceLink = messageReader.ReadEntityReferenceLink(); var queryContext = new QueryContext(this.ServiceRootUri, referenceLink.Url, this.DataSource.Model); var target = queryContext.ResolveQuery(this.DataSource); this.DataSource.UpdateProvider.UpdateLink(parent, navigationPropertyName, target); this.DataSource.UpdateProvider.SaveChanges(); } ResponseWriter.WriteEmptyResponse(responseMessage); }
private ProcessingResult ProcessStream(RequestContext context, IActionResult action) { StreamResult result = (StreamResult)action; if (context.Response.ContentType.Value == "text/html") { context.Response.ContentType.Value = "application/octet-stream"; } context.Response.ContentLength.Value = result.Stream.Length; ResponseWriter writer = new ResponseWriter(); writer.SendHeaders(context.HttpContext, context.Response); byte[] buffer = new byte[8196]; int bytesRead = result.Stream.Read(buffer, 0, buffer.Length); while (bytesRead > 0) { context.HttpContext.Stream.Write(buffer, 0, bytesRead); bytesRead = result.Stream.Read(buffer, 0, buffer.Length); } return(ProcessingResult.Abort); }
public void ShowHomePage() { // 先输出页框架 ResponseWriter.WritePage(null /* pageVirtualPath */, null /* model */, true /* flush */); string appRootPath = this.WebRuntime.GetWebSitePath(); BlogBLL bll = new BlogBLL(); // 加载博客内容,第一个数据 string blogFilePath = Path.Combine(appRootPath, "App_Data\\BigPipe\\BlogBody.txt"); ResponseWriter.WriteUserControl("~/BigPipe/UserControls/BlogBody.ascx", bll.GetBlog(blogFilePath), "blog-body", true); // 加载左链接导航栏,第二个数据 string linksFilePath = Path.Combine(appRootPath, "App_Data\\BigPipe\\Links.txt"); ResponseWriter.WriteUserControl("~/BigPipe/UserControls/TagLinks.ascx", bll.GetLinks(linksFilePath), "right", true); // 加载评论,第三个数据 string commentFilePath = Path.Combine(appRootPath, "App_Data\\BigPipe\\Comments.txt"); ResponseWriter.WriteUserControl("~/BigPipe/UserControls/CommentList.ascx", bll.GetComments(commentFilePath), "blog-comments-placeholder", true); ResponseWriter.WriteUserControl("~/BigPipe/UserControls/PageEnd.ascx", null /* model */, true /* flush */); }
public void Handle(HttpListenerRequest req, HttpListenerResponse res) { var revokeSessionIntent = RequestReader.ReadBody <RevokeSessionTokenCommand>(req); if (!revokeSessionIntent.Found) { ResponseWriter.Write(res, HttpStatusCode.Unauthorized, ""); return; } var revokeSessionRequest = revokeSessionIntent.Get(); if (!revokeSessionRequest.IsValid()) { ResponseWriter.Write(res, HttpStatusCode.Unauthorized, ""); return; } var authorized = _bll.RevokeToken(revokeSessionRequest); if (!authorized) { ResponseWriter.Write(res, HttpStatusCode.Unauthorized, ""); return; } var response = new AuthorizeUserResponse(authorized); var body = JsonSerializer.Serialize(response); ResponseWriter.Write(res, body); }
private void SendError(RequestEventArgs e) { e.Response.Status = HttpStatusCode.MethodNotAllowed; e.Response.ContentLength.Value = 0; var generator = new ResponseWriter(); generator.SendHeaders(e.Context, e.Response); }
protected override void Save(XDocument document) { var stream = new MemoryStream(); document.Save(stream); HttpContext.Current.Response.ClearHeaders(); ResponseWriter.WriteFileToResponse(stream, CaptionHelper.GetClassCaption(View.ObjectTypeInfo.Type.FullName) + ".xml"); }
private static void OnHttpMessageEnd( string requestHeaders, byte[] requestBody, string responseHeaders, byte[] responseBody, out bool shouldBlock, ResponseWriter responseWriter ) { shouldBlock = false; }
private void ProcessDelete(object target, IODataResponseMessage responseMessage) { this.DataSource.UpdateProvider.Delete(target); // Protocol 11.4.5 Delete an Entity // On successful completion of the delete, the response MUST be 204 No Content and contain an empty body. ResponseWriter.WriteEmptyResponse(responseMessage); }
/// <summary> /// Processes this response /// </summary> /// <returns></returns> public override async Task <ControllerResponseResult> Process() { var handler = new MessageBoxHandler(TemplateFactory, StringTableManager, DataCollector); await ResponseWriter.WriteAsync(handler.GetInline(Text, Status), Context.Response); return(ControllerResponseResult.RawOutput); }
public ProcessingResult Process(RequestContext context) { IRequest request = context.Request; IResponse response = context.Response; var header = request.Headers["FWCID"].HeaderValue; var IsFWCHandy = header != null; bool IsAuthed = false; if (IsFWCHandy) { IsAuthed = (dbConn.Find <users>(x => x.mobile_id == header)).mobile_id == header; } string output = ""; string R = System.IO.Path.GetFileName(request.Uri.LocalPath); if (R == "register") { var xUsr = new users { mobile_id = header, Nachname = request.Parameters["lname"], Vorname = request.Parameters["fname"], rights = "" }; System.Net.WebClient WC = new System.Net.WebClient(); WC.DownloadString("https://www.feuerwehrcloud.de/deiva/regalert.php?fname=" + request.Parameters["fname"] + "&lname=" + request.Parameters["lname"] + "&id=" + header + "&fwid=" + System.Environment.MachineName); dbConn.Insert(xUsr); } else if (R == "alarms" && IsAuthed) { System.Collections.Generic.Dictionary <string, string> Data = new System.Collections.Generic.Dictionary <string, string>(); foreach (var item in System.IO.Directory.GetFiles("public/alarms/", "*.txt")) { //var F = new System.Collections.Generic.Dictionary<string, string>(); Data.Add(item, System.IO.File.ReadAllText(item.Replace(".txt", ".xml"))); } output = JsonConvert.SerializeObject(Data, Formatting.Indented); } else if (R == "mydata" && IsAuthed) { } else { return(ProcessingResult.Continue); } // Set default content type response.ContentType = new ContentTypeHeader("text/html"); //ProcessHeaders(response, CgiFeuerwehrCloud.Helper.ParseCgiHeaders(ref output)); response.ContentLength.Value = output.Length; ResponseWriter generator = new ResponseWriter(); generator.SendHeaders(context.HttpContext, response); generator.Send(context.HttpContext, output, System.Text.Encoding.UTF8); return(ProcessingResult.Abort); }
/// <summary> /// Processes this response /// </summary> /// <returns></returns> public override ControllerResponseResult Process() { Context.Response.ContentType = "application/json"; Context.Response.StatusCode = _statusCode; ResponseWriter.Write(JsonConvert.SerializeObject(_objectToConvert), Context.Response); return(ControllerResponseResult.RawOutput); }
/// <summary> /// Processes this response /// </summary> /// <returns></returns> public override async Task <ControllerResponseResult> Process() { Context.Response.ContentType = "application/json"; Context.Response.StatusCode = _statusCode; await ResponseWriter.WriteAsync(JsonSerializer.Serialize(_objectToConvert), Context.Response); return(ControllerResponseResult.RawOutput); }
/// <summary> /// Will send a file to client. /// </summary> /// <param name="context">HTTP context containing outbound stream.</param> /// <param name="response">Response containing headers.</param> /// <param name="stream">File stream</param> private void SendFile(IHttpContext context, IResponse response, Stream stream) { response.ContentLength.Value = stream.Length; ResponseWriter generator = new ResponseWriter(); generator.SendHeaders(context, response); generator.SendBody(context, stream); }
public override void Process(IODataRequestMessage requestMessage, IODataResponseMessage responseMessage) { if (this.TryDispatch(requestMessage, responseMessage)) { return; } if (this.QueryContext.Target.TypeKind != EdmTypeKind.Collection) { throw Utility.BuildException(HttpStatusCode.BadRequest, "The new resource can only be created under collection resource.", null); } if (this.QueryContext.Target.IsReference) { this.ProcessCreateLink(requestMessage, responseMessage); return; } try { var targetEntitySet = (IEdmEntitySetBase)this.QueryContext.Target.NavigationSource; // TODO: [lianw] Try to remove "targetEntitySet" later. var queryResults = this.QueryContext.ResolveQuery(this.DataSource); if (!IsAllowInsert(targetEntitySet as IEdmEntitySet)) { throw new ODataServiceException(HttpStatusCode.BadRequest, "The insert request is not allowed.", null); } var bodyObject = ProcessPostBody(requestMessage, targetEntitySet, queryResults); using (var messageWriter = this.CreateMessageWriter(responseMessage)) { this.DataSource.UpdateProvider.SaveChanges(); // 11.4.2 Create an Entity // Upon successful completion the service MUST respond with either 201 Created, or 204 No Content if the request included a return Prefer header with a value of return=minimal. responseMessage.SetStatusCode(HttpStatusCode.Created); responseMessage.SetHeader(ServiceConstants.HttpHeaders.Location, Utility.BuildLocationUri(this.QueryContext, bodyObject).OriginalString); var currentETag = Utility.GetETagValue(bodyObject); // if the current entity has ETag field if (currentETag != null) { responseMessage.SetHeader(ServiceConstants.HttpHeaders.ETag, currentETag); } ResponseWriter.WriteEntry(messageWriter.CreateODataResourceWriter(targetEntitySet), bodyObject, targetEntitySet, ODataVersion.V4, null); } } catch { this.DataSource.UpdateProvider.ClearChanges(); throw; } }
protected override void DashbardExportXMLExecute(object sender, SimpleActionExecuteEventArgs e) { base.DashbardExportXMLExecute(sender, e); var stream = new MemoryStream(); var document = XDocument.Parse(((IDashboardDefinition)View.CurrentObject).Xml); document.Save(stream); HttpContext.Current.Response.ClearHeaders(); ResponseWriter.WriteFileToResponse(stream, CaptionHelper.GetClassCaption(View.ObjectTypeInfo.Type.FullName) + ".xml"); }
private bool SendFile(RequestEventArgs e, string path, string url) { try { string fileExtension = Path.GetExtension(path); if (fileExtension != null && fileExtension.StartsWith(".")) { fileExtension = fileExtension.Substring(1); } ContentTypeHeader header; if (!contentTypes.TryGetValue(fileExtension, out header)) { header = contentTypes["default"]; } e.Response.ContentType = header; DateTime modified = File.GetLastWriteTime(path).ToUniversalTime(); // Only send file if it has not been modified. var browserCacheDate = e.Request.Headers["If-Modified-Since"] as DateHeader; if (browserCacheDate != null) { DateTime since = browserCacheDate.Value.ToUniversalTime(); // Allow for file systems with subsecond time stamps modified = new DateTime(modified.Year, modified.Month, modified.Day, modified.Hour, modified.Minute, modified.Second, modified.Kind); if (since >= modified) { e.Response.Status = HttpStatusCode.NotModified; var generator = new ResponseWriter(); e.Response.ContentLength.Value = 0; generator.SendHeaders(e.Context, e.Response); return(true); } } using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { e.Response.Add(new DateHeader("Last-Modified", modified)); // Send response and tell server to do nothing more with the request. SendFile(e.Context, fs, url); return(true); } } catch { return(false); } }
/// <summary> /// Processes this response /// </summary> public override ControllerResponseResult Process() { Context.Response.StatusCode = StatusCode; if (AjaxData != null) { ResponseWriter.Write(AjaxData, Context.Response); } return(ControllerResponseResult.RawOutput); }
public async Task OnDuplexStream(string p_title, RequestReader p_reader, ResponseWriter p_writer) { while (await p_reader.MoveNext()) { Log.Information("服务端读取:" + p_reader.Val <string>()); var msg = "++" + p_reader.Val <string>(); await p_writer.Write(msg); Log.Information("服务端写入:" + msg); } }
public override void setResponseWriter (ResponseWriter __p1) { _facesContex.setResponseWriter (__p1); }
public override async Task WriteTo(ResponseWriter writer) { await writer.Write(this); }
public abstract Task WriteTo(ResponseWriter writer);