예제 #1
0
        public async Task SendMultipartformData()
        {
            IFormCollection formCollection = null;

            HttpPipeline httpPipeline = HttpPipelineBuilder.Build(GetOptions());

            using TestServer testServer = new TestServer(
                      context =>
            {
                formCollection = context.Request.Form;
                return(Task.CompletedTask);
            });

            using Request request = httpPipeline.CreateRequest();
            request.Method        = RequestMethod.Put;
            request.Uri.Reset(testServer.Address);

            var content = new MultipartFormDataContent("test_boundary");

            content.Add(RequestContent.Create(Encoding.UTF8.GetBytes("John")), "FirstName", "file_name.txt", new Dictionary <string, string>
            {
                { "Content-Type", "text/plain; charset=utf-8" }
            });
            content.Add(RequestContent.Create(Encoding.UTF8.GetBytes("Doe")), "LastName", "file_name.txt", new Dictionary <string, string>
            {
                { "Content-Type", "text/plain; charset=utf-8" }
            });

            content.ApplyToRequest(request);

            using Response response = await ExecuteRequest(request, httpPipeline);

            Assert.AreEqual(response.Status, 200);
            Assert.AreEqual(formCollection.Files.Count, 2);

            var formData = formCollection.Files.GetEnumerator();

            formData.MoveNext();
            Assert.AreEqual(formData.Current.Name, "FirstName");
            Assert.AreEqual(formData.Current.FileName, "file_name.txt");
            Assert.AreEqual(formData.Current.Headers.Count, 2);
            Assert.AreEqual(formData.Current.ContentType, "text/plain; charset=utf-8");
            Assert.AreEqual(formData.Current.ContentDisposition, "form-data; name=FirstName; filename=file_name.txt");

            formData.MoveNext();
            Assert.AreEqual(formData.Current.Name, "LastName");
            Assert.AreEqual(formData.Current.FileName, "file_name.txt");
            Assert.AreEqual(formData.Current.Headers.Count, 2);
            Assert.AreEqual(formData.Current.ContentType, "text/plain; charset=utf-8");
            Assert.AreEqual(formData.Current.ContentDisposition, "form-data; name=LastName; filename=file_name.txt");
        }
예제 #2
0
        /// <summary>
        /// Initializes a new instance of <see cref="LogsQueryClient"/>.
        /// </summary>
        /// <param name="endpoint">The service endpoint to use.</param>
        /// <param name="credential">The <see cref="TokenCredential"/> instance to use for authentication.</param>
        /// <param name="options">The <see cref="LogsQueryClientOptions"/> instance to use as client configuration.</param>
        public LogsQueryClient(Uri endpoint, TokenCredential credential, LogsQueryClientOptions options)
        {
            Argument.AssertNotNull(credential, nameof(credential));
            Argument.AssertNotNull(endpoint, nameof(endpoint));

            Endpoint = endpoint;
            options ??= new LogsQueryClientOptions();
            endpoint           = new Uri(endpoint, options.GetVersionString());
            _clientDiagnostics = new ClientDiagnostics(options);
            _pipeline          = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(
                                                               credential,
                                                               $"{options.Audience ?? LogsQueryClientAudience.AzurePublicCloud}//.default"));
            _queryClient = new QueryRestClient(_clientDiagnostics, _pipeline, endpoint);
        }
예제 #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DocumentAnalysisClient"/> class.
        /// </summary>
        /// <param name="endpoint">The endpoint to use for connecting to the Form Recognizer Azure Cognitive Service.</param>
        /// <param name="credential">A credential used to authenticate to an Azure Service.</param>
        /// <param name="options">A set of options to apply when configuring the client.</param>
        /// <remarks>
        /// The <paramref name="endpoint"/> URI string can be found in the Azure Portal.
        /// For more information see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/formrecognizer/Azure.AI.FormRecognizer/README.md#authenticate-the-client"> here</see>.
        /// </remarks>
        public DocumentAnalysisClient(Uri endpoint, TokenCredential credential, DocumentAnalysisClientOptions options)
        {
            Argument.AssertNotNull(endpoint, nameof(endpoint));
            Argument.AssertNotNull(credential, nameof(credential));

            options ??= new DocumentAnalysisClientOptions();

            string defaultScope = $"{(string.IsNullOrEmpty(options.Audience?.ToString()) ? DocumentAnalysisAudience.AzurePublicCloud : options.Audience)}/.default";

            Diagnostics = new ClientDiagnostics(options);
            var pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, defaultScope));

            ServiceClient = new DocumentAnalysisRestClient(Diagnostics, pipeline, endpoint.AbsoluteUri);
        }
