Exemplo n.º 1
0
        /// <summary>
        /// Creates the channel.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <returns>The channel.</returns>
        private ChannelBase CreateChannel(GoogleAdsConfig config)
        {
            ChannelCredentials channelCredentials;

            if (config.AuthorizationMethod == AuthorizationMethod.Insecure)
            {
                channelCredentials = ChannelCredentials.Insecure;
            }
            else // if config.AuthenticationMode == AuthenticationMode.OAUTH)
            {
                channelCredentials =
                    GoogleGrpcCredentials.ToChannelCredentials(config.Credentials);
            }
            Uri uri = new Uri(config.ServerUrl);

            List <ChannelOption> options = new List <ChannelOption>()
            {
                new ChannelOption(GRPC_MAX_RECEIVE_MESSAGE_LENGTH_IN_BYTES_SETTING_NAME,
                                  config.MaxReceiveMessageSizeInBytes),
                new ChannelOption(GRPC_MAX_METADATA_SIZE_IN_BYTES_SETTING_NAME,
                                  config.MaxMetadataSizeInBytes),
            };

            if (config.Proxy != null)
            {
                options.Add(new ChannelOption(GRPC_HTTP_PROXY_SETTING_NAME,
                                              config.Proxy.Address.ToString()));
            }

            return(new Channel(uri.Host, uri.Port, channelCredentials, options));
        }
        public void TestAsyncUnaryCallWithPartialFailure()
        {
            GoogleAdsConfig config  = new GoogleAdsConfig();
            LoggingHandler  handler = new LoggingHandler(config);

            handler.WriteSummaryLogs = delegate(LogEntry logEntry)
            {
                Assert.AreEqual(config.ServerUrl, logEntry.Host);
                Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method);
                CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders);
                Assert.False(logEntry.IsFailure);
            };
            handler.WriteDetailedLogs = delegate(LogEntry logEntry)
            {
                Assert.AreEqual(config.ServerUrl, logEntry.Host);
                Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method);
                CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders);
                CompareMetadata(TEST_RESPONSE_METADATA, logEntry.ResponseHeaders);
                Assert.AreSame(TEST_REQUEST, logEntry.Request);
                Assert.AreSame(TEST_RESPONSE_PARTIAL_FAILURES, logEntry.Response);
                Assert.AreEqual(TEST_CUSTOMER_ID, logEntry.CustomerId);
                Assert.False(logEntry.IsFailure);
                Assert.AreEqual(TEST_PARTIAL_FAILURE_TEXT, logEntry.PartialFailures);
            };
            ClientInterceptorContext <HelloRequest, HelloResponse> context =
                GetClientInterceptorContext();
            AsyncUnaryCall <HelloResponse> call =
                ContinuationWithPartialFailures(TEST_REQUEST, context);

            handler.HandleAsyncUnaryLogging(TEST_REQUEST, context, call.ResponseAsync, call);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WebLoginHelper"/> class.
        /// </summary>
        /// <param name="page">The parent page.</param>
        public WebLoginHelper(Page page)
        {
            this.page = page;

            config = new GoogleAdsConfig();
            flow   = new GoogleAuthorizationCodeFlow(
                new GoogleAuthorizationCodeFlow.Initializer
            {
                //Google will only return a refresh token on the user's first authorization request,
                //unless you always specify prompt=consent in your query params.
                Prompt        = "consent",
                ClientSecrets = new ClientSecrets()
                {
                    ClientId     = config.OAuth2ClientId,
                    ClientSecret = config.OAuth2ClientSecret
                },
                Scopes = new[] { config.OAuth2Scope },
                // Set the state parameter so we can distinguish between a normal
                // page load and a callback.
                UserDefinedQueryParams = new KeyValuePair <string, string>[]
                {
                    new KeyValuePair <string, string>("state", STATE_PARAMETER)
                }
            }
                );
        }
