示例#1
0
        public override Task SetupAsync()
        {
            var data = new
            {
                analysisInput = new
                {
                    conversationItem = new
                    {
                        text          = "Send an email to Carol about the tomorrow's demo",
                        id            = "1",
                        participantId = "1",
                    }
                },
                parameters = new
                {
                    projectName    = TestEnvironment.ProjectName,
                    deploymentName = TestEnvironment.DeploymentName,

                    // Use Utf16CodeUnit for Strings in .NET.
                    stringIndexType = "Utf16CodeUnit",
                },
                kind = "Conversation",
            };

            _content = RequestContent.Create(data);
            return(Task.CompletedTask);
        }
        public void DisableRequestBodyRecordingMakesRequestBodyNull()
        {
            var                   tempFile  = Path.GetTempFileName();
            TestRecording         recording = new TestRecording(RecordedTestMode.Record, tempFile, new TestSanitizer(), new RecordMatcher());
            HttpPipelineTransport transport = recording.CreateTransport(Mock.Of <HttpPipelineTransport>());

            var body = "A nice and long body.";

            var request = new MockRequest();

            request.Content = RequestContent.Create(Encoding.UTF8.GetBytes(body));
            request.Headers.Add("Content-Type", "text/json");

            HttpMessage message = new HttpMessage(request, null);

            message.Response = new MockResponse(200);

            using (recording.DisableRequestBodyRecording())
            {
                transport.Process(message);
            }

            recording.Dispose(true);
            var text = File.ReadAllText(tempFile);

            StringAssert.DoesNotContain(body, text);
            StringAssert.Contains($"\"RequestBody\": null", text);
        }
示例#3
0
        public async Task CanGetAndSetMethod(RequestMethod method, string expectedMethod, bool content = false)
        {
            string httpMethod = null;

            using TestServer testServer = new TestServer(
                      context =>
            {
                httpMethod = context.Request.Method.ToString();
            });

            var     transport = GetTransport();
            Request request   = transport.CreateRequest();

            request.Method = method;
            request.Uri.Reset(testServer.Address);

            if (content)
            {
                request.Content = RequestContent.Create(Array.Empty <byte>());
            }

            Assert.AreEqual(method, request.Method);

            await ExecuteRequest(request, transport);

            Assert.AreEqual(expectedMethod, httpMethod);
        }
        public async Task CanGetAndSetContentStream()
        {
            byte[] requestBytes = null;
            using TestServer testServer = new TestServer(
                      context =>
            {
                using var memoryStream = new MemoryStream();
                context.Request.Body.CopyTo(memoryStream);
                requestBytes = memoryStream.ToArray();
            });

            var stream = new MemoryStream();

            stream.SetLength(10 * 1024);
            var content   = RequestContent.Create(stream);
            var transport = GetTransport();

            Request request = transport.CreateRequest();

            request.Method = RequestMethod.Post;
            request.Uri.Reset(testServer.Address);
            request.Content = content;

            Assert.AreEqual(content, request.Content);

            await ExecuteRequest(request, transport);

            CollectionAssert.AreEqual(stream.ToArray(), requestBytes);
            Assert.AreEqual(10 * 1024, requestBytes.Length);
        }
        public async Task CanSetContentLenghtOverMaxInt()
        {
            long contentLength = 0;

            using TestServer testServer = new TestServer(
                      context =>
            {
                contentLength = context.Request.ContentLength.Value;
            });

            var     requestContentLength = long.MaxValue;
            var     transport            = GetTransport();
            Request request = transport.CreateRequest();

            request.Method = RequestMethod.Post;
            request.Uri.Reset(testServer.Address);
            request.Content = RequestContent.Create(new byte[10]);
            request.Headers.Add("Content-Length", requestContentLength.ToString());

            try
            {
                await ExecuteRequest(request, transport);
            }
            catch (Exception)
            {
                // Sending the request would fail because of length mismatch
            }

            Assert.AreEqual(requestContentLength, requestContentLength);
        }
        public async Task <Response> SendAsync(string tableName, IEnumerable <IDictionary <string, object> > values)
        {
            byte[] data;
            using (var stream = new MemoryStream())
            {
                using (var writer = new Utf8JsonWriter(stream))
                {
                    writer.WriteObjectValue(values);
                }

                data = stream.ToArray();
            }

            var request = _pipeline.CreateRequest();

            request.Uri.Reset(new Uri($"https://{_workspaceId}.{_ingestEndpointSuffix}/api/logs?api-version=2016-04-01"));
            request.Method = RequestMethod.Post;
            request.Headers.SetValue("Content-Type", "application/json");
            request.Headers.SetValue("Log-Type", tableName);
            request.Headers.SetValue("time-generated-field", "EventTimeGenerated");
            request.Content = RequestContent.Create(data);

            var response = await _pipeline.SendRequestAsync(request, default);

            if (response.Status != 200)
            {
                throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response);
            }

            return(response);
        }
        private async Task <Response> SendCloudNativeCloudEventsInternalAsync(ReadOnlyMemory <byte> cloudEvents, bool async, CancellationToken cancellationToken = default)
        {
            using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(EventGridPublisherClient)}.{nameof(SendEncodedCloudEvents)}");
            scope.Start();

            try
            {
                using HttpMessage message = _pipeline.CreateMessage();
                Request request = message.Request;
                request.Method = RequestMethod.Post;
                var uri = new RawRequestUriBuilder();
                uri.AppendRaw("https://", false);
                uri.AppendRaw(_hostName, false);
                uri.AppendPath("/api/events", false);
                uri.AppendQuery("api-version", _apiVersion, true);
                request.Uri = uri;
                request.Headers.Add("Content-Type", "application/cloudevents-batch+json; charset=utf-8");
                RequestContent content = RequestContent.Create(cloudEvents);
                request.Content = content;
                if (async)
                {
                    await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    _pipeline.Send(message, cancellationToken);
                }
                return(message.Response.Status switch
                {
                    200 => message.Response,
                    _ => async ?
                    throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false) :
                    throw _clientDiagnostics.CreateRequestFailedException(message.Response)
                });
            }