예제 #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DocumentTranslationClient"/>
        /// class for the specified service instance.
        /// </summary>
        /// <param name="endpoint">A <see cref="Uri"/> to the service the client
        /// sends requests to.  Endpoint can be found in the Azure portal.</param>
        /// <param name="credential">A <see cref="TokenCredential"/> used to
        /// authenticate requests to the service, such as DefaultAzureCredential.</param>
        /// <param name="options"><see cref="DocumentTranslationClientOptions"/> that allow
        /// callers to configure how requests are sent to the service.</param>
        public DocumentTranslationClient(Uri endpoint, TokenCredential credential, DocumentTranslationClientOptions options)
        {
            Argument.AssertNotNull(endpoint, nameof(endpoint));
            Argument.AssertNotNull(credential, nameof(credential));
            Argument.AssertNotNull(options, nameof(options));

            _clientDiagnostics = new ClientDiagnostics(options);
            _options           = options;
            string defaultScope = $"{(string.IsNullOrEmpty(options.Audience?.ToString()) ? DocumentTranslationAudience.AzurePublicCloud : options.Audience)}/.default";

            HttpPipeline pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, defaultScope));

            _serviceRestClient = new DocumentTranslationRestClient(_clientDiagnostics, pipeline, endpoint.AbsoluteUri);
        }
예제 #5
0
        /// <summary>
        /// Initializes a new instance of <see cref="LogsQueryClient"/>.
        /// </summary>
        /// <param name="endpoint">The service endpoint to use.</param>
        /// <param name="credential">The <see cref="TokenCredential"/> instance to use for authentication.</param>
        /// <param name="options">The <see cref="LogsQueryClientOptions"/> instance to use as client configuration.</param>
        public LogsQueryClient(Uri endpoint, TokenCredential credential, LogsQueryClientOptions options)
        {
            Argument.AssertNotNull(credential, nameof(credential));
            Argument.AssertNotNull(endpoint, nameof(endpoint));

            Endpoint = endpoint;
            options ??= new LogsQueryClientOptions();
            var scope = $"{endpoint.AbsoluteUri}/.default";

            endpoint           = new Uri(endpoint, options.GetVersionString());
            _clientDiagnostics = new ClientDiagnostics(options);
            _pipeline          = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, scope));
            _queryClient       = new QueryRestClient(_clientDiagnostics, _pipeline, endpoint);
        }
예제 #6
0
        /// <summary>
        /// Initializes a new instance of <see cref="LogsQueryClient"/>.
        /// </summary>
        /// <param name="endpoint">The service endpoint to use.</param>
        /// <param name="credential">The <see cref="TokenCredential"/> instance to use for authentication.</param>
        /// <param name="options">The <see cref="LogsQueryClientOptions"/> instance to use as client configuration.</param>
        public LogsQueryClient(Uri endpoint, TokenCredential credential, LogsQueryClientOptions options)
        {
            Argument.AssertNotNull(credential, nameof(credential));
            Argument.AssertNotNull(endpoint, nameof(endpoint));

            options ??= new LogsQueryClientOptions();
            endpoint           = new Uri(endpoint, options.GetVersionString());
            _clientDiagnostics = new ClientDiagnostics(options);
            _pipeline          = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(
                                                               credential,
                                                               options.AuthenticationScope ?? "https://api.loganalytics.io//.default"));
            _queryClient = new QueryRestClient(_clientDiagnostics, _pipeline, endpoint);
            _rowBinder   = new RowBinder();
        }
예제 #7
0
        /// <summary>
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="options"></param>
        public ContainerRegistryClient(Uri endpoint, string username, string password, ContainerRegistryClientOptions options)
        {
            Argument.AssertNotNull(endpoint, nameof(endpoint));
            Argument.AssertNotNull(options, nameof(options));

            // The HttpPipelineBuilder.Build method, builds up a pipeline with client options, and any number of additional policies.
            _pipeline = HttpPipelineBuilder.Build(options, new BasicAuthenticationPolicy(username, password));

            _clientDiagnostics = new ClientDiagnostics(options);

            _endpoint = endpoint;

            _restClient = new RepositoryRestClient(_clientDiagnostics, _pipeline, _endpoint.AbsoluteUri);
        }