Exemplo n.º 4
0
        /// <summary>
        /// Gets an instance of the specified service.
        /// </summary>
        /// <param name="serviceTemplate">The service template.</param>
        /// <param name="config">The configuration.</param>
        /// <returns>A service instance.</returns>
        internal TService GetService <TService, TServiceSetting>(
            ServiceTemplate <TService, TServiceSetting> serviceTemplate, GoogleAdsConfig config)
            where TServiceSetting : ServiceSettingsBase, new()
            where TService : GoogleAdsServiceClientBase
        {
            Channel     channel     = CreateChannel(config);
            CallInvoker callInvoker = channel.Intercept(
                LoggingInterceptor.GetInstance(config));

            // Build a service context to bind the service, configuration and CallSettings.
            GoogleAdsServiceContext serviceContext = new GoogleAdsServiceContext();

            // Build the call settings.
            CallSettings callSettings = CreateCallSettings <TServiceSetting>(config,
                                                                             serviceContext);

            serviceContext.CallSettings = callSettings;

            // Create the service settings.
            TServiceSetting serviceSettings = CreateServiceSettings <TServiceSetting>(
                serviceContext);

            // Create the service.
            TService service = Create(serviceTemplate, callInvoker, serviceSettings);

            serviceContext.Service = service;
            service.ServiceContext = serviceContext;
            return(service);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Updates the call settings with configuration parameters.
        /// </summary>
        /// <param name="callSettings">The call settings.</param>
        /// <param name="config">The configuration.</param>
        /// <param name="serviceContext">The service context.</param>
        /// <returns></returns>
        private CallSettings UpdateCallSettingsWithConfigParameters(CallSettings callSettings,
                                                                    GoogleAdsConfig config, GoogleAdsServiceContext serviceContext)
        {
            callSettings = callSettings.WithHeader(GoogleAdsConfig.DEVELOPER_TOKEN_KEYNAME,
                                                   config.DeveloperToken)
                           .WithResponseMetadataHandler(delegate(Metadata metadata)
            {
                GoogleAdsResponseMetadata responseMetadata =
                    new GoogleAdsResponseMetadata(metadata);
                serviceContext.OnResponseMetadataReceived(responseMetadata);
            });

            if (!string.IsNullOrEmpty(config.LoginCustomerId))
            {
                callSettings = callSettings.WithHeader(GoogleAdsConfig.LOGIN_CUSTOMER_ID_KEYNAME,
                                                       config.LoginCustomerId);
            }

            if (!string.IsNullOrEmpty(config.LibraryIdentifierOverride))
            {
                callSettings = callSettings.WithHeader(GoogleAdsConfig.LIBRARY_IDENTIFIER_KEYNAME,
                                                       config.LibraryIdentifierOverride);
            }

            callSettings = callSettings.WithCallTiming(CallTiming.FromTimeout(
                                                           TimeSpan.FromMilliseconds(config.Timeout)));

            return(callSettings);
        }
Exemplo n.º 6
0
        public void TestServerStreamingWithResult()
        {
            GoogleAdsConfig config  = new GoogleAdsConfig();
            LoggingHandler  handler = new LoggingHandler(config);

            handler.WriteLogs = delegate(LogEntry logEntry)
            {
                Assert.AreEqual(config.ServerUrl, logEntry.Host);
                Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method);
                CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders);
                CompareMetadata(TEST_RESPONSE_METADATA, logEntry.ResponseHeaders);
                Assert.AreSame(TEST_REQUEST, logEntry.Request);
                Assert.AreSame(TEST_RESPONSE, logEntry.Response);
                Assert.AreEqual(TEST_CUSTOMER_ID, logEntry.CustomerId);
                Assert.False(logEntry.IsFailure);
            };

            ClientInterceptorContext <HelloRequest, HelloResponse> context =
                GetClientInterceptorContext();
            AsyncServerStreamingCall <HelloResponse> call =
                StreamingContinuationWithResult <HelloResponse>();

            handler.HandleAsyncServerStreamingLogging(TEST_REQUEST,
                                                      TEST_RESPONSE, context, null, call);
        }
