private HttpClientHandler CreateHttpClientHandler(CosmosClientOptions clientOptions)
        {
            if (clientOptions == null || (clientOptions.WebProxy == null))
            {
                return(null);
            }

            HttpClientHandler httpClientHandler = new HttpClientHandler();

            httpClientHandler.Proxy = clientOptions.WebProxy;

            return(httpClientHandler);
        }
Beispiel #2
0
        private static HttpClientHandler CreateHttpClientHandler(CosmosClientOptions clientOptions)
        {
            if (clientOptions == null || clientOptions.WebProxy == null)
            {
                return(null);
            }

            HttpClientHandler httpClientHandler = new HttpClientHandler
            {
                Proxy = clientOptions.WebProxy
            };

            return(httpClientHandler);
        }
Beispiel #3
0
 internal ClientContextCore(
     CosmosClient client,
     CosmosClientOptions clientOptions,
     CosmosSerializerCore serializerCore,
     CosmosResponseFactory cosmosResponseFactory,
     RequestInvokerHandler requestHandler,
     DocumentClient documentClient)
 {
     this.Client          = client;
     this.ClientOptions   = clientOptions;
     this.SerializerCore  = serializerCore;
     this.ResponseFactory = cosmosResponseFactory;
     this.RequestHandler  = requestHandler;
     this.DocumentClient  = documentClient;
 }
        internal static CosmosClientContext Create(
            CosmosClient cosmosClient,
            DocumentClient documentClient,
            CosmosClientOptions clientOptions,
            RequestInvokerHandler requestInvokerHandler = null)
        {
            if (cosmosClient == null)
            {
                throw new ArgumentNullException(nameof(cosmosClient));
            }

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

            clientOptions = ClientContextCore.CreateOrCloneClientOptions(clientOptions);

            if (requestInvokerHandler == null)
            {
                //Request pipeline
                ClientPipelineBuilder clientPipelineBuilder = new ClientPipelineBuilder(
                    cosmosClient,
                    clientOptions.ConsistencyLevel,
                    clientOptions.CustomHandlers);

                requestInvokerHandler = clientPipelineBuilder.Build();
            }

            CosmosSerializerCore serializerCore = CosmosSerializerCore.Create(
                clientOptions.Serializer,
                clientOptions.SerializerOptions);

            // This sets the serializer on client options which gives users access to it if a custom one is not configured.
            clientOptions.SetSerializerIfNotConfigured(serializerCore.GetCustomOrDefaultSerializer());

            CosmosResponseFactoryInternal responseFactory = new CosmosResponseFactoryCore(serializerCore);

            return(new ClientContextCore(
                       client: cosmosClient,
                       clientOptions: clientOptions,
                       serializerCore: serializerCore,
                       cosmosResponseFactory: responseFactory,
                       requestHandler: requestInvokerHandler,
                       documentClient: documentClient,
                       userAgent: documentClient.ConnectionPolicy.UserAgentContainer.UserAgent,
                       batchExecutorCache: new BatchAsyncContainerExecutorCache()));
        }
        /// <summary>
        /// Used for unit testing only.
        /// </summary>
        internal CosmosClient(
            CosmosClientOptions cosmosClientOptions,
            DocumentClient documentClient)
        {
            if (cosmosClientOptions == null)
            {
                throw new ArgumentNullException(nameof(cosmosClientOptions));
            }

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

            this.Init(cosmosClientOptions, documentClient);
        }
        private static HttpClientHandler CreateHttpClientHandler(CosmosClientOptions clientOptions)
        {
            if (clientOptions == null)
            {
                throw new ArgumentNullException(nameof(clientOptions));
            }

            // https://docs.microsoft.com/en-us/archive/blogs/timomta/controlling-the-number-of-outgoing-connections-from-httpclient-net-core-or-full-framework
            HttpClientHandler httpClientHandler = new HttpClientHandler
            {
                Proxy = clientOptions.WebProxy,
                MaxConnectionsPerServer = clientOptions.GatewayModeMaxConnectionLimit
            };

            return(httpClientHandler);
        }
