Пример #1
0
        /// <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, "v201710", 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>
        /// 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, "v201502", 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();
        }
Пример #3
0
        private List <DLM.AdPerformance> DefinitionToRecords(DataLakeAdWordsContext dbContext, ReportDefinition definition, DateTime now)
        {
            var utilities = new ReportUtilities(User, ApiVersion, definition);
            var records   = ReportToRecords(utilities, r => new DLM.AdPerformance {
                CampaignId    = r.CampaignID,
                AdGroupId     = r.AdgroupID,
                AdId          = r.AdID,
                Headline      = r.Ad,
                Date          = r.Day,
                Impressions   = r.Impressions,
                VideoViews    = r.Views,
                Clicks        = r.Clicks,
                Engagements   = r.Engagements,
                AverageCpm    = r.AvgCPM,
                AverageCpv    = r.AvgCPV,
                AverageCpc    = r.AvgCPC,
                AverageCpe    = r.AvgCPE,
                Cost          = r.Cost,
                ValidityStart = now,
                ValidityEnd   = DateTime.MaxValue,
            });
            var result = new List <DLM.AdPerformance>();

            foreach (var r in records)
            {
                var existing = dbContext.AdPerformanceReports
                               .Where(a => a.AdId == r.AdId && a.Date == r.Date && a.ValidityStart <= now && now < a.ValidityEnd)
                               .SingleOrDefault();
                if (existing == null)
                {
                    result = result.Append(r).ToList();
                }
                else if (!r.Equals(existing))
                {
                    result = result.Append(r).ToList();
                    existing.ValidityEnd = now;
                }
            }
            return(result);
        }
Пример #4
0
        /// <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, "v201809", 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);
            }
        }
        private async Task <ReportResponse> GetResponse(AdWordsUser user, IReportDefinition reportDefinition)
        {
            var utils    = new ReportUtilities(user, reportDefinition);
            var response = default(ReportResponse);

            utils.OnReady  = new AdsReportUtilities.OnReadyCallback((r) => response = r);
            utils.OnFailed = new AdsReportUtilities.OnFailedCallback((ex) => throw ex);

            var task = Task.Run(async() =>
            {
                while (response == default(ReportResponse))
                {
                    await Task.Delay(300);
                }

                return(response);
            });

            utils.GetResponseAsync();

            return(await task);
        }
            /// <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);
                }
            }
Пример #7
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();
        }
Пример #8
0
        protected override void Method(DataLakeAdWordsContext dbContext)
        {
            var now        = DateTime.UtcNow;
            var definition = new ReportDefinition {
                reportName     = "Structural VIDEO_PERFORMANCE_REPORT",
                dateRangeType  = ReportDefinitionDateRangeType.ALL_TIME,
                reportType     = ReportDefinitionReportType.VIDEO_PERFORMANCE_REPORT,
                downloadFormat = DownloadFormat.TSV,
                selector       = new Selector {
                    fields = new string[] {
                        "CreativeId",
                        "VideoId"
                    }
                }
            };
            var utilities = new ReportUtilities(User, ApiVersion, definition);
            var records   = ReportToRecords(utilities, r => new DLM.StructuralVideoPerformance {
                CreativeId    = r.AdID,
                VideoId       = r.VideoId,
                ValidityStart = now,
                ValidityEnd   = DateTime.MaxValue
            });
            var recordsToAdd = records.Where(r => !(from c in dbContext.StructuralVideoPerformanceReports
                                                    where c.VideoId == r.VideoId && c.CreativeId == r.CreativeId &&
                                                    c.ValidityStart <= now && now < c.ValidityEnd
                                                    select c).Any());
            var recordsToUpdate = dbContext.StructuralVideoPerformanceReports.Where(r => r.ValidityStart <= now && now < r.ValidityEnd);

            foreach (var r in recordsToUpdate)
            {
                if (!records.Where(n => n.CreativeId == r.CreativeId && n.VideoId == r.VideoId).Any())
                {
                    r.ValidityEnd = now;
                }
            }

            dbContext.AddRange(recordsToAdd);
            Logger.Debug("Inserted {Count} new records", recordsToAdd.Count());
        }
        /// <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;
            definition.includeZeroImpressions = true;

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

            try {
                ReportUtilities utilities = new ReportUtilities(user, "v201409", 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);
            }
        }
Пример #10
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>
        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);
                }
            }
        }
Пример #12
0
        protected override void Method(DataLakeAdWordsContext dbContext)
        {
            var now        = DateTime.UtcNow;
            var definition = new ReportDefinition {
                reportName     = "Structural CRITERIA_PERFORMANCE_REPORT",
                dateRangeType  = ReportDefinitionDateRangeType.LAST_30_DAYS,
                reportType     = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT,
                downloadFormat = DownloadFormat.TSV,
                selector       = new Selector {
                    fields = new string[] {
                        "Id",
                        "CampaignId",
                        "AdGroupId",
                        "AdGroupName",
                        "Criteria",
                        "CriteriaType",
                        "DisplayName",
                        "IsNegative"
                    }
                }
            };
            var utilities = new ReportUtilities(User, ApiVersion, definition);
            var records   = ReportToRecords(utilities, r => new DLM.StructuralCriteriaPerformance {
                KeywordId     = r.KeywordID,
                CampaignId    = r.CampaignID,
                AdGroupId     = r.AdgroupID,
                AdGroupName   = r.Adgroup,
                Criteria      = r.KeywordPlacement,
                CriteriaType  = r.CriteriaType,
                DisplayName   = r.CriteriaDisplayName,
                IsNegative    = r.Isnegative,
                ValidityEnd   = DateTime.MaxValue,
                ValidityStart = now
            });
            var groupedRecords = records.GroupBy(r => r.AdGroupId);

            Func <IGrouping <string, DLM.StructuralCriteriaPerformance>, bool> shouldAddRecord = record => {
                var lastValid = dbContext.StructuralCriteriaPerformanceReports
                                .Where(r => r.AdGroupId == record.Key && r.ValidityStart <= now && r.ValidityEnd >= now);
                if (!lastValid.Any())
                {
                    return(true);
                }
                if (lastValid.Count() != record.Count())
                {
                    lastValid.ToList().ForEach(r => r.ValidityEnd = now);
                    return(true);
                }
                var lastValidOrdered = OrderCriteriaByAllFields(lastValid);
                var recordOrdered    = OrderCriteriaByAllFields(record);
                var count            = lastValid.Count();
                for (var i = 0; i < count; i++)
                {
                    var o = lastValidOrdered.ElementAt(i);
                    var n = recordOrdered.ElementAt(i);
                    if (!o.Equals(n))
                    {
                        lastValid.ToList().ForEach(r => r.ValidityEnd = now);
                        return(true);
                    }
                }
                return(false);
            };

            var recordsToAdd = groupedRecords.Where(shouldAddRecord).SelectMany(r => r);

            dbContext.AddRange(recordsToAdd);
            Logger.Debug("Inserted {Count} new records", recordsToAdd.Count());
        }
Пример #13
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);
                }
            }
        }
        /// <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);
                }
            }
        }
Пример #15
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());
        }
Пример #16
0
        private FileResult ExportDetailedReport(vmEventManager_DetailedReport report, vmEventManager_EventFilter filter)
        {
            int rowNumber = 0;

            NPOI.SS.UserModel.IRow row;

            //Create new Excel workbook
            var workbook = new HSSFWorkbook();

            //Create new Excel sheet
            int col   = 0;
            var sheet = workbook.CreateSheet();

            sheet.SetColumnWidth(col++, 22 * 256);
            sheet.SetColumnWidth(col++, 22 * 256);
            sheet.SetColumnWidth(col++, 33 * 256);
            sheet.SetColumnWidth(col++, 33 * 256);
            sheet.SetColumnWidth(col++, 33 * 256);
            sheet.SetColumnWidth(col++, 22 * 256);
            sheet.SetColumnWidth(col++, 44 * 256);
            sheet.SetColumnWidth(col++, 44 * 256);
            sheet.SetColumnWidth(col++, 11 * 256);
            sheet.SetColumnWidth(col++, 15 * 256);
            sheet.SetColumnWidth(col++, 15 * 256);
            sheet.SetColumnWidth(col++, 18 * 256);

            var allStyles = ReportUtilities.CreateStyles(workbook);

            ReportUtilities.ExportReportHeader("Detailed Report", sheet, allStyles, ref rowNumber);
            if (filter.EventId != null)
            {
                var thisEvent = _service.GetEventById(filter.EventId.Value);

                row = sheet.CreateRow(rowNumber++);
                ReportUtilities.CreateCell(row, 0, string.Format("{0} - {1}", thisEvent.GeneralLocality, thisEvent.EventDates.Min().DateOfEvent.ToShortDateString()), allStyles.Header2Style);
            }
            sheet.CreateRow(rowNumber++);
            row = sheet.CreateRow(rowNumber++);
            col = 0;
            ReportUtilities.CreateCell(row, col++, "Location", allStyles.TitleStyle);
            ReportUtilities.CreateCell(row, col++, "Start Time", allStyles.TitleStyle);
            ReportUtilities.CreateCell(row, col++, "First Name", allStyles.TitleStyle);
            ReportUtilities.CreateCell(row, col++, "Last Name", allStyles.TitleStyle);
            ReportUtilities.CreateCell(row, col++, "Emergency Contact", allStyles.TitleStyle);
            ReportUtilities.CreateCell(row, col++, "Emergency Phone", allStyles.TitleStyle);
            ReportUtilities.CreateCell(row, col++, "Medical Information", allStyles.TitleStyle);
            ReportUtilities.CreateCell(row, col++, "Special Needs", allStyles.TitleStyle);
            ReportUtilities.CreateCell(row, col++, "Shirt Size", allStyles.TitleStyle);
            ReportUtilities.CreateCell(row, col++, "Agreed Legal", allStyles.TitleStyle);
            ReportUtilities.CreateCell(row, col++, "Agreed Trademark", allStyles.TitleStyle);
            ReportUtilities.CreateCell(row, col++, "ConfirmationCode", allStyles.TitleStyle);

            foreach (var wave in report.WaveData)
            {
                col = 0;
                row = sheet.CreateRow(rowNumber++);
                ReportUtilities.CreateCell(row, col++, report.EventName, allStyles.LeftAligned);
                ReportUtilities.CreateCell(row, col++, wave.StartTime.ToString("MM/dd/yyyy HH:mm"), allStyles.RightAligned);
                ReportUtilities.CreateCell(row, col++, wave.Firstname, allStyles.LeftAligned);
                ReportUtilities.CreateCell(row, col++, wave.Lastname, allStyles.LeftAligned);
                ReportUtilities.CreateCell(row, col++, wave.EmergencyContact, allStyles.LeftAligned);
                ReportUtilities.CreateCell(row, col++, wave.EmergencyPhone, allStyles.LeftAligned);
                ReportUtilities.CreateCell(row, col++, wave.MedicalInformation, allStyles.LeftAligned);
                ReportUtilities.CreateCell(row, col++, wave.SpecialNeeds, allStyles.LeftAligned);
                ReportUtilities.CreateCell(row, col++, wave.ShirtSize, allStyles.LeftAligned);
                ReportUtilities.CreateCell(row, col++, wave.AgreedLegal, allStyles.LeftAligned);
                ReportUtilities.CreateCell(row, col++, wave.AgreedTrademark, allStyles.LeftAligned);
                ReportUtilities.CreateCell(row, col++, wave.ConfirmationCode, allStyles.LeftAligned);
            }

            //Write the workbook to a memory stream
            var output = new MemoryStream();

            workbook.Write(output);

            //Return the result to the end user

            return(File(output.ToArray(),           //The binary data of the XLS file
                        "application/vnd.ms-excel", //MIME type of Excel files
                        "DetailedExport.xls"));     //Suggested file name in the "Save as" dialog which will be displayed to the end user
        }
