private async Task <CosmosDatabase> CreateDatabaseStreamHelper( string databaseId = null, int?throughput = null, bool databaseExists = false) { if (string.IsNullOrEmpty(databaseId)) { databaseId = Guid.NewGuid().ToString(); } CosmosDatabaseSettings databaseSettings = new CosmosDatabaseSettings() { Id = databaseId }; using (Stream streamPayload = CosmosResource.ToStream(databaseSettings)) { CosmosResponseMessage response = await this.cosmosClient.Databases.CreateDatabaseStreamAsync( streamPayload, throughput : 400); Assert.IsNotNull(response); Assert.IsNotNull(response.Headers.RequestCharge); Assert.IsNotNull(response.Headers.ActivityId); Assert.IsTrue(response.StatusCode == HttpStatusCode.OK || (response.StatusCode == HttpStatusCode.Created && !databaseExists)); return(this.cosmosClient.Databases[databaseId]); } }
private async Task <ContainerProperties> ReadCollectionAsync( string collectionLink, IDocumentClientRetryPolicy retryPolicyInstance, ITrace trace, IClientSideRequestStatistics clientSideRequestStatistics, CancellationToken cancellationToken) { using (ITrace childTrace = trace.StartChild("Read Collection", TraceComponent.Transport, TraceLevel.Info)) { cancellationToken.ThrowIfCancellationRequested(); RequestNameValueCollection headers = new RequestNameValueCollection(); using (DocumentServiceRequest request = DocumentServiceRequest.Create( OperationType.Read, ResourceType.Collection, collectionLink, AuthorizationTokenType.PrimaryMasterKey, headers)) { headers.XDate = Rfc1123DateTimeCache.UtcNow(); request.RequestContext.ClientRequestStatistics = clientSideRequestStatistics ?? new ClientSideRequestStatisticsTraceDatum(DateTime.UtcNow, trace.Summary); if (clientSideRequestStatistics == null) { childTrace.AddDatum( "Client Side Request Stats", request.RequestContext.ClientRequestStatistics); } string authorizationToken = await this.tokenProvider.GetUserAuthorizationTokenAsync( request.ResourceAddress, PathsHelper.GetResourcePath(request.ResourceType), HttpConstants.HttpMethods.Get, request.Headers, AuthorizationTokenType.PrimaryMasterKey, childTrace); headers.Authorization = authorizationToken; using (new ActivityScope(Guid.NewGuid())) { retryPolicyInstance?.OnBeforeSendRequest(request); try { using (DocumentServiceResponse response = await this.storeModel.ProcessMessageAsync(request)) { return(CosmosResource.FromStream <ContainerProperties>(response)); } } catch (DocumentClientException ex) { childTrace.AddDatum("Exception Message", ex.Message); throw; } } } } }
public override Task <UserDefinedFunctionResponse> ReplaceUserDefinedFunctionAsync( UserDefinedFunctionProperties userDefinedFunctionProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { if (userDefinedFunctionProperties == null) { throw new ArgumentNullException(nameof(userDefinedFunctionProperties)); } if (string.IsNullOrEmpty(userDefinedFunctionProperties.Id)) { throw new ArgumentNullException(nameof(userDefinedFunctionProperties.Id)); } if (string.IsNullOrEmpty(userDefinedFunctionProperties.Body)) { throw new ArgumentNullException(nameof(userDefinedFunctionProperties.Body)); } return(this.ProcessUserDefinedFunctionOperationAsync( id: userDefinedFunctionProperties.Id, operationType: OperationType.Replace, streamPayload: CosmosResource.ToStream(userDefinedFunctionProperties), requestOptions: requestOptions, cancellationToken: cancellationToken)); }
public override Task <TriggerResponse> ReplaceTriggerAsync( TriggerProperties triggerProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { if (triggerProperties == null) { throw new ArgumentNullException(nameof(triggerProperties)); } if (string.IsNullOrEmpty(triggerProperties.Id)) { throw new ArgumentNullException(nameof(triggerProperties.Id)); } if (string.IsNullOrEmpty(triggerProperties.Body)) { throw new ArgumentNullException(nameof(triggerProperties.Body)); } return(this.ProcessTriggerOperationAsync( id: triggerProperties.Id, operationType: OperationType.Replace, streamPayload: CosmosResource.ToStream(triggerProperties), requestOptions: requestOptions, cancellationToken: cancellationToken)); }
private static string CosmosSerialize(object input) { using (Stream stream = CosmosResource.ToStream(input)) { using (StreamReader sr = new StreamReader(stream)) { return(sr.ReadToEnd()); } } }
internal static void ValidateResource(CosmosResource resource) { Assert.IsFalse(string.IsNullOrWhiteSpace(resource.AltLink), "AltLink for a resource cannot be null or whitespace"); Assert.IsFalse(string.IsNullOrWhiteSpace(resource.ETag), "Etag for a resource cannot be null or whitespace"); Assert.IsFalse(string.IsNullOrWhiteSpace(resource.Id), "Id for a resource cannot be null or whitespace"); Assert.IsFalse(string.IsNullOrWhiteSpace(resource.ResourceId), "ResourceId for a resource cannot be null or whitespace"); Assert.AreNotSame(resource.Id, resource.ResourceId, "ResourceId and Id for a resource cannot be same"); Assert.IsFalse(string.IsNullOrWhiteSpace(resource.SelfLink), "SelfLink for a resource cannot be null or whitespace"); Assert.AreNotSame(resource.SelfLink, resource.AltLink, "SelfLink and altLink for a resource cannot be same"); Assert.IsTrue(resource.Timestamp > DateTime.MinValue, "Timestamp set for resource is not correct"); }
public override Task <StoredProcedureResponse> ReplaceStoredProcedureAsync( CosmosStoredProcedureSettings storedProcedureSettings, RequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { return(this.ProcessStoredProcedureOperationAsync( id: storedProcedureSettings.Id, operationType: OperationType.Replace, streamPayload: CosmosResource.ToStream(storedProcedureSettings), requestOptions: requestOptions, cancellationToken: cancellationToken)); }
public override Task <StoredProcedureResponse> CreateStoredProcedureAsync( CosmosStoredProcedureSettings storedProcedureSettings, RequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken)) { return(this.ProcessStoredProcedureOperationAsync( linkUri: this.container.LinkUri, operationType: OperationType.Create, streamPayload: CosmosResource.ToStream(storedProcedureSettings), requestOptions: requestOptions, cancellationToken: cancellationToken)); }
private static T CosmosDeserialize <T>(string payload) { using (MemoryStream ms = new MemoryStream()) { StreamWriter sw = new StreamWriter(ms, new UTF8Encoding(false, true), 1024, leaveOpen: true); sw.Write(payload); sw.Flush(); ms.Position = 0; return(CosmosResource.FromStream <T>(ms)); } }
private async Task <ContainerProperties> ReadCollectionAsync(string collectionLink, CancellationToken cancellationToken, IDocumentClientRetryPolicy retryPolicyInstance, ITrace trace) { using (ITrace childTrace = trace.StartChild("Read Collection", TraceComponent.Transport, TraceLevel.Info)) { cancellationToken.ThrowIfCancellationRequested(); using (DocumentServiceRequest request = DocumentServiceRequest.Create( OperationType.Read, ResourceType.Collection, collectionLink, AuthorizationTokenType.PrimaryMasterKey, new StoreRequestNameValueCollection())) { request.Headers[HttpConstants.HttpHeaders.XDate] = DateTime.UtcNow.ToString("r"); (string authorizationToken, string payload) = await this.tokenProvider.GetUserAuthorizationAsync( request.ResourceAddress, PathsHelper.GetResourcePath(request.ResourceType), HttpConstants.HttpMethods.Get, request.Headers, AuthorizationTokenType.PrimaryMasterKey); request.Headers[HttpConstants.HttpHeaders.Authorization] = authorizationToken; using (new ActivityScope(Guid.NewGuid())) { if (retryPolicyInstance != null) { retryPolicyInstance.OnBeforeSendRequest(request); } try { using (DocumentServiceResponse response = await this.storeModel.ProcessMessageAsync(request)) { return(CosmosResource.FromStream <ContainerProperties>(response)); } } catch (DocumentClientException ex) { childTrace.AddDatum("Exception Message", ex.Message); throw; } } } } }
private async Task <DataAccessResult> SetResourceAsync <T>(T resource) where T : ICosmosResource { try { var res = new CosmosResource <T>(resource); ItemResponse <CosmosResource <T> > result = await container.UpsertItemAsync <CosmosResource <T> >(res, new PartitionKey(res.Pk)); return(DataAccessResult.Ok); } catch (CosmosException ex) { return(new DataAccessResult(false, ex.Status)); } }
public static Task <T> ToResourceAsync <T>(this HttpContent httpContent) where T : JsonSerializable, new() { Task <Stream> readStreamTask = httpContent.ReadAsStreamAsync(); return(readStreamTask.ContinueWith(delegate { using (httpContent) { if (readStreamTask.Exception != null) { throw readStreamTask.Exception.InnerException; } return CosmosResource.LoadFrom <T>(readStreamTask.Result); } })); }
private async Task <ContainerProperties> ReadCollectionAsync(string collectionLink, CancellationToken cancellationToken, IDocumentClientRetryPolicy retryPolicyInstance) { cancellationToken.ThrowIfCancellationRequested(); using (DocumentServiceRequest request = DocumentServiceRequest.Create( OperationType.Read, ResourceType.Collection, collectionLink, AuthorizationTokenType.PrimaryMasterKey, new DictionaryNameValueCollection())) { request.Headers[HttpConstants.HttpHeaders.XDate] = DateTime.UtcNow.ToString("r"); string payload; string authorizationToken = this.tokenProvider.GetUserAuthorizationToken( request.ResourceAddress, PathsHelper.GetResourcePath(request.ResourceType), HttpConstants.HttpMethods.Get, request.Headers, AuthorizationTokenType.PrimaryMasterKey, out payload); request.Headers[HttpConstants.HttpHeaders.Authorization] = authorizationToken; using (new ActivityScope(Guid.NewGuid())) { if (retryPolicyInstance != null) { retryPolicyInstance.OnBeforeSendRequest(request); } using (DocumentServiceResponse response = await this.storeModel.ProcessMessageAsync(request)) { return(CosmosResource.FromStream <ContainerProperties>(response)); } } } }
public async Task StreamCreateConflictTestAsync() { CosmosDatabaseSettings databaseSettings = new CosmosDatabaseSettings() { Id = Guid.NewGuid().ToString() }; using (CosmosResponseMessage response = await this.cosmosClient.Databases.CreateDatabaseStreamAsync(CosmosResource.ToStream(databaseSettings))) { Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); Assert.IsNotNull(response.Headers); Assert.IsTrue(response.Headers.RequestCharge > 0); } // Stream operations do not throw exceptions. using (CosmosResponseMessage response = await this.cosmosClient.Databases.CreateDatabaseStreamAsync(CosmosResource.ToStream(databaseSettings))) { Assert.AreEqual(HttpStatusCode.Conflict, response.StatusCode); Assert.IsNotNull(response.Headers); Assert.IsTrue(response.Headers.RequestCharge > 0); } using (CosmosResponseMessage response = await this.cosmosClient.Databases[databaseSettings.Id].DeleteStreamAsync()) { Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode); Assert.IsNotNull(response.Headers); Assert.IsTrue(response.Headers.RequestCharge > 0); } }
public async Task StreamPartitionedCreateWithPathDelete() { string containerName = Guid.NewGuid().ToString(); string partitionKeyPath = "/users"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); partitionKeyDefinition.Paths.Add(partitionKeyPath); CosmosContainerSettings settings = new CosmosContainerSettings(containerName, partitionKeyDefinition); using (CosmosResponseMessage containerResponse = await this.cosmosDatabase.Containers.CreateContainerStreamAsync(CosmosResource.ToStream(settings))) { Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode); } using (CosmosResponseMessage containerResponse = await this.cosmosDatabase.Containers[containerName].DeleteStreamAsync()) { Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode); } }