예제 #8
0
        public RbacManagementClient(string tenantID, Uri endpoint, TokenCredential tokenCredential, RbacManagementClientOptions options = null)
        {
            if (tenantID == null)
            {
                throw new ArgumentNullException(nameof(tenantID));
            }
            endpoint ??= new Uri("https://graph.windows.net");

            options ??= new RbacManagementClientOptions();
            _clientDiagnostics = new ClientDiagnostics(options);
            _pipeline          = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(tokenCredential, $"{endpoint}/.default"));
            _tenantID          = tenantID;
            _endpoint          = endpoint;
        }
        /// <summary>
        /// Creates an instance of the UsernamePasswordCredential with the details needed to authenticate against Azure Active Directory with a simple username
        /// and password.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password">The user account's user name, UPN.</param>
        /// <param name="clientId">The client (application) ID of an App Registration in the tenant.</param>
        /// <param name="tenantId">The Azure Active Directory tenant (directory) ID or name.</param>
        /// <param name="options">The client options for the newly created UsernamePasswordCredential</param>
        public UsernamePasswordCredential(string username, string password, string clientId, string tenantId, AzureCredentialOptions options)
        {
            _username = username ?? throw new ArgumentNullException(nameof(username));

            _password = (password != null) ? password.ToSecureString() : throw new ArgumentNullException(nameof(password));

            _options = options ?? new AzureCredentialOptions();

            _pipeline = HttpPipelineBuilder.Build(_options);

            _clientDiagnostics = new ClientDiagnostics(options);

            _pubApp = PublicClientApplicationBuilder.Create(clientId).WithHttpClientFactory(new HttpPipelineClientFactory(_pipeline)).WithTenantId(tenantId).Build();
        }
예제 #10
0
        private static async Task Playback()
        {
            var recordingId = await StartPlayback();

            var pipeline = HttpPipelineBuilder.Build(new TestClientOptions()
            {
                Transport = new TestProxyTransport(new HttpClientTransport(_httpClient), _proxy.Host, _proxy.Port, recordingId, "playback"),
            });

            await SendRequest(pipeline);
            await SendRequest(pipeline);

            await StopPlayback(recordingId);
        }
예제 #11
0
        /// <summary>
        /// Creates a new SharedTokenCacheCredential with the specifeid options, which will authenticate users with the specified application.
        /// </summary>
        /// <param name="clientId">The client id of the application to which the users will authenticate</param>
        /// <param name="username">The username of the user to authenticate</param>
        /// TODO: need to link to info on how the application has to be created to authenticate users, for multiple applications
        /// <param name="options">The client options for the newly created SharedTokenCacheCredential</param>
        public SharedTokenCacheCredential(string clientId, string username, SharedTokenCacheCredentialOptions options)
        {
            _clientId = clientId ?? throw new ArgumentNullException(nameof(clientId));

            options ??= new SharedTokenCacheCredentialOptions();

            _username = username;

            HttpPipeline pipeline = HttpPipelineBuilder.Build(options);

            _pubApp = PublicClientApplicationBuilder.Create(_clientId).WithHttpClientFactory(new HttpPipelineClientFactory(pipeline)).Build();

            _cacheReader = new MsalCacheReader(_pubApp.UserTokenCache, options.CacheFilePath, options.CacheAccessRetryCount, options.CacheAccessRetryDelay);
        }