Beispiel #7
0
        internal static CosmosClientContext Create(
            CosmosClient cosmosClient,
            DocumentClient documentClient,
            CosmosClientOptions clientOptions,
            RequestInvokerHandler requestInvokerHandler = null)
        {
            if (cosmosClient == null)
            {
                throw new ArgumentNullException(nameof(cosmosClient));
            }

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

            clientOptions = ClientContextCore.CreateOrCloneClientOptions(clientOptions);

            if (requestInvokerHandler == null)
            {
                //Request pipeline
                ClientPipelineBuilder clientPipelineBuilder = new ClientPipelineBuilder(
                    cosmosClient,
                    clientOptions.ConsistencyLevel,
                    clientOptions.CustomHandlers);

                requestInvokerHandler = clientPipelineBuilder.Build();
            }

            CosmosSerializerCore serializerCore = CosmosSerializerCore.Create(
                clientOptions.Serializer,
                clientOptions.SerializerOptions);

            CosmosResponseFactory responseFactory = new CosmosResponseFactory(serializerCore);

            return(new ClientContextCore(
                       client: cosmosClient,
                       clientOptions: clientOptions,
                       serializerCore: serializerCore,
                       cosmosResponseFactory: responseFactory,
                       requestHandler: requestInvokerHandler,
                       documentClient: documentClient,
                       userAgent: documentClient.ConnectionPolicy.UserAgentContainer.UserAgent,
                       encryptionProcessor: new EncryptionProcessor(),
                       dekCache: new DekCache(),
                       batchExecutorCache: new BatchAsyncContainerExecutorCache()));
        }
Beispiel #8
0
        /// <summary>
        /// Extracts the account endpoint and key from the connection string.
        /// </summary>
        /// <example>"AccountEndpoint=https://mytestcosmosaccount.documents.azure.com:443/;AccountKey={SecretAccountKey};"</example>
        /// <param name="connectionString">The connection string must contain AccountEndpoint and AccountKey.</param>
        public CosmosClientOptions(string connectionString)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentNullException(nameof(connectionString));
            }

            DbConnectionStringBuilder builder = new DbConnectionStringBuilder {
                ConnectionString = connectionString
            };

            this.EndPoint = new Uri(CosmosClientOptions.GetValueFromSqlConnectionString(builder,
                                                                                        CosmosClientOptions.ConnectionStringAccountEndpoint));
            this.AccountKey = CosmosClientOptions.GetValueFromSqlConnectionString(builder, CosmosClientOptions.ConnectionStringAccountKey);

            this.Initialize();
        }
 private ClientContextCore(
     CosmosClient client,
     CosmosClientOptions clientOptions,
     CosmosSerializerCore serializerCore,
     CosmosResponseFactoryInternal cosmosResponseFactory,
     RequestInvokerHandler requestHandler,
     DocumentClient documentClient,
     string userAgent,
     BatchAsyncContainerExecutorCache batchExecutorCache)
 {
     this.client             = client;
     this.clientOptions      = clientOptions;
     this.serializerCore     = serializerCore;
     this.responseFactory    = cosmosResponseFactory;
     this.requestHandler     = requestHandler;
     this.documentClient     = documentClient;
     this.userAgent          = userAgent;
     this.batchExecutorCache = batchExecutorCache;
 }
