Exemplo n.º 1
0
        /// <summary>
        /// Uploads the image asset.
        /// </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="imageUrl">The image URL.</param>
        /// <param name="width">The image width in pixels.</param>
        /// <param name="height">The image height in pixels.</param>
        /// <returns></returns>
        private static string UploadImageAsset(GoogleAdsClient client, long customerId,
                                               string imageUrl, long width, long height)
        {
            // Get the AssetServiceClient.
            AssetServiceClient assetService =
                client.GetService(Services.V3.AssetService);

            // Creates an image content.
            byte[] imageContent = MediaUtilities.GetAssetDataFromUrl(imageUrl, client.Config);

            // Creates an image asset.
            ImageAsset imageAsset = new ImageAsset()
            {
                Data     = ByteString.CopyFrom(imageContent),
                FileSize = imageContent.Length,
                MimeType = MimeType.ImageJpeg,
                FullSize = new ImageDimension()
                {
                    HeightPixels = height,
                    WidthPixels  = width,
                    Url          = imageUrl
                }
            };

            // Creates an asset.
            Asset asset = new Asset()
            {
                // Optional: Provide a unique friendly name to identify your asset.
                // If you specify the name field, then both the asset name and the image being
                // uploaded should be unique, and should not match another ACTIVE asset in this
                // customer account.
                // Name = 'Jupiter Trip #' + ExampleUtilities.GetRandomString(),
                Type       = AssetType.Image,
                ImageAsset = imageAsset
            };

            // Creates an asset operation.
            AssetOperation operation = new AssetOperation()
            {
                Create = asset
            };

            // Issues a mutate request to add the asset.
            MutateAssetsResponse response =
                assetService.MutateAssets(customerId.ToString(), new[] { operation });

            string assetResourceName = response.Results.First().ResourceName;

            // Print out some information about the added asset.
            Console.WriteLine($"Added asset with resource name = '{assetResourceName}'.");

            return(assetResourceName);
        }
 /// <summary>Snippet for MutateAssets</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void MutateAssets()
 {
     // Create client
     AssetServiceClient assetServiceClient = AssetServiceClient.Create();
     // Initialize request argument(s)
     string customerId = "";
     IEnumerable <AssetOperation> operations = new AssetOperation[]
     {
         new AssetOperation(),
     };
     // Make the request
     MutateAssetsResponse response = assetServiceClient.MutateAssets(customerId, operations);
 }
        // [START add_asset]
        /// <summary>
        /// Creates Assets to be used in a DSA page feed.
        /// </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="dsaPageUrlLabel">The DSA page URL label.</param>
        /// <returns>The list of asset resource names.</returns>
        private static List <string> CreateAssets(GoogleAdsClient client, long customerId,
                                                  string dsaPageUrlLabel)
        {
            AssetServiceClient assetService = client.GetService(Services.V10.AssetService);

            string[] urls = new[]
            {
                "http://www.example.com/discounts/rental-cars",
                "http://www.example.com/discounts/hotel-deals",
                "http://www.example.com/discounts/flight-deals"
            };

            // Creates one operation per URL.
            List <AssetOperation> assetOperations = new List <AssetOperation>();

            foreach (string url in urls)
            {
                PageFeedAsset pageFeedAsset = new PageFeedAsset()
                {
                    // Sets the URL of the page to include.
                    PageUrl = url,

                    // Recommended: adds labels to the asset. These labels can be used later in
                    // ad group targeting to restrict the set of pages that can serve.
                    Labels = { dsaPageUrlLabel }
                };

                assetOperations.Add(
                    new AssetOperation()
                {
                    Create = new Asset()
                    {
                        PageFeedAsset = pageFeedAsset
                    }
                });
            }

            // Adds the assets.
            MutateAssetsResponse response =
                assetService.MutateAssets(customerId.ToString(), assetOperations);

            // Prints some information about the result.
            List <string> resourceNames = response.Results.Select(
                assetResult => assetResult.ResourceName).ToList();

            foreach (string resourceName in resourceNames)
            {
                Console.Write($"Created asset with resource name {resourceName}.");
            }
            return(resourceNames);
        }
        // [START add_asset]
        /// <summary>
        /// Creates an Asset to use in dynamic remarketing.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID.</param>
        /// <returns>The resource name of the newly created asset.</returns>
        private string CreateAsset(GoogleAdsClient client, long customerId)
        {
            AssetServiceClient assetService = client.GetService(Services.V10.AssetService);

            // Creates a DynamicEducationAsset.
            // See https://support.google.com/google-ads/answer/6053288?#zippy=%2Ceducation for a
            // detailed explanation of the field format.
            DynamicEducationAsset educationAsset = new DynamicEducationAsset()
            {
                // Defines meta-information about the school and program.
                SchoolName         = "The University of Unknown",
                Address            = "Building 1, New York, 12345, USA",
                ProgramName        = "BSc. Computer Science",
                Subject            = "Computer Science",
                ProgramDescription = "Slinging code for fun and profit!",
                // Sets up the program ID which is the ID that should be specified in
                // the tracking pixel.
                ProgramId = "bsc-cs-uofu",
                // Sets up the location ID which may additionally be specified in the
                // tracking pixel.
                LocationId     = "nyc",
                ImageUrl       = "https://gaagl.page.link/Eit5",
                AndroidAppLink = "android-app://com.example.android/http/example.com/gizmos?1234",
                IosAppLink     = "exampleApp://content/page",
                IosAppStoreId  = 123L
            };
            Asset asset = new Asset()
            {
                DynamicEducationAsset = educationAsset,
                // The final_urls list must not be empty
                FinalUrls = { "https://www.example.com" }
            };

            // Creates an operation to add the asset.
            AssetOperation operation = new AssetOperation()
            {
                Create = asset
            };

            // Sends the mutate request.
            MutateAssetsResponse response =
                assetService.MutateAssets(customerId.ToString(), new[] { operation });
            // Prints some information about the response.
            string resourceName = response.Results[0].ResourceName;

            Console.Write($"Created a dynamic education asset with resource name {resourceName}.");
            return(resourceName);
        }
Exemplo n.º 5
0
 /// <summary>Snippet for MutateAssets</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void MutateAssetsRequestObject()
 {
     // Create client
     AssetServiceClient assetServiceClient = AssetServiceClient.Create();
     // Initialize request argument(s)
     MutateAssetsRequest request = new MutateAssetsRequest
     {
         CustomerId = "",
         Operations =
         {
             new AssetOperation(),
         },
     };
     // Make the request
     MutateAssetsResponse response = assetServiceClient.MutateAssets(request);
 }
Exemplo n.º 6
0
        public async Task MutateAssetsAsync2()
        {
            Mock <AssetService.AssetServiceClient> mockGrpcClient = new Mock <AssetService.AssetServiceClient>(MockBehavior.Strict);
            MutateAssetsRequest request = new MutateAssetsRequest
            {
                CustomerId = "customerId-1772061412",
                Operations = { },
            };
            MutateAssetsResponse expectedResponse = new MutateAssetsResponse();

            mockGrpcClient.Setup(x => x.MutateAssetsAsync(request, It.IsAny <CallOptions>()))
            .Returns(new Grpc.Core.AsyncUnaryCall <MutateAssetsResponse>(Task.FromResult(expectedResponse), null, null, null, null));
            AssetServiceClient   client   = new AssetServiceClientImpl(mockGrpcClient.Object, null);
            MutateAssetsResponse response = await client.MutateAssetsAsync(request);

            Assert.AreEqual(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
Exemplo n.º 7
0
        public void MutateAssets2()
        {
            Mock <AssetService.AssetServiceClient> mockGrpcClient = new Mock <AssetService.AssetServiceClient>(MockBehavior.Strict);
            MutateAssetsRequest request = new MutateAssetsRequest
            {
                CustomerId = "customerId-1772061412",
                Operations = { },
            };
            MutateAssetsResponse expectedResponse = new MutateAssetsResponse();

            mockGrpcClient.Setup(x => x.MutateAssets(request, It.IsAny <CallOptions>()))
            .Returns(expectedResponse);
            AssetServiceClient   client   = new AssetServiceClientImpl(mockGrpcClient.Object, null);
            MutateAssetsResponse response = client.MutateAssets(request);

            Assert.AreEqual(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
        /// <summary>Snippet for MutateAssetsAsync</summary>
        public async Task MutateAssetsAsync()
        {
            // Snippet: MutateAssetsAsync(string, IEnumerable<AssetOperation>, CallSettings)
            // Additional: MutateAssetsAsync(string, IEnumerable<AssetOperation>, CancellationToken)
            // Create client
            AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();

            // Initialize request argument(s)
            string customerId = "";
            IEnumerable <AssetOperation> operations = new AssetOperation[]
            {
                new AssetOperation(),
            };
            // Make the request
            MutateAssetsResponse response = await assetServiceClient.MutateAssetsAsync(customerId, operations);

            // End snippet
        }
Exemplo n.º 9
0
        /// <summary>Snippet for MutateAssetsAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task MutateAssetsRequestObjectAsync()
        {
            // Create client
            AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();

            // Initialize request argument(s)
            MutateAssetsRequest request = new MutateAssetsRequest
            {
                CustomerId = "",
                Operations =
                {
                    new AssetOperation(),
                },
                ResponseContentType = ResponseContentTypeEnum.Types.ResponseContentType.Unspecified,
            };
            // Make the request
            MutateAssetsResponse response = await assetServiceClient.MutateAssetsAsync(request);
        }
 /// <summary>Snippet for MutateAssets</summary>
 public void MutateAssetsRequestObject()
 {
     // Snippet: MutateAssets(MutateAssetsRequest, CallSettings)
     // Create client
     AssetServiceClient assetServiceClient = AssetServiceClient.Create();
     // Initialize request argument(s)
     MutateAssetsRequest request = new MutateAssetsRequest
     {
         CustomerId = "",
         Operations =
         {
             new AssetOperation(),
         },
         ResponseContentType = ResponseContentTypeEnum.Types.ResponseContentType.Unspecified,
     };
     // Make the request
     MutateAssetsResponse response = assetServiceClient.MutateAssets(request);
     // End snippet
 }
 /// <summary>Snippet for MutateAssets</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void MutateAssetsRequestObject()
 {
     // Create client
     AssetServiceClient assetServiceClient = AssetServiceClient.Create();
     // Initialize request argument(s)
     MutateAssetsRequest request = new MutateAssetsRequest
     {
         CustomerId = "",
         Operations =
         {
             new AssetOperation(),
         },
         ResponseContentType = ResponseContentTypeEnum.Types.ResponseContentType.Unspecified,
         ValidateOnly        = false,
         PartialFailure      = false,
     };
     // Make the request
     MutateAssetsResponse response = assetServiceClient.MutateAssets(request);
 }
        /// <summary>Snippet for MutateAssetsAsync</summary>
        public async Task MutateAssetsRequestObjectAsync()
        {
            // Snippet: MutateAssetsAsync(MutateAssetsRequest, CallSettings)
            // Additional: MutateAssetsAsync(MutateAssetsRequest, CancellationToken)
            // Create client
            AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();

            // Initialize request argument(s)
            MutateAssetsRequest request = new MutateAssetsRequest
            {
                CustomerId = "",
                Operations =
                {
                    new AssetOperation(),
                },
            };
            // Make the request
            MutateAssetsResponse response = await assetServiceClient.MutateAssetsAsync(request);

            // End snippet
        }
        /// <summary>
        /// Creates a media bundle from the assets in a zip file. The zip file contains the
        /// HTML5 components.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <returns>The string resource name of the newly uploaded media bundle.</returns>
        private string CreateMediaBundleAsset(GoogleAdsClient client, long customerId)
        {
            // Gets the AssetService.
            AssetServiceClient assetServiceClient = client.GetService(Services.V10.AssetService);

            // The HTML5 zip file contains all the HTML, CSS, and images needed for the
            // HTML5 ad. For help on creating an HTML5 zip file, check out Google Web
            // Designer (https://www.google.com/webdesigner/).
            byte[] html5Zip = MediaUtilities.GetAssetDataFromUrl("https://gaagl.page.link/ib87",
                                                                 client.Config);

            // Creates the media bundle asset.
            Asset mediaBundleAsset = new Asset()
            {
                Type             = AssetTypeEnum.Types.AssetType.MediaBundle,
                MediaBundleAsset = new MediaBundleAsset()
                {
                    Data = ByteString.CopyFrom(html5Zip)
                },
                Name = "Ad Media Bundle"
            };

            // Creates the asset operation.
            AssetOperation operation = new AssetOperation()
            {
                Create = mediaBundleAsset
            };

            // Adds the asset to the client account.
            MutateAssetsResponse response = assetServiceClient.MutateAssets(customerId.ToString(),
                                                                            new[] { operation });

            // Displays the resulting resource name.
            string uploadedAssetResourceName = response.Results.First().ResourceName;

            Console.WriteLine($"Uploaded media bundle: {uploadedAssetResourceName}");

            return(uploadedAssetResourceName);
        }
Exemplo n.º 14
0
        /// <summary>Snippet for MutateAssetsAsync</summary>
        public async Task MutateAssetsRequestObjectAsync()
        {
            // Snippet: MutateAssetsAsync(MutateAssetsRequest, CallSettings)
            // Additional: MutateAssetsAsync(MutateAssetsRequest, CancellationToken)
            // Create client
            AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();

            // Initialize request argument(s)
            MutateAssetsRequest request = new MutateAssetsRequest
            {
                CustomerId = "",
                Operations =
                {
                    new AssetOperation(),
                },
                ResponseContentType = ResponseContentTypeEnum.Types.ResponseContentType.Unspecified,
                ValidateOnly        = false,
                PartialFailure      = false,
            };
            // Make the request
            MutateAssetsResponse response = await assetServiceClient.MutateAssetsAsync(request);

            // End snippet
        }
Exemplo n.º 15
0
        /// <summary>
        /// Creates a new asset for the call.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID.</param>
        /// <param name="phoneCountry">The phone number country.</param>
        /// <param name="phoneNumber">The phone number itself.</param>
        /// <param name="conversionActionId">The conversion action ID or null.</param>
        /// <returns>The resource name of the created call asset</returns>
        private string AddExtensionAsset(
            GoogleAdsClient client,
            long customerId,
            string phoneCountry,
            string phoneNumber,
            long?conversionActionId)
        {
            // Creates the call asset.
            CallAsset callAsset = new CallAsset()
            {
                // Sets the country code and phone number of the business to call.
                CountryCode = phoneCountry,
                PhoneNumber = phoneNumber,

                // Optional: Specifies all day and time intervals for which the asset may serve.
                AdScheduleTargets =
                {
                    new AdScheduleInfo()
                    {
                        // Sets the day of this schedule as Monday.
                        DayOfWeek = DayOfWeek.Monday,

                        // Sets the start hour to 9am.
                        StartHour = 9,

                        // Sets the end hour to 5pm.
                        EndHour = 17,

                        // Sets the start and end minute of zero, for example: 9:00 and 5:00.
                        StartMinute = MinuteOfHour.Zero,
                        EndMinute   = MinuteOfHour.Zero
                    }
                }
            };

            // Sets the conversion action ID to the one provided if any.
            if (conversionActionId.HasValue)
            {
                callAsset.CallConversionAction =
                    ResourceNames.ConversionAction(customerId, conversionActionId.Value);

                callAsset.CallConversionReportingState =
                    CallConversionReportingState.UseResourceLevelCallConversionAction;
            }

            // Creates an asset operation wrapping the call asset in an asset.
            AssetOperation assetOperation = new AssetOperation()
            {
                Create = new Asset()
                {
                    CallAsset = callAsset
                }
            };

            AssetServiceClient assetServiceClient =
                client.GetService(Services.V10.AssetService);

            // Issues a mutate request to add the asset and prints its information.
            MutateAssetsResponse response = assetServiceClient.MutateAssets(
                customerId.ToString(),
                new[] { assetOperation }
                );

            string createdAssetResourceName = response.Results.First().ResourceName;

            Console.WriteLine(
                $"Created a call asset with resource name: '{createdAssetResourceName}'."
                );

            return(createdAssetResourceName);
        }
        // [END add_lead_form_extension_1]

        /// <summary>
        /// Creates the lead form asset.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <returns>The lead form asset resource name.</returns>
        // [START add_lead_form_extension]
        private string CreateLeadFormAsset(GoogleAdsClient client, long customerId)
        {
            AssetServiceClient assetService = client.GetService(Services.V10.AssetService);

            // Creates the lead form asset.
            Asset leadFormAsset = new Asset()
            {
                Name          = $"Interplanetary Cruise #{ExampleUtilities.GetRandomString()} Lead Form",
                LeadFormAsset = new LeadFormAsset()
                {
                    // Specify the details of the extension that the users will see.
                    CallToActionType        = LeadFormCallToActionType.BookNow,
                    CallToActionDescription = "Latest trip to Jupiter!",

                    // Define the form details.
                    BusinessName     = "Interplanetary Cruise",
                    Headline         = "Trip to Jupiter",
                    Description      = "Our latest trip to Jupiter is now open for booking.",
                    PrivacyPolicyUrl = "http://example.com/privacy",

                    // Define the fields to be displayed to the user.
                    Fields =
                    {
                        new LeadFormField()
                        {
                            InputType = LeadFormFieldUserInputType.FullName,
                        },
                        new LeadFormField()
                        {
                            InputType = LeadFormFieldUserInputType.Email,
                        },
                        new LeadFormField()
                        {
                            InputType = LeadFormFieldUserInputType.PhoneNumber,
                        },
                        new LeadFormField()
                        {
                            InputType           = LeadFormFieldUserInputType.PreferredContactTime,
                            SingleChoiceAnswers = new LeadFormSingleChoiceAnswers()
                            {
                                Answers ={ "Before 9 AM",               "Any time", "After 5 PM" }
                            }
                        },
                        new LeadFormField()
                        {
                            InputType = LeadFormFieldUserInputType.TravelBudget,
                        },
                    },

                    // Optional: You can also specify a background image asset. To upload an asset,
                    // see Misc/UploadImageAsset.cs. BackgroundImageAsset =
                    // "INSERT_IMAGE_ASSET_HERE",

                    // Optional: Define the response page after the user signs up on the form.
                    PostSubmitHeadline    = "Thanks for signing up!",
                    PostSubmitDescription = "We will reach out to you shortly. Visit our website " +
                                            "to see past trip details.",
                    PostSubmitCallToActionType = LeadFormPostSubmitCallToActionType.VisitSite,

                    // Optional: Display a custom disclosure that displays along with the Google
                    // disclaimer on the form.
                    CustomDisclosure = "Trip may get cancelled due to meteor shower.",

                    // Optional: Define a delivery method for the form response. See
                    // https://developers.google.com/google-ads/webhook/docs/overview for more
                    // details on how to define a webhook.
                    DeliveryMethods =
                    {
                        new LeadFormDeliveryMethod()
                        {
                            Webhook = new WebhookDelivery()
                            {
                                AdvertiserWebhookUrl = "http://example.com/webhook",
                                GoogleSecret         = "interplanetary google secret",
                                PayloadSchemaVersion = 3L
                            }
                        }
                    },
                },
                FinalUrls = { "http://example.com/jupiter" }
            };

            // Creates the operation.
            AssetOperation operation = new AssetOperation()
            {
                Create = leadFormAsset,
            };

            // Makes the API call.
            MutateAssetsResponse response = assetService.MutateAssets(customerId.ToString(),
                                                                      new[] { operation });

            string leadFormAssetResourceName = response.Results[0].ResourceName;

            // Displays the result.
            Console.WriteLine($"Asset with resource name = '{leadFormAssetResourceName}' " +
                              "was created.");
            return(leadFormAssetResourceName);
        }
        /// <summary>
        /// Creates a list of <see cref="SitelinkAsset"/> objects which can then be added
        /// to campaigns.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <returns>The list of sitelink resource names.</returns>
        private List <string> CreateSitelinkAssets(GoogleAdsClient client, long customerId)
        {
            AssetServiceClient assetService = client.GetService(Services.V10.AssetService);

            // Creates some sitelink assets.
            SitelinkAsset storeLocatorExtension = new SitelinkAsset()
            {
                Description1 = "Get in touch",
                Description2 = "Find your local store",
                LinkText     = "Store locator"
            };

            SitelinkAsset storeExtension = new SitelinkAsset()
            {
                Description1 = "Buy some stuff",
                Description2 = "It's really good",
                LinkText     = "Store"
            };

            SitelinkAsset storeAdditionalExtension = new SitelinkAsset()
            {
                Description1 = "Even more stuff",
                Description2 = "There's never enough",
                LinkText     = "Store for more"
            };

            // Wraps the sitelinks in an Asset and sets the URLs.
            List <Asset> assets = new List <Asset>()
            {
                new Asset()
                {
                    SitelinkAsset = storeLocatorExtension,
                    FinalUrls     = { "http://example.com/contact/store-finder" },
                    // Optionally sets a different URL for mobile.
                    FinalMobileUrls = { "http://example.com/mobile/contact/store-finder" }
                },
                new Asset()
                {
                    SitelinkAsset = storeExtension,
                    FinalUrls     = { "http://example.com/store" },
                    // Optionally sets a different URL for mobile.
                    FinalMobileUrls = { "http://example.com/mobile/store" }
                },
                new Asset()
                {
                    SitelinkAsset = storeAdditionalExtension,
                    FinalUrls     = { "http://example.com/store/more" },
                    // Optionally sets a different URL for mobile.
                    FinalMobileUrls = { "http://example.com/mobile/store/more" }
                }
            };

            // Creates an operation to add each asset.
            List <AssetOperation> operations = assets.Select(
                asset => new AssetOperation()
            {
                Create = asset,
            }).ToList();

            // Sends the mutate request.
            MutateAssetsResponse response = assetService.MutateAssets(
                customerId.ToString(), operations);

            // Prints some information about the result.

            List <string> resourceNames = response.Results.Select(
                result => result.ResourceName).ToList();

            foreach (string resourceName in resourceNames)
            {
                Console.WriteLine($"Created sitelink asset with resource name '{resourceNames}'.");
            }
            return(resourceNames);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Creates a price asset.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <returns>the resource name of the newly created price asset.</returns>
        private string CreatePriceAsset(GoogleAdsClient client, long customerId)
        {
            PriceAsset priceAsset = new PriceAsset
            {
                Type = PriceExtensionType.Services,
                // Price qualifier is optional.
                PriceQualifier = PriceExtensionPriceQualifier.From,
                LanguageCode   = "en",
                PriceOfferings =
                {
                    CreatePriceOffering(
                        "Scrubs",
                        "Body Scrub, Salt Scrub",
                        "http://www.example.com/scrubs",
                        "http://m.example.com/scrubs",
                        60000000, // 60 USD
                        "USD",
                        PriceExtensionPriceUnit.PerHour
                        ),
                    CreatePriceOffering(
                        "Hair Cuts",
                        "Once a month",
                        "http://www.example.com/haircuts",
                        "http://m.example.com/haircuts",
                        250000000, // 60 USD
                        "USD",
                        PriceExtensionPriceUnit.PerMonth
                        ),
                    CreatePriceOffering(
                        "Skin Care Package",
                        "Four times a month",
                        "http://www.example.com/skincarepackage",
                        null,
                        250000000, // 250 USD
                        "USD",
                        PriceExtensionPriceUnit.PerMonth
                        ),
                },
            };

            Asset asset = new Asset
            {
                Name = "Price Asset #" + ExampleUtilities.GetRandomString(),
                TrackingUrlTemplate = "http://tracker.example.com/?u={lpurl}",
                PriceAsset          = priceAsset,
            };

            AssetOperation operation = new AssetOperation
            {
                Create = asset,
            };

            AssetServiceClient   assetClient = client.GetService(Services.V10.AssetService);
            MutateAssetsResponse response    = assetClient.MutateAssets(customerId.ToString(),
                                                                        new[] { operation });
            string resourceName = response.Results[0].ResourceName;

            Console.WriteLine($"Created price asset with resource name '{resourceName}'.");

            return(resourceName);
        }
Exemplo n.º 19
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>
        // [START upload_image_asset]
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the AssetServiceClient.
            AssetServiceClient assetService =
                client.GetService(Services.V10.AssetService);

            // Creates an image content.
            byte[] imageContent = MediaUtilities.GetAssetDataFromUrl(IMAGE_URL, client.Config);

            // Creates an image asset.
            ImageAsset imageAsset = new ImageAsset()
            {
                Data     = ByteString.CopyFrom(imageContent),
                FileSize = imageContent.Length,
                MimeType = MimeType.ImageJpeg,
                FullSize = new ImageDimension()
                {
                    HeightPixels = 315,
                    WidthPixels  = 600,
                    Url          = IMAGE_URL
                }
            };

            // Creates an asset.
            Asset asset = new Asset()
            {
                // Optional: Provide a unique friendly name to identify your asset.
                // If you specify the name field, then both the asset name and the image being
                // uploaded should be unique, and should not match another ACTIVE asset in this
                // customer account.
                // Name = 'Jupiter Trip #' + ExampleUtilities.GetRandomString(),
                Type       = AssetType.Image,
                ImageAsset = imageAsset,
                // 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 = "Marketing Image"
            };

            // Creates an asset operation.
            AssetOperation operation = new AssetOperation()
            {
                Create = asset
            };

            try
            {
                // Issues a mutate request to add the asset.
                MutateAssetsResponse response =
                    assetService.MutateAssets(customerId.ToString(), new[] { operation });

                // Displays the result.
                Console.WriteLine($"Image asset with resource name: " +
                                  $"'{response.Results.First().ResourceName}' is created.");
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Create a Promotion asset that copies values from the specified extension feed item.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="extensionFeedItem">The extension feed item to be migrated.</param>
        /// <returns>The resource name of the newly created Promotion asset.</returns>
        // [START migrate_promotion_feed_to_asset]
        private string CreatePromotionAssetFromFeed(GoogleAdsClient client, long customerId,
                                                    ExtensionFeedItem extensionFeedItem)
        {
            // Get the Asset Service client.
            AssetServiceClient assetServiceClient = client.GetService(Services.V10.AssetService);

            PromotionFeedItem promotionFeedItem = extensionFeedItem.PromotionFeedItem;

            // Create the Promotion asset.
            Asset asset = new Asset
            {
                // Name field is optional.
                Name           = $"Migrated from feed item #{extensionFeedItem.Id}",
                PromotionAsset = new PromotionAsset
                {
                    PromotionTarget     = promotionFeedItem.PromotionTarget,
                    DiscountModifier    = promotionFeedItem.DiscountModifier,
                    RedemptionStartDate = promotionFeedItem.PromotionStartDate,
                    RedemptionEndDate   = promotionFeedItem.PromotionEndDate,
                    Occasion            = promotionFeedItem.Occasion,
                    LanguageCode        = promotionFeedItem.LanguageCode,
                },
                TrackingUrlTemplate = promotionFeedItem.TrackingUrlTemplate,
                FinalUrlSuffix      = promotionFeedItem.FinalUrlSuffix
            };

            // Either PercentOff or MoneyAmountOff must be set.
            if (promotionFeedItem.PercentOff > 0)
            {
                // Adjust the percent off scale when copying.
                asset.PromotionAsset.PercentOff = promotionFeedItem.PercentOff / 100;
            }
            else
            {
                asset.PromotionAsset.MoneyAmountOff = new Money
                {
                    AmountMicros = promotionFeedItem.MoneyAmountOff.AmountMicros,
                    CurrencyCode = promotionFeedItem.MoneyAmountOff.CurrencyCode
                };
            }

            // Either PromotionCode or OrdersOverAmount must be set.
            if (!string.IsNullOrEmpty(promotionFeedItem.PromotionCode))
            {
                asset.PromotionAsset.PromotionCode = promotionFeedItem.PromotionCode;
            }
            else
            {
                asset.PromotionAsset.OrdersOverAmount = new Money
                {
                    AmountMicros = promotionFeedItem.OrdersOverAmount.AmountMicros,
                    CurrencyCode = promotionFeedItem.OrdersOverAmount.CurrencyCode
                };
            }

            // Set the start and end dates if set in the existing extension.
            if (extensionFeedItem.HasStartDateTime)
            {
                asset.PromotionAsset.StartDate = DateTime.Parse(extensionFeedItem.StartDateTime)
                                                 .ToString("yyyy-MM-dd");
            }

            if (extensionFeedItem.HasEndDateTime)
            {
                asset.PromotionAsset.EndDate = DateTime.Parse(extensionFeedItem.EndDateTime)
                                               .ToString("yyyy-MM-dd");
            }

            asset.PromotionAsset.AdScheduleTargets.Add(extensionFeedItem.AdSchedules);
            asset.FinalUrls.Add(promotionFeedItem.FinalUrls);
            asset.FinalMobileUrls.Add(promotionFeedItem.FinalMobileUrls);
            asset.UrlCustomParameters.Add(promotionFeedItem.UrlCustomParameters);

            // Build an operation to create the Promotion asset.
            AssetOperation operation = new AssetOperation
            {
                Create = asset
            };

            // Issue the request and return the resource name of the new Promotion asset.
            MutateAssetsResponse response = assetServiceClient.MutateAssets(
                customerId.ToString(), new[] { operation });

            Console.WriteLine("Created Promotion asset with resource name " +
                              $"{response.Results.First().ResourceName}");
            return(response.Results.First().ResourceName);
        }