/// <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.
        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 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) {
      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, "v201502", query,
            DownloadFormat.GZIPPED_CSV.ToString());
        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);
      }
    }
        /// <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, "v201601", 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)
        {
            string query = "SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, Impressions, " +
              "Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT WHERE Status IN [ACTIVE, PAUSED] " +
              "DURING LAST_7_DAYS";

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

              try {
            // If you know that your report is small enough to fit in memory, then
            // you can instead use
            // ReportUtilities utilities = new ReportUtilities(user);
            // utilities.ReportVersion = "v201306";
            // ClientReport report = utilities.GetClientReport(query, format);
            //
            // // Get the text report directly if you requested a text format
            // // (e.g. xml)
            // string reportText = report.Text;
            //
            // // Get the binary report if you requested a binary format
            // // (e.g. gzip)
            // byte[] reportBytes = report.Contents;
            //
            // // Deflate a zipped binary report for further processing.
            // string deflatedReportText = Encoding.UTF8.GetString(
            //     MediaUtilities.DeflateGZipData(report.Contents));
            ReportUtilities utilities = new ReportUtilities(user);
            utilities.ReportVersion = "v201306";
            utilities.DownloadClientReport(query, DownloadFormat.GZIPPED_CSV.ToString(), filePath);
            Console.WriteLine("Report was downloaded to '{0}'.", filePath);
              } catch (Exception ex) {
            throw new System.ApplicationException("Failed to download report.", ex);
              }
        }
    /// <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 {
        // If you know that your report is small enough to fit in memory, then
        // you can instead use
        // ReportUtilities utilities = new ReportUtilities(user);
        // utilities.ReportVersion = "v201309";
        // ClientReport report = utilities.GetClientReport(definition);
        //
        // // Get the text report directly if you requested a text format
        // // (e.g. xml)
        // string reportText = report.Text;
        //
        // // Get the binary report if you requested a binary format
        // // (e.g. gzip)
        // byte[] reportBytes = report.Contents;
        //
        // // Deflate a zipped binary report for further processing.
        // string deflatedReportText = Encoding.UTF8.GetString(
        //     MediaUtilities.DeflateGZipData(report.Contents));

        // Set the customer id.
        (user.Config as AdWordsAppConfig).ClientCustomerId = txtCustomerId.Text;
        ReportUtilities utilities = new ReportUtilities(user);
        utilities.ReportVersion = "v201309";
        utilities.DownloadClientReport(definition, 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>
        /// 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="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>
        /// 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",
              "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 = ExampleUtilities.GetHomeDir() + Path.DirectorySeparatorChar + fileName;

              try {
            // If you know that your report is small enough to fit in memory, then
            // you can instead use
            // ReportUtilities utilities = new ReportUtilities(user);
            // utilities.ReportVersion = "v201309";
            // ClientReport report = utilities.GetClientReport(definition);
            //
            // // Get the text report directly if you requested a text format
            // // (e.g. xml)
            // string reportText = report.Text;
            //
            // // Get the binary report if you requested a binary format
            // // (e.g. gzip)
            // byte[] reportBytes = report.Contents;
            //
            // // Deflate a zipped binary report for further processing.
            // string deflatedReportText = Encoding.UTF8.GetString(
            //     MediaUtilities.DeflateGZipData(report.Contents));
            ReportUtilities utilities = new ReportUtilities(user);
            utilities.ReportVersion = "v201309";
            utilities.DownloadClientReport(definition, filePath);
            Console.WriteLine("Report was downloaded to '{0}'.", filePath);
              } catch (Exception ex) {
            throw new System.ApplicationException("Failed to download report.", ex);
              }
        }
        /// <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 e) {
            throw new System.ApplicationException("Failed to download report.", e);
              }
        }