public virtual async Task <T> SendAsync <T>(
            Uri resourceUri,
            ResourceType resourceType,
            OperationType operationType,
            RequestOptions requestOptions,
            CosmosContainerCore cosmosContainerCore,
            Cosmos.PartitionKey partitionKey,
            Stream streamPayload,
            Action <CosmosRequestMessage> requestEnricher,
            Func <CosmosResponseMessage, T> responseCreator,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (responseCreator == null)
            {
                throw new ArgumentNullException(nameof(responseCreator));
            }

            CosmosResponseMessage responseMessage = await this.SendAsync(
                resourceUri : resourceUri,
                resourceType : resourceType,
                operationType : operationType,
                requestOptions : requestOptions,
                cosmosContainerCore : cosmosContainerCore,
                partitionKey : partitionKey,
                streamPayload : streamPayload,
                requestEnricher : requestEnricher,
                cancellationToken : cancellationToken);

            return(responseCreator(responseMessage));
        }
示例#2
0
            internal CosmosChangeFeedResultSetIteratorCoreMock(
                CosmosContainerCore cosmosContainer,
                string continuationToken,
                int?maxItemCount,
                CosmosChangeFeedRequestOptions options) : base(cosmosContainer, continuationToken, maxItemCount, options)
            {
                List <CompositeContinuationToken> compositeContinuationTokens = new List <CompositeContinuationToken>()
                {
                    new CompositeContinuationToken()
                    {
                        Token = null,
                        Range = new Documents.Routing.Range <string>("A", "B", true, false)
                    }
                };

                string serialized = JsonConvert.SerializeObject(compositeContinuationTokens);

                this.compositeContinuationToken = StandByFeedContinuationToken.CreateAsync("containerRid", serialized, (string containerRid, Documents.Routing.Range <string> ranges, bool forceRefresh) =>
                {
                    IReadOnlyList <Documents.PartitionKeyRange> filteredRanges = new List <Documents.PartitionKeyRange>()
                    {
                        new Documents.PartitionKeyRange()
                        {
                            MinInclusive = "A", MaxExclusive = "B", Id = "0"
                        }
                    };

                    if (forceRefresh)
                    {
                        this.HasCalledForceRefresh = true;
                    }

                    return(Task.FromResult(filteredRanges));
                }).Result;
            }
        public static ChangeFeedPartitionKeyResultSetIteratorCore BuildResultSetIterator(
            string partitionKeyRangeId,
            string continuationToken,
            int?maxItemCount,
            CosmosContainerCore cosmosContainer,
            DateTime?startTime,
            bool startFromBeginning)
        {
            ChangeFeedRequestOptions requestOptions = new ChangeFeedRequestOptions();

            if (startTime.HasValue)
            {
                requestOptions.StartTime = startTime.Value;
            }
            else if (startFromBeginning)
            {
                requestOptions.StartTime = DateTime.MinValue;
            }

            return(new ChangeFeedPartitionKeyResultSetIteratorCore(
                       partitionKeyRangeId: partitionKeyRangeId,
                       continuationToken: continuationToken,
                       maxItemCount: maxItemCount,
                       clientContext: cosmosContainer.ClientContext,
                       cosmosContainer: cosmosContainer,
                       options: requestOptions));
        }
示例#4
0
        public async Task StandByFeedIterator_WithMaxItemCount()
        {
            await this.CreateRandomItems(2, randomPartitionKey : true);

            CosmosContainerCore itemsCore    = (CosmosContainerCore)this.Container;
            FeedIterator        feedIterator = itemsCore.GetStandByFeedIterator(maxItemCount: 1, requestOptions: new ChangeFeedRequestOptions()
            {
                StartTime = DateTime.MinValue
            });

            while (feedIterator.HasMoreResults)
            {
                using (CosmosResponseMessage responseMessage =
                           await feedIterator.FetchNextSetAsync(this.cancellationToken))
                {
                    if (responseMessage.IsSuccessStatusCode)
                    {
                        Collection <ToDoActivity> response = new CosmosJsonSerializerCore().FromStream <CosmosFeedResponseUtil <ToDoActivity> >(responseMessage.Content).Data;
                        if (response.Count > 0)
                        {
                            Assert.AreEqual(1, response.Count);
                            return;
                        }
                    }
                }
            }

            Assert.Fail("Found no batch with size 1");
        }