Пример #17
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();
        }
        /// <summary>
        /// The print appointment confirmations.
        /// </summary>
        /// <param name="confirmationDate">
        /// The confirmation date.
        /// </param>
        /// <param name="officeNum">
        /// The office number.
        /// </param>
        /// <param name="userId">
        /// The user id.
        /// </param>
        /// <returns>
        /// The the result
        /// </returns>
        public ActionResult PrintAppointmentConfirmations(string confirmationDate, string officeNum, int userId)
        {
            var date = DateTime.Parse(confirmationDate);
            var confirmationSummaries = this.appointmentManager.GetAppointmentConfirmations(date, officeNum, userId);

            foreach (var confirmation in confirmationSummaries)
            {
                switch (confirmation.ConfirmationStatus)
                {
                case "Confirmed":
                {
                    confirmation.ConfirmationStatus = "<span style='font-weight:bold'>Confirmed</span>" + "</br>" + "Left Message" + "</br>" + "None" +
                                                      "</br>" + "Not Available";
                    break;
                }

                case "Left Message":
                {
                    confirmation.ConfirmationStatus = "Confirmed" + "</br>" + "<span style='font-weight:bold'>Left Message</span>" + "</br>" + "None" +
                                                      "</br>" + "Not Available";
                    break;
                }

                case "Not Available":
                {
                    confirmation.ConfirmationStatus = "Confirmed" + "</br>" + "Left Message" + "</br>" + "None" + "</br>" + "<span style='font-weight:bold'>Not Available</span>";
                    break;
                }

                case "None":
                {
                    confirmation.ConfirmationStatus = "Confirmed" + "</br>" + "Left Message" + "</br>" + "<span style='font-weight:bold'>None</span>" +
                                                      "</br>" + "Not Available";
                    break;
                }

                default:
                {
                    confirmation.ConfirmationStatus = "Confirmed" + "</br>" + "Left Message" + "</br>" + "<span style='font-weight:bold'>None</span>" +
                                                      "</br>" + "Not Available";
                    break;
                }
                }
            }

            var confirmationsReport = ReportFactory.CreateReportWithManualDispose <AppointmentConfirmationsReport>();

            // This will be disposed after the report is streamed.
            var companyId = OfficeHelper.GetCompanyId(officeNum);

            confirmationsReport.SetDataSource(confirmationSummaries);
            confirmationsReport.SetParameterValue("Date", confirmationDate);
            var util      = new ReportUtilities();
            var outStream =
                (MemoryStream)util.AddLogo(confirmationsReport, confirmationsReport.Section1, 0, companyId, officeNum);

            if (outStream != null)
            {
                this.Response.Clear();
                this.Response.ClearHeaders();
                this.Response.ContentType = "application/pdf";
                this.Response.BinaryWrite(outStream.ToArray());
                this.Response.End();
            }

            ReportFactory.CloseAndDispose(confirmationsReport); // report has been streamed, it is safe to dispose it
            return(null);
        }
