public async Task <ChartDto> GetCheckoutsByDayReport()
        {
            var data = await _context.Checkouts.AsNoTracking()
                       .Where(d => d.Since > DateTime.Today.AddDays(-7))
                       .GroupBy(d => new { Date = d.Since })
                       .Select(x => new DataDto
            {
                Count = x.Count(),
                Date  = x.Key.Date,
                Day   = x.Key.Date.DayOfWeek,
                Name  = x.Key.Date.ToString("ddd")
            })
                       .ToListAsync();

            var days = GetDays(30);

            data = ParseData(7, data);

            var chartData = new ChartDto()
            {
                Data  = data,
                Label = "Checkouts"
            };

            return(chartData);
        }
        public ChartDto PassengersByPrivileges(DateTime startPeriod, DateTime endPeriod, int[] selectedRoutes)
        {
            if (startPeriod.CompareTo(endPeriod) == 1)
            {
                return(new ChartDto()
                {
                    ErrorMessage = EndLessStartError
                });
            }

            var data = uow.TicketVerifications.GetAll()
                       .Where(d => d.VerificationUTCDate >= startPeriod && d.VerificationUTCDate <= endPeriod && d.IsVerified &&
                              (selectedRoutes.Length == 0 || selectedRoutes.Contains(d.Transport.RouteId)))
                       .Include(t => t.Ticket)
                       .ThenInclude(u => u.User)
                       .ThenInclude(p => p.Privilege)
                       .Select(n => n.Ticket.User.Privilege)
                       .GroupBy(p => p.Name)
                       .Select(g => new { name = g.Key ?? "No privilege", count = g.Count().ToString() })
                       .ToDictionary(k => k.name, k => k.count);


            var chartDto = new ChartDto {
                Labels = data.Keys.ToArray(), Data = data.Values.ToArray()
            };

            return(chartDto);
        }
        public ChartDto GetReport(int reportTypeId)
        {
            var result = new ChartDto();
            var data   = new List <DataPointDto>();

            switch (reportTypeId)
            {
            case (int)ReportType.EmployeesByPositions:
                data = GetEmployeesByPosition();
                break;

            case (int)ReportType.ProjectAssignedEmployees:
                data = GetProjectAssignedEmployees();
                break;

            default:
                result = null;
                break;
            }

            if (result != null)
            {
                result.Data       = JsonConvert.SerializeObject(data);
                result.ChartTitle = GetReportName(reportTypeId);
            }

            return(result);
        }
        public AbstractChartDto ParseChart(string p_chartData)
        {
            AbstractChartDto chart = new ChartDto();

            chart.Type = ChartType.Shazam;
            chart.Name = "Shazam 100 " + DateTime.Now.ToString("MM-dd-yyyy");
            chart.Uid  = "Shazam-100-" + DateTime.Now.ToString("MM-dd-yyyy");
            chart.Date = DateTime.Now;


            JObject ojson = JObject.Parse(p_chartData);

            int charPosCounter = 1;

            foreach (var chartItem in ojson["chart"])
            {
                AbstractChartSongDto _song = new ChartSongDto();
                _song.Name     = chartItem["heading"]["title"].ToString();
                _song.Artist   = chartItem["heading"]["subtitle"].ToString();
                _song.Position = charPosCounter;


                chart.SongsList.Add(_song);
                chart.SongNum += 1;


                charPosCounter += 1;
            }



            return(chart);
        }
        public void GenerateHistogram(ChartDto chartDto)
        {
            if (chartDto == null)
            {
                return;
            }

            currentChartDto = chartDto;

            Action <string, string> exec = (s, s1) =>
            {
                ChartsListFormViewModel.Instance.ChartsDtoList = StatistiquesBLL.Current.GetChartsDtoList(); //Permet de remettre à jour le graphique
            };

            var progressWindow = new ProgressWindow();

            progressWindow.SetTitle("Chargement en cours");
            var backgroundWorker = new BackgroundWorker();

            // set the worker to call your long-running method
            backgroundWorker.DoWork += (object sender, DoWorkEventArgs e) =>
            {
                exec.Invoke("path", "parameters");
            };

            // set the worker to close your progress form when it's completed
            backgroundWorker.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
            {
                progressWindow.Close();
            };
            progressWindow.Show();
            backgroundWorker.RunWorkerAsync();

            SeriesCollection = chartDto.SeriesCollection;

            ChartTitle = chartDto.ChartTitle;
            TitleXAxis = chartDto.TitleXAxis;
            TitleYAxis = chartDto.TitleYAxis;
            Labels     = chartDto.Labels.ToArray();
            Formatter  = value => value.ToString("N");

            SeriesCollection = new SeriesCollection();
            foreach (var chartDtoValue in chartDto.Values)
            {
                SeriesCollection.Add(new PieSeries
                {
                    Title  = chartDtoValue.SerieTitle,
                    Values = new ChartValues <int> {
                        chartDtoValue.Count
                    },
                    DataLabels = true,
                    LabelPoint = chartPoint =>
                                 string.Format("{0} ({1:P})", chartPoint.Y, chartPoint.Participation)
                });
            }
        }
