Esempio n. 1
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);
                }
            }
        }
Esempio n. 2
0
    /// <summary>
    /// Creates a new mesh
    /// </summary>
    /// <param name="device">The device used to create the mesh</param>
    /// <param name="filename">the file to load</param>
    public void Create(Device device, string filename)
    {
        worldPosition = new WorldPosition();

        GraphicsStream adjacencyBuffer;

        ExtendedMaterial[] Mat;

        this.device = device;
        if (device != null)
        {
            device.DeviceLost  += new System.EventHandler(this.InvalidateDeviceObjects);
            device.Disposing   += new System.EventHandler(this.InvalidateDeviceObjects);
            device.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects);
        }
        filename = MediaUtilities.FindFile(filename);
        // Load the mesh
        systemMemoryMesh = Mesh.FromFile(filename, MeshFlags.SystemMemory, device, out adjacencyBuffer, out Mat);

        Mesh   tempMesh = null;
        string errorString;

        tempMesh = Mesh.Clean(systemMemoryMesh, adjacencyBuffer, adjacencyBuffer, out errorString);
        systemMemoryMesh.Dispose();
        systemMemoryMesh = tempMesh;

        // Optimize the mesh for performance
        MeshFlags flags = MeshFlags.OptimizeCompact | MeshFlags.OptimizeAttrSort | MeshFlags.OptimizeVertexCache;

        systemMemoryMesh.OptimizeInPlace(flags, adjacencyBuffer);
        adjacencyBuffer.Close();
        adjacencyBuffer = null;
        // Setup bounding volumes
        VertexBuffer   vb         = systemMemoryMesh.VertexBuffer;
        GraphicsStream vertexData = vb.Lock(0, 0, LockFlags.ReadOnly);

        boundingSphere.Radius = Geometry.ComputeBoundingSphere(vertexData, systemMemoryMesh.NumberVertices, systemMemoryMesh.VertexFormat, out boundingSphere.CenterPoint);
        vb.Unlock();
        vb.Dispose();

        textures  = new Texture[Mat.Length];
        materials = new Direct3D.Material[Mat.Length];

        for (int i = 0; i < Mat.Length; i++)
        {
            materials[i] = Mat[i].Material3D;
            // Set the ambient color for the material (D3DX does not do this)
            materials[i].Ambient = materials[i].Diffuse;

            if (Mat[i].TextureFilename != null)
            {
                // Create the texture
                textures[i] = TextureLoader.FromFile(device, MediaUtilities.FindFile(Mat[i].TextureFilename));
            }
        }
        RestoreDeviceObjects(device, null);
    }
Esempio n. 3
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (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(
                    "https://goo.gl/3b9Wfh");
                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);
                }
            }
        }
Esempio n. 4
0
 /// <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]);
     }
 }
Esempio n. 5
0
        /// <summary>
        /// Calls the token endpoint to obtain an access token.
        /// </summary>
        /// <param name="body">The request body.</param>
        /// <param name="errorMessage">The error message.</param>
        protected void CallTokenEndpoint(string body)
        {
            WebRequest request = HttpUtilities.BuildRequest(TOKEN_ENDPOINT, "POST", config);

            request.ContentType = "application/x-www-form-urlencoded";

            LogEntry    logEntry = new LogEntry(config, new DefaultDateTimeProvider());
            WebResponse response = null;

            try {
                HttpUtilities.WritePostBodyAndLog(request, body, logEntry, REQUEST_HEADERS_TO_MASK);
                response = request.GetResponse();

                string contents = MediaUtilities.GetStreamContentsAsString(response.GetResponseStream());
                logEntry.LogResponse(response, false, contents, RESPONSE_FIELDS_TO_MASK,
                                     new JsonBodyFormatter());
                logEntry.Flush();

                Dictionary <string, string> values = ParseJsonObjectResponse(contents);
                if (values.ContainsKey("access_token"))
                {
                    this.AccessToken = values["access_token"];
                }
                if (values.ContainsKey("refresh_token"))
                {
                    this.RefreshToken = values["refresh_token"];
                }
                if (values.ContainsKey("token_type"))
                {
                    this.tokenType = values["token_type"];
                }
                if (values.ContainsKey("expires_in"))
                {
                    this.expiresIn = int.Parse(values["expires_in"]);
                }
                this.updatedOn = DateTime.UtcNow;

                if (this.OnOAuthTokensObtained != null)
                {
                    this.OnOAuthTokensObtained(this);
                }
            } catch (WebException e) {
                string contents = HttpUtilities.GetErrorResponseBody(e);
                logEntry.LogResponse(response, true, contents, RESPONSE_FIELDS_TO_MASK,
                                     new JsonBodyFormatter());
                logEntry.Flush();

                throw new ApplicationException(contents, e);
            } finally {
                if (response != null)
                {
                    response.Close();
                }
            }
        }
 public HttpContent AudioContent(FileInfo audio, long start, long end)
 {
     return(new PushStreamContent((outputStream, httpContent, transpContext)
                                  =>
     {
         using (outputStream) // copy file stream vào outputstream theo range trong header
             using (Stream inputStream = audio.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
                 MediaUtilities.CreatePartialContent(inputStream, outputStream, start, end);
         //inputStream.CopyTo(outputStream, MediaUtilities.BufferSize);
     }, MediaUtilities.GetMimeType(audio.Extension)));
 }
        // [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);
        }
        /// <summary>
        /// Gets the response text from a web response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <returns>The web response contents.</returns>
        protected static string GetResponseText(WebResponse response)
        {
            if (response == null)
            {
                return(String.Empty);
            }
            MemoryStream memStream = new MemoryStream();

            MediaUtilities.CopyStream(response.GetResponseStream(), memStream);
            return(Encoding.UTF8.GetString(memStream.ToArray()));
        }
        // [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);
        }
