/// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201602.ReportService);

            // Set the file path where the report will be saved.
            String filePath = _T("INSERT_FILE_PATH_HERE");

            // Create report job.
            ReportJob reportJob = new ReportJob();

            reportJob.reportQuery            = new ReportQuery();
            reportJob.reportQuery.dimensions = new Dimension[] { Dimension.SALESPERSON_ID,
                                                                 Dimension.SALESPERSON_NAME };
            reportJob.reportQuery.columns = new Column[] {
                Column.AD_SERVER_IMPRESSIONS,
                Column.AD_SERVER_CPM_AND_CPC_REVENUE,
                Column.AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM
            };
            reportJob.reportQuery.dateRangeType = DateRangeType.LAST_MONTH;

            try {
                // Run report.
                reportJob = reportService.runReportJob(reportJob);

                ReportUtilities reportUtilities = new ReportUtilities(reportService, reportJob.id);

                // Set download options.
                ReportDownloadOptions options = new ReportDownloadOptions();
                options.exportFormat                  = ExportFormat.CSV_DUMP;
                options.useGzipCompression            = true;
                reportUtilities.reportDownloadOptions = options;

                // Download the report.
                using (ReportResponse reportResponse = reportUtilities.GetResponse()) {
                    reportResponse.Save(filePath);
                }
                Console.WriteLine("Report saved to \"{0}\".", filePath);
            } catch (Exception e) {
                Console.WriteLine("Failed to run sales report. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="fileName">The file to which the report is downloaded.
        /// </param>
        public void Run(AdWordsUser user, string fileName)
        {
            string query = "SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, Impressions, " +
                           "Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT WHERE Status IN [ENABLED, PAUSED] " +
                           "DURING LAST_7_DAYS";

            string filePath = ExampleUtilities.GetHomeDir() + Path.DirectorySeparatorChar + fileName;

            try {
                ReportUtilities utilities = new ReportUtilities(user, "v201710", query,
                                                                DownloadFormat.GZIPPED_CSV.ToString());
                using (ReportResponse response = utilities.GetResponse()) {
                    response.Save(filePath);
                }
                Console.WriteLine("Report was downloaded to '{0}'.", filePath);
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to download report.", e);
            }
        }
        private string DownloadReport(ReportDefinition definition)
        {
            try
            {
                // xml is more easily consumed for bulk insert than csv
                // additionally this application is expecting GZipped XML format
                definition.downloadFormat = DownloadFormat.GZIPPED_XML;
                // the specific date is always provided and the range is for only that date
                definition.dateRangeType = ReportDefinitionDateRangeType.CUSTOM_DATE;
                var dateString = this._rptdDate.ToString("yyyyMMdd");
                definition.selector.dateRange = new DateRange()
                {
                    min = dateString,
                    max = dateString
                };

                // temp folder to hold compressed download
                var filePath = BuildTempFileName();

                ResetRetryCount();

                var utilities = new ReportUtilities(this._user, "v201609", definition);

                // todo: handle throttling
                SetReportStage(ReportStage.ReportRequested);
                using (var reportResponse = utilities.GetResponse())
                {
                    reportResponse.Save(filePath); // save file to temp dir
                }
                SetReportStage(ReportStage.Downloaded);

                // decompress it to disk for reading later, delete original file
                var decompressedFilePath = Utilities.ExtractGZipFile(new FileInfo(filePath), "xml", this._deleteDownloadedReportOnCompletion);
                SetReportStage(ReportStage.Decompressed);

                return(decompressedFilePath);
            }
            catch (Exception ex)
            {
                throw new System.ApplicationException("Failed to download report.", ex);
            }
        }
        /// <summary>
        /// Gets the seed keywords from a Search Query Report.
        /// </summary>
        /// <param name="user">The user for which reports are run.</param>
        /// <param name="campaignId">ID of the campaign for which we are generating
        ///  keyword ideas.</param>
        /// <returns>A list of seed keywords from SQR, to be used for getting
        /// further keyword ideas.</returns>
        private List<SeedKeyword> GetSeedKeywordsFromQueryReport(AdWordsUser user, long campaignId)
        {
            string query = string.Format("Select Query, MatchTypeWithVariant, Clicks, Impressions " +
              "from SEARCH_QUERY_PERFORMANCE_REPORT where CampaignId = {0} during LAST_MONTH",
              campaignId);

              AdWordsAppConfig config = (AdWordsAppConfig) user.Config;
              config.SkipReportHeader = true;
              config.SkipReportSummary = true;

              ReportUtilities utilities = new ReportUtilities(user, query, DownloadFormat.CSV.ToString());
              ReportResponse response = utilities.GetResponse();

              List<SeedKeyword> retval = new List<SeedKeyword>();

              using (response) {
            byte[] data = response.Download();
            string report = Encoding.UTF8.GetString(data);

            CsvFile csvFile = new CsvFile();
            csvFile.ReadFromString(report, true);

            foreach (string[] row in csvFile.Records) {
              row[1] = row[1].Replace("(close variant)", "").Trim();
              SeedKeyword sqrKeyword = new SeedKeyword() {
            Keyword = new LocalKeyword() {
              Text = row[0],
              MatchType = (KeywordMatchType) Enum.Parse(typeof(KeywordMatchType), row[1], true)
            },
            Stat = new Stat() {
              Clicks = long.Parse(row[2]),
              Impressions = long.Parse(row[3])
            },
            Source = GetNewKeywords.Source.SQR
              };
              retval.Add(sqrKeyword);
            }
              }

              LimitResults(retval, Settings.SQR_MAX_RESULTS);
              return retval;
        }
Example #5
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201611.ReportService);

            // Set the file path where the report will be saved.
            String filePath = _T("INSERT_FILE_PATH_HERE");

            // Create report job.
            ReportJob reportJob = new ReportJob();

            // Create report query.
            ReportQuery reportQuery = new ReportQuery();

            reportQuery.dateRangeType = DateRangeType.REACH_LIFETIME;
            reportQuery.dimensions    = new Dimension[] { Dimension.LINE_ITEM_ID, Dimension.LINE_ITEM_NAME };
            reportQuery.columns       = new Column[] { Column.REACH_FREQUENCY, Column.REACH_AVERAGE_REVENUE,
                                                       Column.REACH };
            reportJob.reportQuery = reportQuery;

            try {
                // Run report.
                reportJob = reportService.runReportJob(reportJob);

                ReportUtilities reportUtilities = new ReportUtilities(reportService, reportJob.id);

                // Set download options.
                ReportDownloadOptions options = new ReportDownloadOptions();
                options.exportFormat                  = ExportFormat.CSV_DUMP;
                options.useGzipCompression            = true;
                reportUtilities.reportDownloadOptions = options;

                // Download the report.
                using (ReportResponse reportResponse = reportUtilities.GetResponse()) {
                    reportResponse.Save(filePath);
                }
                Console.WriteLine("Report saved to \"{0}\".", filePath);
            } catch (Exception e) {
                Console.WriteLine("Failed to run delivery report. Exception says \"{0}\"",
                                  e.Message);
            }
        }
