private Request CreateClientSecretAuthRequest(string tenantId, string clientId, string clientSecret, string[] scopes) { Request request = _pipeline.CreateRequest(); request.Method = RequestMethod.Post; request.Headers.Add(HttpHeader.Common.FormUrlEncodedContentType); request.Uri.Reset(_options.AuthorityHost); request.Uri.AppendPath(tenantId); request.Uri.AppendPath("/oauth2/v2.0/token", escape: false); var bodyStr = $"response_type=token&grant_type=client_credentials&client_id={Uri.EscapeDataString(clientId)}&client_secret={Uri.EscapeDataString(clientSecret)}&scope={Uri.EscapeDataString(string.Join(" ", scopes))}"; ReadOnlyMemory <byte> content = Encoding.UTF8.GetBytes(bodyStr).AsMemory(); request.Content = RequestContent.Create(content); return(request); }
public async Task StreamRequestContentCanBeSentMultipleTimes() { var requests = new List <long?>(); using TestServer testServer = new TestServer(context => { requests.Add(context.Request.ContentLength); }); var transport = GetTransport(); Request request = transport.CreateRequest(); request.Method = RequestMethod.Post; request.Uri.Reset(testServer.Address); request.Content = RequestContent.Create(new MemoryStream(new byte[] { 1, 2, 3 })); await ExecuteRequest(request, transport); await ExecuteRequest(request, transport); Assert.AreEqual(new long [] { 3, 3 }, requests); }
public void FailedTransaction() { var client = InstrumentClient( new ConfidentialLedgerClient( new("https://client.name"), new MockCredential(), new ConfidentialLedgerClientOptions { Retry = { Delay = TimeSpan.Zero, MaxRetries = 0 }, Transport = new MockTransport( req => { if (req.Uri.Host == "identity.accledger.azure.com") { var cert = new MockResponse(200); cert.SetContent( @" { ""ledgerTlsCertificate"": ""-----BEGIN CERTIFICATE-----\nMIIBejCCASGgAwIBAgIRANPpW17pcDYr1KnqsJH5yC8wCgYIKoZIzj0EAwIwFjEU\nMBIGA1UEAwwLQ0NGIE5ldHdvcmswHhcNMjEwMzExMDAwMDAwWhcNMjMwNjExMjM1\nOTU5WjAWMRQwEgYDVQQDDAtDQ0YgTmV0d29yazBZMBMGByqGSM49AgEGCCqGSM49\nAwEHA0IABOCPGnfcmfm5Vyax3bvg5Xqg6RUZtda0U5qpmxqGgLfL3LYJd3heTPd\u002B\n51o29pMtKJGG4cWeZ3\u002BYbhZzHnetf8WjUDBOMAwGA1UdEwQFMAMBAf8wHQYDVR0O\nBBYEFFxq\u002BImyEVh4u4BfynwnEAsbvRJBMB8GA1UdIwQYMBaAFFxq\u002BImyEVh4u4Bf\nynwnEAsbvRJBMAoGCCqGSM49BAMCA0cAMEQCIC597R3C89/IzfqjkO31XKy4Rnfy\nXauWszBChtH1v2CoAiAS0tmFNjD3fweHH8O2ySXK/tPCBTq877pIjFGwvuj2uw==\n-----END CERTIFICATE-----\n\u0000"", ""ledgerId"": ""chrissconfidentialledger""}"); return(cert); } if (req.Uri.Path.Contains($"transactions/{transactionId}/status")) { var success = new MockResponse(500); success.SetContent("success"); return(success); } var failed = new MockResponse(200); failed.AddHeader("x-ms-ccf-transaction-id", transactionId); failed.SetContent("failed"); return(failed); }) })); var ex = Assert.ThrowsAsync <InvalidOperationException>( async() => await client.PostLedgerEntryAsync(RequestContent.Create(new { contents = "test" }), null, true, default)); Assert.That(ex.Message, Does.Contain(transactionId)); }
internal HttpMessage CreateTrackRequest(IEnumerable <TelemetryEnvelope> body) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.AppendRaw(endpoint, false); uri.AppendRaw("/v2", false); uri.AppendPath("/track", false); request.Uri = uri; request.Headers.Add("Content-Type", "application/json"); using var content = new NDJsonWriter(); foreach (var item in body) { content.JsonWriter.WriteObjectValue(item); content.WriteNewLine(); } request.Content = RequestContent.Create(content.ToBytes()); return(message); }
protected void CreateProject(string projectName = default) { if (projectName == default) { projectName = CreateTestProjectName(); } RequestContent creationRequestContent = RequestContent.Create( new { description = "This is the description for a test project", language = "en", multilingualResource = false, settings = new { defaultAnswer = "No answer found for your question." } } ); Client.CreateProject(projectName, creationRequestContent); }
public async Task ScanOperations() { string dataSourceName = "test-datasource1009"; string scanName = "test-scan1009-2"; var client = GetPurviewScanClient(dataSourceName, scanName); //Create var data = new { name = scanName, kind = "AmazonS3Credential", properties = new { credential = new { referenceName = "test-credential1009", credentialType = "AmazonARN" }, collection = new { type = "CollectionReference", referenceName = "dotnetllcpurviewaccount" } } }; Response createResponse = await client.CreateOrUpdateAsync(RequestContent.Create(data)); Assert.AreEqual(201, createResponse.Status); //Get Response getResponse = await client.GetPropertiesAsync(new()); Assert.AreEqual(200, getResponse.Status); JsonElement getBodyJson = JsonDocument.Parse(GetContentFromResponse(getResponse)).RootElement; Assert.AreEqual("datasources/test-datasource1009/scans/test-scan1009-2", getBodyJson.GetProperty("id").GetString()); //Delete Response deleteResponse = await client.DeleteAsync(); Assert.AreEqual(200, deleteResponse.Status); }
protected async Task <Response> CreateProjectAsync(string projectName = default) { if (projectName == default) { projectName = CreateTestProjectName(); } RequestContent creationRequestContent = RequestContent.Create( new { description = "This is the description for a test project", language = "en", multilingualResource = false, settings = new { defaultAnswer = "No answer found for your question." } } ); return(await Client.CreateProjectAsync(projectName, creationRequestContent)); }
public virtual async Task <Response> CreateOrUpdateAsync(string seasonId, RequestContent content, RequestOptions options = null) #pragma warning restore AZC0002 { options ??= new RequestOptions(); HttpMessage message = CreateCreateOrUpdateRequest(seasonId, content, options); if (options.PerCallPolicy != null) { message.SetProperty("RequestOptionsPerCallPolicyCallback", options.PerCallPolicy); } using var scope = _clientDiagnostics.CreateScope("SeasonsClient.CreateOrUpdate"); scope.Start(); try { await Pipeline.SendAsync(message, options.CancellationToken).ConfigureAwait(false); if (options.StatusOption == ResponseStatusOption.Default) { switch (message.Response.Status) { case 200: case 201: return(message.Response); default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } else { return(message.Response); } } catch (Exception e) { scope.Failed(e); throw; } }
public Task <IEnumerable <ResponseContent> > HandleIncomingRequestAsync(RequestContent request) { List <ResponseContent> responseContents = new List <ResponseContent>(); var rankingArgs = (BitConverter.ToUInt16(request.Data, 0).Swap()); if (rankingArgs == 0) // get the first ranking page { var rankCategoryList = _rankingManagementService.GetRankingCategory(); responseContents.Add(request.CreateResponse(0x7833, BitConverter.GetBytes(((ushort)rankCategoryList.Count).Swap()))); foreach (var category in rankCategoryList) { responseContents.Add(request.CreateResponse(0x7835, category)); } } else if (rankingArgs >= 8) // get class List { request.Client._rankingCategoryID = rankingArgs; var rankClassList = Extensions.GetClassList(); responseContents.Add(request.CreateResponse(0x7833, BitConverter.GetBytes(((ushort)rankClassList.Count).Swap()))); foreach (var category in rankClassList) { responseContents.Add(request.CreateResponse(0x7835, category)); } } else { var playerRankingList = _rankingManagementService.GetPlayerRanking(request.Client._rankingCategoryID, rankingArgs); responseContents.Add(request.CreateResponse(0x7836, BitConverter.GetBytes(((uint)playerRankingList.Count).Swap()))); foreach (var player in playerRankingList) { responseContents.Add(request.CreateResponse(0x7837, player)); } } return(Task.FromResult <IEnumerable <ResponseContent> >(responseContents)); }
public async Task ServiceClientCanBroadcastMessages() { WebPubSubServiceClientOptions options = InstrumentClientOptions(new WebPubSubServiceClientOptions()); var serviceClient = new WebPubSubServiceClient(TestEnvironment.ConnectionString, nameof(ServiceClientCanBroadcastMessages), options); // broadcast messages var textContent = "Hello"; var response = await serviceClient.SendToAllAsync(textContent, ContentType.TextPlain); Assert.AreEqual(202, response.Status); var jsonContent = BinaryData.FromObjectAsJson(new { hello = "world" }); response = await serviceClient.SendToAllAsync(RequestContent.Create(jsonContent), ContentType.ApplicationJson); Assert.AreEqual(202, response.Status); var binaryContent = BinaryData.FromString("Hello"); response = await serviceClient.SendToAllAsync(RequestContent.Create(binaryContent), ContentType.ApplicationOctetStream); Assert.AreEqual(202, response.Status); }
public async Task DeployProject() { string testProjectName = CreateTestProjectName(); await CreateProjectAsync(testProjectName); string sourceUri = "https://www.microsoft.com/en-in/software-download/faq"; RequestContent updateSourcesRequestContent = RequestContent.Create( new[] { new { op = "add", value = new { displayName = "MicrosoftFAQ", source = sourceUri, sourceUri = sourceUri, sourceKind = "url", contentStructureKind = "unstructured", refresh = false } } }); Operation <BinaryData> updateSourcesOperation = await Client.UpdateSourcesAsync(false, testProjectName, updateSourcesRequestContent); await updateSourcesOperation.WaitForCompletionAsync(); string testDeploymentName = "production"; Operation <BinaryData> deploymentOperation = await Client.DeployProjectAsync(false, testProjectName, testDeploymentName); await deploymentOperation.WaitForCompletionAsync(); AsyncPageable <BinaryData> deployments = Client.GetDeploymentsAsync(testProjectName); Assert.True(deploymentOperation.HasCompleted); Assert.That((await deployments.ToEnumerableAsync()).Any(deployment => deployment.ToString().Contains(testDeploymentName))); await DeleteProjectAsync(testProjectName); }
public async Task UpdateSynonyms() { string testProjectName = CreateTestProjectName(); await CreateProjectAsync(testProjectName); RequestContent updateSynonymsRequestContent = RequestContent.Create( new { value = new[] { new { alterations = new[] { "qnamaker", "qna maker", } }, new { alterations = new[] { "qna", "question and answer", } } } }); Response updateSynonymsResponse = await Client.UpdateSynonymsAsync(testProjectName, updateSynonymsRequestContent); // Synonyms can be retrieved as follows AsyncPageable <BinaryData> synonyms = Client.GetSynonymsAsync(testProjectName); Assert.AreEqual(204, updateSynonymsResponse.Status); Assert.That((await synonyms.ToEnumerableAsync()).Any(synonym => synonym.ToString().Contains("qnamaker"))); Assert.That((await synonyms.ToEnumerableAsync()).Any(synonym => synonym.ToString().Contains("qna"))); await DeleteProjectAsync(testProjectName); }
private async Task <(IEnumerable <string> jobId, IEnumerable <string> errors)> SubmitConversationsAsync(IEnumerable <AnalyzeConversationsRequest> data) { var errors = new List <string>(); var jobs = new List <string>(); try { Log.LogInformation($"Sending language conversation requests."); foreach (var request in data) { using var input = RequestContent.Create(JsonConvert.SerializeObject(request)); var operation = await ConversationAnalysisClient.AnalyzeConversationAsync(WaitUntil.Started, input).ConfigureAwait(false); var response = await operation.UpdateStatusAsync().ConfigureAwait(false); using JsonDocument result = JsonDocument.Parse(response.ContentStream); var jobResults = result.RootElement; var jobId = jobResults.GetProperty("jobId"); Log.LogInformation($"Submitting TA job: {jobId}"); jobs.Add(jobId.ToString()); } return(jobs, errors); } catch (OperationCanceledException) { throw new TimeoutException($"The operation has timed out after {RequestTimeout.TotalSeconds} seconds."); } // do not catch throttling errors, rather throw and retry catch (RequestFailedException e) when(e.Status != 429) { errors.Add($"Conversation analytics request failed with error: {e.Message}"); } return(jobs, errors); }
public virtual Response CreateOrUpdate(string farmerId, RequestContent requestBody, RequestOptions requestOptions = null) #pragma warning restore AZC0002 { requestOptions ??= new RequestOptions(); HttpMessage message = CreateCreateOrUpdateRequest(farmerId, requestBody, requestOptions); if (requestOptions.PerCallPolicy != null) { message.SetProperty("RequestOptionsPerCallPolicyCallback", requestOptions.PerCallPolicy); } using var scope = _clientDiagnostics.CreateScope("FarmersClient.CreateOrUpdate"); scope.Start(); try { Pipeline.Send(message, requestOptions.CancellationToken); if (requestOptions.StatusOption == ResponseStatusOption.Default) { switch (message.Response.Status) { case 200: case 201: return(message.Response); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } else { return(message.Response); } } catch (Exception e) { scope.Failed(e); throw; } }
public virtual async Task <Response> CreateDataDeleteJobAsync(string jobId, RequestContent requestBody, RequestOptions requestOptions = null) #pragma warning restore AZC0002 { requestOptions ??= new RequestOptions(); HttpMessage message = CreateCreateDataDeleteJobRequest(jobId, requestBody, requestOptions); if (requestOptions.PerCallPolicy != null) { message.SetProperty("RequestOptionsPerCallPolicyCallback", requestOptions.PerCallPolicy); } using var scope = _clientDiagnostics.CreateScope("WeatherClient.CreateDataDeleteJob"); scope.Start(); try { await Pipeline.SendAsync(message, requestOptions.CancellationToken).ConfigureAwait(false); if (requestOptions.StatusOption == ResponseStatusOption.Default) { switch (message.Response.Status) { case 202: return(message.Response); default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } else { return(message.Response); } } catch (Exception e) { scope.Failed(e); throw; } }
public void StreamCopyTo() { int size = 100; var sourceArray = new byte[size]; var destinationArray = new byte[size * 2]; new Random(100).NextBytes(sourceArray); var source = new MemoryStream(sourceArray); var destination = new MemoryStream(destinationArray); var content = RequestContent.Create(source); content.WriteTo(destination, default); for (int i = 0; i < size; i++) { Assert.AreEqual(sourceArray[i], destinationArray[i]); } for (int i = size; i < destinationArray.Length; i++) { Assert.AreEqual(0, destinationArray[i]); } }
public async Task Serialize_FileNameStringContent_Success() { var content = new MultipartFormDataContent("test_boundary"); var headers = new Dictionary <string, string> { { "Content-Type", "text/plain; charset=utf-8" } }; content.Add(RequestContent.Create(Encoding.UTF8.GetBytes("Hello World")), "test_name", "test_file_name", headers); var output = new MemoryStream(); await content.WriteToAsync(output, CancellationToken.None); output.Seek(0, SeekOrigin.Begin); string result = new StreamReader(output).ReadToEnd(); Assert.AreEqual( "--test_boundary\r\nContent-Type: text/plain; charset=utf-8\r\n" + "Content-Disposition: form-data; name=test_name; " + "filename=test_file_name\r\n\r\n" + "Hello World\r\n--test_boundary--\r\n", result); }
public async Task StreamRequestContentCanBeSentMultipleTimes() { var requests = new List <HttpRequestMessage>(); var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK); var mockHandler = new MockHttpClientHandler(httpRequestMessage => { requests.Add(httpRequestMessage); return(Task.FromResult(httpResponseMessage)); }); var transport = new HttpClientTransport(new HttpClient(mockHandler)); Request request = transport.CreateRequest(); request.Content = RequestContent.Create(new MemoryStream(new byte[] { 1, 2, 3 })); request.Method = RequestMethod.Get; request.Uri.Reset(new Uri("https://example.com:340")); await ExecuteRequest(request, transport); await ExecuteRequest(request, transport); Assert.AreEqual(2, requests.Count); }
// We are overriding this method because the new generator attempts to add 2 content types to the Content-Type header, // causing auth to fail. https://github.com/Azure/autorest/issues/3914. https://github.com/Azure/azure-sdk-for-net/issues/19030. internal HttpMessage CreateSubmitBatchRequest(long contentLength, string multipartContentType, Stream body, int?timeout) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.AppendRaw(_url, false); uri.AppendPath("/", false); uri.AppendQuery("comp", "batch", true); if (timeout != null) { uri.AppendQuery("timeout", timeout.Value, true); } request.Uri = uri; request.Headers.Add("x-ms-version", _version); request.Headers.Add("Accept", "application/xml"); request.Headers.Add("Content-Length", contentLength); request.Headers.Add("Content-Type", multipartContentType); request.Content = RequestContent.Create(body); return(message); }
public static StepResult InitializeKernel(ScenarioContext context) { var baseAddress = $"{context[Context.ServiceUrl] as string}/api/DataX.Flow/Flow.InteractiveQueryService/kernel"; Helper helper = new Helper(); context[Context.InitializeKernelJson] = helper.GetInitializeKernelJson(context); string jsonResult = Request.Post(baseAddress, RequestContent.EncodeAsJson( JObject.Parse(context[Context.InitializeKernelJson] as string)), context[Context.AuthToken] as string); dynamic result = JObject.Parse(jsonResult); context[Context.KernelId] = (string)result.result.result; context[Context.InitializeKernelJson] = helper.GetInitializeKernelJson(context); return(new StepResult(!(string.IsNullOrWhiteSpace(context[Context.KernelId] as string) && (string)result.result.message == ""), nameof(InitializeKernel), $"Initialize a kernel '{context[Context.KernelId]}' ")); }
public virtual Operation <BinaryData> CreateDataIngestionJob(string jobId, RequestContent content, RequestOptions options = null) #pragma warning restore AZC0002 { options ??= new RequestOptions(); HttpMessage message = CreateCreateDataIngestionJobRequest(jobId, content, options); if (options.PerCallPolicy != null) { message.SetProperty("RequestOptionsPerCallPolicyCallback", options.PerCallPolicy); } using var scope = _clientDiagnostics.CreateScope("FarmClient.CreateDataIngestionJob"); scope.Start(); try { Pipeline.Send(message, options.CancellationToken); if (options.StatusOption == ResponseStatusOption.Default) { switch (message.Response.Status) { case 202: return(new LowLevelBinaryDataOperation(_clientDiagnostics, Pipeline, message.Request, message.Response, OperationFinalStateVia.Location, "FarmClient.CreateDataIngestionJob")); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } else { return(new LowLevelBinaryDataOperation(_clientDiagnostics, Pipeline, message.Request, message.Response, OperationFinalStateVia.Location, "FarmClient.CreateDataIngestionJob")); } } catch (Exception e) { scope.Failed(e); throw; } }
public virtual Response GetOAuthConnectionLink(RequestContent content, RequestOptions options = null) #pragma warning restore AZC0002 { options ??= new RequestOptions(); HttpMessage message = CreateGetOAuthConnectionLinkRequest(content, options); if (options.PerCallPolicy != null) { message.SetProperty("RequestOptionsPerCallPolicyCallback", options.PerCallPolicy); } using var scope = _clientDiagnostics.CreateScope("OAuthTokensClient.GetOAuthConnectionLink"); scope.Start(); try { Pipeline.Send(message, options.CancellationToken); if (options.StatusOption == ResponseStatusOption.Default) { switch (message.Response.Status) { case 200: return(message.Response); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } else { return(message.Response); } } catch (Exception e) { scope.Failed(e); throw; } }
public void BadArgument() { ConversationAnalysisClient client = Client; #region Snippet:ConversationAnalysisClient_BadRequest try { var data = new { analysisInput = new { conversationItem = new { text = "Send an email to Carol about tomorrow's demo", id = "1", participantId = "1", } }, parameters = new { projectName = "invalid-project", deploymentName = "production", // Use Utf16CodeUnit for strings in .NET. stringIndexType = "Utf16CodeUnit", }, kind = "Conversation", }; Response response = client.AnalyzeConversation(RequestContent.Create(data)); } catch (RequestFailedException ex) { Console.WriteLine(ex.ToString()); } #endregion }
public HttpReq PackRequest() { HttpHeaders headers; RequestLine line = new RequestLine { szRequestMethod = this.method, szRequestUri = this.URL, szHttpVersion = this.version }; ListLinqView <HeaderUnit> view = new ListLinqView <HeaderUnit>(); foreach (KeyValuePair <string, string> pair in this.headers) { byte[] bytes = Encoding.UTF8.GetBytes(pair.Key); byte[] buffer2 = Encoding.UTF8.GetBytes(pair.Value); HeaderUnit item = new HeaderUnit { szHeaderName = bytes, szHeaderContent = buffer2 }; view.Add(item); } headers = new HttpHeaders { astHeaderUnit = view.ToArray(), dwHeaderCount = (uint)headers.astHeaderUnit.Length }; RequestContent content = new RequestContent { szData = this.data, dwDataLen = (uint)this.data.Length }; HttpReq req = new HttpReq { stRequestLine = line, stHttpHeaders = headers, stRequestContent = content }; ADebug.Log("send request :" + this.ToString()); return(req); }
private async Task TestCookiesEnabled() { int requestCount = 0; using (TestServer testServer = new TestServer( async context => { if (requestCount++ == 1) { Assert.IsTrue(context.Request.Headers.ContainsKey("cookie")); Assert.AreEqual("stsservicecookie=estsfd", context.Request.Headers["cookie"].First()); } context.Response.StatusCode = 200; context.Response.Headers.Add( "set-cookie", "stsservicecookie=estsfd; path=/; secure; samesite=none; httponly"); await context.Response.WriteAsync(""); }, https: true)) { var transport = GetTransport(https: true); Request request = transport.CreateRequest(); request.Method = RequestMethod.Post; request.Uri.Reset(testServer.Address); request.Content = RequestContent.Create("Hello"); await ExecuteRequest(request, transport); // create a second request to verify cookies not set request = transport.CreateRequest(); request.Method = RequestMethod.Post; request.Uri.Reset(testServer.Address); request.Content = RequestContent.Create("Hello"); await ExecuteRequest(request, transport); } }
public virtual Response CreateRasterizeJob(string jobId, RequestContent content, RequestOptions options = null) #pragma warning restore AZC0002 { options ??= new RequestOptions(); HttpMessage message = CreateCreateRasterizeJobRequest(jobId, content, options); if (options.PerCallPolicy != null) { message.SetProperty("RequestOptionsPerCallPolicyCallback", options.PerCallPolicy); } using var scope = _clientDiagnostics.CreateScope("ImageProcessingClient.CreateRasterizeJob"); scope.Start(); try { Pipeline.Send(message, options.CancellationToken); if (options.StatusOption == ResponseStatusOption.Default) { switch (message.Response.Status) { case 202: return(message.Response); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } else { return(message.Response); } } catch (Exception e) { scope.Failed(e); throw; } }
public async Task CanSetRequestHeaders(string headerName, string headerValue, bool contentHeader) { StringValues httpHeaderValues; using TestServer testServer = new TestServer( context => { Assert.True(context.Request.Headers.TryGetValue(headerName, out httpHeaderValues)); }); var transport = GetTransport(); Request request = CreateRequest(transport, testServer); request.Headers.Add(headerName, "Random value"); request.Headers.SetValue(headerName, headerValue); if (contentHeader) { request.Content = RequestContent.Create(new byte[16]); } Assert.True(request.Headers.TryGetValue(headerName, out var value)); Assert.AreEqual(headerValue, value); Assert.True(request.Headers.TryGetValue(headerName.ToUpper(), out value)); Assert.AreEqual(headerValue, value); CollectionAssert.AreEqual(new[] { new HttpHeader(headerName, headerValue), }, request.Headers); await ExecuteRequest(request, transport); Assert.AreEqual(headerValue, string.Join(",", httpHeaderValues)); }
public async Task CanGetAndSetContent() { byte[] requestBytes = null; var mockHandler = new MockHttpClientHandler( async httpRequestMessage => { requestBytes = await httpRequestMessage.Content.ReadAsByteArrayAsync(); }); var bytes = Encoding.ASCII.GetBytes("Hello world"); var content = RequestContent.Create(bytes); var transport = new HttpClientTransport(new HttpClient(mockHandler)); Request request = transport.CreateRequest(); request.Method = RequestMethod.Get; request.Uri.Reset(new Uri("https://example.com:340")); request.Content = content; Assert.AreEqual(content, request.Content); await ExecuteRequest(request, transport); CollectionAssert.AreEqual(bytes, requestBytes); }
private Request CreateAddRequest(ConfigurationSetting setting) { Argument.AssertNotNull(setting, nameof(setting)); Argument.AssertNotNullOrEmpty(setting.Key, $"{nameof(setting)}.{nameof(setting.Key)}"); Request request = _pipeline.CreateRequest(); ReadOnlyMemory <byte> content = Serialize(setting); request.Method = RequestMethod.Put; BuildUriForKvRoute(request.Uri, setting); MatchConditions requestOptions = new MatchConditions(); requestOptions.IfNoneMatch = ETag.All; ConditionalRequestOptionsExtensions.ApplyHeaders(request, requestOptions); request.Headers.Add(s_mediaTypeKeyValueApplicationHeader); request.Headers.Add(HttpHeader.Common.JsonContentType); request.Content = RequestContent.Create(content); return(request); }
public async Task GettingErrorRequestProducesEvents() { var response = new MockResponse(500); response.SetContent(new byte[] { 6, 7, 8, 9, 0 }); response.AddHeader(new HttpHeader("Custom-Response-Header", "Improved value")); MockTransport mockTransport = CreateMockTransport(response); var pipeline = new HttpPipeline(mockTransport, new[] { new LoggingPolicy(logContent: true, int.MaxValue, s_allowedHeaders, s_allowedQueryParameters, "Test-SDK") }); string requestId = null; await SendRequestAsync(pipeline, request => { request.Method = RequestMethod.Get; request.Uri.Reset(new Uri("https://contoso.a.io")); request.Headers.Add("Date", "3/26/2019"); request.Headers.Add("Custom-Header", "Value"); request.Content = RequestContent.Create(new byte[] { 1, 2, 3, 4, 5 }); requestId = request.ClientRequestId; }); EventWrittenEventArgs e = _listener.SingleEventById(ErrorResponseEvent); Assert.AreEqual(EventLevel.Warning, e.Level); Assert.AreEqual("ErrorResponse", e.EventName); Assert.AreEqual(requestId, e.GetProperty <string>("requestId")); Assert.AreEqual(e.GetProperty <int>("status"), 500); StringAssert.Contains($"Custom-Response-Header:Improved value{Environment.NewLine}", e.GetProperty <string>("headers")); e = _listener.SingleEventById(ErrorResponseContentEvent); Assert.AreEqual(EventLevel.Informational, e.Level); Assert.AreEqual("ErrorResponseContent", e.EventName); Assert.AreEqual(requestId, e.GetProperty <string>("requestId")); CollectionAssert.AreEqual(new byte[] { 6, 7, 8, 9, 0 }, e.GetProperty <byte[]>("content")); }
public Response( MessageType messageType , Boolean isSuccess , RequestContent response ) : this() { this.Type = messageType; this.IsSuccess = isSuccess; this.ResponseContent = response; }
public Request( MessageType type , String userID , RequestContent requestContent ) { this.Type = type; this.UserID = userID; this.RequestContent = requestContent; }
private void DealReceiveSharingInfo( RequestContent ResponseContent ) { SecuruStik.Protocal.SharingInfo si = ResponseContent as SecuruStik.Protocal.SharingInfo; if ( si != null ) { try { PreKeyring.SharingFile_Update( new DB.SharingInfo { CopyRef = si.Reference , FileName = si.FileName , ID_From = si.ID_From , CKEY_E = si.CKey_E , CKEY_F = si.CKey_F , CKEY_U = si.CKey_U , CKEY_W = si.CKey_W } ); String savePath = Path.Combine( DropBoxController.Local_ShareInfoFolder , String.Format( "[{1}]{0}.{2}" , si.FileName , si.ID_From , AppSetting.Name_ShareInfoFileExtension ) ); Byte[] sharingInfoBytes = CommunicatingProtocal.Serialize( si ); File.WriteAllBytes( BaseExtension.FileStringHelper.GetNonConflictFileName(savePath) , sharingInfoBytes ); } catch (System.Exception ex){} } }
private void DealReceivePK( RequestContent ResponseContent ) { SecuruStik.Protocal.PublicKey receivepk = ResponseContent as SecuruStik.Protocal.PublicKey; if ( receivepk != null ) { PublicKeyUnit pku = PKList[receivepk.ID]; if ( pku == null ) { this.PKList.Add(new PublicKeyUnit(receivepk.ID, receivepk)); } else { PublicKey pk = pku.PK; if ( pk == null || pk.PK1 != receivepk.PK1 || pk.PK2 != receivepk.PK2 ) { pku.PK = receivepk; } } SecuruStikMessageQueue.SendMessage_ReceivePK( pku.ID , pku.PK.PK1 , pku.PK.PK2 ); } return; }
public Request( MessageType type , String userID ) { this.Type = type; this.UserID = userID; this.RequestContent = null; }