private static void AddRequestHeaders(EndpointConfig config, RequestSettings settings, HttpClient client, params object[] obj) { var requestHeaders = new HeaderCollection(); if (settings.GlobalHeaders != null && settings.GlobalHeaders.Count > 1) { requestHeaders.Add(settings.GlobalHeaders); } if (settings.AuthenticationProvider != null) { var authHeaderTask = settings.AuthenticationProvider.GetAuthorizationHeader(); Task.WhenAll(authHeaderTask); if (authHeaderTask.Result != null) { requestHeaders.Add(authHeaderTask.Result.Item1, authHeaderTask.Result.Item2); } } requestHeaders.Add(config.GetRequestHeaders(obj)); foreach (var h in requestHeaders.GetHeaders()) { client.DefaultRequestHeaders.Add(h.Item1, h.Item2); } }
public HTTPResponse(StatusCode status) { this.Status = status; Headers = new HeaderCollection(); Headers.Add("Server", "My web server"); Headers.Add("Date", $"{DateTime.UtcNow:r}"); }
public void HeaderCollection_Supports_MultipleHeaders() { var hc = new HeaderCollection(); hc.Add("Header1", "foo"); hc.Add("Header2", "bar"); var headers = hc.GetHeaders(); headers.Should().HaveCount(2); }
public void it_should_serialize_the_headers_to_its_string_representation() { HeaderCollection headers = new HeaderCollection(); headers.Add(new Header("Header1", new[] { new HeaderValue("Value1", new HeaderParameter("Parameter1", "ParameterValue1")) })); headers.Add(new Header("Header2", new[] { new HeaderValue("Value2", new HeaderParameter("Parameter2", "ParameterValue2")) })); string expected = String.Format("{0}\r\n{1}\r\n\r\n", headers["Header1"], headers["Header2"]); headers.ToString().Should().Be(expected); }
public void it_should_add_a_header() { HeaderCollection headers = new HeaderCollection(); headers.Add(new Header("Header1", new List <HeaderValue>(new[] { new HeaderValue("Value1", new HeaderParameter("Parameter1", "ParameterValue1")) }))); headers.Add("Header1", "Value2"); headers.Count.Should().Be(1); headers["Header1"].Values.Count.Should().Be(2); headers["Header1"].Values.First().Parameters.Count.Should().Be(1); }
public void HeaderCollection_Combines_DuplicateHeaders() { var hc = new HeaderCollection(); hc.Add("TestHeader", "foo"); hc.Add("TestHeader", "bar"); var headers = hc.GetHeaders(); headers.Should().HaveCount(1); headers.First().Item2.Should().BeEquivalentTo("foo;bar"); }
public void HeaderCollection_HeaderKey_IsCaseInsensitive() { var hc = new HeaderCollection(); hc.Add("Testheader", "foo"); hc.Add("testheader", "bar"); hc.Add("tEsThEaDeR", "snafu"); var headers = hc.GetHeaders(); headers.Should().HaveCount(1); headers.First().Item2.Should().BeEquivalentTo("foo;bar;snafu"); }
public IResponseResult <Application> WhoAmI(BasicToken basicToken) { var url = $"{this.BaseUrl}/whoami"; var headers = HeaderCollection.Add("Authorization", basicToken.ToString()); return(this.ExecuteRequest <Application>(HttpMethod.Get, url, null, headers)); }
public async Task <IResponseResult <CollectionResponseData <EventLog> > > GetEventsAsync(string accessToken, int?skip = null, int?limit = null) { IQueryString queryString = null; if (skip != null) { queryString = QueryString.Add("skip", skip.Value); } if (limit != null) { queryString = queryString == null?QueryString.Add("limit", limit.Value) : queryString.Add("limit", limit.Value); } var response = await this.EventsEndpoint.PostAsync( urlParams : new EventsEndpoint.EventsEndpointUrlParams().SetMembershipId(this.MembershipId).UseMongoQuery(), body : new RequestBody(), queryString : queryString, headers : HeaderCollection.Add("Authorization", $"Bearer {accessToken}")); if (response.IsSuccess) { string json = response.Data.ToString(); var root = Newtonsoft.Json.JsonConvert.DeserializeObject(json); if (root is JObject rootNode) { var dataNode = rootNode["data"]; var items = dataNode?["items"]; int.TryParse(dataNode?["count"].ToString(), out int totalCount); if (items is JArray itemsArray) { List <EventLog> eventList = new List <EventLog>(); foreach (var jsonToken in itemsArray) { var eventItem = this.DeserializeEvent(jsonToken); if (eventItem != null) { eventList.Add(eventItem); } } return(new ResponseResult <CollectionResponseData <EventLog> >(true) { Data = new CollectionResponseData <EventLog> { Items = eventList, Count = totalCount } }); } } return(new ResponseResult <CollectionResponseData <EventLog> >(false, "Events coul not deserialized!")); } else { return(new ResponseResult <CollectionResponseData <EventLog> >(false, response.Message)); } }
public async Task <IResponseResult <EventLog> > GetEventAsync(string accessToken, string eventId) { var response = await this.EventsEndpoint.GetAsync( urlParams : new EventsEndpoint.EventsEndpointUrlParams().SetMembershipId(this.MembershipId).SetEventId(eventId), headers : HeaderCollection.Add("Authorization", $"Bearer {accessToken}")); if (response.IsSuccess) { string json = response.Data.ToString(); var root = Newtonsoft.Json.JsonConvert.DeserializeObject(json); if (root is JObject rootNode) { var eventItem = this.DeserializeEvent(rootNode); if (eventItem != null) { return(new ResponseResult <EventLog>(true) { Data = eventItem }); } } return(new ResponseResult <EventLog>(false, "Response could not deserialized!")); } else { return(new ResponseResult <EventLog>(false, response.Message)); } }
public async void SendEmail(string to) { var mailHeader = new MailHeader("X-CUSTOM-HEADER", "Header content"); var headers = new HeaderCollection(); headers.Add(mailHeader); var message = new PostmarkMessage() { To = to, From = "*****@*****.**", TrackOpens = true, Subject = "A complex email", TextBody = "Plain Text Body", HtmlBody = "<html><body><img src=\"cid:embed_name.jpg\"/></body></html>", Tag = "New Year's Email Campaign", Headers = headers }; var imageContent = File.ReadAllBytes("test.jpg"); message.AddAttachment(imageContent, "test.jpg", "image/jpg", "cid:embed_name.jpg"); var client = new PostmarkClient("6cce5c93-a59e-4f32-b37d-c71525956b6b"); var sendResult = await client.SendMessageAsync(message); if (sendResult.Status == PostmarkStatus.Success) /* Handle success */ } {
public async Task <IResponseResult <BearerToken> > GetTokenAsync(string username, string password, string ipAddress = null, string userAgent = null) { var url = $"{this.BaseUrl}/generate-token"; var headers = HeaderCollection.Add("X-Ertis-Alias", this.MembershipId); if (!string.IsNullOrEmpty(ipAddress)) { headers.Add("X-IpAddress", ipAddress); } if (!string.IsNullOrEmpty(userAgent)) { headers.Add("X-UserAgent", userAgent); } var body = new { username, password }; var response = await this.ExecuteRequestAsync(HttpMethod.Post, url, null, headers, new JsonRequestBody(body)); return(ConvertToBearerTokenResponse(response)); }
/// <summary> /// Extract per-recipient dsn headers as a collection /// Fields are formatted just like MIME headers, but embedded within the Body of MimeEntity instead /// </summary> /// <param name="fieldEntity">Source entity</param> /// <returns>Collection of <see cref="HeaderCollection"/></returns> public static List <HeaderCollection> ParsePerRecientFields(MimeEntity fieldEntity) { if (fieldEntity == null) { throw new ArgumentNullException("fieldEntity"); } Body dsnBody = fieldEntity.Body; if (dsnBody == null) { throw new DSNException(DSNError.InvalidDSNBody); } HeaderCollection dsnFields = new HeaderCollection(); try { dsnFields.Add(new HeaderCollection(MimeSerializer.Default.DeserializeHeaders(dsnBody.PerRecipientSeperator())) , PerRecipientFieldList()); } catch (Exception ex) { throw new DSNException(DSNError.InvalidDSNFields, ex); } if (dsnFields.IsNullOrEmpty()) { throw new DSNException(DSNError.InvalidDSNFields); } return(PerRecipientList(dsnFields)); }
public async Task <IResponseResult <User> > CreateUserAsync(RegistrationForm userForm, string accessToken) { var response = await this.UsersEndpoint.PostAsync <User>( body : new RequestBody(userForm), urlParams : new UsersEndpoint.UsersEndpointUrlParams() .SetMembershipId(this.MembershipId), headers : HeaderCollection.Add("Authorization", $"Bearer {accessToken}")); if (response.IsSuccess) { return(new ResponseResult <User>(true) { Data = response.Data }); } else { if (response.HttpCode != null) { return(new ResponseResult <User>(response.HttpCode.Value, response.Message)); } else { return(new ResponseResult <User>(false, response.Message)); } } }
public async Task <IResponseResult <BearerToken> > RefreshTokenAsync(string refreshToken) { var url = $"{this.AuthApiBaseUrl}/refresh-token"; var headers = HeaderCollection.Add("Authorization", $"Bearer {refreshToken}"); return(await this.ExecuteRequestAsync <BearerToken>(HttpMethod.Get, url, null, headers)); }
public void AddFilteredByHeaderStringsThrowsArgumentNullException() { var headers = new HeaderCollection(); var ex = Assert.Throws <ArgumentNullException>(() => headers.Add(null, header => true)); Assert.Equal("source", ex.ParamName); }
/// <summary> /// Add a new header. /// </summary> /// <param name="name"></param> /// <param name="value"></param> public void Add(string name, IHeader value) { string lowerName = name.ToLower(); if (lowerName == "host") { var header = (StringHeader)value; string method = HttpContext.Current.IsSecure ? "https://" : "http://"; Uri = new Uri(method + header.Value + Uri.PathAndQuery); return; } if (lowerName == "content-length") { ContentLength = (NumericHeader)value; } if (lowerName == "content-type") { ContentType = (ContentTypeHeader)value; string charset = ContentType.Parameters["charset"]; if (!string.IsNullOrEmpty(charset)) { Encoding = Encoding.GetEncoding(charset); } } if (lowerName == "cookie") { Cookies = ((CookieHeader)value).Cookies; } _headers.Add(name, value); }
public async Task <IResponseResult <Application> > GetApplicationAsync(string applicationId, string accessToken) { var response = await this.ApplicationsEndpoint.GetAsync <Application>( new ApplicationsEndpoint.ApplicationsEndpointUrlParams() .SetMembershipId(this.MembershipId) .SetApplicationId(applicationId), headers : HeaderCollection.Add("Authorization", $"Bearer {accessToken}")); if (response.IsSuccess) { return(new ResponseResult <Application>(true) { Data = response.Data }); } else { if (response.HttpCode != null) { return(new ResponseResult <Application>(response.HttpCode.Value, response.Message)); } else { return(new ResponseResult <Application>(false, response.Message)); } } }
public async Task <IResponseResult <CollectionResponseData <Application> > > GetApplicationsAsync(string accessToken, int?skip, int?limit) { IQueryString queryString = null; if (skip != null) { queryString = QueryString.Add("skip", skip.Value); } if (limit != null) { queryString = queryString == null?QueryString.Add("limit", limit.Value) : queryString.Add("limit", limit.Value); } var response = await this.ApplicationsEndpoint.PostAsync <CollectionResponse <Application> >( urlParams : new ApplicationsEndpoint.ApplicationsEndpointUrlParams().SetMembershipId(this.MembershipId).UseMongoQuery(), body : new RequestBody(), queryString : queryString, headers : HeaderCollection.Add("Authorization", $"Bearer {accessToken}")); if (response.IsSuccess) { return(new ResponseResult <CollectionResponseData <Application> >(true) { Data = response.Data.Data }); } else { return(new ResponseResult <CollectionResponseData <Application> >(false, response.Message)); } }
public static HeaderCollection ToHeaderCollection(this IHeaderDictionary headers) { if (headers == null) { throw new ArgumentNullException(nameof(headers)); } HttpHeaderType headerType; if (headers.ContainsKey(HeaderCollection.ResponseCookieHeaderName)) { headerType = HttpHeaderType.ResponseHeader; } else { headerType = HttpHeaderType.RequestHeader; } var hc = new HeaderCollection(headerType); foreach (var kv in headers) { hc.Add(kv.Key, kv.Value.ToArray()); } return(hc); }
internal void EncodeHeaders(HeaderCollection headers) { if (this.headersEncoding == null) { this.headersEncoding = Encoding.GetEncoding("utf-8"); } for (int i = 0; i < headers.Count; i++) { string key = headers.GetKey(i); if (MailHeaderInfo.IsUserSettable(key)) { string[] values = headers.GetValues(key); string str2 = string.Empty; for (int j = 0; j < values.Length; j++) { if (MimeBasePart.IsAscii(values[j], false)) { str2 = values[j]; } else { str2 = MimeBasePart.EncodeHeaderValue(values[j], this.headersEncoding, MimeBasePart.ShouldUseBase64Encoding(this.headersEncoding), key.Length); } if (j == 0) { headers.Set(key, str2); } else { headers.Add(key, str2); } } } } }
public IResponseResult <BearerToken> RefreshToken(BearerToken bearerToken) { var url = $"{this.AuthApiBaseUrl}/refresh-token"; var headers = HeaderCollection.Add("Authorization", bearerToken.RefreshToken); return(this.ExecuteRequest <BearerToken>(HttpMethod.Get, url, null, headers)); }
public void AddThrowsArgumentNullException2() { var headers = new HeaderCollection(); var ex = Assert.Throws <ArgumentNullException>(() => headers.Add(null, new string[0])); Assert.Equal("source", ex.ParamName); }
public IResponseResult <User> WhoAmI(BearerToken bearerToken) { var url = $"{this.AuthApiBaseUrl}/whoami"; var headers = HeaderCollection.Add("Authorization", bearerToken.ToString()); return(this.ExecuteRequest <User>(HttpMethod.Get, url, null, headers)); }
public async Task <IResponseResult <Application> > WhoAmIAsync(BasicToken basicToken) { var url = $"{this.AuthApiBaseUrl}/whoami"; var headers = HeaderCollection.Add("Authorization", basicToken.ToString()); return(await this.ExecuteRequestAsync <Application>(HttpMethod.Get, url, null, headers)); }
public IResponseResult RevokeToken(BearerToken token) { var url = $"{this.AuthApiBaseUrl}/revoke-token"; var headers = HeaderCollection.Add("Authorization", token.ToString()); return(this.ExecuteRequest <BearerToken>(HttpMethod.Get, url, null, headers)); }
private static bool TryParseMessage(string broadcastMessage, out HeaderCollection headers) { headers = null; if (string.IsNullOrEmpty(broadcastMessage)) { return(false); } string[] lines = broadcastMessage.Split(new string[] { "\r\n" }, StringSplitOptions.None); if (lines.Length < 7) { return(false); } else if (!string.Equals(lines[0], MessageRequestLine) || lines[lines.Length - 3].Length != 0 || lines[lines.Length - 2].Length != 0 || lines[lines.Length - 1].Length != 0) { return(false); } headers = new HeaderCollection(); for (int i = 1; i < lines.Length - 3; i++) { string line = lines[i]; int colonIndex = line.IndexOf(':'); if (colonIndex == -1 || colonIndex == (line.Length - 1) || line[colonIndex + 1] != ' ') { return(false); } string headerName = line.Substring(0, colonIndex); string headerValue = line.Substring(colonIndex + 2); headers.Add(headerName, headerValue); } return(true); }
public async Task <IResponseResult> DeleteUserAsync(string userId, string accessToken) { var response = await this.UsersEndpoint.DeleteAsync <User>( urlParams : new UsersEndpoint.UsersEndpointUrlParams() .SetMembershipId(this.MembershipId) .SetUserId(userId), headers : HeaderCollection.Add("Authorization", $"Bearer {accessToken}")); if (response.IsSuccess) { return(new ResponseResult(true) { Data = response.Data }); } else { if (response.HttpCode != null) { return(new ResponseResult(response.HttpCode.Value, response.Message)); } else { return(new ResponseResult(false, response.Message)); } } }
public async Task<IResponseResult<IPaginationCollection<T>>> GetAsync( TokenBase token, int? skip = null, int? limit = null, bool? withCount = null, string orderBy = null, SortDirection? sortDirection = null, string searchKeyword = null) { if (string.IsNullOrEmpty(searchKeyword) || string.IsNullOrEmpty(searchKeyword.Trim())) { return await this.ExecuteRequestAsync<PaginationCollection<T>>( HttpMethod.Get, $"{this.BaseUrl}/memberships/{this.MembershipId}/{this.Slug}", QueryStringHelper.GetQueryString(skip, limit, withCount, orderBy, sortDirection), HeaderCollection.Add("Authorization", token.ToString())); } else { return await this.ExecuteRequestAsync<PaginationCollection<T>>( HttpMethod.Get, $"{this.BaseUrl}/memberships/{this.MembershipId}/{this.Slug}/search", QueryStringHelper.GetQueryString(skip, limit, withCount, orderBy, sortDirection).Add("keyword", searchKeyword), HeaderCollection.Add("Authorization", token.ToString())); } }
public async Task <IResponseResult <BearerToken> > VerifyTokenAsync(BearerToken token) { var url = $"{this.AuthApiBaseUrl}/verify-token"; var headers = HeaderCollection.Add("Authorization", token.ToString()); return(await this.ExecuteRequestAsync <BearerToken>(HttpMethod.Get, url, null, headers)); }
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 void AddThrowsArgumentNullException2() { var headers = new HeaderCollection(); var ex = Assert.Throws<ArgumentNullException>(() => headers.Add(null, new string[0])); Assert.Equal("source", ex.ParamName); }
public void FilteredVersionOfAdd() { var a = new Header("a", "a"); var b = new Header("b", "b"); var aa = new Header("aa", "c"); Header[] headers = new Header[] { a, b, aa }; HeaderCollection coll = new HeaderCollection(); coll.Add(headers, h => h.Name.StartsWith("a")); Assert.True(coll.Contains(a)); Assert.True(coll.Contains(aa)); Assert.False(coll.Contains(b)); }
public void AddFilteredByHeaderStringsThrowsArgumentNullException() { var headers = new HeaderCollection(); var ex = Assert.Throws<ArgumentNullException>(() => headers.Add(null, header => true)); Assert.Equal("source", ex.ParamName); }
public void StringArrayFilteredVersionOfAdd() { var a = new Header("a", "a"); var b = new Header("b", "b"); var aa = new Header("aa", "c"); var headers = new Header[] { a, b, aa }; HeaderCollection coll = new HeaderCollection(); coll.Add(headers, new string[] { "a", "aa" }); Assert.True(coll.Contains(a)); Assert.True(coll.Contains(aa)); Assert.False(coll.Contains(b)); }
private IEnumerator<object> RequestTask(ListenerContext context, SocketDataAdapter adapter) { var startedWhen = DateTime.UtcNow; bool successful = false; try { const int headerBufferSize = 1024 * 32; const int bodyBufferSize = 1024 * 128; const double requestLineTimeout = 5; // RFC2616: // Words of *TEXT MAY contain characters from character sets other than ISO-8859-1 [22] // only when encoded according to the rules of RFC 2047 [14]. Encoding headerEncoding; try { headerEncoding = Encoding.GetEncoding("ISO-8859-1"); } catch { headerEncoding = Encoding.ASCII; } Request request; RequestBody body; HeaderCollection headers; long bodyBytesRead = 0; long? expectedBodyLength = null; var reader = new AsyncTextReader(adapter, headerEncoding, headerBufferSize, false); string requestLineText; while (true) { var fRequestLine = reader.ReadLine(); var fRequestOrTimeout = Scheduler.Start(new WaitWithTimeout(fRequestLine, requestLineTimeout)); yield return fRequestOrTimeout; if (fRequestOrTimeout.Failed) { if (!(fRequestOrTimeout.Error is TimeoutException)) OnRequestError(fRequestOrTimeout.Error); yield break; } if (fRequestLine.Failed) { if (!(fRequestLine.Error is SocketDisconnectedException)) OnRequestError(fRequestLine.Error); yield break; } requestLineText = fRequestLine.Result; // RFC2616: // In the interest of robustness, servers SHOULD ignore any empty line(s) received where a // Request-Line is expected. In other words, if the server is reading the protocol stream // at the beginning of a message and receives a CRLF first, it should ignore the CRLF. if ((requestLineText != null) && (requestLineText.Trim().Length == 0)) continue; break; } var requestLineParsed = DateTime.UtcNow; headers = new HeaderCollection(); while (true) { var fHeaderLine = reader.ReadLine(); yield return fHeaderLine; if (String.IsNullOrWhiteSpace(fHeaderLine.Result)) break; headers.Add(new Header(fHeaderLine.Result)); } var headersParsed = DateTime.UtcNow; var expectHeader = (headers.GetValue("Expect") ?? "").ToLowerInvariant(); var expectsContinue = expectHeader.Contains("100-continue"); string hostName; if (headers.Contains("Host")) { hostName = String.Format("http://{0}", headers["Host"].Value); } else { var lep = (IPEndPoint)adapter.Socket.LocalEndPoint; hostName = String.Format("http://{0}:{1}", lep.Address, lep.Port); } var requestLine = new RequestLine(hostName, requestLineText); var remainingBytes = reader.DisposeAndGetRemainingBytes(); bodyBytesRead += remainingBytes.Count; var connectionHeader = (headers.GetValue("Connection") ?? "").ToLowerInvariant(); var shouldKeepAlive = ((requestLine.Version == "1.1") || connectionHeader.Contains("keep-alive")) && !connectionHeader.Contains("close"); if (headers.Contains("Content-Length")) expectedBodyLength = long.Parse(headers["Content-Length"].Value); body = new RequestBody(remainingBytes, expectedBodyLength); if (expectsContinue) yield return adapter.Write(Continue100, 0, Continue100.Length); request = new Request( this, adapter, shouldKeepAlive, requestLine, headers, body ); IncomingRequests.Enqueue(request); var requestEnqueued = DateTime.UtcNow; DateTime? requestBodyRead = null; // FIXME: I think it's technically accepted to send a body without a content-length, but // it seems to be impossible to make that work right. if (expectedBodyLength.HasValue) { using (var bodyBuffer = BufferPool<byte>.Allocate(bodyBufferSize)) while (bodyBytesRead < expectedBodyLength.Value) { long bytesToRead = Math.Min(expectedBodyLength.Value - bodyBytesRead, bodyBufferSize); if (bytesToRead <= 0) break; var fBytesRead = adapter.Read(bodyBuffer.Data, 0, (int)bytesToRead); yield return fBytesRead; if (fBytesRead.Failed) { if (fBytesRead.Error is SocketDisconnectedException) break; body.Failed(fBytesRead.Error); OnRequestError(fBytesRead.Error); yield break; } var bytesRead = fBytesRead.Result; bodyBytesRead += bytesRead; body.Append(bodyBuffer.Data, 0, bytesRead); } requestBodyRead = DateTime.UtcNow; } body.Finish(); successful = true; request.Timing = new Request.TimingData { Line = (requestLineParsed - startedWhen), Headers = (headersParsed - requestLineParsed), Queue = (requestEnqueued - headersParsed), Body = (requestBodyRead - requestEnqueued) }; } finally { if (!successful) adapter.Dispose(); } }
public IEnumerable<IDocumentPart> Parse (Lexer lexer) { bool have_parsed_headers = false; foreach (var unit in ParseUnits (lexer)) { if (have_parsed_headers) { yield return unit; continue; } var is_header_message = false; foreach (var message in unit.Messages) { if (!message.HasValue) { break; } else if (message.Type == MessageType.SingularIdentifier && message.Value == String.Empty) { is_header_message = true; } else if (message.Type == MessageType.SingularString && is_header_message) { var headers = new HeaderCollection (); foreach (var header in ParseHeaders (message)) { have_parsed_headers = true; headers.Add (header); } if (have_parsed_headers) { yield return headers; } else { yield return unit; } break; } } } }