Пример #19
0
        protected void get_report(ModuleIdentifier moduleIdentifier, string reportName, bool excel, bool rtl,
                                  bool isPersian, ref Dictionary <string, string> dic, int pageNumber, int pageSize, ref string responseText,
                                  List <ReportParameter> parameters, string password)
        {
            //Privacy Check: OK
            if (!paramsContainer.GBEdit)
            {
                return;
            }

            bool isSystemAdmin =
                PublicMethods.is_system_admin(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID.Value);

            Guid?reportId = ReportUtilities.get_report_id(moduleIdentifier, reportName);

            bool hasAccess = reportId.HasValue && (isSystemAdmin ||
                                                   AuthorizationManager.has_right(AccessRoleName.Reports, paramsContainer.CurrentUserID));

            hasAccess = hasAccess && (isSystemAdmin ||
                                      PrivacyController.check_access(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID,
                                                                     reportId.Value, PrivacyObjectType.Report, PermissionType.View));

            if (!hasAccess)
            {
                responseText = "{\"ErrorText\":\"" + Messages.AccessDenied + "\"}";
                return;
            }

            DataTable tbl     = new DataTable();
            string    actions = string.Empty;

            Dictionary <string, string> columnsDic = new Dictionary <string, string>();

            ReportsController.get_report(paramsContainer.Tenant.Id,
                                         moduleIdentifier, reportName, ref tbl, ref actions, ref columnsDic, parameters);

            int firstRow = excel ? 0 : (pageSize * (pageNumber - 1));
            int lastRow  = (excel ? tbl.Rows.Count : Math.Min(firstRow + pageSize, tbl.Rows.Count)) - 1;

            for (int c = 0; c < tbl.Columns.Count; ++c)
            {
                if (tbl.Columns[c].DataType != typeof(string) || tbl.Columns[c].ColumnName.IndexOf("_HTML") < 0)
                {
                    continue;
                }

                tbl.Columns[c].ColumnName = tbl.Columns[c].ColumnName.Replace("_HTML", string.Empty);

                for (int r = firstRow; r <= lastRow; ++r)
                {
                    if (tbl.Rows[r][c] != DBNull.Value && !string.IsNullOrEmpty((string)tbl.Rows[r][c]))
                    {
                        //tbl.Rows[r][c] = PublicMethods.markup2plaintext(
                        //Expressions.replace((string)tbl.Rows[r][c], Expressions.Patterns.HTMLTag, " ")).Trim();

                        string str = (string)tbl.Rows[r][c];
                        str = Expressions.replace(str, Expressions.Patterns.HTMLTag, " ");
                        str = PublicMethods.markup2plaintext(paramsContainer.Tenant.Id, str).Trim();

                        tbl.Rows[r][c] = str;
                    }
                }
            }

            if (excel)
            {
                try
                {
                    Dictionary <string, bool> usedColNames = new Dictionary <string, bool>();

                    foreach (string n in dic.Values)
                    {
                        usedColNames[n] = true;
                    }

                    for (int c = 0; c < tbl.Columns.Count; ++c)
                    {
                        if (columnsDic.ContainsKey(tbl.Columns[c].ColumnName))
                        {
                            string colName = columnsDic[tbl.Columns[c].ColumnName];
                            int    num     = 1;
                            while (true)
                            {
                                string tmpName = colName + (num <= 1 ? string.Empty : " (" + num.ToString() + ")");

                                if (!usedColNames.ContainsKey(tmpName))
                                {
                                    usedColNames[tmpName] = true;
                                    colName = tmpName;
                                    break;
                                }
                                else
                                {
                                    ++num;
                                }
                            }

                            tbl.Columns[c].ColumnName = colName;
                        }

                        bool isString = tbl.Columns[c].DataType == typeof(string);
                        bool isDic    = tbl.Columns[c].ColumnName.IndexOf("_Dic") >= 0;

                        if (isString && isDic)
                        {
                            Dictionary <string, string> colDic = _get_dictionary(tbl.Columns[c].ColumnName);

                            for (int r = 0; r < tbl.Rows.Count; ++r)
                            {
                                bool isNull = tbl.Rows[r].ItemArray[c] == DBNull.Value || tbl.Rows[r].ItemArray[c] == null;

                                if (!isNull && colDic.ContainsKey((string)tbl.Rows[r].ItemArray[c]))
                                {
                                    tbl.Rows[r][c] = colDic[(string)tbl.Rows[r].ItemArray[c]];
                                }
                            }
                        }

                        if (isDic)
                        {
                            tbl.Columns[c].ColumnName = tbl.Columns[c].ColumnName.Replace("_Dic", string.Empty);
                        }
                    }

                    //meta data for exported file
                    Privacy p = !reportId.HasValue ? null :
                                PrivacyController.get_settings(paramsContainer.Tenant.Id, reportId.Value);
                    string confidentiality = p == null ? null : p.Confidentiality.Title;

                    User currentUser = !paramsContainer.CurrentUserID.HasValue ? null :
                                       UsersController.get_user(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID.Value);
                    if (currentUser == null)
                    {
                        currentUser = new User();
                    }
                    DownloadedFileMeta meta = new DownloadedFileMeta(PublicMethods.get_client_ip(HttpContext.Current),
                                                                     currentUser.UserName, currentUser.FirstName, currentUser.LastName, confidentiality);
                    //end of meta data for exported file

                    string reportFileName = "Reports_" + PublicMethods.get_random_number().ToString();

                    ExcelUtilities.ExportToExcel(reportFileName, tbl, rtl, dic, password, meta);
                }
                catch (Exception ex)
                {
                    responseText = "{\"ErrorText\":\"" + Messages.OperationFailed + "\"}";

                    LogController.save_error_log(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID,
                                                 "ExportReportToExcel", ex, ModuleIdentifier.RPT, LogLevel.Fatal);
                }

                return;
            }

            Dictionary <string, bool> isFloatDic = new Dictionary <string, bool>();

            responseText = "{\"Columns\":[";

            for (int i = 0, lnt = tbl.Columns.Count; i < lnt; ++i)
            {
                object obj = null;
                for (int j = firstRow; j <= lastRow; ++j)
                {
                    if (tbl.Rows[j][i] != DBNull.Value && tbl.Rows[j][i] != null && !string.IsNullOrEmpty(tbl.Rows[j][i].ToString()))
                    {
                        obj = tbl.Rows[j][i];
                        break;
                    }
                }

                bool isNumber = false;
                bool isFloat  = false;
                if (obj != null)
                {
                    var objType = obj.GetType();
                    isNumber = objType == typeof(int) || objType == typeof(long) ||
                               objType == typeof(float) || objType == typeof(double) || objType == typeof(decimal);
                    isFloat = objType == typeof(float) || objType == typeof(double) || objType == typeof(decimal);
                }

                isFloatDic.Add(tbl.Columns[i].ColumnName, isFloat);

                string colTitle = columnsDic.ContainsKey(tbl.Columns[i].ColumnName) ?
                                  columnsDic[tbl.Columns[i].ColumnName] : tbl.Columns[i].ColumnName;

                responseText += (i == 0 ? string.Empty : ",") + "{\"ID\":\"" + tbl.Columns[i].ColumnName +
                                "\",\"Title\":\"" + Base64.encode(colTitle) + "\",\"Encoded\":true" +
                                ",\"IsNumber\":" + isNumber.ToString().ToLower() + "}";
            }

            responseText += "],\"Total\":" + tbl.Rows.Count.ToString() + ",\"Rows\":[";

            for (int i = firstRow; i <= lastRow; ++i)
            {
                responseText += (i == firstRow ? string.Empty : ",") + "{";
                for (int j = 0, _ln = tbl.Columns.Count; j < _ln; ++j)
                {
                    if (isFloatDic[tbl.Columns[j].ColumnName])
                    {
                        tbl.Rows[i].ItemArray[j] =
                            Math.Round(double.Parse((tbl.Rows[i].ItemArray[j] == DBNull.Value ? 0 : tbl.Rows[i].ItemArray[j]).ToString()), 2);
                    }

                    string strVal = tbl.Rows[i].ItemArray[j].GetType() == typeof(DateTime) ?
                                    PublicMethods.get_local_date((DateTime)tbl.Rows[i].ItemArray[j], true) :
                                    (isFloatDic[tbl.Columns[j].ColumnName] ?
                                     Math.Round(double.Parse((tbl.Rows[i].ItemArray[j] == DBNull.Value ? 0 : tbl.Rows[i].ItemArray[j]).ToString()), 2) :
                                     tbl.Rows[i].ItemArray[j]).ToString();

                    responseText += (j == 0 ? string.Empty : ",") + "\"" + tbl.Columns[j].ColumnName + "\":\"" + Base64.encode(strVal) + "\"";
                }
                responseText += "}";
            }

            responseText += "],\"Actions\":" + (string.IsNullOrEmpty(actions) ? "{}" : actions) + "}";
        }