示例#5
0
        public void ApplyBuildConfiguration(
            DocumentServiceLeaseStoreManager customDocumentServiceLeaseStoreManager,
            CosmosContainerCore leaseContainer,
            string monitoredContainerRid,
            string instanceName,
            ChangeFeedLeaseOptions changeFeedLeaseOptions,
            ChangeFeedProcessorOptions changeFeedProcessorOptions,
            CosmosContainerCore monitoredContainer)
        {
            if (monitoredContainer == null)
            {
                throw new ArgumentNullException(nameof(monitoredContainer));
            }
            if (customDocumentServiceLeaseStoreManager == null && leaseContainer == null)
            {
                throw new ArgumentNullException(nameof(leaseContainer));
            }
            if (instanceName == null)
            {
                throw new ArgumentNullException("InstanceName is required for the processor to initialize.");
            }

            this.documentServiceLeaseStoreManager = customDocumentServiceLeaseStoreManager;
            this.leaseContainer             = leaseContainer;
            this.monitoredContainerRid      = monitoredContainerRid;
            this.instanceName               = instanceName;
            this.changeFeedProcessorOptions = changeFeedProcessorOptions;
            this.changeFeedLeaseOptions     = changeFeedLeaseOptions;
            this.monitoredContainer         = monitoredContainer;
        }
        public async Task ContainerContractTest()
        {
            ContainerResponse response = await this.cosmosDatabase.CreateContainerAsync(new Guid().ToString(), "/id");

            Assert.IsNotNull(response);
            Assert.IsTrue(response.RequestCharge > 0);
            Assert.IsNotNull(response.Headers);
            Assert.IsNotNull(response.Headers.ActivityId);

            CosmosContainerSettings containerSettings = response.Resource;

            Assert.IsNotNull(containerSettings.Id);
            Assert.IsNotNull(containerSettings.ResourceId);
            Assert.IsNotNull(containerSettings.ETag);
            Assert.IsTrue(containerSettings.LastModified.HasValue);

            Assert.IsNotNull(containerSettings.PartitionKeyPath);
            Assert.IsNotNull(containerSettings.PartitionKeyPathTokens);
            Assert.AreEqual(1, containerSettings.PartitionKeyPathTokens.Length);
            Assert.AreEqual("id", containerSettings.PartitionKeyPathTokens[0]);

            CosmosContainerCore containerCore = response.Container as CosmosContainerCore;

            Assert.IsNotNull(containerCore);
            Assert.IsNotNull(containerCore.LinkUri);
            Assert.IsFalse(containerCore.LinkUri.ToString().StartsWith("/"));

            Assert.IsTrue(containerSettings.LastModified.Value > new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), containerSettings.LastModified.Value.ToString());
        }
        public override Task <CosmosResponseMessage> ExecuteStoredProcedureStreamAsync(
            Cosmos.PartitionKey partitionKey,
            string storedProcedureId,
            Stream streamPayload,
            StoredProcedureRequestOptions requestOptions = null,
            CancellationToken cancellationToken          = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(storedProcedureId))
            {
                throw new ArgumentNullException(nameof(storedProcedureId));
            }

            CosmosContainerCore.ValidatePartitionKey(partitionKey, requestOptions);

            Uri linkUri = this.clientContext.CreateLink(
                parentLink: this.container.LinkUri.OriginalString,
                uriPathSegment: Paths.StoredProceduresPathSegment,
                id: storedProcedureId);

            return(this.ProcessStreamOperationAsync(
                       resourceUri: linkUri,
                       resourceType: ResourceType.StoredProcedure,
                       operationType: OperationType.ExecuteJavaScript,
                       partitionKey: partitionKey,
                       streamPayload: streamPayload,
                       requestOptions: requestOptions,
                       cancellationToken: cancellationToken));
        }
示例#8
0
        public FeedProcessorFactoryCore(
            CosmosContainerCore container,
            ChangeFeedProcessorOptions changeFeedProcessorOptions,
            DocumentServiceLeaseCheckpointer leaseCheckpointer,
            CosmosJsonSerializer cosmosJsonSerializer)
        {
            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }
            if (changeFeedProcessorOptions == null)
            {
                throw new ArgumentNullException(nameof(changeFeedProcessorOptions));
            }
            if (leaseCheckpointer == null)
            {
                throw new ArgumentNullException(nameof(leaseCheckpointer));
            }
            if (cosmosJsonSerializer == null)
            {
                throw new ArgumentNullException(nameof(cosmosJsonSerializer));
            }

            this.container = container;
            this.changeFeedProcessorOptions = changeFeedProcessorOptions;
            this.leaseCheckpointer          = leaseCheckpointer;
            this.cosmosJsonSerializer       = cosmosJsonSerializer;
        }
 internal CosmosScriptsCore(
     CosmosContainerCore container,
     CosmosClientContext clientContext)
 {
     this.container     = container;
     this.clientContext = clientContext;
 }
