Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

redame content and some additional samples #14713

Merged
merged 3 commits into from
Aug 31, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
205 changes: 192 additions & 13 deletions sdk/tables/Azure.Data.Tables/readme.md
Original file line number Diff line number Diff line change
@@ -1,34 +1,207 @@
# Azure Tables client library for .NET

Content forthcoming
Azure Table storage is a service that stores large amounts of structured NoSQL data in the cloud, providing
a key/attribute store with a schema-less design.

## Getting started
Azure Cosmos DB provides a Table API for applications that are written for Azure Table storage and that need premium capabilities like:

- Turnkey global distribution.
- Dedicated throughput worldwide.
- Single-digit millisecond latencies at the 99th percentile.
- Guaranteed high availability.
- Automatic secondary indexing.

Content forthcoming
The Azure Tables client library can seamlessly target either Azure table storage or Azure Cosmos DB table service endpoints with no code changes.

## Getting started

### Install the package
Install the Azure Tables client library for .NET with [NuGet][nuget]:

```
dotnet add package Azure.Data.Tables --version 3.0.0-beta.1
```

### Prerequisites
* An [Azure subscription][azure_sub].
* An existing Azure storage account or Azure Cosmos DB database with Azure Table API specified.

If you need to create either of these, you can use the [Azure CLI][azure_cli].

Content forthcoming
#### Creating a storage account

### Authenticate the client
Create a storage account `mystorageaccount` in resource group `MyResourceGroup`
in the subscription `MySubscription` in the West US region.
```
az storage account create -n mystorageaccount -g MyResourceGroup -l westus --subscription MySubscription
```

Content forthcoming
#### Creating a Cosmos DB

Create a storage account `MyCosmosDBDatabaseAccount` in resource group `MyResourceGroup`
christothes marked this conversation as resolved.
Show resolved Hide resolved
in the subscription `MySubscription` and a table named `MyTableName` in the account.

```
az cosmosdb create --name MyCosmosDBDatabaseAccount --resource-group MyResourceGroup --subscription MySubscription

az cosmosdb table create --name MyTableName --resource-group MyResourceGroup --account-name MyCosmosDBDatabaseAccount
```

## Key concepts

Content forthcoming
Common uses of the Table service include:

- Storing TBs of structured data capable of serving web scale applications
- Storing datasets that don't require complex joins, foreign keys, or stored procedures and can be de-normalized for fast access
- Quickly querying data using a clustered index
- Accessing data using the OData protocol and LINQ filter expressions

Learn more about options for authentication _(including Connection Strings, Shared Key, and Shared Key Signatures)_ [in our samples.](samples/Sample0Auth.md)

## Examples

Content forthcoming
### Create, Get, and Delete an Azure table

First, we need to construct a `TableServiceClient`.

```C# Snippet:TablesSample1CreateClient
// Construct a new <see cref="TableServiceClient" /> using a <see cref="TableSharedKeyCredential" />.

var serviceClient = new TableServiceClient(
new Uri(storageUri),
new TableSharedKeyCredential(accountName, storageAccountKey));
```

Next, we can create a new table.

```C# Snippet:TablesSample1CreateTable
// Create a new table. The <see cref="TableItem" /> class stores properties of the created table.

TableItem table = serviceClient.CreateTable(tableName);
Console.WriteLine($"The created table's name is {table.TableName}.");
```

The set of existing Azure tables can be queries using an OData filter.

```C# Snippet:TablesSample3QueryTables
// Use the <see cref="TableServiceClient"> to query the service. Passing in OData filter strings is optional.

Pageable<TableItem> queryTableResults = serviceClient.GetTables(filter: $"TableName eq '{tableName}'");

Console.WriteLine("The following are the names of the tables in the query results:");

// Iterate the <see cref="Pageable"> in order to access queried tables.

foreach (TableItem table in queryTableResults)
{
Console.WriteLine(table.TableName);
}
```

Individual tables can bel deleted from the service.
christothes marked this conversation as resolved.
Show resolved Hide resolved

```C# Snippet:TablesSample1DeleteTable
// Deletes the table made previously.

serviceClient.DeleteTable(tableName);
```

### Add, Query, and Delete table entities

To interact with table entities, we must first construct a `TableClient`.

```C# Snippet:TablesSample2CreateTableWithTableClient
// Construct a new <see cref="TableClient" /> using a <see cref="TableSharedKeyCredential" />.

var tableClient = new TableClient(
new Uri(storageUri),
tableName,
new TableSharedKeyCredential(accountName, storageAccountKey));

// Create the table in the service.
tableClient.Create();
```

Let's define a new `TableEntity` so that we can add it to the table.

