Exemplo n.º 1
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (ReportService reportService = user.GetService <ReportService>())
            {
                // Set the file path where the report will be saved.
                String filePath = _T("INSERT_FILE_PATH_HERE");

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

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

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

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

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

                    Console.WriteLine("Report saved to \"{0}\".", filePath);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to run sales report. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Create the query.
            ReportQuery query = new ReportQueryBuilder()
                                .Select("Id", "AdNetworkType1", "Impressions")
                                .From(ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT)
                                .Where("Status").In("ENABLED", "PAUSED")
                                .During(ReportDefinitionDateRangeType.LAST_7_DAYS)
                                .Build();

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

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

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

                                    break;
                                }
                            }
                        }
                    }
                }

                Console.WriteLine("Network, Impressions");
                foreach (string network in impressionsByAdNetworkType1.Keys)
                {
                    Console.WriteLine("{0}, {1}", network, impressionsByAdNetworkType1[network]);
                }
            }
            catch (Exception e)
            {
                throw new System.ApplicationException("Failed to download report.", e);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Create the query.
            string query =
                "SELECT Id, AdNetworkType1, Impressions FROM CRITERIA_PERFORMANCE_REPORT " +
                "WHERE Status IN [ENABLED, PAUSED] DURING LAST_7_DAYS";

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

            try
            {
                using (ReportResponse response = reportUtilities.GetResponse())
                {
                    using (GZipStream gzipStream =
                               new GZipStream(response.Stream, CompressionMode.Decompress))
                    {
                        // Deserialize the report into a list of CriteriaReportRow.
                        // You can also deserialize the list into your own POCOs as follows.
                        // 1. Annotate your class properties with ReportRow annotation.
                        //
                        //  public class MyCriteriaReportRow {
                        //
                        //    [ReportColumn]
                        //    public long KeywordID { get; set; }
                        //
                        //    [ReportColumn]
                        //    public long Impressions { get; set; }
                        //  }
                        //
                        // 2. Deserialize into your own report rows.
                        //
                        // var report = new AwReport<MyCriteriaReportRow>(
                        //                new AwXmlTextReader(gzipStream), "Example");
                        using (var report =
                                   new AwReport <CriteriaReportRow>(new AwXmlTextReader(gzipStream),
                                                                    "Example"))
                        {
                            // Print the contents of each row object.
                            foreach (var record in report.Rows)
                            {
                                Console.WriteLine(record);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new System.ApplicationException("Failed to download and parse report.", e);
            }
        }
Exemplo n.º 4
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.v201505.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();
        }
        public GADCustomReport Get(GADCustomReportInitializer initializer)
        {
            GCommonCredentialsExtended cred   = (GCommonCredentialsExtended)(new GCommonCredentialManager <GRestUserCredentialReceiver, GRestUserCredentialInitializer>().Get(new GRestUserCredentialInitializer(initializer.Config.CredentialsJsonPath, null)));
            AdWordsAppConfig           config = new AdWordsAppConfig();

            config.DeveloperToken = initializer.Config.DeveloperToken;

            AdWordsUser user = new AdWordsUser(config);

            user.Config.OAuth2RefreshToken = cred.RefreshToken;
            user.Config.OAuth2AccessToken  = cred.AccessToken;
            user.Config.OAuth2ClientId     = cred.ClientId;
            user.Config.OAuth2ClientSecret = cred.ClientSecret;



            config.ClientCustomerId = initializer.Account.Id;
            // Create the required service.

            ReportQuery query = new ReportQueryBuilder()
                                .Select(initializer.Columns.Select(x => x.Value.Name).ToArray())
                                .From(initializer.Type.Name)
                                .During(initializer.DateStart, initializer.DateEnd)
                                .Build();
            ReportUtilities utilities = new ReportUtilities(user, "v201809", query,
                                                            DownloadFormat.XML.ToString());
            string xmlResult;

            using (ReportResponse response = utilities.GetResponse())
            {
                using (var sr = new StreamReader(response.Stream))
                {
                    xmlResult = sr.ReadToEnd();
                }
            }
            XmlSerializer           serializer = new XmlSerializer(typeof(XML201809ReportResponse));
            XML201809ReportResponse xmlReport;

            using (TextReader tr = new StringReader(xmlResult))
            {
                xmlReport = (XML201809ReportResponse)serializer.Deserialize(tr);
            }
            GADCustomReport report = new GADCustomReport(initializer);

            report.Rows = xmlReport.Table.Row.Select(x => new CustomReportRow(
                                                         ((XmlNode[])x)
                                                         .Where(t => initializer.AlterColumns.ContainsKey(t.Name.ToLower()))
                                                         .Select(t => new CustomReportCell(initializer.AlterColumns[t.Name.ToLower()], t.Value)).ToArray()
                                                         )
                                                     ).ToArray();
            return(report);
        }
Exemplo n.º 6
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.v201502.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 };
            reportJob.reportQuery.dateRangeType = DateRangeType.LAST_MONTH;
            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 ex) {
                Console.WriteLine("Failed to run delivery report. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
        public ActionResult ReviewReport(ReportResponse model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var reportManager = new ReportManager(model.TaskId, model.ReportId, model.ProjectId);

            reportManager.CreateReportResponse(model);

            return(RedirectToAction("Index"));
        }
Exemplo n.º 8
0
        public void TestGetStream()
        {
            ReportResponse response = new ReportResponse(webResponse);

            using (MemoryStream stream = new MemoryStream())
                using (StreamWriter writer = new StreamWriter(stream)) {
                    writer.Write(FILE_CONTENTS);
                    writer.Flush();
                    stream.Position = 0;

                    FileAssert.AreEqual(stream, response.Stream, "Streams do not match");
                }
        }
Exemplo n.º 9
0
        public void getReport()
        {
            // Arrange
            Repository     oRepo     = new Repository();
            ReportResponse response  = new ReportResponse();
            int            idService = 2;

            // Act
            response = oRepo.getReporte(idService);

            // Assert
            Assert.AreEqual(true, response.success);
        }
Exemplo n.º 10
0
        public ReportResponse GetRepoersByType(ReportRequest request)
        {
            ReportResponse response = new ReportResponse();

            Query query = new Query("Report");

            query.AddCriterion("Type", request.ReportType, CriteriaOperator.Equal);
            IEnumerable <Report> reports = reportRepository.FindBy(query);

            response.Reports = reports;

            return(response);
        }
        public ServiceResult <List <ReportItem> > GetReports(string smsReferenceNo)
        {
            ServiceResult <List <ReportItem> > result = new ServiceResult <List <ReportItem> >();

            ReportRequest  reportRequest  = new ReportRequest(_userName, _password, smsReferenceNo);
            ReportResponse reportResponse = Post <ReportResponse>("http://api.mesajpaneli.com/json_api/report", reportRequest);

            if (reportResponse == null)
            {
                result.Success = false;
                result.Message = "Cannot get any response from service.";
            }
            else if (!reportResponse.Success || reportResponse.Data == null || reportResponse.Data.ReportDetailItemContainer == null)
            {
                result.Success = false;
                result.Message = String.Format("There is a problem with the service response. Check the response string for more information: {0}", reportResponse.ResponseString);
            }
            else if (!String.IsNullOrEmpty(reportResponse.Data.ErrorMessage))
            {
                result.Success = false;
                result.Message = reportResponse.Data.ErrorMessage;
            }
            else
            {
                result.Success = true;
                result.Data    = new List <ReportItem>();

                List <ReportItem> waitingRequests    = GetWaitingReportItemsFromNumbers(reportResponse.Data.ReportDetailItemContainer.WaitingNumberReportDetailItems);
                List <ReportItem> successfulRequests = GetReportItemsFromReportDetailItems(reportResponse.Data.ReportDetailItemContainer.SentNumberReportDetailItems, MessageStatusEnum.Success);
                List <ReportItem> failedRequests     = GetReportItemsFromReportDetailItems(reportResponse.Data.ReportDetailItemContainer.FailedNumberReportDetailItems, MessageStatusEnum.Failed);

                if (waitingRequests != null && waitingRequests.Any())
                {
                    result.Data.AddRange(waitingRequests);
                }

                if (successfulRequests != null && successfulRequests.Any())
                {
                    result.Data.AddRange(successfulRequests);
                }

                if (failedRequests != null && failedRequests.Any())
                {
                    result.Data.AddRange(failedRequests);
                }

                return(result);
            }

            return(result);
        }
Exemplo n.º 12
0
 private void OnReportCreated(ReportResponse responseData)
 {
     if (ReportCreated != null)
     {
         foreach (Action <ReportResponse> handler in ReportCreated.GetInvocationList())
         {
             handler(responseData);
         }
     }
     else
     {
         //throw ERROR: no subscribers
     }
 }
 /// <summary>Snippet for Report</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void ReportRequestObject()
 {
     // Create client
     ServiceControllerClient serviceControllerClient = ServiceControllerClient.Create();
     // Initialize request argument(s)
     ReportRequest request = new ReportRequest
     {
         ServiceName     = "",
         Operations      = { new Operation(), },
         ServiceConfigId = "",
     };
     // Make the request
     ReportResponse response = serviceControllerClient.Report(request);
 }
Exemplo n.º 14
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Create the query.
            string query =
                "SELECT Id, AdNetworkType1, Impressions FROM CRITERIA_PERFORMANCE_REPORT " +
                "WHERE Status IN [ENABLED, PAUSED] DURING LAST_7_DAYS";

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

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

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

                                    break;
                                }
                            }
                        }
                    }
                }

                Console.WriteLine("Network, Impressions");
                foreach (string network in impressionsByAdNetworkType1.Keys)
                {
                    Console.WriteLine("{0}, {1}", network, impressionsByAdNetworkType1[network]);
                }
            }
            catch (Exception e)
            {
                throw new System.ApplicationException("Failed to download report.", e);
            }
        }