Exemplo n.º 7
0
        public void TestAsyncUnaryCallWithException()
        {
            GoogleAdsConfig config  = new GoogleAdsConfig();
            LoggingHandler  handler = new LoggingHandler(config);

            handler.WriteLogs = delegate(LogEntry logEntry)
            {
                Assert.AreEqual(config.ServerUrl, logEntry.Host);
                Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method);
                CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders);
                CompareMetadata(TEST_RESPONSE_METADATA, logEntry.ResponseHeaders);
                Assert.AreSame(TEST_REQUEST, logEntry.Request);

                // Response is null if there's an exception.
                Assert.IsNull(logEntry.Response);

                Assert.AreEqual(TEST_CUSTOMER_ID, logEntry.CustomerId);
                Assert.True(logEntry.IsFailure);
                GoogleAdsException googleAdsException = logEntry.Exception as GoogleAdsException;
                Assert.NotNull(googleAdsException);

                Assert.AreEqual(TEST_REQUEST_ID, googleAdsException.RequestId);

                Assert.NotNull(googleAdsException.Failure);
                Assert.AreEqual(1, googleAdsException.Failure.Errors.Count);
                Assert.NotNull(googleAdsException.Failure.Errors[0].ErrorCode);
                Assert.NotNull(googleAdsException.Failure.Errors[0].ErrorCode.DistinctError);
            };

            ClientInterceptorContext <HelloRequest, HelloResponse> context =
                GetClientInterceptorContext();
            AsyncUnaryCall <HelloResponse> call = ContinuationWithException(TEST_REQUEST, context);

            handler.HandleAsyncUnaryLogging(TEST_REQUEST, context, call.ResponseAsync, call);
        }
        /// <summary>
        /// Creates a service context that binds the service, callsettings and the client.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <returns>The service context.</returns>
        private GoogleAdsServiceContext CreateServiceContext(GoogleAdsConfig config)
        {
            GoogleAdsServiceContext serviceContext = new GoogleAdsServiceContext();
            CallSettings            callSettings   = CallSettings.FromCallTiming(
                CallTiming.FromRetry(new RetrySettings(
                                         retryBackoff : backoffSettings,
                                         timeoutBackoff : backoffSettings,
                                         totalExpiration : Expiration.FromTimeout(TimeSpan.FromMilliseconds(
                                                                                      config.Timeout)),
                                         retryFilter : retryFilter
                                         )))
                                                     .WithHeader(GoogleAdsConfig.DEVELOPER_TOKEN_KEYNAME, config.DeveloperToken)
                                                     .WithResponseMetadataHandler(delegate(Metadata metadata)
            {
                GoogleAdsResponseMetadata responseMetadata = new GoogleAdsResponseMetadata(metadata);
                serviceContext.OnResponseMetadataReceived(responseMetadata);
            });

            if (!string.IsNullOrEmpty(config.LoginCustomerId))
            {
                callSettings.WithHeader("login-customer-id", config.LoginCustomerId);
            }

            serviceContext.CallSettings = callSettings;
            return(serviceContext);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates the channel.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <returns>The channel.</returns>
        private static Channel CreateChannel(GoogleAdsConfig config)
        {
            ChannelCredentials channelCredentials = null;

            if (config.AuthorizationMethod == AuthorizationMethod.Insecure)
            {
                channelCredentials = ChannelCredentials.Insecure;
            }
            else // if config.AuthenticationMode == AuthenticationMode.OAUTH)
            {
                channelCredentials =
                    GoogleGrpcCredentials.ToChannelCredentials(config.Credentials);
            }
            Uri uri = new Uri(config.ServerUrl);

            return(new Channel(uri.Host, uri.Port, channelCredentials,
                               new List <ChannelOption>()
            {
                new ChannelOption(GRPC_MAX_RECEIVE_MESSAGE_LENGTH_IN_BYTES_SETTING_NAME,
                                  MAX_RECEIVE_MESSAGE_LENGTH_IN_BYTES),
                new ChannelOption(GRPC_MAX_METADATA_SIZE_IN_BYTES_SETTING_NAME,
                                  MAX_METADATA_SIZE_IN_BYTES),
            }
                               ));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AdsController"/> class.
        /// </summary>
        /// <param name="configRoot">The configuration root.</param>
        public AdsController(IConfiguration configRoot)
        {
            IConfigurationSection section = configRoot.GetSection("GoogleAdsApi");
            GoogleAdsConfig       config  = new GoogleAdsConfig(section);

            client = new GoogleAdsClient(config);
        }
 /// <summary>
 /// Gets an instance of the specified service.
 /// </summary>
 /// <param name="serviceTemplate">The service template.</param>
 /// <param name="config">The configuration.</param>
 /// <returns>A service instance.</returns>
 internal TService GetService <TService, TServiceSetting>(
     ServiceTemplate <TService, TServiceSetting> serviceTemplate, GoogleAdsConfig config)
     where TServiceSetting : ServiceSettingsBase, new()
     where TService : GoogleAdsServiceClientBase
 {
     return(GetService(serviceTemplate, null, config));
 }
Exemplo n.º 12
0
        /// <summary>
        /// Updates the call settings with configuration parameters.
        /// </summary>
        /// <param name="callSettings">The call settings.</param>
        /// <param name="config">The configuration.</param>
        /// <param name="serviceContext">The service context.</param>
        /// <returns></returns>
        private CallSettings UpdateCallSettingsWithConfigParameters(CallSettings callSettings,
                                                                    GoogleAdsConfig config, GoogleAdsServiceContext serviceContext)
        {
            callSettings = callSettings.WithHeader(MetadataKeyNames.DeveloperToken,
                                                   config.DeveloperToken)
                           .WithResponseMetadataHandler(delegate(Metadata metadata)
            {
                AdsResponseMetadata responseMetadata = new AdsResponseMetadata(metadata);
                serviceContext.OnResponseMetadataReceived(responseMetadata);
            });

            if (!string.IsNullOrEmpty(config.LoginCustomerId))
            {
                callSettings = callSettings.WithHeader(MetadataKeyNames.LoginCustomerId,
                                                       config.LoginCustomerId);
            }

            if (!string.IsNullOrEmpty(config.LinkedCustomerId))
            {
                callSettings = callSettings.WithHeader(MetadataKeyNames.LinkedCustomerId,
                                                       config.LinkedCustomerId);
            }

            if (!string.IsNullOrEmpty(config.LibraryIdentifierOverride))
            {
                callSettings = callSettings.WithHeader(MetadataKeyNames.LibraryIdentifier,
                                                       config.LibraryIdentifierOverride);
            }

            callSettings = callSettings.WithExpiration(Expiration.FromTimeout(
                                                           TimeSpan.FromMilliseconds(config.Timeout)));

            return(callSettings);
        }
Exemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LoggingHandler"/> class.
 /// </summary>
 /// <param name="config">The configuration.</param>
 internal LoggingHandler(GoogleAdsConfig config)
 {
     this.config            = config;
     this.traceWriter       = new DefaultTraceWriter();
     this.logCustomizer     = new LogFormatter();;
     this.WriteDetailedLogs = WriteDetailedLogEntry;
     this.WriteSummaryLogs  = WriteSummaryLogEntry;
 }
Exemplo n.º 14
0
 public void Init()
 {
     TEST_CONFIG = new GoogleAdsConfig()
     {
         Proxy   = TEST_PROXY,
         Timeout = TEST_TIMEOUT,
     };
 }
Exemplo n.º 15
0
        /// <summary>
        /// Creates the channel for the new service, and sets the proxy server.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <returns>The new channel.</returns>
        private ChannelBase CreateChannel(GoogleAdsConfig config)
        {
            // GRPC uses c-ares DNS resolver, which doesn't seem to work on some Windows machines.
            // Turn it off for now.
            // https://github.com/googleads/google-ads-dotnet/issues/59
            Environment.SetEnvironmentVariable("GRPC_DNS_RESOLVER", "native");

            return(channelFactory.GetChannel(config));
        }
Exemplo n.º 16
0
 /// <summary>
 /// Gets an instance of the logging interceptor.
 /// </summary>
 /// <param name="config">The application configuration.</param>
 /// <returns>An instance of the logging interceptor.</returns>
 public static LoggingInterceptor GetInstance(GoogleAdsConfig config)
 {
     lock (typeof(LoggingInterceptor))
     {
         if (instance == null)
         {
             instance = new LoggingInterceptor(config);
         }
     }
     return(instance);
 }
        public void TestServerStreamingWithException()
        {
            GoogleAdsConfig config  = new GoogleAdsConfig();
            LoggingHandler  handler = new LoggingHandler(config);

            handler.WriteSummaryLogs = delegate(LogEntry logEntry)
            {
                Assert.AreEqual(config.ServerUrl, logEntry.Host);
                Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method);
                CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders);
                Assert.True(logEntry.IsFailure);
                HelloException helloException = logEntry.Exception as HelloException;
                Assert.NotNull(helloException);

                Assert.AreEqual(TEST_REQUEST_ID, helloException.RequestId);

                Assert.NotNull(helloException.Failure);
                Assert.AreEqual(1, helloException.Failure.Errors.Count);
                Assert.NotNull(helloException.Failure.Errors[0].ErrorCode);
                Assert.NotNull(helloException.Failure.Errors[0].ErrorCode.RequestError);
            };
            handler.WriteDetailedLogs = delegate(LogEntry logEntry)
            {
                Assert.AreEqual(config.ServerUrl, logEntry.Host);
                Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method);
                CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders);
                CompareMetadata(TEST_RESPONSE_METADATA, logEntry.ResponseHeaders);
                Assert.AreSame(TEST_REQUEST, logEntry.Request);

                // Response is null if there's an exception.
                Assert.IsNull(logEntry.Response);

                Assert.AreEqual(TEST_CUSTOMER_ID, logEntry.CustomerId);
                Assert.True(logEntry.IsFailure);
                HelloException helloException = logEntry.Exception as HelloException;
                Assert.NotNull(helloException);

                Assert.AreEqual(TEST_REQUEST_ID, helloException.RequestId);

                Assert.NotNull(helloException.Failure);
                Assert.AreEqual(1, helloException.Failure.Errors.Count);
                Assert.NotNull(helloException.Failure.Errors[0].ErrorCode);
                Assert.NotNull(helloException.Failure.Errors[0].ErrorCode.RequestError);
            };

            ClientInterceptorContext <HelloRequest, HelloResponse> context =
                GetClientInterceptorContext();
            AsyncServerStreamingCall <HelloResponse> call =
                StreamingContinuationWithException <HelloResponse>();

            handler.HandleAsyncServerStreamingLogging(TEST_REQUEST,
                                                      null, context, new AggregateException(TEST_EXCEPTION),
                                                      call);
        }