Beispiel #10
0
 internal ClientContextCore(
     CosmosClient client,
     CosmosClientOptions clientOptions,
     CosmosSerializer userJsonSerializer,
     CosmosSerializer defaultJsonSerializer,
     CosmosResponseFactory cosmosResponseFactory,
     RequestInvokerHandler requestHandler,
     DocumentClient documentClient,
     IDocumentQueryClient documentQueryClient)
 {
     this.Client               = client;
     this.ClientOptions        = clientOptions;
     this.CosmosSerializer     = userJsonSerializer;
     this.PropertiesSerializer = defaultJsonSerializer;
     this.ResponseFactory      = cosmosResponseFactory;
     this.RequestHandler       = requestHandler;
     this.DocumentClient       = documentClient;
     this.DocumentQueryClient  = documentQueryClient;
 }
        /// <summary>
        /// Creates a new CosmosClient with the account endpoint URI string and account key.
        ///
        /// CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime
        /// of the application which enables efficient connection management and performance. Please refer to the
        /// <see href="https://docs.microsoft.com/azure/cosmos-db/performance-tips">performance guide</see>.
        /// </summary>
        /// <param name="accountEndpoint">The cosmos service endpoint to use</param>
        /// <param name="authKeyOrResourceToken">The cosmos account key or resource token to use to create the client.</param>
        /// <param name="clientOptions">(Optional) client options</param>
        /// <example>
        /// The CosmosClient is created with the AccountEndpoint, AccountKey or ResourceToken and configured to use "East US 2" region.
        /// <code language="c#">
        /// <![CDATA[
        /// using Microsoft.Azure.Cosmos;
        ///
        /// CosmosClient cosmosClient = new CosmosClient(
        ///             "account-endpoint-from-portal",
        ///             "account-key-from-portal",
        ///             new CosmosClientOptions()
        ///             {
        ///                 ApplicationRegion = Regions.EastUS2,
        ///             });
        ///
        /// // Dispose cosmosClient at application exit
        /// ]]>
        /// </code>
        /// </example>
        /// <seealso cref="CosmosClientOptions"/>
        /// <seealso cref="Fluent.CosmosClientBuilder"/>
        /// <seealso href="https://docs.microsoft.com/azure/cosmos-db/performance-tips">Performance Tips</seealso>
        /// <seealso href="https://docs.microsoft.com/azure/cosmos-db/troubleshoot-dot-net-sdk">Diagnose and troubleshoot issues</seealso>
        public CosmosClient(
            string accountEndpoint,
            string authKeyOrResourceToken,
            CosmosClientOptions clientOptions = null)
        {
            if (accountEndpoint == null)
            {
                throw new ArgumentNullException(nameof(accountEndpoint));
            }

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

            if (clientOptions == null)
            {
                clientOptions = new CosmosClientOptions();
            }

            this.Endpoint   = new Uri(accountEndpoint);
            this.AccountKey = authKeyOrResourceToken;
            CosmosClientOptions clientOptionsClone = clientOptions.Clone();

            DocumentClient documentClient = new DocumentClient(
                this.Endpoint,
                this.AccountKey,
                apitype: clientOptionsClone.ApiType,
                sendingRequestEventArgs: clientOptionsClone.SendingRequestEventArgs,
                transportClientHandlerFactory: clientOptionsClone.TransportClientHandlerFactory,
                connectionPolicy: clientOptionsClone.GetConnectionPolicy(),
                enableCpuMonitor: clientOptionsClone.EnableCpuMonitor,
                storeClientFactory: clientOptionsClone.StoreClientFactory,
                desiredConsistencyLevel: clientOptionsClone.GetDocumentsConsistencyLevel(),
                handler: this.CreateHttpClientHandler(clientOptions),
                sessionContainer: clientOptionsClone.SessionContainer);

            this.Init(
                clientOptionsClone,
                documentClient);
        }
 internal ClientContextCore(
     CosmosClient client,
     CosmosClientOptions clientOptions,
     CosmosSerializerCore serializerCore,
     CosmosResponseFactory cosmosResponseFactory,
     RequestInvokerHandler requestHandler,
     DocumentClient documentClient,
     string userAgent,
     EncryptionProcessor encryptionProcessor = null,
     DekCache dekCache = null)
 {
     this.Client              = client;
     this.ClientOptions       = clientOptions;
     this.SerializerCore      = serializerCore;
     this.ResponseFactory     = cosmosResponseFactory;
     this.RequestHandler      = requestHandler;
     this.DocumentClient      = documentClient;
     this.UserAgent           = userAgent;
     this.EncryptionProcessor = encryptionProcessor;
     this.DekCache            = dekCache;
 }
