The Google Ads API client library provides several configuration settings that you can
use to customize the library behavior.

## Configure the library at runtime

The preferred way to configure the client library is to initialize a
`GoogleAdsConfig` object at runtime:

    using Google.Ads.Gax.Config;
    using Google.Ads.GoogleAds.Config;
    using Google.Ads.GoogleAds.Lib;

    GoogleAdsConfig config = new GoogleAdsConfig()
    {
        OAuth2Mode = OAuth2Flow.APPLICATION,
        OAuth2ClientId = "INSERT_CLIENT_ID.apps.googleusercontent.com",
        OAuth2ClientSecret = "INSERT_CLIENT_SECRET",
        OAuth2RefreshToken = "INSERT_REFRESH_TOKEN",
        LoginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
    };

    GoogleAdsClient client = new GoogleAdsClient(config);

## Alternate configuration options

The library also provides additional options to load configuration settings from
`appsettings.json`, custom JSON files, environment variables, or `App.config`.
To enable them, install the
[`Google.Ads.GoogleAds.Extensions` NuGet package](https://www.nuget.org/packages/Google.Ads.GoogleAds.Extensions/) in your
project:

    dotnet add package Google.Ads.GoogleAds.Extensions

If you use one of these options, configuration settings are not picked up
automatically; you must explicitly load them as shown in the following
sections. Make sure to handle file I/O exceptions (such as
`FileNotFoundException` or `UnauthorizedAccessException`) when loading settings
from external files or streams.

### Use appsettings.json or settings.json

In `.NET 8.0` and ASP.NET Core applications, place your configuration keys
inside a `GoogleAdsApi` section in `appsettings.json` (or `settings.json`):

    {
      "GoogleAdsApi": {
        "LoginCustomerId": "INSERT_LOGIN_CUSTOMER_ID_HERE",
        "OAuth2Mode": "APPLICATION",
        "OAuth2ClientId": "INSERT_CLIENT_ID.apps.googleusercontent.com",
        "OAuth2ClientSecret": "INSERT_CLIENT_SECRET",
        "OAuth2RefreshToken": "INSERT_REFRESH_TOKEN"
      }
    }

Next, extract the `GoogleAdsApi` section from your application's
`IConfiguration` instance (for example, injected by ASP.NET Core or built with
`ConfigurationBuilder`) and load it with `LoadFromConfigurationSection`:

    using Google.Ads.GoogleAds.Config;
    using Google.Ads.GoogleAds.Extensions.Config;
    using Google.Ads.GoogleAds.Lib;
    using Microsoft.Extensions.Configuration;

    IConfigurationSection section = configuration.GetSection("GoogleAdsApi");
    GoogleAdsConfig config = new GoogleAdsConfig();
    config.LoadFromConfigurationSection(section);
    GoogleAdsClient client = new GoogleAdsClient(config);

Alternatively, you can load an `appsettings.json` or `settings.json` file
directly by path using `LoadFromSettingsJson`:

    using Google.Ads.GoogleAds.Config;
    using Google.Ads.GoogleAds.Extensions.Config;
    using Google.Ads.GoogleAds.Lib;

    GoogleAdsConfig config = new GoogleAdsConfig();
    config.LoadFromSettingsJson("appsettings.json", "GoogleAdsApi");
    GoogleAdsClient client = new GoogleAdsClient(config);

You can also load the path from the `GOOGLE_ADS_CONFIGURATION_FILE_PATH`
environment variable (`EnvironmentVariableNames.CONFIG_FILE_PATH`) by calling
`config.TryLoadFromEnvironmentFilePath`.

### Use a custom JSON file

You can also use an [`IConfigurationRoot`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.iconfigurationroot) instance to load a
flat JSON file without a top-level `GoogleAdsApi` section.

#### Create a JSON file

Create a JSON file named `GoogleAdsApi.json` that defines the configuration keys
at the root level:

    {
      "Timeout": "2000",
      "ProxyServer": "http://localhost:8888",
      "ProxyUser": "",
      "ProxyPassword": "",
      "ProxyDomain": "",
      "LoginCustomerId": "INSERT_LOGIN_CUSTOMER_ID_HERE",
      "OAuth2Mode": "APPLICATION",
      "OAuth2ClientId": "INSERT_CLIENT_ID.apps.googleusercontent.com",
      "OAuth2ClientSecret": "INSERT_CLIENT_SECRET",
      "OAuth2RefreshToken": "INSERT_REFRESH_TOKEN"
    }

#### Load the configuration

Next, load the JSON file into an `IConfigurationRoot`:

    using System.IO;
    using Google.Ads.GoogleAds.Config;
    using Google.Ads.GoogleAds.Extensions.Config;
    using Google.Ads.GoogleAds.Lib;
    using Microsoft.Extensions.Configuration;

    ConfigurationBuilder builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("GoogleAdsApi.json");
    IConfigurationRoot configRoot = builder.Build();

    GoogleAdsConfig config = new GoogleAdsConfig();
    config.LoadFromConfigurationRoot(configRoot);
    GoogleAdsClient client = new GoogleAdsClient(config);

### Use environment variables

You can also initialize the `GoogleAdsClient` using environment variables:

    using Google.Ads.GoogleAds.Config;
    using Google.Ads.GoogleAds.Extensions.Config;
    using Google.Ads.GoogleAds.Lib;

    GoogleAdsConfig config = new GoogleAdsConfig();
    config.LoadFromEnvironmentVariables();
    GoogleAdsClient client = new GoogleAdsClient(config);

> [!NOTE]
> **Note:** Because `GoogleAdsConfig.OAuth2Mode` defaults to `APPLICATION`, when authenticating with a service account using `GOOGLE_ADS_JSON_KEY_FILE_PATH`, make sure to also set `GOOGLE_ADS_OAUTH2_MODE=SERVICE_ACCOUNT`.

See the [full list of supported environment variables](https://developers.google.com/google-ads/api/docs/client-libs#configuration).

### Use App.config

In `.NET Framework` applications, all settings specific to the Google Ads API are
stored in the `GoogleAdsApi` node of the `App.config` file. A typical
configuration `App.config` is as follows:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <section name="GoogleAdsApi"
                 type="System.Configuration.DictionarySectionHandler" />
      </configSections>
      <GoogleAdsApi>
        <!-- Set the service timeout in milliseconds. -->
        <add key="Timeout" value="2000" />

        <!-- Proxy settings for library. -->
        <add key="ProxyServer" value="http://localhost:8888" />
        <add key="ProxyUser" value="" />
        <add key="ProxyPassword" value="" />
        <add key="ProxyDomain" value="" />

        <!-- Google Ads API settings. -->
        <add key="LoginCustomerId" value="INSERT_LOGIN_CUSTOMER_ID_HERE" />

        <!-- OAuth2 settings -->
        <add key="OAuth2Mode" value="APPLICATION" />
        <add key="OAuth2ClientId"
             value="INSERT_CLIENT_ID.apps.googleusercontent.com" />
        <add key="OAuth2ClientSecret" value="INSERT_CLIENT_SECRET" />
        <add key="OAuth2RefreshToken" value="INSERT_REFRESH_TOKEN" />
      </GoogleAdsApi>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
      </startup>
    </configuration>

To load configuration settings from an `App.config` file, call the
`LoadFromDefaultAppConfigSection` method on a `GoogleAdsConfig` object:

    using Google.Ads.GoogleAds.Config;
    using Google.Ads.GoogleAds.Extensions.Config;
    using Google.Ads.GoogleAds.Lib;

    GoogleAdsConfig config = new GoogleAdsConfig();
    config.LoadFromDefaultAppConfigSection();
    GoogleAdsClient client = new GoogleAdsClient(config);

### Specify a separate App.config file

If you don't want your `App.config` cluttered, you can move the
library-specific configuration into its own configuration file using the
[`configSource`](https://learn.microsoft.com/en-us/dotnet/api/system.configuration.sectioninformation.configsource) property:

1. **Specify a `configSource` in your `App.config`.** Modify your `App.config`
   to reference an external configuration file:

       <?xml version="1.0" encoding="utf-8" ?>
       <configuration>
         <configSections>
           <section name="GoogleAdsApi"
                    type="System.Configuration.DictionarySectionHandler" />
         </configSections>
         <GoogleAdsApi configSource="GoogleAdsApi.config" />
       </configuration>

2. **Specify the contents of your config file.** Create another configuration
   file with the name you specified in `configSource` (`GoogleAdsApi.config`),
   and move the `GoogleAdsApi` configuration node from your `App.config` into
   this file:

       <?xml version="1.0" encoding="utf-8" ?>
       <GoogleAdsApi>
         <!-- More settings. -->
       </GoogleAdsApi>

3. **Update the build rules in your `.csproj`.** Include the new configuration
   file in your project and set its **Copy to Output Directory** property to
   **Copy always**. Rebuild and run your project so your application picks up
   values from the new configuration file.

### Use a generic stream

You can also load the configuration, or parts of it, from a generic stream,
including an encrypted one:

    GoogleAdsConfig config = new GoogleAdsConfig()
    {
        // Set some configuration properties in code.
        OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
    };

    // Load your encrypted data from a file and dispose of the streams properly.
    using (CryptoStream strm = GetEncryptedCredentialsStream())
    using (StreamReader rdr = new StreamReader(strm))
    {
        // Configure the OAuth credentials from the encrypted stream.
        config.LoadOAuth2SecretsFromStream(rdr);
    }

    GoogleAdsClient client = new GoogleAdsClient(config);

## Configuration fields

The following sections list the settings supported by the Google Ads .NET library.

### Connectivity settings

- `Timeout`: Use this key to set the service timeout in milliseconds. The default value is set based on the `method_config/timeout` setting in [`googleads_grpc_service_config.json`](https://github.com/googleapis/googleapis/tree/HEAD/google/ads/googleads/v26/googleads_grpc_service_config.json). Set a lower value if you need to enforce a shorter limit on the maximum time for an API call. You can set the timeout to 2 hours or more, but the API may still time out extremely long-running requests and return a [`DEADLINE_EXCEEDED`](https://developers.google.com/google-ads/api/reference/rpc/v26/InternalErrorEnum.InternalError) error.
- `ProxyServer`: Set this to the HTTP proxy server URL if you are using a proxy to connect to the internet.
- `ProxyUser`: Set this to the username you require to authenticate against the proxy server. Leave this empty if a username is not required.
- `ProxyPassword`: Set this to the password of `ProxyUser` if you set a value for `ProxyUser`.
- `ProxyDomain`: Set this to the domain for `ProxyUser` if your proxy server requires one to be set.
- `MaxReceiveMessageLengthInBytes`: Use this setting to increase the maximum size of the API response that the client library can handle. The default value is 64 MB.
- `MaxMetadataSizeInBytes`: Use this setting to increase the maximum size of the API error response that the client library can handle. The default value is 16 MB.

Adjust the `MaxReceiveMessageLengthInBytes` and `MaxMetadataSizeInBytes`
settings to fix certain `ResourceExhausted` errors. These settings address
errors of the form:

    Status(StatusCode="ResourceExhausted",Detail="Received
    message larger than max (423184132 versus 67108864)"

In this example, the error is due to the message size (`423184132 bytes`)
being larger than what the library can handle (`67108864 bytes`). Increase
`MaxReceiveMessageLengthInBytes` to `500000000` to avoid this error. Note
that the error also indicates that your code handled a significantly large
response object (such as a large [`SearchGoogleAdsResponse`](https://developers.google.com/google-ads/api/reference/rpc/v26/SearchGoogleAdsResponse)).
This could have performance implications for your code due to .NET's
[Large Object Heap](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/large-object-heap#loh-performance-implications). If this becomes a performance concern, then you might
have to explore how to reorganize your API calls or redesign parts of your app.

### OAuth2 settings

When using OAuth 2.0 to authorize your calls against the Google Ads API servers, you
should set the following configuration keys:

- `AuthorizationMethod`: Set to `OAuth2`.
- `OAuth2Mode`: Set to `APPLICATION` or `SERVICE_ACCOUNT`.
- `OAuth2ClientId`: Set this value to your OAuth 2.0 client ID.
- `OAuth2ClientSecret`: Set this value to your OAuth 2.0 client secret.
- `OAuth2Scope`: Set this value to different scopes if you want to authorize OAuth 2.0 tokens for multiple APIs. This setting is optional.
- `UseApplicationDefaultCredentials`: Set this value to `true` to authenticate using Application Default Credentials (supported in `Google.Ads.GoogleAds` `v24.1.0` and later; `config.LoadFromEnvironmentVariables()` reads the unprefixed `USE_APPLICATION_DEFAULT_CREDENTIALS` environment variable).
- `Credentials`: *(Runtime only, supported in `v27.0.0` and later)* Inject a pre-constructed `ICredential` or `GoogleCredential` instance directly on `GoogleAdsConfig` at runtime.

If you're using `OAuth2Mode == APPLICATION`, then you need to set the following
additional configuration keys:

- `OAuth2RefreshToken`: Set this value to a pre-generated OAuth 2.0 refresh token if you want to reuse OAuth 2.0 tokens. This setting is optional.
- `OAuth2RedirectUri`: Set this value to the OAuth 2.0 redirect URL. This setting is optional.

See the following guides for more details:

- [OAuth desktop application flow](https://developers.google.com/google-ads/api/docs/oauth/single-user-authentication)
- [OAuth web application flow](https://developers.google.com/google-ads/api/docs/oauth/multi-user-authentication)

If you are using `OAuth2Mode == SERVICE_ACCOUNT`, then you need to set the
following additional configuration keys:

- `OAuth2SecretsJsonPath`: Set this value to the path of the OAuth 2.0 JSON key file.
- `OAuth2PrnEmail`: Set this value to the email address of the account you are impersonating when using Google Workspace domain-wide delegation. This setting is optional.

See the [OAuth service account flow](https://developers.google.com/google-ads/api/docs/oauth/service-accounts) guide for more details.

### Transportation settings

- `UseGrpcCore`: Set this setting to `true` to use the `Grpc.Core` library as the underlying transport layer. See [Use the `Grpc.Core` library](https://developers.google.com/google-ads/api/docs/client-libs/dotnet/basic-usage#grpc-core).

### Google Ads API settings

The following settings are specific to the Google Ads API:

- `LoginCustomerId`: This is the customer ID of the authorized customer to use in the request, without hyphens (`-`).
- `LinkedCustomerId`: This header is only required for methods that update the resources of an entity when permissioned through Linked Accounts in the Google Ads UI (`AccountLink` resource in the Google Ads API). Set this value to the customer ID of the data provider that updates the resources of the specified customer ID. It should be set without hyphens (`-`). [Learn more about Linked Accounts](https://support.google.com/google-ads/answer/7365001).