Exemple #6
0
 public void Initialize(ChartDto Data)
 {
     this.Data   = Data;
     BilibiliUrl = string.Format("{0}av{1}", LimChartZoneManager.BilibiliVideoPrefix, Data.BilibiliAvIndex.ToString());
     StartCoroutine(GetBilibiliQrCode());
     OnlineRating       = (float)Data.AvgRating;
     RatingSlider.value = OnlineRating;
     UserRating         = Data.UsrRating;
     ChartNameText.text = Data.ChartName;
     DesignerText.text  = Data.Designer;
     NoteCountText.text = Data.NoteCount.ToString();
     SizeText.text      = Data.Size;
     _IsInitialized     = true;
 }
        public async Task <IActionResult> Chart(string chart_guid)
        {
            if (String.IsNullOrEmpty(chart_guid))
            {
                return(View(new UnknownChartDto()));
            }

            AbstractChartDto modelChart = new ChartDto();

            modelChart = await _chartManager.GetByUid(chart_guid);

            await _chartManager.AddView(modelChart.Id);

            return(View(modelChart));
        }
Exemple #8
0
        //chart-details
        public AbstractChartDto ParseChart(string p_chartData)
        {
            AbstractChartDto chart = new ChartDto();

            chart.Type = ChartType.YouTube;
            chart.Name = "Top Songs 100 " + DateTime.Now.ToString("MM-dd-yyyy");
            chart.Uid  = "Top-Songs-100-" + DateTime.Now.ToString("MM-dd-yyyy");
            chart.Date = DateTime.Now;


            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(p_chartData);


            IEnumerable <HtmlAgilityPack.HtmlNode> currNodeItems = doc.DocumentNode.SelectNodes("//*[contains(@class,'chart-list-item')]");


            string node_html      = "";
            int    charPosCounter = 1;

            foreach (var item in currNodeItems)
            {
                string dataRank   = string.Empty;
                string dataArtist = string.Empty;
                string dataTitle  = string.Empty;

                if (item.Attributes["data-rank"] != null && item.Attributes["data-artist"] != null && item.Attributes["data-title"] != null)
                {
                    dataRank   = item.Attributes["data-rank"].Value.ToString();
                    dataArtist = item.Attributes["data-artist"].Value.ToString();
                    dataTitle  = item.Attributes["data-title"].Value.ToString();


                    ChartSongDto _song = new ChartSongDto();
                    _song.Name     = dataTitle.Replace("\\n", "").Trim();
                    _song.Artist   = dataArtist.Replace("\\n", "").Trim();
                    _song.Position = charPosCounter;


                    chart.SongsList.Add(_song);
                    chart.SongNum += 1;

                    charPosCounter += 1;
                }
            }

            return(chart);
        }