예제 #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MixedRealityStsClient" /> class.
        /// </summary>
        /// <param name="accountId">The Mixed Reality service account identifier.</param>
        /// <param name="endpoint">The Mixed Reality STS service endpoint.</param>
        /// <param name="credential">The credential used to access the Mixed Reality service.</param>
        /// <param name="options">The options.</param>
        public MixedRealityStsClient(string accountId, Uri endpoint, TokenCredential credential, MixedRealityStsClientOptions?options = null)
        {
            Argument.AssertNotNull(accountId, nameof(accountId));
            Argument.AssertNotNull(endpoint, nameof(endpoint));
            Argument.AssertNotNull(credential, nameof(credential));

            options ??= new MixedRealityStsClientOptions();

            AccountId          = accountId;
            Endpoint           = endpoint;
            _clientDiagnostics = new ClientDiagnostics(options);
            _pipeline          = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, GetDefaultScope(endpoint)));
            _restClient        = new MixedRealityStsRestClient(_clientDiagnostics, _pipeline, endpoint, options.Version);
        }
        public PurviewClassificationRuleClient(Uri endpoint, string classificationRuleName, TokenCredential credential, PurviewScanningServiceClientOptions options = null)
        {
            Argument.AssertNotNull(endpoint, nameof(endpoint));
            Argument.AssertNotNullOrEmpty(classificationRuleName, nameof(classificationRuleName));
            Argument.AssertNotNull(credential, nameof(credential));
            options ??= new PurviewScanningServiceClientOptions();

            ClientDiagnostics       = new ClientDiagnostics(options);
            _tokenCredential        = credential;
            _pipeline               = HttpPipelineBuilder.Build(options, Array.Empty <HttpPipelinePolicy>(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier());
            _endpoint               = endpoint;
            _classificationRuleName = classificationRuleName;
            _apiVersion             = options.Version;
        }
        internal RemoteCryptographyClient(Uri keyId, TokenCredential credential, CryptographyClientOptions options)
        {
            Argument.AssertNotNull(keyId, nameof(keyId));
            Argument.AssertNotNull(credential, nameof(credential));

            _keyId = keyId;
            options ??= new CryptographyClientOptions();
            string apiVersion = options.GetVersionString();

            HttpPipeline pipeline = HttpPipelineBuilder.Build(options,
                                                              new ChallengeBasedAuthenticationPolicy(credential));

            Pipeline = new KeyVaultPipeline(keyId, apiVersion, pipeline, new ClientDiagnostics(options));
        }
        /// <summary>
        /// Synchronously sends data to the service and generates a tree structure containing the model results.
        /// </summary>
        /// <param name="strokes">The list of ink strokes to recognize.</param>
        /// <param name="unit"> The physical unit for the points in the stroke.</param>
        /// <param name="unitMultiple"> A multiplier applied to the unit value to indicate the true unit being used.
        /// This allows the caller to specify values in a fraction or multiple of a unit.</param>
        /// <param name="language"> IETF BCP 47 language code (for ex. en-US, en-GB, hi-IN etc.) for the strokes.
        /// This is only needed when the language is different from the default set when the client was instantiated.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
        /// <returns> RecognitionRoot containing the model results in a hierarchy. </returns>
        /// <exception cref="RequestFailedException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        public virtual Response <RecognitionRoot> RecognizeInk(
            IEnumerable <InkStroke> strokes,
            InkPointUnit unit,
            float unitMultiple,
            string language,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (strokes == null)
            {
                throw new ArgumentNullException(nameof(strokes));
            }

            try
            {
                // var policies = new HttpPipelinePolicy[] { _options.TelemetryPolicy, _options.LoggingPolicy, _options.RetryPolicy };

                //var pipeline = HttpPipelineBuilder.Build(_options, true, policies);
                var pipeline = HttpPipelineBuilder.Build(_options, null);
                var request  = CreateInkRecognitionRequest(pipeline,
                                                           strokes,
                                                           _options.ApplicationKind,
                                                           language,
                                                           unit,
                                                           unitMultiple);
                var response = pipeline.SendRequest(request, cancellationToken);

                var    reader       = new StreamReader(response.ContentStream);
                string responseText = reader.ReadToEnd();

                if (response.Status == 200)
                {
                    var root = InkRecognitionResponse.Parse(responseText);
                    return(Response.FromValue <RecognitionRoot>(root, response));
                }
                // For bad requests and internal server errors
                else if (response.Status >= 400 && response.Status < 600)
                {
                    var serverError = new HttpErrorDetails(responseText);
                    throw new RequestFailedException(serverError.ToString());
                }
                else
                {
                    throw new RequestFailedException(responseText);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="FormRecognizerClient"/> class.
        /// </summary>
        /// <param name="endpoint">The endpoint to use for connecting to the Form Recognizer Azure Cognitive Service.</param>
        /// <param name="credential">A credential used to authenticate to an Azure Service.</param>
        /// <param name="options">A set of options to apply when configuring the client.</param>
        /// <remarks>
        /// Both the <paramref name="endpoint"/> URI <c>string</c> and the <paramref name="credential"/> <c>string</c> key
        /// can be found in the Azure Portal.
        /// </remarks>
        /// <seealso href="https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/formrecognizer/Azure.AI.FormRecognizer/README.md#authenticate-a-form-recognizer-client"/>
        public FormRecognizerClient(Uri endpoint, AzureKeyCredential credential, FormRecognizerClientOptions options)
        {
            Argument.AssertNotNull(endpoint, nameof(endpoint));
            Argument.AssertNotNull(credential, nameof(credential));
            Argument.AssertNotNull(options, nameof(options));

            _endpoint   = endpoint;
            _credential = credential;

            Diagnostics = new ClientDiagnostics(options);
            var pipeline = HttpPipelineBuilder.Build(options, new AzureKeyCredentialPolicy(_credential, Constants.AuthorizationHeader));

            ServiceClient = new ServiceClient(Diagnostics, pipeline, _endpoint.ToString());
        }
예제 #17
0
    public AuthenticatedGateway(IHttpClientFactory httpClientFactory, ILogger <AuthenticatedGateway> logger)
    {
        var options = new ClientOptions(new Uri("https://httppipeline.azurewebsites.net"), httpClientFactory, logger)
        {
            Retry =
            {
                MaxRetries = 10
            }
        };

        options.AddPolicy(HttpPipelinePosition.BeforeTransport, new AuthenticatedGatewayBearerTokenPolicy("username", "password"));

        _httpPipeline = HttpPipelineBuilder.Build(options);
    }
        public async Task DoesntDisposeRequestInSendRequestAsync()
        {
            HttpPipeline httpPipeline = HttpPipelineBuilder.Build(new TestOptions()
            {
                Transport = new MockTransport(new MockResponse(200))
            });

            using MockRequest request = (MockRequest)httpPipeline.CreateRequest();

            MockResponse response = (MockResponse)await httpPipeline.SendRequestAsync(request, default);

            Assert.False(request.IsDisposed);
            Assert.False(response.IsDisposed);
        }
예제 #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormTrainingClient"/> class.
        /// </summary>
        /// <param name="endpoint">The endpoint to use for connecting to the Form Recognizer Azure Cognitive Service.</param>
        /// <param name="credential">A credential used to authenticate to an Azure Service.</param>
        /// <param name="options">A set of options to apply when configuring the client.</param>
        /// <remarks>
        /// The <paramref name="endpoint"/> URI string can be found in the Azure Portal.
        /// For more information see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/formrecognizer/Azure.AI.FormRecognizer/README.md#authenticate-a-form-recognizer-client"> here</see>.
        /// </remarks>
        public FormTrainingClient(Uri endpoint, TokenCredential credential, FormRecognizerClientOptions options)
        {
            Argument.AssertNotNull(endpoint, nameof(endpoint));
            Argument.AssertNotNull(credential, nameof(credential));
            Argument.AssertNotNull(options, nameof(options));

            string defaultScope = $"{(string.IsNullOrEmpty(options.Audience?.ToString()) ? FormRecognizerAudience.AzurePublicCloud : options.Audience)}/.default";

            Diagnostics    = new ClientDiagnostics(options);
            ServiceVersion = options.Version;
            var pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, defaultScope));

            ServiceClient = new FormRecognizerRestClient(Diagnostics, pipeline, endpoint.AbsoluteUri, FormRecognizerClientOptions.GetVersionString(ServiceVersion));
        }
예제 #20
0
        /// <summary>
        /// Initializes a new instance of <see cref="MetricsQueryClient"/>.
        /// </summary>
        /// <param name="endpoint">The resource manager service endpoint to use. For example <c>https://management.azure.com/</c> for public cloud.</param>
        /// <param name="credential">The <see cref="TokenCredential"/> instance to use for authentication.</param>
        /// <param name="options">The <see cref="MetricsQueryClientOptions"/> instance to as client configuration.</param>
        public MetricsQueryClient(Uri endpoint, TokenCredential credential, MetricsQueryClientOptions options = null)
        {
            Argument.AssertNotNull(credential, nameof(credential));

            options ??= new MetricsQueryClientOptions();

            _clientDiagnostics = new ClientDiagnostics(options);

            var pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, "https://management.azure.com//.default"));

            _metricDefinitionsClient = new MetricDefinitionsRestClient(_clientDiagnostics, pipeline, endpoint);
            _metricsRestClient       = new MetricsRestClient(_clientDiagnostics, pipeline, endpoint);
            _namespacesRestClient    = new MetricNamespacesRestClient(_clientDiagnostics, pipeline, endpoint);
        }
        public DnsManagementClient(string subscriptionId, Uri endpoint, TokenCredential tokenCredential, DnsManagementClientOptions options = null)
        {
            if (subscriptionId == null)
            {
                throw new ArgumentNullException(nameof(subscriptionId));
            }
            endpoint ??= new Uri("https://management.azure.com");

            options ??= new DnsManagementClientOptions();
            _clientDiagnostics = new ClientDiagnostics(options);
            _pipeline          = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(tokenCredential, $"{endpoint}/.default"));
            _subscriptionId    = subscriptionId;
            _endpoint          = endpoint;
        }
        public async Task CustomPolicyOrdering()
        {
            bool perCallRan         = false;
            bool perRetryRan        = false;
            bool beforeTransportRan = false;

            var transport = new MockTransport(new MockResponse(200));
            var options   = new TestOptions();

            options.AddPolicy(new CallbackPolicy(m =>
            {
                perCallRan = true;
                Assert.False(perRetryRan);
                Assert.False(beforeTransportRan);
            }), HttpPipelinePosition.PerCall);

            options.AddPolicy(new CallbackPolicy(m =>
            {
                perRetryRan = true;
                Assert.True(perCallRan);
                Assert.False(beforeTransportRan);
            }), HttpPipelinePosition.PerRetry);

            // Intentionally add some null policies to ensure it does not break indexing
            options.AddPolicy(null, HttpPipelinePosition.PerCall);
            options.AddPolicy(null, HttpPipelinePosition.PerRetry);
            options.AddPolicy(null, HttpPipelinePosition.BeforeTransport);

            options.AddPolicy(new CallbackPolicy(m =>
            {
                beforeTransportRan = true;
                Assert.True(perRetryRan);
                Assert.True(perCallRan);
            }), HttpPipelinePosition.BeforeTransport);

            options.Transport = transport;

            HttpPipeline pipeline = HttpPipelineBuilder.Build(options);

            using Request request = transport.CreateRequest();
            request.Method        = RequestMethod.Get;
            request.Uri.Reset(new Uri("http://example.com"));

            await pipeline.SendRequestAsync(request, CancellationToken.None);

            Assert.True(perRetryRan);
            Assert.True(perCallRan);
            Assert.True(beforeTransportRan);
        }