Esempio n. 10
0
        /// <summary>
        /// Downloads a report to stream.
        /// </summary>
        /// <param name="downloadUrl">The download url.</param>
        /// <param name="postBody">The POST body.</param>
        private ReportResponse DownloadReport(string downloadUrl, string postBody)
        {
            AdWordsErrorHandler errorHandler = new AdWordsErrorHandler(this.User as AdWordsUser);

            while (true)
            {
                WebResponse    response = null;
                HttpWebRequest request  = BuildRequest(downloadUrl, postBody);

                LogEntry logEntry = new LogEntry(User.Config, new DefaultDateTimeProvider());

                logEntry.LogRequest(request, postBody, HEADERS_TO_MASK);

                try {
                    response = request.GetResponse();

                    logEntry.LogResponse(response, false, "Response truncated.");
                    logEntry.Flush();
                    return(new ReportResponse(response));
                } catch (WebException e) {
                    string    contents         = "";
                    Exception reportsException = null;

                    using (response = e.Response) {
                        try {
                            contents = MediaUtilities.GetStreamContentsAsString(
                                response.GetResponseStream());
                        } catch {
                            contents = e.Message;
                        }

                        logEntry.LogResponse(response, true, contents);
                        logEntry.Flush();

                        reportsException = ParseException(e, contents);

                        if (AdWordsErrorHandler.IsOAuthTokenExpiredError(reportsException))
                        {
                            reportsException = new AdWordsCredentialsExpiredException(
                                request.Headers["Authorization"]);
                        }
                    }
                    if (errorHandler.ShouldRetry(reportsException))
                    {
                        errorHandler.PrepareForRetry(reportsException);
                    }
                    else
                    {
                        throw reportsException;
                    }
                }
            }
        }
        /// <summary>
        /// Downloads a report to stream.
        /// </summary>
        /// <param name="downloadUrl">The download url.</param>
        /// <param name="returnMoneyInMicros">True if money values are returned
        /// in micros.</param>
        /// <param name="postBody">The POST body.</param>
        /// <param name="outputStream">The stream to which report is downloaded.
        /// </param>
        private void DownloadReportToStream(string downloadUrl, bool?returnMoneyInMicros,
                                            string postBody, Stream outputStream)
        {
            AdWordsErrorHandler errorHandler = new AdWordsErrorHandler(user);

            while (true)
            {
                WebResponse    response = null;
                HttpWebRequest request  = BuildRequest(downloadUrl, returnMoneyInMicros, postBody);
                try {
                    response = request.GetResponse();
                    MediaUtilities.CopyStream(response.GetResponseStream(), outputStream);
                    return;
                } catch (WebException ex) {
                    Exception reportsException = null;

                    try {
                        response = ex.Response;

                        if (response != null)
                        {
                            MemoryStream memStream = new MemoryStream();
                            MediaUtilities.CopyStream(response.GetResponseStream(), memStream);
                            String exceptionBody = Encoding.UTF8.GetString(memStream.ToArray());
                            reportsException = ParseException(exceptionBody);
                        }

                        if (AdWordsErrorHandler.IsOAuthTokenExpiredError(reportsException))
                        {
                            reportsException = new AdWordsCredentialsExpiredException(
                                request.Headers["Authorization"]);
                        }
                    } catch (Exception) {
                        reportsException = ex;
                    }
                    if (errorHandler.ShouldRetry(reportsException))
                    {
                        errorHandler.PrepareForRetry(reportsException);
                    }
                    else
                    {
                        throw reportsException;
                    }
                } finally {
                    if (response != null)
                    {
                        response.Close();
                    }
                }
            }
        }
        /// <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);
                }
            }
        }