Exemple #9
0
        private ChartDto GetComplexChartDto(List <IncomeReport> incomes, List <ConsumptionReport> consumptions)
        {
            var model = new ChartDto();

            var dates = incomes.Select(x => x.Date).Union(consumptions.Select(x => x.Date)).Distinct().OrderBy(x => x).ToList();

            model.Labels = dates.Select(x => x.ToString("MMM yyyy")).ToArray();

            var series = new List <SeriesDto>();

            var incomePoints = new List <Decimal>();
            var incomeReport = incomes
                               .GroupBy(x => x.Date)
                               .ToDictionary(x => x.Key, x => x.Sum(y => y.Sum));

            foreach (var date in dates)
            {
                var sum = incomeReport.ContainsKey(date) ? incomeReport[date] : 0;
                incomePoints.Add(sum);
            }

            series.Add(new SeriesDto()
            {
                Name   = "Доходы",
                Points = incomePoints.ToArray()
            });

            var consumptionPoints = new List <Decimal>();
            var consumptionReport = consumptions
                                    .GroupBy(x => x.Date)
                                    .ToDictionary(x => x.Key, x => x.Sum(y => y.Sum));

            foreach (var date in dates)
            {
                var sum = consumptionReport.ContainsKey(date) ? consumptionReport[date] : 0;
                consumptionPoints.Add(sum);
            }

            series.Add(new SeriesDto()
            {
                Name   = "Расходы",
                Points = consumptionPoints.ToArray()
            });

            model.Series = series.ToArray();

            return(model);
        }
        public IActionResult PassengersByTime(DateTime startPeriod, DateTime endPeriod, ChartScale scale)
        {
            log.Info(nameof(MetricsController.PassengersByTime));

            try
            {
                ChartDto chartDto = metricsService.PassengersByTime(startPeriod, endPeriod, scale);

                return(Json(chartDto));
            }
            catch (Exception e)
            {
                log.Error(e);

                return(BadRequest());
            }
        }
        public IActionResult GetPassengersByDaysOfWeek(DateTime startPeriod, DateTime endPeriod)
        {
            log.Info(nameof(MetricsController.GetPassengersByDaysOfWeek));

            try
            {
                ChartDto chartDtoTicketsByTicketTypes = metricsService.PassengersByDaysOfWeek(startPeriod, endPeriod);

                return(Json(chartDtoTicketsByTicketTypes));
            }
            catch (Exception e)
            {
                log.Error(e);

                return(BadRequest());
            }
        }