Example #6
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Create the query.
            String query = "SELECT Id, AdNetworkType1, Impressions FROM CRITERIA_PERFORMANCE_REPORT " +
                           "WHERE Status IN [ENABLED, PAUSED] DURING LAST_7_DAYS";

            ReportUtilities reportUtilities = new ReportUtilities(user, "v201705", query,
                                                                  DownloadFormat.GZIPPED_XML.ToString());

            Dictionary <string, long> impressionsByAdNetworkType1 = new Dictionary <string, long>();

            try {
                using (ReportResponse response = reportUtilities.GetResponse()) {
                    using (GZipStream gzipStream = new GZipStream(response.Stream,
                                                                  CompressionMode.Decompress)) {
                        using (XmlTextReader reader = new XmlTextReader(gzipStream)) {
                            while (reader.Read())
                            {
                                switch (reader.NodeType)
                                {
                                case XmlNodeType.Element: // The node is an Element.
                                    if (reader.Name == "row")
                                    {
                                        ParseRow(impressionsByAdNetworkType1, reader);
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }

                Console.WriteLine("Network, Impressions");
                foreach (string network in impressionsByAdNetworkType1.Keys)
                {
                    Console.WriteLine("{0}, {1}", network, impressionsByAdNetworkType1[network]);
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to download report.", e);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="fileName">The file to which the report is downloaded.
        /// </param>
        public void Run(AdWordsUser user, string fileName)
        {
            ReportDefinition definition = new ReportDefinition();

            definition.reportName     = "Last 7 days CRITERIA_PERFORMANCE_REPORT";
            definition.reportType     = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT;
            definition.downloadFormat = DownloadFormat.GZIPPED_CSV;
            definition.dateRangeType  = ReportDefinitionDateRangeType.LAST_7_DAYS;

            // Create selector.
            Selector selector = new Selector();

            selector.fields = new string[] { "CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria",
                                             "FinalUrls", "Clicks", "Impressions", "Cost" };

            Predicate predicate = new Predicate();

            predicate.field     = "Status";
            predicate.@operator = PredicateOperator.IN;
            predicate.values    = new string[] { "ENABLED", "PAUSED" };
            selector.predicates = new Predicate[] { predicate };

            definition.selector = selector;

            // Optional: Include zero impression rows.
            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            config.IncludeZeroImpressions = true;

            string filePath = ExampleUtilities.GetHomeDir() + Path.DirectorySeparatorChar + fileName;

            try {
                ReportUtilities utilities = new ReportUtilities(user, "v201506", definition);
                using (ReportResponse response = utilities.GetResponse()) {
                    response.Save(filePath);
                }
                Console.WriteLine("Report was downloaded to '{0}'.", filePath);
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to download report.", ex);
            }
        }
Example #8
0
        /// <summary>
        /// Downloads the campaign performance report.
        /// </summary>
        /// <param name="user">The user for which the report is run..</param>
        /// <param name="startDate">The start date in yyyyMMdd format.</param>
        /// <param name="endDate">The end date in yyyyMMdd format.</param>
        /// <returns>The campaign performance report, as a CSV file.</returns>
        private CsvFile DownloadCampaignPerformanceReport(AdWordsUser user, string startDate,
                                                          string endDate)
        {
            string query = string.Format("Select {0} from CAMPAIGN_PERFORMANCE_REPORT DURING {1}, {2}",
                                         string.Join(", ", CAMPAIGN_PERFORMANCE_COLUMNS), startDate, endDate);

            AdWordsAppConfig appConfig = user.Config as AdWordsAppConfig;

            appConfig.SkipReportHeader  = true;
            appConfig.SkipReportSummary = true;

            ReportUtilities reportUtilities = new ReportUtilities(user, query,
                                                                  DownloadFormat.CSV.ToString());

            using (ReportResponse response = reportUtilities.GetResponse()) {
                string  reportContents = Encoding.UTF8.GetString(response.Download());
                CsvFile csvFile        = new CsvFile();
                csvFile.ReadFromString(reportContents, true);
                return(csvFile);
            }
        }
        /// <summary>
        /// Handles the Click event of the btnDownloadReport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing
        /// the event data.</param>
        protected void OnDownloadReportButtonClick(object sender, EventArgs e)
        {
            ConfigureUserForOAuth();
            ReportDefinition definition = new ReportDefinition();

            definition.reportName     = "Last 7 days CRITERIA_PERFORMANCE_REPORT";
            definition.reportType     = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT;
            definition.downloadFormat = DownloadFormat.GZIPPED_CSV;
            definition.dateRangeType  = ReportDefinitionDateRangeType.LAST_7_DAYS;

            // Create selector.
            Selector selector = new Selector();

            selector.fields = new string[] { "CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria",
                                             "CriteriaDestinationUrl", "Clicks", "Impressions", "Cost" };

            Predicate predicate = new Predicate();

            predicate.field     = "Status";
            predicate.@operator = PredicateOperator.IN;
            predicate.values    = new string[] { "ACTIVE", "PAUSED" };
            selector.predicates = new Predicate[] { predicate };

            definition.selector = selector;
            definition.includeZeroImpressions = true;

            string filePath = Path.GetTempFileName();

            try {
                ReportUtilities utilities = new ReportUtilities(user, "v201406", definition);
                using (ReportResponse response = utilities.GetResponse()) {
                    response.Save(filePath);
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to download report.", ex);
            }
            Response.AddHeader("content-disposition", "attachment;filename=report.gzip");
            Response.WriteFile(filePath);
            Response.End();
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="fileName">The file to which the report is downloaded.
        /// </param>
        public void Run(AdWordsUser user, string fileName)
        {
            ReportDefinition definition = new ReportDefinition()
            {
                reportName     = "Last 7 days CRITERIA_PERFORMANCE_REPORT",
                reportType     = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT,
                downloadFormat = DownloadFormat.GZIPPED_CSV,
                dateRangeType  = ReportDefinitionDateRangeType.LAST_7_DAYS,

                selector = new Selector()
                {
                    fields = new string[] { "CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria",
                                            "FinalUrls", "Clicks", "Impressions", "Cost" },
                    predicates = new Predicate[] {
                        Predicate.In("Status", new string[] { "ENABLED", "PAUSED" })
                    }
                },
            };

            // Optional: Include zero impression rows.
            (user.Config as AdWordsAppConfig).IncludeZeroImpressions = true;

            // Optional: You can also skip the report headers, column headers and
            // report summary etc. to make the report parsing simpler.
            // (user.Config as AdWordsAppConfig).SkipColumnHeader = true;
            // (user.Config as AdWordsAppConfig).SkipReportHeader = true;
            // (user.Config as AdWordsAppConfig).SkipReportSummary = true;

            string filePath = ExampleUtilities.GetHomeDir() + Path.DirectorySeparatorChar + fileName;

            try {
                ReportUtilities utilities = new ReportUtilities(user, "v201609", definition);
                using (ReportResponse response = utilities.GetResponse()) {
                    response.Save(filePath);
                }
                Console.WriteLine("Report was downloaded to '{0}'.", filePath);
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to download report.", e);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Retreiving the raw values of enum-type fields instead of display values
            (user.Config as AdWordsAppConfig).UseRawEnumValues = true;

            // Create the query.
            string query =
                "SELECT AccountCurrencyCode, AccountDescriptiveName FROM FINAL_URL_REPORT " +
                "DURING LAST_7_DAYS";

            ReportUtilities reportUtilities = new ReportUtilities(user, "v201806", query,
                                                                  DownloadFormat.GZIPPED_XML.ToString());

            try
            {
                using (ReportResponse response = reportUtilities.GetResponse())
                {
                    using (GZipStream gzipStream =
                               new GZipStream(response.Stream, CompressionMode.Decompress))
                    {
                        // Create the report object using the stream.
                        using (var report =
                                   new AwReport <FinalUrlReportReportRow>(new AwXmlTextReader(gzipStream),
                                                                          "Example"))
                        {
                            // Print the contents of each row object.
                            while (report.MoveNext())
                            {
                                Console.WriteLine(report.Current.accountCurrencyCode + " " +
                                                  report.Current.accountDescriptiveName);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new System.ApplicationException("Failed to download and parse report.", e);
            }
        }
Example #12
0
        /// <summary>
        /// Handles the Click event of the btnDownloadReport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing
        /// the event data.</param>
        protected void OnDownloadReportButtonClick(object sender, EventArgs eventArgs)
        {
            ConfigureUserForOAuth();
            ReportDefinition definition = new ReportDefinition()
            {
                reportName     = "Last 7 days CRITERIA_PERFORMANCE_REPORT",
                reportType     = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT,
                downloadFormat = DownloadFormat.GZIPPED_CSV,
                dateRangeType  = ReportDefinitionDateRangeType.LAST_7_DAYS,

                selector = new Selector()
                {
                    fields = new string[] { "CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria",
                                            "FinalUrls", "Clicks", "Impressions", "Cost" },
                    predicates = new Predicate[] {
                        Predicate.In("Status", new string[] { "ACTIVE", "PAUSED" })
                    }
                }
            };

            // Optional: Include zero impression rows.
            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            config.IncludeZeroImpressions = true;

            string filePath = Path.GetTempFileName();

            try {
                ReportUtilities utilities = new ReportUtilities(user, "v201506", definition);
                using (ReportResponse response = utilities.GetResponse()) {
                    response.Save(filePath);
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to download report.", e);
            }
            Response.AddHeader("content-disposition", "attachment;filename=report.gzip");
            Response.WriteFile(filePath);
            Response.End();
        }
            /// <summary>
            /// Processes the customer.
            /// </summary>
            /// <param name="user">The AdWords user.</param>
            /// <param name="customerId">The customer ID.</param>
            /// <param name="query">The report query.</param>
            private void ProcessCustomer(AdWordsUser user, long customerId, string query)
            {
                // Set the customer ID to the current customer.
                this.Config.ClientCustomerId = customerId.ToString();

                string downloadFile = string.Format("{0}{1}adgroup_{2:D10}.gz", this.DownloadFolder,
                                                    Path.DirectorySeparatorChar, customerId);

                // Download the report.
                Console.WriteLine("[Thread #{0}]: Downloading report for customer: {1} into {2}...",
                                  this.ThreadIndex, customerId, downloadFile);

                try {
                    ReportUtilities utilities = new ReportUtilities(user, "v201806", query,
                                                                    DownloadFormat.GZIPPED_CSV.ToString());
                    using (ReportResponse response = utilities.GetResponse()) {
                        response.Save(downloadFile);
                    }

                    // Mark this report download as success.
                    SuccessfulReportDownload success = new SuccessfulReportDownload {
                        CustomerId = customerId,
                        Path       = downloadFile
                    };
                    SuccessfulReports.TryAdd(success);

                    Console.WriteLine("Report was downloaded to '{0}'.", downloadFile);
                } catch (AdWordsReportsException e) {
                    // Mark this report download as failure.
                    FailedReportDownload failure = new FailedReportDownload {
                        CustomerId = customerId,
                        Exception  = e
                    };
                    FailedReports.TryAdd(failure);

                    Console.WriteLine("Failed to download report for customer: {0}. Exception says {1}",
                                      customerId, e.Message);
                }
            }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201705.ReportService);

            // Get the NetworkService.
            NetworkService networkService = (NetworkService)user.GetService(
                DfpService.v201705.NetworkService);

            // Set the file path where the report will be saved.
            String filePath = _T("INSERT_FILE_PATH_HERE");

            // Get the root ad unit ID to filter on.
            String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;

            // Create statement to filter on an ancestor ad unit with the root ad unit ID to include all
            // ad units in the network.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("PARENT_AD_UNIT_ID = :parentAdUnitId")
                                                .AddValue("parentAdUnitId", long.Parse(rootAdUnitId));

            // Create report query.
            ReportQuery reportQuery = new ReportQuery();

            reportQuery.dimensions =
                new Dimension[] { Dimension.AD_UNIT_ID, Dimension.AD_UNIT_NAME };
            reportQuery.columns = new Column[] { Column.AD_SERVER_IMPRESSIONS,
                                                 Column.AD_SERVER_CLICKS, Column.DYNAMIC_ALLOCATION_INVENTORY_LEVEL_IMPRESSIONS,
                                                 Column.DYNAMIC_ALLOCATION_INVENTORY_LEVEL_CLICKS,
                                                 Column.TOTAL_INVENTORY_LEVEL_IMPRESSIONS,
                                                 Column.TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE };

            // Set the filter statement.
            reportQuery.statement = statementBuilder.ToStatement();

            reportQuery.adUnitView    = ReportQueryAdUnitView.HIERARCHICAL;
            reportQuery.dateRangeType = DateRangeType.LAST_WEEK;

            // Create report job.
            ReportJob reportJob = new ReportJob();

            reportJob.reportQuery = reportQuery;

            try {
                // Run report.
                reportJob = reportService.runReportJob(reportJob);

                ReportUtilities reportUtilities = new ReportUtilities(reportService, reportJob.id);

                // Set download options.
                ReportDownloadOptions options = new ReportDownloadOptions();
                options.exportFormat                  = ExportFormat.CSV_DUMP;
                options.useGzipCompression            = true;
                reportUtilities.reportDownloadOptions = options;

                // Download the report.
                using (ReportResponse reportResponse = reportUtilities.GetResponse()) {
                    reportResponse.Save(filePath);
                }
                Console.WriteLine("Report saved to \"{0}\".", filePath);
            } catch (Exception e) {
                Console.WriteLine("Failed to run inventory report. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user, long savedQueryId)
        {
            using (ReportService reportService = user.GetService <ReportService>())
            {
                // Set the file path where the report will be saved.
                String filePath = _T("INSERT_FILE_PATH_HERE");

                // Create statement to retrieve the saved query.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :id")
                                                    .OrderBy("id ASC")
                                                    .Limit(1)
                                                    .AddValue("id", savedQueryId);

                SavedQueryPage page =
                    reportService.getSavedQueriesByStatement(statementBuilder.ToStatement());
                SavedQuery savedQuery = page.results[0];

                if (!savedQuery.isCompatibleWithApiVersion)
                {
                    throw new InvalidOperationException("Saved query is not compatible with this " +
                                                        "API version");
                }

                // Optionally modify the query.
                ReportQuery reportQuery = savedQuery.reportQuery;
                reportQuery.adUnitView = ReportQueryAdUnitView.HIERARCHICAL;

                // Create a report job using the saved query.
                ReportJob reportJob = new ReportJob();
                reportJob.reportQuery = reportQuery;

                try
                {
                    // Run report.
                    reportJob = reportService.runReportJob(reportJob);

                    ReportUtilities reportUtilities =
                        new ReportUtilities(reportService, reportJob.id);

                    // Set download options.
                    ReportDownloadOptions options = new ReportDownloadOptions();
                    options.exportFormat                  = ExportFormat.CSV_DUMP;
                    options.useGzipCompression            = true;
                    reportUtilities.reportDownloadOptions = options;

                    // Download the report.
                    using (ReportResponse reportResponse = reportUtilities.GetResponse())
                    {
                        reportResponse.Save(filePath);
                    }

                    Console.WriteLine("Report saved to \"{0}\".", filePath);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to run saved query. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Example #16
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (LineItemService lineItemService =
                       (LineItemService)user.GetService(DfpService.v201802.LineItemService))
                using (ReportService reportService =
                           (ReportService)user.GetService(DfpService.v201802.ReportService)) {
                    try {
                        // Set the ID of the order to get line items from.
                        long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

                        // Set the file path where the report will be saved.
                        String filePath = _T("INSERT_FILE_PATH_HERE");

                        // Sets default for page.
                        LineItemPage page = new LineItemPage();

                        // Create a statement to only select line items from a given order.
                        StatementBuilder statementBuilder = new StatementBuilder()
                                                            .Where("orderId = :orderId")
                                                            .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                            .AddValue("orderId", orderId);


                        // Collect all line item custom field IDs for an order.
                        List <long> customFieldIds = new List <long>();
                        do
                        {
                            // Get line items by statement.
                            page = lineItemService.getLineItemsByStatement(statementBuilder.ToStatement());

                            // Get custom field IDs from the line items of an order.
                            if (page.results != null)
                            {
                                foreach (LineItem lineItem in page.results)
                                {
                                    if (lineItem.customFieldValues != null)
                                    {
                                        foreach (BaseCustomFieldValue customFieldValue in lineItem.customFieldValues)
                                        {
                                            if (!customFieldIds.Contains(customFieldValue.customFieldId))
                                            {
                                                customFieldIds.Add(customFieldValue.customFieldId);
                                            }
                                        }
                                    }
                                }
                            }

                            statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                        } while (statementBuilder.GetOffset() < page.totalResultSetSize);


                        // Create statement to filter for an order.
                        statementBuilder.RemoveLimitAndOffset();

                        // Create report job.
                        ReportJob reportJob = new ReportJob();

                        // Create report query.
                        ReportQuery reportQuery = new ReportQuery();
                        reportQuery.dateRangeType = DateRangeType.LAST_MONTH;
                        reportQuery.dimensions    = new Dimension[] {
                            Dimension.LINE_ITEM_ID,
                            Dimension.LINE_ITEM_NAME
                        };
                        reportQuery.statement      = statementBuilder.ToStatement();
                        reportQuery.customFieldIds = customFieldIds.ToArray();
                        reportQuery.columns        = new Column[] { Column.AD_SERVER_IMPRESSIONS };
                        reportJob.reportQuery      = reportQuery;

                        // Run report job.
                        reportJob = reportService.runReportJob(reportJob);

                        ReportUtilities reportUtilities = new ReportUtilities(reportService, reportJob.id);

                        // Set download options.
                        ReportDownloadOptions options = new ReportDownloadOptions();
                        options.exportFormat                  = ExportFormat.CSV_DUMP;
                        options.useGzipCompression            = true;
                        reportUtilities.reportDownloadOptions = options;

                        // Download the report.
                        using (ReportResponse reportResponse = reportUtilities.GetResponse()) {
                            reportResponse.Save(filePath);
                        }
                        Console.WriteLine("Report saved to \"{0}\".", filePath);
                    } catch (Exception e) {
                        Console.WriteLine("Failed to run cusom fields report. Exception says \"{0}\"",
                                          e.Message);
                    }
                }
        }
Example #17
0
        // public IHttpActionResult GetGoogleCampignPerformance(int ProductMasterId,GoogleAdwordCredential credential)
        public IHttpActionResult GetGoogleCampignPerformance(int productMasterId)
        {
            List <AdwordsPerformance> _adwordsPerformance = new List <AdwordsPerformance>();

            if (productMasterId == 0)
            {
                return(Content(HttpStatusCode.BadRequest, "Bad Request"));
            }

            GoogleAdwordCredential credential = getGoogleAdwordsCredentialByProductId(productMasterId);

            if (credential == null)
            {
                return(Content(HttpStatusCode.NotFound, "Invalid"));
            }


            AdWordsUser user = new AdWordsUser();

            (user.Config as AdWordsAppConfig).ClientCustomerId   = credential.ClientCustomerId;   // credential.ClientCustomerId;// "740-435-6551";// "278-414-1536";
            (user.Config as AdWordsAppConfig).DeveloperToken     = credential.DeveloperToken;     //"0Wf3sFhDmmahNnTxbynJfg"; //credential.DeveloperToken;
            (user.Config as AdWordsAppConfig).OAuth2ClientId     = credential.OAuth2ClientId;     //"215226543458-nd2eg32u4udlskt3ab8r1437mpim21is.apps.googleusercontent.com"; //credential.OAuth2ClientId;
            (user.Config as AdWordsAppConfig).OAuth2ClientSecret = credential.OAuth2ClientSecret; // "LFzx_vtGuRP-Fn_Mk9b6S1DU"; // credential.OAuth2ClientSecret;
            (user.Config as AdWordsAppConfig).OAuth2Mode         = OAuth2Flow.APPLICATION;
            (user.Config as AdWordsAppConfig).OAuth2RefreshToken = credential.OAuth2RefreshToken; //"1/hmq7O1c8pObwH376sev5F0PZyu_X5pvLbLbcpVF7xbA";  //credential.OAuth2RefreshToken;

            //TODO (Add more configuration settings here.

            //   CampaignService campaignService = (CampaignService)user.GetService(AdWordsService.v201802.CampaignService);
            //TODO (Add your code here to use the service.)
            //string startDate = DateTime.Now.Date.ToString("yyyyMMdd");
            //string endDate = DateTime.Now.Date.Subtract(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day - 5)).ToString("yyyyMMdd");

            // ReportDefinitionDateRangeType dateRangeType = GetReportDateTimeRange(startDate, endDate);


            ReportDefinition definition = new ReportDefinition()
            {
                reportName             = DateTime.Now.ToString("dd-mm-yyyy"),
                reportType             = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT,
                downloadFormat         = DownloadFormat.XML,
                dateRangeType          = ReportDefinitionDateRangeType.YESTERDAY,
                dateRangeTypeSpecified = true,

                selector = new Selector()
                {
                    fields = new string[] {
                        "CampaignId",             // get campaign id
                        "CampaignName",           // get campaign Name
                        "AdGroupId",              // adwords id
                        "AdGroupName",
                        "Id",                     // kewords id
                        "CriteriaType",           // type of search
                        "Criteria",               // get keywords name
                        "CriteriaDestinationUrl", // ads url
                        "FinalUrls",              //
                        "CpcBid",                 // max cpc
                        "Clicks",                 // total click per ad
                        "Impressions",            // no of ads shows on google netwoks
                        "Cost",                   // cost per ads
                        "Ctr",                    // total click per total impression
                        "AverageCpc",
                        "CampaignStatus",         // campaign status
                        "Conversions",            // no of leads convert
                        "CostPerConversion",      // cpa
                        "ValuePerConversion",
                        "AveragePosition",
                        "ConversionRate" // (convertion/click) *100,
                    },
                    //dateRange = new DateRange()
                    //{
                    //    min = "20150201",
                    //    max = "20150201"
                    //},
                    predicates = new Predicate[] {
                        Predicate.In("Status", new string[] { "PAUSED", "ENABLED" })
                    }
                }
            };

            // Optional: Include zero impression rows.
            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            config.IncludeZeroImpressions = false;

            string filePath = Path.GetTempPath();


            try
            {
                ReportUtilities utilities = new ReportUtilities(user, "v201802", definition);
                using (ReportResponse response = utilities.GetResponse())
                {
                    //  response.Save(filePath + "respp.csv");
                    var         downloadedStream = response.Stream;
                    XmlDocument doc = new XmlDocument();
                    doc.Load(downloadedStream);
                    string   json            = JsonConvert.SerializeObject(doc);
                    var      jsonObject      = JsonConvert.DeserializeObject <dynamic>(json);
                    var      rows            = jsonObject.report.table.row;
                    string   dateRange       = jsonObject.report["date-range"]["@date"];
                    DateTime parsedDateRange = DateTime.Parse(dateRange);
                    if (rows == null)
                    {
                        return(Ok());
                    }
                    foreach (var row in rows)
                    {
                        string url = row["@finalURL"];
                        Tuple <int, string> prodVal = getFilterProdValue(url, credential);
                        int    websitemasterId      = prodVal.Item1;
                        string productName          = prodVal.Item2;

                        removeDuplicateData(DateTime.Today.AddDays(-1), websitemasterId, productName);


                        string _avgCpc = row["@avgCPC"];
                        double avgCpc  = FilterRateTypeValue(_avgCpc);

                        string _conversionRate = row["@convRate"];
                        double conversionRate  = FilterRateTypeValue(_conversionRate);

                        string _ctr = row["@ctr"];
                        double ctr  = FilterRateTypeValue(_ctr);

                        AdwordsPerformance adwordsPerformance = new AdwordsPerformance()
                        {
                            AccountId = credential.ClientCustomerId,// credential.ClientCustomerId, // will chnage, get from user param

                            AdGroupId        = row["@adGroupID"],
                            AdGroupName      = row["@adGroup"],
                            AvgCpc           = avgCpc,
                            AvgPosition      = row["@avgPosition"],
                            CampaignId       = row["@campaignID"],
                            CampaignName     = row["@campaign"],
                            Impression       = row["@impressions"],
                            Cost             = row["@cost"],
                            Click            = row["@clicks"],
                            Convertion       = row["@conversions"],
                            ConvertionRate   = conversionRate,
                            Cpa              = row["@costConv"],
                            Ctr              = ctr,
                            GenerateDateTime = DateTime.Now.AddDays(-1),

                            KeywordId            = row["@keywordID"],
                            KeywordName          = row["@keywordPlacement"],
                            AdwordType           = 1,// google
                            OrganizationMasterId = 1,
                            ProductName          = productName,
                            WebsiteMasterId      = websitemasterId
                        };

                        _adwordsPerformance.Add(adwordsPerformance);
                    }
                    response.Dispose();

                    saveToDataBase(_adwordsPerformance);
                }
            }
            catch (Exception e)
            {
                throw new System.ApplicationException("Failed to download report.", e);
            }


            return(Ok());
        }
Example #18
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (ReportService reportService =
                       (ReportService)user.GetService(DfpService.v201802.ReportService))
            {
                // Set the file path where the report will be saved.
                String filePath = _T("INSERT_FILE_PATH_HERE");

                long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

                // Create report job.
                ReportJob reportJob = new ReportJob();
                reportJob.reportQuery            = new ReportQuery();
                reportJob.reportQuery.dimensions = new Dimension[]
                {
                    Dimension.ORDER_ID,
                    Dimension.ORDER_NAME
                };
                reportJob.reportQuery.dimensionAttributes = new DimensionAttribute[]
                {
                    DimensionAttribute.ORDER_TRAFFICKER,
                    DimensionAttribute.ORDER_START_DATE_TIME,
                    DimensionAttribute.ORDER_END_DATE_TIME
                };
                reportJob.reportQuery.columns = new Column[]
                {
                    Column.AD_SERVER_IMPRESSIONS,
                    Column.AD_SERVER_CLICKS,
                    Column.AD_SERVER_CTR,
                    Column.AD_SERVER_CPM_AND_CPC_REVENUE,
                    Column.AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM
                };

                // Set a custom date range for the last 8 days
                reportJob.reportQuery.dateRangeType = DateRangeType.CUSTOM_DATE;
                System.DateTime endDateTime = System.DateTime.Now;
                reportJob.reportQuery.startDate = DateTimeUtilities
                                                  .FromDateTime(endDateTime.AddDays(-8), "America/New_York").date;
                reportJob.reportQuery.endDate = DateTimeUtilities
                                                .FromDateTime(endDateTime, "America/New_York").date;

                // Create statement object to filter for an order.
                StatementBuilder statementBuilder = new StatementBuilder().Where("ORDER_ID = :id")
                                                    .AddValue("id", orderId);
                reportJob.reportQuery.statement = statementBuilder.ToStatement();

                try
                {
                    // Run report job.
                    reportJob = reportService.runReportJob(reportJob);

                    ReportUtilities reportUtilities =
                        new ReportUtilities(reportService, reportJob.id);

                    // Set download options.
                    ReportDownloadOptions options = new ReportDownloadOptions();
                    options.exportFormat                  = ExportFormat.CSV_DUMP;
                    options.useGzipCompression            = true;
                    reportUtilities.reportDownloadOptions = options;

                    // Download the report.
                    using (ReportResponse reportResponse = reportUtilities.GetResponse())
                    {
                        reportResponse.Save(filePath);
                    }

                    Console.WriteLine("Report saved to \"{0}\".", filePath);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to run delivery report. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
        /// <summary>
        /// Handles the Click event of the btnDownloadReport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing
        /// the event data.</param>
        protected void OnDownloadReportButtonClick(object sender, EventArgs eventArgs)
        {
            ConfigureUserForOAuth();
            ReportService reportService =
                (ReportService)user.GetService(DfpService.v201802.ReportService);

            ReportQuery reportQuery = new ReportQuery();

            reportQuery.dimensions = new Dimension[]
            {
                Dimension.AD_UNIT_ID,
                Dimension.AD_UNIT_NAME
            };
            reportQuery.columns = new Column[]
            {
                Column.AD_SERVER_IMPRESSIONS,
                Column.AD_SERVER_CLICKS,
                Column.DYNAMIC_ALLOCATION_INVENTORY_LEVEL_IMPRESSIONS,
                Column.DYNAMIC_ALLOCATION_INVENTORY_LEVEL_CLICKS,
                Column.TOTAL_INVENTORY_LEVEL_IMPRESSIONS,
                Column.TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE
            };

            reportQuery.adUnitView    = ReportQueryAdUnitView.HIERARCHICAL;
            reportQuery.dateRangeType = DateRangeType.YESTERDAY;

            // Create report job.
            ReportJob reportJob = new ReportJob();

            reportJob.reportQuery = reportQuery;

            string filePath = Path.GetTempFileName();

            try
            {
                // Run report.
                reportJob = reportService.runReportJob(reportJob);

                ReportUtilities reportUtilities = new ReportUtilities(reportService, reportJob.id);

                // Set download options.
                ReportDownloadOptions options = new ReportDownloadOptions();
                options.exportFormat                  = ExportFormat.CSV_DUMP;
                options.useGzipCompression            = true;
                reportUtilities.reportDownloadOptions = options;

                // Download the report.
                using (ReportResponse reportResponse = reportUtilities.GetResponse())
                {
                    reportResponse.Save(filePath);
                }
            }
            catch (Exception e)
            {
                throw new System.ApplicationException("Failed to download report.", e);
            }

            Response.AddHeader("content-disposition", "attachment;filename=report.csv.gzip");
            Response.WriteFile(filePath);
            Response.End();
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>

        public void Run(AdWordsUser user)
        {
            //ReportQuery query = new ReportQueryBuilder()
            //    .Select("CampaignId", "AdGroupId", "Id", "Criteria", "CriteriaType",
            //        "Impressions", "Clicks", "Cost")
            //    .From(ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT)
            //    .Where("Status").In("ENABLED", "PAUSED")
            //    .During(ReportDefinitionDateRangeType.LAST_7_DAYS)
            //    .Build();

            //string filePath =
            //    ExampleUtilities.GetHomeDir() + Path.DirectorySeparatorChar + fileName;
            string DebugClientID = "";

            WriteLog("===========================Scheduler Started=========================================" + DateTime.Now);
            try
            {
                var     connectionString = ConfigurationManager.ConnectionStrings["AMS"].ConnectionString;             //"DATA SOURCE=10.108.135.231; UID=amslogin05; PWD=MoJ$t0$xAMSxps; INITIAL CATALOG=UAT_TRAINING_AMS;";//
                DataSet ds = new DataSet();

                SqlConnection conn = new SqlConnection(connectionString);
                if (conn.State.ToString() != "1")
                {
                    conn.Open();
                }

                SqlCommand cmd = new SqlCommand("select distinct GoogleAdWordsClientID from branch where isnull(GoogleAdWordsClientID,'0') <> '0' and GoogleAdWordsClientID<>'362-801-4584' ", conn);
                cmd.CommandType = CommandType.Text;
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                sda.Fill(ds);

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string query = "SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, Impressions, " +
                                   "Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT WHERE Status IN [ENABLED, PAUSED] " +
                                   "DURING YESTERDAY";

                    ((Google.Api.Ads.AdWords.Lib.AdWordsAppConfig)user.Config).ClientCustomerId = row["GoogleAdWordsClientID"].ToString();

                    //string filePath = ExampleUtilities.GetHomeDir() + Path.DirectorySeparatorChar + fileName;
                    string filePath = ConfigurationManager.AppSettings["FolderPath"].ToString() + row["GoogleAdWordsClientID"].ToString() + ".csv";
                    DebugClientID = row["GoogleAdWordsClientID"].ToString();
                    try
                    {
                        ReportUtilities utilities = new ReportUtilities(user, "v201809", query,
                                                                        DownloadFormat.CSV.ToString());
                        using (ReportResponse response = utilities.GetResponse())
                        {
                            response.Save(filePath);
                        }
                        Console.WriteLine("Report was downloaded to '{0}'.", filePath);
                    }
                    catch (Exception e)
                    {
                        errorExisted = "yes";
                        //throw new System.ApplicationException("Failed to download report.", e);
                        WriteLog("*******************************Failed to download report for the Client ID=========================================" + DebugClientID);
                        WriteLog(e.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                errorExisted = "yes";
                WriteLog("*******************************ExCeption Starts for the Client ID=========================================" + DebugClientID);
                WriteLog(ex.ToString());
                WriteLog("*******************************ExCeption Ends=========================================");
                //throw;
            }
            finally
            {
                WriteLog("===========================Scheduler Ended=========================================" + DateTime.Now);

                string  SMTPCLIENT   = System.Configuration.ConfigurationManager.AppSettings["SMTPCLIENT"].ToString();
                string  MAILUSERNAME = System.Configuration.ConfigurationManager.AppSettings["MAILUSERNAME"].ToString();
                string  MAILPWD      = System.Configuration.ConfigurationManager.AppSettings["MAILPWD"].ToString();
                int     Port         = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Port"]);
                Boolean EnableSsl    = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["EnableSsl"]);

                System.Net.Mail.MailMessage msg;


                msg      = new System.Net.Mail.MailMessage();
                msg.Body = "Hi Team, <br><br> Please find the attached file for the Google AdWords log details. <br> <br> Thanks.";


                msg.From = new MailAddress("*****@*****.**");

                string[] strMails = ConfigurationManager.AppSettings["ToMail"].ToString().Split(';');
                for (int i = 0; i < strMails.Length - 1; i++)
                {
                    msg.To.Add(strMails[i].ToString());
                }


                if (errorExisted == "yes")
                {
                    msg.Subject = "Google AdWords Scheduler Status on " + System.DateTime.Today.ToString("MM-dd-yyyy") + " ****** Error Occurred **********";
                }
                else
                {
                    msg.Subject = "Google AdWords Scheduler Status on " + System.DateTime.Today.ToString("MM-dd-yyyy") + " ******* Run Successfully ******";
                }

                System.Net.Mail.SmtpClient   smtpServer  = null;
                System.Net.NetworkCredential credentials = null;
                smtpServer                       = new System.Net.Mail.SmtpClient(SMTPCLIENT);
                smtpServer.Port                  = Port;
                smtpServer.EnableSsl             = EnableSsl;
                smtpServer.UseDefaultCredentials = false;
                smtpServer.Port                  = Port;
                smtpServer.EnableSsl             = EnableSsl;
                smtpServer.UseDefaultCredentials = false;
                credentials                      = new System.Net.NetworkCredential(MAILUSERNAME, MAILPWD);
                smtpServer.Credentials           = credentials;
                smtpServer.DeliveryMethod        = SmtpDeliveryMethod.Network;
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

                MemoryStream ms1  = new MemoryStream(File.ReadAllBytes(logFineName));
                Attachment   att1 = new System.Net.Mail.Attachment(ms1, "LogFile.txt");
                msg.Attachments.Add(att1);

                msg.IsBodyHtml         = true;
                smtpServer.Credentials = credentials;
                smtpServer.Send(msg);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (ReportService reportService = user.GetService <ReportService>())
            {
                try
                {
                    // Set the ID of the custom field to report on.
                    long customFieldId = long.Parse(_T("INSERT_FIELD_ID_HERE"));

                    // Set the key ID of the custom dimension to report on.
                    long customDimensionKeyId =
                        long.Parse(_T("INSERT_CUSTOM_DIMENSION_KEY_ID_HERE"));

                    // Set the file path where the report will be saved.
                    String filePath = _T("INSERT_FILE_PATH_HERE");

                    // Create report job.
                    ReportJob reportJob = new ReportJob();

                    // Create report query.
                    ReportQuery reportQuery = new ReportQuery();
                    reportQuery.dateRangeType = DateRangeType.LAST_MONTH;
                    reportQuery.dimensions    = new Dimension[]
                    {
                        Dimension.CUSTOM_DIMENSION,
                        Dimension.LINE_ITEM_ID,
                        Dimension.LINE_ITEM_NAME
                    };
                    reportQuery.customFieldIds        = new long[] { customFieldId };
                    reportQuery.customDimensionKeyIds = new long[] { customDimensionKeyId };
                    reportQuery.columns = new Column[]
                    {
                        Column.AD_SERVER_IMPRESSIONS
                    };
                    reportJob.reportQuery = reportQuery;

                    // Run report job.
                    reportJob = reportService.runReportJob(reportJob);

                    ReportUtilities reportUtilities =
                        new ReportUtilities(reportService, reportJob.id);

                    // Set download options.
                    ReportDownloadOptions options = new ReportDownloadOptions();
                    options.exportFormat                  = ExportFormat.CSV_DUMP;
                    options.useGzipCompression            = true;
                    reportUtilities.reportDownloadOptions = options;

                    // Download the report.
                    using (ReportResponse reportResponse = reportUtilities.GetResponse())
                    {
                        reportResponse.Save(filePath);
                    }

                    Console.WriteLine("Report saved to \"{0}\".", filePath);
                }
                catch (Exception e)
                {
                    Console.WriteLine(
                        "Failed to run custom fields report. Exception says \"{0}\"", e.Message);
                }
            }
        }
Example #22
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (ReportService reportService =
                       (ReportService)user.GetService(DfpService.v201802.ReportService))
            {
                // Set the file path where the report will be saved.
                String filePath = _T("INSERT_FILE_PATH_HERE");

                // Create report query.
                ReportQuery reportQuery = new ReportQuery();
                reportQuery.dimensions = new Dimension[]
                {
                    Dimension.AD_EXCHANGE_DATE,
                    Dimension.AD_EXCHANGE_COUNTRY_NAME
                };
                reportQuery.columns = new Column[]
                {
                    Column.AD_EXCHANGE_AD_REQUESTS,
                    Column.AD_EXCHANGE_IMPRESSIONS,
                    Column.AD_EXCHANGE_ESTIMATED_REVENUE
                };

                reportQuery.dateRangeType = DateRangeType.LAST_WEEK;

                // Run in pacific time.
                reportQuery.timeZoneType      = TimeZoneType.AD_EXCHANGE;
                reportQuery.adxReportCurrency = "EUR";

                // Create report job.
                ReportJob reportJob = new ReportJob();
                reportJob.reportQuery = reportQuery;

                try
                {
                    // Run report.
                    reportJob = reportService.runReportJob(reportJob);

                    ReportUtilities reportUtilities =
                        new ReportUtilities(reportService, reportJob.id);

                    // Set download options.
                    ReportDownloadOptions options = new ReportDownloadOptions();
                    options.exportFormat                  = ExportFormat.CSV_DUMP;
                    options.useGzipCompression            = true;
                    reportUtilities.reportDownloadOptions = options;

                    // Download the report.
                    using (ReportResponse reportResponse = reportUtilities.GetResponse())
                    {
                        reportResponse.Save(filePath);
                    }

                    Console.WriteLine("Report saved to \"{0}\".", filePath);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to run Ad Exchange report. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }