/// <summary> /// Initialise a new instance of a network packet to send to the network connection plugin. /// </summary> public NetworkPacket() { if (DefaultHeader != null) _header = DefaultHeader; else _header = new HeaderCollection(); }
public Request() { this.contentLength = 0; this.contentType = MimeType.Default; this.cookies = new CookieCollection(); this.hasEntityBody = false; this.headers = new HeaderCollection(); this.isAuthenticated = false; this.isLocal = false; this.isSecureConnection = false; this.keepAlive = false; this.localEndPoint = null; this.method = RequestMethod.Unknown; this.protocolType = null; this.protocolVersion = null; this.rawMethod = null; this.rawRequest = null; this.rawUrl = null; this.referrer = null; this.remoteEndPoint = null; this.requestData = new RequestDataCollection(); this.url = null; this.userAgent = null; this.userHostName = null; }
public void ReturnHeaderValueIfSpecified() { var header = new Header(Header.Origin, "ServerName", checkReservedNames: false); var headers = new HeaderCollection(header.ToEnumerable()); Assert.Equal("ServerName", headers.GetOrigin()); }
public void ReturnHeadersFromEventContextIfNotNull() { var e = new FakeEvent(); var headers = new HeaderCollection(Enumerable.Empty<Header>()); using (new EventContext(GuidStrategy.NewGuid(), headers, e)) Assert.Same(headers, e.Headers); }
public void ReturnHeadersFromCommandContextIfNotNull() { var command = new FakeCommand(); var headers = new HeaderCollection(Enumerable.Empty<Header>()); using (new CommandContext(GuidStrategy.NewGuid(), headers, CommandEnvelope.Empty)) Assert.Same(headers, command.Headers); }
/// <summary> /// Creates a new <see cref="CallbackContext"/> from a list of headers /// </summary> /// <param name="headers">The <see cref="HeaderCollection"/> used to populate the object</param> /// <returns><see cref="CallbackContext"/></returns> public static new CallbackContext FromHeaders(HeaderCollection headers) { CallbackDataBase baseObj = CallbackDataBase.FromHeaders(headers); CallbackContext context = new CallbackContext(baseObj.Data, baseObj.Type); return context; }
public void CanShortCircuitAccessToOriginHeader() { var e = new FakeEvent(); var headers = new HeaderCollection(new[] { new Header(Header.Origin, "MyOrigin", checkReservedNames: false) }); using (new EventContext(GuidStrategy.NewGuid(), headers, e)) Assert.Equal("MyOrigin", e.GetOrigin()); }
public void CanShortCircuitAccessToUserAddressHeader() { var command = new FakeCommand(); var headers = new HeaderCollection(new[] { new Header(Header.UserAddress, IPAddress.Loopback.ToString(), checkReservedNames: false) }); using (new CommandContext(GuidStrategy.NewGuid(), headers, CommandEnvelope.Empty)) Assert.Equal(IPAddress.Loopback, command.GetUserAddress()); }
public void CanShortCircuitAccessToOriginHeader() { var command = new FakeCommand(); var headers = new HeaderCollection(new[] { new Header(Header.Origin, "MyOrigin", checkReservedNames: false) }); using (new CommandContext(GuidStrategy.NewGuid(), headers, CommandEnvelope.Empty)) Assert.Equal("MyOrigin", command.GetOrigin()); }
/// <summary> /// Initializes a new instance of <see cref="CommitData"/> /// </summary> /// <param name="headers">The headers associated with this commit.</param> /// <param name="events">The events associated with this commit.</param> public CommitData(HeaderCollection headers, EventCollection events) { Verify.NotNull(headers, nameof(headers)); Verify.NotNull(events, nameof(events)); Headers = headers; Events = events; }
public void CanShortCircuitAccessToTimestampHeader() { var now = DateTime.UtcNow; var e = new FakeEvent(); var headers = new HeaderCollection(new[] { new Header(Header.Timestamp, now.ToString(DateTimeFormat.RoundTrip), checkReservedNames: false) }); using (new EventContext(GuidStrategy.NewGuid(), headers, e)) Assert.Equal(now, e.GetTimestamp()); }
public void CanShortCircuitAccessToTimestampHeader() { var now = DateTime.UtcNow; var command = new FakeCommand(); var headers = new HeaderCollection(new[] { new Header(Header.Timestamp, now.ToString(DateTimeFormat.RoundTrip), checkReservedNames: false) }); using (new CommandContext(GuidStrategy.NewGuid(), headers, CommandEnvelope.Empty)) Assert.Equal(now, command.GetTimestamp()); }
/// <summary> /// Creates a new <see cref="Error"/> from a list of headers /// </summary> /// <param name="headers">The <see cref="HeaderCollection"/> used to populate the object</param> /// <returns><see cref="Error"/></returns> public static Error FromHeaders(HeaderCollection headers) { int errorCode = headers.GetHeaderIntValue(Header.ERROR_CODE, true); string description = headers.GetHeaderStringValue(Header.ERROR_DESCRIPTION, false); Error error = new Error(errorCode, description); SetInhertiedAttributesFromHeaders(error, headers); return error; }
/// <summary> /// Parses a response message and returns the corresponding <see cref="Response"/> object, returning the list of parsed headers as well. /// </summary> /// <param name="message">The entire GNTP response message</param> /// <param name="context">If this is a CALLBACK response, returns the <see cref="CallbackData"/> associated with the response; otherwise <c>null</c></param> /// <param name="headers">Contains the list of parsed headers</param> /// <returns><see cref="Response"/>The <see cref="Response"/> represented by the message</returns> public Response Parse(string message, out CallbackData context, out HeaderCollection headers) { context = null; headers = null; Response response = Parse(message, out headers); context = response.CallbackData; return response; }
/// <summary> /// Creates a new <see cref="CallbackDataBase"/> from a list of headers /// </summary> /// <param name="headers">The <see cref="HeaderCollection"/> used to populate the object</param> /// <returns><see cref="CallbackDataBase"/></returns> public static CallbackDataBase FromHeaders(HeaderCollection headers) { string data = headers.GetHeaderStringValue(Header.NOTIFICATION_CALLBACK_CONTEXT, true); string type = headers.GetHeaderResourceValue(Header.NOTIFICATION_CALLBACK_CONTEXT_TYPE, true); CallbackDataBase context = new CallbackDataBase(data, type); return context; }
public void CanMutateUnderlyingCollection() { var dictionary = new Dictionary<String, String>(); var headers = new HeaderCollection(dictionary); dictionary.Add("MyTestKey", "MyTestValue"); Assert.Equal(1, headers.Count); }
/// <summary> /// Initializes a new instance of the <see cref="Response"/> class. /// </summary> /// <param name="context">Context that the response will be sent through.</param> /// <param name="request">Request that the response is for.</param> /// <exception cref="FormatException">Version must start with 'HTTP/'</exception> public Response(IHttpContext context, IRequest request) { _context = context; HttpVersion = request.HttpVersion; Reason = ""; // 可以在此定制 Status = HttpStatusCode.OK; ContentType = new ContentTypeHeader("text/html"); Encoding = request.Encoding; _headers = CreateHeaderCollection(); }
/// <summary> /// Initializes a new instance of the <see cref="GNTPRequest"/> class. /// </summary> /// <param name="version">The version of the GNTP request.</param> /// <param name="directive">The type of GNTP request.</param> /// <param name="key">The key used to validate and encrypt the message.</param> /// <param name="headers">The collection of headers parsed from the current request.</param> /// <param name="applicationName">The name of the application sending the request.</param> /// <param name="notificationsToBeRegistered">A collection of the groups of headers for each notification type to be registered.</param> /// <param name="callbackContext">The callback context associated with the request.</param> public GNTPRequest(string version, RequestType directive, Key key, HeaderCollection headers, string applicationName, List<HeaderCollection> notificationsToBeRegistered, CallbackContext callbackContext) { this.version = version; this.directive = directive; this.key = key; this.headers = headers; this.applicationName = applicationName; this.notificationsToBeRegistered = notificationsToBeRegistered; this.callbackContext = callbackContext; }
/// <summary> /// Initializes a new instance of the <see cref = "PostmarkMessage" /> class. /// </summary> /// <param name = "from">An email address for a sender.</param> /// <param name = "to">An email address for a recipient.</param> /// <param name = "subject">The message subject line.</param> /// <param name = "body">The message body.</param> /// <param name = "headers" oo>A collection of additional mail headers to send with the message. (optional)</param> public PostmarkMessage(string from, string to, string subject, string body, IDictionary<string, string> headers = null) : base() { var isHtml = !body.Equals(WebUtility.HtmlEncode(body)); From = from; To = to; Subject = subject; TextBody = isHtml ? null : body; HtmlBody = isHtml ? body : null; Headers = new HeaderCollection(headers ?? new Dictionary<string, string>()); }
/// <summary> /// Converts the Error to a list of headers /// </summary> /// <returns><see cref="HeaderCollection"/></returns> public virtual HeaderCollection ToHeaders() { Header hErrorCode = new Header(Header.ERROR_CODE, this.ErrorCode.ToString()); Header hDescription = new Header(Header.ERROR_DESCRIPTION, this.ErrorDescription); HeaderCollection headers = new HeaderCollection(); headers.AddHeader(hErrorCode); headers.AddHeader(hDescription); this.AddInheritedAttributesToHeaders(headers); return headers; }
internal DSN(MimeEntity explanation, HeaderCollection fields, IEnumerable<HeaderCollection> perRecipientCollection) { m_explanation = explanation; m_perMessage = new DSNPerMessage(fields); m_perRecipients = new List<DSNPerRecipient>(); foreach (HeaderCollection perRecipientFields in perRecipientCollection) { m_perRecipients.Add(new DSNPerRecipient(perRecipientFields)); } }
/// <summary> /// Converts a NameValueCollection /// (as is used in the 1.x client) /// to the HeaderCollection required for the 2.0 client. /// </summary> /// <param name="collection"></param> /// <returns></returns> public static HeaderCollection AsHeaderCollection(this NameValueCollection collection) { var retval = new HeaderCollection(); if (collection != null) { foreach (var key in collection.AllKeys) { retval[key] = collection[key]; } } return retval; }
/// <summary> /// Converts the SubscriptionResponse to a list of headers /// </summary> /// <returns><see cref="HeaderCollection"/></returns> public override HeaderCollection ToHeaders() { HeaderCollection headers = new HeaderCollection(); Header hTTL = new Header(Header.SUBSCRIPTION_TTL, this.ttl.ToString()); headers.AddHeader(hTTL); HeaderCollection baseHeaders = base.ToHeaders(); headers.AddHeaders(baseHeaders); return headers; }
/// <summary> /// Writes a collection of headers. /// </summary> /// <param name="headers">The headers to write.</param> public void Write(HeaderCollection headers) { if (headers == null) { throw new ArgumentNullException("headers"); } foreach(Header header in headers) { Write(header); } }
/// <summary> /// Initializes a new instance of the <see cref="Response"/> class. /// </summary> /// <param name="version">HTTP Version.</param> /// <param name="code">HTTP status code.</param> /// <param name="reason">Why the status code was selected.</param> /// <exception cref="FormatException">Version must start with 'HTTP/'</exception> public Response(string version, HttpStatusCode code, string reason) { if (!version.StartsWith("HTTP/")) throw new FormatException("Version must start with 'HTTP/'"); Status = code; Reason = reason; HttpVersion = version; ContentType = new ContentTypeHeader("text/html"); Encoding = Encoding.UTF8; _headers = CreateHeaderCollection(); }
/// <summary> /// Initializes a new instance of the <see cref="Response"/> class. /// </summary> public Response() { this.cookies = new CookieCollection(); this.headers = new HeaderCollection(); this.headersSent = false; this.contentType = MimeType.Default; this.outputBuffer = new List<byte>(); this.sent = 0; this.status = StatusCode.Http500InternalServerError; this.useChunkedTransferEncoding = false; this.useCompression = false; }
/// <summary> /// Initializes a new instance of <see cref="EventContext"/> with the specified <paramref name="aggregateId"/> and <paramref name="headers"/>. /// </summary> /// <param name="aggregateId">The unique <see cref="Aggregate"/> identifier.</param> /// <param name="headers">The <see cref="Event"/> headers.</param> /// <param name="e">The <see cref="Event"/>.</param> public EventContext(Guid aggregateId, HeaderCollection headers, Event e) { Verify.NotEqual(Guid.Empty, aggregateId, nameof(aggregateId)); Verify.NotNull(headers, nameof(headers)); Verify.NotNull(e, nameof(e)); this.originalContext = currentContext; this.thread = Thread.CurrentThread; this.aggregateId = aggregateId; this.headers = headers; this.@event = e; currentContext = this; }
/// <summary> /// Initializes a new instance of <see cref="CommandContext"/> with the specified <paramref name="commandId"/> and <paramref name="headers"/>. /// </summary> /// <param name="commandId">The unique <see cref="Command"/> identifier.</param> /// <param name="headers">The <see cref="Command"/> headers.</param> /// <param name="envelope">The <see cref="CommandEnvelope"/> associated with this context.</param> public CommandContext(Guid commandId, HeaderCollection headers, CommandEnvelope envelope) { Verify.NotNull(headers, nameof(headers)); Verify.NotNull(envelope, nameof(envelope)); this.raisedEvents = new List<Event>(); this.originalContext = currentContext; this.thread = Thread.CurrentThread; this.commandId = commandId; this.envelope = envelope; this.headers = headers; currentContext = this; }
/// <summary> /// Initializes a new instance of <see cref="Commit"/>. /// </summary> /// <param name="id">The unique commit id.</param> /// <param name="timestamp">The <see cref="DateTime"/> when the snapshot was persisted.</param> /// <param name="correlationId">The correlation id.</param> /// <param name="streamId">The event stream id.</param> /// <param name="version">The event stream revision.</param> /// <param name="headers">The optional set of headers associated with this commit.</param> /// <param name="events">The optional set of events associated with this commit.</param> internal Commit(Int64? id, DateTime timestamp, Guid correlationId, Guid streamId, Int32 version, HeaderCollection headers, EventCollection events) { Verify.NotEqual(Guid.Empty, correlationId, nameof(correlationId)); Verify.NotEqual(Guid.Empty, streamId, nameof(streamId)); Verify.GreaterThan(0, version, nameof(version)); Id = id; Timestamp = timestamp; CorrelationId = correlationId; StreamId = streamId; Version = version; Events = events ?? EventCollection.Empty; Headers = headers ?? HeaderCollection.Empty; }
internal DSNPerRecipient(HeaderCollection fields) { // // Required Fields // Action = (DSNStandard.DSNAction)Enum.Parse(typeof(DSNStandard.DSNAction), fields.GetValue(DSNStandard.Fields.Action),true); Status = fields.GetValue((DSNStandard.Fields.Status)); FinalRecipient = DSNParser.ParseFinalRecipient(fields.GetValue((DSNStandard.Fields.FinalRecipient))); // // Optional Fields // HeaderCollection otherFields = new HeaderCollection(); otherFields.Add(fields, DSNStandard.PerRecipientOptionalFields); OtherFields = otherFields; }
public static async IAsyncEnumerable <RequestMessage> UnpackJsonRequestBodyAsync( Stream body, CancellationToken cancellationToken ) { var document = await JsonDocument.ParseAsync(body, new JsonDocumentOptions { AllowTrailingCommas = true, //CommentHandling = JsonCommentHandling.Allow, MaxDepth = 100 }, cancellationToken); var rootRequests = document.RootElement.EnumerateArray(); foreach (var request in rootRequests) { var requestObject = request.EnumerateObject(); string requestProtocolVersion = "1.1"; string requestMethod = null; string requestUri = null; HeaderCollection requestHeaders = null; Stream requestBody = null; foreach (var objProperty in requestObject) { switch (objProperty.Name.ToLower()) { case "protocol-version": { requestProtocolVersion = objProperty.Value.GetString(); break; } case "method": { requestMethod = objProperty.Value.GetString(); break; } case "uri": { requestUri = objProperty.Value.GetString(); break; } case "headers": { requestHeaders = new HeaderCollection(HttpHeaderType.RequestHeader); foreach (var header in objProperty.Value.EnumerateObject()) { switch (header.Value.ValueKind) { case JsonValueKind.Array: requestHeaders.Add(header.Name, header.Value.EnumerateArray().Cast <string>().ToList()); break; case JsonValueKind.String: requestHeaders.Add(header.Name, header.Value.GetString()); break; case JsonValueKind.Undefined: break; default: throw new NotSupportedException(); } } break; } case "body": { switch (objProperty.Value.ValueKind) { case JsonValueKind.Null: case JsonValueKind.Undefined: break; case JsonValueKind.Object: throw new NotImplementedException(); break; case JsonValueKind.Array: throw new NotImplementedException(); break; case JsonValueKind.String: using (var transform = new FromBase64Transform()) { requestBody = new CryptoStream( new MemoryStream(Encoding.ASCII.GetBytes(objProperty.Value.GetString())), transform, CryptoStreamMode.Read ); } break; case JsonValueKind.Number: throw new NotImplementedException(); break; case JsonValueKind.True: throw new NotImplementedException(); break; case JsonValueKind.False: throw new NotImplementedException(); break; default: throw new ArgumentOutOfRangeException(); } break; } default: { throw new RedTransportException("UnknownJsonRequestKey"); } } } if (string.IsNullOrWhiteSpace(requestMethod)) { requestMethod = "GET"; //throw new RedTransportException("UnknownJsonRequestMethod"); } if (string.IsNullOrWhiteSpace(requestUri)) { throw new RedTransportException("UnknownJsonRequestUri"); } if (System.Uri.CheckHostName(requestUri) == UriHostNameType.Unknown) { string path; string queryString; var questionMarkIndex = requestUri.IndexOf('?'); if (questionMarkIndex >= 0) { path = requestUri.Substring(0, questionMarkIndex); queryString = requestMethod.Substring(questionMarkIndex + 1); } else { path = requestUri; queryString = string.Empty; } if (!path.StartsWith('/')) { path = '/' + path; } var scheme = "http"; var host = string.Empty; var pathBase = string.Empty; var rawTarget = string.Empty; yield return(new RequestMessage( requestProtocolVersion, scheme, host, pathBase, path, queryString, rawTarget, requestMethod, requestHeaders, requestBody )); } else { var uri = new Uri(requestUri); yield return(new RequestMessage( requestProtocolVersion, uri, requestMethod, requestHeaders, requestBody )); } } }
public Request Parse(string requestData) { var lines = requestData.Split(Environment.NewLine); var requestLine = lines.First(); var match = RequestLineRegex.Match(requestLine); if (!match.Success) { throw new ApplicationException("Unable to process request"); } var method = ParseHelper.ParseMethod(match.Groups[1].Value); if (method == Method.None) { throw new ApplicationException($"Unable to match {match.Groups[1].Value} to an available method"); } var path = match.Groups[2].Value; var query = match.Groups[3].Value; var queryDictionary = new Dictionary <string, string>(); var qmatch = QueryRegex.Matches(query); foreach (var qm in qmatch) { //var KeyVauePairmatch = qm.ToString(); var kvp = qm.ToString(); var KVPParsed = QueryKeyValuePair.Match(qm.ToString()); var key = KVPParsed.Groups[1].ToString(); var value = KVPParsed.Groups[2].ToString(); queryDictionary.Add(key, value); } ServerInterfaces.QueryCollection queryColl = new ServerInterfaces.QueryCollection(queryDictionary); // to-do: map headers, querystring, body, etc... var headerLines = lines.Skip(1).TakeWhile(line => !string.IsNullOrEmpty(line)); var headerDict = new Dictionary <string, string>(); foreach (var line in headerLines) { var hmatch = HeaderRegex.Match(line); if (!hmatch.Success) { throw new ApplicationException($"Unable to process header line {line}"); } var headerName = hmatch.Groups[1].Value; var headerValue = hmatch.Groups[2].Value; headerDict.Add(headerName, headerValue); } HeaderCollection headers = new HeaderCollection(headerDict); var bodyLines = lines.SkipWhile(line => !string.IsNullOrEmpty(line)).Skip(1); var body = string.Join(Environment.NewLine, bodyLines); return(new Request { Method = method, Path = path, Query = queryColl.ToString(), Headers = headers, Body = body }); }
private void _showReport(string fileName) { try { Mail mail = new Mail("TryIt"); mail.Load(fileName, false); if (!mail.IsReport) { MessageBox.Show("This is not a report"); return; } string s = ""; MailReport report = mail.GetReport(); switch (report.ReportType) { case DeliveryReportType.DeliveryReceipt: s = "This is a deliver receipt.\r\n\r\n"; break; case DeliveryReportType.ReadReceipt: s = "This is a read receipt.\r\n\r\n"; break; case DeliveryReportType.Deleted: s = "This is a unread receipt, this email was deleted without read.\r\n\r\n"; break; case DeliveryReportType.DelayedReport: s = "This is a delay report, this email will be retried later automatically.\r\n\r\n"; break; default: s = "This is a failure report.\r\n\r\n"; break; } s += string.Format("Original Sender: {0}\r\n", report.OriginalSender); s += string.Format("Original Recipient: {0}\r\n", report.OriginalRecipient); s += string.Format("Original Message-ID: {0}\r\n\r\n", report.OriginalMessageID); if (report.ReportType == DeliveryReportType.FailureReport || report.ReportType == DeliveryReportType.DelayedReport) { s += string.Format("Original Subject: {0}\r\n", report.OriginalSubject); s += string.Format("Report MTA: {0}\r\n", report.ReportMTA); s += string.Format("Error Code: {0}\r\n", report.ErrCode); s += string.Format("Error Description: {0}\r\n\r\n", report.ErrDescription); s += "---- Original Message Header ----\r\n\r\n"; HeaderCollection headers = report.OriginalHeaders; int count = headers.Count; for (int i = 0; i < count; i++) { HeaderItem header = headers[i] as HeaderItem; s += string.Format("{0}: {1}\r\n", header.HeaderKey, header.HeaderValue); } } textReport.Text = s; } catch (Exception ep) { MessageBox.Show(ep.Message); } }
public static async Task <WebResponse> Delete(this Uri url, ReadOnlyMemory <byte> payload, HeaderCollection headers, CancellationToken token, int?timeout = default) { HttpWebRequest req = WebRequest.CreateHttp(url); if (timeout.HasValue) { req.Timeout = timeout.Value; } req.Method = "DELETE"; req.SetHeaders(headers); req.ContentLength = payload.Length; await using (Stream stream = await req.GetRequestStreamAsync().ConfigureAwait(false)) { await stream.WriteAsync(payload, token).ConfigureAwait(false); //Push it out there } return(await req.GetResponseAsync(token).ConfigureAwait(false)); }
private static IEnumerable <string> GetHeaderInfo(HeaderCollection headers) => headers.Keys.Select(key => $"<div>{key}: {string.Join(", ", headers.GetValues(key))}</div>");
/// <summary> /// </summary> /// <param name="httpVersion">Version like <c>HTTP/1.1</c></param> protected HttpMessage(string httpVersion) { HttpVersion = httpVersion; _headers = new HeaderCollection(OnHeaderSet); }
protected void InitializeContext() { _thisHandle = GCHandle.Alloc(this); Method = GetVerb(); RawTarget = GetRawUrl(); // TODO version is slow. HttpVersion = GetVersion(); Scheme = SslStatus != SslStatus.Insecure ? Constants.HttpsScheme : Constants.HttpScheme; KnownMethod = VerbId; StatusCode = 200; var originalPath = GetOriginalPath(); if (KnownMethod == HttpApiTypes.HTTP_VERB.HttpVerbOPTIONS && string.Equals(RawTarget, "*", StringComparison.Ordinal)) { PathBase = string.Empty; Path = string.Empty; } else { // Path and pathbase are unescaped by RequestUriBuilder // The UsePathBase middleware will modify the pathbase and path correctly PathBase = string.Empty; Path = originalPath; } var cookedUrl = GetCookedUrl(); QueryString = cookedUrl.GetQueryString() ?? string.Empty; RequestHeaders = new RequestHeaders(this); HttpResponseHeaders = new HeaderCollection(); ResponseHeaders = HttpResponseHeaders; if (_options.ForwardWindowsAuthentication) { WindowsUser = GetWindowsPrincipal(); if (_options.AutomaticAuthentication) { User = WindowsUser; } } ResetFeatureCollection(); if (!_server.IsWebSocketAvailable(_pInProcessHandler)) { _currentIHttpUpgradeFeature = null; } _streams = new Streams(this); (RequestBody, ResponseBody) = _streams.Start(); var pipe = new Pipe( new PipeOptions( _memoryPool, readerScheduler: PipeScheduler.ThreadPool, pauseWriterThreshold: PauseWriterThreshold, resumeWriterThreshold: ResumeWriterTheshold, minimumSegmentSize: MinAllocBufferSize)); _bodyOutput = new OutputProducer(pipe); NativeMethods.HttpSetManagedContext(_pInProcessHandler, (IntPtr)_thisHandle); }
public IResponseResult <Me> WhoAmI(string token) { return(this.MeEndpoint.Get <Me>(headers: HeaderCollection.Add("Authorization", $"Bearer {token}"))); }
public async Task <IResponseResult <Me> > WhoAmIAsync(string token) { return(await this.MeEndpoint.GetAsync <Me>(headers : HeaderCollection.Add("Authorization", $"Bearer {token}"))); }
/// <summary> /// Sets the value of the Accept header for a query. /// </summary> /// <param name="headers">The headers to modify.</param> /// <param name="components">The query components for the request.</param> internal void SetRequestAcceptHeaderForQuery(HeaderCollection headers, QueryComponents components) { this.SetAcceptHeaderAndCharset(headers, ChooseMediaType(components.HasSelectQueryOption)); }
/// <summary> /// Sets the value of the Accept header to the appropriate value for the current format. /// </summary> /// <param name="headers">The headers to modify.</param> internal void SetRequestAcceptHeader(HeaderCollection headers) { this.SetAcceptHeaderAndCharset(headers, ChooseMediaType(false)); }
internal unsafe IISHttpContext(MemoryPool <byte> memoryPool, IntPtr pInProcessHandler, IISOptions options, IISHttpServer server) : base((HttpApiTypes.HTTP_REQUEST *)NativeMethods.http_get_raw_request(pInProcessHandler)) { _thisHandle = GCHandle.Alloc(this); _memoryPool = memoryPool; _pInProcessHandler = pInProcessHandler; _server = server; NativeMethods.http_set_managed_context(pInProcessHandler, (IntPtr)_thisHandle); unsafe { Method = GetVerb(); RawTarget = GetRawUrl(); // TODO version is slow. HttpVersion = GetVersion(); Scheme = SslStatus != SslStatus.Insecure ? Constants.HttpsScheme : Constants.HttpScheme; KnownMethod = VerbId; var originalPath = RequestUriBuilder.DecodeAndUnescapePath(GetRawUrlInBytes()); if (KnownMethod == HttpApiTypes.HTTP_VERB.HttpVerbOPTIONS && string.Equals(RawTarget, "*", StringComparison.Ordinal)) { PathBase = string.Empty; Path = string.Empty; } else { // Path and pathbase are unescaped by RequestUriBuilder // The UsePathBase middleware will modify the pathbase and path correctly PathBase = string.Empty; Path = originalPath; } var cookedUrl = GetCookedUrl(); QueryString = cookedUrl.GetQueryString() ?? string.Empty; // TODO: Avoid using long.ToString, it's pretty slow RequestConnectionId = ConnectionId.ToString(CultureInfo.InvariantCulture); // Copied from WebListener // This is the base GUID used by HTTP.SYS for generating the activity ID. // HTTP.SYS overwrites the first 8 bytes of the base GUID with RequestId to generate ETW activity ID. // The requestId should be set by the NativeRequestContext var guid = new Guid(0xffcb4c93, 0xa57f, 0x453c, 0xb6, 0x3f, 0x84, 0x71, 0xc, 0x79, 0x67, 0xbb); *((ulong *)&guid) = RequestId; // TODO: Also make this not slow TraceIdentifier = guid.ToString(); var localEndPoint = GetLocalEndPoint(); LocalIpAddress = localEndPoint.GetIPAddress(); LocalPort = localEndPoint.GetPort(); var remoteEndPoint = GetRemoteEndPoint(); RemoteIpAddress = remoteEndPoint.GetIPAddress(); RemotePort = remoteEndPoint.GetPort(); StatusCode = 200; RequestHeaders = new RequestHeaders(this); HttpResponseHeaders = new HeaderCollection(); ResponseHeaders = HttpResponseHeaders; if (options.ForwardWindowsAuthentication) { WindowsUser = GetWindowsPrincipal(); if (options.AutomaticAuthentication) { User = WindowsUser; } } ResetFeatureCollection(); // Check if the Http upgrade feature is available in IIS. // To check this, we can look at the server variable WEBSOCKET_VERSION // And see if there is a version. Same check that Katana did: // https://github.com/aspnet/AspNetKatana/blob/9f6e09af6bf203744feb5347121fe25f6eec06d8/src/Microsoft.Owin.Host.SystemWeb/OwinAppContext.cs#L125 // Actively not locking here as acquiring a lock on every request will hurt perf more than checking the // server variables a few extra times if a bunch of requests hit the server at the same time. if (_websocketAvailability == WebsocketAvailabilityStatus.Uninitialized) { NativeMethods.http_get_server_variable(pInProcessHandler, WebSocketVersionString, out var webSocketsSupported); var webSocketsAvailable = !string.IsNullOrEmpty(webSocketsSupported); _websocketAvailability = webSocketsAvailable ? WebsocketAvailabilityStatus.Available : WebsocketAvailabilityStatus.NotAvailable; } if (_websocketAvailability == WebsocketAvailabilityStatus.NotAvailable) { _currentIHttpUpgradeFeature = null; } } RequestBody = new IISHttpRequestBody(this); ResponseBody = new IISHttpResponseBody(this); Input = new Pipe(new PipeOptions(_memoryPool, readerScheduler: PipeScheduler.ThreadPool, minimumSegmentSize: MinAllocBufferSize)); var pipe = new Pipe(new PipeOptions( _memoryPool, readerScheduler: PipeScheduler.ThreadPool, pauseWriterThreshold: PauseWriterThreshold, resumeWriterThreshold: ResumeWriterTheshold, minimumSegmentSize: MinAllocBufferSize)); Output = new OutputProducer(pipe); }
public void SerializeEnity_EnumProperty() { MyEntity1 myEntity1 = new MyEntity1() { ID = 2, MyColorValue = MyColor.Yellow, MyFlagsColorValue = MyFlagsColor.Blue, ComplexValue1Value = new ComplexValue1() { MyColorValue = MyColor.Green, MyFlagsColorValue = MyFlagsColor.Red }, MyFlagsColorCollection1 = new List <MyFlagsColor>() { MyFlagsColor.Blue, MyFlagsColor.Red, MyFlagsColor.Red }, MyColorCollection = new List <MyColor?>() }; DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc")); dataServiceContext.EnableAtom = true; dataServiceContext.Format.UseAtom(); dataServiceContext.AttachTo("MyEntitySet1", myEntity1); var requestInfo = new RequestInfo(dataServiceContext); var serializer = new Serializer(requestInfo); var headers = new HeaderCollection(); headers.SetHeader("Content-Type", "application/atom+xml;odata.metadata=minimal"); var clientModel = new ClientEdmModel(ODataProtocolVersion.V4); var entityDescriptor = new EntityDescriptor(clientModel); entityDescriptor.State = EntityStates.Added; entityDescriptor.Entity = myEntity1; var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto); var linkDescriptors = new LinkDescriptor[] { }; var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo); serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper); // read result: MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream); stream.Position = 0; string payload = (new StreamReader(stream)).ReadToEnd(); payload = Regex.Replace(payload, "<updated>[^<]*</updated>", ""); payload.Should().Be( "<?xml version=\"1.0\" encoding=\"utf-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\" " + "xmlns:d=\"http://docs.oasis-open.org/odata/ns/data\" xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\" " + "xmlns:georss=\"http://www.georss.org/georss\" xmlns:gml=\"http://www.opengis.net/gml\">" + "<id />" + "<title />" + //"<updated>2013-11-11T19:29:54Z</updated>" + "<author><name /></author>" + "<content type=\"application/xml\">" + "<m:properties>" + "<d:ComplexValue1Value>" + "<d:MyColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyColor\">Green</d:MyColorValue>" + "<d:MyFlagsColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyFlagsColor\">Red</d:MyFlagsColorValue>" + "<d:StringValue m:null=\"true\" />" + "</d:ComplexValue1Value>" + "<d:ID m:type=\"Int64\">2</d:ID>" + "<d:MyColorCollection />" + "<d:MyColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyColor\">Yellow</d:MyColorValue>" + "<d:MyFlagsColorCollection1>" + "<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Blue</m:element>" + "<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Red</m:element>" + "<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Red</m:element>" + "</d:MyFlagsColorCollection1>" + "<d:MyFlagsColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyFlagsColor\">Blue</d:MyFlagsColorValue>" + "</m:properties>" + "</content>" + "</entry>"); }
protected void InitializeContext() { // create a memory barrier between initialize and disconnect to prevent a possible // NullRef with disconnect being called before these fields have been written // disconnect aquires this lock as well lock (_abortLock) { _thisHandle = GCHandle.Alloc(this); Method = GetVerb() ?? string.Empty; RawTarget = GetRawUrl() ?? string.Empty; // TODO version is slow. HttpVersion = GetVersion(); Scheme = SslStatus != SslStatus.Insecure ? Constants.HttpsScheme : Constants.HttpScheme; KnownMethod = VerbId; StatusCode = 200; var originalPath = GetOriginalPath(); if (KnownMethod == HttpApiTypes.HTTP_VERB.HttpVerbOPTIONS && string.Equals(RawTarget, "*", StringComparison.Ordinal)) { PathBase = string.Empty; Path = string.Empty; } else { // Path and pathbase are unescaped by RequestUriBuilder // The UsePathBase middleware will modify the pathbase and path correctly PathBase = string.Empty; Path = originalPath ?? string.Empty; } var cookedUrl = GetCookedUrl(); QueryString = cookedUrl.GetQueryString() ?? string.Empty; RequestHeaders = new RequestHeaders(this); HttpResponseHeaders = new HeaderCollection(); ResponseHeaders = HttpResponseHeaders; // Request headers can be modified by the app, read these first. RequestCanHaveBody = CheckRequestCanHaveBody(); if (_options.ForwardWindowsAuthentication) { WindowsUser = GetWindowsPrincipal(); if (_options.AutomaticAuthentication) { User = WindowsUser; } } MaxRequestBodySize = _options.MaxRequestBodySize; ResetFeatureCollection(); if (!_server.IsWebSocketAvailable(_requestNativeHandle)) { _currentIHttpUpgradeFeature = null; } _streams = new Streams(this); (RequestBody, ResponseBody) = _streams.Start(); var pipe = new Pipe( new PipeOptions( _memoryPool, readerScheduler: PipeScheduler.ThreadPool, pauseWriterThreshold: PauseWriterThreshold, resumeWriterThreshold: ResumeWriterTheshold, minimumSegmentSize: MinAllocBufferSize)); _bodyOutput = new OutputProducer(pipe); } NativeMethods.HttpSetManagedContext(_requestNativeHandle, (IntPtr)_thisHandle); }
internal MultipartRequestPartSentEventArgs(SessionEventArgs session, string boundary, HeaderCollection headers) : base(session.Server, session.ClientConnection) { Session = session; Boundary = boundary; Headers = headers; }
public static IEnumerable <HttpHeader> ExtractHeader(HeaderCollection headers, string headerName) { return(headers.ToArray().Where(t => t.Name == headerName)); }
/// <summary> /// Sets the value of the Accept header for a stream request (will set it to '*/*'). /// </summary> /// <param name="headers">The headers to modify.</param> internal void SetRequestAcceptHeaderForStream(HeaderCollection headers) { this.SetAcceptHeaderAndCharset(headers, XmlConstants.MimeAny); }
/// <summary>Initializes a new instance of the <see cref="Microsoft.OData.Client.ChangeOperationResponse" /> class. </summary> /// <param name="headers">HTTP headers</param> /// <param name="descriptor">response object containing information about resources that got changed.</param> internal ChangeOperationResponse(HeaderCollection headers, Descriptor descriptor) : base(headers) { Debug.Assert(descriptor != null, "descriptor != null"); this.descriptor = descriptor; }
/// <summary> /// Handles the form's Shown event. /// </summary> /// <param name="e">The even arguments.</param> protected override void OnShown(EventArgs e) { base.OnShown(e); try { _client.Progress += _client_Progress; // Create a new memory stream to store the downloaded message. MemoryStream mem = new MemoryStream(); // Get message data to the newly created memory stream. _client.DownloadMessage(_sequenceId, mem); // Create a new message from the memory stream. mem.Seek(0, SeekOrigin.Begin); // Get raw data; byte[] rawData = mem.ToArray(); _msg = new MailMessage(mem); // Fill from, to, cc. txtFrom.Text = _msg.From.ToString(); txtTo.Text = _msg.To.ToString(); txtCc.Text = _msg.Cc.ToString(); // Fill subject. txtSubject.Text = _msg.Subject; saveAsToolStripMenuItem.Enabled = true; copyToolStripMenuItem.Enabled = true; selectAllToolStripMenuItem.Enabled = true; Util.EnableCloseButton(this, true); // Fill the attachment list. if (_msg.Attachments.Count > 0) { foreach (Attachment at in _msg.Attachments) { cbxAttachment.Items.Add(at.FileName); } } if (cbxAttachment.Items.Count > 0) { cbxAttachment.SelectedIndex = 0; saveAttachmentsToolStripMenuItem.Enabled = true; } else { cbxAttachment.Enabled = false; saveAttachmentsToolStripMenuItem.Enabled = false; } // Fill body plain text version. txtBody.Text = _msg.BodyText.Replace("\n", "\r\n"); // Fill body HTML version. txtHtml.Text = _msg.BodyHtml.Replace("\n", "\r\n"); HeaderCollection headers = _msg.Headers; // Show all message header for (int i = 0; i < headers.Count; i++) { Header header = headers[i]; // add name column ListViewItem item = new ListViewItem(header.Name); // add header raw content column item.SubItems.Add(header.Raw); // show unparsed (corrupted) headers in red if (header.Unparsable) { item.ForeColor = System.Drawing.Color.Red; } // add row to the ListView lvwHeaders.Items.Add(item); } // Fill raw message. string rawtext = System.Text.Encoding.Default.GetString(rawData, 0, Math.Min(rawData.Length, 500000)); txtRawText.Text = rawtext; } catch (Exception exc) { if (!_abort) { Util.ShowError(exc); } else { this.DialogResult = DialogResult.Abort; } this.Close(); } finally { // Unregister the Progress event handler. _client.Progress -= _client_Progress; toolStripProgressLabel.Visible = false; toolStripProgressBar.Visible = false; toolStripProgressCancelButton.Visible = false; toolStripStatusLabel.Visible = true; } }
/// <summary> /// Sets the value of the Accept header for a count request (will set it to 'text/plain'). /// </summary> /// <param name="headers">The headers to modify.</param> internal void SetRequestAcceptHeaderForCount(HeaderCollection headers) { this.SetAcceptHeaderAndCharset(headers, XmlConstants.MimeTextPlain); }
/// <summary> /// Initializes a new instance of the <see cref = "PostmarkMessage" /> class. /// </summary> public PostmarkMessageBase() { Headers = new HeaderCollection(); Attachments = new List <PostmarkMessageAttachment>(0); }
/// <summary> /// Sets the value of the Accept header for a batch request /// Will set it to 'multipart/mixed' for a multipart batch request /// Will set it to 'application/json' for a json batch request /// </summary> /// <param name="headers">The headers to modify.</param> internal void SetRequestAcceptHeaderForBatch(HeaderCollection headers) { bool useJsonBatch = headers.GetHeader(XmlConstants.HttpContentType).Equals(MimeApplicationJson, StringComparison.Ordinal); this.SetAcceptHeaderAndCharset(headers, useJsonBatch ? MimeApplicationJson : MimeMultiPartMixed); }
internal RequestBuilder() { Headers = new HeaderCollection(); }
/// <summary> /// Sets the value of the Content-Type header a request with operation parameters to the appropriate value for the current format. /// </summary> /// <param name="headers">Dictionary of request headers.</param> internal void SetRequestContentTypeForOperationParameters(HeaderCollection headers) { // Note: There has never been an atom or xml format for parameters. this.SetRequestContentTypeHeader(headers, MimeApplicationJsonODataLight); }
public Response(long handle) { this.handle = handle; Headers = new HeaderCollection(handle); }
/// <summary> /// Sets the value of the ContentType header on the specified links request to the appropriate value for the current format. /// </summary> /// <param name="headers">Dictionary of request headers.</param> internal void SetRequestContentTypeForLinks(HeaderCollection headers) { this.SetRequestContentTypeHeader(headers, ChooseMediaType(false)); }
/// <summary> /// Initializes a new instance of <see cref="Commit"/>. /// </summary> /// <param name="id">The unique commit id.</param> /// <param name="timestamp">The <see cref="DateTime"/> when the snapshot was persisted.</param> /// <param name="correlationId">The correlation id.</param> /// <param name="streamId">The event stream id.</param> /// <param name="version">The event stream revision.</param> /// <param name="headers">The optional set of headers associated with this commit.</param> /// <param name="events">The optional set of events associated with this commit.</param> internal Commit(Int64?id, DateTime timestamp, Guid correlationId, Guid streamId, Int32 version, HeaderCollection headers, EventCollection events) { Verify.NotEqual(Guid.Empty, correlationId, nameof(correlationId)); Verify.NotEqual(Guid.Empty, streamId, nameof(streamId)); Verify.GreaterThan(0, version, nameof(version)); Id = id; Timestamp = timestamp; CorrelationId = correlationId; StreamId = streamId; Version = version; Events = events ?? EventCollection.Empty; Headers = headers ?? HeaderCollection.Empty; }
/// <summary> /// Initializes a new instance of <see cref="Commit"/>. /// </summary> /// <param name="correlationId">The correlation id.</param> /// <param name="streamId">The event stream id.</param> /// <param name="version">The event stream revision.</param> /// <param name="headers">The optional set of headers associated with this commit.</param> /// <param name="events">The optional set of events associated with this commit.</param> public Commit(Guid correlationId, Guid streamId, Int32 version, HeaderCollection headers, EventCollection events) : this(null, SystemTime.Now, correlationId, streamId, version, headers, events) { }
/// <summary> /// Notification for column header-related DependencyProperty changes from the grid or from columns. /// </summary> internal void NotifyPropertyChanged(DependencyObject d, string propertyName, DependencyPropertyChangedEventArgs e, DataGridNotificationTarget target) { DataGridColumn column = d as DataGridColumn; if (DataGridHelper.ShouldNotifyColumnHeadersPresenter(target)) { if (e.Property == DataGridColumn.WidthProperty || e.Property == DataGridColumn.DisplayIndexProperty) { if (column.IsVisible) { InvalidateDataGridCellsPanelMeasureAndArrange(); } } else if (e.Property == DataGrid.FrozenColumnCountProperty || e.Property == DataGridColumn.VisibilityProperty || e.Property == DataGrid.CellsPanelHorizontalOffsetProperty || string.Compare(propertyName, "ViewportWidth", StringComparison.Ordinal) == 0 || string.Compare(propertyName, "DelayedColumnWidthComputation", StringComparison.Ordinal) == 0) { InvalidateDataGridCellsPanelMeasureAndArrange(); } else if (e.Property == DataGrid.HorizontalScrollOffsetProperty) { InvalidateArrange(); InvalidateDataGridCellsPanelMeasureAndArrange(); } else if (string.Compare(propertyName, "RealizedColumnsBlockListForNonVirtualizedRows", StringComparison.Ordinal) == 0) { InvalidateDataGridCellsPanelMeasureAndArrange(/* withColumnVirtualization */ false); } else if (string.Compare(propertyName, "RealizedColumnsBlockListForVirtualizedRows", StringComparison.Ordinal) == 0) { InvalidateDataGridCellsPanelMeasureAndArrange(/* withColumnVirtualization */ true); } else if (e.Property == DataGrid.CellsPanelActualWidthProperty) { InvalidateArrange(); } else if (e.Property == DataGrid.EnableColumnVirtualizationProperty) { DataGridHelper.TransferProperty(this, VirtualizingPanel.IsVirtualizingProperty); } } if (DataGridHelper.ShouldNotifyColumnHeaders(target)) { if (e.Property == DataGridColumn.HeaderProperty) { if (HeaderCollection != null) { HeaderCollection.NotifyHeaderPropertyChanged(column, e); } } else { // Notify the DataGridColumnHeader objects about property changes ContainerTracking <DataGridColumnHeader> tracker = _headerTrackingRoot; while (tracker != null) { tracker.Container.NotifyPropertyChanged(d, e); tracker = tracker.Next; } // Handle Style & Height change notification for PART_FillerColumnHeader. if (d is DataGrid && (e.Property == DataGrid.ColumnHeaderStyleProperty || e.Property == DataGrid.ColumnHeaderHeightProperty)) { DataGridColumnHeader fillerColumnHeader = GetTemplateChild(ElementFillerColumnHeader) as DataGridColumnHeader; if (fillerColumnHeader != null) { fillerColumnHeader.NotifyPropertyChanged(d, e); } } } } }
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- public static async Task <TResult> TryDelete <TResult>(this Uri url, Func <WebResponse, CancellationToken, Task <TResult> > handler, string payload, HeaderCollection headers, Encoding encoding, CancellationToken token = default) => await url.TryDelete(handler, encoding.GetBytes(payload).AsMemory(), headers, token);