/// <summary> /// Basic constructor that saves a reference to the parent /// <see cref="GraphPane"/> object. /// </summary> /// <param name="pane">The parent <see cref="GraphPane"/> object.</param> /// <param name="initialize">A <see cref="bool"/> flag to indicate whether or /// not the drawing variables should be initialized. Initialization is not /// required if this is part of a ZedGraph internal draw operation (i.e., its in /// the middle of a call to <see cref="GraphPane.Draw"/>). Otherwise, you should /// initialize to make sure the drawing variables are configured. true to do /// an initialization, false otherwise.</param> public ValueHandler(GraphPane pane, bool initialize) { _pane = pane; if (initialize) // just create a dummy image, which results in a full draw operation { using (Image image = pane.GetImage()) {} } }
/// <summary> /// Basic constructor that saves a reference to the parent /// <see cref="GraphPane"/> object. /// </summary> /// <param name="pane">The parent <see cref="GraphPane"/> object.</param> /// <param name="initialize">A <see cref="bool"/> flag to indicate whether or /// not the drawing variables should be initialized. Initialization is not /// required if this is part of a ZedGraph internal draw operation (i.e., its in /// the middle of a call to <see cref="GraphPane.Draw"/>). Otherwise, you should /// initialize to make sure the drawing variables are configured. true to do /// an initialization, false otherwise.</param> public ValueHandler(GraphPane pane, bool initialize) { _pane = pane; if (initialize) { // just create a dummy image, which results in a full draw operation using (Image image = pane.GetImage()) { } } }
/// <summary> /// Bar chart. /// </summary> /// <param name="query">The query.</param> /// <param name="_options">GraphOptions.</param> /// <param name="binaryOutput">if set to <c>true</c> the image will output in the response stream.</param> /// <returns></returns> public static System.Drawing.Bitmap BarChart( string query, Dictionary<string, object> _options, bool binaryOutput ) { ( "FUNCTION /w binaryStream barChart" ).Debug( 10 ); /* * 0 = name * 1 = value * 2 = color1 * 3 = color2 * 4 = angle */ GraphOptions options = null; JToken jtOpt = JToken.FromObject( _options ); using( JTokenReader tr = new JTokenReader( jtOpt ) ) { JsonSerializer serializer = new JsonSerializer(); options = ( GraphOptions )serializer.Deserialize( tr, typeof( GraphOptions ) ); } System.Drawing.Bitmap image = null; GraphPane myPane = null; using(SqlConnection cn = Site.CreateConnection(true, true)) { cn.Open(); try { using(SqlCommand cmd = new SqlCommand(query, cn)) { myPane = new GraphPane(new System.Drawing.Rectangle(0, 0, options.Width, options.Height), options.Title, "", ""); myPane.Title.Text = options.Title; myPane.XAxis.Title.Text = options.XAxisTitle; myPane.YAxis.Title.Text = options.YAxisTitle; if(options.Orientation) { myPane.YAxis.Type = AxisType.Ordinal; } else { myPane.XAxis.Type = AxisType.Ordinal; } float barLocation = 0; using(SqlDataReader r = cmd.ExecuteReader()) { if(r.HasRows) { while(r.Read()) { PointPairList list = new PointPairList(); if(options.Orientation) { list.Add(Convert.ToDouble(r.GetValue(1)), barLocation); BarItem myCurve = myPane.AddBar(r.GetString(0), list, System.Drawing.Color.FromName(r.GetString(2))); myCurve.Bar.Fill = new Fill( System.Drawing.Color.FromName(r.GetString(2)), System.Drawing.Color.FromName(r.GetString(3)), System.Drawing.Color.FromName(r.GetString(2)), (float)r.GetInt32(4) ); } else { list.Add(barLocation, Convert.ToDouble(r.GetValue(1))); BarItem myCurve = myPane.AddBar(r.GetString(0), list, System.Drawing.Color.FromName(r.GetString(2))); myCurve.Bar.Fill = new Fill( System.Drawing.Color.FromName(r.GetString(2)), System.Drawing.Color.FromName(r.GetString(3)), (float)r.GetInt32(4) ); } barLocation += options.BarSpacing; } }else{ if(image == null) { image = new Bitmap(700, 700); } image = WriteImageError(image, options.NoDataMessage, options.FontFamily, options.XAxisFontSize); return image; } } if(options.Orientation) { myPane.YAxis.IsVisible = false; //myPane.YAxis.Scale.Max=barLocation; myPane.YAxis.Scale.Min = 0; myPane.BarSettings.Base = BarBase.Y; } else { myPane.XAxis.IsVisible = false; myPane.XAxis.Scale.Min = 0; //myPane.XAxis.Scale.Max=barLocation-options.barSpacing; myPane.BarSettings.Base = BarBase.X; } // Fill the chart background with a color gradient myPane.Chart.Fill = new Fill( System.Drawing.Color.FromName(options.Fill.StartColor), System.Drawing.Color.FromName(options.Fill.EndColor), options.Fill.Angle); myPane.AxisChange(); // Create TextObj's to provide labels for each bar BarItem.CreateBarLabels(myPane, false, "f0"); image = myPane.GetImage(true); using(MemoryStream ms = new MemoryStream()) { image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); if(HttpContext.Current != null) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "image/png"; HttpContext.Current.Response.AddHeader("Expires", "0");/* RFC 2616 14.21 Content has already expired */ HttpContext.Current.Response.AddHeader("Cache-Control", "no-store");/* RFC 2616 14.9.2 Don't ever cache */ HttpContext.Current.Response.AddHeader("Pragma", "no-store");/* RFC 2616 14.32 Pragma - same as cache control */ ms.WriteTo(HttpContext.Current.Response.OutputStream); } } } } catch(Exception ex) { if(image == null) { image = new Bitmap(700, 700); } image = WriteImageError(image, ex.Message, "Arial", 8f); } } return image; }
/// <summary> /// Creates a tic chart based on the query batch. /// </summary> /// <param name="query">The query batch. Each line is a seperate query batch. The query should look like: /// 0:name, 1:x, 2:y, 3:colorName, 4:fillColorName, 5:lineWidth, 6:ticSize.</param> /// <param name="_options">GraphOptions.</param> /// <param name="binaryOutput">if set to <c>true</c> the image will output in the response stream.</param> /// <returns></returns> public static System.Drawing.Bitmap TicChart( string query, Dictionary<string, object> _options, bool binaryOutput ) { ( "FUNCTION /w binaryStream ticChart" ).Debug( 10 ); /* query expects two columns * 0 name * 1 x * 2 y * 3 color * 4 fill color * 5 line Width * 6 symbol size */ JToken jtOpt = JToken.FromObject( _options ); JsonSerializer serializer = new JsonSerializer(); GraphOptions options = ( GraphOptions )serializer.Deserialize( new JTokenReader( jtOpt ), typeof( GraphOptions ) ); System.Drawing.Bitmap image = null; GraphPane myPane = null; using(SqlConnection cn = Site.CreateConnection(true, true)) { cn.Open(); try{ using(SqlCommand cmd = new SqlCommand(query, cn)) { myPane = new GraphPane(new System.Drawing.Rectangle(0, 0, options.Width, options.Height), options.Title, "", ""); // Set the titles and axis labels myPane.Title.Text = options.Title; myPane.XAxis.Title.Text = options.XAxisTitle; myPane.YAxis.Title.Text = options.YAxisTitle; myPane.XAxis.Type = AxisType.Date; myPane.XAxis.Scale.FontSpec.Angle = options.XAxisFontAngle; myPane.XAxis.Scale.FontSpec.Size = options.XAxisFontSize; myPane.XAxis.Scale.Format = options.XAxisFormat; using(SqlDataReader r = cmd.ExecuteReader()) { float lineWidth = 4.5f; ZedGraph.Fill fill = new Fill(System.Drawing.Color.White); float size = 5; string label = ""; System.Drawing.Color symbolColor = System.Drawing.Color.Black; bool nextResult = r.HasRows; while(nextResult) { int count = 0; PointPairList list = new PointPairList(); while(r.Read()) { lineWidth = (float)Convert.ToDouble(r.GetValue(5)); fill = new Fill(System.Drawing.Color.FromName(r.GetString(4))); size = (float)Convert.ToDouble(r.GetValue(6)); label = r.GetString(0); symbolColor = System.Drawing.Color.FromName(r.GetString(3)); list.Add(new XDate(r.GetDateTime(1)), Convert.ToDouble(r.GetValue(2))); count++; } LineItem curve = myPane.AddCurve(label, list, symbolColor, SymbolType.Circle); curve.Line.Width = lineWidth; curve.Symbol.Fill = fill; curve.Symbol.Size = size; nextResult = r.NextResult(); if(options.NodeLabel) { const double offset = 1.0; // Loop to add text labels to the points for(int i = 0; i < count; i++) { // Get the pointpair PointPair pt = curve.Points[i]; // Create a text label from the Y data value TextObj text = new TextObj(pt.Y.ToString(options.NodeLabelFormat), pt.X, pt.Y + offset, CoordType.AxisXYScale, AlignH.Left, AlignV.Center); text.FontSpec.Size = options.NodeLabelFontSize; text.ZOrder = ZOrder.A_InFront; // Hide the border and the fill text.FontSpec.Border.IsVisible = false; text.FontSpec.Fill.IsVisible = false; // text.FontSpec.Fill = new Fill( Color.FromArgb( 100, Color.White ) ); // Rotate the text to 90 degrees text.FontSpec.Angle = options.NodeLabelRotation; myPane.GraphObjList.Add(text); } } } } } myPane.Legend.IsVisible = options.ShowLegend; myPane.XAxis.Scale.MinGrace = 0; myPane.XAxis.Scale.MaxGrace = 0; // Fill the axis background with a gradient myPane.Chart.Fill = new Fill(System.Drawing.Color.FromName(options.Fill.StartColor), System.Drawing.Color.FromName(options.Fill.EndColor), options.Fill.Angle); myPane.AxisChange(); image = myPane.GetImage(true); } catch(Exception ex) { if(image == null) { image = new Bitmap(700, 700); } image = WriteImageError(image, ex.Message, "Arial", 8f); } if(binaryOutput) { using(MemoryStream ms = new MemoryStream()) { image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); if(HttpContext.Current != null) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "image/png"; HttpContext.Current.Response.AddHeader("Expires", "0");/* RFC 2616 14.21 Content has already expired */ HttpContext.Current.Response.AddHeader("Cache-Control", "no-store");/* RFC 2616 14.9.2 Don't ever cache */ HttpContext.Current.Response.AddHeader("Pragma", "no-store");/* RFC 2616 14.32 Pragma - same as cache control */ ms.WriteTo(HttpContext.Current.Response.OutputStream); } } } } return image; }
/// <summary> /// Creates a pie chart from a JSON request. /// </summary> /// <param name="query">Query batch.</param> /// <param name="_options">GraphOptions.</param> /// <param name="binaryOutput">if set to <c>true</c> the image will output in the response stream.</param> /// <returns></returns> public static System.Drawing.Bitmap PieChart( string query, Dictionary<string, object> _options, bool binaryOutput ) { ( "FUNCTION /w binaryStream pieChart" ).Debug( 10 ); /* query expects two columns * 0 name * 1 value * 2 color1 (or null) * 3 color2 (or null) */ JToken jtOpt = JToken.FromObject( _options ); JsonSerializer serializer = new JsonSerializer(); GraphOptions options = ( GraphOptions )serializer.Deserialize( new JTokenReader( jtOpt ), typeof( GraphOptions ) ); if( options.Width == 0 || options.Height == 0 ) { /*bad image size defined */ return null; } System.Drawing.Bitmap image = null; GraphPane myPane = null; using(SqlConnection cn = Site.CreateConnection(true, true)) { cn.Open(); try { using(SqlCommand cmd = new SqlCommand(query, cn)) { myPane = new GraphPane(new System.Drawing.Rectangle(0, 0, options.Width, options.Height), options.Title, "", ""); // Set the GraphPane title myPane.Title.Text = options.Title; myPane.Title.FontSpec.IsItalic = options.IsItalic; myPane.Title.FontSpec.Size = options.TitleFontSize; myPane.Title.FontSpec.Family = options.FontFamily; System.Drawing.Color fill1 = System.Drawing.Color.FromName(options.Fill.StartColor); System.Drawing.Color fill2 = System.Drawing.Color.FromName(options.Fill.EndColor); // Fill the pane background with a color gradient myPane.Fill = new Fill(fill1, fill2, options.Fill.Angle); // No fill for the chart background myPane.Chart.Fill.Type = FillType.None; // Set the legend to an arbitrary location myPane.Legend.IsVisible = options.ShowLegend; myPane.Legend.Position = LegendPos.Float; myPane.Legend.Location = new Location(0.95f, 0.15f, CoordType.PaneFraction, AlignH.Right, AlignV.Top); myPane.Legend.FontSpec.Size = 10f; myPane.Legend.IsHStack = false; List<PieItem> segments = new List<PieItem>(); using(SqlDataReader r = cmd.ExecuteReader()) { while(r.Read()) { System.Drawing.Color color1 = System.Drawing.Color.FromName(r.GetString(2)); System.Drawing.Color color2 = System.Drawing.Color.FromName(r.GetString(3)); PieItem s = myPane.AddPieSlice(Convert.ToDouble(r.GetValue(1)), color1, color2, 45f, 0, r.GetString(0)); if(r.GetValue(1).GetType() == typeof(decimal)) { s.Label.Text = r.GetString(0) + ' ' + r.GetDecimal(1).ToString(options.NodeLabelFormat); } else { s.Label.Text = s.Label.Text = r.GetString(0) + ' ' + Convert.ToString(r.GetValue(1)); } segments.Add(s); } } } // Sum up the pie values CurveList curves = myPane.CurveList; double total = 0; for(int x = 0; x < curves.Count; x++) total += ((PieItem)curves[x]).Value; // Calculate the Axis Scale Ranges myPane.AxisChange(); image = myPane.GetImage(true); } catch(Exception ex) { if(image == null) { image = new Bitmap(700, 700); } image = WriteImageError(image, ex.Message, "Arial", 8f); } if(binaryOutput) { using(MemoryStream ms = new MemoryStream()) { image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); if(HttpContext.Current != null) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "image/png"; HttpContext.Current.Response.AddHeader("Expires", "0");/* RFC 2616 14.21 Content has already expired */ HttpContext.Current.Response.AddHeader("Cache-Control", "no-store");/* RFC 2616 14.9.2 Don't ever cache */ HttpContext.Current.Response.AddHeader("Pragma", "no-store");/* RFC 2616 14.32 Pragma - same as cache control */ ms.WriteTo(HttpContext.Current.Response.OutputStream); } } image.Dispose(); if(HttpContext.Current != null) { HttpContext.Current.Response.Flush(); HttpContext.Current.ApplicationInstance.CompleteRequest(); } } } return image; }
/// <summary> /// Gas gauge chart. /// </summary> /// <param name="query">The query.</param> /// <param name="_options">GraphOptions.</param> /// <param name="binaryOutput">if set to <c>true</c> the image will output in the response stream.</param> /// <returns></returns> public static System.Drawing.Bitmap GasGauge( string query, Dictionary<string, object> _options, bool binaryOutput ) { ( "FUNCTION /w binaryStream gasGauge" ).Debug( 10 ); JToken jtOpt = JToken.FromObject( _options ); JsonSerializer serializer = new JsonSerializer(); GraphOptions options = null; using( JTokenReader jtr = new JTokenReader( jtOpt ) ) { options = ( GraphOptions )serializer.Deserialize( jtr, typeof( GraphOptions ) ); } GraphPane myPane = new GraphPane( new System.Drawing.Rectangle( 0, 0, options.Width, options.Height ), options.Title, "", "" ); myPane.Title.Text = options.Title; // Define the title myPane.Title.Text = "Gas Gauge Demo"; // Fill the pane with gray myPane.Fill = new Fill( System.Drawing.Color.LightGray, System.Drawing.Color.White, 45.0f ); // Fill the chart rect with blue myPane.Chart.Fill = new Fill( System.Drawing.Color.White, System.Drawing.Color.SkyBlue, 45.0f ); // Don't show any axes for the gas gauge myPane.XAxis.IsVisible = false; myPane.Y2Axis.IsVisible = false; myPane.YAxis.IsVisible = false; //Define needles; can add more than one GasGaugeNeedle gg1 = new GasGaugeNeedle( "Cereal", 30.0f, System.Drawing.Color.Black ); GasGaugeNeedle gg2 = new GasGaugeNeedle( "Milk", 80.0f, System.Drawing.Color.DarkGreen ); myPane.CurveList.Add( gg1 ); myPane.CurveList.Add( gg2 ); //Define all regions GasGaugeRegion ggr1 = new GasGaugeRegion( "Red", 0.0f, 33.0f, System.Drawing.Color.Red ); GasGaugeRegion ggr2 = new GasGaugeRegion( "Yellow", 33.0f, 66.0f, System.Drawing.Color.Yellow ); GasGaugeRegion ggr3 = new GasGaugeRegion( "Green", 66.0f, 100.0f, System.Drawing.Color.Green ); // Add the curves myPane.CurveList.Add( ggr1 ); myPane.CurveList.Add( ggr2 ); myPane.CurveList.Add( ggr3 ); System.Drawing.Bitmap image = myPane.GetImage( true ); if( binaryOutput ) { using( MemoryStream ms = new MemoryStream() ) { image.Save( ms, System.Drawing.Imaging.ImageFormat.Png ); if(HttpContext.Current!=null){ HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "image/png"; HttpContext.Current.Response.AddHeader( "Expires", "0" );/* RFC 2616 14.21 Content has already expired */ HttpContext.Current.Response.AddHeader( "Cache-Control", "no-store" );/* RFC 2616 14.9.2 Don't ever cache */ HttpContext.Current.Response.AddHeader( "Pragma", "no-store" );/* RFC 2616 14.32 Pragma - same as cache control */ ms.WriteTo( HttpContext.Current.Response.OutputStream ); } } image.Dispose(); } return image; }
//meta: 0.Graph Name, 1.Labelfor X, 2.Label for Y static void plotMeasrdAndTyp(string site_code, string second_site, string var_code, string var_name, DateTime dStart, DateTime dEnd, dbConnection dataObject, string[] meta) { /* * clsRemoveDataGaps.missingValues(ref ptList); */ double lBnd = Convert.ToDouble( meta[3]); double upBnd = Convert.ToDouble(meta[4]); float graphWidth = 4.0f; PointPairList MeasUpper = getData(site_code, var_code, dStart, dEnd, dataObject, lBnd, upBnd); //MeasUpper = cleanValues(MeasUpper, dataObject.getDVCstm(site_code, var_code, dStart, dEnd)); PointPairList TypAvgUpper = getDataTyp(site_code, var_code, dataObject, lBnd, upBnd ); //getDailyAvg(MeasUpper); PointPairList MeasLower = getData(second_site, var_code, dStart, dEnd, dataObject, lBnd, upBnd); //MeasLower = cleanValues(MeasLower, dataObject.getDVCstm(site_code, var_code, dStart, dEnd)); PointPairList TypAvgLower = getDataTyp(second_site, var_code, dataObject, lBnd, upBnd); //getDailyAvg(MeasLower); //Measured Graph. -- Display all data. From January 1st. -- GraphPane graphPaneMeas = new GraphPane(new Rectangle(0, 0, 1680, 1050), "Measured Values", meta[1], meta[2]); graphPaneMeas.XAxis.Title.Text = "Date"; graphPaneMeas.XAxis.Type = AxisType.Date; formatXaxis(ref graphPaneMeas); LineItem upperSite_M = new LineItem(site_code == "LR_WaterLab_AA" ? "Logan River Upper Site" : "Little Bear River Upper Site", MeasUpper, Color.Black, SymbolType.None, graphWidth); LineItem lowerSite_M = new LineItem(site_code == "LR_WaterLab_AA" ? "Logan River Lower Site" : "Little Bear River Lower Site", MeasLower, Color.Blue, SymbolType.None, graphWidth); graphPaneMeas.CurveList.Add(upperSite_M); graphPaneMeas.CurveList.Add(lowerSite_M); double miny = 99999; double maxy = -99999; foreach (CurveItem c in graphPaneMeas.CurveList) { for (int i = 0; i < c.Points.Count; i += 1) { if (c.Points[i].Y < miny) miny = c.Points[i].Y; if (c.Points[i].Y > maxy) maxy = c.Points[i].Y; } } formatYaxis(ref graphPaneMeas, maxy, miny); //Typical Graph. -- Daily averaged. Full Year Plotting. -- GraphPane graphPaneTyp = new GraphPane(new Rectangle(0, 0, 1680, 1050), "Typical Values", meta[1], meta[2]); graphPaneTyp.XAxis.Title.Text = "Date"; graphPaneTyp.XAxis.Type = AxisType.Date; formatXaxis(ref graphPaneTyp); LineItem upperSite_T = new LineItem(site_code == "LR_WaterLab_AA" ? "Logan River Upper Site" : "Little Bear River Upper Site", TypAvgUpper, Color.Black, SymbolType.None, graphWidth); graphPaneTyp.CurveList.Add(upperSite_T); LineItem lowerSite_T = new LineItem(site_code == "LR_WaterLab_AA" ? "Logan River Lower Site" : "Little Bear River Lower Site", TypAvgLower, Color.Blue, SymbolType.None, graphWidth); graphPaneTyp.CurveList.Add(lowerSite_T); miny = 99999; maxy = -99999; //find the max and min values of the two series foreach(CurveItem c in graphPaneTyp.CurveList){ for ( int i =0; i < c.Points.Count; i +=1){//Point p in c.Points){ if (c.Points[i].Y < miny) miny = c.Points[i].Y; if (c.Points[i].Y > maxy) maxy = c.Points[i].Y; } } formatYaxis(ref graphPaneTyp, maxy, miny); Bitmap bm = new Bitmap(1, 1); using (Graphics g = Graphics.FromImage(bm)) graphPaneMeas.AxisChange(g); graphPaneMeas.GetImage().Save(Properties.Settings.Default.imagePath + "\\" + @"measured_" + site_code + "_" + second_site + "_" + var_code + ".png", ImageFormat.Png); Bitmap bm2 = new Bitmap(1, 1); using (Graphics g2 = Graphics.FromImage(bm2)) graphPaneTyp.AxisChange(g2); graphPaneTyp.GetImage().Save(Properties.Settings.Default.imagePath + "\\"+ @"typical_" + site_code + "_" + second_site + "_" + var_code + ".png", ImageFormat.Png); }
private void CreatePercentGraph(OSPCResult r) { GraphPane g = new GraphPane(GraphRect, "Distribution of % similarity", "-", "% similarity"); SetupGraph(g); var lst = r.Results.SelectMany(i => new[] { 100.0 * i.SimilarityA, 100.0 * i.SimilarityB }).OrderBy(i => i).ToArray(); var c = g.AddCurve("Similarity", Enumerable.Range(1, lst.Length).Select(i => (double)i).ToArray(), lst, Color.Red); c.Symbol.IsVisible = false; #if SHOW_DERIVATION_2 var derv_2 = lst.CalcDerv2(); c = g.AddCurve("Derivation 2", Enumerable.Range(1, derv_2.Length).Select(i => (double)i).ToArray(), derv_2.ToArray(), Color.Green); c.IsY2Axis = true; c.Symbol.IsVisible = false; #endif AddLine(g, 100.0 * r.AVG_Similarity, Color.Blue, "Avg"); AddLine(g, 100.0 * r.POI_Similarity, Color.Green, "POI"); g.AxisChange(); using (var img = g.GetImage(512, 256, 72.0f)) { img.Save(Path.Combine(OutPath, "PercentGraph.png"), ImageFormat.Png); } }
public void UpdateGraph() { try { try { DateTime startTime = DateTime.Now; // Take a copy of the metrics file. if (File.Exists(m_metricsFileCopyName)) { File.Delete(m_metricsFileCopyName); } logger.Debug("Copying " + m_metricsFileName + " to " + m_metricsFileCopyName); File.Copy(m_metricsFileName, m_metricsFileCopyName); StreamReader metricsReader = new StreamReader(m_metricsFileCopyName); m_totalSIPPacketsList.Clear(); m_sipRequestsInList.Clear(); m_sipResponsesInList.Clear(); m_sipRequestsOutList.Clear(); m_sipResponsesOutList.Clear(); m_pendingTransactionsList.Clear(); m_discardsList.Clear(); m_unrecognisedList.Clear(); m_tooLargeList.Clear(); m_badSIPList.Clear(); m_stunList.Clear(); m_totalParseTimeList.Clear(); m_avgParseTimeList.Clear(); m_sipMethodsLists = new Dictionary<SIPMethodsEnum, RollingPointPairList>(); m_topTalkersLists.Clear(); m_topTalkersCount.Clear(); string metricsLine = metricsReader.ReadLine(); int sampleCount = 0; while (metricsLine != null) { #region Process metrics line. if (metricsLine.Trim().Length != 0 && Regex.Match(metricsLine, ",").Success) { string[] fields = metricsLine.Split(','); XDate sampleDate = new XDate(DateTime.Parse(fields[1])); int samplePeriod = Convert.ToInt32(fields[2]); // Sample period in seconds. if (samplePeriod == 0) { throw new ApplicationException("The sample period for a measurement was 0 in SIPTransportMetricsGraphAgent."); } if (metricsLine.StartsWith(m_trafficMetrics)) { try { m_totalSIPPacketsList.Add(sampleDate, Convert.ToDouble(fields[3]) / samplePeriod); m_sipRequestsInList.Add(sampleDate, Convert.ToDouble(fields[4]) / samplePeriod); m_sipResponsesInList.Add(sampleDate, Convert.ToDouble(fields[5]) / samplePeriod); m_sipRequestsOutList.Add(sampleDate, Convert.ToDouble(fields[6]) / samplePeriod); m_sipResponsesOutList.Add(sampleDate, Convert.ToDouble(fields[7]) / samplePeriod); m_pendingTransactionsList.Add(sampleDate, Convert.ToDouble(fields[8])); m_unrecognisedList.Add(sampleDate, Convert.ToDouble(fields[9]) / samplePeriod); m_badSIPList.Add(sampleDate, Convert.ToDouble(fields[10]) / samplePeriod); m_stunList.Add(sampleDate, Convert.ToDouble(fields[11]) / samplePeriod); m_discardsList.Add(sampleDate, Convert.ToDouble(fields[12]) / samplePeriod); m_tooLargeList.Add(sampleDate, Convert.ToDouble(fields[13]) / samplePeriod); m_totalParseTimeList.Add(sampleDate, Convert.ToDouble(fields[14]) / samplePeriod); m_avgParseTimeList.Add(sampleDate, Convert.ToDouble(fields[15])); sampleCount++; } catch (Exception sampleExcp) { logger.Warn("Could not process metrics sample: " + metricsLine + ". " + sampleExcp.Message); } } else if (metricsLine.StartsWith(m_methodMetrics)) { for (int index = 3; index < fields.Length; index++) { string[] methodSplit = fields[index].Split('='); SIPMethodsEnum method = SIPMethods.GetMethod(methodSplit[0]); int methodPackets = Convert.ToInt32(methodSplit[1]) / samplePeriod; if(!m_sipMethodsLists.ContainsKey(method)) { m_sipMethodsLists.Add(method, new RollingPointPairList(GRAPH_SAMPLES)); } m_sipMethodsLists[method].Add(sampleDate, methodPackets); } } else if (metricsLine.StartsWith(m_topTalkerMetrics)) { for (int index = 3; index < fields.Length; index++) { string[] talkersSplit = fields[index].Split('='); string topTalkerSocket = talkersSplit[0]; int topTalkerPackets = Convert.ToInt32(talkersSplit[1]) / samplePeriod; if (!m_topTalkersLists.ContainsKey(topTalkerSocket)) { m_topTalkersLists.Add(topTalkerSocket, new RollingPointPairList(GRAPH_SAMPLES)); m_topTalkersCount.Add(topTalkerSocket, 0); } //logger.Debug("Adding point for " + topTalkerSocket + " and " + topTalkerPackets + "."); m_topTalkersLists[topTalkerSocket].Add(sampleDate, topTalkerPackets); m_topTalkersCount[topTalkerSocket] = m_topTalkersCount[topTalkerSocket] + topTalkerPackets; } } } #endregion metricsLine = metricsReader.ReadLine(); } metricsReader.Close(); #region Create the traffic graphs. GraphPane totalSIPPacketsGraphPane = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "Total SIP Packets per Second", "Time", "Packets/s"); GraphPane pendingSIPTransactionsGraphPane = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "Pending SIP Transactions", "Time", "Total"); GraphPane breakdownGraphPane = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "SIP Request and Responses per Second", "Time", "Packets/s"); GraphPane anomaliesGraphPane = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "Anomalous Packets per Second", "Time", "Packets/s"); GraphPane totalParseTimesGraphPane = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "SIP Packet Parse Time per Second", "Time", "Total Parse Tme (ms)/s"); GraphPane averageParseTimesGraphPane = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "Average SIP Packet Parse Time", "Time", "Average Parse Tme (ms)"); totalSIPPacketsGraphPane.Legend.IsVisible = false; totalSIPPacketsGraphPane.XAxis.Type = AxisType.Date; totalSIPPacketsGraphPane.XAxis.Scale.Format = "HH:mm:ss"; pendingSIPTransactionsGraphPane.Legend.IsVisible = false; pendingSIPTransactionsGraphPane.XAxis.Type = AxisType.Date; pendingSIPTransactionsGraphPane.XAxis.Scale.Format = "HH:mm:ss"; breakdownGraphPane.Legend.Location.AlignH = AlignH.Right; breakdownGraphPane.XAxis.Type = AxisType.Date; breakdownGraphPane.XAxis.Scale.Format = "HH:mm:ss"; anomaliesGraphPane.XAxis.Type = AxisType.Date; anomaliesGraphPane.XAxis.Scale.Format = "HH:mm:ss"; totalParseTimesGraphPane.XAxis.Type = AxisType.Date; totalParseTimesGraphPane.Legend.IsVisible = false; totalParseTimesGraphPane.XAxis.Scale.Format = "HH:mm:ss"; averageParseTimesGraphPane.XAxis.Type = AxisType.Date; averageParseTimesGraphPane.Legend.IsVisible = false; averageParseTimesGraphPane.XAxis.Scale.Format = "HH:mm:ss"; LineItem totalSIPPacketsCurve = totalSIPPacketsGraphPane.AddCurve("Total SIP Packets", m_totalSIPPacketsList, Color.Black, SymbolType.None); LineItem pendingTransactionsCurve = pendingSIPTransactionsGraphPane.AddCurve("Pending SIP Transactions", m_pendingTransactionsList, Color.Black, SymbolType.None); LineItem sipRequestsInCurve = breakdownGraphPane.AddCurve("Requests In", m_sipRequestsInList, Color.Blue, SymbolType.None); LineItem sipResponsesInCurve = breakdownGraphPane.AddCurve("Responses In", m_sipResponsesInList, Color.DarkGreen, SymbolType.None); LineItem sipRequestsOutCurve = breakdownGraphPane.AddCurve("Requests Out", m_sipRequestsOutList, Color.BlueViolet, SymbolType.None); LineItem sipResponsesOutCurve = breakdownGraphPane.AddCurve("Responses Out", m_sipResponsesOutList, Color.DarkKhaki, SymbolType.None); LineItem discardsCurve = anomaliesGraphPane.AddCurve("Discards", m_discardsList, Color.Red, SymbolType.None); LineItem badSIPCurve = anomaliesGraphPane.AddCurve("Bad SIP", m_badSIPList, Color.Purple, SymbolType.None); LineItem unrecognisedCurve = anomaliesGraphPane.AddCurve("Unrecognised", m_unrecognisedList, Color.Green, SymbolType.None); LineItem tooLargeCurve = anomaliesGraphPane.AddCurve("Too Large", m_tooLargeList, Color.Coral, SymbolType.None); LineItem stunCurve = anomaliesGraphPane.AddCurve("STUN", m_stunList, Color.Blue, SymbolType.None); LineItem totalParseTimeCurve = totalParseTimesGraphPane.AddCurve("Total Parse Time", m_totalParseTimeList, Color.Black, SymbolType.None); LineItem averageParseTimeCurve = averageParseTimesGraphPane.AddCurve("Average Parse Time", m_avgParseTimeList, Color.Black, SymbolType.None); totalSIPPacketsGraphPane.AxisChange(m_g); pendingSIPTransactionsGraphPane.AxisChange(m_g); breakdownGraphPane.AxisChange(m_g); anomaliesGraphPane.AxisChange(m_g); totalParseTimesGraphPane.AxisChange(m_g); averageParseTimesGraphPane.AxisChange(m_g); Bitmap totalsGraphBitmap = totalSIPPacketsGraphPane.GetImage(); totalsGraphBitmap.Save(m_localGraphsDir + "siptotals.png", ImageFormat.Png); Bitmap pendingTransactionsGraphBitmap = pendingSIPTransactionsGraphPane.GetImage(); pendingTransactionsGraphBitmap.Save(m_localGraphsDir + "siptransactions.png", ImageFormat.Png); Bitmap breakdownGraphBitmap = breakdownGraphPane.GetImage(); breakdownGraphBitmap.Save(m_localGraphsDir + "sipmessagetypes.png", ImageFormat.Png); Bitmap anomaliesGraphBitmap = anomaliesGraphPane.GetImage(); anomaliesGraphBitmap.Save(m_localGraphsDir + "anomalies.png", ImageFormat.Png); Bitmap totalParseTimeGraphBitmap = totalParseTimesGraphPane.GetImage(); totalParseTimeGraphBitmap.Save(m_localGraphsDir + "siptotalparse.png", ImageFormat.Png); Bitmap averageParseTimeGraphBitmap = averageParseTimesGraphPane.GetImage(); averageParseTimeGraphBitmap.Save(m_localGraphsDir + "sipaverageparse.png", ImageFormat.Png); #endregion #region Create SIP methods graph. GraphPane methodsGraphPane = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "SIP Packets for Method per Second", "Time", "SIP Packets/s"); methodsGraphPane.XAxis.Type = AxisType.Date; methodsGraphPane.XAxis.Scale.Format = "HH:mm:ss"; foreach (KeyValuePair<SIPMethodsEnum, RollingPointPairList> entry in m_sipMethodsLists) { Color methodColor = (m_methodColours.ContainsKey(entry.Key)) ? m_methodColours[entry.Key] : Color.Black; LineItem methodCurve = methodsGraphPane.AddCurve(entry.Key.ToString(), entry.Value, methodColor, SymbolType.None); } methodsGraphPane.AxisChange(m_g); Bitmap methodsGraphBitmap = methodsGraphPane.GetImage(); methodsGraphBitmap.Save(m_localGraphsDir + "sipmethods.png", ImageFormat.Png); #endregion #region Create top talkers graph. // Get the top 10 talkers. if (m_topTalkersCount.Count > 0) { string[] topTalkerSockets = new string[m_topTalkersCount.Count]; int[] topTalkerValues = new int[m_topTalkersCount.Count]; m_topTalkersCount.Keys.CopyTo(topTalkerSockets, 0); m_topTalkersCount.Values.CopyTo(topTalkerValues, 0); Array.Sort<int, string>(topTalkerValues, topTalkerSockets); GraphPane toptalkersGraphPane = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "SIP Top Talkers", "Time", "SIP Packets/s"); toptalkersGraphPane.XAxis.Type = AxisType.Date; toptalkersGraphPane.XAxis.Scale.Format = "HH:mm:ss"; //foreach (KeyValuePair<string, RollingPointPairList> entry in m_topTalkersLists) for (int index = topTalkerSockets.Length - 1; (index >= topTalkerSockets.Length - NUMBER_TOPTALKERS_TOPPLOT && index >= 0); index--) { string socket = topTalkerSockets[index]; RollingPointPairList topTalkerPoints = m_topTalkersLists[socket]; Color topTalkerColor = m_topTalkerColours[topTalkerSockets.Length - 1 - index]; //logger.Debug("Adding curve for " + socket + " (count=" + topTalkerValues[index] + ")."); LineItem topTalkersCurve = toptalkersGraphPane.AddCurve(socket, topTalkerPoints, topTalkerColor, SymbolType.None); //break; } toptalkersGraphPane.AxisChange(m_g); Bitmap topTalkersGraphBitmap = toptalkersGraphPane.GetImage(); topTalkersGraphBitmap.Save(m_localGraphsDir + "siptoptalkers.png", ImageFormat.Png); } #endregion logger.Debug("Metrics graph for " + m_metricsFileCopyName + " completed in " + DateTime.Now.Subtract(startTime).TotalMilliseconds.ToString("0.##") + "ms, " + sampleCount + " samples."); #region Uplodad file to server. /*if (m_serverFilename != null && m_serverFilename.Trim().Length > 0) { Uri target = new Uri(m_serverFilename); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential("anonymous", "*****@*****.**"); FileStream localStream = File.OpenRead(m_totalsGraphFilename); Stream ftpStream = request.GetRequestStream(); byte[] buffer = new byte[localStream.Length]; localStream.Read(buffer, 0, buffer.Length); localStream.Close(); ftpStream.Write(buffer, 0, buffer.Length); ftpStream.Close(); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); response.Close(); //logger.Debug("Result of ftp upload to " + m_serverFilename + " is " + response.StatusDescription + "."); }*/ #endregion } catch (Exception graphExcp) { logger.Error("Exception Saving Graph. " + graphExcp.Message); } } catch (Exception excp) { logger.Debug("Exception UpdateGraph. " + excp.Message); } }
private Image GetGraphFor(DataSet dataSet) { var pane = new GraphPane(new RectangleF(0, 0, 770, 600), dataSet.Title, dataSet.XAxisTitle, dataSet.YAxisTitle); pane.Title.IsVisible = false; pane.Legend.IsVisible = false; pane.XAxis.Type = AxisType.Linear; pane.XAxis.Title.FontSpec.Size = 8; pane.XAxis.Scale.FontSpec.Size = 8; pane.XAxis.Scale.Min = dataSet.Points[0].X; pane.XAxis.Scale.Max = dataSet.Points[dataSet.Points.Count - 1].X; pane.YAxis.Title.FontSpec.Size = 8; pane.YAxis.Scale.FontSpec.Size = 8; var curve = pane.AddCurve(dataSet.Title, dataSet.Points, Color.Red, SymbolType.None); curve.Line.StepType = StepType.NonStep; //curve.Line.IsSmooth = true; var bitmap = new Bitmap(1, 1); var graphics = Graphics.FromImage(bitmap); pane.AxisChange(graphics); return pane.GetImage(); }
/// <summary> /// 当前列表导出Excel /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void lbt_importall_Click(object sender, EventArgs e) { string TimeRange=""; if (ext_StartInputDt.SelectedDate != DateTime.MinValue && ext_EndInputDt.SelectedDate != DateTime.MinValue) { TimeRange = ext_StartInputDt.SelectedDate.ToShortDateString() + "至" + ext_EndInputDt.SelectedDate.ToShortDateString(); } else if (ext_StartInputDt.SelectedDate != DateTime.MinValue && ext_EndInputDt.SelectedDate == DateTime.MinValue) { TimeRange = ext_StartInputDt.SelectedDate.ToShortDateString() + "至—"; } else if (ext_StartInputDt.SelectedDate == DateTime.MinValue && ext_EndInputDt.SelectedDate != DateTime.MinValue) { TimeRange = "—至" + ext_EndInputDt.SelectedDate.ToShortDateString(); } else { TimeRange = ""; } DataSet ds = logic.complaint.outputExcel(strWhere()); DataTable dtlist = ds.Tables[0], dtcompany = ds.Tables[1], dtcomplaint = ds.Tables[2], dtcategory = ds.Tables[3], dtdepartment = ds.Tables[4]; dtlist.Columns["complaintdt"].ColumnName = "日期"; dtlist.Columns["buyername"].ColumnName = "客户名称"; dtlist.Columns["productname"].ColumnName = "投诉产品"; dtlist.Columns["complaintname"].ColumnName = "投诉类别"; dtlist.Columns["department"].ColumnName = "责任部门"; dtlist.Columns["responsibler"].ColumnName = "责任人"; dtlist.Columns["sellername"].ColumnName = "责任供应商"; dtlist.Columns["levelname"].ColumnName = "严重级别"; dtlist.Columns["result"].ColumnName = "处理结果"; dtlist.Columns["inputname"].ColumnName = "录入人"; dtlist.Columns["remarks"].ColumnName = "投诉问题详情"; dtlist.Columns.Remove("buyerid"); dtlist.Columns.Remove("sellerid"); ExportFacade facade = new ExportFacade(); HSSFWorkbook workbook = facade.InitializeWorkbook("杭州农副产品物流网络有限公司", logic.sysAdmin.AdminID.ToString(), "采购配送系统", "投诉管理"); Sheet sheet1 = workbook.CreateSheet("投诉详细"); facade.CreateRowHeader(workbook, sheet1, TimeRange + " 投诉列表", dtlist); facade.FillRowData(workbook, sheet1, 2, dtlist, null, null, null, null); Sheet sheet2 = workbook.CreateSheet("客户投诉"); facade.CreateRowHeader(workbook, sheet2, TimeRange + " 客户投诉情况", dtcompany); facade.FillRowData(workbook, sheet2, 2, dtcompany, null, null, null, null); Sheet sheet3 = workbook.CreateSheet("投诉汇总"); facade.CreateRowHeader(workbook, sheet3, TimeRange + " 投诉问题汇总", dtcomplaint); facade.FillRowData(workbook, sheet3, 2, dtcomplaint, null, null, null, null); #region 小类投诉情况 GraphPane graphpane = new GraphPane(); graphpane.Title.Text = "小类投诉情况"; graphpane.Title.FontSpec.Size = 12f; graphpane.XAxis.Title.Text = "小类"; graphpane.XAxis.Title.FontSpec.Size = 11f; graphpane.YAxis.Title.Text = ChangeStr("投诉数量"); graphpane.YAxis.Title.FontSpec.Angle = 90; graphpane.YAxis.Title.FontSpec.Size = 11f; graphpane.XAxis.IsVisible = true; graphpane.YAxis.IsVisible = true; List<string> category=new List<string>(); List<double> cnum = new List<double>(); int maxcnum = 2; foreach (DataRow dr in dtcategory.Rows) { if(Convert.ToInt32( dr[1].ToString())>maxcnum) maxcnum=Convert.ToInt32( dr[1].ToString()); category.Add(ChangeStr( dr[0].ToString())); cnum.Add(Convert.ToDouble(dr[1].ToString())); } BarItem baritem = graphpane.AddBar(null,null,cnum.ToArray(), Color.Red); baritem.Bar.Fill = new Fill(Color.Red, Color.White, Color.Red); BarItem.CreateBarLabels(graphpane, false, "f0"); graphpane.XAxis.Scale.TextLabels = category.ToArray(); graphpane.XAxis.Scale.Max = category.ToArray().Length+1; graphpane.XAxis.Scale.MajorStep = 1; graphpane.XAxis.MinorTic.Size = 0; graphpane.XAxis.MajorTic.Size = 0; graphpane.XAxis.Cross = 0; graphpane.XAxis.Scale.FontSpec.Size = 10f; graphpane.XAxis.Scale.FontSpec.Family = "宋体"; graphpane.XAxis.Type = AxisType.Text; graphpane.XAxis.MajorTic.IsOutside = false; graphpane.XAxis.MajorTic.IsOpposite = false; graphpane.YAxis.Scale.Max = maxcnum+2; graphpane.YAxis.MinorTic.Size = 0; graphpane.YAxis.MinorGrid.DashOff = 0; graphpane.YAxis.Scale.MajorStep = 1; graphpane.YAxis.MajorTic.IsOpposite = false; graphpane.YAxis.MajorTic.IsOutside = false; graphpane.Chart.Fill = new Fill(Color.White, Color.FromArgb(255, 255, 166), 90F); graphpane.Fill = new Fill(Color.White, Color.FromArgb(250, 250, 255),45.0f); graphpane.Fill.IsScaled = true; MemoryStream ms = new MemoryStream(); //zgc.GetImage().Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg); Bitmap map = graphpane.GetImage(750,550,17); map.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] picbyte = ms.ToArray(); int index = workbook.AddPicture(picbyte, NPOI.SS.UserModel.PictureType.JPEG); Sheet sheet4 = workbook.CreateSheet("小类投诉"); facade.CreateRowHeader(workbook, sheet4, TimeRange + " 小类投诉情况", dtcategory); facade.FillRowData(workbook, sheet4, 2, dtcategory, null, null, null, null); HSSFPatriarch hssfpatriarch = (HSSFPatriarch)sheet4.CreateDrawingPatriarch(); HSSFClientAnchor hssfanchor = new HSSFClientAnchor(0, 0, 0, 0, 4, 1, 18, 28); HSSFPicture hssfpic = (HSSFPicture)hssfpatriarch.CreatePicture(hssfanchor, index); #endregion #region 部门投诉情况 GraphPane gp2 = new GraphPane(); gp2.Title.Text = "部门投诉情况"; gp2.XAxis.IsVisible = false; gp2.YAxis.IsVisible = false; gp2.Title.FontSpec.Size = 12f; gp2.Fill = new Fill(Color.White); gp2.Chart.Fill.Type = FillType.None; gp2.Legend.Position = LegendPos.Float; gp2.Legend.Location = new Location(0.95f, 0.08f, CoordType.PaneFraction, AlignH.Right, AlignV.Top); gp2.Legend.FontSpec.Size = 10f; gp2.Legend.IsHStack = false; List<double> comnum=new List<double>(); List<string> dname=new List<string>(); foreach(DataRow dr in dtdepartment.Rows ) { gp2.AddPieSlice(Convert.ToDouble(dr[1].ToString()), GetRandomColor(), 0, dr[0].ToString()+" ("+dr[1].ToString()+")").LabelType=PieLabelType.Percent; } Bitmap bitmap = gp2.GetImage(700, 700, 14); MemoryStream mstream = new MemoryStream(); bitmap.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] buffer = mstream.ToArray(); int picindex = workbook.AddPicture(buffer, NPOI.SS.UserModel.PictureType.JPEG); Sheet sheet5 = workbook.CreateSheet("部门投诉"); facade.CreateRowHeader(workbook, sheet5, TimeRange + " 责任部门投诉情况", dtdepartment); facade.FillRowData(workbook, sheet5, 2, dtdepartment, null, null, null, null); HSSFPatriarch patriarch = (HSSFPatriarch)sheet5.CreateDrawingPatriarch(); HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, 4, 1, 15, 34); HSSFPicture pic = (HSSFPicture)patriarch.CreatePicture(anchor, picindex); #endregion facade.ExportByWeb(workbook, TimeRange.ToString() + "采购配送系统投诉统计", TimeRange.ToString() + "采购配送系统投诉统计.xls"); }
/// <summary> /// Generate image, and save it to the output stream /// </summary> /// <param name="outputStream"></param> /// <param name="dataResults"></param> public void Generate(Stream outputStream, IEnumerable<RequestDataResults> dataResults) { var gp = new GraphPane(); int index = 1; var maxY = (int)(dataResults.Max(x => x.AverageResponseTime) * 1.2); var orderedResults = dataResults.OrderBy(x => x.Date); foreach (var d in orderedResults) { float offset = 0.5f; // Create bar RenderBar(gp, orderedResults, index - 1, index - offset, GenerateBarColor); // Add average response time on top of the bar RenderBarContent(gp, d, index); // Add request at the bottom of the bar RenderBarLabel(gp, d, index); // Add min/max point to list RenderMinMaxLine(gp, d, index, maxY); RenderMinMaxExcludingExtremesLine(gp, d, index, maxY); RenderAverageLine(gp, d, index); RenderResponseTimeDistributionCurve(gp, d, index, maxY); index++; } // Title RenderTitle(gp, orderedResults); // X Axis RenderXAxis(gp, string.Empty, 0, index + 1); // Y Axis RenderYAxis(gp, "Response time (in ms)", 0, maxY); // Add legend RenderLegend(gp, orderedResults); // Fill background RenderBackground(gp); // Add time tag RenderTimeTag(gp); // Add space at the bottom gp.Margin.Bottom = BottomMargin; gp.Margin.Left = LeftMargin; // Refresh panel gp.AxisChange(); // Render image var bitmap = gp.GetImage(Width, Height, Dpi); bitmap.Save(outputStream, ImageFormat.Jpeg); }
private void CopyToGif( GraphPane thePane ) { if ( thePane != null ) thePane.GetImage().Save( @"c:\zedgraph.gif", ImageFormat.Gif ); }
public void DrawMelFiltersBank(string fileName) { GraphPane myPane = new GraphPane( new RectangleF( 0, 0, 1200, 600 ), "Mel Filter Bank", "X Title", "Y Title" ); Random random = new Random(); PointPairList ppl = new PointPairList(); double[] filterSpectrum; foreach(var filter in filters) { ppl.Clear(); if (filter.IsEnabled()) { filterSpectrum = filter.GetFilterSpectrum(); for (int i = 0; i < 200; i++) { ppl.Add(i, filterSpectrum[i]); } Color color = Color.FromArgb(random.Next(0, 255), random.Next(0,255),random.Next(0,255)); LineItem myCurve = myPane.AddCurve("", ppl.Clone(), color, SymbolType.None ); } } Bitmap bm = new Bitmap( 1, 1 ); using ( Graphics g = Graphics.FromImage( bm ) ) myPane.AxisChange( g ); myPane.GetImage().Save(fileName, ImageFormat.Png); }
public void SaveImage(int width, int height, string title, string outputFile, ImageFormat imageFormat) { GraphPane myPane = new GraphPane(new RectangleF(0, 0, width, height), title, "Week", "Hours"); myPane.IsBoundedRanges = true; var ppl = new PointPairList(); foreach (var week in data) { ppl.Add(week.Item1, week.Item2); } // Hide the legend myPane.Legend.IsVisible = false; var foreground = Color.FromArgb(255, 55, 108, 153); myPane.XAxis.AxisGap = 1f; myPane.XAxis.Type = AxisType.Text; myPane.XAxis.Scale.TextLabels = data.Select(t => "Week " + t.Item1).ToArray(); myPane.YAxis.Scale.Min = 0; myPane.YAxis.Scale.MinorStep = 1; myPane.YAxis.MinorTic.Color = Color.Transparent; myPane.Border.IsVisible = false; LineItem curve = myPane.AddCurve("Hours of effort", ppl, foreground, SymbolType.Circle); curve.Line.Width = 2.0F; curve.Line.IsAntiAlias = true; curve.Symbol.Fill = new Fill(Color.White); curve.Symbol.Size = 7; // Leave some extra space on top for the labels to fit within the chart rect myPane.YAxis.Scale.MaxGrace = 0.1; myPane.Chart.Fill = new Fill(Color.White, Color.FromArgb(220, 220, 255), 45); myPane.Fill = new Fill(Color.White); Bitmap bm = new Bitmap(1, 1); using (Graphics g = Graphics.FromImage(bm)) myPane.AxisChange(g); myPane.GetImage().Save(outputFile, imageFormat); }
/// <summary> /// Graphs an array of doubles varying between -1 and 1 /// </summary> /// <param name="data">data</param> /// <param name="fileName">filename to save png to</param> /// <param name="onlyCanvas">true if no borders should be printed</param> public static void DrawGraph(double[] data, string fileName, bool onlyCanvas=false) { GraphPane myPane = new GraphPane( new RectangleF( 0, 0, 1200, 600 ), "", "", "" ); if (onlyCanvas) { myPane.Chart.Border.IsVisible = false; myPane.Chart.Fill.IsVisible = false; myPane.Fill.Color = Color.Black; myPane.Margin.All = 0; myPane.Title.IsVisible = false; myPane.XAxis.IsVisible = false; myPane.YAxis.IsVisible = false; } myPane.XAxis.Scale.Max = data.Length - 1; myPane.XAxis.Scale.Min = 0; //myPane.YAxis.Scale.Max = 1; //myPane.YAxis.Scale.Min = -1; // add pretty stuff myPane.Fill = new Fill( Color.WhiteSmoke, Color.Lavender, 0F ); myPane.Chart.Fill = new Fill( Color.FromArgb( 255, 255, 245 ), Color.FromArgb( 255, 255, 190 ), 90F ); var timeData = Enumerable.Range(0, data.Length) .Select(i => (double) i) .ToArray(); myPane.AddCurve(null, timeData, data, Color.Blue, SymbolType.None); Bitmap bm = new Bitmap( 1, 1 ); using ( Graphics g = Graphics.FromImage( bm ) ) myPane.AxisChange( g ); myPane.GetImage().Save(fileName, ImageFormat.Png); }
private MemoryStream CreatePlayerCountImageOneMonth(GameServer server, out string fileName) { LordControl.PlayerCountStatisticInfo[] _infoArray = null; DateTime _endTime = DateTime.Now; DateTime _startTime = _endTime.AddMonths(-1); _infoArray = server.GetPlugInData(0, LordControl.PlugInGuid, LordControl.DataKeyPlayerCountStatistic, _startTime, _endTime) as LordControl.PlayerCountStatisticInfo[]; if (_infoArray.Length != 0) { ArrayList playerCountArrayList = new ArrayList(); LordControl.PlayerCountStatisticInfo tempInfo = new LordControl.PlayerCountStatisticInfo(); tempInfo.Time = _infoArray[0].Time; int countInOneDay = 0; for (int i = 0; i < _infoArray.Length; i++) { LordControl.PlayerCountStatisticInfo info = _infoArray[i]; if (tempInfo.Time.Date == info.Time.Date) { if (info.MaxCount > tempInfo.MaxCount) tempInfo.MaxCount = info.MaxCount; if (info.MinCount < tempInfo.MinCount) tempInfo.MinCount = info.MinCount; tempInfo.AverageCount += info.AverageCount; countInOneDay++; if (i == _infoArray.Length - 1) { tempInfo.AverageCount /= countInOneDay; playerCountArrayList.Add(tempInfo); } } else { tempInfo.AverageCount /= countInOneDay; playerCountArrayList.Add(tempInfo); tempInfo = new LordControl.PlayerCountStatisticInfo(); tempInfo.Time = info.Time; tempInfo.AverageCount = info.AverageCount; tempInfo.MaxCount = info.MaxCount; tempInfo.MinCount = info.MinCount; countInOneDay = 1; if (i == _infoArray.Length - 1) { playerCountArrayList.Add(tempInfo); } } } double[] maxCountArray = new double[playerCountArrayList.Count]; double[] minCountArray = new double[playerCountArrayList.Count]; double[] averageCountArray = new double[playerCountArrayList.Count]; double[] timeArray = new double[playerCountArrayList.Count]; for (int i = 0; i < playerCountArrayList.Count; i++) { LordControl.PlayerCountStatisticInfo info = playerCountArrayList[i] as LordControl.PlayerCountStatisticInfo; maxCountArray[i] = info.MaxCount; minCountArray[i] = info.MinCount; averageCountArray[i] = info.AverageCount; timeArray[i] = new XDate(info.Time); } GraphPane graphPane = new GraphPane(new Rectangle(0, 0, 840, 450), String.Empty, String.Empty, String.Empty); graphPane.Fill = new Fill(Color.FromArgb(212, 208, 200)); graphPane.Legend.Fill.IsVisible = false; graphPane.Legend.Border.IsVisible = false; graphPane.Legend.FontSpec.Fill.IsVisible = false; graphPane.XAxis.Title.Text = "时间"; graphPane.XAxis.MajorGrid.Color = Color.DarkGreen; graphPane.XAxis.Type = AxisType.Date; graphPane.XAxis.Scale.FontSpec.Size = 11; graphPane.YAxis.Title.Text = "玩家数量"; //graphPane.YAxis.MajorGrid.IsVisible = true; //graphPane.YAxis.MajorGrid.DashOff = 0; //graphPane.YAxis.MajorGrid.Color = Color.Gray; //graphPane.YAxis.MinorGrid.IsVisible = true; //graphPane.YAxis.MinorGrid.Color = Color.LightGray; //graphPane.YAxis.MinorGrid.DashOff = 0; graphPane.YAxis.Scale.Min = 0; graphPane.Title.Text = string.Format("{0} [ {1} {2} ]", "玩家数量", _startTime, _endTime); graphPane.AddCurve("最大", timeArray, maxCountArray, Color.Red, SymbolType.Triangle); graphPane.AddCurve("最小", timeArray, minCountArray, Color.Green, SymbolType.TriangleDown); graphPane.AddCurve("平均", timeArray, averageCountArray, Color.Orange, SymbolType.Diamond); graphPane.AxisChange(); fileName = server.Group.Name + "-" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "-(Month)" + ".jpg"; MemoryStream imageMemoryStream = new MemoryStream(); graphPane.GetImage().Save(imageMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg); imageMemoryStream.Position = 0; return imageMemoryStream; } else { fileName = String.Empty; return null; } }
private Bitmap ExportGraph(GraphPane pane) { Bitmap bm = new Bitmap(1, 1); using (Graphics g = Graphics.FromImage(bm)) { pane.AxisChange(g); } return pane.GetImage(); }
public Bitmap GenerateCurveImage(Size size) { GraphPane pane = new GraphPane(new RectangleF(0, 0, size.Width, size.Height), string.Empty, string.Empty, string.Empty); Bitmap result = new Bitmap(size.Width, size.Height); pane.AddCurve(string.Empty, Points, ActiveCurveGridColor); pane.XAxis.Scale.Min = 0; pane.XAxis.Scale.Max = 100; pane.YAxis.Scale.Min = 0; pane.YAxis.Scale.Max = 100; pane.XAxis.IsVisible = false; pane.YAxis.IsVisible = false; pane.Legend.IsVisible = false; pane.Title.IsVisible = false; pane.Chart.Fill = new Fill(SystemColors.Control); pane.Border = new Border(SystemColors.Control, 0); using (Graphics g = Graphics.FromImage(result)) { pane.AxisChange(g); result = pane.GetImage(true); } return result; }
private string CreateStatisticMoneyImage(GameServer server, string dateFrom, string dateTo, ChartType type, bool showSymbol) { using (IBlazeDatabase db = DbFactory.GetDatabase()) { IBlazeTable gameLogTable = db.GetTable(TableString.GameLogTableName); DataSet data = new DataSet(); gameLogTable.Get( data, FilterFactory.CreateAndFilter( FilterFactory.CreateEqualFilter(TableString.GameLogFieldGameServerId, server.Id), FilterFactory.CreateAndFilter( FilterFactory.CreateLargerEqualFilter(TableString.GameLogFieldDate, dateFrom), FilterFactory.CreateLesserEqualFilter(TableString.GameLogFieldDate, dateTo) ) ) ); DataTable table = data.Tables[0]; int count = table.Rows.Count; double[] money = new double[count]; double[] moneyInBox = new double[count]; double[] moneyTotal = new double[count]; double[] date = new double[count]; for (int i = 0; i < count; i++) { DataRow row = table.Rows[i]; money[i] = (long)row[TableString.GameLogFieldTotalMoney]; moneyInBox[i] = (long)row[TableString.GameLogFieldTotalMoneyInBox]; moneyTotal[i] = money[i] + moneyInBox[i]; DateTime currentDate = (DateTime)row[TableString.GameLogFieldDate]; date[i] = new XDate(currentDate.Year, currentDate.Month, currentDate.Day); } bool success = true; if (success) { //»æÖÆͼ±í GraphPane graphPane = new GraphPane(); graphPane.Title.Text = StringDef.MoneyStatistic; graphPane.Fill = new Fill(WebConfig.GraphPaneBgColor); graphPane.Legend.Fill.IsVisible = false; graphPane.Legend.Border.IsVisible = false; graphPane.XAxis.Title.Text = StringDef.Date; graphPane.XAxis.MajorGrid.Color = WebConfig.GraphXAxisGridColor; graphPane.XAxis.Type = AxisType.DateAsOrdinal; graphPane.XAxis.MinorTic.Size = 0; graphPane.XAxis.Scale.MajorStep = 1; graphPane.XAxis.Scale.MajorUnit = DateUnit.Day; graphPane.XAxis.Scale.FontSpec.Size = 12; graphPane.XAxis.Scale.Format = "M-d"; graphPane.YAxis.Title.Text = StringDef.Money; graphPane.YAxis.MajorGrid.IsVisible = true; graphPane.YAxis.MajorGrid.DashOff = 0; graphPane.YAxis.MajorGrid.Color = Color.Gray; graphPane.YAxis.MinorGrid.IsVisible = true; graphPane.YAxis.MinorGrid.Color = Color.LightGray; graphPane.YAxis.MinorGrid.DashOff = 0; if (type == ChartType.Bar) { graphPane.BarSettings.Type = BarType.Stack; BarItem barItemMoney = graphPane.AddBar(StringDef.Money, date, money, Colors[0]); BarItem barItemMoneyInBox = graphPane.AddBar(StringDef.MoneyInBox, date, moneyInBox, Colors[1]); barItemMoney.Bar.Fill = new Fill(Colors[0]); barItemMoneyInBox.Bar.Fill = new Fill(Colors[1]); } else if (type == ChartType.Line) { LineItem lineItemMoney = graphPane.AddCurve(StringDef.Money, date, money, Colors[0], (showSymbol ? WebConfig.GraphSymbols[0] : SymbolType.None)); LineItem lineItemMoneyInBox = graphPane.AddCurve(StringDef.MoneyInBox, date, moneyInBox, Colors[1], (showSymbol ? WebConfig.GraphSymbols[1] : SymbolType.None)); LineItem lineItemMoneyTotal = graphPane.AddCurve(StringDef.MoneyTotal, date, moneyTotal, Colors[2], (showSymbol ? WebConfig.GraphSymbols[2] : SymbolType.None)); } Bitmap bitmap = new Bitmap(1, 1); using (Graphics g = Graphics.FromImage(bitmap)) { graphPane.AxisChange(g); } bitmap = graphPane.GetImage(WebConfig.StatisticRoleCountByLevelGraphWidth, WebConfig.StatisticRoleCountByLevelGraphHeight, 75.0f); string imageName = WebUtil.CreateRandomName("Statistic", WebConfig.GraphFileSuffix); string file = WebConfig.WebsiteRootPath + WebConfig.TempGraphPath + imageName; try { bitmap.Save(file, WebConfig.GraphImageFormat); TempFileManager.TheInstance.AddTempFile(file, 5000 * WebConfig.TempGraphDeleteDelayMultiple); return imageName; } catch (Exception) { //TODO ¼Ç¼´íÎó return null; } } return null; } }
private void CreateTokenMatchGraph(OSPCResult r) { GraphPane g = new GraphPane(GraphRect, "Distribution of token / match", "-", "Token / match"); SetupGraph(g); var lst = r.Results.Select(i => (double)i.TokenCount / (double)i.MatchCount).OrderBy(i => i).ToArray(); var c = g.AddCurve("Token / match", Enumerable.Range(1, lst.Length).Select(i => (double)i).ToArray(), lst, Color.Red); c.Symbol.IsVisible = false; #if SHOW_DERIVATION_2 var derv_2 = lst.CalcDerv2(); c = g.AddCurve("Derivation 2", Enumerable.Range(1, derv_2.Length).Select(i => (double)i).ToArray(), derv_2.ToArray(), Color.Green); c.IsY2Axis = true; c.Symbol.IsVisible = false; #endif AddLine(g, r.AVG_TokenPerMatch, Color.Blue, "Avg"); AddLine(g, r.POI_TokenPerMatch, Color.Green, "POI"); g.AxisChange(); using (var img = g.GetImage()) { img.Save(Path.Combine(OutPath, "TokenMatchGraph.png"), ImageFormat.Png); } }
public override Image Draw( GraphDefinition graphDefinition, IEnumerable <PersistedCityStatisticsWithFinancialData> statistics, Font font, Size size) { using (var chartMemoryStream = new MemoryStream()) { var chart = new ZedGraph.GraphPane(); foreach (var axis in new[] { chart.XAxis, chart.YAxis as Axis }) { axis.Scale.IsUseTenPower = false; axis.Scale.Format = "F0"; } chart.XAxis.Title.Text = "Time"; chart.XAxis.Type = AxisType.LinearAsOrdinal; chart.YAxis.Type = AxisType.Linear; chart.YAxis.Title.Text = graphDefinition.Title; foreach (var z in graphDefinition.GraphSeriesSet) { var pointPairList = new PointPairList(); foreach (var statistic in statistics) { pointPairList.Add(statistic.PersistedCityStatistics.TimeCode, z.GetValue(statistic)); } chart.AddCurve(z.Label, pointPairList, z.Color, SymbolType.None); } chart.Title.Text = graphDefinition.Title; if (graphDefinition.IsCurrency) { chart.YAxis.ScaleFormatEvent += (pane, axis, val, index) => { return(val.ToString("C")); }; } graphDefinition.DataMeter.WithResultIfHasMatch(dataMeter => { chart.YAxis.ScaleFormatEvent += (pane, axis, val, index) => { var meter = dataMeter.Thresholds.SingleOrDefault( x => x.MinMeasureUnitThreshold <= val && x.MaxMeasureUnitThreshold > val); if (meter != null) { return(meter.Category.ToString()); } return(string.Empty); }; }); return(chart.GetImage()); } }