Пример #20
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);
                    }
                }
        }
Пример #21
0
        /// <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(string p_user, string p_repName, string[] p_fields)
        {
            AdWordsUser user = new AdWordsUser();

            ((AdWordsAppConfig)user.Config).ClientCustomerId = p_user;

            ReportDefinition definition = new ReportDefinition();

            definition.reportName     = "Nov2013_ " + p_repName;
            definition.reportType     = (ReportDefinitionReportType)Enum.Parse(typeof(ReportDefinitionReportType), p_repName);
            definition.downloadFormat = DownloadFormat.GZIPPED_CSV;
            definition.dateRangeType  = ReportDefinitionDateRangeType.CUSTOM_DATE;



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

            selector.dateRange = new Google.Api.Ads.AdWords.v201309.DateRange();
            string start = string.Format("{0:yyyy-MM-dd}", "2013-11-01");

            start = start.Replace("-", "");
            selector.dateRange.min = start;

            string end = string.Format("{0:yyyy-MM-dd}", "2013-11-30");

            end = end.Replace("-", "");
            selector.dateRange.max = end;



            selector.fields = p_fields;

/*
 *    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 + p_repName +"_"+p_user+ ".GZ";
            string filePath = "C:\\TEMP\\GOOGLE" + Path.DirectorySeparatorChar + p_repName + "_" + p_user + ".GZ";

            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, false, filePath);
                Console.WriteLine("Report was downloaded to '{0}'.", filePath);
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to download report.", ex);
            }
        }
        /// <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>
        /// 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);
            }
        }