Exemple #12
0
        //chart-details

        public AbstractChartDto ParseChart(string p_chartData)
        {
            AbstractChartDto chart = new ChartDto();

            chart.Type = ChartType.Billboard;
            chart.Name = "Billboard Hot 100 " + DateTime.Now.ToString("MM-dd-yyyy");
            chart.Uid  = "Billboard-Hot-100-" + DateTime.Now.ToString("MM-dd-yyyy");
            chart.Date = DateTime.Now;


            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(p_chartData);


            IEnumerable <HtmlAgilityPack.HtmlNode> currNodeItems = doc.DocumentNode.SelectNodes("//li[@class='chart-list__element display--flex']");
            //"//*[contains(@class,'chart-list-item')]");


            string node_html      = "";
            int    charPosCounter = 1;

            foreach (var item in currNodeItems)
            {
                node_html = item.InnerHtml;

                HtmlAgilityPack.HtmlDocument itemNode = new HtmlAgilityPack.HtmlDocument();
                itemNode.LoadHtml(node_html);

                HtmlAgilityPack.HtmlNode currNodeSongName   = itemNode.DocumentNode.SelectSingleNode("//span[@class='chart-element__information__song text--truncate color--primary']");
                HtmlAgilityPack.HtmlNode currNodeArtistName = itemNode.DocumentNode.SelectSingleNode("//span[@class='chart-element__information__artist text--truncate color--secondary']");


                AbstractChartSongDto _song = new ChartSongDto();
                _song.Name     = currNodeSongName.InnerText.Replace("\\n", "").Trim();
                _song.Artist   = currNodeArtistName.InnerText.Replace("\\n", "").Trim();
                _song.Position = charPosCounter;


                chart.SongsList.Add(_song);
                chart.SongNum += 1;

                charPosCounter += 1;
            }

            return(chart);
        }
        public async Task <ActionResult <List <ChartDto> > > GetChartDataAsync()
        {
            IEnumerable <ChartDto> list = Enumerable.Empty <ChartDto>();

            byte[] bytes = await _distributedCache.GetAsync("chartData");

            if (bytes == null)
            {
                var orders = await _repositoryWrapper.OrderRepository.GetAllAsync();

                List <ChartDto> chartDtos = new List <ChartDto>();

                foreach (var item in orders.Where(m => m.Status != 4).ToList())
                {
                    ChartDto chartDto = new ChartDto();
                    var      product  = await _repositoryWrapper.ProductRepository.GetByIdAsync(item.ProductId);

                    var cate = await _repositoryWrapper.Product_CategoryRepository.GetByIdAsync(product.Product_CategoryId);

                    if (cate.Id == 30 || cate.Id == 31 || cate.Id == 32)
                    {
                        chartDto.Id    = cate.Id;
                        chartDto.Name  = cate.Title;
                        chartDto.Count = item.Count;
                        chartDtos.Add(chartDto);
                        continue;
                    }
                    var parentCate = await _repositoryWrapper.Product_CategoryRepository.GetByIdAsync(cate.PId);

                    chartDto.Id    = parentCate.Id;
                    chartDto.Name  = parentCate.Title;
                    chartDto.Count = item.Count;
                    chartDtos.Add(chartDto);
                }

                list = chartDtos.GroupBy(m => m.Name).Select(g => new ChartDto {
                    Name = g.Key.ToString(), Count = g.Sum(m => m.Count), Id = g.FirstOrDefault().Id
                }).OrderBy(m => m.Id).ToList();
                await _cacheHelper.SetRedisCacheAsync("chartData", list);

                return(list.ToList());
            }
            list = await _cacheHelper.GetRedisCacheAsync <List <ChartDto> >(bytes);

            return(list.ToList());;
        }
        public AbstractChartDto ParseChart(string p_chartData)
        {
            AbstractChartDto chart = new ChartDto();

            chart.Type = ChartType.iTunes;
            chart.Name = "iTunes Hot 100 " + DateTime.Now.ToString("MM-dd-yyyy");
            chart.Uid  = "iTunes-Hot-100-" + DateTime.Now.ToString("MM-dd-yyyy");
            chart.Date = DateTime.Now;


            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(p_chartData);

            //<div class="section-conten-">
            //HtmlAgilityPack.HtmlNode fNode = doc.DocumentNode.SelectSingleNode("");

            IEnumerable <HtmlAgilityPack.HtmlNode> currNodeItems = doc.DocumentNode.SelectNodes("//div[@class='col col-song']");

            string node_html      = "";
            int    charPosCounter = 1;

            foreach (var item in currNodeItems)
            {
                node_html = item.InnerHtml;

                HtmlAgilityPack.HtmlDocument itemNode = new HtmlAgilityPack.HtmlDocument();
                itemNode.LoadHtml(node_html);

                HtmlAgilityPack.HtmlNode currNodeSongName   = itemNode.DocumentNode.SelectSingleNode("//div[@class='song-name typography-label']");
                HtmlAgilityPack.HtmlNode currNodeArtistName = itemNode.DocumentNode.SelectSingleNode("//div[@class='by-line typography-caption']");


                AbstractChartSongDto _song = new ChartSongDto();
                _song.Name     = currNodeSongName.InnerText.Replace("\\n", "").Trim();
                _song.Artist   = currNodeArtistName.InnerText.Replace("\\n", "").Trim();
                _song.Position = charPosCounter;


                chart.SongsList.Add(_song);
                chart.SongNum += 1;

                charPosCounter += 1;
            }

            return(chart);
        }
Exemple #15
0
        public ChartDto GetCommunnityEntryState(DateTime startDate, DateTime endDate)
        {
            var querySql = @"select convert(char(8),EntryTime,112) StateDate, count(*) StateNum,CommunityId,
                        (select ChineseName from biz_Area where AreaUUID= t.CommunityId and Deleted=0) CommunityName
                        from biz_EntryHistory t";

            querySql += " where convert(char(8),EntryTime,112)>=" + startDate.ToString("yyyyMMdd");
            querySql += " and convert(char(8),EntryTime,112)<=" + endDate.ToString("yyyyMMdd");

            querySql += "group by convert(char(8),EntryTime,112),CommunityId";


            var queryList = _dbContext.SqlQuery <MappingData>(querySql).ToList();

            var columns = new List <string>();
            var rows    = new List <Dictionary <string, object> >();

            columns.Add("日期");

            var communityList = queryList.Select(p => p.CommunityName).Distinct().ToList();

            columns = columns.Union(communityList).ToList();

            for (var dt = startDate; dt <= endDate; dt = dt.AddDays(1))
            {
                var dict = new Dictionary <string, object>();


                dict.Add("日期", dt.ToString("MM/dd"));
                foreach (var community in communityList)
                {
                    var item = queryList.Where(a => a.CommunityName == community && a.StateDate == dt.ToString("yyyyMMdd")).FirstOrDefault();
                    dict.Add(community, item?.StateNum ?? 0);
                }
                rows.Add(dict);
            }

            var chart = new ChartDto()
            {
                columns = columns,
                rows    = rows
            };

            return(chart);
        }
        public async Task <ChartDto> GetCategoryDistributionReport()
        {
            var data = await _context.LibraryAssets.AsNoTracking()
                       .GroupBy(d => new { d.Category.Name })
                       .Select(x => new DataDto
            {
                Count = x.Count(),
                Name  = x.Key.Name
            })
                       .ToListAsync();

            var chartData = new ChartDto()
            {
                Data  = data,
                Label = "CategoryDistribution"
            };

            return(chartData);
        }