示例#8
0
        public async Task DataSourceOperations()
        {
            string name   = "test-datasources3";
            var    client = GetPurviewDataSourceClient(name);
            var    data   = new
            {
                kind       = "AmazonS3",
                name       = name,
                properties = new
                {
                    serviceUrl = "s3://testpurview",
                    collection = new
                    {
                        type          = "CollectionReference",
                        referenceName = "dotnetllcpurviewaccount"
                    }
                }
            };
            //Create
            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-datasources3", getBodyJson.GetProperty("id").GetString());
            //Delete
            Response deleteResponse = await client.DeleteAsync();

            Assert.AreEqual(200, deleteResponse.Status);
        }
        private Request CreateInkRecognitionRequest(HttpPipeline pipeline,
                                                    IEnumerable <InkStroke> strokes,
                                                    ApplicationKind applicationKind,
                                                    string language,
                                                    InkPointUnit inkPointUnit,
                                                    float unitMultiple)
        {
            Request request = pipeline.CreateRequest();

            // add content
            var inkRecognitionRequest = new InkRecognitionRequest(strokes,
                                                                  applicationKind,
                                                                  language,
                                                                  inkPointUnit,
                                                                  unitMultiple);
            var content = new MemoryStream(Encoding.UTF8.GetBytes(inkRecognitionRequest.ToJson()));

            request.Content = RequestContent.Create(content);

            // specify HTTP request line
            request.Method = RequestMethod.Put;
            var requestUri = new RequestUriBuilder();

            requestUri.Reset(_endpoint);
            request.Uri.Scheme = requestUri.Scheme;
            request.Uri.Host   = requestUri.Host;
            request.Uri.Port   = requestUri.Port;
            request.Uri.Path   = requestUri.Path;
            request.Uri.Query  = requestUri.Query;

            // add headers for authentication
            _credential.SetRequestCredentials(request);

            return(request);
        }