Exemplo n.º 15
0
        private static List <ReportResponse> GetData()
        {
            var responses = new List <ReportResponse>();

            foreach (ulong key in TrackedFiles[0xEB])
            {
                var reportResponse = new ReportResponse(key);
                if (reportResponse.GUID != 0)
                {
                    responses.Add(reportResponse);
                }
            }

            return(responses);
        }
        private void FillColumns <T>(ReportResponse response)
        {
            var type       = typeof(T);
            var properties = type.GetTypeInfo().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy)
                             .Where(property => property.GetCustomAttribute <DataMemberAttribute>() != null);

            response.Columns = properties
                               .Select(property =>
                                       new WebApiColumnSchema()
            {
                DbType = DbTypeForProperty(property),
                Name   = NameForProperty(property)
            })
                               .ToArray();
        }
Exemplo n.º 17
0
        public static string GetReportName(string reportTypeId)
        {
            ReportRequest request = new ReportRequest
            {
                ReportType = int.Parse(reportTypeId)
            };
            ReportService  service  = new ReportService();
            ReportResponse response = service.GetRepoersByType(request);

            IEnumerable <ReportNameView> reportName = response.Reports.ConvertToReportNameViews();

            string result = JsonHelper.ObjectToJson(reportName);

            return(result);
        }
