Ejemplo n.º 1
0
        public IPagedEnumerable<BrokenLink> GetPage(int? page, int? count)
        {
            var db = UnitOfWork.Current;
            var lower = count * page - 1 ;
            var offset = lower + count - 1;

            var total = db.Execute("SELECT COUNT(1) FROM BrokenLink");
            var links = db.Query<BrokenLink>("SELECT * FROM BrokenLink ORDER BY Count, LastOccurrence LIMIT @Count, @Offset", new { Count = count, Offset = offset });
            var result = new PagedEnumerable<BrokenLink>(links, page.Value, count.Value, total);
            return result;
        }
        /// <summary>Snippet for ListAuthorizedCertificates</summary>
        public void ListAuthorizedCertificatesRequestObject()
        {
            // Snippet: ListAuthorizedCertificates(ListAuthorizedCertificatesRequest, CallSettings)
            // Create client
            AuthorizedCertificatesClient authorizedCertificatesClient = AuthorizedCertificatesClient.Create();
            // Initialize request argument(s)
            ListAuthorizedCertificatesRequest request = new ListAuthorizedCertificatesRequest
            {
                Parent = "",
                View   = AuthorizedCertificateView.BasicCertificate,
            };
            // Make the request
            PagedEnumerable <ListAuthorizedCertificatesResponse, AuthorizedCertificate> response = authorizedCertificatesClient.ListAuthorizedCertificates(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (AuthorizedCertificate item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListAuthorizedCertificatesResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (AuthorizedCertificate item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <AuthorizedCertificate> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (AuthorizedCertificate item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsServiceClient .
            GoogleAdsServiceClient service = client.GetService(Services.V5.GoogleAdsService);

            string query =
                @"SELECT
                recommendation.type,
                recommendation.campaign,
                recommendation.text_ad_recommendation
            FROM
                recommendation
            WHERE
                recommendation.type = TEXT_AD";

            // Create a request that will retrieve all recommendations using pages of the
            // specified page size.
            SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
            {
                CustomerId = customerId.ToString(),
                PageSize   = PAGE_SIZE,
                Query      = query
            };

            try
            {
                // Issue the search request.
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
                    service.Search(customerId.ToString(), query);

                // Iterates over all rows in all pages and prints the requested field values
                // for the recommendation in each row.
                foreach (GoogleAdsRow googleAdsRow in searchPagedResponse)
                {
                    Recommendation recommendation = googleAdsRow.Recommendation;
                    // [START_EXCLUDE]
                    Ad recommendedAd = recommendation.TextAdRecommendation.Ad;

                    Console.WriteLine($"Recommendation ({recommendation.ResourceName}) was " +
                                      $"found for campaign {recommendation.Campaign}:");
                    if (recommendedAd.ExpandedTextAd != null)
                    {
                        ExpandedTextAdInfo eta = recommendedAd.ExpandedTextAd;
                        Console.WriteLine("\tHeadline 1 = {0}\n\tHeadline 2 = {1}\t" +
                                          "Description = {2}",
                                          eta.HeadlinePart1, eta.HeadlinePart2, eta.Description);
                    }
                    Console.WriteLine($"\tDisplay URL = {recommendedAd.DisplayUrl}");
                    foreach (string url in recommendedAd.FinalUrls)
                    {
                        Console.WriteLine($"\tFinal URL = {url}");
                    }
                    foreach (string url in recommendedAd.FinalMobileUrls)
                    {
                        Console.WriteLine($"\tFinal Mobile URL = {url}");
                    }
                    // [END_EXCLUDE]
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Ejemplo n.º 4
0
        public static int Main(string[] args)
        {
            // Read projectId from args
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: Project ID must be passed as first argument.");
                Console.WriteLine();
                return(1);
            }
            string projectId = args[0];

            // Create client
            MetricServiceClient client = MetricServiceClient.Create();

            // Initialize request argument(s)
            ProjectName name = new ProjectName(projectId);

            // Call API method
            PagedEnumerable <ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> pagedResponse = client.ListMonitoredResourceDescriptors(name);

            // Show the result
            foreach (var item in pagedResponse)
            {
                Console.WriteLine(item);
            }

            // Success
            Console.WriteLine("Smoke test passed OK");
            return(0);
        }
        /// <summary>Snippet for AggregatedList</summary>
        public void AggregatedList()
        {
            // Snippet: AggregatedList(string, string, int?, CallSettings)
            // Create client
            NodeTypesClient nodeTypesClient = NodeTypesClient.Create();
            // Initialize request argument(s)
            string project = "";
            // Make the request
            PagedEnumerable <NodeTypeAggregatedList, KeyValuePair <string, NodeTypesScopedList> > response = nodeTypesClient.AggregatedList(project);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (KeyValuePair <string, NodeTypesScopedList> item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (NodeTypeAggregatedList page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (KeyValuePair <string, NodeTypesScopedList> item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <KeyValuePair <string, NodeTypesScopedList> > singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (KeyValuePair <string, NodeTypesScopedList> item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
Ejemplo n.º 6
0
        /// <summary>Snippet for ListNotificationChannelDescriptors</summary>
        public void ListNotificationChannelDescriptors()
        {
            // Snippet: ListNotificationChannelDescriptors(ProjectName,string,int?,CallSettings)
            // Create client
            NotificationChannelServiceClient notificationChannelServiceClient = NotificationChannelServiceClient.Create();
            // Initialize request argument(s)
            ProjectName name = new ProjectName("[PROJECT]");
            // Make the request
            PagedEnumerable <ListNotificationChannelDescriptorsResponse, NotificationChannelDescriptor> response =
                notificationChannelServiceClient.ListNotificationChannelDescriptors(name);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (NotificationChannelDescriptor item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListNotificationChannelDescriptorsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (NotificationChannelDescriptor item in page)
                {
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <NotificationChannelDescriptor> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (NotificationChannelDescriptor item in singlePage)
            {
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupId">Optional: ID of the ad group to restrict search to.</param>
        public void Run(GoogleAdsClient client, long customerId, long?adGroupId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V4.GoogleAdsService);

            string searchQuery =
                $@"SELECT
                 ad_group.id,
                 ad_group_ad.ad.id,
                 ad_group_ad.ad.responsive_search_ad.headlines,
                 ad_group_ad.ad.responsive_search_ad.descriptions,
                 ad_group_ad.status
            FROM ad_group_ad
            WHERE
                ad_group_ad.ad.type = RESPONSIVE_SEARCH_AD
                AND ad_group_ad.status != 'REMOVED'";

            if (adGroupId != null)
            {
                searchQuery += $" AND ad_group.id = {adGroupId}";
            }

            // Create a request that will retrieve all ads using pages of the specified page size.
            SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
            {
                CustomerId = customerId.ToString(),
                PageSize   = PAGE_SIZE,
                Query      = searchQuery
            };

            try
            {
                // Issue the search request.
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
                    googleAdsService.Search(request);

                // Iterates over all rows in all pages and prints the requested field values for
                // the ad in each row.
                foreach (GoogleAdsRow googleAdsRow in searchPagedResponse)
                {
                    Ad ad = googleAdsRow.AdGroupAd.Ad;

                    Console.WriteLine($"Responsive search ad with resource name '{ad.ResourceName}'," +
                                      $"status '{googleAdsRow.AdGroupAd.Status}' was found.");
                    // Prints the ad text asset detail.
                    ResponsiveSearchAdInfo responsiveSearchAdInfo = ad.ResponsiveSearchAd;
                    Console.WriteLine("Headlines:{0},\nDescriptions:{1}",
                                      FormatAdTextAssetsAsString(responsiveSearchAdInfo.Headlines),
                                      FormatAdTextAssetsAsString(responsiveSearchAdInfo.Descriptions));
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Ejemplo n.º 8
0
        public void Paged_enumerable_should_return_correct_enumerables_for_pages()
        {
            int capacity = 250;
            IList<int> list = new List<int>(capacity);
            for (int i = 0; i < capacity; i++)
            {
                list.Add(i);
            }
            var pagedList = new PagedEnumerable<int>(list, 10, 10);
            Assert.That(pagedList.TotalPages, Is.EqualTo(25));

            var pagedList2 = new PagedEnumerable<int>(list, 10, 10);
            Assert.That(pagedList2.Count(), Is.EqualTo(10));

            var pagedList3 = list.GetPaged(13, 25);
            Assert.That(pagedList3.TotalPages, Is.EqualTo(10));
            Assert.That(pagedList3.CurrentPage, Is.EqualTo(13));

            var pagedList4 = list.GetPaged(20, 13);
            Assert.That(pagedList4.TotalPages, Is.EqualTo(20));
            Assert.That(pagedList4.Count(), Is.EqualTo(3));
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="campaignId">Id of the campaign for which disapproved ads
        /// are retrieved.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V1.GoogleAdsService);

            String searchQuery =
                $@"SELECT
                    ad_group_ad.ad.id,
                    ad_group_ad.ad.type,
                    ad_group_ad.policy_summary
                FROM ad_group_ad
                WHERE
                    campaign.id = {campaignId}";

            // Create a request that will retrieve all Disapproved Ads
            SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
            {
                PageSize   = PAGE_SIZE,
                Query      = searchQuery,
                CustomerId = customerId.ToString()
            };

            int disapprovedAdsCount = 0;

            try
            {
                // Issue the search request.
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
                    googleAdsService.Search(request);

                // Iterate over all rows in all rows returned and count disapproved Ads
                foreach (GoogleAdsRow googleAdsRow in searchPagedResponse)
                {
                    AdGroupAdPolicySummary policySummary = googleAdsRow.AdGroupAd.PolicySummary;
                    AdGroupAd adGroupAd = googleAdsRow.AdGroupAd;
                    Ad        ad        = adGroupAd.Ad;

                    if (adGroupAd.PolicySummary.ApprovalStatus != PolicyApprovalStatus.Disapproved)
                    {
                        continue;
                    }

                    disapprovedAdsCount++;

                    Console.WriteLine(
                        "Ad with ID {0} and type '{1}' was disapproved with the " +
                        "following policy topic entries: ",
                        ad.Id, ad.Type);

                    // Display the policy topic entries related to the ad disapproval.
                    foreach (PolicyTopicEntry policyTopicEntry in policySummary.PolicyTopicEntries)
                    {
                        Console.WriteLine("  topic: {0}, type: '{1}'",
                                          policyTopicEntry.Topic,
                                          policyTopicEntry.Type);

                        // Display the attributes and values that triggered the policy topic.
                        if (policyTopicEntry.Evidences != null)
                        {
                            foreach (PolicyTopicEvidence evidence in policyTopicEntry.Evidences)
                            {
                                if (evidence.TextList != null)
                                {
                                    for (int i = 0; i < evidence.TextList.Texts.Count; i++)
                                    {
                                        Console.WriteLine("    evidence text[{0}]: {1}", i,
                                                          evidence.TextList.Texts[i]);
                                    }
                                }
                            }
                        }
                    }
                }

                Console.WriteLine("Number of disapproved ads found: {0}", disapprovedAdsCount);
            }
            catch (Exception e)
            {
                throw new System.ApplicationException("Failed to get disapproved ads.", e);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        // [START get_billing_setup]
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsServiceClient.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V10.GoogleAdsService);

            // Define a GAQL query to retrieve all billing setup information.
            string searchQuery = @"
                SELECT
                    billing_setup.id,
                    billing_setup.status,
                    billing_setup.payments_account,
                    billing_setup.payments_account_info.payments_account_id,
                    billing_setup.payments_account_info.payments_account_name,
                    billing_setup.payments_account_info.payments_profile_id,
                    billing_setup.payments_account_info.payments_profile_name,
                    billing_setup.payments_account_info.secondary_payments_profile_id
                FROM billing_setup";

            // Creates a request that will retrieve all billing setups using pages of the specified
            // page size.
            SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
            {
                PageSize   = PAGE_SIZE,
                Query      = searchQuery,
                CustomerId = customerId.ToString()
            };

            try
            {
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
                    googleAdsService.Search(request);

                foreach (GoogleAdsRow googleAdsRow in searchPagedResponse)
                {
                    BillingSetup billingSetup = googleAdsRow.BillingSetup;
                    Console.WriteLine($"Billing setup with ID '{billingSetup.Id}'has status " +
                                      $"'{billingSetup.Status}'.");

                    // A missing billing setup will have no payments account information.
                    if (billingSetup.HasPaymentsAccount)
                    {
                        Console.WriteLine(
                            $"\tPayments account: {billingSetup.PaymentsAccount}\n" +
                            "\tPayments account Id: " +
                            $"{billingSetup.PaymentsAccountInfo.PaymentsAccountId}\n" +
                            "\tPayments profile id: " +
                            $"{billingSetup.PaymentsAccountInfo.PaymentsProfileId}\n");

                        // A pending billing setup will not have values for certain fields.
                        if (billingSetup.Status != BillingSetupStatus.Pending)
                        {
                            Console.WriteLine(
                                "\tPayments account name: " +
                                $"{billingSetup.PaymentsAccountInfo.PaymentsAccountName}\n" +
                                "\tPayments profile name: " +
                                $"{billingSetup.PaymentsAccountInfo.PaymentsProfileName}\n" +
                                "\tSecondary payments profile id: " +
                                $"{billingSetup.PaymentsAccountInfo.SecondaryPaymentsProfileId}");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Payments account details missing or incomplete.");
                    }
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <summary>Snippet for ListMeasurementProtocolSecrets</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void ListMeasurementProtocolSecretsRequestObject()
        {
            // Create client
            AnalyticsAdminServiceClient analyticsAdminServiceClient = AnalyticsAdminServiceClient.Create();
            // Initialize request argument(s)
            ListMeasurementProtocolSecretsRequest request = new ListMeasurementProtocolSecretsRequest
            {
                ParentAsWebDataStreamName = WebDataStreamName.FromPropertyWebDataStream("[PROPERTY]", "[WEB_DATA_STREAM]"),
            };
            // Make the request
            PagedEnumerable <ListMeasurementProtocolSecretsResponse, MeasurementProtocolSecret> response = analyticsAdminServiceClient.ListMeasurementProtocolSecrets(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (MeasurementProtocolSecret item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListMeasurementProtocolSecretsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (MeasurementProtocolSecret item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <MeasurementProtocolSecret> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (MeasurementProtocolSecret item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Get user's projects.
        /// </summary>
        /// <param name="userId">User id the projects related to.</param>
        /// <param name="page">Page number.</param>
        /// <param name="pageSize">Page size, default is 10.</param>
        /// <returns>Projects paged enumerable.</returns>
        public PagedEnumerable <ProjectDto> GetByUser(string userId, int page, int pageSize = 10)
        {
            var query = uow.ProjectRepository.Find(p => p.User.Id == userId).Select(p => new ProjectDto(p));

            return(PagedEnumerable.Create(query, page, pageSize));
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for the conversion action is
        ///     added.</param>
        /// <param name="adGroupId">The ad group ID for which to update the audience targeting
        ///     restriction.</param>
        public void Run(GoogleAdsClient client, long customerId, long adGroupId)
        {
            // Get the GoogleAdsService client.
            GoogleAdsServiceClient googleAdsServiceClient =
                client.GetService(Services.V6.GoogleAdsService);

            // Create a search request that retrieves the targeting settings from a given ad group.
            string query = $@"
                SELECT ad_group.id, ad_group.name, ad_group.targeting_setting.target_restrictions
                FROM ad_group
                WHERE ad_group.id = {adGroupId}";

            try
            {
                // Issue the search request.
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchResponse =
                    googleAdsServiceClient.Search(customerId.ToString(), query);

                // Create an empty TargetingSetting instance.
                TargetingSetting targetingSetting = new TargetingSetting();

                // Create a flag that specifies whether or not we should update the targeting
                // setting. We should only do this if we find an AUDIENCE target restriction with
                // bid_only set to false.
                bool shouldUpdateTargetingSetting = false;

                // Iterate over all rows in all pages and prints the requested field values for the
                // ad group in each row.
                foreach (GoogleAdsRow googleAdsRow in searchResponse)
                {
                    AdGroup adGroup = googleAdsRow.AdGroup;

                    Console.WriteLine($"Ad group with ID {adGroup.Id} and name '{adGroup.Name}' " +
                                      "was found with the following targeting restrictions:");

                    RepeatedField <TargetRestriction> targetRestrictions =
                        adGroup.TargetingSetting.TargetRestrictions;

                    // Loop through and print each of the target restrictions. Reconstruct the
                    // TargetingSetting object with the updated audience target restriction because
                    // Google will overwrite the entire targeting_setting field of the ad group when
                    // the field mask includes targeting_setting in an update operation.
                    foreach (TargetRestriction targetRestriction in targetRestrictions)
                    {
                        TargetingDimension targetingDimension =
                            targetRestriction.TargetingDimension;
                        bool bidOnly = targetRestriction.BidOnly;

                        Console.WriteLine("\tTargeting restriction with targeting dimension " +
                                          $"'{targetingDimension}' and bid only set to '{bidOnly}'.");

                        // Add the target restriction to the TargetingSetting object as is if the
                        // targeting dimension has a value other than AUDIENCE because those should
                        // not change.
                        if (targetingDimension != TargetingDimension.Audience)
                        {
                            targetingSetting.TargetRestrictions.Add(targetRestriction);
                        }
                        else if (!bidOnly)
                        {
                            shouldUpdateTargetingSetting = true;

                            // Add an AUDIENCE target restriction with bid_only set to true to the
                            // targeting setting object. This has the effect of setting the AUDIENCE
                            // target restriction to "Observation". For more details about the
                            // targeting setting, visit
                            // https://support.google.com/google-ads/answer/7365594.
                            targetingSetting.TargetRestrictions.Add(new TargetRestriction
                            {
                                TargetingDimension = TargetingDimension.Audience,
                                BidOnly            = true
                            });
                        }
                    }
                }

                // Only update the TargetSetting on the ad group if there is an AUDIENCE
                // TargetRestriction with bid_only set to false.
                if (shouldUpdateTargetingSetting)
                {
                    UpdateTargetingSetting(client, customerId, adGroupId, targetingSetting);
                }
                else
                {
                    Console.WriteLine("No target restrictions to update.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <summary>Snippet for ListInstances</summary>
        public void ListInstances()
        {
            // Snippet: ListInstances(string, string, string, RegionInstanceGroupsListInstancesRequest, string, int?, CallSettings)
            // Create client
            RegionInstanceGroupsClient regionInstanceGroupsClient = RegionInstanceGroupsClient.Create();
            // Initialize request argument(s)
            string project       = "";
            string region        = "";
            string instanceGroup = "";
            RegionInstanceGroupsListInstancesRequest regionInstanceGroupsListInstancesRequestResource = new RegionInstanceGroupsListInstancesRequest();
            // Make the request
            PagedEnumerable <RegionInstanceGroupsListInstances, InstanceWithNamedPorts> response = regionInstanceGroupsClient.ListInstances(project, region, instanceGroup, regionInstanceGroupsListInstancesRequestResource);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (InstanceWithNamedPorts item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (RegionInstanceGroupsListInstances page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (InstanceWithNamedPorts item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <InstanceWithNamedPorts> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (InstanceWithNamedPorts item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="campaignId">Id of the campaign for which disapproved ads
        /// are retrieved.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V6.GoogleAdsService);

            string searchQuery = $@"
                SELECT
                    ad_group_ad.ad.id,
                    ad_group_ad.ad.type,
                    ad_group_ad.policy_summary.approval_status,
                    ad_group_ad.policy_summary.policy_topic_entries
                FROM ad_group_ad
                WHERE
                    campaign.id = {campaignId}
                    AND ad_group_ad.policy_summary.approval_status = DISAPPROVED";

            // Create a request that will retrieve all Disapproved Ads
            SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
            {
                PageSize   = PAGE_SIZE,
                Query      = searchQuery,
                CustomerId = customerId.ToString(),
                ReturnTotalResultsCount = true
            };

            try
            {
                // Issue the search request.
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
                    googleAdsService.Search(request);

                long disapprovedAdsCount = searchPagedResponse.AsRawResponses()
                                           .First().TotalResultsCount;

                // Iterate over all rows in all rows returned and count disapproved Ads
                foreach (GoogleAdsRow googleAdsRow in searchPagedResponse)
                {
                    AdGroupAdPolicySummary policySummary = googleAdsRow.AdGroupAd.PolicySummary;
                    AdGroupAd adGroupAd = googleAdsRow.AdGroupAd;
                    Ad        ad        = adGroupAd.Ad;
                    Console.WriteLine(
                        "Ad with ID {0} and type '{1}' was disapproved with the " +
                        "following policy topic entries: ",
                        ad.Id, ad.Type);

                    // Display the policy topic entries related to the ad disapproval.
                    foreach (PolicyTopicEntry policyTopicEntry in policySummary.PolicyTopicEntries)
                    {
                        Console.WriteLine("  topic: {0}, type: '{1}'",
                                          policyTopicEntry.Topic,
                                          policyTopicEntry.Type);

                        // Display the attributes and values that triggered the policy topic.
                        if (policyTopicEntry.Evidences != null)
                        {
                            foreach (PolicyTopicEvidence evidence in policyTopicEntry.Evidences)
                            {
                                if (evidence.TextList != null)
                                {
                                    for (int i = 0; i < evidence.TextList.Texts.Count; i++)
                                    {
                                        Console.WriteLine("    evidence text[{0}]: {1}", i,
                                                          evidence.TextList.Texts[i]);
                                    }
                                }
                            }
                        }
                    }
                }

                Console.WriteLine("Number of disapproved ads found: {0}", disapprovedAdsCount);
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <summary>Snippet for ListPredictionApiKeyRegistrations</summary>
        public void ListPredictionApiKeyRegistrationsResourceNames()
        {
            // Snippet: ListPredictionApiKeyRegistrations(EventStoreName, string, int?, CallSettings)
            // Create client
            PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = PredictionApiKeyRegistryClient.Create();
            // Initialize request argument(s)
            EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
            // Make the request
            PagedEnumerable <ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> response = predictionApiKeyRegistryClient.ListPredictionApiKeyRegistrations(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (PredictionApiKeyRegistration item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListPredictionApiKeyRegistrationsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (PredictionApiKeyRegistration item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <PredictionApiKeyRegistration> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (PredictionApiKeyRegistration item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
Ejemplo n.º 17
0
        /// <summary>Snippet for ListNetworkEndpoints</summary>
        public void ListNetworkEndpoints()
        {
            // Snippet: ListNetworkEndpoints(string, string, string, int?, CallSettings)
            // Create client
            GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
            // Initialize request argument(s)
            string project = "";
            string networkEndpointGroup = "";
            // Make the request
            PagedEnumerable <NetworkEndpointGroupsListNetworkEndpoints, NetworkEndpointWithHealthStatus> response = globalNetworkEndpointGroupsClient.ListNetworkEndpoints(project, networkEndpointGroup);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (NetworkEndpointWithHealthStatus item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (NetworkEndpointGroupsListNetworkEndpoints page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (NetworkEndpointWithHealthStatus item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <NetworkEndpointWithHealthStatus> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (NetworkEndpointWithHealthStatus item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupId">The ad group ID for which ad group bid modiifers will
        /// be retrieved.</param>
        public void Run(GoogleAdsClient client, long customerId, long?adGroupId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService =
                client.GetService(Services.V10.GoogleAdsService);

            string searchQuery = @"
                SELECT
                    ad_group.id,
                    ad_group_bid_modifier.criterion_id,
                    campaign.id,
                    ad_group_bid_modifier.bid_modifier,
                    ad_group_bid_modifier.device.type,
                    ad_group_bid_modifier.hotel_date_selection_type.type,
                    ad_group_bid_modifier.hotel_advance_booking_window.min_days,
                    ad_group_bid_modifier.hotel_advance_booking_window.max_days,
                    ad_group_bid_modifier.hotel_length_of_stay.min_nights,
                    ad_group_bid_modifier.hotel_length_of_stay.max_nights,
                    ad_group_bid_modifier.hotel_check_in_day.day_of_week,
                    ad_group_bid_modifier.hotel_check_in_date_range.start_date,
                    ad_group_bid_modifier.hotel_check_in_date_range.end_date,
                    ad_group_bid_modifier.preferred_content.type
                FROM
                    ad_group_bid_modifier";

            if (adGroupId != null)
            {
                searchQuery += $" WHERE ad_group.id = {adGroupId}";
            }

            searchQuery += " LIMIT 10000";
            // Creates a request that will retrieve ad group bid modifiers using pages of the
            // specified page size.
            SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
            {
                CustomerId = customerId.ToString(),
                Query      = searchQuery,
                PageSize   = PAGE_SIZE
            };

            try
            {
                // Issue the search request.
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
                    googleAdsService.Search(request);

                // Iterates over all rows in all pages and prints the requested field values for
                // the ad group bid modifiers in each row.
                foreach (GoogleAdsRow googleAdsRow in searchPagedResponse)
                {
                    AdGroupBidModifier agBidModifier = googleAdsRow.AdGroupBidModifier;
                    AdGroup            adGroup       = googleAdsRow.AdGroup;
                    Campaign           campaign      = googleAdsRow.Campaign;
                    Console.WriteLine("Ad group bid modifier with criterion ID {0}, bid " +
                                      "modifier value {1:0.00} was found in an ad group with ID {2} of " +
                                      "campaign ID {3}.",
                                      agBidModifier.CriterionId,
                                      agBidModifier.BidModifier,
                                      adGroup.Id, campaign.Id);

                    string criterionDetails = "  - Criterion type: " +
                                              $"{agBidModifier.CriterionCase}, ";
                    switch (agBidModifier.CriterionCase)
                    {
                    case CriterionOneofCase.Device:
                        criterionDetails += $"Type: {agBidModifier.Device.Type}";
                        break;

                    case CriterionOneofCase.HotelAdvanceBookingWindow:
                        criterionDetails +=
                            $"Min Days: {agBidModifier.HotelAdvanceBookingWindow.MinDays}," +
                            $"Max Days: {agBidModifier.HotelAdvanceBookingWindow.MaxDays}";
                        break;

                    case CriterionOneofCase.HotelCheckInDay:
                        criterionDetails += $"Day of the week: " +
                                            $"{agBidModifier.HotelCheckInDay.DayOfWeek}";
                        break;

                    case CriterionOneofCase.HotelDateSelectionType:
                        criterionDetails += $"Date selection type: " +
                                            $"{agBidModifier.HotelDateSelectionType.Type}";
                        break;

                    case CriterionOneofCase.HotelLengthOfStay:
                        criterionDetails +=
                            $"Min Nights: {agBidModifier.HotelLengthOfStay.MinNights}," +
                            $"Max Nights: {agBidModifier.HotelLengthOfStay.MaxNights}";
                        break;

                    case CriterionOneofCase.HotelCheckInDateRange:
                        criterionDetails +=
                            $"Start Date: {agBidModifier.HotelCheckInDateRange.StartDate}," +
                            $"End Date: {agBidModifier.HotelCheckInDateRange.EndDate}";
                        break;

                    case CriterionOneofCase.PreferredContent:
                        criterionDetails +=
                            $"Type: {agBidModifier.PreferredContent.Type}";
                        break;
                    }
                    Console.WriteLine(criterionDetails);
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="googleAdsClient">The Google Ads client instance.</param>
        /// <param name="managerCustomerId">Optional manager account ID. If none provided, this method
        /// will instead list the accounts accessible from the authenticated Google Ads account.
        /// </param>
        /// <param name="loginCustomerId">The login customer ID used to create the GoogleAdsClient.
        /// </param>
        public void Run(GoogleAdsClient googleAdsClient, long?managerCustomerId = null,
                        long?loginCustomerId = null)
        {
            if (loginCustomerId.HasValue)
            {
                googleAdsClient.Config.LoginCustomerId = loginCustomerId.Value.ToString();
            }

            GoogleAdsServiceClient googleAdsServiceClient =
                googleAdsClient.GetService(Services.V6.GoogleAdsService);

            CustomerServiceClient customerServiceClient =
                googleAdsClient.GetService(Services.V6.CustomerService);

            // List of Customer IDs to handle.
            List <long> seedCustomerIds = new List <long>();

            // If a Manager ID was provided in the customerId parameter, it will be the only ID
            // in the list. Otherwise, we will issue a request for all customers accessible by
            // this authenticated Google account.
            if (managerCustomerId.HasValue)
            {
                seedCustomerIds.Add(managerCustomerId.Value);
            }
            else
            {
                Console.WriteLine(
                    "No manager customer ID is specified. The example will print the hierarchies " +
                    " of all accessible customer IDs:");

                string[] customerResourceNames = customerServiceClient.ListAccessibleCustomers();

                foreach (string customerResourceName in customerResourceNames)
                {
                    CustomerName customerName = CustomerName.Parse(customerResourceName);
                    Console.WriteLine(customerName.CustomerId);
                    seedCustomerIds.Add(long.Parse(customerName.CustomerId));
                }

                Console.WriteLine();
            }

            // Create a query that retrieves all child accounts of the manager specified in
            // search calls below.
            const string query = @"SELECT
                                    customer_client.client_customer,
                                    customer_client.level,
                                    customer_client.manager,
                                    customer_client.descriptive_name,
                                    customer_client.currency_code,
                                    customer_client.time_zone,
                                    customer_client.id
                                FROM customer_client
                                WHERE
                                    customer_client.level <= 1";

            // Perform a breadth-first search to build a Dictionary that maps managers to their
            // child accounts.
            Dictionary <long, List <CustomerClient> > customerIdsToChildAccounts =
                new Dictionary <long, List <CustomerClient> >();

            foreach (long seedCustomerId in seedCustomerIds)
            {
                Queue <long> unprocessedCustomerIds = new Queue <long>();
                unprocessedCustomerIds.Enqueue(seedCustomerId);
                CustomerClient rootCustomerClient = null;

                while (unprocessedCustomerIds.Count > 0)
                {
                    managerCustomerId = unprocessedCustomerIds.Dequeue();
                    PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> response =
                        googleAdsServiceClient.Search(
                            managerCustomerId.ToString(),
                            query,
                            pageSize: PAGE_SIZE
                            );

                    // Iterate over all rows in all pages to get all customer clients under the
                    // specified customer's hierarchy.
                    foreach (GoogleAdsRow googleAdsRow in response)
                    {
                        CustomerClient customerClient = googleAdsRow.CustomerClient;

                        // The customer client that with level 0 is the specified customer.
                        if (customerClient.Level == 0)
                        {
                            if (rootCustomerClient == null)
                            {
                                rootCustomerClient = customerClient;
                            }

                            continue;
                        }

                        // For all level-1 (direct child) accounts that are a manager account,
                        // the above query will be run against them to create a Dictionary of
                        // managers mapped to their child accounts for printing the hierarchy
                        // afterwards.
                        if (!customerIdsToChildAccounts.ContainsKey(managerCustomerId.Value))
                        {
                            customerIdsToChildAccounts.Add(managerCustomerId.Value,
                                                           new List <CustomerClient>());
                        }

                        customerIdsToChildAccounts[managerCustomerId.Value].Add(customerClient);

                        if (customerClient.Manager)
                        {
                            // A customer can be managed by multiple managers, so to prevent
                            // visiting the same customer many times, we need to check if it's
                            // already in the Dictionary.
                            if (!customerIdsToChildAccounts.ContainsKey(customerClient.Id) &&
                                customerClient.Level == 1)
                            {
                                unprocessedCustomerIds.Enqueue(customerClient.Id);
                            }
                        }
                    }
                }

                if (rootCustomerClient != null)
                {
                    Console.WriteLine("The hierarchy of customer ID {0} is printed below:",
                                      rootCustomerClient.Id);
                    PrintAccountHierarchy(rootCustomerClient, customerIdsToChildAccounts, 0);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(
                        "Customer ID {0} is likely a test account, so its customer client " +
                        " information cannot be retrieved.", managerCustomerId);
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsServiceClient.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V4.GoogleAdsService);

            // Define a GAQL query to retrieve all billing setup information.
            string searchQuery = @"
                SELECT
                    billing_setup.id,
                    billing_setup.status,
                    billing_setup.payments_account,
                    billing_setup.payments_account_info.payments_account_id,
                    billing_setup.payments_account_info.payments_account_name,
                    billing_setup.payments_account_info.payments_profile_id,
                    billing_setup.payments_account_info.payments_profile_name,
                    billing_setup.payments_account_info.secondary_payments_profile_id
                FROM billing_setup";

            // Creates a request that will retrieve all billing setups using pages of the specified
            // page size.
            SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
            {
                PageSize   = PAGE_SIZE,
                Query      = searchQuery,
                CustomerId = customerId.ToString()
            };

            try
            {
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
                    googleAdsService.Search(request);

                foreach (SearchGoogleAdsResponse response in searchPagedResponse.AsRawResponses())
                {
                    foreach (GoogleAdsRow googleAdsRow in response.Results)
                    {
                        BillingSetup billingSetup = googleAdsRow.BillingSetup;
                        Console.WriteLine("Billing setup with ID '{0}', status '{1}', " +
                                          "payments account '{2}', payments account Id '{3}', " +
                                          "payments account name '{4}', payments profile id '{5}', " +
                                          "payments profile name '{6}', secondary payments profile id '{7}'.",
                                          billingSetup.Id,
                                          billingSetup.Status,
                                          billingSetup.PaymentsAccount,
                                          billingSetup.PaymentsAccountInfo.PaymentsAccountId,
                                          billingSetup.PaymentsAccountInfo.PaymentsAccountName,
                                          billingSetup.PaymentsAccountInfo.PaymentsProfileId,
                                          billingSetup.PaymentsAccountInfo.PaymentsProfileName,
                                          billingSetup.PaymentsAccountInfo.SecondaryPaymentsProfileId);
                    }
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <summary>Snippet for Predict</summary>
        public void Predict()
        {
            // Snippet: Predict(string, UserEvent, string, int?, CallSettings)
            // Create client
            PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
            // Initialize request argument(s)
            string    name      = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]/placements/[PLACEMENT]";
            UserEvent userEvent = new UserEvent();
            // Make the request
            PagedEnumerable <PredictResponse, PredictResponse.Types.PredictionResult> response = predictionServiceClient.Predict(name, userEvent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (PredictResponse.Types.PredictionResult item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (PredictResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (PredictResponse.Types.PredictionResult item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <PredictResponse.Types.PredictionResult> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (PredictResponse.Types.PredictionResult item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">The ID of the campaign for which shared criterion is updated.
        /// </param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId)
        {
            try
            {
                SharedCriterionServiceClient sharedCriterionService = client.GetService(
                    Services.V2.SharedCriterionService);

                GoogleAdsServiceClient googleAdsService = client.GetService(
                    Services.V2.GoogleAdsService);

                List <long?>  sharedSetIds       = new List <long?>();
                List <string> criterionResources = new List <string>();

                // First, retrieve all shared sets associated with the campaign.
                string sharedSetQuery = $"SELECT shared_set.id, shared_set.name FROM " +
                                        $"campaign_shared_set WHERE campaign.id = {campaignId}";

                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> sharedSetResponse =
                    googleAdsService.Search(customerId.ToString(), sharedSetQuery);

                // Display the results.
                foreach (GoogleAdsRow googleAdsRow in sharedSetResponse)
                {
                    SharedSet sharedSet = googleAdsRow.SharedSet;
                    Console.WriteLine("Campaign shared set ID {0} and name '{1}' was found.",
                                      sharedSet.Id, sharedSet.Name);

                    sharedSetIds.Add(sharedSet.Id);
                }

                // Next, retrieve shared criteria for all found shared sets.
                string sharedCriterionQuery =
                    "SELECT shared_criterion.type, shared_criterion.keyword.text, " +
                    "shared_criterion.keyword.match_type, shared_set.id FROM shared_criterion " +
                    $"WHERE shared_set.id IN(" +
                    string.Join(",", sharedSetIds.ConvertAll(x => x.ToString())) + ")";

                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> sharedCriterionResponse =
                    googleAdsService.Search(customerId.ToString(), sharedCriterionQuery);

                // Display the results.
                foreach (GoogleAdsRow googleAdsRow in sharedCriterionResponse)
                {
                    SharedCriterion sharedCriterion = googleAdsRow.SharedCriterion;
                    if (sharedCriterion.Type == CriterionType.Keyword)
                    {
                        Console.WriteLine("Shared criterion with resource name '{0}' for " +
                                          "negative keyword with text '{1}' and match type '{2}' was found.",
                                          sharedCriterion.ResourceName,
                                          sharedCriterion.Keyword.Text,
                                          sharedCriterion.Keyword.MatchType);
                    }
                    else
                    {
                        Console.WriteLine("Shared criterion with resource name '{0}' was found.",
                                          sharedCriterion.ResourceName);
                    }
                    criterionResources.Add(sharedCriterion.ResourceName);
                }

                // Finally, remove the criteria.
                List <SharedCriterionOperation> operations = new List <SharedCriterionOperation>();
                foreach (string criterionResource in criterionResources)
                {
                    SharedCriterionOperation operation = new SharedCriterionOperation()
                    {
                        Remove = criterionResource
                    };
                    operations.Add(operation);
                }

                MutateSharedCriteriaResponse response =
                    sharedCriterionService.MutateSharedCriteria(
                        customerId.ToString(), operations);

                foreach (MutateSharedCriterionResult result in response.Results)
                {
                    Console.WriteLine($"Removed shared criterion {result.ResourceName}.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
            }
        }
        /// <summary>Snippet for Predict</summary>
        public void PredictRequestObject()
        {
            // Snippet: Predict(PredictRequest, CallSettings)
            // Create client
            PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
            // Initialize request argument(s)
            PredictRequest request = new PredictRequest
            {
                PlacementName = PlacementName.FromProjectLocationCatalogEventStorePlacement("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PLACEMENT]"),
                UserEvent     = new UserEvent(),
                Filter        = "",
                DryRun        = false,
                Params        = { { "", new Value() }, },
                Labels        = { { "", "" }, },
            };
            // Make the request
            PagedEnumerable <PredictResponse, PredictResponse.Types.PredictionResult> response = predictionServiceClient.Predict(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (PredictResponse.Types.PredictionResult item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (PredictResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (PredictResponse.Types.PredictionResult item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <PredictResponse.Types.PredictionResult> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (PredictResponse.Types.PredictionResult item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
        /// <summary>Snippet for AggregatedList</summary>
        public void AggregatedListRequestObject()
        {
            // Snippet: AggregatedList(AggregatedListPacketMirroringsRequest, CallSettings)
            // Create client
            PacketMirroringsClient packetMirroringsClient = PacketMirroringsClient.Create();
            // Initialize request argument(s)
            AggregatedListPacketMirroringsRequest request = new AggregatedListPacketMirroringsRequest
            {
                OrderBy              = "",
                Project              = "",
                Filter               = "",
                IncludeAllScopes     = false,
                ReturnPartialSuccess = false,
            };
            // Make the request
            PagedEnumerable <PacketMirroringAggregatedList, KeyValuePair <string, PacketMirroringsScopedList> > response = packetMirroringsClient.AggregatedList(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (KeyValuePair <string, PacketMirroringsScopedList> item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (PacketMirroringAggregatedList page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (KeyValuePair <string, PacketMirroringsScopedList> item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <KeyValuePair <string, PacketMirroringsScopedList> > singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (KeyValuePair <string, PacketMirroringsScopedList> item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
        /// <summary>Snippet for ListAndroidAppDataStreams</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void ListAndroidAppDataStreams()
        {
            // Create client
            AnalyticsAdminServiceClient analyticsAdminServiceClient = AnalyticsAdminServiceClient.Create();
            // Initialize request argument(s)
            string parent = "properties/[PROPERTY]";
            // Make the request
            PagedEnumerable <ListAndroidAppDataStreamsResponse, AndroidAppDataStream> response = analyticsAdminServiceClient.ListAndroidAppDataStreams(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (AndroidAppDataStream item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListAndroidAppDataStreamsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (AndroidAppDataStream item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <AndroidAppDataStream> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (AndroidAppDataStream item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        // [START GetChangeSummary]
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V6.GoogleAdsService);

            string searchQuery = @"
                SELECT
                    change_status.resource_name,
                    change_status.last_change_date_time,
                    change_status.resource_type,
                    change_status.campaign,
                    change_status.ad_group,
                    change_status.resource_status,
                    change_status.ad_group_ad,
                    change_status.ad_group_criterion,
                    change_status.campaign_criterion
                FROM change_status
                WHERE
                    change_status.last_change_date_time DURING LAST_14_DAYS
                ORDER BY change_status.last_change_date_time
                LIMIT 10000";

            // Create a request that will retrieve all changes using pages of the specified
            // page size.
            SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
            {
                PageSize   = PAGE_SIZE,
                Query      = searchQuery,
                CustomerId = customerId.ToString()
            };

            try
            {
                // Issue the search request.
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
                    googleAdsService.Search(request);

                // Iterate over all rows in all pages and prints the requested field values for the
                // campaign in each row.
                foreach (GoogleAdsRow googleAdsRow in searchPagedResponse)
                {
                    Console.WriteLine("Last change: {0}, Resource type: {1}, " +
                                      "Resource name: {2}, Resource status: {3}, Specific resource name: {4}",
                                      googleAdsRow.ChangeStatus.LastChangeDateTime,
                                      googleAdsRow.ChangeStatus.ResourceType,
                                      googleAdsRow.ChangeStatus.ResourceName,
                                      googleAdsRow.ChangeStatus.ResourceStatus,
                                      SpecificResourceName(googleAdsRow.ChangeStatus.ResourceType,
                                                           googleAdsRow));
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Ejemplo n.º 27
0
 public ResourceCollection(IEnumerable <T> source, int pageIndex, int pageSize, int totalCount)
 {
     Data = new PagedEnumerable <T>(source, pageIndex, pageSize, totalCount);
 }
        public void ListMonitoredResourceDescriptors_RequestObject()
        {
            // Snippet: ListMonitoredResourceDescriptors(ListMonitoredResourceDescriptorsRequest,CallSettings)
            // Create client
            LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create();
            // Initialize request argument(s)
            ListMonitoredResourceDescriptorsRequest request = new ListMonitoredResourceDescriptorsRequest();
            // Make the request
            PagedEnumerable <ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response =
                loggingServiceV2Client.ListMonitoredResourceDescriptors(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (MonitoredResourceDescriptor item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListMonitoredResourceDescriptorsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (MonitoredResourceDescriptor item in page)
                {
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <MonitoredResourceDescriptor> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (MonitoredResourceDescriptor item in singlePage)
            {
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsServiceClient.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V2.GoogleAdsService);

            // Construct a GAQL query which will retrieve AccountBudgetProposals.
            String searchQuery =
                @"SELECT
                    account_budget.status,
                    account_budget.billing_setup,
                    account_budget.approved_spending_limit_micros,
                    account_budget.approved_spending_limit_type,
                    account_budget.proposed_spending_limit_micros,
                    account_budget.proposed_spending_limit_type,
                    account_budget.approved_start_date_time,
                    account_budget.proposed_start_date_time,
                    account_budget.approved_end_date_time,
                    account_budget.approved_end_time_type,
                    account_budget.proposed_end_date_time,
                    account_budget.proposed_end_time_type
                 FROM
                     account_budget";

            // Creates a request that will retrieve all account budgets using pages of the
            // specified page size.
            SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
            {
                PageSize   = PAGE_SIZE,
                Query      = searchQuery,
                CustomerId = customerId.ToString()
            };

            try
            {
                // Issues the search request.
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
                    googleAdsService.Search(request);

                // Iterates over all rows in all pages and prints the requested field values for
                // the account budget in each row.
                foreach (GoogleAdsRow googleAdsRow in searchPagedResponse)
                {
                    AccountBudget budget = googleAdsRow.AccountBudget;

                    Console.WriteLine(String.Format("Account budget '{0}' with status '{1}', " +
                                                    "billing setup '{2}', amount served {3:0.00}, total adjustments " +
                                                    "{4:0.00}, approved spending limit '{5}' (proposed '{6}'), approved " +
                                                    "start time '{7}' (proposed '{8}'), approved end time '{9}' " +
                                                    "(proposed '{10}')",
                                                    budget.ResourceName,
                                                    budget.Status,
                                                    budget.BillingSetup,
                                                    budget.AmountServedMicros.Value / 1_000_000.0,
                                                    budget.TotalAdjustmentsMicros.Value / 1_000_000.0,
                                                    budget.ApprovedSpendingLimitMicros.HasValue
                            ? String.Format(
                                                        "%.2f", budget.ApprovedSpendingLimitMicros.Value / 1_000_000.0)
                            : budget.ApprovedSpendingLimitType.ToString(),
                                                    budget.ProposedSpendingLimitMicros.HasValue
                            ? String.Format(
                                                        "%.2f", budget.ProposedSpendingLimitMicros.Value / 1_000_000.0)
                            : budget.ProposedSpendingLimitType.ToString(),
                                                    budget.ApprovedStartDateTime,
                                                    budget.ProposedStartDateTime,
                                                    String.IsNullOrEmpty(budget.ApprovedEndDateTime)
                            ? budget.ApprovedEndTimeType.ToString()
                            : budget.ApprovedEndDateTime,
                                                    String.IsNullOrEmpty(budget.ProposedEndDateTime)
                            ? budget.ProposedEndTimeType.ToString()
                            : budget.ProposedEndDateTime));
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
            }
        }