C# hello world
This code sample is a "hello world" application written in C#. The sampleillustrates how to complete the following tasks:
- Set up authentication
- Connect to a Bigtable instance
- Create a new table.
- Write data to the table.
- Read the data back.
- Delete the table.
Set up authentication
To use the .NET samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Running the sample
This code communicates with Bigtable using theC# Admin API andC# Data API libraries intheGoogle Cloud Client Libraries for .NET.
To run this sample program, follow the.NET Bigtable Samples instructions on GitHub.Complete theBuild and Run andQuick Start steps to create resourcesthat you can use in your Hello World application. Make sure you edit theHelloWorld.cs file to add the names of the resources you create.
Using the Cloud Client Libraries with Bigtable
The sample application connects to Bigtable and demonstrates somesimple operations.
Connecting to Bigtable
To get started, create two client objects that you can use to connect toBigtable. The C# Admin APIsBigtableTableAdminClient helps you create and delete instances and tables. The C#Data APIsBigtableClient helps you read and write tabledata.
// BigtableTableAdminClient API lets us create, manage and delete tables.BigtableTableAdminClientbigtableTableAdminClient=BigtableTableAdminClient.Create();// BigtableClient API lets us read and write to a table.BigtableClientbigtableClient=BigtableClient.Create();Creating a table
Call theCreateTable() method in theBigtableTableAdminClient class togenerate aTable object that stores the "helloworld" greetings. The table has a single column family that retains one versionof each value.
// Create a table with a single column family.Console.WriteLine($"Create new table: {tableId} with column family: {columnFamily}, instance: {instanceId}");// Check whether a table with given TableName already exists.if(!TableExist(bigtableTableAdminClient)){bigtableTableAdminClient.CreateTable(newInstanceName(projectId,instanceId),tableId,newTable{Granularity=Table.Types.TimestampGranularity.Millis,ColumnFamilies={{columnFamily,newColumnFamily{GcRule=newGcRule{MaxNumVersions=1}}}}});// Confirm that table was created successfully.Console.WriteLine(TableExist(bigtableTableAdminClient)?$"Table {tableId} created successfully\n":$"There was a problem creating a table {tableId}");}else{Console.WriteLine($"Table: {tableId} already exists");}Writing rows to a table
Use the string arrays_greetings[], which contains three simple greetings, asa source of data to write to the table. First, write a single row to the tableusingMutateRow(). Then loop through the restof the array to build aMutateRowsRequest objectthat contains an entry for each greeting. Make the request to write all theentries at once withMutateRows(). Then loopthrough the returned response to check the status code for each entry to makesure it was written successfully.
// Initialize Google.Cloud.Bigtable.V2.TableName object.Google.Cloud.Bigtable.Common.V2.TableNametableName=newGoogle.Cloud.Bigtable.Common.V2.TableName(projectId,instanceId,tableId);// Write some rows/* Each row has a unique row key. Note: This example uses sequential numeric IDs for simplicity, but this can result in poor performance in a production application. Since rows are stored in sorted order by key, sequential keys can result in poor distribution of operations across nodes. For more information about how to design a Bigtable schema for the best performance, see the documentation: https://cloud.google.com/bigtable/docs/schema-design */Console.WriteLine($"Write some greetings to the table {tableId}");// Insert 1 row using MutateRow()s_greetingIndex=0;try{bigtableClient.MutateRow(tableName,rowKeyPrefix+s_greetingIndex,MutationBuilder());Console.WriteLine($"\tGreeting: -- {s_greetings[s_greetingIndex],-18}-- written successfully");}catch(Exceptionex){Console.WriteLine($"\tFailed to write greeting: --{s_greetings[s_greetingIndex]}");Console.WriteLine(ex.Message);throw;}// Insert multiple rows using MutateRows()// Build a MutateRowsRequest (contains table name and a collection of entries).MutateRowsRequestrequest=newMutateRowsRequest{TableNameAsTableName=tableName};s_mapToOriginalGreetingIndex=newList<int>();while(++s_greetingIndex <s_greetings.Length){s_mapToOriginalGreetingIndex.Add(s_greetingIndex);// Build an entry for every greeting (consists of rowkey and a collection of mutations).stringrowKey=rowKeyPrefix+s_greetingIndex;request.Entries.Add(Mutations.CreateEntry(rowKey,MutationBuilder()));}// Make the request to write multiple rows.MutateRowsResponseresponse=bigtableClient.MutateRows(request);// Check the status code of each entry to ensure that it was written successfully.foreach(MutateRowsResponse.Types.Entryentryinresponse.Entries){s_greetingIndex=s_mapToOriginalGreetingIndex[(int)entry.Index];if(entry.Status.Code==0){Console.WriteLine($"\tGreeting: -- {s_greetings[s_greetingIndex],-18}-- written successfully");}else{Console.WriteLine($"\tFailed to write greeting: --{s_greetings[s_greetingIndex]}");Console.WriteLine(entry.Status.Message);}}MutationMutationBuilder()=>Mutations.SetCell(columnFamily,columnName,s_greetings[s_greetingIndex],newBigtableVersion(DateTime.UtcNow));Creating a filter
Before you read the data that you wrote, create a filter to limit the data thatBigtable returns. This filter tells Bigtable toreturn only the most recent version of each value, even if the table containsolder cells that are eligible for garbage collection but have not yet been deleted.
RowFilterfilter=RowFilters.CellsPerRowLimit(1);Reading a row by its row key
Use theReadRow() method, passing in the filteryou just created, to get one version of each value in that row.
// Read from the table.Console.WriteLine("Read the first row");introwIndex=0;// Read a specific row. Apply a filter to return latest only cell value accross entire row.RowrowRead=bigtableClient.ReadRow(tableName,rowKey:rowKeyPrefix+rowIndex,filter:filter);Console.WriteLine($"\tRow key: {rowRead.Key.ToStringUtf8()} "+$" -- Value: {rowRead.Families[0].Columns[0].Cells[0].Value.ToStringUtf8(),-16} "+$" -- Time Stamp: {rowRead.Families[0].Columns[0].Cells[0].TimestampMicros}");Scanning all table rows
Call theReadRows() method, passing in thefilter, to get all of the rows in the table. Because you passed in the filter,Bigtable returns only one version of each value.
Console.WriteLine("Read all rows using streaming");// stream the content of the whole table. Apply a filter to return latest only cell values accross all rows.ReadRowsStreamresponseRead=bigtableClient.ReadRows(tableName,filter:filter);TaskprintRead=PrintReadRowsAsync();printRead.Wait();asyncTaskPrintReadRowsAsync(){varresponseEnumerator=responseRead.GetAsyncEnumerator(default);while(awaitresponseEnumerator.MoveNextAsync()){Rowrow=responseEnumerator.Current;Console.WriteLine($"\tRow key: {row.Key.ToStringUtf8()} "+$" -- Value: {row.Families[0].Columns[0].Cells[0].Value.ToStringUtf8(),-16} "+$" -- Time Stamp: {row.Families[0].Columns[0].Cells[0].TimestampMicros}");}}Deleting a table
Delete the table with theDeleteTable() method.
// Clean up. Delete the table.Console.WriteLine($"Delete table: {tableId}");bigtableTableAdminClient.DeleteTable(name:tableName);if(!TableExist(bigtableTableAdminClient)){Console.WriteLine($"Table: {tableId} deleted successfully");}Putting it all together
Here is the full code sample without comments.
usingGoogle.Cloud.Bigtable.Admin.V2;usingGoogle.Cloud.Bigtable.Common.V2;usingGoogle.Cloud.Bigtable.V2;usingGrpc.Core;usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;namespaceGoogleCloudSamples.Bigtable{publicclassHelloWorld{privateconststringprojectId="YOUR-PROJECT-ID";privateconststringinstanceId="YOUR-INSTANCE-ID";privateconststringtableId="Hello-Bigtable";privateconststringcolumnFamily="cf";privateconststringcolumnName="greeting";privatestaticreadonlystring[]s_greetings={"Hello World!","Hello Bigtable!","Hello C#!"};privatestaticList<int>s_mapToOriginalGreetingIndex;privateconststringrowKeyPrefix="greeting";privatestaticints_greetingIndex;privatestaticvoidDoHelloWorld(){try{BigtableTableAdminClientbigtableTableAdminClient=BigtableTableAdminClient.Create();BigtableClientbigtableClient=BigtableClient.Create();Console.WriteLine($"Create new table: {tableId} with column family: {columnFamily}, instance: {instanceId}");if(!TableExist(bigtableTableAdminClient)){bigtableTableAdminClient.CreateTable(newInstanceName(projectId,instanceId),tableId,newTable{Granularity=Table.Types.TimestampGranularity.Millis,ColumnFamilies={{columnFamily,newColumnFamily{GcRule=newGcRule{MaxNumVersions=1}}}}});Console.WriteLine(TableExist(bigtableTableAdminClient)?$"Table {tableId} created successfully\n":$"There was a problem creating a table {tableId}");}else{Console.WriteLine($"Table: {tableId} already exists");}Google.Cloud.Bigtable.Common.V2.TableNametableName=newGoogle.Cloud.Bigtable.Common.V2.TableName(projectId,instanceId,tableId);Note:ThisexampleusessequentialnumericIDsforsimplicity,butthiscanresultinpoorperformanceinaproductionapplication.Sincerowsarestoredinsortedorderbykey,sequentialkeyscanresultinpoordistributionofoperationsacrossnodes.FormoreinformationabouthowtodesignaBigtableschemaforthebestperformance,seethedocumentation:https://cloud.google.com/bigtable/docs/schema-design */Console.WriteLine($"Write some greetings to the table {tableId}");s_greetingIndex=0;try{bigtableClient.MutateRow(tableName,rowKeyPrefix+s_greetingIndex,MutationBuilder());Console.WriteLine($"\tGreeting: -- {s_greetings[s_greetingIndex],-18}-- written successfully");}catch(Exceptionex){Console.WriteLine($"\tFailed to write greeting: --{s_greetings[s_greetingIndex]}");Console.WriteLine(ex.Message);throw;}MutateRowsRequestrequest=newMutateRowsRequest{TableNameAsTableName=tableName};s_mapToOriginalGreetingIndex=newList<int>();while(++s_greetingIndex <s_greetings.Length){s_mapToOriginalGreetingIndex.Add(s_greetingIndex);stringrowKey=rowKeyPrefix+s_greetingIndex;request.Entries.Add(Mutations.CreateEntry(rowKey,MutationBuilder()));}MutateRowsResponseresponse=bigtableClient.MutateRows(request);foreach(MutateRowsResponse.Types.Entryentryinresponse.Entries){s_greetingIndex=s_mapToOriginalGreetingIndex[(int)entry.Index];if(entry.Status.Code==0){Console.WriteLine($"\tGreeting: -- {s_greetings[s_greetingIndex],-18}-- written successfully");}else{Console.WriteLine($"\tFailed to write greeting: --{s_greetings[s_greetingIndex]}");Console.WriteLine(entry.Status.Message);}}MutationMutationBuilder()=>Mutations.SetCell(columnFamily,columnName,s_greetings[s_greetingIndex],newBigtableVersion(DateTime.UtcNow));RowFilterfilter=RowFilters.CellsPerRowLimit(1);Console.WriteLine("Read the first row");introwIndex=0;RowrowRead=bigtableClient.ReadRow(tableName,rowKey:rowKeyPrefix+rowIndex,filter:filter);Console.WriteLine($"\tRow key: {rowRead.Key.ToStringUtf8()} "+$" -- Value: {rowRead.Families[0].Columns[0].Cells[0].Value.ToStringUtf8(),-16} "+$" -- Time Stamp: {rowRead.Families[0].Columns[0].Cells[0].TimestampMicros}");Console.WriteLine("Read all rows using streaming");ReadRowsStreamresponseRead=bigtableClient.ReadRows(tableName,filter:filter);TaskprintRead=PrintReadRowsAsync();printRead.Wait();asyncTaskPrintReadRowsAsync(){varresponseEnumerator=responseRead.GetAsyncEnumerator(default);while(awaitresponseEnumerator.MoveNextAsync()){Rowrow=responseEnumerator.Current;Console.WriteLine($"\tRow key: {row.Key.ToStringUtf8()} "+$" -- Value: {row.Families[0].Columns[0].Cells[0].Value.ToStringUtf8(),-16} "+$" -- Time Stamp: {row.Families[0].Columns[0].Cells[0].TimestampMicros}");}}Console.WriteLine($"Delete table: {tableId}");bigtableTableAdminClient.DeleteTable(name:tableName);if(!TableExist(bigtableTableAdminClient)){Console.WriteLine($"Table: {tableId} deleted successfully");}}catch(Exceptionex){Console.WriteLine($"Exception while running HelloWorld: {ex.Message}");}}privatestaticboolTableExist(BigtableTableAdminClientbigtableTableAdminClient){GetTableRequestrequest=newGetTableRequest{TableName=newGoogle.Cloud.Bigtable.Common.V2.TableName(projectId,instanceId,tableId),View=Table.Types.View.NameOnly};try{vartables=bigtableTableAdminClient.GetTable(request);returntrue;}catch(RpcExceptionex){if(ex.StatusCode==StatusCode.NotFound){returnfalse;}throw;}}publicstaticintMain(string[]args){if(projectId=="YOUR-PROJECT"+"-ID"){Console.WriteLine("Edit HelloWorld.cs and replace YOUR-PROJECT-ID with your project ID.");return-1;}if(instanceId=="YOUR-INSTANCE"+"-ID"){Console.WriteLine("Edit HelloWorld.cs and replace YOUR-INSTANCE-ID with your instance ID.");return-1;}DoHelloWorld();return0;}}}Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.