Beispiel #13
0
        /// <summary>
        /// Creates a new CosmosClient with the account endpoint URI string and account key.
        ///
        /// CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime
        /// of the application which enables efficient connection management and performance. Please refer to the
        /// <see href="https://docs.microsoft.com/azure/cosmos-db/performance-tips">performance guide</see>.
        /// </summary>
        /// <param name="accountEndpoint">The cosmos service endpoint to use</param>
        /// <param name="authKeyOrResourceToken">The cosmos account key or resource token to use to create the client.</param>
        /// <param name="clientOptions">(Optional) client options</param>
        /// <example>
        /// The CosmosClient is created with the AccountEndpoint, AccountKey or ResourceToken and configured to use "East US 2" region.
        /// <code language="c#">
        /// <![CDATA[
        /// using Microsoft.Azure.Cosmos;
        ///
        /// CosmosClient cosmosClient = new CosmosClient(
        ///             "account-endpoint-from-portal",
        ///             "account-key-from-portal",
        ///             new CosmosClientOptions()
        ///             {
        ///                 ApplicationRegion = Regions.EastUS2,
        ///             });
        ///
        /// // Dispose cosmosClient at application exit
        /// ]]>
        /// </code>
        /// </example>
        /// <seealso cref="CosmosClientOptions"/>
        /// <seealso cref="Fluent.CosmosClientBuilder"/>
        /// <seealso href="https://docs.microsoft.com/azure/cosmos-db/performance-tips">Performance Tips</seealso>
        /// <seealso href="https://docs.microsoft.com/azure/cosmos-db/troubleshoot-dot-net-sdk">Diagnose and troubleshoot issues</seealso>
        public CosmosClient(
            string accountEndpoint,
            string authKeyOrResourceToken,
            CosmosClientOptions clientOptions = null)
        {
            if (string.IsNullOrEmpty(accountEndpoint))
            {
                throw new ArgumentNullException(nameof(accountEndpoint));
            }

            if (string.IsNullOrEmpty(authKeyOrResourceToken))
            {
                throw new ArgumentNullException(nameof(authKeyOrResourceToken));
            }

            this.Endpoint   = new Uri(accountEndpoint);
            this.AccountKey = authKeyOrResourceToken;

            this.ClientContext = ClientContextCore.Create(
                this,
                clientOptions);
        }
        /// <summary>
        /// Create a new CosmosClient with the account endpoint URI string and account key
        /// </summary>
        /// <param name="accountEndpoint">The cosmos service endpoint to use to create the client.</param>
        /// <param name="accountKey">The cosmos account key to use to create the client.</param>
        /// <param name="clientOptions">(Optional) client options</param>
        /// <example>
        /// This example creates a CosmosClient
        /// <code language="c#">
        /// <![CDATA[
        /// using (CosmosClient cosmosClient = new CosmosClient(
        ///     accountEndPoint: "https://testcosmos.documents.azure.com:443/",
        ///     accountKey: "SuperSecretKey"))
        /// {
        ///     // Create a database and other CosmosClient operations
        /// }
        /// ]]>
        /// </code>
        /// </example>
        public CosmosClient(
            string accountEndpoint,
            string accountKey,
            CosmosClientOptions clientOptions = null)
        {
            if (accountEndpoint == null)
            {
                throw new ArgumentNullException(nameof(accountEndpoint));
            }

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

            if (clientOptions == null)
            {
                clientOptions = new CosmosClientOptions();
            }

            this.Endpoint   = new Uri(accountEndpoint);
            this.AccountKey = accountKey;
            CosmosClientOptions clientOptionsClone = clientOptions.Clone();

            DocumentClient documentClient = new DocumentClient(
                this.Endpoint,
                this.AccountKey,
                apitype: clientOptionsClone.ApiType,
                sendingRequestEventArgs: clientOptionsClone.SendingRequestEventArgs,
                transportClientHandlerFactory: clientOptionsClone.TransportClientHandlerFactory,
                connectionPolicy: clientOptionsClone.GetConnectionPolicy(),
                enableCpuMonitor: clientOptionsClone.EnableCpuMonitor,
                storeClientFactory: clientOptionsClone.StoreClientFactory);

            this.Init(
                clientOptionsClone,
                documentClient);
        }
