/// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the CreativeService.
            CreativeService creativeService =
                (CreativeService)user.GetService(DfpService.v201705.CreativeService);

            // Set the ID of the advertiser (company) that all creatives will be
            // assigned to.
            long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE"));

            // Create the local custom creative object.
            CustomCreative customCreative = new CustomCreative();

            customCreative.name           = "Custom creative " + GetTimeStamp();
            customCreative.advertiserId   = advertiserId;
            customCreative.destinationUrl = "http://google.com";

            // Set the custom creative image asset.
            CustomCreativeAsset customCreativeAsset = new CustomCreativeAsset();

            customCreativeAsset.macroName = "IMAGE_ASSET";
            CreativeAsset asset = new CreativeAsset();

            asset.fileName       = string.Format("inline{0}.jpg", GetTimeStamp());
            asset.assetByteArray = MediaUtilities.GetAssetDataFromUrl(
                "http://www.google.com/intl/en/adwords/select/images/samples/inline.jpg");
            customCreativeAsset.asset = asset;

            customCreative.customCreativeAssets = new CustomCreativeAsset[] { customCreativeAsset };

            // Set the HTML snippet using the custom creative asset macro.
            customCreative.htmlSnippet = "<a href='%%CLICK_URL_UNESC%%%%DEST_URL%%'>" +
                                         "<img src='%%FILE:" + customCreativeAsset.macroName + "%%'/>" +
                                         "</a><br>Click above for great deals!";

            // Set the creative size.
            Size size = new Size();

            size.width         = 300;
            size.height        = 250;
            size.isAspectRatio = false;

            customCreative.size = size;

            try {
                // Create the custom creative on the server.
                Creative[] createdCreatives = creativeService.createCreatives(
                    new Creative[] { customCreative });

                foreach (Creative createdCreative in createdCreatives)
                {
                    Console.WriteLine("A custom creative with ID \"{0}\", name \"{1}\", and size ({2}, " +
                                      "{3}) was created and can be previewed at {4}", createdCreative.id,
                                      createdCreative.name, createdCreative.size.width, createdCreative.size.height,
                                      createdCreative.previewUrl);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create custom creatives. Exception says \"{0}\"", e.Message);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Uploads the image from the specified <paramref name="url"/>.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="url">The image URL.</param>
        /// <returns>ID of the uploaded image.</returns>
        private static long UploadImageAsset(AdWordsUser user, string url)
        {
            using (AssetService assetService =
                       (AssetService)user.GetService(AdWordsService.v201809.AssetService))
            {
                // Create the image asset.
                ImageAsset imageAsset = new ImageAsset()
                {
                    // Optional: Provide a unique friendly name to identify your asset. If you
                    // specify the assetName 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.
                    // assetName = "Image asset " + ExampleUtilities.GetRandomString(),
                    imageData = MediaUtilities.GetAssetDataFromUrl(url, user.Config),
                };

                // Create the operation.
                AssetOperation operation = new AssetOperation()
                {
                    @operator = Operator.ADD,
                    operand   = imageAsset
                };

                // Create the asset and return the ID.
                return(assetService.mutate(new AssetOperation[]
                {
                    operation
                }).value[0].assetId);
            }
        }
        /// <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 AssetServiceClient.
            AssetServiceClient assetService =
                client.GetService(Services.V6.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
            };

            // 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;
            }
        }
        /// <summary>
        /// Create a test company for running further tests.
        /// </summary>
        /// <returns>A creative for running further tests.</returns>
        public Creative CreateCreative(DfpUser user, long advertiserId)
        {
            CreativeService creativeService = (CreativeService)user.GetService(
                DfpService.v201602.CreativeService);

            // Create creative size.
            Size size = new Size();

            size.width  = 300;
            size.height = 250;

            // Create an image creative.
            ImageCreative imageCreative = new ImageCreative();

            imageCreative.name           = string.Format("Image creative #{0}", GetTimeStamp());
            imageCreative.advertiserId   = advertiserId;
            imageCreative.destinationUrl = "http://www.google.com";
            imageCreative.size           = size;

            // Create image asset.
            CreativeAsset creativeAsset = new CreativeAsset();

            creativeAsset.fileName       = "image.jpg";
            creativeAsset.assetByteArray = MediaUtilities.GetAssetDataFromUrl(
                "http://www.google.com/intl/en/adwords/select/images/samples/inline.jpg");
            creativeAsset.size = size;
            imageCreative.primaryImageAsset = creativeAsset;

            return(creativeService.createCreatives(new Creative[] { imageCreative })[0]);
        }
