/// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="user">The DFP user object running the code example.</param>
    public override void Run(DfpUser user) {
      ReportService reportService = (ReportService) user.GetService(
          DfpService.v201508.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 statement object to filter for an order.
      StatementBuilder statementBuilder = new StatementBuilder()
          .Where("ORDER_ID = :id")
          .AddValue("id", orderId);

      // 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;

      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);
      }
    }
    public void TestRunDeliveryReport() {
      ReportJob reportJob = new ReportJob();
      reportJob.reportQuery = new ReportQuery();
      reportJob.reportQuery.dimensions = new Dimension[] {Dimension.ORDER_ID, Dimension.ORDER_NAME};
      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};
      reportJob.reportQuery.dateRangeType = DateRangeType.LAST_MONTH;

      ReportJob newReportJob = null;

      Assert.DoesNotThrow(delegate() {
        newReportJob = reportService.runReportJob(reportJob);
      });

      Assert.NotNull(newReportJob);
    }
Exemplo n.º 3
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201405.ReportService);

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

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

            reportQuery.dateRangeType = DateRangeType.LAST_MONTH;
            reportQuery.dimensions    = new Dimension[] { Dimension.ORDER_ID, Dimension.ORDER_NAME };
            reportQuery.columns       = new Column[] { Column.MERGED_AD_SERVER_IMPRESSIONS,
                                                       Column.MERGED_AD_SERVER_CLICKS, Column.MERGED_AD_SERVER_CTR,
                                                       Column.MERGED_AD_SERVER_CPM_AND_CPC_REVENUE,
                                                       Column.MERGED_AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM };
            reportJob.reportQuery = reportQuery;

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

                do
                {
                    Console.WriteLine("Report with ID '{0}' is still running.", reportJob.id);
                    Thread.Sleep(30000);
                    // Get report job.
                    reportJob = reportService.getReportJob(reportJob.id);
                } while (reportJob.reportJobStatus == ReportJobStatus.IN_PROGRESS);

                if (reportJob.reportJobStatus == ReportJobStatus.FAILED)
                {
                    Console.WriteLine("Report job with ID '{0}' failed to finish successfully.",
                                      reportJob.id);
                }
                else
                {
                    Console.WriteLine("Report job with ID '{0}' completed successfully.", reportJob.id);
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to run delivery report. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
Exemplo n.º 4
0
        public void ExecuteJob_OnExecute_DownloadsFile()
        {
            // setup
            ReportJob job = new ReportJob();

            job.Command        = Guid.NewGuid().ToString();
            job.OutputFilePath = Environment.CurrentDirectory;
            job.OutputFileName = Path.GetRandomFileName();

            string expectedOutPath = Path.Combine(job.OutputFilePath, job.OutputFileName);

            // execute
            _reportExecutor.ExecuteJob(null, job);

            // assert
            _webClientWrapper.Received(1).UseDefaultCredentials = true;
            _webClientWrapper.Received(1).DownloadFile(job.Command, expectedOutPath);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201403.ReportService);

            // 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);
                // Wait for report to complete.
                while (reportJob.reportJobStatus == ReportJobStatus.IN_PROGRESS)
                {
                    Console.WriteLine("Report job with id = '{0}' is still running.", reportJob.id);
                    Thread.Sleep(30000);
                    // Get report job.
                    reportJob = reportService.getReportJob(reportJob.id);
                }

                if (reportJob.reportJobStatus == ReportJobStatus.COMPLETED)
                {
                    Console.WriteLine("Report job with id = '{0}' completed successfully.", reportJob.id);
                }
                else if (reportJob.reportJobStatus == ReportJobStatus.FAILED)
                {
                    Console.WriteLine("Report job with id = '{0}' failed to complete successfully.",
                                      reportJob.id);
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to run sales report. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (ReportService reportService = (ReportService)user.GetService(
                       DfpService.v201708.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);
                }
            }
        }
    public void TestRunInventoryReport() {
      ReportJob reportJob = new ReportJob();
      reportJob.reportQuery = new ReportQuery();
      reportJob.reportQuery.dimensions = new Dimension[] {Dimension.DATE};
      reportJob.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};
      reportJob.reportQuery.dateRangeType = DateRangeType.LAST_WEEK;

      ReportJob newReportJob = null;

      Assert.DoesNotThrow(delegate() {
        newReportJob = reportService.runReportJob(reportJob);
      });

      Assert.NotNull(newReportJob);
    }
        public void TestRunInventoryReport()
        {
            ReportJob reportJob = new ReportJob();

            reportJob.reportQuery            = new ReportQuery();
            reportJob.reportQuery.dimensions = new Dimension[] { Dimension.DATE };
            reportJob.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 };
            reportJob.reportQuery.dateRangeType = DateRangeType.LAST_WEEK;

            Assert.DoesNotThrow(delegate() {
                reportJob = reportService.runReportJob(reportJob);
            });

            Assert.NotNull(reportJob);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public void Run(DfpUser user)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201605.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);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201405.ReportService);

            // 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);
                // Wait for report to complete.
                while (reportJob.reportJobStatus == ReportJobStatus.IN_PROGRESS)
                {
                    Console.WriteLine("Report job with id = '{0}' is still running.", reportJob.id);
                    Thread.Sleep(30000);
                    // Get report job.
                    reportJob = reportService.getReportJob(reportJob.id);
                }

                if (reportJob.reportJobStatus == ReportJobStatus.COMPLETED)
                {
                    Console.WriteLine("Report job with id = '{0}' completed successfully.", reportJob.id);
                }
                else if (reportJob.reportJobStatus == ReportJobStatus.FAILED)
                {
                    Console.WriteLine("Report job with id = '{0}' failed to complete successfully.",
                                      reportJob.id);
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to run delivery report. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
Exemplo n.º 11
0
        public void ExecuteJob_OnExecute_ResultIsValid()
        {
            // setup
            ReportJob job = new ReportJob();

            job.Command        = Guid.NewGuid().ToString();
            job.OutputFilePath = Environment.CurrentDirectory;
            job.OutputFileName = Path.GetRandomFileName();

            string expectedOutPath = Path.Combine(job.OutputFilePath, job.OutputFileName);

            // execute
            ReportJobResult result = _reportExecutor.ExecuteJob(null, job);

            // assert
            Assert.IsNotNull(result);
            Assert.AreEqual(-1, result.RowCount);
            Assert.GreaterOrEqual(result.ExecutionTime.Milliseconds, 0);
        }
Exemplo n.º 12
0
        public void TestRunSalesReport()
        {
            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;

            ReportJob newReportJob = null;

            Assert.DoesNotThrow(delegate() {
                reportJob = reportService.runReportJob(reportJob);
            });

            Assert.NotNull(reportJob);
        }
    /// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="user">The DFP user object running the code example.</param>
    public override void Run(DfpUser user) {
      ReportService reportService = (ReportService) user.GetService(
          DfpService.v201511.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);
      }
    }
        public ReportJobResult ExecuteJob(ConnectionSetting connection, ReportJob job)
        {
            DateTime start = DateTime.UtcNow;

            string url             = job.Command;
            string outputhFilePath = Path.Combine(job.OutputFilePath, job.OutputFileName);

            _logger.Info("Sending web request to {0} as user {1}", url, CredentialCache.DefaultNetworkCredentials.UserName);

            _webClientWrapper.UseDefaultCredentials = true;
            _webClientWrapper.DownloadFile(url, outputhFilePath);

            _logger.Info("Reporting services file saved to {0}", outputhFilePath);

            ReportJobResult result = new ReportJobResult();

            result.RowCount      = -1;
            result.ExecutionTime = DateTime.UtcNow.Subtract(start);
            return(result);
        }
    /// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="user">The DFP user object running the code example.</param>
    public override void Run(DfpUser user) {
      ReportService reportService = (ReportService) user.GetService(
          DfpService.v201508.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);
      }
    }
        public void ExecuteJob_OnExecute_CreatesConnectionUsingFactory()
        {
            // setup
            string            connString  = Guid.NewGuid().ToString();
            ConnectionSetting connSetting = new ConnectionSetting(Guid.NewGuid().ToString(), connString);
            ReportJob         job         = new ReportJob();

            IDbConnection dbConn = Substitute.For <IDbConnection>();

            _dbConnectionFactory.CreateConnection(connString, true).Returns(dbConn);

            IDbCommand cmd = Substitute.For <IDbCommand>();

            dbConn.CreateCommand().Returns(cmd);

            // execute
            _reportExecutor.ExecuteJob(connSetting, job);

            // assert
            _dbConnectionFactory.Received(1).CreateConnection(connString, true);
        }
        public void ExecuteJob_OutputFormatSpecified_CommandExecutedWithWriter()
        {
            // setup
            string            connString  = Guid.NewGuid().ToString();
            ConnectionSetting connSetting = new ConnectionSetting(Guid.NewGuid().ToString(), connString);
            ReportJob         job         = new ReportJob();

            job.Command        = Guid.NewGuid().ToString();
            job.OutputFormat   = Guid.NewGuid().ToString();
            job.OutputFileName = Guid.NewGuid().ToString();
            job.OutputFilePath = Environment.CurrentDirectory;
            job.Delimiter      = Guid.NewGuid().ToString();

            IDbConnection dbConn = Substitute.For <IDbConnection>();

            _dbConnectionFactory.CreateConnection(connString, true).Returns(dbConn);

            IDbCommand cmd = Substitute.For <IDbCommand>();

            dbConn.CreateCommand().Returns(cmd);

            IReportWriter reportWriter = Substitute.For <IReportWriter>();

            _reportWriterFactory.GetReportWriter(job.OutputFormat).Returns(reportWriter);

            IDataReader reader = Substitute.For <IDataReader>();

            reader.GetSchemaTable().Returns(new DataTable());
            cmd.ExecuteReader().Returns(reader);

            // execute
            ReportJobResult result = _reportExecutor.ExecuteJob(connSetting, job);

            // assert
            cmd.DidNotReceive().ExecuteNonQuery();
            cmd.Received(1).ExecuteReader();

            reportWriter.Received(1).Initialise(Arg.Any <String>(), job.Delimiter);
            reportWriter.Received(1).WriteHeader(Arg.Any <IEnumerable <String> >());
        }
        public void Execute_WithoutDbConnection_Validate()
        {
            // setup
            string            connString  = Guid.NewGuid().ToString();
            ConnectionSetting connSetting = new ConnectionSetting(Guid.NewGuid().ToString(), connString);
            int       jobId     = new Random().Next(100, 100000);
            ReportJob reportJob = new ReportJob()
            {
                Id = jobId
            };
            IDbConnection dbConnection = Substitute.For <IDbConnection>();

            _dbConnectionFactory.CreateConnection(connString, true).Returns(dbConnection);

            // execute
            _failJobCommand.Execute(connSetting, jobId, new Exception("test exception"));

            // assert
            _dbConnectionFactory.Received(1).CreateConnection(connString);
            _concurrencyCoordinator.Received(1).UnlockReportJob(connSetting.Name, jobId);
            dbConnection.Received(1).Execute(Arg.Any <string>(), Arg.Any <object>(), null, null, null);
        }
        public void ExecuteJob_MultipleDbParameters_MultipleCommandParameterSet()
        {
            // setup
            string            connString  = Guid.NewGuid().ToString();
            ConnectionSetting connSetting = new ConnectionSetting(Guid.NewGuid().ToString(), connString);
            ReportJob         job         = new ReportJob();

            job.Command    = Guid.NewGuid().ToString();
            job.Parameters = Guid.NewGuid().ToString();

            IDbConnection dbConn = Substitute.For <IDbConnection>();

            _dbConnectionFactory.CreateConnection(connString, true).Returns(dbConn);

            IDbCommand cmd = Substitute.For <IDbCommand>();

            dbConn.CreateCommand().Returns(cmd);

            IDataParameterCollection parmColl = Substitute.For <IDataParameterCollection>();

            cmd.Parameters.Returns(parmColl);

            SqlParameter parm1 = new SqlParameter(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
            SqlParameter parm2 = new SqlParameter(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
            SqlParameter parm3 = new SqlParameter(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());

            _dbParameterUtility.ConvertXmlToDbParameters(job.Parameters).Returns(new SqlParameter[] { parm1, parm2, parm3 });

            // execute
            _reportExecutor.ExecuteJob(connSetting, job);

            // assert
            parmColl.Received(1).Add(parm1);
            parmColl.Received(1).Add(parm2);
            parmColl.Received(1).Add(parm3);
            parmColl.Received(3).Add(Arg.Any <IDbDataParameter>());
        }
        public void ExecuteJob_JobCommandTypeSetToStoredProcedure_CommandTypeSetCorrectly()
        {
            // setup
            string            connString  = Guid.NewGuid().ToString();
            ConnectionSetting connSetting = new ConnectionSetting(Guid.NewGuid().ToString(), connString);
            ReportJob         job         = new ReportJob();

            job.Command     = Guid.NewGuid().ToString();
            job.CommandType = Constants.CommandType.StoredProcedure;

            IDbConnection dbConn = Substitute.For <IDbConnection>();

            _dbConnectionFactory.CreateConnection(connString, true).Returns(dbConn);

            IDbCommand cmd = Substitute.For <IDbCommand>();

            dbConn.CreateCommand().Returns(cmd);

            // execute
            _reportExecutor.ExecuteJob(connSetting, job);

            // assert
            cmd.Received(1).CommandType = System.Data.CommandType.StoredProcedure;
        }
        public void ExecuteJob_JobCommandTypeNotStoredProcedure_CommandTypeNotSet(string jobCommandType)
        {
            // setup
            string            connString  = Guid.NewGuid().ToString();
            ConnectionSetting connSetting = new ConnectionSetting(Guid.NewGuid().ToString(), connString);
            ReportJob         job         = new ReportJob();

            job.Command     = Guid.NewGuid().ToString();
            job.CommandType = jobCommandType;

            IDbConnection dbConn = Substitute.For <IDbConnection>();

            _dbConnectionFactory.CreateConnection(connString, true).Returns(dbConn);

            IDbCommand cmd = Substitute.For <IDbCommand>();

            dbConn.CreateCommand().Returns(cmd);

            // execute
            _reportExecutor.ExecuteJob(connSetting, job);

            // assert
            cmd.DidNotReceive().CommandType = Arg.Any <System.Data.CommandType>();
        }
        public void ExecuteJob_OnSuccess_FailsJob()
        {
            // setup
            ConnectionSetting connSetting = new ConnectionSetting("MyConn", "MyConnString");
            ReportJob         reportJob   = new ReportJob();

            reportJob.Id           = new Random().Next(1, 100);
            reportJob.CommandType  = Guid.NewGuid().ToString();
            reportJob.OutputFormat = Guid.NewGuid().ToString();

            IReportExecutor reportExecutor = Substitute.For <IReportExecutor>();

            _reportExecutorFactory.GetReportExecutor(reportJob.CommandType).Returns(reportExecutor);
            reportExecutor.When(x => x.ExecuteJob(Arg.Any <ConnectionSetting>(), Arg.Any <ReportJob>())).Do((c) => { throw new Exception(); });

            // execute
            _reportJobAgent.ExecuteJob(connSetting, reportJob);

            // assert
            _reportExecutorFactory.Received(1).GetReportExecutor(reportJob.CommandType);
            _startJobCommand.Received(1).Execute(connSetting, reportJob.Id);
            _failJobCommand.Received(1).Execute(connSetting, reportJob.Id, Arg.Any <Exception>());
            _finaliseJobCommand.Received(0).Execute(Arg.Any <ConnectionSetting>(), Arg.Any <int>());
        }
Exemplo n.º 23
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>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201403.ReportService);

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

            // 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("AD_UNIT_ANCESTOR_AD_UNIT_ID = :ancestorAdUnitId")
                                                .AddValue("ancestorAdUnitId", 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);
                // Wait for report to complete.
                while (reportJob.reportJobStatus == ReportJobStatus.IN_PROGRESS)
                {
                    Console.WriteLine("Report job with id = '{0}' is still running.", reportJob.id);
                    Thread.Sleep(30000);
                    // Get report job.
                    reportJob = reportService.getReportJob(reportJob.id);
                }

                if (reportJob.reportJobStatus == ReportJobStatus.COMPLETED)
                {
                    Console.WriteLine("Report job with id = '{0}' completed successfully.", reportJob.id);
                }
                else if (reportJob.reportJobStatus == ReportJobStatus.FAILED)
                {
                    Console.WriteLine("Report job with id = '{0}' failed to complete successfully.",
                                      reportJob.id);
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to run inventory report. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
    /// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="user">The DFP user object running the code example.</param>
    public override void Run(DfpUser user) {
      // Get the LineItemService.
      LineItemService lineItemService =
          (LineItemService) user.GetService(DfpService.v201511.LineItemService);
      // Get the ReportService.
      ReportService reportService =
          (ReportService) user.GetService(DfpService.v201511.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);
      }
    }
Exemplo n.º 26
0
 public ReportJob Begin(ReportJob parentJob, int level, ILogTarget target, string text, bool timed, bool noLog = false)
 {
     return(null);
 }
    /// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="user">The DFP user object running the code example.</param>
    public override void Run(DfpUser user) {
      ReportService reportService = (ReportService) user.GetService(
          DfpService.v201508.ReportService);

      // Get the NetworkService.
      NetworkService networkService = (NetworkService) user.GetService(
            DfpService.v201508.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);
      }
    }