示例#10
0
        public async Task CreateOrUpdateTask()
        {
            var options              = new PurviewAccountClientOptions();
            var collectionName       = "mysubCollection";
            PurviewCollection client = GetCollectionsClient(collectionName);

            var data = new
            {
                parentCollection = new
                {
                    referenceName = "dotnetLLCPurviewAccount"
                },
            };
            Response createResponse = await client.CreateOrUpdateCollectionAsync(RequestContent.Create(data), default);

            JsonElement createBodyJson = JsonDocument.Parse(GetContentFromResponse(createResponse)).RootElement;

            Assert.AreEqual("mysubCollection", createBodyJson.GetProperty("name").GetString());
            while (true)
            {
                System.Threading.Thread.Sleep(1000);
                Response getResponse = await client.GetCollectionAsync(new());

                JsonElement getBodyJson = JsonDocument.Parse(GetContentFromResponse(getResponse)).RootElement;
                if (getBodyJson.GetProperty("collectionProvisioningState").GetString() == "Succeeded")
                {
                    break;
                }
            }
            Response delRespons = await client.DeleteCollectionAsync(default);
示例#11
0
        public async Task CanSetContentLengthOverMaxInt()
        {
            long contentLength = 0;

            using TestServer testServer = new TestServer(
                      context =>
            {
                contentLength = context.Request.ContentLength.Value;
                context.Abort();
            });

            var     transport = GetTransport();
            Request request   = transport.CreateRequest();

            request.Method = RequestMethod.Post;
            request.Uri.Reset(testServer.Address);
            var infiniteStream = new InfiniteStream();

            request.Content = RequestContent.Create(infiniteStream);

            try
            {
                await ExecuteRequest(request, transport);
            }
            catch (Exception)
            {
                // Sending the request would fail because of length mismatch
            }

            // InfiniteStream has a length of long.MaxValue check that it got sent correctly
            Assert.AreEqual(infiniteStream.Length, contentLength);
            Assert.Greater(infiniteStream.Length, int.MaxValue);
        }
示例#12
0
        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 async Task ScanTriggerOperations()
        {
            var client = GetPurviewScanClient("test-datasource1009", "test-scan1009");
            //Create
            var data = new
            {
                name       = "default",
                properties = new
                {
                    scanLevel  = "Incremental",
                    recurrence = new
                    {
                        startTime = "2021-10-12T09:30:00",
                        interval  = 1,
                        frequency = "Month",
                        timezone  = "China Standard Time",
                        schedule  = new
                        {
                            monthDays = new[]
                            {
                                1
                            }
                        }
                    }
                }
            };
            Response createResponse = await client.CreateOrUpdateTriggerAsync(RequestContent.Create(data));

            Assert.AreEqual(201, createResponse.Status);
            //Delete
            Response deleteResponse = await client.DeleteTriggerAsync();

            Assert.AreEqual(200, deleteResponse.Status);
        }
        public async Task FliterOperations()
        {
            var client = GetPurviewScanClient("test-datasource1009", "test-scan1009");
            //Create
            var data = new
            {
                name       = "custom",
                id         = "datasources/test-datasource1009/scans/test-scan1009/filters/custom",
                properties = new
                {
                    includeUriPrefixes = new[]
                    {
                        "https://foo.file.core.windows.net/share1/user",
                        "https://foo.file.core.windows.net/share1/aggregated"
                    },
                    excludeUriPrefixes = new[]
                    {
                        "https://foo.file.core.windows.net/share1/user/temp"
                    }
                }
            };
            Response createResponse = await client.CreateOrUpdateFilterAsync(RequestContent.Create(data));

            Assert.AreEqual(200, createResponse.Status);
            //Get
            Response getResponse = await client.GetFilterAsync(new());

            Assert.AreEqual(200, getResponse.Status);
            JsonElement fetchBodyJson = JsonDocument.Parse(GetContentFromResponse(getResponse)).RootElement;

            Assert.AreEqual("https://foo.file.core.windows.net/share1/user/temp", fetchBodyJson.GetProperty("properties").GetProperty("excludeUriPrefixes")[0].GetString());
        }
        public void FailedTransaction()
        {
            var client = InstrumentClient(
                new ConfidentialLedgerClient(
                    new("https://client"),
                    new MockCredential(),
                    new ConfidentialLedgerClientOptions
            {
                Transport = new MockTransport(
                    req =>
                {
                    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));
        }
示例#16
0
        static async Task Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: publisher <connectionString>");
                return;
            }

            var connectionString = args[0];
            var hub = "test01";

            var serviceClient = new WebPubSubServiceClient(connectionString, hub);
            var user          = "******";
            var count         = 0;

            do
            {
                Console.WriteLine($"Sending {count}");

                serviceClient.SendToUser(user, RequestContent.Create(new {
                    TimeStamp = DateTime.UtcNow,
                    Message   = $"Hello World - {count}"
                }));

                count++;
                await Task.Delay(5000);
            }while(true);
        }
        public async Task FarmersSmokeTest()
        {
            FarmersClient client   = GetFarmersClient();
            const string  farmerId = "smoke-test-farmer";

            Response createdResponse = await client.CreateOrUpdateAsync(farmerId, RequestContent.Create(new object()));

            JsonElement createdBodyJson = JsonDocument.Parse(GetContentFromResponse(createdResponse)).RootElement;

            Assert.AreEqual(farmerId, createdBodyJson.GetProperty("id").GetString());
            Assert.IsTrue(HasProperty(createdBodyJson, "eTag"));
            Assert.IsTrue(HasProperty(createdBodyJson, "createdDateTime"));
            Assert.IsTrue(HasProperty(createdBodyJson, "modifiedDateTime"));

            Response fetchResponse = await client.GetFarmerAsync(farmerId, new());

            JsonElement fetchBodyJson = JsonDocument.Parse(GetContentFromResponse(fetchResponse)).RootElement;

            Assert.AreEqual(createdBodyJson.GetProperty("id").GetString(), fetchBodyJson.GetProperty("id").GetString());
            Assert.AreEqual(createdBodyJson.GetProperty("eTag").GetString(), fetchBodyJson.GetProperty("eTag").GetString());
            Assert.AreEqual(createdBodyJson.GetProperty("createdDateTime").GetString(), fetchBodyJson.GetProperty("createdDateTime").GetString());
            Assert.AreEqual(createdBodyJson.GetProperty("modifiedDateTime").GetString(), fetchBodyJson.GetProperty("modifiedDateTime").GetString());

            await client.DeleteAsync(farmerId);
        }
示例#18
0
        public async Task UpdateSources()
        {
            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();

            AsyncPageable <BinaryData> sources = Client.GetSourcesAsync(testProjectName);

            Assert.True(updateSourcesOperation.HasCompleted);
            Assert.AreEqual(200, updateSourcesOperation.GetRawResponse().Status);
            Assert.That((await sources.ToEnumerableAsync()).Any(source => source.ToString().Contains(sourceUri)));

            await DeleteProjectAsync(testProjectName);
        }
        public async Task RequestContentLogsAreLimitedInLength()
        {
            var           response      = new MockResponse(500);
            MockTransport mockTransport = CreateMockTransport(response);

            var    pipeline  = new HttpPipeline(mockTransport, new[] { new LoggingPolicy(logContent: true, 5, s_allowedHeaders, s_allowedQueryParameters) });
            string requestId = null;

            await SendRequestAsync(pipeline, request =>
            {
                request.Method = RequestMethod.Get;
                request.Uri.Reset(new Uri("https://contoso.a.io"));
                request.Content = RequestContent.Create(Encoding.UTF8.GetBytes("Hello world"));
                request.Headers.Add("Content-Type", "text/json");
                requestId = request.ClientRequestId;
            });

            EventWrittenEventArgs e = _listener.SingleEventById(RequestContentTextEvent);

            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("RequestContentText", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual("Hello", e.GetProperty <string>("content"));

            CollectionAssert.IsEmpty(_listener.EventsById(ResponseContentEvent));
        }
示例#20
0
        public async Task Import()
        {
            string         testProjectName      = CreateTestProjectName();
            string         importFormat         = "json";
            RequestContent importRequestContent = RequestContent.Create(new
            {
                Metadata = new
                {
                    ProjectName          = "NewProjectForExport",
                    Description          = "This is the description for a test project",
                    Language             = "en",
                    DefaultAnswer        = "No answer found for your question.",
                    MultilingualResource = false,
                    CreatedDateTime      = "2021-11-25T09=35=33Z",
                    LastModifiedDateTime = "2021-11-25T09=35=33Z",
                    Settings             = new
                    {
                        DefaultAnswer = "No answer found for your question."
                    }
                }
            });

            Operation <BinaryData> importOperation = await Client.ImportAsync(true, testProjectName, importRequestContent, importFormat);

            Response projectDetails = await Client.GetProjectDetailsAsync(testProjectName);

            Assert.True(importOperation.HasCompleted);
            Assert.AreEqual(200, importOperation.GetRawResponse().Status);
            Assert.AreEqual(200, projectDetails.Status);
            Assert.That(projectDetails.Content.ToString().Contains(testProjectName));

            await DeleteProjectAsync(testProjectName);
        }
        public async Task CanGetAndSetContent()
        {
            byte[] requestBytes = null;
            using TestServer testServer = new TestServer(
                      context =>
            {
                using var memoryStream = new MemoryStream();
                context.Request.Body.CopyTo(memoryStream);
                requestBytes = memoryStream.ToArray();
            });

            var     bytes     = Encoding.ASCII.GetBytes("Hello world");
            var     content   = RequestContent.Create(bytes);
            var     transport = GetTransport();
            Request request   = transport.CreateRequest();

            request.Method = RequestMethod.Post;
            request.Uri.Reset(testServer.Address);
            request.Content = content;

            Assert.AreEqual(content, request.Content);

            await ExecuteRequest(request, transport);

            CollectionAssert.AreEqual(bytes, requestBytes);
        }
示例#22
0
        public async Task AddFeedback()
        {
            string testProjectName = CreateTestProjectName();

            await CreateProjectAsync(testProjectName);

            RequestContent addFeedbackRequestContent = RequestContent.Create(
                new
            {
                records = new[]
                {
                    new
                    {
                        userId       = "userX",
                        userQuestion = "what do you mean?",
                        qnaId        = 1
                    }
                }
            });

            Response addFeedbackResponse = await Client.AddFeedbackAsync(testProjectName, addFeedbackRequestContent);

            Assert.AreEqual(204, addFeedbackResponse.Status);
            await DeleteProjectAsync(testProjectName);
        }
        public async Task SettingHeaderOverridesDefaultContentLength()
        {
            long contentLength = 0;

            using TestServer testServer        = new TestServer(
                      context => contentLength = context.Request.ContentLength.Value);

            var     transport = GetTransport();
            Request request   = transport.CreateRequest();

            request.Method = RequestMethod.Post;
            request.Uri.Reset(testServer.Address);
            request.Content = RequestContent.Create(new byte[10]);
            request.Headers.Add("Content-Length", "50");

            try
            {
                await ExecuteRequest(request, transport);
            }
            catch (Exception)
            {
                // Sending the request would fail because of length mismatch
            }

            Assert.AreEqual(50, contentLength);
        }
示例#24
0
        public async Task UpdateQnAs()
        {
            string testProjectName = CreateTestProjectName();

            await CreateProjectAsync(testProjectName);

            string         question = "What is the easiest way to use azure services in my .NET project?";
            string         answer   = "Using Microsoft's Azure SDKs";
            RequestContent updateQnasRequestContent = RequestContent.Create(
                new[] {
                new {
                    op    = "add",
                    value = new
                    {
                        questions = new[]
                        {
                            question
                        },
                        answer = answer
                    }
                }
            });

            Operation <BinaryData> updateQnasOperation = await Client.UpdateQnasAsync(true, testProjectName, updateQnasRequestContent);

            AsyncPageable <BinaryData> sources = Client.GetQnasAsync(testProjectName);

            Assert.True(updateQnasOperation.HasCompleted);
            Assert.AreEqual(200, updateQnasOperation.GetRawResponse().Status);
            Assert.That((await sources.ToEnumerableAsync()).Any(source => source.ToString().Contains(question)));
            Assert.That((await sources.ToEnumerableAsync()).Any(source => source.ToString().Contains(answer)));

            await DeleteProjectAsync(testProjectName);
        }
        private async Task <Response> SendCloudNativeCloudEventsInternalAsync(ReadOnlyMemory <byte> cloudEvents, bool async, CancellationToken cancellationToken = default)
        {
            using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(EventGridPublisherClient)}.{nameof(SendEncodedCloudEvents)}");
            scope.Start();

            try
            {
                using HttpMessage message = _pipeline.CreateMessage();
                Request        request = CreateEventRequest(message, "application/cloudevents-batch+json; charset=utf-8");
                RequestContent content = RequestContent.Create(cloudEvents);
                request.Content = content;
                if (async)
                {
                    await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    _pipeline.Send(message, cancellationToken);
                }
                return(message.Response.Status switch
                {
                    200 => message.Response,
                    _ => async ?
                    throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false) :
                    throw _clientDiagnostics.CreateRequestFailedException(message.Response)
                });
            }
示例#26
0
        public async Task ExportAndImportAsync()
        {
            QuestionAnsweringProjectsClient client = Client;
            string exportedProjectName             = CreateTestProjectName();

            await CreateProjectAsync(exportedProjectName);

            #region Snippet:QuestionAnsweringProjectsClient_ExportProjectAsync
            Operation <BinaryData> exportOperation = await client.ExportAsync(waitForCompletion : true, exportedProjectName, format : "json");

            // retrieve export operation response, and extract url of exported file
            JsonDocument operationValueJson = JsonDocument.Parse(exportOperation.Value);
            string       exportedFileUrl    = operationValueJson.RootElement.GetProperty("resultUrl").ToString();
            #endregion

            Assert.True(exportOperation.HasCompleted);
            Assert.True(!String.IsNullOrEmpty(exportedFileUrl));

            #region Snippet:QuestionAnsweringProjectsClient_ImportProjectAsync
            // Set import project name and request content
            string importedProjectName = "{ProjectNameToBeImported}";
#if !SNIPPET
            importedProjectName = "importedProject";
#endif
            RequestContent importRequestContent = RequestContent.Create(new
            {
                Metadata = new
                {
                    ProjectName          = "NewProjectForExport",
                    Description          = "This is the description for a test project",
                    Language             = "en",
                    DefaultAnswer        = "No answer found for your question.",
                    MultilingualResource = false,
                    CreatedDateTime      = "2021-11-25T09=35=33Z",
                    LastModifiedDateTime = "2021-11-25T09=35=33Z",
                    Settings             = new
                    {
                        DefaultAnswer = "No answer found for your question."
                    }
                }
            });

            Operation <BinaryData> importOperation = await client.ImportAsync(waitForCompletion : true, importedProjectName, importRequestContent, format : "json");

            Console.WriteLine($"Operation status: {importOperation.GetRawResponse().Status}");
            #endregion

            Assert.True(importOperation.HasCompleted);
            Assert.AreEqual(200, importOperation.GetRawResponse().Status);

            #region Snippet:QuestionAnsweringProjectsClient_GetProjectDetailsAsync
            Response projectDetails = await client.GetProjectDetailsAsync(importedProjectName);

            Console.WriteLine(projectDetails.Content);
            #endregion

            Assert.AreEqual(200, projectDetails.Status);

            await DeleteProjectAsync(importedProjectName);
        }
        public void RecordSessionLookupSkipsRequestBodyWhenFilterIsOn()
        {
            var request = new MockRequest();

            request.Uri.Reset(new Uri("https://mockuri.com"));
            request.Content = RequestContent.Create(Encoding.UTF8.GetBytes("A nice and long body."));
            request.Headers.Add("Content-Type", "text/json");

            HttpMessage message = new HttpMessage(request, null);

            message.Response = new MockResponse(200);

            var session         = new RecordSession();
            var recordTransport = new RecordTransport(session, Mock.Of <HttpPipelineTransport>(), entry => EntryRecordModel.RecordWithoutRequestBody, Mock.Of <Random>());

            recordTransport.Process(message);

            request.Content = RequestContent.Create(Encoding.UTF8.GetBytes("A bad and longer body."));

            var skipRequestBody   = true;
            var playbackTransport = new PlaybackTransport(session, new RecordMatcher(), new RecordedTestSanitizer(), Mock.Of <Random>(), entry => skipRequestBody);

            playbackTransport.Process(message);

            skipRequestBody = false;
            Assert.Throws <InvalidOperationException>(() => playbackTransport.Process(message));
        }
示例#28
0
        internal HttpMessage CreateAddRequest(string id, Stream twin, CreateOrReplaceDigitalTwinOptions digitalTwinsAddOptions)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;

            request.Method = RequestMethod.Put;
            var uri = new RawRequestUriBuilder();

            uri.Reset(endpoint);
            uri.AppendPath("/digitaltwins/", false);
            uri.AppendPath(id, true);
            uri.AppendQuery("api-version", apiVersion, true);
            request.Uri = uri;
            if (digitalTwinsAddOptions?.TraceParent != null)
            {
                request.Headers.Add("TraceParent", digitalTwinsAddOptions.TraceParent);
            }
            if (digitalTwinsAddOptions?.TraceState != null)
            {
                request.Headers.Add("TraceState", digitalTwinsAddOptions.TraceState);
            }
            if (digitalTwinsAddOptions?.IfNoneMatch != null)
            {
                request.Headers.Add("If-None-Match", digitalTwinsAddOptions.IfNoneMatch);
            }
            request.Headers.Add("Content-Type", "application/json");
            request.Headers.Add("Accept", "application/json");
            var content = RequestContent.Create(twin);

            request.Content = content;
            return(message);
        }
示例#29
0
        public async Task CanGetAndAddRequestHeaders(string headerName, string headerValue, bool contentHeader, bool supportsMultiple)
        {
            StringValues httpHeaderValues = default;

            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, 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));
        }
示例#30
0
        /// <summary>
        /// Use text analytics services and detect whether a review is positive or not positive and print out the result to the console
        /// </summary>
        static async Task Task1()
        {
            var requestBody = new JsonData();
            var documents   = requestBody.SetEmptyArray("documents");

            int i = 0;

            foreach (string review in ReadReviewsFromJson().Take(10))
            {
                var document = documents.AddEmptyObject();
                document["id"]   = (++i).ToString();
                document["text"] = review;
            }

            Response response = await client.GetSentimentAsync(RequestContent.Create(requestBody));

            var responseBody = JsonData.FromBytes(response.Content.ToMemory());

            if (response.Status == 200)
            {
                foreach (var document in responseBody["documents"].Items)
                {
                    Console.WriteLine($"{document["id"]} is {document["sentiment"]}");
                }
            }
            else
            {
                Console.Error.WriteLine(responseBody["error"]);
            }
        }