/// <summary> /// Initializes a new instance of the <see cref="Configuration" /> class. /// </summary> /// <param name="uri">The URI used to connect to the remote EventSource API.</param> /// <param name="messageHandler">The message handler to use when sending API requests. If null, the <see cref="HttpClientHandler"/> is used.</param> /// <param name="connectionTimeOut">The connection timeout. If null, defaults to 10 seconds.</param> /// <param name="delayRetryDuration">The time to wait before attempting to reconnect to the EventSource API. If null, defaults to 1 second.</param> /// <param name="readTimeout">The timeout when reading data from the EventSource API. If null, defaults to 5 minutes.</param> /// <param name="requestHeaders">Request headers used when connecting to the remote EventSource API.</param> /// <param name="lastEventId">The last event identifier.</param> /// <param name="logger">The logger used for logging internal messages.</param> /// <param name="method">The HTTP method used to connect to the remote EventSource API.</param> /// <param name="requestBodyFactory">A function that produces an HTTP request body to send to the remote EventSource API.</param> /// <exception cref="ArgumentNullException">Throws ArgumentNullException if the uri parameter is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <p><paramref name="connectionTimeOut"/> is less than zero. </p> /// <p>- or - </p> /// <p><paramref name="delayRetryDuration"/> is greater than 30 seconds. </p> /// <p>- or - </p> /// <p><paramref name="readTimeout"/> is less than zero. </p> /// </exception> public Configuration(Uri uri, HttpMessageHandler messageHandler = null, TimeSpan?connectionTimeout = null, TimeSpan?delayRetryDuration = null, TimeSpan?readTimeout = null, IDictionary <string, string> requestHeaders = null, string lastEventId = null, ILog logger = null, HttpMethod method = null, HttpContentFactory requestBodyFactory = null, TimeSpan?backoffResetThreshold = null) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (connectionTimeout.HasValue) { CheckConnectionTimeout(connectionTimeout.Value); } if (delayRetryDuration.HasValue) { CheckDelayRetryDuration(delayRetryDuration.Value); } if (readTimeout.HasValue) { CheckReadTimeout(readTimeout.Value); } Uri = uri; MessageHandler = messageHandler; ConnectionTimeout = connectionTimeout ?? DefaultConnectionTimeout; DelayRetryDuration = delayRetryDuration ?? DefaultDelayRetryDuration; BackoffResetThreshold = backoffResetThreshold ?? DefaultBackoffResetThreshold; ReadTimeout = readTimeout ?? DefaultReadTimeout; RequestHeaders = requestHeaders; LastEventId = lastEventId; Logger = logger; Method = method; RequestBodyFactory = requestBodyFactory; }
private RESTCommand <NullType> SetServicePropertiesImpl(ServiceProperties properties, TableRequestOptions requestOptions) { MultiBufferMemoryStream memoryStream = new MultiBufferMemoryStream(null /* bufferManager */, (int)(1 * Constants.KB)); try { properties.WriteServiceProperties(memoryStream); } catch (InvalidOperationException invalidOpException) { throw new ArgumentException(invalidOpException.Message, "properties"); } RESTCommand <NullType> retCmd = new RESTCommand <NullType>(this.Credentials, this.StorageUri); requestOptions.ApplyToStorageCommand(retCmd); retCmd.BuildRequest = (cmd, uri, builder, cnt, serverTimeout, ctx) => TableHttpRequestMessageFactory.SetServiceProperties(uri, serverTimeout, cnt, ctx, this.GetCanonicalizer(), this.Credentials); retCmd.BuildContent = (cmd, ctx) => HttpContentFactory.BuildContentFromStream(memoryStream, 0, memoryStream.Length, null /* md5 */, cmd, ctx); retCmd.StreamToDispose = memoryStream; retCmd.PreProcessResponse = (cmd, resp, ex, ctx) => HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.Accepted, resp, null /* retVal */, cmd, ex); requestOptions.ApplyToStorageCommand(retCmd); return(retCmd); }
/// <summary> /// This writes the supplied content to the response of the httpListenerContext /// It's actually a bit overkill, as it convers to HttpContent and writes this to a stream /// But performance and memory usage are currently not our main concern for the HttpListener /// </summary> /// <typeparam name="TContent">Type of the content</typeparam> /// <param name="httpListenerContext">HttpListenerContext</param> /// <param name="content">TContent object</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>Task</returns> public static async Task RespondAsync <TContent>(this HttpListenerContext httpListenerContext, TContent content, CancellationToken cancellationToken = default) where TContent : class { HttpContent httpContent; if (typeof(HttpContent).IsAssignableFrom(typeof(TContent))) { httpContent = content as HttpContent; } else { httpContent = HttpContentFactory.Create(content); } using (var response = httpListenerContext.Response) { if (httpContent is null) { Log.Error().WriteLine("Nothing to respond with..."); response.StatusCode = (int)HttpStatusCode.InternalServerError; return; } // Write to response stream. response.ContentLength64 = httpContent.Headers?.ContentLength ?? 0; response.ContentType = httpContent.GetContentType(); response.StatusCode = (int)HttpStatusCode.OK; Log.Debug().WriteLine("Responding with {0}", response.ContentType); using (var stream = response.OutputStream) { await httpContent.CopyToAsync(stream).ConfigureAwait(false); } } }
private RESTCommand <NullType> SetServicePropertiesImpl(ServiceProperties properties, BlobRequestOptions requestOptions) { MemoryStream memoryStream = new MemoryStream(); try { properties.WriteServiceProperties(memoryStream); } catch (InvalidOperationException invalidOpException) { throw new ArgumentException(invalidOpException.Message, "properties"); } RESTCommand <NullType> retCmd = new RESTCommand <NullType>(this.Credentials, this.BaseUri); retCmd.ApplyRequestOptions(requestOptions); retCmd.BuildRequest = (cmd, cnt, ctx) => BlobHttpRequestMessageFactory.SetServiceProperties(cmd.Uri, cmd.ServerTimeoutInSeconds, cnt, ctx); retCmd.BuildContent = (cmd, ctx) => HttpContentFactory.BuildContentFromStream(memoryStream, 0, memoryStream.Length, null /* md5 */, cmd, ctx); retCmd.RetrieveResponseStream = true; retCmd.Handler = this.AuthenticationHandler; retCmd.BuildClient = HttpClientFactory.BuildHttpClient; retCmd.PreProcessResponse = (cmd, resp, ex, ctx) => HttpResponseParsers.ProcessExpectedStatusCodeNoException(System.Net.HttpStatusCode.Accepted, resp, null /* retVal */, cmd, ex, ctx); retCmd.ApplyRequestOptions(requestOptions); return(retCmd); }
public async Task Post_AuthorRequest_ResponseContainsExpectedAuthorDto() { // Arrange var expectedId = Guid.NewGuid(); var expectedAuthor = new Author { Id = expectedId, FirstName = $"Name{expectedId.ToString()}", LastName = "author last name", DateOfBirth = DateTime.Now }; var request = AuthorRequestFactory.Create(expectedAuthor.FirstName, expectedAuthor.LastName, expectedAuthor.DateOfBirth); A.CallTo(() => _authorRepositoryMock.CreateAsync(A <Author> .That.Matches(a => a.FirstName == expectedAuthor.FirstName))) .Returns(Task.FromResult(expectedAuthor)); using var content = HttpContentFactory.CreateStringContent(request); // Act using var response = await _client.PostAsync("api/authors", content); // Assert var authorResponse = await response.DeserializeToAsync <AuthorResponse>(); authorResponse.FirstName.Should().Be(expectedAuthor.FirstName); authorResponse.LastName.Should().Be(expectedAuthor.LastName); authorResponse.DateOfBirth.Should().Be(expectedAuthor.DateOfBirth); }
public async Task Post_AuthorRequest_StatusCodeIsCreated() { // Arrange var request = AuthorRequestFactory.Create("Mr", "Andersson", DateTime.Now); // Act using var content = HttpContentFactory.CreateStringContent(request); using var response = await _client.PostAsync("api/authors", content); // Assert response.StatusCode.Should().Be(HttpStatusCode.Created); }
/// <summary> /// Implementation for the SetPermissions method. /// </summary> /// <param name="acl">The permissions to set.</param> /// <param name="requestOptions">A <see cref="TableRequestOptions"/> object that specifies execution options, such as retry policy and timeout settings, for the operation.</param> /// <returns>A <see cref="RESTCommand"/> that sets the permissions.</returns> private RESTCommand <NullType> SetPermissionsImpl(TablePermissions acl, TableRequestOptions requestOptions) { MultiBufferMemoryStream memoryStream = new MultiBufferMemoryStream(null /* bufferManager */, (int)(1 * Constants.KB)); TableRequest.WriteSharedAccessIdentifiers(acl.SharedAccessPolicies, memoryStream); RESTCommand <NullType> putCmd = new RESTCommand <NullType>(this.ServiceClient.Credentials, this.Uri); putCmd.ApplyRequestOptions(requestOptions); putCmd.Handler = this.ServiceClient.AuthenticationHandler; putCmd.BuildClient = HttpClientFactory.BuildHttpClient; putCmd.BuildRequest = (cmd, cnt, ctx) => TableHttpRequestMessageFactory.SetAcl(cmd.Uri, cmd.ServerTimeoutInSeconds, cnt, ctx); putCmd.BuildContent = (cmd, ctx) => HttpContentFactory.BuildContentFromStream(memoryStream, 0, memoryStream.Length, null /* md5 */, cmd, ctx); putCmd.PreProcessResponse = (cmd, resp, ex, ctx) => { HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.NoContent, resp, NullType.Value, cmd, ex); return(NullType.Value); }; return(putCmd); }
public async Task Post_AuthorRequest_ResponseContainsCopyrightAndLocationHeaders() { // Arrange var expectedId = Guid.NewGuid(); var expectedLocation = $"{_baseUrl}/api/authors/{expectedId.ToString()}"; var request = AuthorRequestFactory.Create($"Name{expectedId.ToString()}", "Andersson", DateTime.Now); A.CallTo(() => _authorRepositoryMock.CreateAsync(A <Author> .That.Matches(a => a.FirstName == request.FirstName))) .Returns(Task.FromResult(new Author { Id = expectedId })); using var content = HttpContentFactory.CreateStringContent(request); // Act using var response = await _client.PostAsync("api/authors", content); // Assert response.Headers.Location.Should().Be(expectedLocation); response.Headers.GetValues(Constants.CopyrightHeader).ElementAt(0).Should().Be(Constants.CopyrightValue); }
/// <summary> /// Implementation for the SetPermissions method. /// </summary> /// <param name="acl">The permissions to set.</param> /// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the access conditions for the share. If <c>null</c>, no condition is used.</param> /// <param name="options">A <see cref="FileRequestOptions"/> object that specifies additional options for the request.</param> /// <returns>A <see cref="RESTCommand"/> that sets the permissions.</returns> private RESTCommand <NullType> SetPermissionsImpl(FileSharePermissions acl, AccessCondition accessCondition, FileRequestOptions options) { MultiBufferMemoryStream memoryStream = new MultiBufferMemoryStream(null /* bufferManager */, (int)(1 * Constants.KB)); FileRequest.WriteSharedAccessIdentifiers(acl.SharedAccessPolicies, memoryStream); RESTCommand <NullType> putCmd = new RESTCommand <NullType>(this.ServiceClient.Credentials, this.StorageUri); options.ApplyToStorageCommand(putCmd); putCmd.BuildRequest = (cmd, uri, builder, cnt, serverTimeout, ctx) => ShareHttpRequestMessageFactory.SetAcl(uri, serverTimeout, FileSharePublicAccessType.Off, accessCondition, cnt, ctx, this.ServiceClient.GetCanonicalizer(), this.ServiceClient.Credentials); putCmd.BuildContent = (cmd, ctx) => HttpContentFactory.BuildContentFromStream(memoryStream, 0, memoryStream.Length, null /* md5 */, cmd, ctx); putCmd.StreamToDispose = memoryStream; putCmd.PreProcessResponse = (cmd, resp, ex, ctx) => { HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.OK, resp, NullType.Value, cmd, ex); this.UpdateETagAndLastModified(resp); return(NullType.Value); }; return(putCmd); }
public async Task Post_AuthorRequest_AuthorIsAdded() { // Arrange var request = AuthorRequestFactory.Create("Mr", "Andersson", DateTime.Now); using var content = HttpContentFactory.CreateStringContent(request); // Act using var response = await _client.PostAsync("api/authors", content); // Assert response.StatusCode.Should().Be(HttpStatusCode.Created); var authorResponse = await response.DeserializeToAsync <AuthorResponse>(); authorResponse.FirstName.Should().Be(request.FirstName); authorResponse.LastName.Should().Be(request.LastName); authorResponse.DateOfBirth.Should().Be(request.DateOfBirth); response.Headers.Location.Should().Be($"{_baseUrl}/api/authors/{authorResponse.Id.ToString()}"); response.Headers.GetValues(Constants.CopyrightHeader).ElementAt(0).Should().Be(Constants.CopyrightValue); await EnsureAuthorIsCorrectOnDatabaseAsync(authorResponse); }
/// <summary> /// Link the WorkItem and the attachment that was created /// </summary> /// <param name="workItem">WorkItem</param> /// <param name="attachmentResult">CreateAttachmentResult</param> /// <param name="comment">string with optional comment</param> public async Task LinkAttachment(WorkItem workItem, CreateAttachmentResult attachmentResult, string comment = "Attached screenshot from Greenshot") { _tfsHttpBehaviour.MakeCurrent(); var client = HttpClientFactory.Create(_tfsConfiguration.TfsUri).SetBasicAuthorization("", _tfsConfiguration.ApiKey); Uri apiUri = _tfsConfiguration.TfsUri.AppendSegments("_apis").ExtendQuery("api-version", "3.0"); // https://docs.microsoft.com/en-us/rest/api/vsts/wit/work%20items/update#add_an_attachment var linkAttachmentUri = apiUri.AppendSegments("wit", "workItems", workItem.Id); var linkAttachmentRequest = new List <Operation> { new Operation { OperationType = "add", Path = "/relations/-", Value = new Value { Relation = "AttachedFile", Url = attachmentResult.Url, Attributes = new Attributes { Comment = comment } } } }; var content = HttpContentFactory.Create(linkAttachmentRequest); content.SetContentType("application/json-patch+json"); var result = await client.PatchAsync <HttpResponse <string, string> >(linkAttachmentUri, content).ConfigureAwait(false); if (result.HasError) { throw new Exception(result.ErrorResponse); } }
/// <summary> /// The OAuth code receiver /// </summary> /// <param name="authorizeMode">AuthorizeModes tells you which mode was used to call this</param> /// <param name="codeReceiverSettings"></param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>Dictionary with values</returns> public async Task <IDictionary <string, string> > ReceiveCodeAsync(AuthorizeModes authorizeMode, ICodeReceiverSettings codeReceiverSettings, CancellationToken cancellationToken = default(CancellationToken)) { Uri redirectUri; if (codeReceiverSettings.RedirectUrl == null) { redirectUri = new[] { 0 }.CreateLocalHostUri(); // TODO: This will create a problem that with the next "authorize" call it will try to use the same Url, while it might not work // But not setting it, will create a problem in the replacement codeReceiverSettings.RedirectUrl = redirectUri.AbsoluteUri; } else { if (!codeReceiverSettings.RedirectUrl.StartsWith("http:")) { var message = $"The LocalServerCodeReceiver only works for http URLs, not for {0}, use a different AuthorizeMode."; Log.Error().WriteLine(message); throw new ArgumentException(message, nameof(codeReceiverSettings.RedirectUrl)); } redirectUri = new Uri(codeReceiverSettings.RedirectUrl); } var listenTask = redirectUri.ListenAsync(async httpListenerContext => { // Process the request var httpListenerRequest = httpListenerContext.Request; Log.Debug().WriteLine("Got request {0}", httpListenerRequest.Url); // we got the result, parse the Query and set it as a result var result = httpListenerRequest.Url.QueryToDictionary(); try { var htmlContent = HttpContentFactory.Create(ClosePageResponse.Replace("CloudServiceName", codeReceiverSettings.CloudServiceName)); htmlContent.SetContentType(MediaTypes.Html.EnumValueOf()); await httpListenerContext.RespondAsync(htmlContent, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { Log.Error().WriteLine(ex, "Couldn't write a response"); } return(result); }, cancellationToken); // while the listener is beging starter in the "background", here we prepare opening the browser var uriBuilder = new UriBuilder(codeReceiverSettings.AuthorizationUri) { Query = codeReceiverSettings.AuthorizationUri.QueryToKeyValuePairs() .Select(x => new KeyValuePair <string, string>(x.Key, x.Value.FormatWith(codeReceiverSettings))) .ToQueryString() }; // Get the formatted FormattedAuthUrl var authorizationUrl = uriBuilder.Uri; Log.Debug().WriteLine("Opening a browser with: {0}", authorizationUrl.AbsoluteUri); // Open the url in the default browser Process.Start(authorizationUrl.AbsoluteUri); // Return result of the listening return(await listenTask.ConfigureAwait(false)); }
public void GetContentProccesserTest() { var proccesser = HttpContentFactory.GetContentProccesser("application/json"); Assert.IsTrue(proccesser is StringContentProccesser); }