예제 #23
0
        /// <summary>
        /// </summary>
        public ContainerRegistryClient(Uri endpoint, TokenCredential credential, ContainerRegistryClientOptions options)
        {
            Argument.AssertNotNull(endpoint, nameof(endpoint));
            Argument.AssertNotNull(credential, nameof(credential));
            Argument.AssertNotNull(options, nameof(options));

            _endpoint          = endpoint;
            _clientDiagnostics = new ClientDiagnostics(options);

            _acrAuthPipeline = HttpPipelineBuilder.Build(options);
            _acrAuthClient   = new AuthenticationRestClient(_clientDiagnostics, _acrAuthPipeline, endpoint.AbsoluteUri);

            _pipeline   = HttpPipelineBuilder.Build(options, new ContainerRegistryChallengeAuthenticationPolicy(credential, AcrAadScope, _acrAuthClient));
            _restClient = new ContainerRegistryRestClient(_clientDiagnostics, _pipeline, _endpoint.AbsoluteUri);
        }
        /// <summary>
        /// Constructs a new instance of a TextAnalyticsClient using the given endpoint, credentials and options.
        /// </summary>
        /// <param name="endpoint">The endpoint to use.</param>
        /// <param name="credential">The credentials to use.</param>
        /// <param name="options">Options to control the underlying operations.</param>
        public TextAnalyticsClient(Uri endpoint, AzureKeyCredential credential, ProtocolClientOptions options)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }

            if (credential == null)
            {
                throw new ArgumentNullException(nameof(credential));
            }

            Endpoint = endpoint;
            Pipeline = HttpPipelineBuilder.Build(options, new AzureKeyCredentialPolicy(credential, AuthorizationHeader));
        }