Exemple #17
0
        private ChartDto GetConsumptionsChartDto(List <ConsumptionReport> consumptions)
        {
            consumptions = consumptions.OrderBy(x => x.Date).ToList();

            var model = new ChartDto();

            var dates = consumptions.Select(x => x.Date).Distinct();

            model.Labels = dates.Select(x => x.ToString("MMM yyyy")).ToArray();

            var series = new List <SeriesDto>();

            foreach (var type in ProductTypes)
            {
                var names = Products.Where(x => x.TypeId == type.Id).Select(x => x.Name).ToList();

                var report = consumptions
                             .Where(x => names.Contains(x.Name))
                             .GroupBy(x => x.Date)
                             .ToDictionary(x => x.Key, x => x.Sum(y => y.Sum));
                var points = new List <Decimal>();

                foreach (var date in dates)
                {
                    var sum = report.ContainsKey(date) ? report[date] : 0;
                    points.Add(sum);
                }

                series.Add(new SeriesDto()
                {
                    Name   = type.Name,
                    Points = points.ToArray()
                });
            }

            model.Series = series.ToArray();

            return(model);
        }
Exemple #18
0
        private ChartDto GetIncomesChartDto(List <IncomeReport> incomes)
        {
            incomes = incomes.OrderBy(x => x.Date).ToList();

            var model = new ChartDto();

            var dates = incomes.Select(x => x.Date).Distinct();

            model.Labels = dates.Select(x => x.ToString("MMM yyyy")).ToArray();

            var series = new List <SeriesDto>();
            var names  = incomes.Select(x => x.Name).Distinct();

            foreach (var name in names)
            {
                var report = incomes
                             .Where(x => x.Name == name)
                             .GroupBy(x => x.Date)
                             .ToDictionary(x => x.Key, x => x.Sum(y => y.Sum));

                var points = new List <Decimal>();
                foreach (var date in dates)
                {
                    var sum = report.ContainsKey(date) ? report[date] : 0;
                    points.Add(sum);
                }

                series.Add(new SeriesDto()
                {
                    Name   = name,
                    Points = points.ToArray()
                });
            }

            model.Series = series.ToArray();

            return(model);
        }
        public ChartDto TicketsByTicketTypes(DateTime startPeriod, DateTime endPeriod)
        {
            if (startPeriod.CompareTo(endPeriod) == 1)
            {
                return(new ChartDto()
                {
                    ErrorMessage = EndLessStartError
                });
            }

            var data = uow.Tickets.GetAll()
                       .Where(t => t.CreatedUTCDate >= startPeriod && t.CreatedUTCDate <= endPeriod)
                       .GroupBy(t => t.TicketType.TypeName)
                       .Select(g => new { name = g.Key, count = g.Count().ToString() })
                       .ToDictionary(k => k.name, k => k.count);

            ChartDto chartDto = new ChartDto();

            chartDto.Labels = data.Keys.ToArray();
            chartDto.Data   = data.Values.ToArray();

            return(chartDto);
        }
        public async Task <ChartDto> GetCheckoutsByMonthReport()
        {
            var data = await _context.Checkouts.AsNoTracking()
                       .Where(d => d.Since > DateTime.Today.AddMonths(-12))
                       .GroupBy(d => new { d.Since.Month })
                       .Select(x => new DataDto
            {
                Count = x.Count(),
                Month = x.Key.Month,
                Name  = GetMonthName(x.Key.Month)
            })
                       .ToListAsync();

            var result = ParseData(data);

            var chartData = new ChartDto()
            {
                Data  = result,
                Label = "checkouts"
            };

            return(chartData);
        }