Exemplo n.º 18
0
 /// <summary>
 /// Gets an instance of the logging interceptor.
 /// </summary>
 /// <param name="config">The application configuration.</param>
 /// <returns>An instance of the logging interceptor.</returns>
 internal static GoogleAdsGrpcInterceptor GetInstance(GoogleAdsConfig config)
 {
     lock (typeof(GoogleAdsGrpcInterceptor))
     {
         if (instance == null)
         {
             instance = new GoogleAdsGrpcInterceptor(config);
         }
     }
     return(instance);
 }
        public void TestGetChannelCanBeDisabled()
        {
            GoogleAdsConfig configNoCache = new GoogleAdsConfig()
            {
                UseChannelCache = false
            };

            ChannelBase channel1 = factory.GetChannel(configNoCache);
            ChannelBase channel2 = factory.GetChannel(configNoCache);

            Assert.AreNotSame(channel1, channel2);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Creates the call settings.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <param name="serviceContext">The service context.</param>
        /// <returns>The call settings.</returns>
        private CallSettings CreateCallSettings <TServiceSetting>(GoogleAdsConfig config, GoogleAdsServiceContext serviceContext)
            where TServiceSetting : ServiceSettingsBase, new()
        {
            // Get the default call settings from the generated stubs.
            CallSettings callSettings = new TServiceSetting().CallSettings;

            // Override various parameters with configuration parameters.
            callSettings = UpdateCallSettingsWithConfigParameters(callSettings,
                                                                  config, serviceContext);

            return(callSettings);
        }
        // [END add_performance_max_retail_campaign_7]

        // [START add_performance_max_retail_campaign_8]
        /// <summary>
        /// Creates a list of MutateOperations that create a new linked image asset.
        /// </summary>
        /// <param name="assetGroupResourceName">The resource name of the asset group to be
        /// created.</param>
        /// <param name="assetResourceName">The resource name of the text asset to be
        /// created.</param>
        /// <param name="url">The url of the image to be retrieved and put into an asset.</param>
        /// <param name="fieldType">The field type of the asset to be created.</param>
        /// <param name="assetName">The asset name.</param>
        /// <param name="config">The Google Ads config.</param>
        /// <returns>A list of MutateOperations that create a new linked image asset.</returns>
        private List <MutateOperation> CreateAndLinkImageAsset(
            string assetGroupResourceName,
            string assetResourceName,
            string url,
            AssetFieldType fieldType,
            string assetName,
            GoogleAdsConfig config)
        {
            List <MutateOperation> operations = new List <MutateOperation>();

            // Create the Image Asset.
            operations.Add(
                new MutateOperation()
            {
                AssetOperation = new AssetOperation()
                {
                    Create = new Asset()
                    {
                        ResourceName = assetResourceName,
                        ImageAsset   = new ImageAsset()
                        {
                            Data =
                                ByteString.CopyFrom(
                                    MediaUtilities.GetAssetDataFromUrl(url, config)
                                    )
                        },
                        // Provide a unique friendly name to identify your asset.
                        // When there is an existing image asset with the same content but a
                        // different name, the new name will be dropped silently.
                        Name = assetName
                    }
                }
            }
                );

            // Create an AssetGroupAsset to link the Asset to the AssetGroup.
            operations.Add(
                new MutateOperation()
            {
                AssetGroupAssetOperation = new AssetGroupAssetOperation()
                {
                    Create = new AssetGroupAsset()
                    {
                        FieldType  = fieldType,
                        AssetGroup = assetGroupResourceName,
                        Asset      = assetResourceName
                    }
                }
            }
                );

            return(operations);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Gets the channel for the specified configuration.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <returns>The channel.</returns>
        internal ChannelBase GetChannel(GoogleAdsConfig config)
        {
            ChannelBase retval = null;

            if (!config.UseChannelCache)
            {
                return(CreateChannel(config));
            }

            // Channels with unique (credentials, Url) combination should be unique.
            string key = string.Join("~", new object[] {
                config.OAuth2Mode,
                config.OAuth2ClientId,
                config.OAuth2ClientSecret,
                config.OAuth2RefreshToken,
                config.OAuth2PrivateKey,
                config.OAuth2PrnEmail,
                config.ServerUrl
            });

            lock (cache)
            {
                if (cache.ContainsKey(key))
                {
                    retval = cache[key];
                    if ((retval as Channel).State == ChannelState.Shutdown)
                    {
                        // If the channel is shut down, then remove it from cache.
                        lock (cache)
                        {
                            cache.Remove(key);
                            retval = null;
                        }
                    }
                }

                if (retval == null)
                {
                    // Create a new channel.
                    lock (cache)
                    {
                        retval     = CreateChannel(config);
                        cache[key] = retval;
                    }
                }
            }

            return(retval);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Builds an HTTP request with a specified method.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="method">The HTTP method.</param>
        /// <param name="config">The configuration instance for customizing the
        /// connection settings.</param>
        /// <returns>The web request for making HTTP call.</returns>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="config"/>
        /// is null.</exception>
        public static WebRequest BuildRequest(string url, string method, GoogleAdsConfig config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            WebRequest request = HttpWebRequest.Create(url);

            request.Method  = method;
            request.Proxy   = config.Proxy;
            request.Timeout = config.Timeout;

            return(request);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Creates the channel.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <returns>The channel.</returns>
        private static Channel CreateChannel(GoogleAdsConfig config)
        {
            ChannelCredentials channelCredentials =
                GoogleGrpcCredentials.ToChannelCredentials(config.Credentials);
            Uri uri = new Uri(config.ServerUrl);

            return(new Channel(uri.Host, uri.Port, channelCredentials,
                               new List <ChannelOption>()
            {
                new ChannelOption(GRPC_MAX_RECEIVE_MESSAGE_LENGTH_IN_BYTES_SETTING_NAME,
                                  MAX_RECEIVE_MESSAGE_LENGTH_IN_BYTES.ToString()),
                new ChannelOption(GRPC_MAX_METADATA_SIZE_IN_BYTES_SETTING_NAME,
                                  MAX_METADATA_SIZE_IN_BYTES.ToString()),
            }
                               ));
        }
        /// <summary>
        /// Creates the channel for the new service, and sets the proxy server.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <returns>The new channel.</returns>
        private Channel CreateChannel(GoogleAdsConfig config)
        {
            ChannelCredentials channelCredentials =
                GoogleGrpcCredentials.ToChannelCredentials(config.Credentials);

            if (config.Proxy == null)
            {
                Environment.SetEnvironmentVariable("http_proxy", null);
            }
            else
            {
                Environment.SetEnvironmentVariable("http_proxy", config.Proxy.Address.ToString());
            }

            Uri uri = new Uri(config.ServerUrl);

            return(new Channel(uri.Host, uri.Port, channelCredentials, null));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Creates the channel for the new service, and sets the proxy server.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <returns>The new channel.</returns>
        private Channel CreateChannel(GoogleAdsConfig config)
        {
            if (config.Proxy == null)
            {
                Environment.SetEnvironmentVariable("http_proxy", null);
            }
            else
            {
                Environment.SetEnvironmentVariable("http_proxy", config.Proxy.Address.ToString());
            }

            // GRPC uses c-ares DNS resolver, which doesn't seem to work on some Windows machines.
            // Turn it off for now.
            // https://github.com/googleads/google-ads-dotnet/issues/59
            Environment.SetEnvironmentVariable("GRPC_DNS_RESOLVER", "native");

            return(CachedChannelFactory.GetChannel(config));
        }
        /// <summary>
        /// Gets an instance of the specified service.
        /// </summary>
        /// <param name="serviceTemplate">The service template.</param>
        /// <param name="config">The configuration.</param>
        /// <returns>A service instance.</returns>
        internal TService GetService <TService, TServiceSetting>(
            ServiceTemplate <TService, TServiceSetting> serviceTemplate, GoogleAdsConfig config)
            where TServiceSetting : ServiceSettingsBase, new()
            where TService : GoogleAdsServiceClientBase
        {
            Channel     channel     = CreateChannel(config);
            CallInvoker callInvoker = channel.Intercept(
                LoggingInterceptor.GetInstance(config));

            GoogleAdsServiceContext serviceContext  = CreateServiceContext(config);
            TServiceSetting         serviceSettings = CreateServiceSettings <TServiceSetting>(
                serviceContext);
            TService service = Create <TService, TServiceSetting>(
                callInvoker, serviceSettings);

            serviceContext.Service = service;
            service.ServiceContext = serviceContext;
            return(service);
        }
        /// <summary>
        /// Creates the call settings.
        /// </summary>
        /// <typeparam name="TServiceSetting">The type of the service setting.</typeparam>
        /// <param name="userCallSettings">The user call settings.</param>
        /// <param name="config">The configuration.</param>
        /// <param name="serviceContext">The service context.</param>
        /// <returns>The call settings.</returns>
        private CallSettings CreateCallSettings <TServiceSetting>(CallSettings userCallSettings,
                                                                  GoogleAdsConfig config, GoogleAdsServiceContext serviceContext)
            where TServiceSetting : ServiceSettingsBase, new()
        {
            // Get the default call settings from the generated stubs.
            CallSettings callSettings = new TServiceSetting().CallSettings;

            // Override various parameters with configuration parameters.
            callSettings = UpdateCallSettingsWithConfigParameters(callSettings,
                                                                  config, serviceContext);

            // If the user has provided a call settings at the runtime, then override specific
            // settings from there.
            if (userCallSettings != null)
            {
                callSettings = callSettings.MergedWith(userCallSettings);
            }

            return(callSettings);
        }
Exemplo n.º 29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WebLoginHelper"/> class.
 /// </summary>
 /// <param name="context">The HTTP context.</param>
 /// <param name="config">The Google Ads configuration.</param>
 public WebLoginHelper(HttpContext context, GoogleAdsConfig config)
 {
     this.context = context;
     this.config  = config;
     flow         = new GoogleAuthorizationCodeFlow(
         new GoogleAuthorizationCodeFlow.Initializer
     {
         ClientSecrets = new ClientSecrets()
         {
             ClientId     = config.OAuth2ClientId,
             ClientSecret = config.OAuth2ClientSecret
         },
         Scopes = new[] { config.OAuth2Scope },
         // Set the state parameter so we can distinguish between a normal
         // page load and a callback.
         UserDefinedQueryParams = new KeyValuePair <string, string>[]
         {
             new KeyValuePair <string, string>("state", STATE_PARAMETER)
         }
     }
         );
 }
Exemplo n.º 30
0
        /// <summary>
        /// Gets an instance of the specified service.
        /// </summary>
        /// <param name="serviceTemplate">The service template.</param>
        /// <param name="config">The configuration.</param>
        /// <returns>A service instance.</returns>
        internal TService GetService <TService, TServiceSetting>(
            ServiceTemplate <TService, TServiceSetting, GoogleAdsConfig> serviceTemplate,
            GoogleAdsConfig config)
            where TServiceSetting : ServiceSettingsBase, new()
            where TService : GoogleAdsServiceClientBase
        {
            ChannelBase channel            = CreateChannel(config);
            CallInvoker interceptedInvoker = channel
                                             .Intercept(new GoogleAdsGrpcInterceptor(config));

            CallInvoker callInvoker = config.EnableProfiling ?
                                      new ProfilingCallInvoker(interceptedInvoker, config) : interceptedInvoker;

            // Build a service context to bind the service, configuration and CallSettings.
            GoogleAdsServiceContext serviceContext = new GoogleAdsServiceContext();

            // Build the call settings.
            CallSettings callSettings = CreateCallSettings <TServiceSetting>(config,
                                                                             serviceContext);

            serviceContext.CallSettings = callSettings;

            // Create the service settings.
            TServiceSetting serviceSettings =
                CreateServiceSettings <TServiceSetting, GoogleAdsConfig>(serviceContext);

            serviceSettings.VersionHeaderBuilder.AppendAssemblyVersion("gccl", this.GetType());
            serviceSettings.VersionHeaderBuilder.AppendAssemblyVersion("protobuf",
                                                                       typeof(IMessage));

            // Create the service.
            TService service = Create(serviceTemplate, callInvoker, serviceSettings);

            serviceContext.Service             = service;
            service.ServiceContext             = serviceContext;
            service.ServiceContext.ChannelBase = channel;
            return(service);
        }