示例#10
0
        public virtual async Task <CosmosResponseMessage> SendAsync(
            Uri resourceUri,
            ResourceType resourceType,
            OperationType operationType,
            RequestOptions requestOptions,
            CosmosContainerCore cosmosContainerCore,
            object partitionKey,
            Stream streamPayload,
            Action <CosmosRequestMessage> requestEnricher,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (resourceUri == null)
            {
                throw new ArgumentNullException(nameof(resourceUri));
            }

            HttpMethod method = RequestInvokerHandler.GetHttpMethod(operationType);

            CosmosRequestMessage request = new CosmosRequestMessage(method, resourceUri)
            {
                OperationType  = operationType,
                ResourceType   = resourceType,
                RequestOptions = requestOptions,
                Content        = streamPayload
            };

            if (partitionKey != null)
            {
                if (cosmosContainerCore == null && Object.ReferenceEquals(partitionKey, CosmosContainerSettings.NonePartitionKeyValue))
                {
                    throw new ArgumentException($"{nameof(cosmosContainerCore)} can not be null with partition key as PartitionKey.None");
                }
                else if (Object.ReferenceEquals(partitionKey, CosmosContainerSettings.NonePartitionKeyValue))
                {
                    try
                    {
                        PartitionKeyInternal partitionKeyInternal = await cosmosContainerCore.GetNonePartitionKeyValueAsync(cancellationToken);

                        request.Headers.PartitionKey = partitionKeyInternal.ToJsonString();
                    }
                    catch (DocumentClientException dce)
                    {
                        return(dce.ToCosmosResponseMessage(request));
                    }
                }
                else
                {
                    PartitionKey pk = new PartitionKey(partitionKey);
                    request.Headers.PartitionKey = pk.InternalKey.ToJsonString();
                }
            }

            if (operationType == OperationType.Upsert)
            {
                request.Headers.IsUpsert = bool.TrueString;
            }

            requestEnricher?.Invoke(request);
            return(await this.SendAsync(request, cancellationToken));
        }
        public void ValidateUriGenerationForResources()
        {
            string databaseId = "db1234";
            string crId       = "cr42";
            string spId       = "sp9001";
            string trId       = "tr9002";
            string udfId      = "udf9003";

            CosmosClient       mockClient = MockDocumentClient.CreateMockCosmosClient();
            CosmosDatabaseCore db         = new CosmosDatabaseCore(mockClient, databaseId);

            Assert.AreEqual(db.LinkUri.OriginalString, "/dbs/" + databaseId);

            CosmosContainerCore container = new CosmosContainerCore(db, crId);

            Assert.AreEqual(container.LinkUri.OriginalString, "/dbs/" + databaseId + "/colls/" + crId);

            CosmosStoredProcedureCore sp = new CosmosStoredProcedureCore(container, spId);

            Assert.AreEqual(sp.LinkUri.OriginalString, "/dbs/" + databaseId + "/colls/" + crId + "/sprocs/" + spId);

            CosmosTrigger tr = new CosmosTrigger(container, trId);

            Assert.AreEqual(tr.LinkUri.OriginalString, "/dbs/" + databaseId + "/colls/" + crId + "/triggers/" + trId);

            CosmosUserDefinedFunction udf = new CosmosUserDefinedFunction(container, udfId);

            Assert.AreEqual(udf.LinkUri.OriginalString, "/dbs/" + databaseId + "/colls/" + crId + "/udfs/" + udfId);
        }
 public CosmosLinqQueryProvider(
     CosmosContainerCore container,
     CosmosJsonSerializer cosmosJsonSerializer,
     CosmosQueryClient queryClient,
     QueryRequestOptions cosmosQueryRequestOptions,
     bool allowSynchronousQueryExecution)
 {
     this.container                      = container;
     this.cosmosJsonSerializer           = cosmosJsonSerializer;
     this.queryClient                    = queryClient;
     this.cosmosQueryRequestOptions      = cosmosQueryRequestOptions;
     this.allowSynchronousQueryExecution = allowSynchronousQueryExecution;
 }
 public PartitionSynchronizerCore(
     CosmosContainerCore container,
     DocumentServiceLeaseContainer leaseContainer,
     DocumentServiceLeaseManager leaseManager,
     int degreeOfParallelism,
     int maxBatchSize)
 {
     this.container           = container;
     this.leaseContainer      = leaseContainer;
     this.leaseManager        = leaseManager;
     this.degreeOfParallelism = degreeOfParallelism;
     this.maxBatchSize        = maxBatchSize;
 }
        public async Task ConflictsFeedSetsPartitionKeyRangeIdentity()
        {
            CosmosContainerCore container = CosmosConflictTests.GetMockedContainer((request, cancellationToken) => {
                Assert.IsNotNull(request.DocumentServiceRequest.PartitionKeyRangeIdentity);
                return(TestHandler.ReturnSuccess());
            });
            FeedIterator iterator = container.GetConflicts().GetConflictsStreamIterator();

            while (iterator.HasMoreResults)
            {
                CosmosResponseMessage responseMessage = await iterator.FetchNextSetAsync();
            }
        }
        public async Task TestInitialize()
        {
            await base.TestInit();

            string PartitionKey = "/status";
            CosmosContainerResponse response = await this.database.Containers.CreateContainerAsync(
                new CosmosContainerSettings(id : Guid.NewGuid().ToString(), partitionKeyPath : PartitionKey),
                cancellationToken : this.cancellationToken);

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Container);
            Assert.IsNotNull(response.Resource);
            this.container = (CosmosContainerCore)response;
        }