Esempio n. 13
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);
            }
        }
Esempio n. 14
0
        /// <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);
            }
        }
Esempio n. 15
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);
            }
        }
        /// <summary>
        /// Downloads the report to memory and closes the underlying stream.
        /// </summary>
        /// <exception cref="AdsReportsException">If there was an error downloading the report.
        /// </exception>
        public byte[] Download()
        {
            this.EnsureStreamIsOpen();

            try {
                MemoryStream memStream = new MemoryStream();
                MediaUtilities.CopyStream(this.Stream, memStream);
                this.contents = memStream.ToArray();
                this.CloseWebResponse();
            } catch (Exception e) {
                throw new AdsReportsException("Failed to download report. See inner exception " +
                                              "for more details.", e);
            }

            return(this.contents);
        }
        /// <summary>
        /// Saves the report to a specified path and closes the underlying stream.
        /// </summary>
        /// <param name="path">The path to which report is saved.</param>
        /// <exception cref="AdsReportsException">If there was an error saving the report.</exception>
        public void Save(string path)
        {
            this.EnsureStreamIsOpen();

            try {
                using (FileStream fileStream = File.OpenWrite(path)) {
                    fileStream.SetLength(0);
                    MediaUtilities.CopyStream(this.Stream, fileStream);
                    this.CloseWebResponse();
                }
                this.Path = path;
            } catch (Exception e) {
                throw new AdsReportsException("Failed to save report. See inner exception " +
                                              "for more details.", e);
            }
        }
        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");
        }
Esempio n. 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);
                }
            }
        }
Esempio n. 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;
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Revokes the refresh token.
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown if one of the following
        /// OAuth2 parameters are empty: RefreshToken.</exception>
        public void RevokeRefreshToken()
        {
            // Mark the usage.
            featureUsageRegistry.MarkUsage(FEATURE_ID);;

            ValidateOAuth2Parameter("RefreshToken", RefreshToken);

            string url = string.Format("{0}?token={1}", REVOKE_ENDPOINT, RefreshToken);

            WebRequest request = HttpUtilities.BuildRequest(url, "GET", config);

            LogEntry logEntry = new LogEntry(this.Config, new DefaultDateTimeProvider());

            logEntry.LogRequest(request, "", new HashSet <string>());

            WebResponse response = null;

            try {
                response = request.GetResponse();

                string contents = MediaUtilities.GetStreamContentsAsString(response.GetResponseStream());
                logEntry.LogResponse(response, false, contents);
                logEntry.Flush();
            } catch (WebException e) {
                string contents = "";
                response = e.Response;

                try {
                    contents = MediaUtilities.GetStreamContentsAsString(response.GetResponseStream());
                } catch {
                    contents = e.Message;
                }

                logEntry.LogResponse(response, true, contents);
                logEntry.Flush();

                throw new AdsOAuthException("Failed to revoke refresh token.\n" + contents, e);
            } finally {
                if (response != null)
                {
                    response.Close();
                }
            }
        }
Esempio n. 22
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;
            }
        }
Esempio n. 23
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.v201806.MediaService))
            {
                // Create the image.
                Image image = new Image
                {
                    data = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/3b9Wfh", user.Config),
                    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 = newImage.dimensions.ToDict();
                        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);
                }
            }
        }
