Samples updated to latest cosmos sdk client (#470)

* initial commit

* initial commit

* reverting  change from linw pr which got in by mistake

* reverting change for item test

* reverting change for item test , replacing the file itself with master
This commit is contained in:
Naveen Singh 2019-06-19 19:39:16 -04:00 коммит произвёл kirankumarkolli
Родитель b2893543c8
Коммит a32aa719f7
19 изменённых файлов: 182 добавлений и 178 удалений

Просмотреть файл

@ -13,7 +13,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.27" />
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.17-preview" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.18-preview" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">

Просмотреть файл

@ -7,7 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.17-preview" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.18-preview" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.1" />

Просмотреть файл

@ -12,7 +12,7 @@
private static readonly string containerId = "container-samples";
private static readonly string partitionKey = "/activityId";
private static CosmosDatabase database = null;
private static Database database = null;
// Async main requires c# 7.1 which is set in the csproj with the LangVersion attribute
public static async Task Main(string[] args)
@ -68,7 +68,7 @@
// Create the database if necessary
await Program.Setup(client);
CosmosContainer simpleContainer = await Program.CreateContainer();
Container simpleContainer = await Program.CreateContainer();
await Program.CreateContainerWithCustomIndexingPolicy();
@ -89,13 +89,13 @@
database = await client.CreateDatabaseIfNotExistsAsync(databaseId);
}
private static async Task<CosmosContainer> CreateContainer()
private static async Task<Container> CreateContainer()
{
// Set throughput to the minimum value of 400 RU/s
ContainerResponse simpleContainer = await database.CreateContainerIfNotExistsAsync(
id: containerId,
partitionKeyPath: partitionKey,
requestUnitsPerSecond: 400);
throughput: 400);
Console.WriteLine($"\n1.1. Created container :{simpleContainer.Container.Id}");
return simpleContainer;
@ -105,59 +105,59 @@
{
// Create a container with custom index policy (consistent indexing)
// We cover index policies in detail in IndexManagement sample project
CosmosContainerSettings containerSettings = new CosmosContainerSettings(
ContainerProperties containerProperties = new ContainerProperties(
id: "SampleContainerWithCustomIndexPolicy",
partitionKeyPath: partitionKey);
containerSettings.IndexingPolicy.IndexingMode = IndexingMode.Consistent;
containerProperties.IndexingPolicy.IndexingMode = IndexingMode.Consistent;
CosmosContainer containerWithConsistentIndexing = await database.CreateContainerIfNotExistsAsync(
containerSettings,
requestUnitsPerSecond: 400);
Container containerWithConsistentIndexing = await database.CreateContainerIfNotExistsAsync(
containerProperties,
throughput: 400);
Console.WriteLine($"1.2. Created Container {containerWithConsistentIndexing.Id}, with custom index policy \n");
await containerWithConsistentIndexing.DeleteAsync();
await containerWithConsistentIndexing.DeleteContainerAsync();
}
private static async Task CreateContainerWithTtlExpiration()
{
CosmosContainerSettings settings = new CosmosContainerSettings
ContainerProperties properties = new ContainerProperties
(id: "TtlExpiryContainer",
partitionKeyPath: partitionKey);
settings.DefaultTimeToLive = (int)TimeSpan.FromDays(1).TotalSeconds; //expire in 1 day
properties.DefaultTimeToLive = (int)TimeSpan.FromDays(1).TotalSeconds; //expire in 1 day
ContainerResponse ttlEnabledContainerResponse = await database.CreateContainerIfNotExistsAsync(
containerSettings: settings);
CosmosContainerSettings returnedSettings = ttlEnabledContainerResponse;
containerProperties: properties);
ContainerProperties returnedProperties = ttlEnabledContainerResponse;
Console.WriteLine($"\n1.3. Created Container \n{returnedSettings.Id} with TTL expiration of {returnedSettings.DefaultTimeToLive}");
Console.WriteLine($"\n1.3. Created Container \n{returnedProperties.Id} with TTL expiration of {returnedProperties.DefaultTimeToLive}");
await ttlEnabledContainerResponse.Container.DeleteAsync();
await ttlEnabledContainerResponse.Container.DeleteContainerAsync();
}
private static async Task GetAndChangeContainerPerformance(CosmosContainer simpleContainer)
private static async Task GetAndChangeContainerPerformance(Container simpleContainer)
{
//*********************************************************************************************
// Get configured performance (reserved throughput) of a CosmosContainer
//**********************************************************************************************
int? throughput = await simpleContainer.ReadProvisionedThroughputAsync();
ThroughputResponse throughputResponse = await simpleContainer.ReadThroughputAsync();
Console.WriteLine($"\n2. Found throughput \n{throughput.Value}\nusing container's id \n{simpleContainer.Id}");
Console.WriteLine($"\n2. Found throughput \n{throughputResponse.Resource.Throughput.Value}\nusing container's id \n{simpleContainer.Id}");
//******************************************************************************************************************
// Change performance (reserved throughput) of CosmosContainer
// Let's change the performance of the container to 500 RU/s
//******************************************************************************************************************
await simpleContainer.ReplaceProvisionedThroughputAsync(500);
await simpleContainer.ReplaceThroughputAsync(500);
Console.WriteLine("\n3. Replaced throughput. Throughput is now 500.\n");
// Get the offer again after replace
int? throughputAfterReplace = await simpleContainer.ReadProvisionedThroughputAsync();
throughputResponse = await simpleContainer.ReadThroughputAsync();
Console.WriteLine($"3. Found throughput \n{throughputAfterReplace.Value}\n using container's ResourceId {simpleContainer.Id}.\n");
Console.WriteLine($"3. Found throughput \n{throughputResponse.Resource.Throughput.Value}\n using container's ResourceId {simpleContainer.Id}.\n");
}
private static async Task ReadContainerProperties()
@ -165,10 +165,10 @@
//*************************************************
// Get a CosmosContainer by its Id property
//*************************************************
CosmosContainer container = database.GetContainer(containerId);
CosmosContainerSettings containerSettings = await container.ReadAsync();
Container container = database.GetContainer(containerId);
ContainerProperties containerProperties = await container.ReadContainerAsync();
Console.WriteLine($"\n4. Found Container \n{containerSettings.Id}\n");
Console.WriteLine($"\n4. Found Container \n{containerProperties.Id}\n");
}
/// <summary>
@ -179,10 +179,10 @@
{
Console.WriteLine("\n5. Reading all CosmosContainer resources for a database");
FeedIterator<CosmosContainerSettings> resultSetIterator = database.GetContainersIterator();
FeedIterator<ContainerProperties> resultSetIterator = database.GetContainerIterator();
while (resultSetIterator.HasMoreResults)
{
foreach (CosmosContainerSettings container in await resultSetIterator.FetchNextSetAsync())
foreach (ContainerProperties container in await resultSetIterator.ReadNextAsync())
{
Console.WriteLine(container.Id);
}
@ -195,7 +195,7 @@
/// <param name="simpleContainer"></param>
private static async Task DeleteContainer()
{
await database.GetContainer(containerId).DeleteAsync();
await database.GetContainer(containerId).DeleteContainerAsync();
Console.WriteLine("\n6. Deleted Container\n");
}
}

Просмотреть файл

@ -7,7 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.17-preview" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.18-preview" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.1" />

Просмотреть файл

@ -65,12 +65,12 @@
DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync(databaseId, 10000);
// A client side reference object that allows additional operations like ReadAsync
CosmosDatabase database = databaseResponse;
Database database = databaseResponse;
// The response from Azure Cosmos
CosmosDatabaseSettings settings = databaseResponse;
DatabaseProperties properties = databaseResponse;
Console.WriteLine($"\n1. Create a database resource with id: {settings.Id} and last modified time stamp: {settings.LastModified}");
Console.WriteLine($"\n1. Create a database resource with id: {properties.Id} and last modified time stamp: {properties.LastModified}");
Console.WriteLine($"\n2. Create a database resource request charge: {databaseResponse.RequestCharge} and Activity Id: {databaseResponse.ActivityId}");
// Read the database from Azure Cosmos
@ -80,20 +80,20 @@
await readResponse.Database.CreateContainerAsync("testContainer", "/pk");
// Get the current throughput for the database
int? throughput = await database.ReadProvisionedThroughputAsync();
if (throughput.HasValue)
ThroughputResponse throughputResponse = await database.ReadThroughputAsync();
if (throughputResponse.Resource.Throughput.HasValue)
{
Console.WriteLine($"\n4. Read a database throughput: {throughput.Value}");
Console.WriteLine($"\n4. Read a database throughput: {throughputResponse.Resource.Throughput.HasValue}");
// Update the current throughput for the database
await database.ReplaceProvisionedThroughputAsync(11000);
await database.ReplaceThroughputAsync(11000);
}
Console.WriteLine("\n5. Reading all databases resources for an account");
FeedIterator<CosmosDatabaseSettings> iterator = client.GetDatabasesIterator();
FeedIterator<DatabaseProperties> iterator = client.GetDatabaseIterator();
do
{
foreach (CosmosDatabaseSettings db in await iterator.FetchNextSetAsync())
foreach (DatabaseProperties db in await iterator.ReadNextAsync())
{
Console.WriteLine(db.Id);
}

Просмотреть файл

@ -7,14 +7,14 @@
/// <summary>
/// Handler that detects concurrency and etag issues
/// </summary>
class ConcurrencyHandler : CosmosRequestHandler
class ConcurrencyHandler : RequestHandler
{
public override async Task<CosmosResponseMessage> SendAsync(
CosmosRequestMessage request,
public override async Task<ResponseMessage> SendAsync(
RequestMessage request,
CancellationToken cancellationToken)
{
CosmosResponseMessage response = await base.SendAsync(request, cancellationToken);
ResponseMessage response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == System.Net.HttpStatusCode.PreconditionFailed)
{

Просмотреть файл

@ -16,7 +16,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.8.1" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.10-preview" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.18-preview" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.1" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />

Просмотреть файл

@ -9,7 +9,7 @@
/// <summary>
/// This handler will send telemetry to Application Insights
/// </summary>
class LoggingHandler : CosmosRequestHandler
class LoggingHandler : RequestHandler
{
private readonly TelemetryClient telemetryClient;
public LoggingHandler()
@ -17,15 +17,15 @@
this.telemetryClient = new TelemetryClient();
}
public override async Task<CosmosResponseMessage> SendAsync(
CosmosRequestMessage request,
public override async Task<ResponseMessage> SendAsync(
RequestMessage request,
CancellationToken cancellationToken)
{
using (Microsoft.ApplicationInsights.Extensibility.IOperationHolder<RequestTelemetry> operation = this.telemetryClient.StartOperation<RequestTelemetry>("CosmosDBRequest"))
{
this.telemetryClient.TrackTrace($"{request.Method.Method} - {request.RequestUri.ToString()}");
CosmosResponseMessage response = await base.SendAsync(request, cancellationToken);
ResponseMessage response = await base.SendAsync(request, cancellationToken);
operation.Telemetry.ResponseCode = ((int)response.StatusCode).ToString();
operation.Telemetry.Success = response.IsSuccessStatusCode;

Просмотреть файл

@ -8,6 +8,7 @@
using Cosmos.Samples.Handlers.Models;
using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.Configuration;
using Microsoft.Azure.Cosmos.Fluent;
// ----------------------------------------------------------------------------------------------------------
// Prerequisites -
@ -57,11 +58,11 @@
CosmosClient client = cosmosClientBuilder.Build();
CosmosDatabaseResponse databaseResponse = await client.Databases.CreateDatabaseIfNotExistsAsync("mydb");
CosmosDatabase database = databaseResponse.Database;
DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync("mydb");
Database database = databaseResponse.Database;
CosmosContainerResponse containerResponse = await database.Containers.CreateContainerIfNotExistsAsync("mycoll", "/id");
CosmosContainer container = containerResponse.Container;
ContainerResponse containerResponse = await database.CreateContainerIfNotExistsAsync("mycoll", "/id");
Container container = containerResponse.Container;
Item item = new Item()
{
@ -72,39 +73,38 @@
};
// Create
await container.Items.CreateItemAsync<Item>(item.Id, item);
await container.CreateItemAsync<Item>(item, new PartitionKey(item.Id));
item.Completed = true;
// Replace
await container.Items.ReplaceItemAsync<Item>(item.Id, item.Id, item);
await container.ReplaceItemAsync<Item>(item, item.Id, new PartitionKey(item.Id));
// Querying
CosmosResultSetIterator<Item> query = container.Items.CreateItemQuery<Item>(new CosmosSqlQueryDefinition("SELECT * FROM c"), maxConcurrency: 1);
FeedIterator<Item> query = container.GetItemQueryIterator<Item>(new QueryDefinition("SELECT * FROM c"), requestOptions: new QueryRequestOptions() { MaxConcurrency = 1});
List<Item> results = new List<Item>();
while (query.HasMoreResults)
{
CosmosQueryResponse<Item> response = await query.FetchNextSetAsync();
FeedResponse<Item> response = await query.ReadNextAsync();
results.AddRange(response.ToList());
}
// Read Item
CosmosItemResponse<Item> cosmosItemResponse = await container.Items.ReadItemAsync<Item>(item.Id, item.Id);
ItemResponse<Item> cosmosItemResponse = await container.ReadItemAsync<Item>(item.Id, new PartitionKey(item.Id));
AccessCondition accessCondition = new AccessCondition
ItemRequestOptions itemRequestOptions = new ItemRequestOptions()
{
Condition = cosmosItemResponse.ETag,
Type = AccessConditionType.IfMatch
IfMatchEtag = cosmosItemResponse.ETag
};
// Concurrency
List<Task<CosmosItemResponse<Item>>> tasks = new List<Task<CosmosItemResponse<Item>>>
List<Task<ItemResponse<Item>>> tasks = new List<Task<ItemResponse<Item>>>
{
UpdateItemForConcurrency(container, accessCondition, item),
UpdateItemForConcurrency(container, accessCondition, item)
UpdateItemForConcurrency(container, itemRequestOptions, item),
UpdateItemForConcurrency(container, itemRequestOptions, item)
};
try
@ -118,19 +118,17 @@
}
// Delete
await container.Items.DeleteItemAsync<Item>(item.Id, item.Id);
await container.DeleteItemAsync<Item>(item.Id, new PartitionKey(item.Id));
}
private static Task<CosmosItemResponse<Item>> UpdateItemForConcurrency(CosmosContainer container, AccessCondition accessCondition, Item item)
private static Task<ItemResponse<Item>> UpdateItemForConcurrency(Container container, ItemRequestOptions itemRequestOptions, Item item)
{
item.Description = $"Updating description {Guid.NewGuid().ToString()}";
return container.Items.ReplaceItemAsync<Item>(
return container.ReplaceItemAsync<Item>(
item,
item.Id,
item.Id,
item, new CosmosItemRequestOptions()
{
AccessCondition = accessCondition
});
new PartitionKey(item.Id),
itemRequestOptions);
}
}
}

Просмотреть файл

@ -8,14 +8,14 @@
/// <summary>
/// Using Polly to retry on Throttles.
/// </summary>
class ThrottlingHandler : CosmosRequestHandler
class ThrottlingHandler : RequestHandler
{
public override Task<CosmosResponseMessage> SendAsync(
CosmosRequestMessage request,
public override Task<ResponseMessage> SendAsync(
RequestMessage request,
CancellationToken cancellationToken)
{
return Policy
.HandleResult<CosmosResponseMessage>(r => (int)r.StatusCode == 429)
.HandleResult<ResponseMessage>(r => (int)r.StatusCode == 429)
.RetryAsync(3)
.ExecuteAsync(() => base.SendAsync(request, cancellationToken));
}

Просмотреть файл

@ -6,7 +6,7 @@
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.17-preview" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.18-preview" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.1" />

Просмотреть файл

@ -59,8 +59,8 @@
private static readonly JsonSerializer Serializer = new JsonSerializer();
//Reusable instance of ItemClient which represents the connection to a Cosmos endpoint
private static CosmosDatabase database = null;
private static CosmosContainer container = null;
private static Database database = null;
private static Container container = null;
// Async main requires c# 7.1 which is set in the csproj with the LangVersion attribute
public static async Task Main(string[] args)
@ -173,7 +173,7 @@
SalesOrder salesOrderV3 = GetSalesOrderSample("SalesOrderV3");
using (Stream stream = Program.ToStream<SalesOrder>(salesOrderV3))
{
using (CosmosResponseMessage responseMessage = await container.CreateItemStreamAsync(new PartitionKey(salesOrderV3.AccountNumber), stream))
using (ResponseMessage responseMessage = await container.CreateItemStreamAsync(stream, new PartitionKey(salesOrderV3.AccountNumber)))
{
// Item stream operations do not throw exceptions for better performance
if (responseMessage.IsSuccessStatusCode)
@ -207,7 +207,7 @@
SalesOrder readOrder = (SalesOrder)response;
// Read the same item but as a stream.
using (CosmosResponseMessage responseMessage = await container.ReadItemStreamAsync(
using (ResponseMessage responseMessage = await container.ReadItemStreamAsync(
partitionKey: new PartitionKey("Account1"),
id: "SalesOrder1"))
{
@ -235,19 +235,20 @@
//******************************************************************************************************************
Console.WriteLine("\n1.4 - Querying for a item using its AccountNumber property");
CosmosSqlQueryDefinition query = new CosmosSqlQueryDefinition(
QueryDefinition query = new QueryDefinition(
"select * from sales s where s.AccountNumber = @AccountInput ")
.UseParameter("@AccountInput", "Account1");
FeedIterator<SalesOrder> resultSet = container.CreateItemQuery<SalesOrder>(
FeedIterator<SalesOrder> resultSet = container.GetItemQueryIterator<SalesOrder>(
query,
partitionKey: new PartitionKey("Account1"),
maxItemCount: 1);
requestOptions : new QueryRequestOptions() {
PartitionKey = new PartitionKey("Account1"),
MaxItemCount = 1});
List<SalesOrder> allSalesForAccount1 = new List<SalesOrder>();
while (resultSet.HasMoreResults)
{
SalesOrder sale = (await resultSet.FetchNextSetAsync()).First();
SalesOrder sale = (await resultSet.ReadNextAsync()).First();
Console.WriteLine($"\n1.4.1 Account Number: {sale.AccountNumber}; Id: {sale.Id} ");
allSalesForAccount1.Add(sale);
}
@ -255,16 +256,17 @@
Console.WriteLine($"\n1.4.2 Query found {allSalesForAccount1.Count} items.");
// Use the same query as before but get the cosmos response message to access the stream directly
FeedIterator streamResultSet = container.CreateItemQueryStream(
FeedIterator streamResultSet = container.GetItemQueryStreamIterator(
query,
maxConcurrency: 1,
partitionKey: new PartitionKey("Account1"),
maxItemCount: 10);
requestOptions: new QueryRequestOptions() {
PartitionKey = new PartitionKey("Account1"),
MaxItemCount = 10,
MaxConcurrency = 1 });
List<SalesOrder> allSalesForAccount1FromStream = new List<SalesOrder>();
while (streamResultSet.HasMoreResults)
{
using (CosmosResponseMessage responseMessage = await streamResultSet.FetchNextSetAsync())
using (ResponseMessage responseMessage = await streamResultSet.ReadNextAsync())
{
// Item stream operations do not throw exceptions for better performance
if (responseMessage.IsSuccessStatusCode)
@ -311,7 +313,7 @@
order.ShippedDate = DateTime.UtcNow;
using (Stream stream = Program.ToStream<SalesOrder>(order))
{
using (CosmosResponseMessage responseMessage = await container.ReplaceItemStreamAsync(
using (ResponseMessage responseMessage = await container.ReplaceItemStreamAsync(
partitionKey: new PartitionKey(order.AccountNumber),
id: order.Id,
streamPayload: stream))
@ -358,7 +360,7 @@
SalesOrder salesOrderV4 = GetSalesOrderSample("SalesOrder4");
using (Stream stream = Program.ToStream<SalesOrder>(salesOrderV4))
{
using (CosmosResponseMessage responseMessage = await container.UpsertItemStreamAsync(
using (ResponseMessage responseMessage = await container.UpsertItemStreamAsync(
partitionKey: new PartitionKey(salesOrderV4.AccountNumber),
streamPayload: stream))
{
@ -584,7 +586,7 @@
try
{
itemResponse.Resource.TotalDue = 9999999;
updatedDoc = await container.ReplaceItemAsync<SalesOrder>(item.Id, itemResponse, new PartitionKey(item.AccountNumber), new ItemRequestOptions { IfMatchEtag = itemResponse.ETag });
updatedDoc = await container.ReplaceItemAsync<SalesOrder>(itemResponse, item.Id, new PartitionKey(item.AccountNumber), new ItemRequestOptions { IfMatchEtag = itemResponse.ETag });
}
catch (CosmosException cre)
{
@ -622,7 +624,7 @@
// Now change something on the item, then do another get and this time we should get the item back
response.Resource.TotalDue = 42;
response = await container.ReplaceItemAsync<SalesOrder>(item.Id, item, new PartitionKey(item.AccountNumber));
response = await container.ReplaceItemAsync<SalesOrder>(item, item.Id, new PartitionKey(item.AccountNumber));
response = await container.ReadItemAsync<SalesOrder>(
partitionKey: new PartitionKey("Account2"),
@ -685,7 +687,7 @@
database = await client.CreateDatabaseIfNotExistsAsync(databaseId);
// Delete the existing container to prevent create item conflicts
await database.GetContainer(containerId).DeleteAsync();
await database.GetContainer(containerId).DeleteContainerAsync();
// We create a partitioned collection here which needs a partition key. Partitioned collections
// can be created with very high values of provisioned throughput (up to Throughput = 250,000)
@ -694,12 +696,12 @@
// For this demo, we create a collection to store SalesOrders. We set the partition key to the account
// number so that we can retrieve all sales orders for an account efficiently from a single partition,
// and perform transactions across multiple sales order for a single account number.
CosmosContainerSettings containerSettings = new CosmosContainerSettings(containerId, partitionKeyPath: "/AccountNumber");
ContainerProperties containerProperties = new ContainerProperties(containerId, partitionKeyPath: "/AccountNumber");
// Create with a throughput of 1000 RU/s
container = await database.CreateContainerIfNotExistsAsync(
containerSettings,
requestUnitsPerSecond: 1000);
containerProperties,
throughput: 1000);
}
}
}

Просмотреть файл

@ -6,7 +6,7 @@
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.17-preview" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.18-preview" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.1" />

Просмотреть файл

@ -53,7 +53,7 @@
[JsonProperty(PropertyName = "deviceId")]
public string DeviceId { get; set; }
[JsonProperty(PropertyName = "_partitionKey")]
[JsonProperty(PropertyName = "_partitionKey", NullValueHandling = NullValueHandling.Ignore)]
public string PartitionKey { get; set; }
}
@ -82,16 +82,16 @@
using (CosmosClient client = new CosmosClient(endpoint, authKey))
{
CosmosDatabase database = await client.CreateDatabaseIfNotExistsAsync(databaseId);
Database database = await client.CreateDatabaseIfNotExistsAsync(databaseId);
// Create the container using REST API without a partition key definition
await Program.CreateNonPartitionedContainerAsync(endpoint, authKey);
CosmosContainer container = database.GetContainer(containerId);
Container container = database.GetContainer(containerId);
// Read back the same container and verify that partition key path is populated
// Partition key is returned when read from V3 SDK.
ContainerResponse containerResposne = await container.ReadAsync();
ContainerResponse containerResposne = await container.ReadContainerAsync();
if (containerResposne.Resource.PartitionKeyPath != null)
{
Console.WriteLine("Container Partition Key path {0}", containerResposne.Resource.PartitionKeyPath);
@ -137,42 +137,45 @@
/// for the partitionKey parameter
/// New item CRUD could be performed using this NonePartitionKeyValue to target the same logical partition
/// </summary>
private static async Task ItemOperationsWithNonePartitionKeyValue(CosmosContainer container)
private static async Task ItemOperationsWithNonePartitionKeyValue(Container container)
{
string itemid = Guid.NewGuid().ToString();
DeviceInformationItem itemWithoutPK = GetDeviceWithNoPartitionKey(itemid);
// Insert a new item with NonePartitionKeyValue
ItemResponse<DeviceInformationItem> createResponse = await container.CreateItemAsync<DeviceInformationItem>(
partitionKey: PartitionKey.NonePartitionKeyValue,
item: itemWithoutPK);
item: itemWithoutPK,
partitionKey: PartitionKey.NonePartitionKeyValue);
Console.WriteLine("Creating Item {0} Status Code {1}", itemid, createResponse.StatusCode);
// Read an existing item with NonePartitionKeyValue
ItemResponse<DeviceInformationItem> readResponse = await container.ReadItemAsync<DeviceInformationItem>(
partitionKey: PartitionKey.NonePartitionKeyValue,
id: itemid);
id: itemid,
partitionKey: PartitionKey.NonePartitionKeyValue
);
Console.WriteLine("Reading Item {0} Status Code {1}", itemid, readResponse.StatusCode);
// Replace the content of existing item with NonePartitionKeyValue
itemWithoutPK.DeviceId = Guid.NewGuid().ToString();
ItemResponse<DeviceInformationItem> replaceResponse = await container.ReplaceItemAsync<DeviceInformationItem>(
partitionKey: PartitionKey.NonePartitionKeyValue,
item: itemWithoutPK,
id: itemWithoutPK.Id,
item: itemWithoutPK);
partitionKey: PartitionKey.NonePartitionKeyValue
);
Console.WriteLine("Replacing Item {0} Status Code {1}", itemid, replaceResponse.StatusCode);
// Delete an item with NonePartitionKeyValue.
ItemResponse<DeviceInformationItem> deleteResponse = await container.DeleteItemAsync<DeviceInformationItem>(
partitionKey: PartitionKey.NonePartitionKeyValue,
id: itemid);
id: itemid,
partitionKey: PartitionKey.NonePartitionKeyValue
);
Console.WriteLine("Deleting Item {0} Status Code {1}", itemid, deleteResponse.StatusCode);
}
/// <summary>
/// The function demonstrates CRUD operations on the migrated collection supplying a value for the partition key
/// <summary>
private static async Task ItemOperationsWithValidPartitionKeyValue(CosmosContainer container)
private static async Task ItemOperationsWithValidPartitionKeyValue(Container container)
{
string itemid = Guid.NewGuid().ToString();
string partitionKey = "a";
@ -209,7 +212,7 @@
/// The function demonstrates migrating documents that were inserted without a value for partition key, and those inserted
/// pre-migration to other logical partitions, those with a value for partition key.
/// </summary>
private static async Task MigratedItemsFromNonePartitionKeyToValidPartitionKeyValue(CosmosContainer container)
private static async Task MigratedItemsFromNonePartitionKeyToValidPartitionKeyValue(Container container)
{
// Pre-create a few items in the container to demo the migration
const int ItemsToCreate = 4;
@ -219,18 +222,18 @@
string itemid = Guid.NewGuid().ToString();
DeviceInformationItem itemWithoutPK = GetDeviceWithNoPartitionKey(itemid);
ItemResponse<DeviceInformationItem> createResponse = await container.CreateItemAsync<DeviceInformationItem>(
partitionKey: PartitionKey.NonePartitionKeyValue,
item: itemWithoutPK);
partitionKey: PartitionKey.NonePartitionKeyValue,
item: itemWithoutPK);
}
// Query items on the container that have no partition key value by supplying NonePartitionKeyValue
// The operation is made in batches to not lose work in case of partial execution
int resultsFetched = 0;
CosmosSqlQueryDefinition sql = new CosmosSqlQueryDefinition("select * from r");
FeedIterator<DeviceInformationItem> setIterator = container.CreateItemQuery<DeviceInformationItem>(sql, partitionKey: PartitionKey.NonePartitionKeyValue, maxItemCount: 2);
QueryDefinition sql = new QueryDefinition("select * from r");
FeedIterator<DeviceInformationItem> setIterator = container.GetItemQueryIterator<DeviceInformationItem>(sql, requestOptions: new QueryRequestOptions() { PartitionKey = PartitionKey.NonePartitionKeyValue, MaxItemCount = 2 });
while (setIterator.HasMoreResults)
{
FeedResponse<DeviceInformationItem> queryResponse = await setIterator.FetchNextSetAsync();
FeedResponse<DeviceInformationItem> queryResponse = await setIterator.ReadNextAsync();
resultsFetched += queryResponse.Count();
// For the items returned with NonePartitionKeyValue
@ -274,7 +277,7 @@
return new DeviceInformationItem
{
Id = itemId,
DeviceId = Guid.NewGuid().ToString()
DeviceId = Guid.NewGuid().ToString(),
};
}

Просмотреть файл

@ -23,7 +23,7 @@
private static readonly string CosmosDatabaseId = "samples";
private static readonly string containerId = "container-samples";
private static CosmosDatabase cosmosDatabase = null;
private static Database cosmosDatabase = null;
// Async main requires c# 7.1 which is set in the csproj with the LangVersion attribute
public static async Task Main(string[] args)
@ -73,7 +73,7 @@
private static async Task RunDemoAsync(CosmosClient client)
{
cosmosDatabase = await client.CreateDatabaseIfNotExistsAsync(CosmosDatabaseId);
CosmosContainer container = await Program.GetOrCreateContainerAsync(cosmosDatabase, containerId);
Container container = await Program.GetOrCreateContainerAsync(cosmosDatabase, containerId);
await Program.CreateItems(container);
@ -91,16 +91,16 @@
//await cosmosDatabase.DeleteAsync();
}
private static async Task ItemFeed(CosmosContainer container)
private static async Task ItemFeed(Container container)
{
List<Family> families = new List<Family>();
// SQL
FeedIterator<Family> setIterator = container.GetItemsIterator<Family>(maxItemCount: 1);
FeedIterator<Family> setIterator = container.GetItemIterator<Family>(maxItemCount: 1);
while (setIterator.HasMoreResults)
{
int count = 0;
foreach (Family item in await setIterator.FetchNextSetAsync())
foreach (Family item in await setIterator.ReadNextAsync())
{
Assert("Should only return 1 result at a time.", count <= 1);
families.Add(item);
@ -110,16 +110,16 @@
Assert("Expected two families", families.ToList().Count == 2);
}
private static async Task ItemStreamFeed(CosmosContainer container)
private static async Task ItemStreamFeed(Container container)
{
int totalCount = 0;
// SQL
FeedIterator setIterator = container.GetItemsStreamIterator();
FeedIterator setIterator = container.GetItemStreamIterator();
while (setIterator.HasMoreResults)
{
int count = 0;
using (CosmosResponseMessage response = await setIterator.FetchNextSetAsync())
using (ResponseMessage response = await setIterator.ReadNextAsync())
{
response.EnsureSuccessStatusCode();
count++;
@ -137,19 +137,21 @@
Assert("Expected two families", totalCount == 2);
}
private static async Task QueryItemsInPartitionAsStreams(CosmosContainer container)
private static async Task QueryItemsInPartitionAsStreams(Container container)
{
// SQL
FeedIterator setIterator = container.CreateItemQueryStream(
FeedIterator setIterator = container.GetItemQueryStreamIterator(
"SELECT F.id, F.LastName, F.IsRegistered FROM Families F",
partitionKey: new PartitionKey("Anderson"),
maxConcurrency: 1,
maxItemCount: 1);
requestOptions: new QueryRequestOptions() {
PartitionKey = new PartitionKey("Anderson"),
MaxConcurrency = 1,
MaxItemCount = 1
});
int count = 0;
while (setIterator.HasMoreResults)
{
using (CosmosResponseMessage response = await setIterator.FetchNextSetAsync())
using (ResponseMessage response = await setIterator.ReadNextAsync())
{
Assert("Response failed", response.IsSuccessStatusCode);
count++;
@ -168,40 +170,39 @@
Assert("Expected 1 family", count == 1);
}
private static async Task QueryWithSqlParameters(CosmosContainer container)
private static async Task QueryWithSqlParameters(Container container)
{
// Query using two properties within each item. WHERE Id == "" AND Address.City == ""
// notice here how we are doing an equality comparison on the string value of City
CosmosSqlQueryDefinition query = new CosmosSqlQueryDefinition("SELECT * FROM Families f WHERE f.id = @id AND f.Address.City = @city")
QueryDefinition query = new QueryDefinition("SELECT * FROM Families f WHERE f.id = @id AND f.Address.City = @city")
.UseParameter("@id", "AndersonFamily")
.UseParameter("@city", "Seattle");
List<Family> results = new List<Family>();
FeedIterator<Family> resultSetIterator = container.CreateItemQuery<Family>(query, partitionKey: new PartitionKey("Anderson"));
FeedIterator<Family> resultSetIterator = container.GetItemQueryIterator<Family>(query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Anderson")});
while (resultSetIterator.HasMoreResults)
{
results.AddRange((await resultSetIterator.FetchNextSetAsync()));
results.AddRange((await resultSetIterator.ReadNextAsync()));
}
Assert("Expected only 1 family", results.Count == 1);
}
private static async Task QueryPartitionedContainerInParallelAsync(CosmosContainer container)
private static async Task QueryPartitionedContainerInParallelAsync(Container container)
{
List<Family> familiesSerial = new List<Family>();
string queryText = "SELECT * FROM Families";
// 0 maximum parallel tasks, effectively serial execution
QueryRequestOptions options = new QueryRequestOptions() { MaxBufferedItemCount = 100 };
FeedIterator<Family> query = container.CreateItemQuery<Family>(
options.MaxConcurrency = 0;
FeedIterator<Family> query = container.GetItemQueryIterator<Family>(
queryText,
maxConcurrency: 0,
requestOptions: options);
while (query.HasMoreResults)
{
foreach (Family family in await query.FetchNextSetAsync())
foreach (Family family in await query.ReadNextAsync())
{
familiesSerial.Add(family);
}
@ -212,14 +213,14 @@
// 1 maximum parallel tasks, 1 dedicated asynchronous task to continuously make REST calls
List<Family> familiesParallel1 = new List<Family>();
query = container.CreateItemQuery<Family>(
options.MaxConcurrency = 1;
query = container.GetItemQueryIterator<Family>(
queryText,
maxConcurrency: 1,
requestOptions: options);
while (query.HasMoreResults)
{
foreach (Family family in await query.FetchNextSetAsync())
foreach (Family family in await query.ReadNextAsync())
{
familiesParallel1.Add(family);
}
@ -232,14 +233,14 @@
// 10 maximum parallel tasks, a maximum of 10 dedicated asynchronous tasks to continuously make REST calls
List<Family> familiesParallel10 = new List<Family>();
query = container.CreateItemQuery<Family>(
options.MaxConcurrency = 10;
query = container.GetItemQueryIterator<Family>(
queryText,
maxConcurrency: 10,
requestOptions: options);
while (query.HasMoreResults)
{
foreach (Family family in await query.FetchNextSetAsync())
foreach (Family family in await query.ReadNextAsync())
{
familiesParallel10.Add(family);
}
@ -254,7 +255,7 @@
/// </summary>
/// <param name="container">The selfLink property for the CosmosContainer where items will be created.</param>
/// <returns>None</returns>
private static async Task CreateItems(CosmosContainer container)
private static async Task CreateItems(Container container)
{
Family AndersonFamily = new Family
{
@ -325,13 +326,13 @@
/// </summary>
/// <param name="id">The id of the CosmosContainer to search for, or create.</param>
/// <returns>The matched, or created, CosmosContainer object</returns>
private static async Task<CosmosContainer> GetOrCreateContainerAsync(CosmosDatabase database, string containerId)
private static async Task<Container> GetOrCreateContainerAsync(Database database, string containerId)
{
CosmosContainerSettings containerDefinition = new CosmosContainerSettings(id: containerId, partitionKeyPath: "/LastName");
ContainerProperties containerProperties = new ContainerProperties(id: containerId, partitionKeyPath: "/LastName");
return await database.CreateContainerIfNotExistsAsync(
containerSettings: containerDefinition,
requestUnitsPerSecond: 400);
containerProperties: containerProperties,
throughput: 400);
}
private static void Assert(string message, bool condition)

Просмотреть файл

@ -6,7 +6,7 @@
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.17-preview" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.18-preview" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.1" />

Просмотреть файл

@ -71,17 +71,17 @@
string databaseId,
string containerId)
{
CosmosDatabase database = await client.CreateDatabaseIfNotExistsAsync(DatabaseId);
Database database = await client.CreateDatabaseIfNotExistsAsync(DatabaseId);
CosmosContainerSettings containerSettings = new CosmosContainerSettings(containerId, "/LastName");
ContainerProperties containerSettings = new ContainerProperties(containerId, "/LastName");
// Delete the existing container to prevent create item conflicts
await database.GetContainer(containerId).DeleteAsync();
await database.GetContainer(containerId).DeleteContainerAsync();
// Create with a throughput of 1000 RU/s
CosmosContainer container = await database.CreateContainerIfNotExistsAsync(
Container container = await database.CreateContainerIfNotExistsAsync(
containerSettings,
requestUnitsPerSecond: 1000);
throughput: 1000);
//Run a simple script
await Program.RunSimpleScript(container);
@ -99,15 +99,15 @@
/// <summary>
/// Runs a simple script which just does a server side query
/// </summary>
private static async Task RunSimpleScript(CosmosContainer container)
private static async Task RunSimpleScript(Container container)
{
// 1. Create stored procedure for script.
string scriptFileName = @"js\SimpleScript.js";
string scriptId = Path.GetFileNameWithoutExtension(scriptFileName);
await TryDeleteStoredProcedure(container, scriptId);
CosmosScripts cosmosScripts = container.GetScripts();
StoredProcedureResponse sproc = await cosmosScripts.CreateStoredProcedureAsync(new CosmosStoredProcedureSettings(scriptId, File.ReadAllText(scriptFileName)));
Scripts cosmosScripts = container.Scripts;
StoredProcedureResponse sproc = await cosmosScripts.CreateStoredProcedureAsync(new StoredProcedureProperties(scriptId, File.ReadAllText(scriptFileName)));
// 2. Create a document.
SampleDocument doc = new SampleDocument
@ -123,17 +123,17 @@
// 3. Run the script. Pass "Hello, " as parameter.
// The script will take the 1st document and echo: Hello, <document as json>.
StoredProcedureExecuteResponse<string> response = await container.GetScripts().ExecuteStoredProcedureAsync<string, string>(new PartitionKey(doc.LastName), scriptId, "Hello");
StoredProcedureExecuteResponse<string> response = await container.Scripts.ExecuteStoredProcedureAsync<string, string>(new PartitionKey(doc.LastName), scriptId, "Hello");
Console.WriteLine("Result from script: {0}\r\n", response.Resource);
await container.DeleteItemAsync<SampleDocument>(new PartitionKey(doc.LastName), doc.Id);
await container.DeleteItemAsync<SampleDocument>(doc.Id, new PartitionKey(doc.LastName));
}
/// <summary>
/// Import many documents using stored procedure.
/// </summary>
private static async Task RunBulkImport(CosmosContainer container)
private static async Task RunBulkImport(Container container)
{
string inputDirectory = @".\Data\";
string inputFileMask = "*.json";
@ -154,8 +154,8 @@
string body = File.ReadAllText(@".\JS\BulkImport.js");
await TryDeleteStoredProcedure(container, scriptId);
CosmosScripts cosmosScripts = container.GetScripts();
StoredProcedureResponse sproc = await cosmosScripts.CreateStoredProcedureAsync(new CosmosStoredProcedureSettings(scriptId, body));
Scripts cosmosScripts = container.Scripts;
StoredProcedureResponse sproc = await cosmosScripts.CreateStoredProcedureAsync(new StoredProcedureProperties(scriptId, body));
// 4. Create a batch of docs (MAX is limited by request size (2M) and to script for execution.
// We send batches of documents to create to script.
@ -184,10 +184,10 @@
// 8. Validate
int numDocs = 0;
FeedIterator<dynamic> setIterator = container.GetItemsIterator<dynamic>();
FeedIterator<dynamic> setIterator = container.GetItemIterator<dynamic>();
while (setIterator.HasMoreResults)
{
FeedResponse<dynamic> response = await setIterator.FetchNextSetAsync();
FeedResponse<dynamic> response = await setIterator.ReadNextAsync();
numDocs += response.Count();
}
@ -197,15 +197,15 @@
/// <summary>
/// Get documents ordered by some doc property. This is done using OrderBy stored procedure.
/// </summary>
private static async Task RunOrderBy(CosmosContainer container)
private static async Task RunOrderBy(Container container)
{
// 1. Create or get the stored procedure.
string body = File.ReadAllText(@"js\OrderBy.js");
string scriptId = "OrderBy";
await TryDeleteStoredProcedure(container, scriptId);
CosmosScripts cosmosScripts = container.GetScripts();
StoredProcedureResponse sproc = await cosmosScripts.CreateStoredProcedureAsync(new CosmosStoredProcedureSettings(scriptId, body));
Scripts cosmosScripts = container.Scripts;
StoredProcedureResponse sproc = await cosmosScripts.CreateStoredProcedureAsync(new StoredProcedureProperties(scriptId, body));
// 2. Prepare to run stored procedure.
string orderByFieldName = "FamilyId";
@ -323,9 +323,9 @@
/// <param name="collectionLink">DocumentCollection to search for the Stored Procedure</param>
/// <param name="sprocId">Id of the Stored Procedure to delete</param>
/// <returns></returns>
private static async Task TryDeleteStoredProcedure(CosmosContainer container, string sprocId)
private static async Task TryDeleteStoredProcedure(Container container, string sprocId)
{
CosmosScripts cosmosScripts = container.GetScripts();
Scripts cosmosScripts = container.Scripts;
StoredProcedureResponse sproc = await cosmosScripts.ReadStoredProcedureAsync(sprocId);
if (sproc != null)
{

Просмотреть файл

@ -6,7 +6,7 @@
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.17-preview" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0.18-preview" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.1" />

Просмотреть файл

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>