示例#16
0
 public CosmosLinqQuery(
     CosmosContainerCore container,
     CosmosJsonSerializer cosmosJsonSerializer,
     CosmosQueryClient queryClient,
     QueryRequestOptions cosmosQueryRequestOptions,
     bool allowSynchronousQueryExecution)
     : this(
         container,
         cosmosJsonSerializer,
         queryClient,
         cosmosQueryRequestOptions,
         null,
         allowSynchronousQueryExecution)
 {
 }
示例#17
0
        public async Task StandByFeedIterator_NoFetchNext()
        {
            var pkRanges = await this.Container.ClientContext.DocumentClient.ReadPartitionKeyRangeFeedAsync(this.Container.LinkUri);

            int expected   = 25;
            int iterations = 0;

            await this.CreateRandomItems(expected, randomPartitionKey : true);

            CosmosContainerCore itemsCore = (CosmosContainerCore)this.Container;
            string continuationToken      = null;
            int    count = 0;

            while (true)
            {
                ChangeFeedRequestOptions requestOptions = new ChangeFeedRequestOptions()
                {
                    StartTime = DateTime.MinValue
                };

                FeedIterator feedIterator = itemsCore.GetStandByFeedIterator(continuationToken, requestOptions: requestOptions);
                using (CosmosResponseMessage responseMessage =
                           await feedIterator.FetchNextSetAsync(this.cancellationToken))
                {
                    continuationToken = responseMessage.Headers.Continuation;
                    if (responseMessage.IsSuccessStatusCode)
                    {
                        Collection <ToDoActivity> response = new CosmosJsonSerializerCore().FromStream <CosmosFeedResponseUtil <ToDoActivity> >(responseMessage.Content).Data;
                        count += response.Count;
                    }
                }

                if (count > expected)
                {
                    Assert.Fail($"{count} does not equal {expected}");
                }

                if (count.Equals(expected))
                {
                    break;
                }

                if (iterations++ > pkRanges.Count)
                {
                    Assert.Fail("Feed does not contain all elements even after looping through PK ranges. Either the continuation is not moving forward or there is some state problem.");
                }
            }
        }
        public FeedProcessorCore(ChangeFeedObserver <T> observer, CosmosContainerCore container, ProcessorSettings settings, PartitionCheckpointer checkpointer)
        {
            this.observer     = observer;
            this.settings     = settings;
            this.checkpointer = checkpointer;
            this.options      = new ChangeFeedOptions
            {
                MaxItemCount        = settings.MaxItemCount,
                PartitionKeyRangeId = settings.LeaseToken,
                SessionToken        = settings.SessionToken,
                StartFromBeginning  = settings.StartFromBeginning,
                RequestContinuation = settings.StartContinuation,
                StartTime           = settings.StartTime,
            };

            this.query = container.ClientContext.DocumentClient.CreateDocumentChangeFeedQuery(container.LinkUri.ToString(), this.options);
        }
        public void ReadConflictContentDeserializesContent()
        {
            CosmosContainerCore container = CosmosConflictTests.GetMockedContainer((request, cancellationToken) => {
                return(TestHandler.ReturnSuccess());
            });

            JObject someJsonObject = new JObject();

            someJsonObject["id"]      = Guid.NewGuid().ToString();
            someJsonObject["someInt"] = 2;

            CosmosConflictSettings conflictSettings = new CosmosConflictSettings();

            conflictSettings.Content = someJsonObject.ToString();

            Assert.AreEqual(someJsonObject.ToString(), container.GetConflicts().ReadConflictContent <JObject>(conflictSettings).ToString());
        }
        public async Task TestInitialize()
        {
            await base.TestInit();

            ContainerResponse response = await this.database.CreateContainerAsync(
                new CosmosContainerSettings(id : Guid.NewGuid().ToString(), partitionKeyPath : PartitionKey),
                requestUnits : 50000,
                cancellationToken : this.cancellationToken);

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Container);
            Assert.IsNotNull(response.Resource);
            this.Container = (CosmosContainerCore)response;

            DocumentFeedResponse <PartitionKeyRange> pkRangesFeed = await this.cosmosClient.DocumentClient.ReadPartitionKeyRangeFeedAsync(this.Container.LinkUri);

            Assert.IsTrue(pkRangesFeed.Count > 1, "Refresh container throughput to have at-least > 1 pk-range");
        }
        public async Task DeleteSendsCorrectPayload()
        {
            const string        expectedId         = "something";
            const string        partitionKey       = "pk";
            Uri                 expectedRequestUri = new Uri($"/dbs/conflictsDb/colls/conflictsColl/conflicts/{expectedId}", UriKind.Relative);
            CosmosContainerCore container          = CosmosConflictTests.GetMockedContainer((request, cancellationToken) => {
                Assert.AreEqual(OperationType.Delete, request.OperationType);
                Assert.AreEqual(ResourceType.Conflict, request.ResourceType);
                Assert.AreEqual(expectedRequestUri, request.RequestUri);
                return(TestHandler.ReturnSuccess());
            });

            CosmosConflictSettings conflictSettings = new CosmosConflictSettings();

            conflictSettings.Id = expectedId;

            await container.Conflicts.DeleteConflictAsync(partitionKey, conflictSettings);
        }
        public override Task <StoredProcedureExecuteResponse <TOutput> > ExecuteStoredProcedureAsync <TInput, TOutput>(
            Cosmos.PartitionKey partitionKey,
            string id,
            TInput input,
            StoredProcedureRequestOptions requestOptions = null,
            CancellationToken cancellationToken          = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException(nameof(id));
            }

            CosmosContainerCore.ValidatePartitionKey(partitionKey, requestOptions);

            Stream parametersStream;

            if (input != null && !input.GetType().IsArray)
            {
                parametersStream = this.clientContext.CosmosSerializer.ToStream <TInput[]>(new TInput[1] {
                    input
                });
            }
            else
            {
                parametersStream = this.clientContext.CosmosSerializer.ToStream <TInput>(input);
            }

            Uri linkUri = this.clientContext.CreateLink(
                parentLink: this.container.LinkUri.OriginalString,
                uriPathSegment: Paths.StoredProceduresPathSegment,
                id: id);

            Task <CosmosResponseMessage> response = this.ProcessStreamOperationAsync(
                resourceUri: linkUri,
                resourceType: ResourceType.StoredProcedure,
                operationType: OperationType.ExecuteJavaScript,
                partitionKey: partitionKey,
                streamPayload: parametersStream,
                requestOptions: requestOptions,
                cancellationToken: cancellationToken);

            return(this.clientContext.ResponseFactory.CreateStoredProcedureExecuteResponseAsync <TOutput>(response));
        }
        public async Task ReadCurrentGetsCorrectRID()
        {
            const string expectedRID  = "something";
            const string partitionKey = "pk";
            // Using "test" as container name because the Mocked DocumentClient has it hardcoded
            Uri expectedRequestUri        = new Uri($"/dbs/conflictsDb/colls/test/docs/{expectedRID}", UriKind.Relative);
            CosmosContainerCore container = CosmosConflictTests.GetMockedContainer((request, cancellationToken) => {
                Assert.AreEqual(OperationType.Read, request.OperationType);
                Assert.AreEqual(ResourceType.Document, request.ResourceType);
                Assert.AreEqual(expectedRequestUri, request.RequestUri);
                return(TestHandler.ReturnSuccess());
            });

            CosmosConflictSettings conflictSettings = new CosmosConflictSettings();

            conflictSettings.SourceResourceId = expectedRID;

            await container.Conflicts.ReadCurrentAsync <JObject>(partitionKey, conflictSettings);
        }
        public RemainingWorkEstimatorCore(
            DocumentServiceLeaseContainer leaseContainer,
            CosmosContainerCore container,
            int degreeOfParallelism)
        {
            if (leaseContainer == null)
            {
                throw new ArgumentNullException(nameof(leaseContainer));
            }
            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }
            if (degreeOfParallelism < 1)
            {
                throw new ArgumentException("Degree of parallelism is out of range", nameof(degreeOfParallelism));
            }

            this.leaseContainer      = leaseContainer;
            this.container           = container;
            this.degreeOfParallelism = degreeOfParallelism;
        }