Exemple #21
0
    IEnumerator GetRating()
    {
        ObjectWrap <ChartDto> DataRef = new ObjectWrap <ChartDto>();

        yield return(LimChartZoneWebApi.GetChartById(Data.Id, DataRef));

        Data               = DataRef.Reference;
        OnlineRating       = (float)Data.AvgRating;
        RatingSlider.value = OnlineRating;
        UserRating         = Data.UsrRating;

        /*WWWForm Form = new WWWForm();
         * Form.AddField("ChartName", Data.ChartName);
         * WWW Rating = new WWW(LimSystem.LanotaliumServer + "/lanotalium/chartzone/ChartZoneGetRating.php", Form);
         * yield return Rating;
         * UnityEngine.Debug.Log(Rating.text);
         *
         * if (!isReceivingUserRating) RatingSlider.value = OnlineRating;
         * Form.AddField("UserId", SystemInfo.deviceUniqueIdentifier);
         * Rating = new WWW(LimSystem.LanotaliumServer + "/lanotalium/chartzone/ChartZoneGetRating.php", Form);
         * yield return Rating;
         * int.TryParse(Rating.text, out UserRating);*/
    }
Exemple #22
0
        public ChartDto GetCommunnityState()
        {
            var communityList = from p in _areaRepository.Table
                                where p.AreaType == 8 && !p.Deleted
                                select new
            {
                CommunityUUID = p.AreaUUID,
                CommunityName = p.ChineseName
            };

            var rows = new List <Dictionary <string, object> >();

            foreach (var community in communityList)
            {
                var dict = new Dictionary <string, object>();

                int roomCount     = GetRoomCountByCommuity(community.CommunityUUID);
                int usedRoomCount = GetRentRoomCountByCommuity(community.CommunityUUID);
                dict.Add("小区名称", community.CommunityName);
                dict.Add("房间数", roomCount);
                dict.Add("已租房间数", usedRoomCount);
                dict.Add("居住人数", GetRoomPersonCountByCommuity(community.CommunityUUID));
                dict.Add("入住率", Math.Round((double)usedRoomCount / roomCount, 2));
                rows.Add(dict);
            }

            var chartData = new ChartDto()
            {
                columns = new List <string>()
                {
                    "小区名称", "房间数", "已租房间数", "居住人数"
                },                                                               //, "入住率"
                rows = rows
            };

            return(chartData);
        }
Exemple #23
0
        public async Task <object> Chart(int workerID, int btnID)
        {
            try
            {
                var iotModel = await _repoCycleTime.FindAll().Where(x => x.datetime.Date == DateTime.Now.Date && x.BtnID == btnID && x.cycleTime <= 90).ToListAsync();

                var button = await _repoBtn.FindAll().Include(x => x.Worker).FirstOrDefaultAsync(x => x.WorkerID == workerID);

                var avg = new ChartDto
                {
                    label = "AVG",
                    data  = new List <double> {
                        Math.Round(iotModel.Average(x => x.cycleTime), 1)
                    }
                };
                var best = new ChartDto
                {
                    label = "Best",
                    data  = new List <double> {
                        iotModel.Min(x => x.cycleTime)
                    }
                };
                var standard = new ChartDto
                {
                    label = "Standard",
                    data  = new List <double> {
                        button.Standard
                    },
                };
                var current = new ChartDto
                {
                    label = "Latest",
                    data  = new List <double> {
                        iotModel.OrderByDescending(x => x.datetime).FirstOrDefault().cycleTime
                    },
                };
                var tt = new ChartDto
                {
                    label = "TT",
                    data  = new List <double> {
                        button.TaktTime
                    },
                };
                var chartData = new List <ChartDto> {
                    tt, standard, avg, best, current
                };
                return(new
                {
                    chartData,
                    button
                });
            }
            catch
            {
                return(new
                {
                    chartData = new object[] { },
                    button = new { },
                });
            }
        }
