### Client-Wide CallSettings Example Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/docs/devsite-help/call-settings.md This example shows how to configure CallSettings client-wide when creating a client object. These settings apply to all RPC calls made by the client unless overridden. ```cs PublisherServiceApiClient.Create(settings); ``` -------------------------------- ### Start Host with Tracing Enabled Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Cloud.Diagnostics.Common/docs/index.md Start the application host after configuring tracing. This is typically done in the Main method. ```csharp var host = builder.Build(); host.StartAsync().GetAwaiter().GetResult(); ``` -------------------------------- ### Instantiate a client with default credentials Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Maps.Places.V1/docs/index.md Instantiate a client using default credentials. This is the simplest way to get started. Ensure you have authenticated using the `gcloud auth application-default login` command. ```csharp PlacesClient client = await PlacesClient.CreateAsync(); ``` -------------------------------- ### Server-Streaming RPC Example (BigQuery Storage API) Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/docs/devsite-help/grpc-streaming.md This example demonstrates the typical usage pattern for a server-streaming RPC call. It uses a `using` statement to ensure the gRPC call is disposed of automatically and an `await foreach` loop to iterate over the asynchronous response stream. The setup and processing of the query and responses are omitted for brevity. ```cs await using var responseStream = client.ReadRows(request); await foreach (var row in responseStream.ConfigureAwait(false).AsAsyncEnumerable()) { // Process row } ``` -------------------------------- ### Install Google Cloud .NET Libraries Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Cloud.Translate.V3/docs/index.md Use the .NET CLI to install the necessary Google Cloud client libraries for your project. This command adds the specified package to your project's dependencies. ```bash dotnet add package Google.Cloud.Translation.V2 ``` -------------------------------- ### Start Host for Error Reporting Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Cloud.Diagnostics.Common/docs/index.md Starts the host application after configuring error reporting. This is usually done in the `Main` method. ```csharp var host = builder.Build(); host.Run(); ``` -------------------------------- ### Configure ExampleClient using Dependency Injection in ASP.NET Core Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/docs/devsite-help/client-lifecycle.md Configure the `ExampleClient` within an ASP.NET Core application's service collection. This example shows basic registration. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services .AddRazorPages() .AddExampleClient(); ``` -------------------------------- ### Start Google Diagnostics Host Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Cloud.Diagnostics.Common/docs/index.md Ensure the host is started after configuring Google Diagnostics to enable the collection and reporting of diagnostic information. ```csharp public static void Main(string[] args) { CreateHostBuilder(args).Build().Start(); } ``` -------------------------------- ### Configure Tracing for Dependency Injection Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Cloud.Diagnostics.Common/docs/index.md Set up the tracing component for dependency injection. This is the initial step before starting the host. ```csharp services.AddGoogleTrace(options => { options.ProjectId = "YOUR_PROJECT_ID"; }); ``` -------------------------------- ### Create and Fetch ChatRoom with Snapshot Attributes Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Cloud.Firestore/docs/datamodel.md Example of creating a chat room document and then fetching it, demonstrating how snapshot attributes automatically populate document metadata. ```csharp var chatRoom = new ChatRoom { Name = "Firestore Discussion" }; await chatRoomsCollection.AddAsync(chatRoom); DocumentSnapshot snapshot = await chatRoomsCollection.Document(chatRoom.Id).GetAsync(); ChatRoom fetchedChatRoom = snapshot.ConvertTo(); Console.WriteLine($"Fetched chat room: {fetchedChatRoom.Name}"); Console.WriteLine($"Created at: {fetchedChatRoom.CreateTime}"); ``` -------------------------------- ### Per-RPC-Method CallSettings Example Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/docs/devsite-help/call-settings.md This snippet illustrates setting CallSettings for a specific RPC method during client creation. This has the lowest priority and is useful for method-specific configurations. ```cs PublisherServiceApiSettings.CreateTopicSettings = PublisherServiceApiSettings.CreateTopicSettings.WithCallSettings(callSettings); ``` -------------------------------- ### Per-RPC CallSettings Example Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/docs/devsite-help/call-settings.md This snippet demonstrates how to specify CallSettings directly when calling an RPC method, offering the highest priority for customization. ```cs await publisher.CreateTopicAsync("New Topic", cancellationToken: callSettings.CancellationToken); ``` -------------------------------- ### Build ExampleClient with JSON Credentials Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/docs/devsite-help/client-lifecycle.md Use the `ExampleClientBuilder` to construct a client with specific JSON credentials. This is useful when you have credentials stored in a JSON file. ```csharp var client = new ExampleClientBuilder { JsonCredentials = json }.Build(); ``` -------------------------------- ### Implement OCC with IAM using Google.Cloud.PubSub.V1 Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/docs/devsite-help/occ.md This C# example demonstrates how to implement Optimistic Concurrency Control (OCC) when updating IAM policies. It shows how to use the Etag value to ensure that the policy has not been modified since it was last retrieved. Ensure you have the necessary Google Cloud client libraries installed. ```csharp public static async Task UpdatePolicyWithOccAsync(string projectId, string topicId, string etag, IEnumerable bindings) { var publisherClient = await PublisherClient.CreateAsync(); var topicName = TopicName.FromProjectTopic(projectId, topicId); var policy = new Policy { Bindings = { bindings }, Etag = ByteString.CopyFromUtf8(etag) }; try { policy = await publisherClient.SetIamPolicyAsync(topicName, policy); Console.WriteLine($"Policy updated successfully. Etag: {policy.Etag}"); return policy; } catch (RpcException e) when (e.Status.StatusCode == StatusCode.Aborted) { Console.WriteLine("Failed to update policy due to OCC conflict. Etag mismatch."); // Handle the OCC conflict, e.g., re-fetch the policy and re-apply changes. throw; } } ``` -------------------------------- ### Build and Deploy Sample App to Cloud Run Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Cloud.Logging.Console/README.md Commands to build the console formatter sample application and deploy it to Google Cloud Run. Ensure the GOOGLE_CLOUD_PROJECT environment variable is set. ```sh gcloud builds submit --tag gcr.io/$GOOGLE_CLOUD_PROJECT/console-formatter ``` ```sh gcloud run deploy --platform managed --image gcr.io/$GOOGLE_CLOUD_PROJECT/console-formatter ``` -------------------------------- ### Install Google Cloud Translation Library Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/docs/devsite-help/getting-started.md Installs the Google.Cloud.Translate.V3 NuGet package into a new console application. Ensure pre-release packages are enabled if installing a prerelease version. ```sh mkdir TranslationExample cd TranslationExample dotnet new console dotnet add package Google.Cloud.Translate.V3 ``` -------------------------------- ### Create SpeechClient with Default Settings (C#) Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/docs/devsite-help/breaking-gax2.md Demonstrates synchronous client creation using the default endpoint, credentials, and settings. ```csharp var client1 = SpeechClient.Create(); ``` -------------------------------- ### Populate Vision Product Search Test Set Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/TESTING.md Run this .NET command to create the product set required for Vision API snippets. Replace {YOUR_PROJECT_ID} with your actual project ID. Allow about 30 minutes for model training. ```bash dotnet run -p Google.Cloud.Vision.V1.PopulateProductSearchTestSet -- Google.Cloud.Vision.V1.Snippets {YOUR_PROJECT_ID} ``` -------------------------------- ### Build Docker Image for google-cloud-dotnet Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/ENVIRONMENT.md Use this command to build the Docker image. Building the image the first time can be slow. ```bash docker build -t google-cloud-dotnet docker ``` -------------------------------- ### Start Bigtable Emulator Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/TESTING.md Use this command to start the Bigtable emulator locally. Ensure the BIGTABLE_EMULATOR_HOST environment variable is set to localhost:8086. ```bash gcloud beta emulators bigtable start ``` -------------------------------- ### Start a Trace for Each Request/Event (Optional) Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Cloud.Diagnostics.Common/docs/index.md Start a trace for each request or event when the emitter does not provide trace context. Set `shouldTrace` to `null` to allow the tracer to decide based on tracing rates. ```csharp var tracer = serviceProvider.GetRequiredService(); var traceContext = tracer.CreateTraceContext(shouldTrace: null); traceContext.RunInSpan("my-span", async () => { // Your code here }); ``` -------------------------------- ### Create SpeechClient Asynchronously with Defaults (C#) Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/docs/devsite-help/breaking-gax2.md Shows how to create a SpeechClient instance asynchronously using default configurations. ```csharp var client2 = await SpeechClient.CreateAsync(); ``` -------------------------------- ### Build Client with Service Account Credentials Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/docs/devsite-help/client-configuration.md Use this to construct a client when you have service account credentials in JSON format. Ensure the JSON contains valid credentials. ```csharp var credential = CredentialFactory.FromJson(json).ToGoogleCredential(); var client = new ExampleClientBuilder { GoogleCredential = credential }.Build(); ``` -------------------------------- ### Get Firestore Document and Collection References Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Cloud.Firestore/docs/userguide.md Demonstrates how to obtain DocumentReference and CollectionReference objects from a FirestoreDb instance using their paths. ```csharp string projectId = "your-project-id"; FirestoreDb db = FirestoreDb.Create(projectId); // Get a reference to a document DocumentReference docRef = db.Collection("users").Document("alovelace"); // Get a reference to a collection CollectionReference collRef = db.Collection("users"); // Get a reference to a subcollection CollectionReference subCollRef = docRef.Collection("posts"); // Get a reference to a subdocument DocumentReference subDocRef = collRef.Document("aturing").Collection("books").Document("book1"); ``` -------------------------------- ### Use SubscriberService in a Console Application Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Cloud.PubSub.V1/docs/index.md An example console application demonstrating the use of dependency injection and `SubscriberService` for handling Pub/Sub messages. ```csharp using Google.Cloud.PubSub.V1; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; var host = Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.AddSubscriberClient(); services.AddHostedService(); }) .Build(); await host.RunAsync(); ``` -------------------------------- ### Register Service with PublisherClient and Use It Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Cloud.PubSub.V1/docs/index.md Demonstrates registering a custom service (MyService) with the DI container, which depends on PublisherClient, and then shows how to use the PublisherClient within that service. ```csharp using Google.Cloud.PubSub.V1; using Microsoft.Extensions.DependencyInjection; public class MyService { private readonly PublisherClient _publisherClient; public MyService(PublisherClient publisherClient) { _publisherClient = publisherClient; } public async Task PublishMessageAsync(string topicId, string message) => await _publisherClient.PublishAsync(topicId, message); } public static class ServiceCollectionExtensions { public static IServiceCollection AddMyServices(this IServiceCollection services) { // Register PublisherClient (assuming AddPublisherClient is defined elsewhere) services.AddPublisherClient(); // Register MyService services.AddTransient(); return services; } } ``` -------------------------------- ### Translate Text Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Cloud.Translate.V3/docs/index.md Use the `TranslationServiceClient` to translate text from a source language to a target language. This example demonstrates a simple text translation. ```csharp string text = "Hello, world!"; string targetLanguage = "es"; // Spanish // Perform the translation TranslationResponse response = client.Translate( text, targetLanguage); Console.WriteLine($"Original text: {text}"); Console.WriteLine($"Translated text: {response.TranslatedText}"); ``` -------------------------------- ### Simple Publisher and Subscriber Overview Source: https://github.com/googleapis/google-cloud-dotnet/blob/main/apis/Google.Cloud.PubSub.V1/docs/index.md Demonstrates basic message publishing and subscribing using PublisherClient and SubscriberClient. Suitable for general use cases. ```csharp using Google.Cloud.PubSub.V1; public class SimpleOverview { public void PublishAndSubscribe(string projectId, string topicId, string subscriptionId) { // Create a PublisherClient and SubscriberClient. PublisherClient publisher = new PublisherClient(projectId, topicId); SubscriberClient subscriber = new SubscriberClient(projectId, subscriptionId); // Publish a message. var message = "Hello, Pub/Sub!"; var publishedMessage = publisher.Publish(message); System.Console.WriteLine($"Published message ID: {publishedMessage.Message.MessageId}"); // Subscribe to messages. subscriber.StartAsync(async (msg, cancellationToken) => { System.Console.WriteLine($"Received message: {msg.Message.Data}"); // Acknowledge the message. return SubscriberClient.Reply.Ack; }); // Keep the subscriber running for a while to receive messages. System.Threading.Thread.Sleep(System.TimeSpan.FromSeconds(10)); // Stop the subscriber. subscriber.StopAsync(System.Threading.CancellationToken.None).Wait(); } } ```