예제 #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RemoteRenderingClient" /> class.
        /// </summary>
        /// <param name="remoteRenderingEndpoint">The rendering service endpoint. This determines the region in which the rendering VM is created.</param>
        /// <param name="account">The Azure Remote Rendering account details.</param>
        /// <param name="credential">The credential used to access the Mixed Reality service.</param>
        /// <param name="options">The options.</param>
        public RemoteRenderingClient(Uri remoteRenderingEndpoint, RemoteRenderingAccount account, TokenCredential credential, RemoteRenderingClientOptions options = null)
        {
            Argument.AssertNotNull(account, nameof(account));
            Argument.AssertNotNull(credential, nameof(credential));

            options ??= new RemoteRenderingClientOptions();

            Uri             authenticationEndpoint = options.AuthenticationEndpoint ?? AuthenticationEndpoint.ConstructFromDomain(account.AccountDomain);
            TokenCredential mrTokenCredential      = MixedRealityTokenCredential.GetMixedRealityCredential(account.AccountId, authenticationEndpoint, credential);

            _accountId         = account.AccountId;
            _clientDiagnostics = new ClientDiagnostics(options);
            _pipeline          = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(mrTokenCredential, GetDefaultScope(remoteRenderingEndpoint)));
            _restClient        = new RemoteRenderingRestClient(_clientDiagnostics, _pipeline, remoteRenderingEndpoint.ToString(), options.Version);
        }
