/// <summary> /// Método que se encarga de llenar los datos de la torta por Tipo de Recursos Valiosos Sobre Total /// </summary> /// <param name="empresa"></param> /// <param name="strDirectorio"></param> /// <returns></returns> public string CrearTortaRecursosSobreTotal(Empresa empresa, string strDirectorio, List <RBV_Clases.RecursoValioso> recursosValiosos, decimal ValorTotal) { System.Web.UI.DataVisualization.Charting.Chart TortaRecursos = CrearTorta(); string[] TitulosTipoVal = recursosValiosos.Where(p => p.Valor >= ValorTotal).Select(p => p.TipoRecurso).Distinct().ToArray(); decimal[] ValoresTipoVal = (from p in recursosValiosos where p.Valor >= ValorTotal group p.IdTipoRecurso by p.IdTipoRecurso into g select Math.Round((Convert.ToDecimal(g.Count()) / Convert.ToDecimal(recursosValiosos.Count)) * 100, 2)).ToArray(); Array.Resize(ref TitulosTipoVal, TitulosTipoVal.Length + 1); TitulosTipoVal[TitulosTipoVal.Length - 1] = "No Valiosos"; Array.Resize(ref ValoresTipoVal, ValoresTipoVal.Length + 1); ValoresTipoVal[ValoresTipoVal.Length - 1] = (100 - ValoresTipoVal.Sum()); TortaRecursos.Series["Recursos"].Points.DataBindXY(TitulosTipoVal, ValoresTipoVal); //TortaRecursos.Series["Recursos"].Points[1]["Exploded"] = "true"; for (int i = 0; i < TortaRecursos.Series["Recursos"].Points.Count; i++) { TortaRecursos.Series["Recursos"].Points[i].LegendText = TitulosTipoVal[i].ToString(); } string strFile = "TortaRecSobret" + empresa.NombreEmpresa + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + ".Jpeg"; string imgName = string.Concat(strDirectorio, "\\", strFile); TortaRecursos.SaveImage(imgName, ChartImageFormat.Jpeg); return(imgName); }
public FileResult Chart2Image(System.Web.UI.DataVisualization.Charting.Chart chart) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { chart.SaveImage(ms, System.Web.UI.DataVisualization.Charting.ChartImageFormat.Png); ms.Seek(0, System.IO.SeekOrigin.Begin); return(File(ms.ToArray(), "image/png", "mychart.png")); } // End Using ms }
public ActionResult ShowDigramForProperty(int propertyId, int sourcePropertyId) { System.Web.UI.DataVisualization.Charting.Chart chart = new System.Web.UI.DataVisualization.Charting.Chart(); string imageName = _diagramBinder.GenerateChart(propertyId, sourcePropertyId, ref chart); chart.SaveImage(Server.MapPath("~/Temp/" + imageName), ChartImageFormat.Png); return(Json(ResponseStatus.Success, new { data = RenderPartialViewToString("Diagram", imageName) }, JsonRequestBehavior.AllowGet)); }
public ActionResult ShowJobGraph() { List <Student> studentList = (List <Student>)TempData.Peek("studentList"); Bitmap image = new Bitmap(500, 50); Graphics g = Graphics.FromImage(image); var chart1 = new System.Web.UI.DataVisualization.Charting.Chart() { Width = 600, Height = 300 }; chart1.ChartAreas.Add("xAxis").BackColor = System.Drawing.Color.FromArgb(64, System.Drawing.Color.White); chart1.Series.Add("xAxis"); chart1.Legends.Add("myLegends"); chart1.Titles.Add("Jobs"); int participated = 0; foreach (var job in db.JobProjectsCategories.Where(x => x.Id != 4)) { participated += studentList.Where(x => x.JobProjects.Where(y => y.Category == job.Id).Count() > 0).Count(); int ptIdx1 = chart1.Series["xAxis"].Points.AddXY( job.Name, studentList.Where(x => x.JobProjects.Where(y => y.Category == job.Id).Count() > 0).Count()); DataPoint pt1 = chart1.Series["xAxis"].Points[ptIdx1]; pt1.Label = "#VALY"; pt1.LegendText = "#VALX: #VALY"; pt1.Font = new Font("Arial", 9f, FontStyle.Regular); pt1.LabelForeColor = Color.Black; } int ptIdx = chart1.Series["xAxis"].Points.AddXY( "NA", studentList.Count() - participated); DataPoint pt = chart1.Series["xAxis"].Points[ptIdx]; pt.Label = "#VALY"; pt.LegendText = "#VALX: #VALY"; pt.Font = new System.Drawing.Font("Arial", 9f, FontStyle.Regular); pt.LabelForeColor = Color.Black; chart1.Series["xAxis"].ChartType = SeriesChartType.Pie; chart1.BackColor = Color.Transparent; MemoryStream imageStream = new MemoryStream(); chart1.SaveImage(imageStream, ChartImageFormat.Png); chart1.TextAntiAliasingQuality = TextAntiAliasingQuality.High; Response.ContentType = "image/png"; imageStream.WriteTo(Response.OutputStream); g.Dispose(); image.Dispose(); return(null); }
public ActionResult EvolucaoMensalPorEstado() { //List<EvolucaoPorEstadoModel> dados = new List<EvolucaoPorEstadoModel>() //{ // new EvolucaoPorEstadoModel() { ANO = 2016, FATURAMENTO = 58970, MES = 12, UF = "BA" }, // new EvolucaoPorEstadoModel() { ANO = 2016, FATURAMENTO = 4387.37, MES = 11, UF = "PB" }, // new EvolucaoPorEstadoModel() { ANO = 2016, FATURAMENTO = 97664.24, MES = 12, UF = "PB" }, // new EvolucaoPorEstadoModel() { ANO = 2017, FATURAMENTO = 86767, MES = 1, UF = "BA" }, // new EvolucaoPorEstadoModel() { ANO = 2017, FATURAMENTO = 98214.5, MES = 2, UF = "BA" } //}; var chart = new System.Web.UI.DataVisualization.Charting.Chart(); chart.Width = 1000; //LARGURA chart.Height = 1000; //ALTURA chart.BackColor = Color.FromArgb(211, 223, 240); chart.BorderlineDashStyle = ChartDashStyle.Solid; chart.BackSecondaryColor = Color.White; chart.BackGradientStyle = GradientStyle.TopBottom; chart.BorderlineWidth = 1; //chart.Palette = ChartColorPalette.BrightPastel; chart.Palette = ChartColorPalette.SeaGreen; chart.BorderlineColor = Color.FromArgb(26, 59, 105); chart.RenderType = RenderType.BinaryStreaming; chart.BorderSkin.SkinStyle = BorderSkinStyle.Emboss; chart.AntiAliasing = AntiAliasingStyles.All; chart.TextAntiAliasingQuality = TextAntiAliasingQuality.Normal; chart.Titles.Add(CreateTitle()); chart.Legends.Add(CreateLegend()); chart.AlignDataPointsByAxisLabel(); var dados = new DiretoriaBLL().GraficoEvolucaoMensalEstado(); //var dados1 = (from X in dados orderby X.ANO, X.MES group X by X.UF into N select N).ToList(); var dados1 = (from X in dados orderby X.ANO descending, X.MES descending group X by X.UF into N select N).ToList(); foreach (var item in dados1) { chart.Series.Add(CriarSerie(SeriesChartType.Bar, item.ToList())); } chart.ChartAreas.Add(CreateChartArea()); chart.DataSource = dados; MemoryStream ms = new MemoryStream(); chart.SaveImage(ms); return(File(ms.GetBuffer(), @"image/png")); }
/// <summary> /// Método que se encarga de llenar los datos del grafico de barras horizontales contra clasificacion /// </summary> /// <param name="empresa">DLP</param> /// <param name="strDirectorio"></param> /// <returns></returns> public string CrearGraficoBarrasHorizontalesClasificacion(Empresa empresa, string strDirectorio, List <RBV_Clases.MatrizValoracion> matrizValoracion, decimal ValorTotal) { System.Web.UI.DataVisualization.Charting.Chart BarrasRecursos = CrearTorta(); BarrasRecursos.Series["Recursos"].ChartType = SeriesChartType.Bar; List <RecursoValioso> recursosValiosos = RBV_Negocio.MatrizBO.CalcularResultadosCaracteritica(matrizValoracion, empresa.IdEmpresa); string[] Titulo = recursosValiosos.Select(p => p.NombreCaracteristica).ToArray(); decimal[] Valor = recursosValiosos.Select(p => p.Valor).ToArray(); BarrasRecursos.Series["Recursos"].Points.DataBindXY(Titulo, Valor); string strFile = "BarrasHorizontalVal" + empresa.NombreEmpresa + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + ".Jpeg"; string imgName = string.Concat(strDirectorio, "\\", strFile); BarrasRecursos.SaveImage(imgName, ChartImageFormat.Jpeg); return(imgName); }
public ActionResult ShowProjectGraph() { List <Student> studentList = (List <Student>)TempData.Peek("studentList"); int maxNumber = db.JobProjects.Where(x => x.Category == 4).GroupBy(x => x.StudentId).Select(group => new { Metric = group.Key, Count = group.Count() }).OrderByDescending(x => x.Count).First().Count; Bitmap image = new Bitmap(500, 50); Graphics g = Graphics.FromImage(image); var chart1 = new System.Web.UI.DataVisualization.Charting.Chart() { Width = 600, Height = 300 }; chart1.ChartAreas.Add("xAxis").BackColor = System.Drawing.Color.FromArgb(64, System.Drawing.Color.White); chart1.Series.Add("xAxis"); chart1.Legends.Add("myLegends"); chart1.Titles.Add("Number of Projects"); foreach (var number in Enumerable.Range(0, maxNumber + 1).ToArray()) { int ptIdx1 = chart1.Series["xAxis"].Points.AddXY( number + "", studentList.Where(x => x.JobProjects.Where(y => y.Category == 4).Count() == number).Count()); DataPoint pt1 = chart1.Series["xAxis"].Points[ptIdx1]; pt1.Label = "#VALX: #VALY"; pt1.LegendText = "#VALX: #VALY"; pt1.Font = new Font("Arial", 9f, FontStyle.Regular); pt1.LabelForeColor = Color.Black; } chart1.Series["xAxis"].ChartType = SeriesChartType.Pie; chart1.BackColor = Color.Transparent; MemoryStream imageStream = new MemoryStream(); chart1.SaveImage(imageStream, ChartImageFormat.Png); chart1.TextAntiAliasingQuality = TextAntiAliasingQuality.SystemDefault; Response.ContentType = "image/png"; imageStream.WriteTo(Response.OutputStream); g.Dispose(); image.Dispose(); return(null); }
/// <summary> /// Método que se encarga de llenar los datos de la torta por porcentaje de recursos /// </summary> /// <param name="empresa"></param> /// <param name="strDirectorio"></param> /// <returns></returns> public string CrearTortaRecursos(Empresa empresa, string strDirectorio, List <RBV_Clases.RecursoValioso> recursosValiosos) { System.Web.UI.DataVisualization.Charting.Chart TortaRecursos = CrearTorta(); string[] TitulosTipo = recursosValiosos.Select(p => p.TipoRecurso).Distinct().ToArray(); decimal[] ValoresTipo = (from p in recursosValiosos group p.IdTipoRecurso by p.IdTipoRecurso into g select Math.Round((Convert.ToDecimal(g.Count()) / Convert.ToDecimal(recursosValiosos.Count)) * 100, 2)).ToArray(); TortaRecursos.Series["Recursos"].Points.DataBindXY(TitulosTipo, ValoresTipo); TortaRecursos.Series["Recursos"].Points[1]["Exploded"] = "true"; for (int i = 0; i < TortaRecursos.Series["Recursos"].Points.Count; i++) { TortaRecursos.Series["Recursos"].Points[i].LegendText = TitulosTipo[i].ToString(); } string strFile = "TortaRec" + empresa.NombreEmpresa + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + ".Jpeg"; string imgName = string.Concat(strDirectorio, "\\", strFile); TortaRecursos.SaveImage(imgName, ChartImageFormat.Jpeg); return(imgName); }
public ActionResult ShowQuotaGraph() { List <Student> studentList = (List <Student>)TempData.Peek("studentList"); Bitmap image = new Bitmap(500, 50); Graphics g = Graphics.FromImage(image); var chart1 = new System.Web.UI.DataVisualization.Charting.Chart() { Width = 1200, Height = 1000 }; chart1.ChartAreas.Add("xAxis").BackColor = System.Drawing.Color.FromArgb(64, System.Drawing.Color.White); chart1.Series.Add("xAxis"); chart1.Legends.Add("myLegends"); chart1.Titles.Add("Admission Quota"); foreach (var quota in db.Quotas) { int ptIdx = chart1.Series["xAxis"].Points.AddXY( quota.Name, studentList.Where(x => x.AdmissionQuota == quota.Id).Count()); DataPoint pt = chart1.Series["xAxis"].Points[ptIdx]; pt.Label = "#VALX: #VALY"; pt.LegendText = "#VALX: #VALY"; pt.Font = new System.Drawing.Font("Arial", 9f, FontStyle.Regular); pt.LabelForeColor = Color.Black; } chart1.Series["xAxis"].ChartType = SeriesChartType.Bar; chart1.BackColor = Color.Transparent; MemoryStream imageStream = new MemoryStream(); chart1.SaveImage(imageStream, ChartImageFormat.Png); chart1.TextAntiAliasingQuality = TextAntiAliasingQuality.High; Response.ContentType = "image/png"; imageStream.WriteTo(Response.OutputStream); g.Dispose(); image.Dispose(); return(null); }
public FileResult ChartLocation(Guid id) { var d = Context.Visits.Where(x => x.Image.Id == id); var result = new List<ShowVisitorOnMapModel>(); foreach (var visit in d) { var geo = visit.Ip.GetGeo(Server); var dm = new ShowVisitorOnMapModel() { created = visit.Time, ip = visit.Ip, referer = visit.Referer, Country = geo.Country, Region = geo.Region, City = geo.City, FullAdress = geo.FillAddress, Lattitude = geo.Latitude, Longitude = geo.Longitude }; result.Add(dm); } var chm = new Dictionary<string, int>(); foreach (var item in result) { if (item.Country == null) item.Country = string.Empty; if (chm.ContainsKey(item.FullAdress)) { chm[item.FullAdress] = chm[item.FullAdress] + 1; } else { chm.Add(item.FullAdress, 1); } } var rt = chm.Select(i => new ChartAdressModel() { Name = i.Key, Count = i.Value }).ToList(); ////////////////////////// var country = rt.Select(x => x.Name); var count = rt.Select(x => x.Count); var mvchart = new System.Web.UI.DataVisualization.Charting.Chart(); mvchart.Width = 800; mvchart.Height = 640; var mySeries = new Series(); mySeries.Points.DataBindXY(country.ToArray(), count.ToArray()); mvchart.Series.Add(mySeries); var area = new ChartArea(); mvchart.ChartAreas.Add(area); mvchart.ChartAreas[0].AxisX.LabelAutoFitStyle = LabelAutoFitStyles.LabelsAngleStep90; mvchart.ChartAreas[0].AxisX.IsLabelAutoFit = true; mvchart.ChartAreas[0].AxisX.LabelStyle.Format = "0.###"; mvchart.ChartAreas[0].AxisX.Maximum = country.Count() + 1; var returnVal = new MemoryStream(); mvchart.SaveImage(returnVal); return File(returnVal.GetBuffer(), @"image/png"); }
public void ProcessRequest( HttpContext context ) { SparePartPriceKey key = SparePartPriceKey.Parse(context.Request.QueryString["ID"]); SparePartFranch part = SparePartsDac.Load(key); if (part != null) { Int32? beforeTime = part.BeforeTime; Int32? onTime = part.OnTime; Int32? delay = part.Delay; Int32? nonDelivery = part.NonDelivery; //beforeTime = 100; onTime = 75; delay = 60; nonDelivery = 35; if (beforeTime != null && onTime != null && delay != null && nonDelivery != null) { Chart ChartStat = new System.Web.UI.DataVisualization.Charting.Chart(); //LiteralControl lc = new LiteralControl(); //lc.Text = "123"; //ChartStat.Controls.Add(lc); Title t = new Title(("Рейтинг" + Environment.NewLine + "поставщика"), Docking.Top); t.Font = new Font(t.Font.FontFamily,(float)t.Font.SizeInPoints * (float)1.325); t.Position = new ElementPosition(18, 2, 65, 20); ChartStat.Titles.Add(t); ChartStat.Series.Add(new Series("SeriesStat")); ChartStat.ChartAreas.Add(new ChartArea("ChartAreaStat")); int[] yValues = { (int) beforeTime, (int) onTime, (int) delay, (int) nonDelivery}; string[] xValues = { "Раньше", "Вовремя", "Задержка", "Непоставка" }; ChartStat.Series["SeriesStat"].Points.DataBindXY(xValues, yValues); ChartStat.Series["SeriesStat"].LabelForeColor = Color.FromArgb(0, Color.White); ChartStat.Series["SeriesStat"].Points[0].Color = Color.FromArgb(0, 127, 255); // синий Раньше ChartStat.Series["SeriesStat"].Points[1].Color = Color.FromArgb(47, 229, 107); // зеленый Вовремя ChartStat.Series["SeriesStat"].Points[2].Color = Color.FromArgb(255, 242, 157); // желтый Задержка ChartStat.Series["SeriesStat"].Points[3].Color = Color.FromArgb(254, 192, 192); // красный Непоставка // Set chart type ChartStat.Series["SeriesStat"].ChartType = SeriesChartType.Pie; // Set labels style ChartStat.Series["SeriesStat"]["PieLabelStyle"] = "Inside"; // Enable 3D ChartStat.ChartAreas["ChartAreaStat"].Area3DStyle.Enable3D = true; // Show a 30% perspective ChartStat.ChartAreas["ChartAreaStat"].Area3DStyle.Perspective = 30; // Set the X Angle to 70 ChartStat.ChartAreas["ChartAreaStat"].Area3DStyle.Inclination = 70; // Set the Y Angle to -2 ChartStat.ChartAreas["ChartAreaStat"].Area3DStyle.Rotation = -2; ChartStat.ChartAreas["ChartAreaStat"].Position = new ElementPosition(16, 5, 68, 68); System.Web.UI.DataVisualization.Charting.Legend l = new Legend("LegendStat"); //l.TitleFont = new Font(); l.Title = "Указанное время доставки:" + Environment.NewLine + part.DisplayDeliveryDaysMin.ToString() + " - " + part.DisplayDeliveryDaysMax.ToString() + " (в рабочих днях)"; l.TitleAlignment = StringAlignment.Center; l.TitleFont = new Font(l.TitleFont.FontFamily, l.TitleFont.SizeInPoints * (float) 1.15); ChartStat.Legends.Add(l); LegendCellColumn firstColumn = new LegendCellColumn(); firstColumn.ColumnType = LegendCellColumnType.SeriesSymbol; ChartStat.Legends["LegendStat"].CellColumns.Add(firstColumn); LegendCellColumn secondColumn = new LegendCellColumn(); secondColumn.ColumnType = LegendCellColumnType.Text; secondColumn.Text = "#LEGENDTEXT"; secondColumn.Alignment = ContentAlignment.MiddleLeft; secondColumn.HeaderBackColor = Color.WhiteSmoke; ChartStat.Legends["LegendStat"].CellColumns.Add(secondColumn); LegendCellColumn thirdColumn = new LegendCellColumn(); thirdColumn.ColumnType = LegendCellColumnType.Text; thirdColumn.Text = "#PERCENT{0#%}"; //thirdColumn.Text = String.Format({0:#%},thirdColumn.Text); thirdColumn.Alignment = ContentAlignment.MiddleRight; thirdColumn.HeaderBackColor = Color.WhiteSmoke; ChartStat.Legends["LegendStat"].CellColumns.Add(thirdColumn); ChartStat.Legends[0].Enabled = true; //(34, 63, 40, 30) ChartStat.Legends[0].Position = new ElementPosition(22, 58, 60, 44); context.Response.ContentType = "image/bmp"; context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate); using (System.IO.MemoryStream imageStream = new System.IO.MemoryStream()) { ChartStat.SaveImage(imageStream, ChartImageFormat.Bmp); context.Response.BinaryWrite(imageStream.ToArray()); } context.Response.End(); } } else { throw new HttpException((int)HttpStatusCode.NotFound, "Not Found"); } }
public string CrearGraficoBarra(Empresa empresa, string strDirectorio) { System.Web.UI.DataVisualization.Charting.Chart Chart1 = new System.Web.UI.DataVisualization.Charting.Chart(); Chart1.Width = System.Web.UI.WebControls.Unit.Pixel(650); Chart1.Height = System.Web.UI.WebControls.Unit.Pixel(400); Legend legend = new Legend(); legend.LegendStyle = LegendStyle.Table; legend.Docking = Docking.Bottom; Chart1.Legends.Add(legend); ChartArea ChartArea1 = new ChartArea("ChartArea1"); System.Web.UI.DataVisualization.Charting.Axis axisX = new System.Web.UI.DataVisualization.Charting.Axis(); axisX.LabelAutoFitStyle = LabelAutoFitStyles.LabelsAngleStep90; axisX.LabelAutoFitMaxFontSize = 10; axisX.IsLabelAutoFit = true; axisX.Interval = 1; System.Web.UI.DataVisualization.Charting.Axis axisY = new System.Web.UI.DataVisualization.Charting.Axis(); axisX.Interval = 0.2; ChartArea1.AxisX = axisX; ChartArea1.AxisY = axisY; Chart1.ChartAreas.Add(ChartArea1); System.Web.UI.DataVisualization.Charting.Series Recursos = new System.Web.UI.DataVisualization.Charting.Series("Recursos"); Recursos.ShadowColor = Color.Gray; Recursos.ChartType = SeriesChartType.Column; Recursos.IsVisibleInLegend = true; Chart1.Series.Add(Recursos); System.Web.UI.DataVisualization.Charting.Series srPromedio = new System.Web.UI.DataVisualization.Charting.Series("Promedio"); srPromedio.ShadowColor = Color.Red; srPromedio.ChartType = SeriesChartType.Line; srPromedio.BorderWidth = 2; Chart1.Series.Add(srPromedio); List <Entidades.MatrizValoracion> MatrizValoracion = new List <RBV_Clases.MatrizValoracion>(); List <RBV_Clases.RecursoValioso> recursosValiosos = new List <RBV_Clases.RecursoValioso>(); decimal ValorTotal = 0; MatrizValoracion = RBV_Negocio.MatrizBO.ConsultarMatrizValoracion(empresa.IdEmpresa).OrderBy(p => p.IdCaracteristica).ThenBy(p => p.IdRecurso).ToList(); if (MatrizValoracion.Count > 0) { recursosValiosos = RBV_Negocio.MatrizBO.CalcularResultadosMatriz(MatrizValoracion, empresa.IdEmpresa); ValorTotal = recursosValiosos.Sum(p => p.Valor) / recursosValiosos.Count; } string[] Titulos = recursosValiosos.Select(p => p.NombreRecurso).ToArray(); decimal[] Valores = recursosValiosos.Select(p => p.Valor).ToArray(); decimal[] Promedio = new decimal[Titulos.Length]; Chart1.Series["Recursos"].Points.DataBindXY(Titulos, Valores); for (int i = 0; i < Titulos.Length; i++) { Promedio[i] = ValorTotal; } Chart1.Series["Promedio"].Points.DataBindXY(Titulos, Promedio); string strFile = "Barra" + empresa.NombreEmpresa + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + ".Jpeg"; string imgName = string.Concat(strDirectorio, "\\", strFile); Chart1.SaveImage(imgName, ChartImageFormat.Jpeg); return(imgName); }
public ActionResult GerarGraficoFaturamentoPorDeposito() { Model.Deposito filtro = (HttpContext.Application["FILTRO"] != null && !string.IsNullOrEmpty(HttpContext.Application["FILTRO"].ToString())) ? (Model.Deposito)HttpContext.Application["FILTRO"] : new Model.Deposito() { descricaoDeposito = "NENHUM PÁTIO SELECIONADO", clienteDeposito = new Model.Cliente() { nomeCliente = "NENHUM" } }; ViewBag.DepositoFiltrado = filtro; #region PARAMETRIZAÇÃO DO GRÁFICO var chart = new System.Web.UI.DataVisualization.Charting.Chart(); chart.Width = 900; //LARGURA chart.Height = 500; //ALTURA chart.BackColor = Color.FromArgb(211, 223, 240); chart.BorderlineDashStyle = ChartDashStyle.Solid; chart.BackSecondaryColor = Color.White; chart.BackGradientStyle = GradientStyle.TopBottom; chart.BorderlineWidth = 1; chart.Palette = ChartColorPalette.BrightPastel; chart.BorderlineColor = Color.FromArgb(26, 59, 105); chart.RenderType = RenderType.BinaryStreaming; chart.BorderSkin.SkinStyle = BorderSkinStyle.Emboss; chart.AntiAliasing = AntiAliasingStyles.All; chart.TextAntiAliasingQuality = TextAntiAliasingQuality.Normal; chart.Titles.Add(CreateTitle(filtro.clienteDeposito.nomeCliente)); chart.Legends.Add(CreateLegend()); #endregion //CONSULTA DOS DADOS var ent = new Business.FaturamentoBLL(filtro); var dados = ent.GetDadosGrafico(); var graf = ent.GraficoFaturamento(); #region SELECIONAR DISTINTAMENTE EIXO-X E RÓTULOS DOS MESMOS var Eixos = graf.Select(x => x.CoordenadasGrafico).Distinct().Select(c => c.FirstOrDefault().ROTULO_X).Distinct(); Dictionary <string, int> ColecaoEixos = new Dictionary <string, int>(); int count = 1; foreach (var item in Eixos) { ColecaoEixos.Add(item.ToString(), count); count++; } #endregion foreach (var item in graf) { var Deposito = item.Deposito; Coordenadas C = item.CoordenadasGrafico.FirstOrDefault(); C.X = ColecaoEixos.Where(e => e.Key == C.ROTULO_X).FirstOrDefault().Value; try { //TENTO CRIAR A SÉRIE E ADICIONAR COORDENADA, CASO JA EXISTA ADICIONAR COORDENADA (CATCH) chart.Series.Add(CreateSeries(SeriesChartType.RangeColumn, C.ROTULO_X, C.X, C.Y, Deposito.descricaoDeposito)); } catch { chart.Series[Deposito.descricaoDeposito].Points.Add(new DataPoint() { AxisLabel = C.ROTULO_X, YValues = new double[] { C.Y }, XValue = C.X, Label = C.Y.ToString("C"), //LabelAngle = -90 }); } } chart.ChartAreas.Add(CreateChartArea()); //EXEMPLO USANDO UM DATASOURCE //var statusNumbers = new Dictionary<string, string> //{ // new StatusNumber{Number="55555", Status="USA"}, // new StatusNumber{Number="11385", Status="China"}, // new StatusNumber{Number="4116", Status="Japan"}, // new StatusNumber{Number="3371", Status="Germany"}, // new StatusNumber{Number="2865", Status="UK"}, // new StatusNumber{Number="2423", Status="France"}, // new StatusNumber{Number="2183", Status="India"}, //}; //chart.DataSource = pontos; MemoryStream ms = new MemoryStream(); chart.SaveImage(ms); return(File(ms.GetBuffer(), @"image/png")); }
public ActionResult GetChart() { DailyRecordConfiguration drc = new DailyRecordConfiguration(); List <DailyRecord> lDailyRecordList = new List <DailyRecord>(); double lRain; double lIrrigation; lDailyRecordList = drc.GetDailyRecordsListDataUntilDateBy(ciwId, Utils.GetDateOfReference().Value); try { ArrayList yArrayRain = new ArrayList(); ArrayList yArrayIrrigation = new ArrayList(); ArrayList yArrayETC = new ArrayList(); ArrayList xDaysAfterSowing = new ArrayList(); foreach (DailyRecord item in lDailyRecordList) { if (item.DaysAfterSowing > 0) { lRain = 0; lIrrigation = 0; if (item.Rain != null) { lRain = item.Rain.Input + item.Rain.ExtraInput; } if (item.Irrigation != null) { lIrrigation = item.Irrigation.ExtraInput + item.Irrigation.Input; } yArrayIrrigation.Add(lIrrigation); yArrayRain.Add(lRain); yArrayETC.Add(Math.Round(item.TotalEvapotranspirationCrop, 1)); xDaysAfterSowing.Add(item.DaysAfterSowing); } } System.Web.UI.DataVisualization.Charting.Chart chart = new System.Web.UI.DataVisualization.Charting.Chart(); chart.Width = 1000; chart.Height = 450; chart.BackColor = Color.FromArgb(210, 240, 204); chart.BorderlineDashStyle = ChartDashStyle.Solid; chart.BackSecondaryColor = Color.White; chart.BackGradientStyle = GradientStyle.TopBottom; chart.BorderlineWidth = 1; chart.Palette = ChartColorPalette.BrightPastel; chart.BorderlineColor = Color.FromArgb(26, 59, 105); chart.RenderType = RenderType.BinaryStreaming; chart.BorderSkin.SkinStyle = BorderSkinStyle.Emboss; chart.AntiAliasing = AntiAliasingStyles.All; chart.TextAntiAliasingQuality = TextAntiAliasingQuality.Normal; chart.ChartAreas.Add(CreateChartArea()); chart.Series.Add(CreateSeries(yArrayETC, xDaysAfterSowing, "ETc acumulada", SeriesChartType.Line, Color.FromArgb(246, 134, 36), AxisType.Primary)); chart.Series.Add(CreateSeries(yArrayRain, xDaysAfterSowing, "Lluvia", SeriesChartType.Column, Color.FromArgb(74, 164, 209), AxisType.Secondary)); chart.Series.Add(CreateSeries(yArrayIrrigation, xDaysAfterSowing, "Riego", SeriesChartType.Column, Color.FromArgb(97, 209, 74), AxisType.Secondary)); System.Web.UI.DataVisualization.Charting.Title title = chart.Titles.Add("Evolución de la ETc acumulada y distribucion de las lluvias y riegos, expresadas en mm de lámina bruta"); title.Font = new Font("Verdana,Arial,Helvetica,sans-serif", 10, FontStyle.Regular); chart.Legends.Clear(); chart.Legends.Add("Default"); chart.Legends[0].Docking = Docking.Bottom; chart.Legends[0].TableStyle = LegendTableStyle.Wide; chart.Legends[0].Alignment = StringAlignment.Center; MemoryStream ms = new MemoryStream(); chart.SaveImage(ms); return(File(ms.GetBuffer(), @"image/png")); } catch (Exception ex) { Utils.LogError(ex, "Exception in ReportPivotState.GetChart \n {0} "); return(null); } }
// GET: /Reading/Chart /// <author> /// Sanders Lee /// </author> /// <summary> /// Renders the graph of a sensor's data /// </summary> /// <param name="id">The id of the sensor to get readings for</param> /// <param name="num">The number of latest readings to get</param> /// <returns>Returns the graph in png format</returns> public ActionResult Chart(int? id, int? num) { if (id == null || num == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); Sensor s = db.Sensors.Find(id); if (s == null) return HttpNotFound(); System.Web.UI.DataVisualization.Charting.Chart chart = new System.Web.UI.DataVisualization.Charting.Chart(); chart.Width = 1100; chart.Height = 470; chart.AntiAliasing = System.Web.UI.DataVisualization.Charting.AntiAliasingStyles.Graphics; chart.BackImageTransparentColor = System.Drawing.Color.Transparent; chart.BackColor = System.Drawing.Color.Transparent; chart.ChartAreas.Add(new ChartArea()); // label the axes chart.ChartAreas[0].AxisX.Title = "Time"; chart.ChartAreas[0].AxisX.TitleFont = new Font("Arial", 12f, FontStyle.Bold); chart.ChartAreas[0].AxisY.Title = s.Type.Type + " (" + s.Type.Units + ")"; chart.ChartAreas[0].AxisY.TitleFont = new Font("Arial", 12f, FontStyle.Bold); chart.ChartAreas[0].BackImageTransparentColor = System.Drawing.Color.Transparent; chart.ChartAreas[0].BackColor = System.Drawing.Color.Transparent; for (int i = 0; i < 4; i++) chart.Series.Add(new Series()); // declarations and stylings for lines and points // main data line chart.Series[0].ChartType = SeriesChartType.Line; chart.Series[0].Color = Color.Navy; chart.Series[0].BorderWidth = 2; // upper limit line chart.Series[1].ChartType = SeriesChartType.Line; chart.Series[1].Color = Color.DarkRed; chart.Series[1].BorderWidth = 3; chart.Series[1].BorderDashStyle = ChartDashStyle.Dash; // lower limit line chart.Series[2].ChartType = SeriesChartType.Line; chart.Series[2].Color = Color.DarkRed; chart.Series[2].BorderWidth = 3; chart.Series[2].BorderDashStyle = ChartDashStyle.Dash; // data point highlight chart.Series[3].ChartType = SeriesChartType.Point; chart.Series[3].MarkerSize = 10; // set the graph data, and only get the specified number of most recent points List<Reading> list = db.Readings.Where(k => k.SensorID == id).OrderBy(k => k.ID).ToList(); // no data == empty image if (list.Count == 0) { Bitmap image = new Bitmap(1, 1); MemoryStream ms = new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); return File(ms.ToArray(), "image/png"); } // cannot grab more data points than there is if (num > list.Count) num = list.Count; for (int i = (int)num - 1; i >=0; i--) { string x = list[list.Count - i - 1].LoggedTime.ToString(); double y = list[list.Count - i - 1].Data; chart.Series[0].Points.AddXY(x, y); // data line chart.Series[1].Points.AddXY(x, s.MaxSafeReading); // upper limit line chart.Series[2].Points.AddXY(x, s.MinSafeReading); // lower limit line chart.Series[3].Points.AddXY(x, y); // data points // color the points differently depending on abnormality if (y < s.MinSafeReading || y > s.MaxSafeReading) chart.Series[3].Points[(int)num - i - 1].Color = Color.Red; else chart.Series[3].Points[(int)num - i - 1].Color = Color.LawnGreen; } // labelling the max and min lines chart.Series[1].Points[0].Label = "Maximum Acceptable Value"; chart.Series[1].Points[0].LabelForeColor = Color.DarkRed; chart.Series[2].Points[0].Label = "Minimum Acceptable Value"; chart.Series[2].Points[0].LabelForeColor = Color.DarkRed; // draw the graph out to a file using (var ms = new MemoryStream()) { chart.SaveImage(ms, ChartImageFormat.Png); ms.Seek(0, SeekOrigin.Begin); return File(ms.ToArray(), "image/png", "datachart.png"); } }
public async Task<MemoryStream> LoadQSORateChart(ChartCtlDataSettingsDto ChartCtlDataSettingsDto, IRepositoryAsync<Log> LogRepository, string username) { MemoryStream MemoryStream = null; bool bOK = true; IList<ContestInfoDTO> ContestInfosDTOList = new List<ContestInfoDTO>(); LoadContestInfoDTO(ChartCtlDataSettingsDto, ContestInfosDTOList, LogRepository, username); //set ContestInfoDTO ContestInfoDTO ContestInfoDTO1 = ContestInfosDTOList.Where(c => c.CallGroup == common.Enum.CallGroupEnum.CALL1).FirstOrDefault(); ContestInfoDTO ContestInfoDTO2 = ContestInfosDTOList.Where(c => c.CallGroup == common.Enum.CallGroupEnum.CALL2).FirstOrDefault(); ContestInfoDTO ContestInfoDTO3= ContestInfosDTOList.Where(c => c.CallGroup == common.Enum.CallGroupEnum.CALL3).FirstOrDefault(); ChartQuery ChartQuery = new Charting.ChartQuery(); ChartAreaInfoParams ChartAreaParams = new ChartAreaInfoParams(); //CHART QSORateChart = new System.Web.UI.DataVisualization.Charting.Chart() { ID = "QSORateChart", Height = new System.Web.UI.WebControls.Unit("400px"), //ImageStorageMode = System.Web.UI.DataVisualization.Charting.ImageStorageMode.UseImageLocation, RenderType = RenderType.BinaryStreaming, BackColor = Color.FromArgb(0xFF, 0xC9, 0xEC, 0xFE), Width = new System.Web.UI.WebControls.Unit("984px"), AntiAliasing = System.Web.UI.DataVisualization.Charting.AntiAliasingStyles.All, TextAntiAliasingQuality = System.Web.UI.DataVisualization.Charting.TextAntiAliasingQuality.High }; QSORateChart.CustomizeLegend += QSORateChart_CustomizeLegend; //QSORateChart.Customize += QSORateChart_Customize; //TITLES Title TitleChartName = new System.Web.UI.DataVisualization.Charting.Title() { Name = "ChartName", TextStyle = System.Web.UI.DataVisualization.Charting.TextStyle.Emboss, ForeColor = Color.FromArgb(0xFF, 0, 99, 99), Font = new System.Drawing.Font(new System.Drawing.FontFamily("Microsoft Sans Serif"), 22) }; Title TitleTkey3 = new System.Web.UI.DataVisualization.Charting.Title() { Name = "Tkey3", TextStyle = System.Web.UI.DataVisualization.Charting.TextStyle.Emboss, ForeColor = Color.FromArgb(0xFF, 0, 99, 99), Font = new System.Drawing.Font(new System.Drawing.FontFamily("Courier New"), 10), Alignment = ContentAlignment.BottomLeft, Docking = System.Web.UI.DataVisualization.Charting.Docking.Bottom, DockingOffset = 2 }; Title TitleTkey2 = new System.Web.UI.DataVisualization.Charting.Title() { Name = "Tkey2", TextStyle = System.Web.UI.DataVisualization.Charting.TextStyle.Emboss, ForeColor = Color.FromArgb(0xFF, 0, 99, 99), Font = new System.Drawing.Font(new System.Drawing.FontFamily("Courier New"), 10), Alignment = ContentAlignment.BottomLeft, Docking = System.Web.UI.DataVisualization.Charting.Docking.Bottom, DockingOffset = 4 }; Title TitleTkey1 = new System.Web.UI.DataVisualization.Charting.Title() { Name = "Tkey1", TextStyle = System.Web.UI.DataVisualization.Charting.TextStyle.Emboss, ForeColor = Color.FromArgb(0xFF, 0, 99, 99), Font = new System.Drawing.Font(new System.Drawing.FontFamily("Courier New"), 10), Alignment = ContentAlignment.BottomLeft, Docking = System.Web.UI.DataVisualization.Charting.Docking.Bottom, DockingOffset = 6 }; Title TitleCorp = new System.Web.UI.DataVisualization.Charting.Title() { Name = "Corp", TextStyle = System.Web.UI.DataVisualization.Charting.TextStyle.Default, ForeColor = Color.Blue, Font = new System.Drawing.Font(new System.Drawing.FontFamily("Trebuchet MS"), 8.25f), Alignment = ContentAlignment.BottomRight, Url = "http://www.psws.com", Text="© PSWS.com", Docking = System.Web.UI.DataVisualization.Charting.Docking.Bottom, DockingOffset = 18 }; Title TitleVersion = new System.Web.UI.DataVisualization.Charting.Title() { Name = "Vers", TextStyle = System.Web.UI.DataVisualization.Charting.TextStyle.Default, ForeColor = Color.Black, Font = new System.Drawing.Font(new System.Drawing.FontFamily("Trebuchet MS"), 8.25f), Alignment = ContentAlignment.BottomRight, Docking = System.Web.UI.DataVisualization.Charting.Docking.Bottom, DockingOffset = 20 }; QSORateChart.Titles.Add(TitleChartName); QSORateChart.Titles.Add(TitleTkey3); QSORateChart.Titles.Add(TitleTkey2); QSORateChart.Titles.Add(TitleTkey1); QSORateChart.Titles.Add(TitleCorp); QSORateChart.Titles.Add(TitleVersion); //LEGENDS Legend LegendLegend1 = new System.Web.UI.DataVisualization.Charting.Legend() { Name = "Legend1", TitleSeparator = System.Web.UI.DataVisualization.Charting.LegendSeparatorStyle.DoubleLine, BorderColor = Color.Black, BorderWidth = 1, LegendStyle = System.Web.UI.DataVisualization.Charting.LegendStyle.Row, IsEquallySpacedItems = true, IsTextAutoFit = false, TitleAlignment = StringAlignment.Center, BackGradientStyle = System.Web.UI.DataVisualization.Charting.GradientStyle.HorizontalCenter, BackColor = Color.FromArgb(0xFF, 0xEE, 0xEE, 0xEE), BackSecondaryColor = Color.White, Alignment = StringAlignment.Center, Docking = System.Web.UI.DataVisualization.Charting.Docking.Bottom, ItemColumnSeparator = System.Web.UI.DataVisualization.Charting.LegendSeparatorStyle.GradientLine, ItemColumnSpacing = 30, }; QSORateChart.Legends.Add(LegendLegend1); //CHARTAREAS ChartArea ChartAreaChartArea1 = new System.Web.UI.DataVisualization.Charting.ChartArea() { Name = "ChartArea1", BackColor = Color.FromArgb(0xFF, 0x99, 0xCC, 0xFF), Area3DStyle = new System.Web.UI.DataVisualization.Charting.ChartArea3DStyle() { Enable3D = false }, BackGradientStyle = System.Web.UI.DataVisualization.Charting.GradientStyle.TopBottom, AxisX = new System.Web.UI.DataVisualization.Charting.Axis() { LineWidth = 2, MaximumAutoSize = 100, Title = "Day-Time", IsMarginVisible = true, IntervalOffsetType = System.Web.UI.DataVisualization.Charting.DateTimeIntervalType.Auto, IsStartedFromZero = false }, AxisY = new System.Web.UI.DataVisualization.Charting.Axis() { LineWidth = 0 } }; QSORateChart.ChartAreas.Add(ChartAreaChartArea1); // get from combobox ChartAreaParams.ChartPointInterval = Convert.ToInt32(ChartCtlDataSettingsDto.ControlSettingsDto.ControlYaxisSettingsDto.YaxisInterval); //ChartInfo int AlphaBlend; string YaxisViewtype = ChartCtlDataSettingsDto.ControlSettingsDto.ControlYaxisSettingsDto.YaxisViewType; if (YaxisViewtype.Contains("3D")) { //strip 3d string str = YaxisViewtype.Replace("3D", ""); ChartAreaParams.charttype = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), str.Trim()); QSORateChart.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true; QSORateChart.ChartAreas["ChartArea1"].Area3DStyle.PointDepth = 75; QSORateChart.ChartAreas["ChartArea1"].Area3DStyle.PointGapDepth = 75; //QSORateChart.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 20; //QSORateChart.ChartAreas["ChartArea1"].Area3DStyle.Rotation = 20; //QSORateChart.ChartAreas["ChartArea1"].ShadowColor = Color.Transparent; //QSORateChart.ChartAreas["ChartArea1"].Area3DStyle.LightStyle= LightStyle.Realistic; AlphaBlend = 220; } else { ChartAreaParams.charttype = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), YaxisViewtype); AlphaBlend = 0xff; } ChartAreaParams.ChartXaxisInterval = 1; ChartAreaParams.ChartXaxisIntervalType = DateTimeIntervalType.Hours; //tickmarks and grids. ChartAreaParams.MajorVerticalInterval = 24; ChartAreaParams.MinorVerticalInterval = 1; ChartAreaParams.AxisXMaxFudgeSeconds = 1; //check if all years the same MixedYears = SetMixedYears(ChartCtlDataSettingsDto.DataCallInfoDto, ContestInfoDTO1, ContestInfoDTO2, ContestInfoDTO3); // get from combo box ChartAreaParams.MixedYears = MixedYears; //ChartTickmarkInfo XMajorTickMarkObj = new ChartTickmarkInfo(ChartXaxisIntervalType, 24, 5, Color.Red, 2); ChartAreaDto ChartAreaDto = new ChartAreaDto(ChartAreaParams); TickMarkInfoParams TMinfo = new TickMarkInfoParams(); GridInfoParams CgInfo = new GridInfoParams(); //Major Vertical TMinfo.IntervalType = ChartAreaDto.ChartXaxisIntervalType; TMinfo.Interval = ChartAreaDto.MajorHorizontalInterval; TMinfo.Size = 5; TMinfo.LineColor = Color.Red; TMinfo.LineWidth = 1; TMinfo.Style = TickMarkStyle.OutsideArea; ChartAreaDto.CreateChartTickmark(QSORateChart.ChartAreas["ChartArea1"].AxisX.MajorTickMark, ChartAreaDto.VerticalType.Major, TMinfo); CgInfo.IntervalType = ChartAreaDto.ChartXaxisIntervalType;// need to set for lines to appear CgInfo.Interval = ChartAreaDto.MajorHorizontalInterval; CgInfo.LineColor = Color.Red; CgInfo.LineDashStyle = ChartDashStyle.Dot; CgInfo.LineWidth = 1; ChartAreaDto.CreateChartGrid(QSORateChart.ChartAreas["ChartArea1"].AxisX.MajorGrid, ChartAreaDto.VerticalType.Major, CgInfo); //Minor Vertical TMinfo.IntervalType = ChartAreaDto.ChartXaxisIntervalType; TMinfo.Interval = ChartAreaDto.MinorHorizontalInterval; TMinfo.Size = 2; TMinfo.LineColor = Color.Black; TMinfo.LineWidth = 1; TMinfo.Style = TickMarkStyle.OutsideArea; ChartAreaDto.CreateChartTickmark(QSORateChart.ChartAreas["ChartArea1"].AxisX.MinorTickMark, ChartAreaDto.VerticalType.Minor, TMinfo); CgInfo.IntervalType = ChartAreaDto.ChartXaxisIntervalType;// need to set for lines to appear CgInfo.Interval = ChartAreaDto.MinorHorizontalInterval; CgInfo.LineColor = Color.FromArgb(37, 0, 0, 0); CgInfo.LineDashStyle = ChartDashStyle.Solid; CgInfo.LineWidth = 1; ChartAreaDto.CreateChartGrid(QSORateChart.ChartAreas["ChartArea1"].AxisX.MinorGrid, ChartAreaDto.VerticalType.Minor, CgInfo); string QSOQuery = string.Empty; ContestViewParmsDTO ContestViewParmsDTO = null; //dummy //Series ICollection<SeriesObj> SerCollection = new System.Collections.ObjectModel.Collection<SeriesObj>(); string YaxisFunction = ChartCtlDataSettingsDto.ControlSettingsDto.ControlYaxisSettingsDto.YaxisFunction; QSOLogFilter QSOFilter; QSOFilter = ChartQuery.GetQSOFilter(ChartCtlDataSettingsDto.ControlSettingsDto.ControlFiltersSettingsDto, ChartCtlDataSettingsDto.DataCallInfoDto); if (!string.IsNullOrEmpty(ChartCtlDataSettingsDto.DataCallInfoDto[0].SelectedCall) && !ChartCtlDataSettingsDto.DataCallInfoDto[0].Disabled) { QsoRadioStationFilter QsoRadioStationFilter = ChartQuery.GetQsoRadioStationFilter(ChartCtlDataSettingsDto.DataCallInfoDto[0]); ChartQuery.GetQuery(LogRepository, QSORateChart.ID, QSOFilter, QsoRadioStationFilter, ChartCtlDataSettingsDto.DataCallInfoDto[0], ChartCtlDataSettingsDto.ControlSettingsDto, ContestInfoDTO1, ChartAreaDto, YaxisFunction, out ContestViewParmsDTO, username); SeriesObj Series1Obj = new SeriesObj(ContestInfoDTO1, Color.FromArgb(AlphaBlend, Color.Blue), ChartQuery.GetDataTableSQL); bOK = Series1Obj.Create(LogRepository, ChartAreaDto, QSORateChart.ID, ContestViewParmsDTO, username); if (bOK) { QSORateChart.Series.Add(Series1Obj); SerCollection.Add(Series1Obj); } } if (!string.IsNullOrEmpty(ChartCtlDataSettingsDto.DataCallInfoDto[1].SelectedCall) && !ChartCtlDataSettingsDto.DataCallInfoDto[1].Disabled) { QsoRadioStationFilter QsoRadioStationFilter = ChartQuery.GetQsoRadioStationFilter(ChartCtlDataSettingsDto.DataCallInfoDto[1]); ChartQuery.GetQuery(LogRepository, QSORateChart.ID, QSOFilter, QsoRadioStationFilter, ChartCtlDataSettingsDto.DataCallInfoDto[1], ChartCtlDataSettingsDto.ControlSettingsDto, ContestInfoDTO2, ChartAreaDto, YaxisFunction, out ContestViewParmsDTO, username); SeriesObj Series2Obj = new SeriesObj(ContestInfoDTO2, Color.FromArgb(AlphaBlend, Color.OrangeRed), ChartQuery.GetDataTableSQL); bOK = Series2Obj.Create(LogRepository, ChartAreaDto, QSORateChart.ID, ContestViewParmsDTO, username); if (bOK) { QSORateChart.Series.Add(Series2Obj); //string st = QSORateChart.Series[Series2Obj.Name].ChartArea; //QSORateChart.Series[Series2Obj.Name].ChartArea = Chart1.ChartAreas["ChartArea1"].Name; SerCollection.Add(Series2Obj); } } if (!string.IsNullOrEmpty(ChartCtlDataSettingsDto.DataCallInfoDto[2].SelectedCall) && !ChartCtlDataSettingsDto.DataCallInfoDto[2].Disabled) { QsoRadioStationFilter QsoRadioStationFilter = ChartQuery.GetQsoRadioStationFilter(ChartCtlDataSettingsDto.DataCallInfoDto[2]); ChartQuery.GetQuery(LogRepository, QSORateChart.ID, QSOFilter, QsoRadioStationFilter, ChartCtlDataSettingsDto.DataCallInfoDto[2], ChartCtlDataSettingsDto.ControlSettingsDto, ContestInfoDTO3, ChartAreaDto, YaxisFunction, out ContestViewParmsDTO, username); SeriesObj Series3Obj = new SeriesObj(ContestInfoDTO3, Color.FromArgb(AlphaBlend, Color.SeaGreen), ChartQuery.GetDataTableSQL); bOK = Series3Obj.Create(LogRepository, ChartAreaDto, QSORateChart.ID, ContestViewParmsDTO, username); if (bOK) { QSORateChart.Series.Add(Series3Obj); SerCollection.Add(Series3Obj); } } //set 2nd titles string key = ""; foreach (SeriesObj obj in SerCollection) { switch (obj.ContestInfoDTO.CallGroup) { case Logqso.mvc.common.Enum.CallGroupEnum.CALL1: key = "Tkey1"; break; case Logqso.mvc.common.Enum.CallGroupEnum.CALL2: key = "Tkey2"; break; case Logqso.mvc.common.Enum.CallGroupEnum.CALL3: key = "Tkey3"; break; default: break; } if (obj.ContestInfoDTO.Call != string.Empty) { string OPr = string.Empty; switch (obj.ContestInfoDTO.CatOperatorEnum) { case Logqso.mvc.common.Enum.CatOperatorEnum.ALL: //should never occur break; case Logqso.mvc.common.Enum.CatOperatorEnum.SINGLE_OP: if (obj.ContestInfoDTO.CatBandEnum == common.Enum.CatBandEnum.ALL) { OPr = "SOAB"; }else{ OPr = "SOSB"; } break; case Logqso.mvc.common.Enum.CatOperatorEnum.MULTI_OP: if (obj.ContestInfoDTO.CatNoOfTxEnum == common.Enum.CatNoOfTxEnum.ONE) { OPr = "MS"; } else if (obj.ContestInfoDTO.CatNoOfTxEnum == common.Enum.CatNoOfTxEnum.TWO) { OPr = "M2"; } else{ OPr = "MM"; } break; case Logqso.mvc.common.Enum.CatOperatorEnum.CHECKLOG: OPr = "CHECKLOG"; break; default: break; } if (OPr == "SOSB") { switch (obj.ContestInfoDTO.CatBandEnum) { case Logqso.mvc.common.Enum.CatBandEnum.ALL: //doews not occur break; case Logqso.mvc.common.Enum.CatBandEnum._160M: OPr += " 160M"; break; case Logqso.mvc.common.Enum.CatBandEnum._80M: OPr += " 80M"; break; case Logqso.mvc.common.Enum.CatBandEnum._40M: OPr += " 40M"; break; case Logqso.mvc.common.Enum.CatBandEnum._20M: OPr += " 20M"; break; case Logqso.mvc.common.Enum.CatBandEnum._15M: OPr += " 15M"; break; case Logqso.mvc.common.Enum.CatBandEnum._10M: OPr += " 10M"; break; default: break; } switch (obj.ContestInfoDTO.CatPowerEnum) { case Logqso.mvc.common.Enum.CatPowerEnum.ALL: //does not occur break; case Logqso.mvc.common.Enum.CatPowerEnum.HIGH: OPr += " HIGH"; break; case Logqso.mvc.common.Enum.CatPowerEnum.LOW: OPr += " LOW"; break; case Logqso.mvc.common.Enum.CatPowerEnum.QRP: OPr += " QRP"; break; default: break; } if (obj.ContestInfoDTO.CatAssistedEnum == common.Enum.CatAssistedEnum.ASSISTED) { OPr += " Assisted"; } else { OPr += " Non-Assisted"; } } QSORateChart.Titles[key].Text += string.Format("{0} {1} {2}", obj.ContestInfoDTO.Call.PadRight(10), obj.ContestInfoDTO.ContestName, OPr); //QSORateChart.Titles[key].ForeColor = Color.FromArgb(0xff, 0, 99, 99); } } //Select Log that exists ContestInfoDTO ContestInfoDTON = null; if (ContestInfoDTO1 != null) { ContestInfoDTON = ContestInfoDTO1; } else if (ContestInfoDTO2 != null) { ContestInfoDTON = ContestInfoDTO2; } else if (ContestInfoDTO3 != null) { ContestInfoDTON = ContestInfoDTO2; } //TITLES if (ChartAreaDto.MixedYears) { QSORateChart.Titles["ChartName"].Text = ContestViewParmsDTO.sTitle; } else { if (ContestInfoDTON != null) { QSORateChart.Titles["ChartName"].Text = string.Format("{0} {1}", ContestInfoDTON.ContestID, ContestViewParmsDTO.sTitle); } } string ver = ConfigurationManager.AppSettings["AppVersion"].ToString(); QSORateChart.Titles["Vers"].Text = string.Format("Version: {0}", ver); //AXISX Font fontAxis = new Font("Times New Roman", 14, FontStyle.Bold); AxisInfoParams Ai = new AxisInfoParams(); Ai.TitleFont = fontAxis; Ai.Title = "Time"; Ai.LineWidth = 1; Ai.LabelStyleFormat = "{0:HH:mm}"; Ai.LabelStyleAngle = -90; //Date can be different but times are the same 48 hours if (ChartAreaDto.MixedYears) { if (ContestInfoDTON != null) { int days = ContestInfoDTON.endTime.AddMinutes(1).Subtract(ContestInfoDTON.startTime).Days; Ai.Minimum = DateTime.Parse("1/1/1990 " + ContestInfoDTON.startTime.TimeOfDay).ToOADate(); Ai.Maximum = DateTime.Parse("1/" + string.Format("{0}", 1 + days) + "/1990 " + ContestInfoDTON.endTime.AddSeconds(ChartAreaDto.AxisXMaxFudgeSeconds).TimeOfDay).ToOADate(); } } else { if (ContestInfoDTO1 != null && !ContestInfoDTO1.Disabled) { Ai.Minimum = ContestInfoDTO1.startTime.ToOADate(); Ai.Maximum = ContestInfoDTO1.endTime.AddSeconds(ChartAreaDto.AxisXMaxFudgeSeconds).ToOADate(); } else if (ContestInfoDTO2 != null && !ContestInfoDTO2.Disabled) { Ai.Minimum = ContestInfoDTO2.startTime.ToOADate(); Ai.Maximum = ContestInfoDTO2.endTime.AddSeconds(ChartAreaDto.AxisXMaxFudgeSeconds).ToOADate(); } else if ( ContestInfoDTO3 != null && !ContestInfoDTO3.Disabled) { Ai.Minimum = ContestInfoDTO3.startTime.ToOADate(); Ai.Maximum = ContestInfoDTO3.endTime.AddSeconds(ChartAreaDto.AxisXMaxFudgeSeconds).ToOADate(); } } Ai.IntervalType = ChartAreaDto.ChartXaxisIntervalType; Ai.Interval = ChartAreaDto.MinorHorizontalInterval; ChartAreaDto.InitChartAxis(QSORateChart.ChartAreas["ChartArea1"].AxisX, Ai); // set second row of labels QSORateChart.ChartAreas["ChartArea1"].AxisX.CustomLabels.Add(24, ChartAreaDto.ChartXaxisIntervalType, "Day {0:dd}", 2, LabelMarkStyle.LineSideMark); //QSORateChart.ChartAreas["ChartArea1"].AxisX.LabelAutoFitStyle = LabelAutoFitStyles.DecreaseFont | LabelAutoFitStyles.StaggeredLabels | LabelAutoFitStyles.LabelsAngleStep90; //QSORateChart.Series[Series1Obj.Name].AxisLabel = "#VALX{dd}\n#VALX{MMM}\n#VALX{yyy}"; //QSORateChart.ChartAreas["ChartArea1"].AxisX.LabelStyle.IsEndLabelVisible = true; //QSORateChart.ChartAreas["ChartArea1"].InnerPlotPosition = new ElementPosition(0, 0, 90, 100); //QSORateChart.ChartAreas["ChartArea1"].AxisX.IntervalOffset = 15; //QSORateChart.ChartAreas["ChartArea1"].AxisX.IntervalOffsetType = DateTimeIntervalType.Minutes; //TabContainerCall.Controls.Add( ////SCALEVIEW int startHour = Convert.ToInt32(ChartCtlDataSettingsDto.ControlSettingsDto.ControlXaxisSettingsDto.XaxisStarttime.Substring(0, 2)); int Size = Convert.ToInt32(ChartCtlDataSettingsDto.ControlSettingsDto.ControlXaxisSettingsDto.XaxisDuration); if (Size != 48) { int Day = 1; if (ChartCtlDataSettingsDto.ControlSettingsDto.ControlXaxisSettingsDto.XaxisStarttime.Contains("Day2")) { Day = 2; } QSORateChart.ChartAreas["ChartArea1"].AxisX.IsStartedFromZero = true; DateTime pos; if (ChartAreaDto.MixedYears) { pos = new DateTime(1990, 1, Day, startHour, 00, 00); } else { if (ContestInfoDTON != null) { if (Day == 2) { pos = ContestInfoDTON.startTime.AddDays(1).AddHours(startHour); } else { pos = ContestInfoDTON.startTime.AddHours(startHour); } }else { pos = new DateTime(1990, 1, Day, startHour, 00, 00); } } QSORateChart.ChartAreas["ChartArea1"].AxisX.ScaleView.Position = pos.ToOADate(); QSORateChart.ChartAreas["ChartArea1"].AxisX.ScaleView.Size = Size;// count of ScaleView.SizeType QSORateChart.ChartAreas["ChartArea1"].AxisX.ScaleView.SizeType = ChartAreaParams.ChartXaxisIntervalType; } //AXISY //QSORateChart.ImageLocation QSORateChart.ChartAreas["ChartArea1"].AxisY.TitleFont = fontAxis; QSORateChart.ChartAreas["ChartArea1"].AxisY.Title = ContestViewParmsDTO.sYAxis; QSORateChart.ChartAreas["ChartArea1"].AxisY.LabelStyle.Format = "{0:n0}"; if (ChartCtlDataSettingsDto.ControlSettingsDto.ControlYaxisSettingsDto.YaxisFunction.Contains("Sum")) { QSORateChart.ChartAreas["ChartArea1"].AxisY.Enabled = AxisEnabled.False; } QSORateChart.ChartAreas["ChartArea1"].AxisY2.Enabled = AxisEnabled.True; QSORateChart.ChartAreas["ChartArea1"].AxisY2.LineWidth = 0; QSORateChart.ChartAreas["ChartArea1"].AxisY2.LabelStyle.Format = "{0:n0}"; QSORateChart.ChartAreas["ChartArea1"].Position = new ElementPosition(0, 10, 100, 80); QSORateChart.Titles["ChartName"].Position = new ElementPosition(2, 0, 50, 10); QSORateChart.Legends["Legend1"].Position = new ElementPosition(50, 1, 50, 9); // LEGENDS QSORateChart.Legends["Legend1"].ForeColor = Color.DarkOliveGreen; Font fontLegend = new Font("Times New Roman", 11, FontStyle.Bold, GraphicsUnit.Point); QSORateChart.Legends["Legend1"].Font = fontLegend; QSORateChart.Legends["Legend1"].Position.Height = 7; // draw! //QSORateChart.Invalidate(); //string path = Server.MapPath("~/ChartImages/chart.png"); try { //String filePath = HostingEnvironment.MapPath("~/Image/charttest.png"); //QSORateChart.SaveImage(filePath, System.Web.UI.DataVisualization.Charting.ChartImageFormat.Png); //FileStream fileStream = new FileStream(filePath, FileMode.Open); //Image image = System.Drawing.Image.FromStream(fileStream); //MemoryStream memoryStream = new MemoryStream(); //image.Save(memoryStream, ImageFormat.Png); MemoryStream = new MemoryStream(); QSORateChart.SaveImage(MemoryStream, ChartImageFormat.Png); } catch (Exception ex) { throw; } return MemoryStream; }
public ActionResult RateChart1() { Dictionary<string, int> chartList = new Dictionary<string, int>(); chartList.Add("1 star:",23); chartList.Add("2 star:",43); chartList.Add("3 star:",34); chartList.Add("4 star:",52); chartList.Add("5 star:",48); int tong = 0; foreach (int i in chartList.Values) tong = tong + i; ViewData["Chart"] = chartList; System.Web.UI.DataVisualization.Charting.Chart Chart2 = new System.Web.UI.DataVisualization.Charting.Chart(); Chart2.Width = 150; Chart2.Height = 120; Chart2.RenderType = RenderType.ImageTag; Chart2.BackColor = System.Drawing.Color.AliceBlue; //Chart2.Palette = ChartColorPalette.EarthTones; Chart2.Palette = ChartColorPalette.BrightPastel; Chart2.BackGradientStyle = GradientStyle.DiagonalRight; Chart2.BackSecondaryColor = System.Drawing.Color.Orange; Title t = new Title(tong + " reviews" , Docking.Top, new System.Drawing.Font("Trebuchet MS", 9, System.Drawing.FontStyle.Bold), System.Drawing.Color.FromArgb(26, 59, 105)); t.Position.X = 50; t.Position.Y = 10; Chart2.Titles.Add(t); Chart2.ChartAreas.Add("Series 1"); Chart2.ChartAreas["Series 1"].AxisX.MajorGrid.Enabled = false; Chart2.ChartAreas["Series 1"].AxisX.MajorTickMark.Enabled = true; Chart2.ChartAreas["Series 1"].AxisX.MajorTickMark.LineWidth = 0; Chart2.ChartAreas["Series 1"].AxisX.MajorTickMark.Interval = 0; Chart2.ChartAreas["Series 1"].AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8, System.Drawing.FontStyle.Regular); Chart2.ChartAreas["Series 1"].AxisY.Enabled =AxisEnabled.False; //Chart2.ChartAreas["Series 1"].AxisY.LabelStyle.Enabled = false; Chart2.ChartAreas["Series 1"].BorderDashStyle = ChartDashStyle.Dot; Chart2.ChartAreas["Series 1"].BackColor = System.Drawing.Color.AliceBlue; Chart2.ChartAreas["Series 1"].BackGradientStyle = GradientStyle.DiagonalRight; Chart2.ChartAreas["Series 1"].BackSecondaryColor = System.Drawing.Color.Orange; // create a couple of series Chart2.Series.Add("Series 1"); Chart2.Series["Series 1"].ChartType = SeriesChartType.Bar; Chart2.Series["Series 1"].IsValueShownAsLabel = true; //Chart2.Series["Series 1"].SmartLabelStyle. //Chart2.Series["Series 1"].EmptyPointStyle.Font = new System.Drawing.Font("Trebuchet MS", 6, System.Drawing.FontStyle.Bold); // add points to series 1 foreach (KeyValuePair<string,int> value in ((Dictionary<string, int>)ViewData["Chart"])) { Chart2.Series["Series 1"].Points.AddXY(value.Key, value.Value); } Chart2.Series["Series 1"].Color = System.Drawing.Color.OrangeRed; Chart2.Series["Series 1"].Font = new System.Drawing.Font("Trebuchet MS", 7, System.Drawing.FontStyle.Bold); Chart2.BorderSkin.SkinStyle = BorderSkinStyle.Sunken; Chart2.BorderColor = System.Drawing.Color.FromArgb(26, 59, 105); Chart2.BorderlineDashStyle = ChartDashStyle.Solid; Chart2.BorderWidth = 0; // Render chart control //Chart2.Page = this; //HtmlTextWriter writer = new HtmlTextWriter(ControllerContext.ParentActionViewContext.Writer); //Chart2.RenderControl(writer); var returnStream = new MemoryStream(); Chart2.ImageType = ChartImageType.Png; Chart2.SaveImage(returnStream); returnStream.Position = 0; return new FileStreamResult(returnStream, "image/png"); }