Beispiel #15
0
        /// <summary>
        /// Creates a new CosmosClient with the account endpoint URI string and account key.
        ///
        /// CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime
        /// of the application which enables efficient connection management and performance. Please refer to the
        /// <see href="https://docs.microsoft.com/azure/cosmos-db/performance-tips">performance guide</see>.
        /// </summary>
        /// <param name="accountEndpoint">The cosmos service endpoint to use</param>
        /// <param name="authKeyOrResourceToken">The cosmos account key or resource token to use to create the client.</param>
        /// <param name="clientOptions">(Optional) client options</param>
        /// <example>
        /// The CosmosClient is created with the AccountEndpoint, AccountKey or ResourceToken and configured to use "East US 2" region.
        /// <code language="c#">
        /// <![CDATA[
        /// using Microsoft.Azure.Cosmos;
        ///
        /// CosmosClient cosmosClient = new CosmosClient(
        ///             "account-endpoint-from-portal",
        ///             "account-key-from-portal",
        ///             new CosmosClientOptions()
        ///             {
        ///                 ApplicationRegion = Regions.EastUS2,
        ///             });
        ///
        /// // Dispose cosmosClient at application exit
        /// ]]>
        /// </code>
        /// </example>
        /// <seealso cref="CosmosClientOptions"/>
        /// <seealso cref="Fluent.CosmosClientBuilder"/>
        /// <seealso href="https://docs.microsoft.com/azure/cosmos-db/performance-tips">Performance Tips</seealso>
        /// <seealso href="https://docs.microsoft.com/azure/cosmos-db/troubleshoot-dot-net-sdk">Diagnose and troubleshoot issues</seealso>
        public CosmosClient(
            string accountEndpoint,
            string authKeyOrResourceToken,
            CosmosClientOptions clientOptions = null)
        {
            if (accountEndpoint == null)
            {
                throw new ArgumentNullException(nameof(accountEndpoint));
            }

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

            if (clientOptions == null)
            {
                clientOptions = new CosmosClientOptions();
            }

            this.Endpoint   = new Uri(accountEndpoint);
            this.AccountKey = authKeyOrResourceToken;
            CosmosClientOptions clientOptionsClone = clientOptions.Clone();

            DocumentClient documentClient = new DocumentClient(
                this.Endpoint,
                this.AccountKey,
                apitype: clientOptionsClone.ApiType,
                sendingRequestEventArgs: clientOptionsClone.SendingRequestEventArgs,
                transportClientHandlerFactory: clientOptionsClone.TransportClientHandlerFactory,
                connectionPolicy: clientOptionsClone.GetConnectionPolicy(),
                enableCpuMonitor: clientOptionsClone.EnableCpuMonitor,
                storeClientFactory: clientOptionsClone.StoreClientFactory,
                desiredConsistencyLevel: clientOptionsClone.GetDocumentsConsistencyLevel(),
                handler: this.CreateHttpClientHandler(clientOptions),
                sessionContainer: clientOptionsClone.SessionContainer);

            this.ClientOptions  = clientOptions;
            this.DocumentClient = documentClient;

            //Request pipeline
            ClientPipelineBuilder clientPipelineBuilder = new ClientPipelineBuilder(
                this,
                this.ClientOptions.CustomHandlers);

            this.RequestHandler = clientPipelineBuilder.Build();

            CosmosSerializerCore serializerCore = CosmosSerializerCore.Create(
                this.ClientOptions.Serializer,
                this.ClientOptions.SerializerOptions);

            this.ResponseFactory = new CosmosResponseFactory(serializerCore);

            this.ClientContext = new ClientContextCore(
                client: this,
                clientOptions: this.ClientOptions,
                serializerCore: serializerCore,
                cosmosResponseFactory: this.ResponseFactory,
                requestHandler: this.RequestHandler,
                documentClient: this.DocumentClient,
                userAgent: this.DocumentClient.ConnectionPolicy.UserAgentContainer.UserAgent,
                encryptionProcessor: new EncryptionProcessor(),
                dekCache: new DekCache());
        }
        internal static CosmosClientContext Create(
            CosmosClient cosmosClient,
            DocumentClient documentClient,
            CosmosClientOptions clientOptions,
            RequestInvokerHandler requestInvokerHandler = null)
        {
            if (cosmosClient == null)
            {
                throw new ArgumentNullException(nameof(cosmosClient));
            }

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

            clientOptions = ClientContextCore.CreateOrCloneClientOptions(clientOptions);

            ConnectionPolicy connectionPolicy = clientOptions.GetConnectionPolicy(cosmosClient.ClientId);
            ClientTelemetry  telemetry        = null;

            if (connectionPolicy.EnableClientTelemetry)
            {
                try
                {
                    telemetry = ClientTelemetry.CreateAndStartBackgroundTelemetry(
                        documentClient: documentClient,
                        userAgent: connectionPolicy.UserAgentContainer.UserAgent,
                        connectionMode: connectionPolicy.ConnectionMode,
                        authorizationTokenProvider: cosmosClient.AuthorizationTokenProvider,
                        diagnosticsHelper: DiagnosticsHandlerHelper.Instance,
                        preferredRegions: clientOptions.ApplicationPreferredRegions);
                }
                catch (Exception ex)
                {
                    DefaultTrace.TraceInformation($"Error While starting Telemetry Job : {ex.Message}. Hence disabling Client Telemetry");
                    connectionPolicy.EnableClientTelemetry = false;
                }
            }
            else
            {
                DefaultTrace.TraceInformation("Client Telemetry Disabled.");
            }

            if (requestInvokerHandler == null)
            {
                //Request pipeline
                ClientPipelineBuilder clientPipelineBuilder = new ClientPipelineBuilder(
                    cosmosClient,
                    clientOptions.ConsistencyLevel,
                    clientOptions.CustomHandlers,
                    telemetry: telemetry);

                requestInvokerHandler = clientPipelineBuilder.Build();
            }

            CosmosSerializerCore serializerCore = CosmosSerializerCore.Create(
                clientOptions.Serializer,
                clientOptions.SerializerOptions);

            // This sets the serializer on client options which gives users access to it if a custom one is not configured.
            clientOptions.SetSerializerIfNotConfigured(serializerCore.GetCustomOrDefaultSerializer());

            CosmosResponseFactoryInternal responseFactory = new CosmosResponseFactoryCore(serializerCore);

            return(new ClientContextCore(
                       client: cosmosClient,
                       clientOptions: clientOptions,
                       serializerCore: serializerCore,
                       cosmosResponseFactory: responseFactory,
                       requestHandler: requestInvokerHandler,
                       documentClient: documentClient,
                       userAgent: documentClient.ConnectionPolicy.UserAgentContainer.UserAgent,
                       batchExecutorCache: new BatchAsyncContainerExecutorCache(),
                       telemetry: telemetry));
        }