Esempio n. 24
0
    void CreateSoundBuffers()
    {
        AddBuffer(MediaUtilities.FindFile("hypercharge.wav"), Sounds.ShipHyper, false);
        AddBuffer(MediaUtilities.FindFile("sci fi bass.wav"), Sounds.ShipAppear, false);
        AddBuffer(MediaUtilities.FindFile("laser2.wav"), Sounds.ShipFire, false);
        AddBuffer(MediaUtilities.FindFile("explode.wav"), Sounds.ShipExplode, false);

        AddBuffer(MediaUtilities.FindFile("engine.wav"), Sounds.ShipThrust, true, VolumeEngine);
        AddBuffer(MediaUtilities.FindFile("laser2_other.wav"), Sounds.OtherShipFire, false, VolumeOtherShot);
        AddBuffer(MediaUtilities.FindFile("explode_other.wav"), Sounds.OtherShipExplode, false);
        AddBuffer(MediaUtilities.FindFile("engine_other.wav"), Sounds.OtherShipThrust, true, VolumeEngine);

        AddBuffer(MediaUtilities.FindFile("sci fi bass.wav"), Sounds.OtherShipAppear, false);
        AddBuffer(MediaUtilities.FindFile("haha.wav"), Sounds.Taunt, false, VolumeHaHa);

        AddBuffer(MediaUtilities.FindFile("dude_quest1.wav"), Sounds.Dude1, false);
        AddBuffer(MediaUtilities.FindFile("dude_quest2.wav"), Sounds.Dude2, false);
        AddBuffer(MediaUtilities.FindFile("dude_quest3.wav"), Sounds.Dude3, false);
        AddBuffer(MediaUtilities.FindFile("dude_quest4.wav"), Sounds.Dude4, false);
        AddBuffer(MediaUtilities.FindFile("dude_quest5.wav"), Sounds.Dude5, false);
    }
Esempio n. 25
0
 public Ship(Device device, GameClass gameClass, HullColors hullColor)
 {
     this.device = device;
     this.game   = gameClass;
     shots       = new Shots(device);
     if (hullColor == HullColors.White)
     {
         shipMesh         = new PositionedMesh(device, "WhiteShip.x");
         startingPosition = new Vector3(10, 0, 10);
     }
     else
     {
         shipMesh         = new PositionedMesh(device, "RedShip.x");
         startingPosition = new Vector3(-50, 0, -150);
     }
     vaporTrail = new ParticleEffects(device);
     vaporTrail.ParticleTexture = TextureLoader.FromFile(device,
                                                         MediaUtilities.FindFile("particle-blue.bmp"));
     shockWave = new Shockwave(device);
     SetRandomPosition(true);
 }
Esempio n. 26
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);
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Downloads the batch job results from a specified URL.
        /// </summary>
        /// <param name="url">The download URL from a batch job.</param>
        /// <returns>The results from the batch job.</returns>
        protected string DownloadResults(string url)
        {
            // Mark the usage.
            featureUsageRegistry.MarkUsage(FEATURE_ID);

            BulkJobErrorHandler errorHandler = new BulkJobErrorHandler(user);

            while (true)
            {
                WebRequest  request  = HttpUtilities.BuildRequest(url, "GET", user.Config);
                WebResponse response = null;

                LogEntry logEntry = new LogEntry(User.Config, new DefaultDateTimeProvider());
                logEntry.LogRequest(GenerateRequestInfo(request, ""), HEADERS_TO_MASK);

                try
                {
                    response = request.GetResponse();
                    string contents =
                        MediaUtilities.GetStreamContentsAsString(response.GetResponseStream());

                    logEntry.LogResponse(GenerateResponseInfo(response, contents, ""));
                    logEntry.Flush();

                    return(contents);
                }
                catch (WebException e)
                {
                    HandleCloudException(errorHandler, logEntry, e);
                }
                finally
                {
                    if (response != null)
                    {
                        response.Close();
                    }
                }
            }
        }
        /// <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);
        }
Esempio n. 30
0
        /// <summary>
        /// Generates a resumable upload URL for a job. This method should be used prior
        /// to calling the Upload() method when using API version >=v201601.
        /// </summary>
        /// <returns>The resumable upload URL.</returns>
        /// <param name="url">The temporary upload URL from BatchJobService.</param>
        public string GetResumableUploadUrl(string url)
        {
            WebRequest request = HttpUtilities.BuildRequest(url, "POST", user.Config);

            request.ContentType   = "application/xml";
            request.ContentLength = 0;
            request.Headers["x-goog-resumable"] = "start";

            WebResponse response = null;

            LogEntry logEntry = new LogEntry(User.Config, new DefaultDateTimeProvider());

            logEntry.LogRequest(request, "", HEADERS_TO_MASK);

            try {
                response = request.GetResponse();
                string contents = MediaUtilities.GetStreamContentsAsString(
                    response.GetResponseStream());
                logEntry.LogResponse(response, false, contents);
                logEntry.Flush();
                return(response.Headers["Location"]);
            } catch (WebException e) {
                response = e.Response;
                string contents = "";
                if (response != null)
                {
                    contents = MediaUtilities.GetStreamContentsAsString(
                        response.GetResponseStream());
                }
                logEntry.LogResponse(response, false, contents);
                logEntry.Flush();
                throw ParseException(e, contents);
            } finally {
                if (response != null)
                {
                    response.Close();
                }
            }
        }