示例#25
0
        public async Task TestInitialize()
        {
            this.cancellationTokenSource = new CancellationTokenSource();
            this.cancellationToken       = this.cancellationTokenSource.Token;

            this.cosmosClient = TestCommon.CreateCosmosClient();
            this.database     = await this.cosmosClient.Databases.CreateDatabaseAsync(Guid.NewGuid().ToString(),
                                                                                      cancellationToken : this.cancellationToken);

            this.documentClient = TestCommon.CreateClient(true, defaultConsistencyLevel: Documents.ConsistencyLevel.Session);

            string            PartitionKey = "/partitionKey";
            ContainerResponse response     = await this.database.Containers.CreateContainerAsync(
                new CosmosContainerSettings(id : Guid.NewGuid().ToString(), partitionKeyPath : PartitionKey),
                cancellationToken : this.cancellationToken);

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Container);
            Assert.IsNotNull(response.Resource);
            this.Container      = (CosmosContainerCore)response;
            this.jsonSerializer = new CosmosJsonSerializerCore();
        }
示例#26
0
 public CosmosLinqQuery(
     CosmosContainerCore container,
     CosmosJsonSerializer cosmosJsonSerializer,
     CosmosQueryClient queryClient,
     QueryRequestOptions cosmosQueryRequestOptions,
     Expression expression,
     bool allowSynchronousQueryExecution)
 {
     this.container                      = container ?? throw new ArgumentNullException(nameof(container));
     this.cosmosJsonSerializer           = cosmosJsonSerializer;
     this.queryClient                    = queryClient;
     this.cosmosQueryRequestOptions      = cosmosQueryRequestOptions;
     this.expression                     = expression ?? Expression.Constant(this);
     this.allowSynchronousQueryExecution = allowSynchronousQueryExecution;
     this.queryProvider                  = new CosmosLinqQueryProvider(
         container,
         cosmosJsonSerializer,
         queryClient,
         cosmosQueryRequestOptions,
         this.allowSynchronousQueryExecution);
     this.correlatedActivityId = Guid.NewGuid();
 }
        public void ValidateUriGenerationForResources()
        {
            string databaseId = "db1234";
            string crId       = "cr42";

            CosmosClientContext context = new CosmosClientContextCore(
                client: null,
                clientOptions: null,
                userJsonSerializer: null,
                defaultJsonSerializer: null,
                cosmosResponseFactory: null,
                requestHandler: null,
                documentClient: null,
                documentQueryClient: new Mock <IDocumentQueryClient>().Object);

            CosmosDatabaseCore db = new CosmosDatabaseCore(context, databaseId);

            Assert.AreEqual(db.LinkUri.OriginalString, "/dbs/" + databaseId);

            CosmosContainerCore container = new CosmosContainerCore(context, db, crId);

            Assert.AreEqual(container.LinkUri.OriginalString, "/dbs/" + databaseId + "/colls/" + crId);
        }