Exemplo n.º 18
0
        /// <summary>Snippet for ReportAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task ReportRequestObjectAsync()
        {
            // Create client
            ServiceControllerClient serviceControllerClient = await ServiceControllerClient.CreateAsync();

            // Initialize request argument(s)
            ReportRequest request = new ReportRequest
            {
                ServiceName     = "",
                Operations      = { new Operation(), },
                ServiceConfigId = "",
            };
            // Make the request
            ReportResponse response = await serviceControllerClient.ReportAsync(request);
        }
Exemplo n.º 19
0
        public ReportResponse Convert(Report source)
        {
            if (source == null)
            {
                return(null);
            }

            var result = new ReportResponse
            {
                IsValid    = source.IsValid(),
                PersonId   = source.PersonId,
                TotalHours = source.GetTotalHours()
            };

            return(result);
        }
Exemplo n.º 20
0
 private static void CreateMainTableColumbs(ReportResponse result)
 {
     result.Columns = new List <Column>
     {
         new Column("col0", "Номер Задачи", "number"),
         new Column("col1", "Статус", "string"),
         new Column("col2", "Тип", "string"),
         new Column("col3", "Состав", "string"),
         new Column("col4", "Вагон", "string"),
         new Column("col5", "Оборудование", "string"),
         new Column("col6", "Кол-во неисправностей", "number"),
         new Column("col7", "Инициатор", "string"),
         new Column("col8", "Дата", "date"),
         new Column("col9", "Переоткрыто раз", "number")
     };
 }
        /// <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);
                }
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Gets the seed keywords from a Search Query Report.
        /// </summary>
        /// <param name="user">The user for which reports are run.</param>
        /// <param name="campaignId">ID of the campaign for which we are generating
        ///  keyword ideas.</param>
        /// <returns>A list of seed keywords from SQR, to be used for getting
        /// further keyword ideas.</returns>
        private List <SeedKeyword> GetSeedKeywordsFromQueryReport(AdWordsUser user, long campaignId)
        {
            string query = string.Format("Select Query, MatchTypeWithVariant, Clicks, Impressions " +
                                         "from SEARCH_QUERY_PERFORMANCE_REPORT where CampaignId = {0} during LAST_MONTH",
                                         campaignId);

            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            config.SkipReportHeader  = true;
            config.SkipReportSummary = true;

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

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

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

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

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

            LimitResults(retval, Settings.SQR_MAX_RESULTS);
            return(retval);
        }