Exemple #24
0
        public async Task <ActionResult> Generate(int Id)
        {
            Compiler.Common.Music.ChartType ChartType = (Compiler.Common.Music.ChartType)Id;

            IChartSongEntity     chartSongManager    = new ChartSongEntity(_currSettings);
            IChartEntity         dbChartManager      = new ChartEntity(chartSongManager, _currSettings);
            IChartBuilderService chartBuilderService = new ChartBuilderService(dbChartManager, _youtubeSearchService);

            List <System.Collections.Generic.KeyValuePair <string, string> > headers_list = new List <KeyValuePair <string, string> >();

            headers_list.Add(new KeyValuePair <string, string>("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"));
            headers_list.Add(new KeyValuePair <string, string>("upgrade-insecure-requests", "1"));
            headers_list.Add(new KeyValuePair <string, string>("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,* / *;q=0.8"));
            headers_list.Add(new KeyValuePair <string, string>("accept-language", "en-US,en;q=0.9"));
            headers_list.Add(new KeyValuePair <string, string>("cache-control", "max-age=0"));
            headers_list.Add(new KeyValuePair <string, string>("Proxy-Connection", "keep-alive"));

            AbstractChartDto currChart = new ChartDto();

            switch (ChartType)
            {
            case Compiler.Common.Music.ChartType.Shazam:
            {
                headers_list.Add(new KeyValuePair <string, string>("authority", "www.shazam.com"));
                headers_list.Add(new KeyValuePair <string, string>("method", "GET"));
                headers_list.Add(new KeyValuePair <string, string>("path", "/shazam/v2/en-US/US/web/-/tracks/web_chart_us"));
                headers_list.Add(new KeyValuePair <string, string>("scheme", "https"));
                IChartParser shazamParser = new ShazamParser();
                currChart = await chartBuilderService.BuildChart("https://www.shazam.com/shazam/v2/en-US/US/web/-/tracks/web_chart_us", headers_list, shazamParser);
            }
            break;

            case Compiler.Common.Music.ChartType.Billboard:
            {
                headers_list.Add(new KeyValuePair <string, string>("Referer", "http://www.billboard.com/charts"));
                IChartParser billboardParser = new BillboardParser();
                currChart = await chartBuilderService.BuildChart("http://www.billboard.com/charts/hot-100", headers_list, billboardParser);
            }
            break;

            case Compiler.Common.Music.ChartType.iTunes:
            {
                headers_list.Add(new KeyValuePair <string, string>("Referer", "https://www.apple.com/itunes/charts/"));
                IChartParser ichartParser = new iTunesParser();
                currChart = await chartBuilderService.BuildChart("https://music.apple.com/us/playlist/top-100-usa/pl.606afcbb70264d2eb2b51d8dbcfa6a12", headers_list, ichartParser);
            }
            break;

            case Compiler.Common.Music.ChartType.YouTube:
            {
                IChartParser youtubeParser = new YoutubeParser();
                currChart = await chartBuilderService.BuildChart("https://charts.youtube.com/charts/TopSongs/us ", headers_list, youtubeParser);
            }
            break;

            default:
                break;
            }

            return(Redirect("/Music/Charts"));
        }