示例#28
0
        public async Task StandByFeedIterator_WithInexistentRange()
        {
            // Add some random range, this will force the failure
            List <CompositeContinuationToken> corruptedTokens = new List <CompositeContinuationToken>
            {
                new CompositeContinuationToken()
                {
                    Range = new Documents.Routing.Range <string>("whatever", "random", true, false),
                    Token = "oops"
                }
            };

            string corruptedTokenSerialized = JsonConvert.SerializeObject(corruptedTokens);

            CosmosContainerCore itemsCore      = (CosmosContainerCore)this.Container;
            FeedIterator        setIteratorNew =
                itemsCore.GetStandByFeedIterator(corruptedTokenSerialized);

            CosmosResponseMessage responseMessage =
                await setIteratorNew.FetchNextSetAsync(this.cancellationToken);

            Assert.Fail("Should have thrown.");
        }
示例#29
0
        public void ValidateUriGenerationForResources()
        {
            string databaseId = "db1234";
            string crId       = "cr42";
            string spId       = "sp9001";
            string trId       = "tr9002";
            string udfId      = "udf9003";

            CosmosClientContext context = new CosmosClientContextCore(
                client: null,
                clientConfiguration: null,
                cosmosJsonSerializer: null,
                cosmosResponseFactory: null,
                requestHandler: null,
                documentClient: null,
                documentQueryClient: new Mock <IDocumentQueryClient>().Object);

            CosmosDatabaseCore db = new CosmosDatabaseCore(context, databaseId);

            Assert.AreEqual(db.LinkUri.OriginalString, "/dbs/" + databaseId);

            CosmosContainerCore container = new CosmosContainerCore(context, db, crId);

            Assert.AreEqual(container.LinkUri.OriginalString, "/dbs/" + databaseId + "/colls/" + crId);

            CosmosStoredProcedureCore sp = new CosmosStoredProcedureCore(context, container, spId);

            Assert.AreEqual(sp.LinkUri.OriginalString, "/dbs/" + databaseId + "/colls/" + crId + "/sprocs/" + spId);

            CosmosTrigger tr = new CosmosTrigger(context, container, trId);

            Assert.AreEqual(tr.LinkUri.OriginalString, "/dbs/" + databaseId + "/colls/" + crId + "/triggers/" + trId);

            CosmosUserDefinedFunction udf = new CosmosUserDefinedFunction(context, container, udfId);

            Assert.AreEqual(udf.LinkUri.OriginalString, "/dbs/" + databaseId + "/colls/" + crId + "/udfs/" + udfId);
        }