예제 #26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ConversationAnalysisClient"/> class.
        /// </summary>
        /// <param name="endpoint">The Conversation Analysis endpoint on which to operate.</param>
        /// <param name="credential">An <see cref="AzureKeyCredential"/> used to authenticate requests to the <paramref name="endpoint"/>.</param>
        /// <param name="options">Optional <see cref="ConversationAnalysisClientOptions"/> to customize requests sent to the endpoint.</param>
        /// <exception cref="ArgumentNullException"><paramref name="endpoint"/> or <paramref name="credential"/> is null.</exception>
        public ConversationAnalysisClient(Uri endpoint, AzureKeyCredential credential, ConversationAnalysisClientOptions options)
        {
            Argument.AssertNotNull(endpoint, nameof(endpoint));
            Argument.AssertNotNull(credential, nameof(credential));

            Endpoint = endpoint;
            options ??= new ConversationAnalysisClientOptions();

            Diagnostics = new ClientDiagnostics(options);
            Pipeline    = HttpPipelineBuilder.Build(
                options,
                new AzureKeyCredentialPolicy(credential, AuthorizationHeader));

            _analysisRestClient = new(Diagnostics, Pipeline, Endpoint, options.Version);
        }
예제 #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="QuestionAnsweringClient"/> class.
        /// </summary>
        /// <param name="endpoint">The Question Answering endpoint on which to operate.</param>
        /// <param name="credential">An <see cref="AzureKeyCredential"/> used to authenticate requests to the <paramref name="endpoint"/>.</param>
        /// <param name="options">Optional <see cref="QuestionAnsweringClientOptions"/> to customize requests sent to the endpoint.</param>
        /// <exception cref="ArgumentNullException"><paramref name="endpoint"/> or <paramref name="credential"/> is null.</exception>
        public QuestionAnsweringClient(Uri endpoint, AzureKeyCredential credential, QuestionAnsweringClientOptions options)
        {
            Argument.AssertNotNull(endpoint, nameof(endpoint));
            Argument.AssertNotNull(credential, nameof(credential));

            Endpoint = endpoint;
            Options  = options ?? new QuestionAnsweringClientOptions();

            Diagnostics = new ClientDiagnostics(Options);
            Pipeline    = HttpPipelineBuilder.Build(
                Options,
                new AzureKeyCredentialPolicy(credential, AuthorizationHeader));

            _restClient = new(Diagnostics, Pipeline, Endpoint, Options.Version);
        }
        public AnomalyDetectorClient(Uri endpoint, AzureKeyCredential credential, AnomalyDetectorClientOptions options)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }

            if (credential == null)
            {
                throw new ArgumentNullException(nameof(credential));
            }

            Endpoint     = endpoint;
            HttpPipeline = HttpPipelineBuilder.Build(options, new AzureKeyCredentialPolicy(credential, AuthorizationHeader));
        }
        public async Task CanAddPolicies_ThreeWays()
        {
            var mockTransport = new MockTransport(new MockResponse(200));

            var clientOptions = new TestOptions()
            {
                Transport = mockTransport,
            };
            var perCallPolicies  = new HttpPipelinePolicy[] { new AddHeaderPolicy("PerCall", "Builder") };
            var perRetryPolicies = new HttpPipelinePolicy[] { new AddHeaderPolicy("PerRetry", "Builder") };

            clientOptions.AddPolicy(new AddHeaderPolicy("BeforeTransport", "ClientOptions"), HttpPipelinePosition.BeforeTransport);
            clientOptions.AddPolicy(new AddHeaderPolicy("PerRetry", "ClientOptions"), HttpPipelinePosition.PerRetry);
            clientOptions.AddPolicy(new AddHeaderPolicy("PerCall", "ClientOptions"), HttpPipelinePosition.PerCall);

            var pipeline = HttpPipelineBuilder.Build(clientOptions, perCallPolicies, perRetryPolicies, null);

            var options = new RequestOptions();

            options.AddPolicy(new AddHeaderPolicy("PerRetry", "RequestContext"), HttpPipelinePosition.PerRetry);
            options.AddPolicy(new AddHeaderPolicy("PerCall", "RequestContext"), HttpPipelinePosition.PerCall);
            options.AddPolicy(new AddHeaderPolicy("BeforeTransport", "RequestContext"), HttpPipelinePosition.BeforeTransport);

            var context = new RequestContext(options);

            context.CancellationToken = default;
            var message = pipeline.CreateMessage(context);
            await pipeline.SendAsync(message, message.CancellationToken);

            Request request = mockTransport.Requests[0];

            Assert.IsTrue(request.Headers.TryGetValues("PerCall", out var perCallValues));
            Assert.AreEqual(3, perCallValues.Count());
            Assert.AreEqual("Builder", perCallValues.ElementAt(0));
            Assert.AreEqual("ClientOptions", perCallValues.ElementAt(1));
            Assert.AreEqual("RequestContext", perCallValues.ElementAt(2));

            Assert.IsTrue(request.Headers.TryGetValues("PerRetry", out var perRetryValues));
            Assert.AreEqual(3, perRetryValues.Count());
            Assert.AreEqual("Builder", perRetryValues.ElementAt(0));
            Assert.AreEqual("ClientOptions", perRetryValues.ElementAt(1));
            Assert.AreEqual("RequestContext", perRetryValues.ElementAt(2));

            Assert.IsTrue(request.Headers.TryGetValues("BeforeTransport", out var beforeTransportValues));
            Assert.AreEqual(2, beforeTransportValues.Count());
            Assert.AreEqual("ClientOptions", beforeTransportValues.ElementAt(0));
            Assert.AreEqual("RequestContext", beforeTransportValues.ElementAt(1));
        }
예제 #30
0
        /// <summary>
        /// Creates a new SharedTokenCacheCredential with the specifeid options, which will authenticate users with the specified application.
        /// </summary>
        /// <param name="clientId">The client id of the application to which the users will authenticate</param>
        /// <param name="username">The username of the user to authenticate</param>
        /// TODO: need to link to info on how the application has to be created to authenticate users, for multiple applications
        /// <param name="options">The client options for the newly created SharedTokenCacheCredential</param>
        public SharedTokenCacheCredential(string clientId, string username, SharedTokenCacheCredentialOptions options)
        {
            _clientId = clientId ?? Constants.DeveloperSignOnClientId;

            options ??= new SharedTokenCacheCredentialOptions();

            _username = username;

            HttpPipeline pipeline = HttpPipelineBuilder.Build(options);

            _pubApp = PublicClientApplicationBuilder.Create(_clientId).WithHttpClientFactory(new HttpPipelineClientFactory(pipeline)).Build();

            _cacheReader = new MsalCacheReader(_pubApp.UserTokenCache, options.CacheFilePath, options.CacheAccessRetryCount, options.CacheAccessRetryDelay);

            _account = new Lazy <Task <IAccount> >(GetAccountAsync);
        }