```C# Snippet:TablesSample2CreateDictionaryEntity
// Make a dictionary entity by defining a <see cref="TableEntity">.

var entity = new TableEntity(partitionKey, rowKey)
{
{ "Product", "Marker Set" },
{ "Price", 5.00 },
{ "Quantity", 21 }
};

Console.WriteLine($"{entity.RowKey}: {entity["Product"]} costs ${entity.GetDouble("Price")}.");
```

Using the `TableClient` we can now add our new entity to the table.

```C# Snippet:TablesSample2AddEntity
// Add the newly created entity.

tableClient.AddEntity(entity);
```

To inspect the set of existing table entities, we can query the table using an OData filter.

```C# Snippet:TablesSample4QueryEntitiesFilter
Pageable<TableEntity> queryResultsFilter = tableClient.Query<TableEntity>(filter: $"PartitionKey eq '{partitionKey}'");

// Iterate the <see cref="Pageable"> to access all queried entities.

foreach (TableEntity qEntity in queryResultsFilter)
{
Console.WriteLine($"{qEntity.GetString("Product")}: {qEntity.GetDouble("Price")}");
}

Console.WriteLine($"The query returned {queryResultsFilter.Count()} entities.");
```

If we no longer need our new table entity, it can be deleted.

```C# Snippet:TablesSample2DeleteEntity
// Delete the entity given the partition and row key.

tableClient.DeleteEntity(partitionKey, rowKey);
```

## Troubleshooting

Content forthcoming
When you interact with the Azure table library using the .NET SDK, errors returned by the service correspond to the same HTTP
status codes returned for [REST API][keyvault_rest] requests.
christothes marked this conversation as resolved.
Show resolved Hide resolved

For example, if you try to retrieve a create a table that already exists, a `409` error is returned, indicating "Conflict".
christothes marked this conversation as resolved.
Show resolved Hide resolved

```C# Snippet:CreateDuplicateTable
// Construct a new TableClient using a connection string.

var client = new TableClient(
connectionString,
tableName);

// Create the table if it doesn't already exist.

client.CreateIfNotExists();

// Now attempt to create the same table unconditionally.

try
{
client.Create();
}
catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.Conflict)
{
Console.WriteLine(ex.ToString());
}
```

## Next steps

Content forthcoming
Get started with our [Table samples](samples/README.MD):


## Contributing

Expand All @@ -38,10 +211,16 @@ the right to, and actually do, grant us the rights to use your contribution. For
details, visit [cla.microsoft.com][cla].

This project has adopted the [Microsoft Open Source Code of Conduct][coc].
For more information see the [Code of Conduct FAQ][coc_faq]
or contact [opencode@microsoft.com][coc_contact] with any
additional questions or comments.
For more information see the [Code of Conduct FAQ][coc_faq] or contact
[opencode@microsoft.com][coc_contact] with any additional questions or comments.

<!-- LINKS -->
[azure_cli]: https://docs.microsoft.com/cli/azure
[azure_sub]: https://azure.microsoft.com/free/
[contrib]: ./CONTRIBUTING.md
[cla]: https://cla.microsoft.com
[coc]: https://opensource.microsoft.com/codeofconduct/
[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
[coc_contact]: mailto:opencode@microsoft.com

![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-net%2Fsdk%2Ftables%2FAzure.Data.Tables%2FREADME.png)
12 changes: 7 additions & 5 deletions sdk/tables/Azure.Data.Tables/samples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ description: Samples for the Azure.Data.Tables client library
Description of Azure Tables. Covers following functions:
* Create and delete a table
* Includes error handling
* Create and delete entities
* Query tables
* Create and delete entities
* Query entities

You can find samples for each of this main functions below.
To get started you'll need an Azure Tables endpoint and credentials. See Azure Tables Client Library [Readme][README] for more information and instructions.

- [Create/delete tables](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/tables/Azure.Data.Tables/samples/Sample1CreateDeleteTables.md)
To get started you'll need an Azure Tables endpoint and credentials. See Azure Tables Client Library [Readme](../readme.md) for more information and instructions.

[README]: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/tables/Azure.Data.Tables/readme.md
- [Create/delete tables](Sample1CreateDeleteTables.md)
- [Query tables](Sample3QueryTables.md)
- [Create/delete table entities](Sample2CreateDeleteEntities.md)
- [Query table entities](Sample4QueryEntities.md)
- [Auth](Sample0Auth.md): Authenticate with connection strings, shared keys, and shared access signatures0.
113 changes: 113 additions & 0 deletions sdk/tables/Azure.Data.Tables/samples/Sample0Auth.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# Authentication

Every request made against an Azure table must be authorized using a connection string,
shared key credential, or shared access signature. The samples below demonstrate the usage
of these methods.

## Connection string

A connection string includes the authentication information required for your application to
access data in an Azure table at runtime using Shared Key authorization.

You can obtain your connection string from the Azure Portal (click **Access Keys** under Settings
in the Portal Storage account blade or **Connection String** under Settings in the Portal Cosmos DB
account blade) or using the Azure CLI with:

```
az storage account show-connection-string --name <account_name> --resource-group <resource_group>
```
or
```
az cosmosdb list-connection-strings --name <account_name> --resource-group <resource_group>
```

```C# Snippet:TablesAuthConnString
// Construct a new TableClient using a connection string.

var client = new TableClient(
connectionString,
tableName);

// Create the table if it doesn't already exist to verify we've successfully authenticated.

await client.CreateIfNotExistsAsync();
```

## Shared Key Credential

Shared Key authorization relies on your account access keys and other parameters to produce
an encrypted signature string that is passed on the request in the Authorization header.

You'll need a Storage or Cosmos DB **account name**, **primary key**, and **endpoint** Uri.
You can obtain both from the Azure Portal by clicking **Access Keys** under Settings in the
Portal Storage account blade or **Connection String** under Settings in the Portal Cosmos DB
account blade.

You can also get access to your account keys from the Azure CLI with:
```
az storage account keys list --account-name <account_name> --resource-group <resource_group>
```
or
```
az cosmosdb list-keys --name <account_name> --resource-group <resource_group>
```

```C# Snippet:TablesAuthSharedKey
// Construct a new TableClient using a TableSharedKeyCredential.

var client = new TableClient(
new Uri(storageUri),
tableName,
new TableSharedKeyCredential(accountName, accountKey));

// Create the table if it doesn't already exist to verify we've successfully authenticated.

await client.CreateIfNotExistsAsync();
```

## Shared Access Signature (SAS)

A shared access signature allows administrators to delegate granular access to an Azure table
without sharing the access key directly. You can control what resources the client may access,
what permissions they have on those resources, and how long the SAS is valid, among other parameters.
It relies on your account access keys and other parameters to produce an encrypted signature string
that is passed on the request in the query string.

To generate a new SAS, you must first start with a Storage or Cosmos DB **account name**, **primary key**, and **endpoint** Uri.
You can obtain both from the Azure Portal by clicking **Access Keys** under Settings in the
Portal Storage account blade or **Connection String** under Settings in the Portal Cosmos DB
account blade.

```C# Snippet:TablesAuthSas
// Construct a new <see cref="TableServiceClient" /> using a <see cref="TableSharedKeyCredential" />.

var credential = new TableSharedKeyCredential(accountName, accountKey);

var serviceClient = new TableServiceClient(
new Uri(storageUri),
credential);

// Build a shared access signature with the Write and Delete permissions and access to all service resource types.

TableAccountSasBuilder sasWriteDelete = serviceClient.GetSasBuilder(TableAccountSasPermissions.Write, TableAccountSasResourceTypes.All, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc));
christothes marked this conversation as resolved.
Show resolved Hide resolved
string tokenWriteDelete = sasWriteDelete.Sign(credential);

// Build SAS URIs.

UriBuilder sasUriWriteDelete = new UriBuilder(storageUri)
{
Query = tokenWriteDelete
};

// Create the TableServiceClients using the SAS URIs.

var serviceClientWithSas = new TableServiceClient(sasUriWriteDelete.Uri);

// Validate that we are able to create a table using the SAS URI with Write and Delete permissions.

await serviceClientWithSas.CreateTableIfNotExistsAsync(tableName);

// Validate that we are able to delete a table using the SAS URI with Write and Delete permissions.

await serviceClientWithSas.DeleteTableAsync(tableName);
```
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ In the sample below, we will use a Storage account and authenticate with an endp

```C# Snippet:TablesSample1CreateClient
// Construct a new <see cref="TableServiceClient" /> using a <see cref="TableSharedKeyCredential" />.

var serviceClient = new TableServiceClient(
new Uri(storageUri),
new TableSharedKeyCredential(accountName, storageAccountKey));
Expand Down Expand Up @@ -38,6 +39,7 @@ To create a table, invoke `CreateTable` with the table name.

```C# Snippet:TablesSample1CreateTable
// Create a new table. The <see cref="TableItem" /> class stores properties of the created table.

TableItem table = serviceClient.CreateTable(tableName);
Console.WriteLine($"The created table's name is {table.TableName}.");
```
Expand All @@ -54,6 +56,7 @@ To delete the table, invoke `DeleteTable` with the table name.

```C# Snippet:TablesSample1DeleteTable
// Deletes the table made previously.

serviceClient.DeleteTable(tableName);
```

Expand Down
Loading