示例#30
0
        internal static async Task <DocumentServiceLeaseStoreManager> InitializeLeaseStoreManagerAsync(
            DocumentServiceLeaseStoreManager documentServiceLeaseStoreManager,
            CosmosContainerCore leaseContainer,
            string leaseContainerPrefix,
            string instanceName)
        {
            if (documentServiceLeaseStoreManager == null)
            {
                ContainerResponse cosmosContainerResponse = await leaseContainer.ReadAsync().ConfigureAwait(false);

                CosmosContainerProperties containerSettings = cosmosContainerResponse.Resource;

                bool isPartitioned =
                    containerSettings.PartitionKey != null &&
                    containerSettings.PartitionKey.Paths != null &&
                    containerSettings.PartitionKey.Paths.Count > 0;
                if (isPartitioned &&
                    (containerSettings.PartitionKey.Paths.Count != 1 || containerSettings.PartitionKey.Paths[0] != "/id"))
                {
                    throw new ArgumentException("The lease collection, if partitioned, must have partition key equal to id.");
                }

                RequestOptionsFactory requestOptionsFactory = isPartitioned ?
                                                              (RequestOptionsFactory) new PartitionedByIdCollectionRequestOptionsFactory() :
                                                              (RequestOptionsFactory) new SinglePartitionRequestOptionsFactory();

                DocumentServiceLeaseStoreManagerBuilder leaseStoreManagerBuilder = new DocumentServiceLeaseStoreManagerBuilder()
                                                                                   .WithLeasePrefix(leaseContainerPrefix)
                                                                                   .WithLeaseContainer(leaseContainer)
                                                                                   .WithRequestOptionsFactory(requestOptionsFactory)
                                                                                   .WithHostName(instanceName);

                documentServiceLeaseStoreManager = await leaseStoreManagerBuilder.BuildAsync().ConfigureAwait(false);
            }

            return(documentServiceLeaseStoreManager);
        }