Exemple #25
0
        public static ChartDto ToChartDto(this Plotting.Chart chart, string title = "")
        {
            var dto = new ChartDto
            {
                ForcedEveryNthCycle = chart.ForcedEveryNthCycle,
                Points = chart.Series
                         .Select((series, index) => new { series, index })
                         .SelectMany(item =>
                                     item.series.Points
                                     .Where(p => !double.IsNaN(p.Y))
                                     .Select(p => new Dictionary <string, double?>
                {
                    { "x", p.X },
                    { item.series.IsZAxis ? "z1" : $"y{item.index}", p.Y },
                    { "highError", p.HighError.GetValueOrDefault(p.Y) },
                    { "lowError", p.LowError.GetValueOrDefault(p.Y) },
                    { "discrete", p.Discrete }
                }))
                         .ToList(),
                PlotParameters = chart.PlotParameters
            };

            var yAxisTextNonNull = chart.PlotParameters.yAxisText.Where(text => !string.IsNullOrWhiteSpace(text)).ToList();

            dto.Series = chart.Series.Select((series, index) => new { series, index })
                         // IMPORTANT: there is a problem with empty series, let's remove them temporarily.
                         // https://github.com/agafonovslava/dqdv/issues/23
                         // https://www.devexpress.com/Support/Center/Question/Details/T557040/chart-sets-vertical-range-incorrectly-when-using-aggregation
                         .Where(item => item.series.Points != null && item.series.Points.Count != 0)
                         .Select(item =>
            {
                var seriesDto        = new SeriesDto();
                seriesDto.Id         = $"{item.series.ProjectId}_{item.series.DisplayName}";
                seriesDto.ProjectId  = item.series.ProjectId;
                seriesDto.Name       = item.series.DisplayName;
                seriesDto.ValueField = item.series.IsZAxis ?
                                       "z1" :
                                       $"y{item.index}";

                seriesDto.Axis = item.series.IsZAxis ?
                                 $"z1" :
                                 null;

                return(seriesDto);
            })
                         .ToList();
            dto.Projects = chart.Projects
                           .Select(p =>
                                   new ProjectDto
            {
                Id            = p.Id,
                Name          = p.Name,
                IsAveragePlot = p.IsAveragePlot
            })
                           .ToList();
            dto.ProjectIds = chart.Projects.Select(p => p.Id).ToList();
            dto.YAxisText  = yAxisTextNonNull.Count > 0 ?
                             yAxisTextNonNull.ToArray() :
                             chart.YAxisText.ToArray();

            dto.Label                = chart.Label;
            dto.XAxisIsInteger       = chart.XAxisIsInteger;
            dto.SelectedTemplateName = chart.SelectedTemplateName;
            dto.XAxisText            = string.IsNullOrEmpty(chart.PlotParameters.xAxisText) ?
                                       chart.XAxisText :
                                       chart.PlotParameters.xAxisText;

            dto.Title = string.IsNullOrEmpty(chart.PlotParameters.ChartTitle) ?
                        title :
                        chart.PlotParameters.ChartTitle;

            return(dto);
        }
        public async System.Threading.Tasks.Task <AbstractChartDto> BuildChart(string p_chartUrl, string p_post_data, List <KeyValuePair <string, string> > p_chartHeaders, IChartParser p_chartParser)
        {
            AbstractChartDto retChart = new ChartDto();

            if (p_chartUrl == null || p_chartUrl == "")
            {
                throw (new ArgumentException("Missing chart url"));
            }

            if (p_chartHeaders == null)
            {
                throw (new ArgumentException("Missing chart request headers"));
            }

            if (p_chartParser == null)
            {
                throw (new ArgumentException("Missing chart parser"));
            }



            using (var client = new HttpClient())
            {
                try
                {
                    foreach (var item in p_chartHeaders)
                    {
                        client.DefaultRequestHeaders.Add(item.Key, item.Value);
                    }
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


                    var stringContent = new StringContent(p_post_data);

                    var response = await client.PostAsync(p_chartUrl, stringContent);

                    response.EnsureSuccessStatusCode();


                    var stringResponse = await response.Content.ReadAsStringAsync();


                    if (p_chartParser.AnalyzeRawChartData(stringResponse))
                    {
                        retChart = p_chartParser.ParseChart(stringResponse);
                    }


                    if (retChart.SongNum > 0)
                    {
                        // save chart to data storage
                        _dbChartManager.Add(retChart);
                    }
                }
                catch (HttpRequestException ex)
                {
                    // record error to log
                }
            }

            return(retChart);
        }
        public async System.Threading.Tasks.Task <AbstractChartDto> BuildChart(string p_chartUrl, List <KeyValuePair <string, string> > p_chartHeaders, IChartParser p_chartParser)
        {
            AbstractChartDto retChart = new ChartDto();


            if (p_chartUrl == null || p_chartUrl == "")
            {
                throw (new ArgumentException("Missing chart url"));
            }

            if (p_chartHeaders == null)
            {
                throw (new ArgumentException("Missing chart request headers"));
            }

            if (p_chartParser == null)
            {
                throw (new ArgumentException("Missing chart parser"));
            }



            using (var client = new HttpClient())
            {
                try
                {
                    foreach (var item in p_chartHeaders)
                    {
                        client.DefaultRequestHeaders.Add(item.Key, item.Value);
                    }


                    var response = await client.GetAsync(p_chartUrl);

                    response.EnsureSuccessStatusCode();


                    var stringResponse = await response.Content.ReadAsStringAsync();


                    if (p_chartParser.AnalyzeRawChartData(stringResponse))
                    {
                        retChart = p_chartParser.ParseChart(stringResponse);
                    }



                    //link chart with youtube ids
                    foreach (var item in retChart.SongsList)
                    {
                        //loop and assign youtube ids
                        item.YouTubeId = await _youtubeSearch.SearchFirstByKeyword(item.Artist + "-" + item.Name);

                        Task.Delay(100);
                    }



                    if (retChart.SongNum > 0)
                    {
                        //save chart to data storage
                        _dbChartManager.Add(retChart);
                    }
                }
                catch (HttpRequestException ex)
                {
                    // record error to log
                }
            }

            return(retChart);
        }