Exemplo n.º 28
0
        /// <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);
                }
            }
        }
Exemplo n.º 29
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);
                }
            }
        }
 public JobArgs(ConnectionSetting connection, ReportJob job)
 {
     this.Connection = connection;
     this.Job        = job;
 }
        /// <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);
                }
            }
        }
Exemplo n.º 32
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();
            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();
        }
Exemplo n.º 33
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);
                    }
                }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            // Get the LineItemService.
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201408.LineItemService);
            // Get the ReportService.
            ReportService reportService =
                (ReportService)user.GetService(DfpService.v201408.ReportService);

            try {
                // Set the ID of the order to get line items from.
                long orderId = long.Parse(_T("INSERT_ORDER_ID_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);

                do
                {
                    Console.WriteLine("Report with ID '{0}' is still running.", reportJob.id);
                    Thread.Sleep(30000);
                    // Get report job.
                    reportJob = reportService.getReportJob(reportJob.id);
                } while (reportJob.reportJobStatus == ReportJobStatus.IN_PROGRESS);

                if (reportJob.reportJobStatus == ReportJobStatus.FAILED)
                {
                    Console.WriteLine("Report job with ID '{0}' failed to finish successfully.",
                                      reportJob.id);
                }
                else
                {
                    Console.WriteLine("Report job with ID '{0}' completed successfully.", reportJob.id);
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to run cusom fields report. Exception says \"{0}\"",
                                  ex.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);
            }
        }
Exemplo n.º 36
0
        public ReportJob CreateReport(DfpUser user)
        {
            // Get ReportService.
              ReportService reportService =
              (ReportService) user.GetService(DfpService.v201511.ReportService);

              ReportJob reportJob = new ReportJob();
              reportJob.reportQuery = new ReportQuery();
              reportJob.reportQuery.dimensions = new Dimension[] {Dimension.ORDER_ID, Dimension.ORDER_NAME};
              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};
              reportJob.reportQuery.dateRangeType = DateRangeType.LAST_MONTH;

              return reportService.runReportJob(reportJob);
        }