Beispiel #5
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201411.ReportService);

            // Set the id of the completed report.
            long   reportJobId = long.Parse(_T("INSERT_REPORT_JOB_ID_HERE"));
            String fileName    = _T("INSERT_FILE_PATH_HERE");

            try {
                // Download report data.
                string url            = reportService.getReportDownloadURL(reportJobId, ExportFormat.CSV_EXCEL);
                byte[] gzipReport     = MediaUtilities.GetAssetDataFromUrl(url);
                string reportContents = Encoding.UTF8.GetString(MediaUtilities.DeflateGZipData(gzipReport));

                using (StreamWriter writer = new StreamWriter(fileName)) {
                    writer.Write(reportContents);
                }

                // Display results.
                Console.WriteLine("Report job with id '{0}' was downloaded to '{1}'.", reportJobId,
                                  fileName);
            } catch (Exception ex) {
                Console.WriteLine("Failed to download report. Exception says \"{0}\"", ex.Message);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Adds an image to the Google Ads account.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The client customer ID.</param>
        /// <param name="imageUrl">The URL of the image.</param>
        /// <param name="assetName">The name of the asset.</param>
        /// <returns>The string resource name of the newly uploaded asset.</returns>
        private string uploadAsset(GoogleAdsClient client, long customerId,
                                   string imageUrl, string assetName)
        {
            // Creates the asset service client.
            AssetServiceClient assetServiceClient = client.GetService(Services.V6.AssetService);

            byte[] imageData = MediaUtilities.GetAssetDataFromUrl(imageUrl, client.Config);

            // Creates the image asset.
            Asset asset = new Asset()
            {
                Name       = assetName,
                Type       = AssetType.Image,
                ImageAsset = new ImageAsset()
                {
                    Data = ByteString.CopyFrom(imageData)
                }
            };

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

            // Adds the image asset.
            MutateAssetsResponse response = assetServiceClient.MutateAssets(customerId.ToString()
                                                                            , new[] { operation });
            string imageResourceName = response.Results.First().ResourceName;

            Console.WriteLine($"Created image asset with resource name '{imageResourceName}'.");
            return(imageResourceName);
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the MediaService.
            MediaService mediaService = (MediaService)user.GetService(
                AdWordsService.v201502.MediaService);

            // Create the image.
            Image image = new Image();

            image.data = MediaUtilities.GetAssetDataFromUrl("http://goo.gl/HJM3L");
            image.type = MediaMediaType.IMAGE;

            try {
                // Upload the image.
                Media[] result = mediaService.upload(new Media[] { image });

                // Display the results.
                if (result != null && result.Length > 0)
                {
                    Media newImage = result[0];
                    Dictionary <MediaSize, Dimensions> dimensions =
                        CreateMediaDimensionMap(newImage.dimensions);
                    Console.WriteLine("Image with id '{0}', dimensions '{1}x{2}', and MIME type '{3}'" +
                                      " was uploaded.", newImage.mediaId, dimensions[MediaSize.FULL].width,
                                      dimensions[MediaSize.FULL].height, newImage.mimeType);
                }
                else
                {
                    Console.WriteLine("No images were uploaded.");
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to upload image.", e);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The Dfa user object running the code example.
        /// </param>
        public override void Run(DfaUser user)
        {
            // Create CreateRemoteService instance.
            CreativeRemoteService service = (CreativeRemoteService)user.GetService(
                DfaService.v1_19.CreativeRemoteService);

            long   advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE"));
            string assetName    = _T("INSERT_MOBILE_ASSET_NAME_HERE");
            string pathToFile   = _T("INSERT_PATH_TO_MOBILE_ASSET_HERE");

            // Set mobile asset structure.
            CreativeAsset mobileAsset = new CreativeAsset();

            mobileAsset.forHTMLCreatives = true;
            mobileAsset.advertiserId     = advertiserId;
            mobileAsset.content          = MediaUtilities.GetAssetDataFromUrl(new Uri(pathToFile));
            mobileAsset.name             = assetName;

            try {
                // Create mobile asset.
                CreativeAssetSaveResult result = service.saveCreativeAsset(mobileAsset);

                // Display asset file name.
                Console.WriteLine("Asset was saved with file name of \"{0}\".", result.savedFilename);
            } catch (Exception ex) {
                Console.WriteLine("Failed to create mobile asset. Exception says \"{0}\"", ex.Message);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201311.ReportService);

            // Set the id of the completed report.
            long         reportJobId  = long.Parse(_T("INSERT_REPORT_JOB_ID_HERE"));
            ExportFormat exportFormat = (ExportFormat)Enum.Parse(typeof(ExportFormat),
                                                                 _T("INSERT_EXPORT_FORMAT_HERE"));

            // Set the format of the report (e.g., CSV_DUMP) and download without
            // compression so we can print it.
            ReportDownloadOptions reportDownloadOptions = new ReportDownloadOptions();

            reportDownloadOptions.exportFormat       = exportFormat;
            reportDownloadOptions.useGzipCompression = false;

            try {
                // Download report data.
                string downloadUrl = reportService.getReportDownloadUrlWithOptions(reportJobId,
                                                                                   reportDownloadOptions);
                byte[] rawReport      = MediaUtilities.GetAssetDataFromUrl(downloadUrl);
                string reportContents = Encoding.UTF8.GetString(rawReport);

                // Display results.
                Console.WriteLine("Data for report job with id '{0}\':\n{1}", reportJobId, reportContents);
            } catch (Exception ex) {
                Console.WriteLine("Failed to download report. Exception says \"{0}\"", ex.Message);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (CreativeService creativeService =
                       (CreativeService)user.GetService(DfpService.v201711.CreativeService)) {
                long creativeId = long.Parse(_T("INSERT_IMAGE_CREATIVE_ID_HERE"));

                // Create a statement to get the image creative.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :id")
                                                    .OrderBy("id ASC")
                                                    .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                    .AddValue("id", creativeId);

                try {
                    // Get the creative.
                    CreativePage page = creativeService.getCreativesByStatement(
                        statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        ImageCreative imageCreative = (ImageCreative)page.results[0];
                        // Since we cannot set id to null, we mark it as not specified.
                        imageCreative.idSpecified = false;

                        imageCreative.advertiserId = imageCreative.advertiserId;
                        imageCreative.name         = imageCreative.name + " (Copy #" + GetTimeStamp() + ")";

                        // Create image asset.
                        CreativeAsset creativeAsset = new CreativeAsset();
                        creativeAsset.fileName       = "image.jpg";
                        creativeAsset.assetByteArray = MediaUtilities.GetAssetDataFromUrl(
                            imageCreative.primaryImageAsset.assetUrl);

                        creativeAsset.size = imageCreative.primaryImageAsset.size;
                        imageCreative.primaryImageAsset = creativeAsset;

                        // Create the copied creative.
                        Creative[] creatives = creativeService.createCreatives(
                            new Creative[] { imageCreative });

                        // Display copied creatives.
                        foreach (Creative copiedCreative in creatives)
                        {
                            Console.WriteLine("Image creative with ID \"{0}\", name \"{1}\", and type \"{2}\" " +
                                              "was created and can be previewed at {3}", copiedCreative.id,
                                              copiedCreative.name, copiedCreative.GetType().Name, copiedCreative.previewUrl);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No creatives were copied.");
                    }
                } catch (Exception e) {
                    Console.WriteLine("Failed to copy creatives. Exception says \"{0}\"", e.Message);
                }
            }
        }
 /// <summary>
 /// Uploads an image to the server.
 /// </summary>
 /// <param name="user">The AdWords user.</param>
 /// <param name="url">The URL of image to upload.</param>
 /// <returns>The created image.</returns>
 private static Media UploadImage(AdWordsUser user, string url)
 {
     using (MediaService mediaService = (MediaService)user.GetService(
                AdWordsService.v201802.MediaService)) {
         Image image = new Image();
         image.data = MediaUtilities.GetAssetDataFromUrl(url);
         image.type = MediaMediaType.IMAGE;
         return(mediaService.upload(new Media[] { image })[0]);
     }
 }
        // [END add_smart_display_ad_4]

        /// <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>
        /// <param name="imageName">Name of the image asset.</param>
        /// <returns>The resource name of the asset.</returns>
        // [START add_smart_display_ad_3]
        private static string UploadImageAsset(GoogleAdsClient client, long customerId,
                                               string imageUrl, long width, long height, string imageName)
        {
            // Get the AssetServiceClient.
            AssetServiceClient assetService =
                client.GetService(Services.V10.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,
                Name       = imageName
            };

            // 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);
        }
        // [END add_performance_max_retail_campaign_7]

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

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

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

            return(operations);
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            using (AssetService assetService =
                       (AssetService)user.GetService(AdWordsService.v201809.AssetService))
            {
                // Create the image asset.
                ImageAsset imageAsset = new ImageAsset()
                {
                    // Optional: Provide a unique friendly name to identify your asset. If you
                    // specify the assetName 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.
                    // assetName = "Jupiter Trip " + ExampleUtilities.GetRandomString(),
                    imageData =
                        MediaUtilities.GetAssetDataFromUrl("https://goo.gl/3b9Wfh", user.Config),
                };

                // Create the operation.
                AssetOperation operation = new AssetOperation()
                {
                    @operator = Operator.ADD,
                    operand   = imageAsset
                };

                try
                {
                    // Create the asset.
                    AssetReturnValue result = assetService.mutate(new AssetOperation[]
                    {
                        operation
                    });

                    // Display the results.
                    if (result != null && result.value != null && result.value.Length > 0)
                    {
                        Asset newAsset = result.value[0];

                        Console.WriteLine("Image asset with id = '{0}' and name = {1} was created.",
                                          newAsset.assetId, newAsset.assetName);
                    }
                    else
                    {
                        Console.WriteLine("No image asset was created.");
                    }
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to create image asset.", e);
                }
            }
        }
Beispiel #15
0
        /// <summary>
        /// Uploads an image.
        /// </summary>
        /// <param name="user">The AdWords user for which the image is uploaded.</param>
        /// <param name="url">The image URL.</param>
        /// <returns>The uploaded image.</returns>
        private static long UploadImage(AdWordsUser user, string url)
        {
            using (MediaService mediaService = (MediaService)user.GetService(
                       AdWordsService.v201802.MediaService)) {
                // Create the image.
                Image image = new Image();
                image.data = MediaUtilities.GetAssetDataFromUrl(url, user.Config);
                image.type = MediaMediaType.IMAGE;

                // Upload the image.
                Media[] result = mediaService.upload(new Media[] { image });
                return(result[0].mediaId);
            }
        }
        /// <summary>
        /// Schedules and downloads a report.
        /// </summary>
        /// <param name="loginService">The login service instance.</param>
        /// <param name="reportService">The report service instance.</param>
        /// <param name="userName">The user name to be used for authentication
        /// purposes.</param>
        /// <param name="password">The password to be used for authentication
        /// purposes.</param>
        /// <param name="queryId">The query id to be used for generating reports.
        /// </param>
        /// <param name="filePath">The file path to which the downloaded report
        /// should be saved.</param>
        public void ScheduleAndDownloadReport(LoginRemoteService loginService,
                                              ReportRemoteService reportService, string userName, string password, long queryId,
                                              string filePath)
        {
            // Override the credentials in App.config with the ones the user
            // provided.
            string authToken = loginService.authenticate(userName, password).token;

            reportService.Token.Username = userName;
            reportService.Token.Password = authToken;

            // Create report request and submit it to the server.
            ReportRequest reportRequest = new ReportRequest();

            reportRequest.queryId = queryId;

            try {
                ReportInfo reportInfo = reportService.runDeferredReport(reportRequest);
                long       reportId   = reportInfo.reportId;
                Console.WriteLine("Report with ID '{0}' has been scheduled.", reportId);

                reportRequest.reportId = reportId;

                while (reportInfo.status.name != "COMPLETE")
                {
                    Console.WriteLine("Still waiting for report with ID '{0}', current status is '{1}'.",
                                      reportId, reportInfo.status.name);
                    Console.WriteLine("Waiting 10 minutes before checking on report status.");
                    // Wait 10 minutes.
                    Thread.Sleep(TIME_BETWEEN_CHECKS);
                    reportInfo = reportService.getReport(reportRequest);
                    if (reportInfo.status.name == "ERROR")
                    {
                        throw new Exception("Deferred report failed with errors. Run in the UI to " +
                                            "troubleshoot.");
                    }
                }

                using (FileStream fs = File.OpenWrite(filePath)) {
                    byte[] bytes = MediaUtilities.GetAssetDataFromUrl(reportInfo.url);
                    fs.Write(bytes, 0, bytes.Length);
                }

                Console.WriteLine("Report successfully downloaded to '{0}'.", filePath);
            } catch (Exception ex) {
                Console.WriteLine("Failed to schedule and download report. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
Beispiel #17
0
        /// <summary>
        /// Uploads the image from the specified <paramref name="url"/>.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="url">The image URL.</param>
        /// <returns>ID of the uploaded image.</returns>
        private static long UploadImage(AdWordsUser user, String url)
        {
            using (MediaService mediaService =
                       (MediaService)user.GetService(AdWordsService.v201710.MediaService)) {
                // Create the image.
                Image image = new Image()
                {
                    data = MediaUtilities.GetAssetDataFromUrl(url, user.Config),
                    type = MediaMediaType.IMAGE
                };

                // Upload the image and return the ID.
                return(mediaService.upload(new Media[] { image })[0].mediaId);
            }
        }
        public void TestCreateCreatives()
        {
            // Create an array to store local image creative objects.
            Creative[] imageCreatives = new ImageCreative[2];

            for (int i = 0; i < 2; i++)
            {
                // Create creative size.
                Size size = new Size();
                size.width  = 300;
                size.height = 250;

                // Create an image creative.
                ImageCreative imageCreative = new ImageCreative();
                imageCreative.name           = string.Format("Image creative #{0}", i);
                imageCreative.advertiserId   = advertiserId;
                imageCreative.destinationUrl = "http://www.google.com";
                imageCreative.size           = size;

                // Create image asset.
                CreativeAsset creativeAsset = new CreativeAsset();
                creativeAsset.fileName       = "image.jpg";
                creativeAsset.assetByteArray = MediaUtilities.GetAssetDataFromUrl(
                    "http://www.google.com/intl/en/adwords/select/images/samples/inline.jpg");
                creativeAsset.size = size;
                imageCreative.primaryImageAsset = creativeAsset;

                imageCreatives[i] = imageCreative;
            }

            Creative[] newCreatives = null;

            Assert.DoesNotThrow(delegate() {
                newCreatives = creativeService.createCreatives(imageCreatives);
            });

            Assert.NotNull(newCreatives);
            Assert.AreEqual(newCreatives.Length, 2);
            Assert.NotNull(newCreatives[0]);
            Assert.That(newCreatives[0] is ImageCreative);
            Assert.AreEqual(newCreatives[0].advertiserId, advertiserId);
            Assert.AreEqual(newCreatives[0].name, "Image creative #0");
            Assert.NotNull(newCreatives[1]);
            Assert.That(newCreatives[1] is ImageCreative);
            Assert.AreEqual(newCreatives[1].advertiserId, advertiserId);
            Assert.AreEqual(newCreatives[1].name, "Image creative #1");
        }
Beispiel #19
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            using (MediaService mediaService =
                       (MediaService)user.GetService(AdWordsService.v201809.MediaService))
            {
                try
                {
                    // Create HTML5 media.
                    byte[] html5Zip =
                        MediaUtilities.GetAssetDataFromUrl("https://goo.gl/9Y7qI2", user.Config);
                    // Create a media bundle containing the zip file with all the HTML5 components.
                    Media[] mediaBundle = new Media[]
                    {
                        new MediaBundle()
                        {
                            data = html5Zip,
                            type = MediaMediaType.MEDIA_BUNDLE
                        }
                    };

                    // Upload HTML5 zip.
                    mediaBundle = mediaService.upload(mediaBundle);

                    // Display HTML5 zip.
                    if (mediaBundle != null && mediaBundle.Length > 0)
                    {
                        Media newBundle = mediaBundle[0];
                        Dictionary <MediaSize, Dimensions>
                        dimensions = newBundle.dimensions.ToDict();
                        Console.WriteLine(
                            "HTML5 media with id \"{0}\", dimensions \"{1}x{2}\", and MIME type " +
                            "\"{3}\" was uploaded.", newBundle.mediaId,
                            dimensions[MediaSize.FULL].width, dimensions[MediaSize.FULL].height,
                            newBundle.mimeType);
                    }
                    else
                    {
                        Console.WriteLine("No HTML5 zip was uploaded.");
                    }
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to upload HTML5 zip file.", e);
                }
            }
        }
Beispiel #20
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>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the MediaFileServiceClient.
            MediaFileServiceClient mediaFileService = client.GetService(
                Services.V10.MediaFileService);

            // Creates an HTML5 zip file media bundle content.
            byte[] bundleContent = MediaUtilities.GetAssetDataFromUrl(BUNDLE_URL, client.Config);

            // Creates a media file.
            MediaFile mediaFile = new MediaFile()
            {
                Name        = "Ad Media Bundle",
                Type        = MediaType.MediaBundle,
                MediaBundle = new MediaBundle()
                {
                    Data = ByteString.CopyFrom(bundleContent),
                }
            };

            // Creates a media file operation.
            MediaFileOperation operation = new MediaFileOperation()
            {
                Create = mediaFile
            };

            try
            {
                // Issues a mutate request to add the media file.
                MutateMediaFilesResponse response =
                    mediaFileService.MutateMediaFiles(customerId.ToString(), new[] { operation });

                // Displays the result.
                Console.WriteLine($"The media bundle 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;
            }
        }
Beispiel #21
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>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the MediaFileServiceClient.
            MediaFileServiceClient mediaFileService =
                client.GetService(Services.V10.MediaFileService);

            const string URL = "https://gaagl.page.link/Eit5";

            MediaFile file = new MediaFile()
            {
                Name      = "Ad Image",
                Type      = MediaType.Image,
                SourceUrl = URL,
                Image     = new MediaImage()
                {
                    Data = ByteString.CopyFrom(MediaUtilities.GetAssetDataFromUrl(
                                                   URL, client.Config))
                }
            };
            MediaFileOperation operation = new MediaFileOperation()
            {
                Create = file
            };

            try
            {
                MutateMediaFilesResponse response =
                    mediaFileService.MutateMediaFiles(customerId.ToString(), new[] { operation });
                Console.WriteLine($"Added {response.Results} images:");
                foreach (MutateMediaFileResult result in response.Results)
                {
                    Console.WriteLine(result.ResourceName);
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Beispiel #22
0
        /// <summary>
        /// Schedules and downloads a report.
        /// </summary>
        /// <param name="service">The report service instance.</param>
        /// <param name="queryId">The query id to be used for generating reports.
        /// </param>
        /// <param name="reportFilePath">The file path to which the downloaded report
        /// should be saved.</param>
        private bool ScheduleAndDownloadReport(ReportRemoteService service, long queryId,
                                               string reportFilePath)
        {
            // Create report request and submit it to the server.
            ReportRequest reportRequest = new ReportRequest();

            reportRequest.queryId = queryId;

            ReportInfo reportInfo = service.runDeferredReport(reportRequest);
            long       reportId   = reportInfo.reportId;

            reportRequest.reportId = reportId;

            while (reportInfo.status.name != "COMPLETE")
            {
                Thread.Sleep(TIME_BETWEEN_CHECKS);
                reportInfo = service.getReport(reportRequest);
                if (reportInfo.status.name == "ERROR")
                {
                    throw new Exception("Deferred report failed with errors. Run in the UI to " +
                                        "troubleshoot.");
                }
            }

            FileStream fs = null;

            try {
                fs = File.OpenWrite(reportFilePath);
                byte[] data = MediaUtilities.GetAssetDataFromUrl(reportInfo.url);
                fs.Write(data, 0, data.Length);
                return(true);
            } catch {
                return(false);
            } finally {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The Dfa user object running the code example.
        /// </param>
        public override void Run(DfaUser user)
        {
            // Request the creative service from the service client factory.
            CreativeRemoteService creativeService = (CreativeRemoteService)user.GetService(
                DfaService.v1_20.CreativeRemoteService);

            string assetName      = _T("INSERT_ASSET_NAME_HERE");
            string pathToFile     = _T("INSERT_PATH_TO_FILE_HERE");
            long   creativeId     = long.Parse(_T("INSERT_IN_STREAM_VIDEO_CREATIVE_ID_HERE"));
            string assetToReplace = _T("INSERT_ASSET_TO_REPLACE_HERE");

            // Create the In-Stream creative asset.
            CreativeAsset inStreamVideoAsset = new CreativeAsset();

            inStreamVideoAsset.name    = assetName;
            inStreamVideoAsset.content = MediaUtilities.GetAssetDataFromUrl(
                new Uri(pathToFile).AbsoluteUri);

            // Create an upload request to make this asset a companion ad file for an
            // existing In-Stream video creative.
            InStreamAssetUploadRequest inStreamAssetUploadRequest = new InStreamAssetUploadRequest();

            inStreamAssetUploadRequest.companion     = true;
            inStreamAssetUploadRequest.inStreamAsset = inStreamVideoAsset;
            inStreamAssetUploadRequest.creativeId    = creativeId;

            try {
                // Replace the existing asset with a newly uploaded asset.
                InStreamVideoCreative inStreamVideoCreative =
                    creativeService.replaceInStreamAsset(assetToReplace, inStreamAssetUploadRequest);

                // Display a success message.
                Console.WriteLine("Replaced companion ad asset \"{0}\" in In-Stream video creative "
                                  + "with ID \"{1}\".%n", assetToReplace, inStreamVideoCreative.id);
            } catch (Exception ex) {
                Console.WriteLine("Failed to replace companion ad asset in in-stream video creative. " +
                                  "Exception says \"{0}\"", ex.Message);
            }
        }
        /// <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);
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The Dfa user object running the code example.
        /// </param>
        public override void Run(DfaUser user)
        {
            // Request the creative service from the service client factory.
            CreativeRemoteService creativeService = (CreativeRemoteService)user.GetService(
                DfaService.v1_19.CreativeRemoteService);

            string assetName  = _T("INSERT_ASSET_NAME_HERE");
            string pathToFile = _T("INSERT_PATH_TO_FILE_HERE");
            long   creativeId = long.Parse(_T("INSERT_IN_STREAM_VIDEO_CREATIVE_ID_HERE"));

            // Create the In-Stream video creative asset.
            CreativeAsset inStreamVideoAsset = new CreativeAsset();

            inStreamVideoAsset.name    = assetName;
            inStreamVideoAsset.content = MediaUtilities.GetAssetDataFromUrl(
                new Uri(pathToFile).AbsolutePath);

            // Create an upload request to make this asset a media file for an existing
            // In-Stream creative.
            InStreamAssetUploadRequest inStreamAssetUploadRequest = new InStreamAssetUploadRequest();

            inStreamAssetUploadRequest.mediaFile     = true;
            inStreamAssetUploadRequest.inStreamAsset = inStreamVideoAsset;
            inStreamAssetUploadRequest.creativeId    = creativeId;

            try {
                // Save the media file.
                InStreamVideoCreative inStreamVideoCreative =
                    creativeService.uploadInStreamAsset(inStreamAssetUploadRequest);

                // Display a success message.
                Console.WriteLine("Added a media file to In-Stream video creative with ID \"{0}\".",
                                  inStreamVideoCreative.id);
            } catch (Exception ex) {
                Console.WriteLine("Failed to add a media file to in-stream video creative. " +
                                  "Exception says \"{0}\"", ex.Message);
            }
        }
Beispiel #26
0
        public void TestCreateCreative()
        {
            // Create creative size.
            Size size = new Size();

            size.width  = 300;
            size.height = 250;

            // Create an image creative.
            ImageCreative imageCreative = new ImageCreative();

            imageCreative.name           = string.Format("Image creative #{0}", new TestUtils().GetTimeStamp());
            imageCreative.advertiserId   = advertiserId;
            imageCreative.destinationUrl = "http://www.google.com";
            imageCreative.size           = size;

            // Create image asset.
            CreativeAsset creativeAsset = new CreativeAsset();

            creativeAsset.fileName       = "image.jpg";
            creativeAsset.assetByteArray = MediaUtilities.GetAssetDataFromUrl(
                "http://www.google.com/intl/en/adwords/select/images/samples/inline.jpg");
            creativeAsset.size = size;
            imageCreative.primaryImageAsset = creativeAsset;

            Creative newCreative = null;

            Assert.DoesNotThrow(delegate() {
                newCreative = creativeService.createCreative(imageCreative);
            });

            Assert.NotNull(newCreative);
            Assert.That(newCreative is ImageCreative);
            Assert.AreEqual(newCreative.advertiserId, imageCreative.advertiserId);
            Assert.AreEqual(newCreative.name, imageCreative.name);
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            // Get the CreativeService.
            CreativeService creativeService =
                (CreativeService)user.GetService(DfpService.v201605.CreativeService);

            // Set the ID of the advertiser (company) that the creative will be
            // assigned to.
            long advertiserId = long.Parse(_T("INSERT_ADVERTISER_COMPANY_ID_HERE"));

            // Use the system defined native app install creative template.
            long creativeTemplateId = 10004400L;

            // Create a native app install creative for the Pie Noon app.
            TemplateCreative nativeAppInstallCreative = new TemplateCreative();

            nativeAppInstallCreative.name =
                String.Format("Native creative #{0}", new Random().Next(int.MaxValue));
            nativeAppInstallCreative.advertiserId       = advertiserId;
            nativeAppInstallCreative.creativeTemplateId = creativeTemplateId;
            nativeAppInstallCreative.destinationUrl     =
                "https://play.google.com/store/apps/details?id=com.google.fpl.pie_noon";

            // Use 1x1 as the size for native creatives.
            Size size = new Size();

            size.width                    = 1;
            size.height                   = 1;
            size.isAspectRatio            = false;
            nativeAppInstallCreative.size = size;

            List <BaseCreativeTemplateVariableValue> templateVariables =
                new List <BaseCreativeTemplateVariableValue>();

            // Set the headline.
            templateVariables.Add(new StringCreativeTemplateVariableValue()
            {
                uniqueName = "Headline",
                value      = "Pie Noon"
            });

            // Set the body text.
            templateVariables.Add(new StringCreativeTemplateVariableValue()
            {
                uniqueName = "Body",
                value      = "Try multi-screen mode!"
            });

            // Set the image asset.
            templateVariables.Add(new AssetCreativeTemplateVariableValue()
            {
                uniqueName = "Image",
                asset      = new CreativeAsset()
                {
                    fileName       = String.Format("image{0}.png", this.GetTimeStamp()),
                    assetByteArray = MediaUtilities.GetAssetDataFromUrl("https://lh4.ggpht.com/"
                                                                        + "GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZOPYnTdOQGaSpGSEZflIFs0iw=h300")
                }
            });

            // Set the price.
            templateVariables.Add(new StringCreativeTemplateVariableValue()
            {
                uniqueName = "Price",
                value      = "Free"
            });

            // Set app icon image asset.
            templateVariables.Add(new AssetCreativeTemplateVariableValue()
            {
                uniqueName = "Appicon",
                asset      = new CreativeAsset()
                {
                    fileName       = String.Format("icon{0}.png", this.GetTimeStamp()),
                    assetByteArray = MediaUtilities.GetAssetDataFromUrl("https://lh6.ggpht.com/"
                                                                        + "Jzvjne5CLs6fJ1MHF-XeuUfpABzl0YNMlp4RpHnvPRCIj4--eTDwtyouwUDzVVekXw=w300")
                }
            });

            // Set the call to action text.
            templateVariables.Add(new StringCreativeTemplateVariableValue()
            {
                uniqueName = "Calltoaction",
                value      = "Install"
            });

            // Set the star rating.
            templateVariables.Add(new StringCreativeTemplateVariableValue()
            {
                uniqueName = "Starrating",
                value      = "4"
            });

            // Set the store type.
            templateVariables.Add(new StringCreativeTemplateVariableValue()
            {
                uniqueName = "Store",
                value      = "Google Play"
            });

            // Set the deep link URL.
            templateVariables.Add(new UrlCreativeTemplateVariableValue()
            {
                uniqueName = "DeeplinkclickactionURL",
                value      = "market://details?id=com.google.fpl.pie_noon"
            });

            nativeAppInstallCreative.creativeTemplateVariableValues = templateVariables.ToArray();

            try {
                // Create the native creative on the server.
                Creative[] createdNativeCreatives = creativeService.createCreatives(
                    new Creative[] { nativeAppInstallCreative });

                foreach (Creative createdNativeCreative in createdNativeCreatives)
                {
                    Console.WriteLine("A native creative with ID \"{0}\" and name \"{1}\" " +
                                      "was created and can be previewed at {2}", createdNativeCreative.id,
                                      createdNativeCreative.name, createdNativeCreative.previewUrl);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create creatives. Exception says \"{0}\"", e.Message);
            }
        }
Beispiel #28
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (CreativeService creativeService = user.GetService <CreativeService>())
            {
                // Set the ID of the advertiser (company) that all creatives will be
                // assigned to.
                long advertiserId = long.Parse(_T("INSERT_ADVERTISER_COMPANY_ID_HERE"));

                // Create an array to store local image creative objects.
                Creative[] imageCreatives = new ImageCreative[5];

                for (int i = 0; i < 5; i++)
                {
                    // Create creative size.
                    Size size = new Size();
                    size.width  = 300;
                    size.height = 250;

                    // Create an image creative.
                    ImageCreative imageCreative = new ImageCreative();
                    imageCreative.name           = string.Format("Image creative #{0}", i);
                    imageCreative.advertiserId   = advertiserId;
                    imageCreative.destinationUrl = "http://www.google.com";
                    imageCreative.size           = size;

                    // Create image asset.
                    CreativeAsset creativeAsset = new CreativeAsset();
                    creativeAsset.fileName       = "image.jpg";
                    creativeAsset.assetByteArray =
                        MediaUtilities.GetAssetDataFromUrl("https://goo.gl/3b9Wfh", user.Config);
                    creativeAsset.size = size;
                    imageCreative.primaryImageAsset = creativeAsset;

                    imageCreatives[i] = imageCreative;
                }

                try
                {
                    // Create the image creatives on the server.
                    imageCreatives = creativeService.createCreatives(imageCreatives);

                    if (imageCreatives != null)
                    {
                        foreach (Creative creative in imageCreatives)
                        {
                            // Use "is" operator to determine what type of creative was
                            // returned.
                            if (creative is ImageCreative)
                            {
                                ImageCreative imageCreative = (ImageCreative)creative;
                                Console.WriteLine(
                                    "An image creative with ID ='{0}', name ='{1}' and size = " +
                                    "({2},{3}) was created and can be previewed at: {4}",
                                    imageCreative.id, imageCreative.name, imageCreative.size.width,
                                    imageCreative.size.height, imageCreative.previewUrl);
                            }
                            else
                            {
                                Console.WriteLine(
                                    "A creative with ID ='{0}', name='{1}' and type='{2}' " +
                                    "was created.", creative.id, creative.name,
                                    creative.GetType().Name);
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("No creatives created.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to create creatives. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Beispiel #29
0
 public void TestGetAssetDataFromUrl2()
 {
     byte[] data = MediaUtilities.GetAssetDataFromUrl(fileUri.AbsoluteUri,
                                                      new GoogleAdsConfig());
     Assert.AreEqual(FILE_CONTENTS, Encoding.UTF8.GetString(data));
 }
Beispiel #30
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group to which ads are added.
        /// </param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            using (AdGroupAdService adGroupAdService =
                       (AdGroupAdService)user.GetService(AdWordsService.v201802.AdGroupAdService)) {
                // Create the template ad.
                TemplateAd clickToDownloadAppAd = new TemplateAd();

                clickToDownloadAppAd.name       = "Ad for demo game";
                clickToDownloadAppAd.templateId = 353;
                clickToDownloadAppAd.finalUrls  = new string[] {
                    "http://play.google.com/store/apps/details?id=com.example.demogame"
                };
                clickToDownloadAppAd.displayUrl = "play.google.com";

                // Create the template elements for the ad. You can refer to
                // https://developers.google.com/adwords/api/docs/appendix/templateads
                // for the list of avaliable template fields.
                TemplateElementField headline = new TemplateElementField();
                headline.name      = "headline";
                headline.fieldText = "Enjoy your drive in Mars";
                headline.type      = TemplateElementFieldType.TEXT;

                TemplateElementField description1 = new TemplateElementField();
                description1.name      = "description1";
                description1.fieldText = "Realistic physics simulation";
                description1.type      = TemplateElementFieldType.TEXT;

                TemplateElementField description2 = new TemplateElementField();
                description2.name      = "description2";
                description2.fieldText = "Race against players online";
                description2.type      = TemplateElementFieldType.TEXT;

                TemplateElementField appId = new TemplateElementField();
                appId.name      = "appId";
                appId.fieldText = "com.example.demogame";
                appId.type      = TemplateElementFieldType.TEXT;

                TemplateElementField appStore = new TemplateElementField();
                appStore.name      = "appStore";
                appStore.fieldText = "2";
                appStore.type      = TemplateElementFieldType.ENUM;

                // Optionally specify a landscape image. The image needs to be in a BASE64
                // encoded form. Here we download a demo image and encode it for this ad.
                byte[] imageData = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/9JmyKk");
                Image  image     = new Image();
                image.data = imageData;
                TemplateElementField landscapeImage = new TemplateElementField();
                landscapeImage.name       = "landscapeImage";
                landscapeImage.fieldMedia = image;
                landscapeImage.type       = TemplateElementFieldType.IMAGE;

                TemplateElement adData = new TemplateElement();
                adData.uniqueName = "adData";
                adData.fields     = new TemplateElementField[] { headline, description1, description2, appId,
                                                                 appStore, landscapeImage };

                clickToDownloadAppAd.templateElements = new TemplateElement[] { adData };

                // Create the adgroupad.
                AdGroupAd clickToDownloadAppAdGroupAd = new AdGroupAd();
                clickToDownloadAppAdGroupAd.adGroupId = adGroupId;
                clickToDownloadAppAdGroupAd.ad        = clickToDownloadAppAd;

                // Optional: Set the status.
                clickToDownloadAppAdGroupAd.status = AdGroupAdStatus.PAUSED;

                // Create the operation.
                AdGroupAdOperation operation = new AdGroupAdOperation();
                operation.@operator = Operator.ADD;
                operation.operand   = clickToDownloadAppAdGroupAd;

                try {
                    // Create the ads.
                    AdGroupAdReturnValue retval = adGroupAdService.mutate(
                        new AdGroupAdOperation[] { operation });

                    // Display the results.
                    if (retval != null && retval.value != null)
                    {
                        foreach (AdGroupAd adGroupAd in retval.value)
                        {
                            Console.WriteLine("New click-to-download ad with id = \"{0}\" and url = \"{1}\" " +
                                              "was created.", adGroupAd.ad.id, adGroupAd.ad.finalUrls[0]);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No click-to-download ads were created.");
                    }
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to create click-to-download ad.", e);
                }
            }
        }