Exemplo n.º 23
0
        public async Task <ActionResult> GetAsync()
        {
            var humanReport = await _mediator.Send(new StatsQuery());

            var response = new ReportResponse()
            {
                CountHumanDna  = 0,
                Ratio          = 0,
                CountMutantDna = 0
            };

            if (humanReport != null)
            {
                response = humanReport.Adapt <ReportResponse>();
            }
            return(new OkObjectResult(response));
        }
Exemplo n.º 24
0
        public async Task <ReportResponse> GetLightReportListAsync(string nameLike = null)
        {
            var reportsQueryable =
                GetReportQueryable(withIncludes: false, nameLike)
                .TagWith(QueryTag("Report list light"))
                .OrderBy(r => r.ReportId)
                .Skip(Constants.DEFAULT_SKIP)
                .Take(Constants.DEFAULT_TAKE);

            var reports = await reportsQueryable.ToListAsync();

            var reportsDto = Mapper.Map <List <ReportListItemDto> >(reports);

            var result = new ReportResponse(reportsDto.Count, Serialize(reportsDto));

            return(result);
        }
            /// <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, "v201809", 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);
                }
            }
Exemplo n.º 26
0
 public void ReportSpeedAsync(string host, SpeedData data, Action <ReportResponse> callback)
 {
     Task.Factory.StartNew(() => {
         TimeSpan timeSpan = TimeSpan.FromSeconds(3);
         try {
             using (HttpClient client = RpcRoot.Create()) {
                 // 可能超过3秒钟,查查原因。因为我的网络不稳经常断线。
                 client.Timeout = timeSpan;
                 Task <HttpResponseMessage> getHttpResponse = client.PostAsJsonAsync($"http://{host}:{NTKeyword.ControlCenterPort.ToString()}/api/{SControllerName}/{nameof(IReportController.ReportSpeed)}", data);
                 ReportResponse response = getHttpResponse.Result.Content.ReadAsAsync <ReportResponse>().Result;
                 callback?.Invoke(response);
             }
         }
         catch (Exception e) {
             Write.DevException(e);
         }
     });
 }
Exemplo n.º 27
0
 private static void CreateMainTableColumbs(ReportResponse result)
 {
     result.Columns = new List <Column>
     {
         new Column("col0", "Номер", "number"),
         new Column("col1", "Статус", "string"),
         new Column("col2", "Тип", "string"),
         new Column("col3", "Состав", "string"),
         new Column("col4", "Инициатор", "string"),
         new Column("col5", "Исполнитель", "string"),
         new Column("col6", "Дата", "date"),
         new Column("col7", "Вагон", "string"),
         new Column("col8", "Оборудование", "string"),
         new Column("col9", "Типовая неисправность", "string"),
         new Column("col10", "Обновлено", "date"),
         new Column("col11", "Обновил", "string"),
     };
 }
        protected ReportResponse Export(ReportRequest request)
        {
            ReportResponse response = new ReportResponse();

            try
            {
                ReportExecuteResult result = new ReportExecuteResult();
                this.LoadReport(request, ref result);
                this.Render(request, ref result, null);
                response.Data = this.SetData(result, true);
            }
            catch (System.Exception ex)
            {
                response.Status  = 1;
                response.Message = ex.Message;
            }
            return(response);
        }
Exemplo n.º 29
0
        public void CheckReportResponseIsParsed()
        {
            dynamic reportResponse = new
            {
                recommendation = GetRecommendationResponse(),
                breakdown      = new List <dynamic>
                {
                    GetBreakdownResponse()
                }
            };

            string         json     = JsonConvert.SerializeObject(reportResponse);
            ReportResponse response =
                JsonConvert.DeserializeObject <ReportResponse>(json);

            AssertRecommendationResponseValuesCorrect(reportResponse.recommendation, response.Recommendation);
            AssertBreakdownResponseValuesCorrect((reportResponse.breakdown as IEnumerable <dynamic>).First(), response.Breakdown.First());
        }
Exemplo n.º 30
0
        public static ReportResponse Create(ReportRequest request, string detail, string message, StatusCode code)
        {
            var responseStatus = new ResponseStatus()
            {
                Detail     = detail,
                Message    = message,
                StatusCode = code
            };

            var response = new ReportResponse()
            {
                RequestData = request,
                Status      = responseStatus
            };


            return(response);
        }