Example #1
0
        private void ConfigureGraph()
        {
            //make sure we only run one configure at a time.
            if (!_configuring)
            {
                _configuring = true;
                _curves      = new List <CurveItem>();

                zg.GraphPane.Title.Text = _statisticName + " by " + _type.ToString();
                this.Text    = zg.GraphPane.Title.Text;
                this.TabText = zg.GraphPane.Title.Text;
                zg.GraphPane.XAxis.Title.Text = "Time";
                _unit = _replay.Boats[0].TotalStatistics.GetStatisticUnit(_statisticName, _unitType);
                zg.GraphPane.YAxis.Title.Text = _statisticName + " (" + _unit.ToString() + ")";
                zg.GraphPane.CurveList.Clear();

                foreach (SelectedStatisticCell ssc in _statistics)
                {
                    SortedList <DateTime, double> data = new SortedList <DateTime, double>();
                    string curveName = GetSelectionLabel(ssc);
                    if (_type == StatisticGroupType.Tack)
                    {
                        data = _replay.Boats[ssc.BoatIndex.Value].TackStatistics[ssc.TackIndex.Value].GetGraphableTimeline(_statisticName, _unitType);
                    }
                    else if (_type == StatisticGroupType.Leg)
                    {
                        data = _replay.Boats[ssc.BoatIndex.Value].LegStatistics[ssc.LegIndex.Value].GetGraphableTimeline(_statisticName, _unitType);
                    }
                    else
                    {
                        data = _replay.Boats[ssc.BoatIndex.Value].TotalStatistics.GetGraphableTimeline(_statisticName, _unitType);
                    }

                    PointPairList graphData = new PointPairList();
                    LineItem      curve     = zg.GraphPane.AddCurve(curveName, graphData, _replay.Boats[ssc.BoatIndex.Value].Color, SymbolType.Diamond);
                    foreach (DateTime dt in data.Keys)
                    {
                        AddPoint(curve, dt, data[dt]);
                    }
                    curve.Symbol.Fill          = new Fill(Color.White);
                    curve.Symbol.IsVisible     = true;
                    curve.Symbol.Size          = 3f;
                    curve.Line.IsOptimizedDraw = true;
                    _curves.Add(curve);
                }

                if (_enableOffset)
                {
                    List <int> usedColors = new List <int>();


                    _offset = DateTime.MaxValue;
                    //find the smallest date
                    //also alter the colors so that they are different
                    foreach (CurveItem ci in zg.GraphPane.CurveList)
                    {
                        if (ci.Points.Count > 0)
                        {
                            if (new XDate(ci[0].X).DateTime < _offset)
                            {
                                _offset = new XDate(ci[0].X).DateTime;
                            }
                        }
                    }

                    //now go through and apply the offset to all points
                    foreach (CurveItem ci in zg.GraphPane.CurveList)
                    {
                        if (ci.Points.Count > 0)
                        {
                            //no point offsetting if we're on the minimum
                            if (new XDate(ci[0].X).DateTime != _offset)
                            {
                                //determine the difference between this curve and the minimum curve
                                TimeSpan difference = new XDate(ci[0].X).DateTime - _offset.Value;
                                //now go through and offset each point
                                for (int i = 0; i < ci.Points.Count; i++)
                                {
                                    ci[i].X = new XDate(new XDate(ci[i].X).DateTime - difference);
                                }
                            }
                        }
                    }
                }
                else
                {
                    _offset = null;
                }

                DateTime simTime = _replay.SimulationTime;
                //_nowLine = new LineObj(Color.Blue,new XDate(simTime), _minYValue, new XDate(simTime), _maxYValue);
                //_nowLine.IsClippedToChartRect = true;
                //_nowLine.ZOrder = ZOrder.A_InFront;
                //_nowLine.IsVisible = true;
                //zg.GraphPane.GraphObjList.Add(_nowLine);

                zg.GraphPane.Legend.IsVisible = false;

                zg.GraphPane.XAxis.MajorGrid.IsVisible = true;
                zg.GraphPane.XAxis.Type = AxisType.Date;

                zg.IsShowHScrollBar  = true;
                zg.IsShowVScrollBar  = true;
                zg.IsAutoScrollRange = true;
                zg.IsShowPointValues = true;
                zg.AxisChange();
                zg.RestoreScale(zg.GraphPane);
                zg.Invalidate();
                _autoScrollSize = _defaultAutoScrollSize;
                _configuring    = false;
            }
        }
Example #2
0
        //Create the Graph and configure is proprties
        private void CreateGraph(ZedGraphControl zgc)
        {
            GraphPane myPane = zgc.GraphPane;

            // Set the titles and axis labels per selection
            myPane.Title.Text = cmbBoxThresholdTypes.GetItemText(cmbBoxThresholdTypes.SelectedItem);
            // Change the color of the title
            //   myPane.Title.FontSpec.Size = 10.0f * (this.Size.Width / 100);

            myPane.XAxis.Title.Text = "Time (Sec)";
            myPane.YAxis.Title.Text = "Threshold";

            myPane.CurveList.Clear();// clear the graph

            XDate minDate = XDate.JulDayMax;
            XDate maxDate = XDate.JulDayMin;
            //Create Random colors to show on Graph
            Random randGenerator = new Random();
            int    idx           = 0;

            foreach (object device in listDevices.SelectedItems)
            {
                String currDeviceName = device.ToString();

                PointPairList listDeviceValues = GetValuesForDevice(currDeviceName, GetSelectedThresholdId());

                if (colorList.Count() <= idx)
                {
                    int r = (int)(randGenerator.NextDouble() * 255);
                    int g = (int)(randGenerator.NextDouble() * 255);
                    int b = (int)(randGenerator.NextDouble() * 255);
                    colorList.Add(Color.FromArgb(255, r, g, b));
                }

                //use this to add line width 3.0F
                myCurve = new LineItem(currDeviceName, listDeviceValues, colorList[idx], SymbolType.XCross);
                myPane.CurveList.Add(myCurve);

                if (listDeviceValues.Count > 0)
                {
                    XDate firstDate = (XDate)(listDeviceValues[0].X);
                    XDate lastDate  = (XDate)listDeviceValues[listDeviceValues.Count - 1].X;
                    if (minDate == XDate.JulDayMax) //The max valid Julian Day, which corresponds to January 1st, 4713 B.C
                    {
                        minDate = firstDate;
                    }
                    else if (firstDate < minDate)
                    {
                        minDate = firstDate;
                    }

                    if (maxDate == XDate.JulDayMin)//The minimum valid Julian Day, which corresponds to January 1st, 4713 B.C
                    {
                        maxDate = lastDate;
                    }
                    else if (lastDate > maxDate)
                    {
                        maxDate = lastDate;
                    }
                }
                idx++;
            }

            Int32         thresholdValue     = GetContractThreshold();//Read the Threshold values
            PointPairList thresholdPointList = new PointPairList();

            thresholdPointList.Add(new PointPair(minDate, thresholdValue));
            thresholdPointList.Add(new PointPair(maxDate, thresholdValue));

            myPane.CurveList.Insert(0, new LineItem("Threshold", thresholdPointList, Color.FromArgb(255, 0, 0, 0), SymbolType.XCross, 3.0f));

            // Fill the axis background with a color gradient
            myPane.Chart.Fill = new Fill(Color.White, Color.LightGoldenrodYellow, 45F);

            // Fill the pane background with a color gradient
            myPane.Fill = new Fill(Color.White, Color.FromArgb(220, 220, 255), 45F);

            //This informs ZedGraph to use the labels supplied by the user in Axis.Scale.TextLabels
            Axis.Default.Type = AxisType.Text;

            //Show tooltips when the mouse hovers over a point
            zgc.IsShowPointValues = true;
            zgc.PointValueEvent  += new ZedGraphControl.PointValueHandler(MyPointValueHandler);

            // Set the XAxis to date type
            myPane.XAxis.Type = AxisType.Date;

            myPane.YAxis.MajorGrid.IsVisible = true;
            myPane.YAxis.MinorGrid.IsVisible = true;

            // Calculate the Axis Scale Ranges
            axisChangeZedGraph(zgc); //refrsh the graph
        }
Example #3
0
        //显示点
        private string MyPointValueHandler(ZedGraphControl control, GraphPane pane, CurveItem curve, int iPt)
        {
            PointPair pt = curve[iPt];

            return(curve.Label.Text.Substring(0, 4) + ": " + pt.Y.ToString() + " " + curve.Label.Text.Substring(4, curve.Label.Text.Length - 4) + " " + XDate.XLDateToDateTime(pt.X).ToString());
        }
Example #4
0
 /// <summary>
 /// Format this PointPair value using a general format string.
 /// Example:  a format string of "e2" would give "( 1.23e+001, -1.69e+001 )".
 /// If <see paramref="isShowAll"/>
 /// is true, then the third all coordinates are shown.
 /// </summary>
 /// <param name="format">A format string that will be used to format each of
 /// the two double type values (see <see cref="System.Double.ToString()"/>).</param>
 /// <returns>A string representation of the PointPair</returns>
 /// <param name="isShowAll">true to show all the value coordinates</param>
 public override string ToString(string format, bool isShowAll)
 {
     return(string.Format("({0}, {1}{2})", XDate.ToString(this.Date, "g"), this.Close.ToString(format),
                          isShowAll ? string.Format(", {0}, {1}, {2}", this.Low.ToString(format), this.Open.ToString(format), this.Close.ToString(format)) : string.Empty));
 }
Example #5
0
        /// <summary>
        /// private method for handling MouseMove events to display tooltips over
        /// individual datapoints.
        /// </summary>
        /// <param name="sender">
        /// A reference to the control that has the MouseMove event.
        /// </param>
        /// <param name="e">
        /// A MouseEventArgs object.
        /// </param>
        private void ZedGraphControl_MouseMove(object sender, MouseEventArgs e)
        {
            Point mousePt = new Point(e.X, e.Y);

            SetCursor(mousePt);

            // If the mouse is being dragged,
            // undraw and redraw the rectangle as the mouse moves.
            if (this.isZooming)
            {
                // Hide the previous rectangle by calling the
                // DrawReversibleFrame method with the same parameters.
                ControlPaint.DrawReversibleFrame(this.dragRect,
                                                 this.BackColor, FrameStyle.Dashed);

                // Calculate the endpoint and dimensions for the new
                // rectangle, again using the PointToScreen method.
                Point curPt = ((Control)sender).PointToScreen(mousePt);
                this.dragRect.Width  = curPt.X - this.dragRect.X;
                this.dragRect.Height = curPt.Y - this.dragRect.Y;

                // Draw the new rectangle by calling DrawReversibleFrame
                // again.
                ControlPaint.DrawReversibleFrame(this.dragRect,
                                                 this.BackColor, FrameStyle.Dashed);
            }
            else if (this.isPanning)
            {
                double x1, x2, y1, y2, yy1, yy2;
                PointF endPoint   = new PointF(e.X, e.Y);
                PointF startPoint = ((Control)sender).PointToClient(this.dragRect.Location);

                this.dragPane.ReverseTransform(startPoint, out x1, out y1, out yy1);
                this.dragPane.ReverseTransform(endPoint, out x2, out y2, out yy2);

                this.dragPane.XAxis.Min += x1 - x2;
                this.dragPane.XAxis.Max += x1 - x2;
                this.dragPane.YAxis.Min += y1 - y2;
                this.dragPane.YAxis.Max += y1 - y2;
                Refresh();

                this.dragRect.Location = ((Control)sender).PointToScreen(mousePt);
            }
            else if (isShowPointValues)
            {
                int       iPt;
                GraphPane pane;
                object    nearestObj;

                Graphics g = this.CreateGraphics();

                if (masterPane.FindNearestPaneObject(new PointF(e.X, e.Y),
                                                     g, out pane, out nearestObj, out iPt))
                {
                    if (nearestObj is CurveItem && iPt >= 0)
                    {
                        CurveItem curve = (CurveItem)nearestObj;
                        if (curve is PieItem)
                        {
                            this.pointToolTip.SetToolTip(this,
                                                         ((PieItem)curve).Value.ToString(this.pointValueFormat));
                        }
                        else
                        {
                            PointPair pt = curve.Points[iPt];

                            if (pt.Tag is string)
                            {
                                this.pointToolTip.SetToolTip(this, (string)pt.Tag);
                            }
                            else
                            {
                                string xStr, yStr;

                                if (pane.XAxis.IsDate)
                                {
                                    xStr = XDate.ToString(pt.X, this.pointDateFormat);
                                }
                                else if (pane.XAxis.IsText && pane.XAxis.TextLabels != null &&
                                         iPt >= 0 && iPt < pane.XAxis.TextLabels.Length)
                                {
                                    xStr = pane.XAxis.TextLabels[iPt];
                                }
                                else
                                {
                                    xStr = pt.X.ToString(this.pointValueFormat);
                                }

                                Axis yAxis = curve.IsY2Axis ? (Axis)pane.Y2Axis : (Axis)pane.YAxis;

                                if (yAxis.IsDate)
                                {
                                    yStr = XDate.ToString(pt.Y, this.pointDateFormat);
                                }
                                else if (yAxis.IsText && yAxis.TextLabels != null &&
                                         iPt >= 0 && iPt < yAxis.TextLabels.Length)
                                {
                                    yStr = yAxis.TextLabels[iPt];
                                }
                                else
                                {
                                    yStr = pt.Y.ToString(this.pointValueFormat);
                                }

                                this.pointToolTip.SetToolTip(this, "( " + xStr + ", " + yStr + " )");

                                //this.pointToolTip.SetToolTip( this,
                                //	curve.Points[iPt].ToString( this.pointValueFormat ) );
                            }
                        }

                        this.pointToolTip.Active = true;
                    }
                    else
                    {
                        this.pointToolTip.Active = false;
                    }
                }

                g.Dispose();
            }
        }
Example #6
0
 public string Format(XDate date) => date.ToUnixTime().ToString();
        public void writeFile(WeatherLogger.FormMain.Weather[] w, int wIndex)
        {
            bool overWrite = false;
            int  i;

            string fileName;    // = DateTime.Now.ToString("ddMMyyyy") + ".wlg";
            string strLineContent, strTime;
            XDate  writeLineTime = new XDate();

            if (!(Directory.Exists("log")))
            {
                Directory.CreateDirectory("log");
            }

            // Set wIndex to a very first valid data
            for (i = 0; i < w.Length; i++)
            {
                if (++wIndex >= w.Length)
                {
                    wIndex = 0;
                }
                if (w[wIndex].time != new XDate(1970, 1, 1))
                {
                    break;
                }
            }
            // Set Max time as the next day
            XDate writeLineMaxTime = new XDate(w[wIndex].time.DateTime.Year, w[wIndex].time.DateTime.Month,
                                               (w[wIndex].time.DateTime.Day)).DateTime.AddDays(1);

            // Write as many files required for each date
            i = 0;
            while (i < w.Length)
            {
                // Create a file name
                fileName = @"log\" + w[wIndex].time.DateTime.ToString("ddMMyyyy") + ".wlg";

                if (File.Exists(fileName))
                {
                    overWrite = true;                                   // File Exists
                }
                else
                {
                    overWrite = false;
                }

                if (overWrite)
                {
                    File.Move(fileName, fileName + ".~orig");           // Rename existing file
                }
                StreamWriter objFile = new StreamWriter(fileName);      // New file

                if (overWrite)
                {
                    // Read the existing file and write the data to the new file
                    StreamReader objReadFile = new StreamReader(fileName + ".~orig");
                    while ((strLineContent = objReadFile.ReadLine()) != null)
                    {
                        strLineContent = strLineContent.Trim();
                        strTime        = strLineContent.Split("  ".ToCharArray())[0];
                        writeLineTime  = DateTime.FromBinary(Convert.ToInt64(strTime));
                        if (writeLineTime >= w[wIndex].time.DateTime)
                        {
                            break;
                        }
                        objFile.WriteLine(strLineContent);
                    }
                    objReadFile.Close();
                    objReadFile.Dispose();
                    File.Delete(fileName + ".~orig");
                }
                // Writes new data to the file
                while (i < w.Length)
                {
                    if (w[wIndex].time >= writeLineMaxTime)
                    {
                        writeLineMaxTime = writeLineMaxTime.DateTime.AddDays(1); // Write next date datas to a new file
                        break;
                    }
                    if (w[wIndex].time != new XDate(1970, 1, 1))
                    {
                        strLineContent = w[wIndex].time.DateTime.ToBinary() + "  " + w[wIndex].humidity.ToString()
                                         + "  " + w[wIndex].pressure.ToString() + "  " + w[wIndex].temp.ToString();
                        objFile.WriteLine(strLineContent);
                    }
                    if (++wIndex >= w.Length)
                    {
                        wIndex = 0;
                    }
                    i++;
                }
                objFile.Close();
                objFile.Dispose();
            }
        }
Example #8
0
        /// <summary>
        /// Provides binding between <see cref="DataSource"/> and the specified pane.  Extracts the
        /// data from <see cref="DataSource"/> and copies it into the appropriate
        /// <see cref="ZedGraph.IPointList"/> for each <see cref="ZedGraph.CurveItem"/> in the
        /// specified <see cref="ZedGraph.GraphPane"/>.
        /// </summary>
        /// <param name="g">The <see cref="Graphics"/> object to be used for rendering the data.</param>
        /// <param name="pane">The <see cref="ZedGraph.GraphPane"/> object which will receive the data.</param>
        protected void PopulateByDataSource(IGraphics g, GraphPane pane)
        {
            if (CurveList.Count == 0)
            {
                return;
            }

            //If the Datasource column names are available we can bind them
            // correctly to their corresponding DataMember.
            if (!string.IsNullOrEmpty(DataMember)
                && DataSource != null
                && DataSource is ITypedList
                && DataSource is IListSource)
            {
                var tlist = DataSource as ITypedList;
                var listSource = DataSource as IListSource;
                IList list = listSource.GetList();
                PropertyDescriptorCollection pdc = tlist.GetItemProperties(null);
                bool bListContainsList = listSource.ContainsListCollection;

                //Get the DataMember and Type of the base axis in the DataSource
                string baseDataMember = DataMember;
                PropertyDescriptor basePd = pdc.Find(baseDataMember, true);
                if (basePd == null)
                {
                    throw new Exception("Can't find DataMember '" + baseDataMember + "' in DataSource for the base axis.");
                }

                //Foreach bar/curve
                //  Get its DataMember and Type in the DataSource
                //	Add the curve to the pane
                //  Add all corresponding points(baseAxis,valueAxis,0)
                //Note: Z axis is not supported
                foreach (ZedGraphWebCurveItem curveItem in CurveList)
                {
                    //Axis valueAxis = curveItem.ValueAxis;
                    PropertyDescriptorCollection pdcValue = pdc;
                    IList valueList = list;
                    bool bValueListContainsList = bListContainsList;

                    //If present, use DataSource of Curve instead of main DataSource
                    if (curveItem.DataSource != null
                        && curveItem.DataSource is ITypedList
                        && curveItem.DataSource is IListSource)
                    {
                        var valueTlist = curveItem.DataSource as ITypedList;
                        pdcValue = valueTlist.GetItemProperties(null);
                        var valueListSource = curveItem.DataSource as IListSource;
                        valueList = valueListSource.GetList();
                        bValueListContainsList = valueListSource.ContainsListCollection;
                    }

                    string valueDataMember = curveItem.DataMember;
                    PropertyDescriptor pd = pdcValue.Find(valueDataMember, true);
                    if (pd == null)
                    {
                        throw new Exception("Can't find DataMember '" + valueDataMember + "' in DataSource for the " + curveItem.Label + " axis.");
                    }
                    int indexValueColumn = pdcValue.IndexOf(pd);

                    //Add points
                    var points = new PointPairList();
                    var pair = new PointPair();
                    object oColumnValue;

                    try
                    {
                        int nRow = 0;
                        foreach (object row in list)
                        {
                            //
                            // Value axis binding (Y axis)
                            //
                            object valueRow = valueList[nRow];

                            //Get item value in 'row'
                            if (bValueListContainsList)
                            {
                                if (!(valueRow is IList))
                                {
                                    throw new InvalidCastException("The DataSource contains a list which declares its items as lists, but these don't support the IList interface.");
                                }
                                oColumnValue = (valueRow as IList)[indexValueColumn];
                            }
                            else
                            {
                                oColumnValue = pd.GetValue(valueRow);
                            }

                            //Convert value to double (always double)
                            double v = 0;
                            if (oColumnValue != null)
                            {
                                switch (oColumnValue.GetType().ToString())
                                {
                                    case "System.DateTime":
                                        v = new XDate(Convert.ToDateTime(oColumnValue)).XLDate;
                                        break;
                                    default:
                                        try
                                        {
                                            v = Convert.ToDouble(oColumnValue);
                                        }
                                        catch
                                        {
                                            throw new NotImplementedException("Conversion from " + oColumnValue.GetType() + " to double not implemented.");
                                        }
                                        break;
                                }

                                //
                                // Base axis binding (X axis)
                                //
                                pair.Tag = oColumnValue; //Original typed value
                            }
                            pair.Y = v;
                            if (XAxis.Type == AxisType.DateAsOrdinal
                                || XAxis.Type == AxisType.Date)
                            {
                                pair.X = new XDate(Convert.ToDateTime(basePd.GetValue(row))).XLDate;
                            }
                            else
                            {
                                pair.X = Convert.ToDouble(basePd.GetValue(row));
                            }

                            points.Add(pair);

                            nRow++;
                        }
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        //A local datasource was set on this curve but it has fewer rows than the axis datasource.
                        //So we stop feeding this curve.
                    }

                    //Create curve in pane with its points
                    curveItem.CreateInPane(pane, points);
                }
            }
            else
            {
                //Add curves and values set in designer
                ZedGraphWebCurveItem curve;
                for (int i = 0; i < CurveList.Count; i++)
                {
                    curve = CurveList[i];

                    var points = new PointPairList();
                    var pair = new PointPair();
                    for (int j = 0; j < curve.Points.Count; j++)
                    {
                        curve.Points[j].CopyTo(pair);
                        points.Add(pair);
                    }

                    curve.CreateInPane(pane, points);
                }
            }

            //NOTE: ZedGraphWeb.DataMember = base axis
            //NOTE: ZedGraphCurveItem.DataMember = Y
            //NOTE: Z values are only supported via the callback (???)
            //TODO: cache the data-map table before processing rows (???)
        }
Example #9
0
 public bool IsBirthday(XDate anotherDay)
 {
     return(BirthDate.IsSameDay(anotherDay));
 }
        private DateTime fillSampleData()
        {
            var csvFileExists = File.Exists(CSVFilename);

            if (File.Exists(Filename) || csvFileExists)
            {
                try
                {
                    m_EMAData.Clear();
                    m_ZigZagData.Clear();
                    m_Data = csvFileExists ? Serializer.ReadFromCSV <CandleClusterPtList>(CSVFilename)
                                 : Serializer.ReadFromBinaryFile <CandleClusterPtList>(Filename);

                    foreach (var pt in m_Data.Cast <ICandleClusteredVolume>())
                    {
                        var lo = pt.Low;
                        var hi = pt.High;

                        var inc  = 0.0005f;
                        var next = (lo - lo % inc) + inc;
                        var list = new List <IClusterVolume>();
                        while (next < hi)
                        {
                            list.Add(new VolInfo(lo, m_Rand.Next(1000), m_Rand.Next(1000)));
                            lo    = next;
                            next += inc;
                        }
                        var px = lo + m_Rand.NextDouble() * (hi - lo);
                        pt.Volumes = list.ToArray();
                    }

                    var close = ((ICandleClusteredVolume)m_Data[0]).Close;
                    m_EMA = close;

                    foreach (var p in m_Data.Cast <ICandleClusteredVolume>())
                    {
                        m_EMA = EMA_ALPHA * close + (1.0 - EMA_ALPHA) * m_EMA;
                        m_EMAData.Add(p.Date, m_EMA);
                    }

                    //int hi, lo;
                    //var output = (IPointListEdit)m_ZigZagData;
                    //Indicator.ZigZag(m_Data, 0, m_Data.Count - 1, m_ZigZagPercent, out lo, out hi, ref output);
                    Indicator.ZigZag(m_Data, m_ZigZagData, 0, m_Data.Count, m_ZigZagPercent, true, true, false);

                    return(new XDate(((StockPt)m_Data[m_Data.Count - 1]).Date));
                }
                catch (Exception)
                {
                    m_Data.Clear();
                }
            }

            // First day is jan 1st
            var now = DateTime.Now;

            m_Now  = new XDate(now) - 15.0f / XDate.MinutesPerDay;
            m_Open = 50.0;

            for (var i = 0; i < 60 * 15; i += 5)
            {
                m_Now.AddSeconds(5);
                calc(m_Now, false);
            }

            Serializer.WriteToBinaryFile(Filename, m_Data);

            return(now);
        }
        //------------------------------------------------------------------------
        // Update data on initialization or on timer
        //------------------------------------------------------------------------
        private void calc(XDate now, bool timer)
        {
            var oldTimerEnabled = m_Timer.Enabled;

            m_Timer.Enabled = false;
            const double diff = 5.0f / XDate.SecondsPerDay;
            var          tm   = now - 5;
            var          add  = !timer || (m_Data.Count > 0 && ((now - LastPoint.Date) > diff));
            StockPt      pt   = null;
            var          up   = m_Rand.NextDouble() > 0.5;
            var          val  = up ? LastPoint.Low : LastPoint.High;

            Action <double, double, bool> set_min_max = (min, max, absolute) =>
            {
                var grace = (m_Pane.Y2Axis.Scale.Max - m_Pane.Y2Axis.Scale.Min) *
                            m_Pane.Y2Axis.Scale.MaxGrace;
                var gap = grace; //m_Pane.Y2Axis.Scale.ReverseTransform(10) + grace;
                m_Pane.Y2Axis.Scale.Min = absolute
                                    ? min - gap
                                    : Math.Min(m_Pane.Y2Axis.Scale.Min, min - gap);
                m_Pane.Y2Axis.Scale.Max = absolute
                                    ? max + gap
                                    : Math.Max(m_Pane.Y2Axis.Scale.Max, max + gap);
            };

            if (add)
            {
                var open  = (float)(m_Open + m_Rand.NextDouble() * 10.0 - 5.0);
                var close = (float)(m_Open + m_Rand.NextDouble() * 10.0 - 5.0);
                var hi    = (float)(Math.Max(open, close) + m_Rand.NextDouble() * 5.0);
                var low   = (float)(Math.Min(open, close) - m_Rand.NextDouble() * 5.0);
                var bvol  = m_Rand.NextDouble() * 1000;
                var svol  = m_Rand.NextDouble() * 1000;

                var x = now.XLDate - (now.XLDate % diff);
                pt = new StockPt(x, open, hi, low, close, (int)bvol, (int)svol);

                m_Data.Add(pt);
                m_Open = close;

                m_EMA = EMA_ALPHA * close + (1.0 - EMA_ALPHA) * m_EMA;
                m_EMAData.Add(x, m_EMA);

                if (timer)
                {
                    //m_Pane.XAxis.Scale.Max = now + 5;
                    //m_Pane.XAxis.Scale.Min += diff;

                    if (Math.Abs(Math.Round(m_Pane.XAxis.Scale.Max) - m_Data.Count) < 5)
                    {
                        var window = (int)(m_Pane.XAxis.Scale.Max - m_Pane.XAxis.Scale.Min);
                        //m_Pane.XAxis.Scale.SetRange();
                        m_Pane.XAxis.Scale.Max = m_Data.Count + 1;
                        m_Pane.XAxis.Scale.Min = m_Pane.XAxis.Scale.Max - window;

                        double min = double.MaxValue, max = double.MinValue;
                        var    xMin = Scale.MinMax(0, (int)m_Pane.XAxis.Scale.Min, m_Data.Count);
                        var    xMax = Scale.MinMax(0, (int)m_Pane.XAxis.Scale.Max, m_Data.Count);
                        for (int i = xMin; i < xMax; ++i)
                        {
                            var d = (StockPt)m_Data[i];
                            min = Math.Min(d.Low, min);
                            max = Math.Max(d.High, max);
                        }

                        set_min_max(min, max, true);
                        m_Pane.AxisChange();
                    }

                    if (m_Data.Count % 1 == 0)
                    {
                        var yy =
                            m_Pane.Y2Axis.Scale.ReverseTransform(m_Pane.Y2Axis.Scale.Transform(val) +
                                                                 (up ? 5 : -5));
                        //var y2 = val * (up ? 0.96 : 1.03);
                        var arrow = new PointObj(m_Data.Count - 1, yy, 5,
                                                 up ? SymbolType.ArrowUp : SymbolType.ArrowDown,
                                                 up ? Color.Green : Color.Red)
                        {
                            IsMovable  = false,
                            IsY2Axis   = true,
                            YAxisIndex = 0,
                            //Fill = {Type = FillType.None},
                            IsClippedToChartRect = true
                        };

                        //arrow.Line.Width = 1;
                        //arrow.Location.CoordinateFrame = CoordType.AxisXYScale;
                        m_Pane.GraphObjList.Add(arrow);
                    }
                }
            }
            else if (m_Data.Count > 0)
            {
                pt       = LastPoint;
                pt.Close = (float)(m_Open + m_Rand.NextDouble() * 10.0 - 5.0);
                pt.High  = (float)Math.Max(pt.High, Math.Max(m_Open, pt.Close) + m_Rand.NextDouble() * 5.0);
                pt.Low   = (float)Math.Min(pt.Low, Math.Min(m_Open, pt.Close) - m_Rand.NextDouble() * 5.0);

                if (timer && Math.Abs(Math.Round(m_Pane.XAxis.Scale.Max) - m_Data.Count) < 5)
                {
                    set_min_max(pt.Low, pt.High, false);
                }
            }

            if (m_Line != null)
            {
                m_Line.Value = pt.Close;
            }

            m_Now           = now;
            m_Timer.Enabled = oldTimerEnabled;
        }
        public void UpdatePutCallRatioGraphCurves()
        {
            GraphPane pane = putCallRatioGraph.GraphPane;

            // delete old curves
            if (call_curve != null)
            {
                pane.CurveList.Remove(call_curve);
                call_curve = null;
            }
            if (put_curve != null)
            {
                pane.CurveList.Remove(put_curve);
                put_curve = null;
            }

            // update titles
            switch (mode)
            {
            case GraphMode.MODE_BY_EXPIRATION:
                pane.XAxis.Title.Text = "Date";
                pane.XAxis.Type       = AxisType.DateAsOrdinal;
                break;

            case GraphMode.MODE_BY_STRIKE:
                pane.XAxis.Title.Text = "Strike";
                pane.XAxis.Type       = AxisType.Linear;
                break;
            }

            // x-axis
            pane.XAxis.Scale.FormatAuto    = true;
            pane.XAxis.Scale.MinAuto       = true;
            pane.XAxis.Scale.MaxAuto       = true;
            pane.XAxis.Scale.MinorStepAuto = true;
            pane.XAxis.Scale.MajorStepAuto = true;

            // y-axis
            pane.YAxis.Scale.MinAuto       = true;
            pane.YAxis.Scale.MinorStepAuto = true;
            pane.YAxis.Scale.MaxAuto       = true;
            pane.YAxis.Scale.MajorStepAuto = true;


            ArrayList xscale_list = null;

            switch (mode)
            {
            case GraphMode.MODE_BY_EXPIRATION:
                xscale_list = core.GetExpirationDateList(DateTime.Now, DateTime.MaxValue);
                break;

            case GraphMode.MODE_BY_STRIKE:
                xscale_list = core.GetStrikeList(DateTime.MinValue);
                break;
            }
            if (xscale_list == null)
            {
                return;
            }

            string[] type_list = new string[2] {
                "Call", "Put"
            };

            foreach (string type in type_list)
            {
                ArrayList x = new ArrayList();
                ArrayList y = new ArrayList();

                foreach (object xscale in xscale_list)
                {
                    ArrayList option_list = null;

                    try
                    {
                        switch (mode)
                        {
                        case GraphMode.MODE_BY_EXPIRATION:
                            option_list = core.GetOptionList("(Type = '" + type + "') AND (Expiration = '" + Global.DefaultCultureToString((DateTime)xscale) + "')");
                            break;

                        case GraphMode.MODE_BY_STRIKE:
                            option_list = core.GetOptionList("(Type = '" + type + "') AND (Strike = " + Global.DefaultCultureToString((double)xscale) + ")");
                            break;
                        }
                    }
                    catch { option_list = null; }

                    if (option_list == null)
                    {
                        continue;
                    }

                    // open int
                    int open_int = 0;
                    foreach (Option option in option_list)
                    {
                        open_int += option.open_int;
                    }

                    switch (mode)
                    {
                    case GraphMode.MODE_BY_EXPIRATION:
                        // date
                        XDate x_expdate = new XDate((DateTime)xscale);
                        x.Add((double)x_expdate.XLDate);
                        break;

                    case GraphMode.MODE_BY_STRIKE:
                        x.Add((double)xscale);
                        break;
                    }
                    y.Add((double)open_int);
                }
                if (x.Count == 0)
                {
                    continue;
                }

                double[] putcallratio_x = (double[])x.ToArray(System.Type.GetType("System.Double"));
                double[] putcallratio_y = (double[])y.ToArray(System.Type.GetType("System.Double"));

                string name = type;

                if (type == "Call")
                {
                    call_curve = pane.AddBar(name, putcallratio_x, putcallratio_y, Config.Color.PositionBackColor(1));
                    call_curve.Bar.Fill.Type = FillType.Solid;
                }
                else
                {
                    put_curve = pane.AddBar(name, putcallratio_x, putcallratio_y, Config.Color.PositionBackColor(0));
                    put_curve.Bar.Fill.Type = FillType.Solid;
                }
            }

            putCallRatioGraph.AxisChange();
            putCallRatioGraph.Invalidate();

            // expand the range of the Y axis slightly to accommodate the labels
            pane.YAxis.Scale.Max += pane.YAxis.Scale.MajorStep;

            Color fg = Config.Color.GraphForeColor;

            if (invert_colors)
            {
                fg = Color.FromArgb(255 - fg.R, 255 - fg.G, 255 - fg.B);
            }

            // create TextObj's to provide labels for each bar
            DeleteBarLabels();
            BarItem.CreateBarLabels(pane, false, "f0", "Microsoft San Serif", 10F, fg, false, false, false);

            // update graph default axis
            putcallratio_xaxis_min = pane.XAxis.Scale.Min;
            putcallratio_xaxis_max = pane.XAxis.Scale.Max;
            putcallratio_xaxis_maj = pane.XAxis.Scale.MajorStep;
            putcallratio_xaxis_mor = pane.XAxis.Scale.MinorStep;
            putcallratio_yaxis_min = pane.YAxis.Scale.Min;
            putcallratio_yaxis_max = pane.YAxis.Scale.Max;
            putcallratio_yaxis_maj = pane.YAxis.Scale.MajorStep;
            putcallratio_yaxis_mor = pane.YAxis.Scale.MinorStep;
        }
Example #13
0
        public void FromDateTimeOffsets()
        {
            var date = new XDate(new DateTimeOffset(2008, 05, 11, 7, 0, 0, TimeSpan.FromHours(-5)));

            Assert.Equal("2008-05-11T07:00-05:00", date.ToString());
        }
Example #14
0
        public void FromDateTimeTests()
        {
            var date = new XDate(new DateTime(2008, 05, 11));

            // Assert.Equal("2008-05-11", date.ToString());ED
        }
Example #15
0
        /// <summary>
        /// Calculate a date that is close to the specified date and an
        /// even multiple of the selected
        /// <see cref="Scale.MajorUnit"/> for a <see cref="AxisType.Date"/> scale.
        /// This method is used by <see cref="PickScale"/>.
        /// </summary>
        /// <param name="date">The date which the calculation should be close to</param>
        /// <param name="direction">The desired direction for the date to take.
        /// 1 indicates the result date should be greater than the specified
        /// date parameter.  -1 indicates the other direction.</param>
        /// <returns>The calculated date</returns>
        protected double CalcEvenStepDate(double date, int direction)
        {
            int year, month, day, hour, minute, second, millisecond;

            XDate.XLDateToCalendarDate(date, out year, out month, out day,
                                       out hour, out minute, out second, out millisecond);

            // If the direction is -1, then it is sufficient to go to the beginning of
            // the current time period, .e.g., for 15-May-95, and monthly steps, we
            // can just back up to 1-May-95
            if (direction < 0)
            {
                direction = 0;
            }

            switch (_majorUnit)
            {
            case DateUnit.Year:
            default:
                // If the date is already an exact year, then don't step to the next year
                if (direction == 1 && month == 1 && day == 1 && hour == 0 &&
                    minute == 0 && second == 0)
                {
                    return(date);
                }
                else
                {
                    return(XDate.CalendarDateToXLDate(year + direction, 1, 1,
                                                      0, 0, 0));
                }

            case DateUnit.Month:
                // If the date is already an exact month, then don't step to the next month
                if (direction == 1 && day == 1 && hour == 0 &&
                    minute == 0 && second == 0)
                {
                    return(date);
                }
                else
                {
                    return(XDate.CalendarDateToXLDate(year, month + direction, 1,
                                                      0, 0, 0));
                }

            case DateUnit.Day:
                // If the date is already an exact Day, then don't step to the next day
                if (direction == 1 && hour == 0 && minute == 0 && second == 0)
                {
                    return(date);
                }
                else
                {
                    return(XDate.CalendarDateToXLDate(year, month,
                                                      day + direction, 0, 0, 0));
                }

            case DateUnit.Hour:
                // If the date is already an exact hour, then don't step to the next hour
                if (direction == 1 && minute == 0 && second == 0)
                {
                    return(date);
                }
                else
                {
                    return(XDate.CalendarDateToXLDate(year, month, day,
                                                      hour + direction, 0, 0));
                }

            case DateUnit.Minute:
                // If the date is already an exact minute, then don't step to the next minute
                if (direction == 1 && second == 0)
                {
                    return(date);
                }
                else
                {
                    return(XDate.CalendarDateToXLDate(year, month, day, hour,
                                                      minute + direction, 0));
                }

            case DateUnit.Second:
                return(XDate.CalendarDateToXLDate(year, month, day, hour,
                                                  minute, second + direction));

            case DateUnit.Millisecond:
                return(XDate.CalendarDateToXLDate(year, month, day, hour,
                                                  minute, second, millisecond + direction));
            }
        }
Example #16
0
        // Fill the graph with the data provided.
        private void FillGraphWithData(ZedGraph.ZedGraphControl zgc, int thresholdId, int deviceId, string deviceType, string thresholdName)
        {
            if (zgc == null)
            {
                return;
            }

            GraphPane myPane = zgc.GraphPane;


            // Set the titles and axis labels per selection
            thresholdName     = thresholdName.Replace(" ", String.Empty);//remove whitespaces
            myPane.Title.Text = thresholdName + " - " + "last 24 hours";
            // myPane.Title.Text = "last 24 hours";
            myPane.XAxis.Title.Text = "Time (Sec)";
            myPane.YAxis.Title.Text = "%";

            // Change the color of the title
            //  myPane.Title.FontSpec.FontColor = Color.Blue;

            //Set the font size
            myPane.Title.FontSpec.Size       = 20.0f;
            myPane.YAxis.Title.FontSpec.Size = 20.0f;
            myPane.YAxis.Scale.FontSpec.Size = 20.0f;
            myPane.XAxis.Title.FontSpec.Size = 20.0f;
            myPane.XAxis.Scale.FontSpec.Size = 20.0f;


            myPane.CurveList.Clear();// clear the graph

            myPane.Legend.IsVisible = false;

            XDate minDate = XDate.JulDayMax;
            XDate maxDate = XDate.JulDayMin;
            //Create Random colors to show on Graph

            PointPairList listDeviceValues = GetValuesForDevice(deviceId, thresholdId);

            //use this to add line width 3.0F
            LineItem myCurve = new LineItem("", listDeviceValues, Color.Blue, SymbolType.XCross);

            myPane.CurveList.Add(myCurve);

            if (listDeviceValues.Count > 0)
            {
                XDate firstDate = (XDate)(listDeviceValues[0].X);
                XDate lastDate  = (XDate)listDeviceValues[listDeviceValues.Count - 1].X;
                if (minDate == XDate.JulDayMax) //The max valid Julian Day, which corresponds to January 1st, 4713 B.C
                {
                    minDate = firstDate;
                }
                else if (firstDate < minDate)
                {
                    minDate = firstDate;
                }

                if (maxDate == XDate.JulDayMin)//The minimum valid Julian Day, which corresponds to January 1st, 4713 B.C
                {
                    maxDate = lastDate;
                }
                else if (lastDate > maxDate)
                {
                    maxDate = lastDate;
                }
            }

            Int32         thresholdValue     = GetContractThreshold(deviceType, thresholdId);//Read the Threshold values
            PointPairList thresholdPointList = new PointPairList();

            thresholdPointList.Add(new PointPair(minDate, thresholdValue));
            thresholdPointList.Add(new PointPair(maxDate, thresholdValue));

            myPane.CurveList.Insert(0, new LineItem("Threshold", thresholdPointList, Color.FromArgb(255, 0, 0, 0), SymbolType.XCross, 3.0f));

            // Fill the axis background with a color gradient
            myPane.Chart.Fill = new Fill(Color.White, Color.LightGoldenrodYellow, 45F);

            // Fill the pane background with a color gradient
            myPane.Fill = new Fill(Color.White, Color.FromArgb(220, 220, 255), 45F);

            //This informs ZedGraph to use the labels supplied by the user in Axis.Scale.TextLabels
            Axis.Default.Type = AxisType.Text;

            ////Show tooltips when the mouse hovers over a point
            //zgc.IsShowPointValues = true;
            //zgc.PointValueEvent += new ZedGraphControl.PointValueHandler(MyPointValueHandler);

            // Set the XAxis to date type
            myPane.XAxis.Type = AxisType.Date;

            myPane.YAxis.MajorGrid.IsVisible = true;
            myPane.YAxis.MinorGrid.IsVisible = true;

            // Calculate the Axis Scale Ranges
            axisChangeZedGraph(zgc); //refrsh the graph
        }
Example #17
0
        void InitPointList()
        {
            x1 = DateTime.Now;
            x0 = x1.AddSeconds(-DisplayTimeSpan);

            if (rdo == null)
            {
                rdo           = new RealDataOperter();
                rdo.DataCount = DisplayTimeSpan / timeGap;
                rdo.Fname     = Application.StartupPath + "\\RealData.bin";
            }
            var j = 0;
            var x = x0;

            if (rdo.Read())
            {
                var i = 0;
                while (rdo.DataList[i].Time < x)
                {
                    i++;
                    if (i >= rdo.DataList.Count)
                    {
                        break;
                    }
                }

                for (; i < rdo.DataList.Count; i++)
                {
                    while (x < rdo.DataList[i].Time)
                    {
                        if ((rdo.DataList[i].Time - x).TotalSeconds < 300)
                        {
                            TopTemp[j] = rdo.DataList[i].T1;
                            BMTTemp[j] = rdo.DataList[i].T2;
                            TopHR[j]   = rdo.DataList[i].H1;
                            BMTHR[j]   = rdo.DataList[i].H2;
                            date[j]    = new XDate(x).XLDate;
                        }
                        else if ((rdo.DataList[i].Time - x).TotalSeconds == 300)
                        {
                            TopTemp[j] = rdo.DataList[i].T1;
                            BMTTemp[j] = rdo.DataList[i].T2;
                            TopHR[j]   = rdo.DataList[i].H1;
                            BMTHR[j]   = rdo.DataList[i].H2;
                            date[j]    = new XDate(rdo.DataList[i - 1].Time).XLDate;
                        }
                        else
                        {
                            TopTemp[j] = 0;
                            BMTTemp[j] = 0;
                            TopHR[j]   = 0;
                            BMTHR[j]   = 0;
                            date[j]    = new XDate(x).XLDate;
                        }

                        x = x.AddSeconds(timeGap);
                        j++;
                    }
                    if (j >= DisplayTimeSpan / timeGap)
                    {
                        j = DisplayTimeSpan / timeGap - 1;
                    }
                    var r = rdo.DataList[i];
                    TopTemp[j] = r.T1;
                    BMTTemp[j] = r.T2;
                    TopHR[j]   = r.H1;
                    BMTHR[j]   = r.H2;
                    date[j]    = new XDate(r.Time);
                    j++;
                    x = x.AddSeconds(timeGap);
                }
            }
            x = x0.AddSeconds(j * timeGap);
            for (; j < DisplayTimeSpan / timeGap; j++)
            {
                TopTemp[j] = 0;
                BMTTemp[j] = 0;
                TopHR[j]   = 0;
                BMTHR[j]   = 0;
                date[j]    = new XDate(x).XLDate;
                x          = x.AddSeconds(timeGap);
            }
            LTopTemp = new PointPairList(date, TopTemp);
            LBMTTemp = new PointPairList(date, BMTTemp);
            LTopHR   = new PointPairList(date, TopHR);
            LBMTHR   = new PointPairList(date, BMTHR);
            for (j = 0; j < DisplayTimeSpan / timeGap; j++)
            {
                TempAVG[j] = (TopTemp[j] + BMTTemp[j]) / 2.0;
                HRAVG[j]   = (TopHR[j] + BMTHR[j]) / 2.0;
            }
        }
        public override bool doEvent(int event_number, object arg)
        {
            switch (event_number)
            {
                #region - event_Load -

            case event_Load:
            {
                //InitEventCode event_Load

                                        #if ROBOT
                var_util.execDefinedRobot(this, var_alias);
                                        #else
                doEvent(event_Translate, null);
                doEvent(event_FormIsOpening, null);
                                        #endif

                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_Translate -

            case event_Translate:
            {
                //InitEventCode event_Translate
                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_FormIsOpening -

            case event_FormIsOpening:
            {
                //InitEventCode event_FormIsOpening

                ctrl_TxtDtIni.AcquireTextBox(i_Form.TxtDtIni, this, event_val_TxtDtIni, dateTextController.FORMAT_DDMMYYYY);
                ctrl_TxtDtFim.AcquireTextBox(i_Form.TxtDtFim, this, event_val_TxtDtFim, dateTextController.FORMAT_DDMMYYYY);
                ctrl_TxtEmpresa.AcquireTextBox(i_Form.TxtEmpresa, this, event_val_TxtEmpresa, 6);
                ctrl_TxtCodLoja.AcquireTextBox(i_Form.TxtCodLoja, this, event_val_TxtCodLoja, 6);

                ctrl_TxtDtFim.SetTextBoxText(DateTime.Now.Day.ToString().PadLeft(2, '0') +
                                             DateTime.Now.Month.ToString().PadLeft(2, '0') +
                                             DateTime.Now.Year.ToString().PadLeft(2, '0'));

                ctrl_TxtDtIni.SetupErrorProvider(ErrorIconAlignment.MiddleRight, false);
                ctrl_TxtDtFim.SetupErrorProvider(ErrorIconAlignment.MiddleRight, false);
                ctrl_TxtEmpresa.SetupErrorProvider(ErrorIconAlignment.MiddleRight, false);
                ctrl_TxtCodLoja.SetupErrorProvider(ErrorIconAlignment.MiddleRight, false);

                if (header.get_tg_user_type() == TipoUsuario.Administrador ||
                    header.get_tg_user_type() == TipoUsuario.AdminGift)
                {
                    ctrl_TxtEmpresa.SetTextBoxText(header.get_st_empresa());
                    i_Form.TxtEmpresa.ReadOnly = true;

                    i_Form.tabControl1.TabPages.RemoveAt(1);
                    i_Form.tabControl1.TabPages.RemoveAt(1);
                }

                i_Form.CboTipo.SelectedIndex  = 0;
                i_Form.CboGraph.SelectedIndex = 0;

                //EndEventCode
                return(true);
            }

                #endregion

                #region - robot_ShowDialog -

            case robot_ShowDialog:
            {
                //InitEventCode robot_ShowDialog
                //EndEventCode
                return(true);
            }

                #endregion

                #region - robot_CloseDialog -

            case robot_CloseDialog:
            {
                //InitEventCode robot_CloseDialog
                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_GeraGrafico -

            case event_GeraGrafico:
            {
                //InitEventCode event_GeraGrafico

                if (i_Form.LstLines.Items.Count == 0)
                {
                    return(false);
                }

                dlgGraph graph = new dlgGraph();

                graph.Text = "Gráficos ConveyNET para desempenho financeiro";

                GraphPane myPane = graph.zed.GraphPane;

                myPane.Title.Text = "Performance financeira comparativa de lojas";

                myPane.XAxis.Title.Text = "Período requerido";
                myPane.XAxis.Type       = AxisType.Date;
                //myPane.XAxis.Scale.Format  = "d";

                myPane.YAxis.Title.Text   = "Valores de compras nas lojas";
                myPane.YAxis.Scale.Format = "c";

                myPane.CurveList.Clear();

                ArrayList lstInput = new ArrayList();

                for (int t = 0; t < i_Form.LstLines.Items.Count; ++t)
                {
                    DadosGraficoFinanceiro dgf = new DadosGraficoFinanceiro();

                    #region - format data -

                    dgf.set_st_empresa(i_Form.LstLines.Items[t].SubItems[0].Text);

                    string dt_ini = i_Form.LstLines.Items[t].SubItems[1].Text;

                    dt_ini = dt_ini.Substring(6, 4) + "-" +
                             dt_ini.Substring(3, 2) + "-" +
                             dt_ini.Substring(0, 2);

                    string dt_fim = i_Form.LstLines.Items[t].SubItems[2].Text;

                    dt_fim = dt_fim.Substring(6, 4) + "-" +
                             dt_fim.Substring(3, 2) + "-" +
                             dt_fim.Substring(0, 2);

                    dgf.set_dt_ini(dt_ini);
                    dgf.set_dt_fim(dt_fim);

                    string loja = i_Form.LstLines.Items[t].SubItems[3].Text;

                    if (loja.StartsWith("L"))
                    {
                        dgf.set_st_loja(loja.Substring(1, loja.IndexOf(" ") - 1).Trim());
                    }

                    dgf.set_nu_id(t.ToString());

                    #endregion

                    lstInput.Add(dgf);
                }

                string st_csv_contents = "";

                if (!var_exchange.graph_financeiro(i_Form.CboTipo.SelectedIndex.ToString(),
                                                   ref header,
                                                   ref lstInput,
                                                   ref st_csv_contents))
                {
                    return(false);
                }

                ArrayList full_memory = new ArrayList();

                while (st_csv_contents != "")
                {
                    ArrayList tmp_memory = new ArrayList();

                    if (var_exchange.fetch_memory(st_csv_contents, "200", ref st_csv_contents, ref tmp_memory))
                    {
                        for (int t = 0; t < tmp_memory.Count; ++t)
                        {
                            full_memory.Add(tmp_memory[t]);
                        }
                    }
                }

                Color col = Color.Green;

                for (int t = 0; t < lstInput.Count; ++t)
                {
                    PointPairList list = new PointPairList();

                    switch (t)
                    {
                    case 0: col = Color.Green;      break;

                    case 1: col = Color.Red;        break;

                    case 2: col = Color.Blue;       break;

                    case 3: col = Color.Gray;       break;

                    case 4: col = Color.Orange;     break;

                    case 5: col = Color.Violet;     break;

                    default: break;
                    }

                    string name_curve = "";
                    string my_id      = t.ToString();

                    for (int g = 0; g < full_memory.Count; ++g)
                    {
                        DadosGraficoFinanceiro dgf = new DadosGraficoFinanceiro(full_memory[g] as DataPortable);

                        if (dgf.get_nu_id() != my_id)
                        {
                            continue;
                        }

                        if (name_curve == "")
                        {
                            name_curve = dgf.get_st_loja();
                        }

                        string line = dgf.get_dt_point();

                        XDate x = new XDate(Convert.ToInt32(line.Substring(0, 4)),                              // ano
                                            Convert.ToInt32(line.Substring(5, 2)),                              // mes
                                            Convert.ToInt32(line.Substring(8, 2)),                              // dia
                                            Convert.ToInt32(line.Substring(11, 2)),                             // hora
                                            Convert.ToInt32(line.Substring(14, 2)),
                                            0, 0);                                                              // minuto

                        list.Add((double)x, Convert.ToDouble(dgf.get_vr_point()) / 100);
                    }

                    if (i_Form.CboGraph.SelectedIndex == 0)
                    {
                        myPane.AddBar(name_curve, (IPointList)list, col);
                    }
                    else
                    {
                        LineItem myCurve = myPane.AddCurve(name_curve, list, col, SymbolType.None);
                        myCurve.Line.Fill = new Fill(Color.White, Color.FromArgb(60, col.R, col.G, col.B), 90F);
                    }

                    name_curve = "";
                }

                myPane.Chart.Fill = new Fill(Color.White, Color.LightGoldenrodYellow, 45F);
                myPane.Fill       = new Fill(Color.White, Color.FromArgb(220, 220, 255), 45F);

                graph.zed.AxisChange();

                graph.ShowDialog();

                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_Adicionar -

            case event_Adicionar:
            {
                //InitEventCode event_Adicionar

                if (!ctrl_TxtDtIni.IsUserValidated)
                {
                    MessageBox.Show("Informe o período inicial", "Aviso");
                    return(false);
                }

                if (!ctrl_TxtDtFim.IsUserValidated)
                {
                    MessageBox.Show("Informe o período final", "Aviso");
                    return(false);
                }

                if (!ctrl_TxtEmpresa.IsUserValidated)
                {
                    MessageBox.Show("Informe a empresa", "Aviso");
                    return(false);
                }

                if (ctrl_TxtCodLoja.IsUserValidated)
                {
                    if (i_Form.TxtNome.Text == "")
                    {
                        MessageBox.Show("Confirmar a loja pressionando enter no campo de código", "Aviso");
                        return(false);
                    }
                }

                if (i_Form.LstLines.Items.Count >= 5)
                {
                    MessageBox.Show("Máximo de cinco items para gráfico", "Aviso");
                    return(false);
                }

                string nome = "";

                if (ctrl_TxtCodLoja.IsUserValidated)
                {
                    nome = "L" + ctrl_TxtCodLoja.getTextBoxValue() + " - " + i_Form.TxtNome.Text;
                }
                else
                {
                    if (ctrl_TxtEmpresa.getTextBoxValue_Long() == 0)
                    {
                        nome = "ConveyNET";
                    }
                    else
                    {
                        nome = "Todas as lojas";
                    }
                }

                string [] full_row = new string [] { ctrl_TxtEmpresa.getTextBoxValue(),
                          ctrl_TxtDtIni.getTextBoxValue(),
                          ctrl_TxtDtFim.getTextBoxValue(),
                          nome };

                i_Form.LstLines.Items.Add(var_util.GetListViewItem(null, full_row));

                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_val_TxtDtIni -

            case event_val_TxtDtIni:
            {
                //InitEventCode event_val_TxtDtIni

                switch (arg as string)
                {
                case dateTextController.DATE_INVALID:
                {
                    i_Form.TxtDtIni.BackColor     = colorInvalid;
                    ctrl_TxtDtIni.IsUserValidated = false;
                    break;
                }

                case dateTextController.DATE_VALID:
                {
                    i_Form.TxtDtIni.BackColor     = Color.White;
                    ctrl_TxtDtIni.IsUserValidated = true;
                    ctrl_TxtDtIni.CleanError();
                    break;
                }

                default: break;
                }

                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_val_TxtDtFim -

            case event_val_TxtDtFim:
            {
                //InitEventCode event_val_TxtDtFim

                switch (arg as string)
                {
                case dateTextController.DATE_INVALID:
                {
                    i_Form.TxtDtFim.BackColor     = colorInvalid;
                    ctrl_TxtDtFim.IsUserValidated = false;
                    break;
                }

                case dateTextController.DATE_VALID:
                {
                    i_Form.TxtDtFim.BackColor     = Color.White;
                    ctrl_TxtDtFim.IsUserValidated = true;
                    ctrl_TxtDtIni.CleanError();
                    break;
                }

                default: break;
                }

                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_val_TxtCodLoja -

            case event_val_TxtCodLoja:
            {
                //InitEventCode event_val_TxtCodLoja

                switch (arg as string)
                {
                case numberTextController.NUMBER_INCOMPLETE:
                case numberTextController.NUMBER_COMPLETE:
                {
                    if (i_Form.TxtCodLoja.Text.Length > 0)
                    {
                        i_Form.TxtCodLoja.BackColor     = Color.White;
                        ctrl_TxtCodLoja.IsUserValidated = true;
                        ctrl_TxtCodLoja.CleanError();

                        if (length_cod_loja > 0)
                        {
                            if (length_cod_loja != i_Form.TxtCodLoja.Text.Length)
                            {
                                i_Form.TxtNome.Text = "";
                            }
                        }

                        length_cod_loja = i_Form.TxtCodLoja.Text.Length;

                        if (ctrl_TxtCodLoja.GetEnterPressed())
                        {
                            DadosLoja dl = new DadosLoja();

                            var_exchange.fetch_dadosLoja("", ctrl_TxtCodLoja.getTextBoxValue(), ref header, ref dl);

                            i_Form.TxtNome.Text = dl.get_st_nome();
                        }
                    }
                    else
                    {
                        i_Form.TxtCodLoja.BackColor     = colorInvalid;
                        ctrl_TxtCodLoja.IsUserValidated = false;
                    }

                    break;
                }

                default: break;
                }

                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_val_TxtEmpresa -

            case event_val_TxtEmpresa:
            {
                //InitEventCode event_val_TxtEmpresa

                switch (arg as string)
                {
                case numberTextController.NUMBER_INCOMPLETE:
                case numberTextController.NUMBER_COMPLETE:
                {
                    if (i_Form.TxtEmpresa.Text.Length > 0)
                    {
                        i_Form.TxtEmpresa.BackColor     = Color.White;
                        ctrl_TxtEmpresa.IsUserValidated = true;
                        ctrl_TxtEmpresa.CleanError();
                    }
                    else
                    {
                        i_Form.TxtEmpresa.BackColor     = colorInvalid;
                        ctrl_TxtEmpresa.IsUserValidated = false;
                    }

                    break;
                }

                default: break;
                }

                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_Remover -

            case event_Remover:
            {
                //InitEventCode event_Remover

                if (i_Form.LstLines.SelectedItems.Count == 0)
                {
                    return(false);
                }

                i_Form.LstLines.Items.RemoveAt(i_Form.LstLines.SelectedIndices[0]);

                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_BuscaListaLojasTransacao -

            case event_BuscaListaLojasTransacao:
            {
                //InitEventCode event_BuscaListaLojasTransacao

                if (!ctrl_TxtDtIni.IsUserValidated)
                {
                    MessageBox.Show("Informe a data inicial", "Aviso");
                    return(false);
                }

                if (!ctrl_TxtDtFim.IsUserValidated)
                {
                    MessageBox.Show("Informe a data final", "Aviso");
                    return(false);
                }

                i_Form.BtnBuscarLista.Enabled = false;
                i_Form.LstTransLojas.Items.Clear();

                string st_csv_contents = "";

                var_exchange.fetch_listaTransacoesLojas(var_util.GetDataBaseTimeFormat(ctrl_TxtDtIni.getTextBoxValue_Date()),
                                                        var_util.GetDataBaseTimeFormat(ctrl_TxtDtFim.getTextBoxValue_Date()),
                                                        ref header,
                                                        ref st_csv_contents);

                ArrayList full_memory = new ArrayList();

                while (st_csv_contents != "")
                {
                    ArrayList tmp_memory = new ArrayList();

                    if (var_exchange.fetch_memory(st_csv_contents, "200", ref st_csv_contents, ref tmp_memory))
                    {
                        for (int t = 0; t < tmp_memory.Count; ++t)
                        {
                            full_memory.Add(tmp_memory[t]);
                        }
                    }
                }

                for (int t = 0; t < full_memory.Count; ++t)
                {
                    DadosConsultaGraficoTransLojas dl = new DadosConsultaGraficoTransLojas(full_memory[t] as DataPortable);

                    string [] full_row = new string [] { dl.get_nu_trans(),
                              dl.get_nu_cod(),
                              dl.get_tg_tipo(),
                              dl.get_st_nome() };

                    i_Form.LstTransLojas.Items.Add(var_util.GetListViewItem(null, full_row));
                }

                i_Form.BtnBuscarLista.Enabled = true;

                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_GeraGraficoTransacao -

            case event_GeraGraficoTransacao:
            {
                //InitEventCode event_GeraGraficoTransacao

                dlgGraph graph = new dlgGraph();

                graph.Text = "Gráficos ConveyNET para quantidade de transações";

                GraphPane myPane = graph.zed.GraphPane;

                myPane.Title.Text = "Performance em transações de associações e lojas";

                myPane.XAxis.Title.Text = "Período requerido";
                myPane.XAxis.Type       = AxisType.Date;

                myPane.YAxis.Title.Text = "Quantidade de transações";

                myPane.CurveList.Clear();

                ArrayList lstInput = new ArrayList();

                for (int t = 0; t < i_Form.LstTransLojas.Items.Count; ++t)
                {
                    if (i_Form.LstTransLojas.Items[t].Checked)
                    {
                        DadosConsultaGraficoTransLojas dl = new DadosConsultaGraficoTransLojas();

                        dl.set_nu_cod(i_Form.LstTransLojas.Items[t].SubItems[1].Text);
                        dl.set_tg_tipo(i_Form.LstTransLojas.Items[t].SubItems[2].Text);
                        dl.set_st_nome(i_Form.LstTransLojas.Items[t].SubItems[3].Text);

                        lstInput.Add(dl);
                    }
                }

                string st_csv_contents = "";

                if (!var_exchange.graph_transacoes(var_util.GetDataBaseTimeFormat(ctrl_TxtDtIni.getTextBoxValue_Date()),
                                                   var_util.GetDataBaseTimeFormat(ctrl_TxtDtFim.getTextBoxValue_Date()),
                                                   ref header,
                                                   ref lstInput,
                                                   ref st_csv_contents))
                {
                    return(false);
                }

                ArrayList full_memory = new ArrayList();

                while (st_csv_contents != "")
                {
                    ArrayList tmp_memory = new ArrayList();

                    if (var_exchange.fetch_memory(st_csv_contents, "200", ref st_csv_contents, ref tmp_memory))
                    {
                        for (int t = 0; t < tmp_memory.Count; ++t)
                        {
                            full_memory.Add(tmp_memory[t]);
                        }
                    }
                }

                Color col = Color.Green;

                for (int t = 0; t < lstInput.Count; ++t)
                {
                    DadosConsultaGraficoTransLojas dl = new DadosConsultaGraficoTransLojas(lstInput[t] as DataPortable);

                    PointPairList list = new PointPairList();

                    switch (t)
                    {
                    case 0: col = Color.Green;      break;

                    case 1: col = Color.Red;        break;

                    case 2: col = Color.Blue;       break;

                    case 3: col = Color.Gray;       break;

                    case 4: col = Color.Orange;     break;

                    case 5: col = Color.Violet;     break;

                    default: break;
                    }

                    string name_curve = dl.get_st_nome();
                    string my_id      = t.ToString();

                    for (int g = 0; g < full_memory.Count; ++g)
                    {
                        DadosConsultaGraficoTransLojas dgt = new DadosConsultaGraficoTransLojas(full_memory[g] as DataPortable);

                        if (dgt.get_nu_id() != my_id)
                        {
                            continue;
                        }

                        string line = dgt.get_dt_trans();

                        XDate x = new XDate(Convert.ToInt32(line.Substring(0, 4)),                              // ano
                                            Convert.ToInt32(line.Substring(5, 2)),                              // mes
                                            Convert.ToInt32(line.Substring(8, 2)),                              // dia
                                            Convert.ToInt32(line.Substring(11, 2)),                             // hora
                                            Convert.ToInt32(line.Substring(14, 2)),
                                            0, 0);                                                              // minuto

                        list.Add((double)x, Convert.ToDouble(dgt.get_nu_trans()));
                    }

                    LineItem myCurve = myPane.AddCurve(name_curve, list, col, SymbolType.None);
                }

                myPane.Chart.Fill = new Fill(Color.White, Color.LightGoldenrodYellow, 45F);
                myPane.Fill       = new Fill(Color.White, Color.FromArgb(220, 220, 255), 45F);

                graph.zed.AxisChange();

                graph.ShowDialog();

                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_Ranking -

            case event_Ranking:
            {
                //InitEventCode event_Ranking
                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_BtnRemoverClick -

            case event_BtnRemoverClick:
            {
                //InitEventCode event_BtnRemoverClick
                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_BtnGraficoClick -

            case event_BtnGraficoClick:
            {
                //InitEventCode event_BtnGraficoClick
                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_BtnAdicionarClick -

            case event_BtnAdicionarClick:
            {
                //InitEventCode event_BtnAdicionarClick
                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_BtnBuscarListaClick -

            case event_BtnBuscarListaClick:
            {
                //InitEventCode event_BtnBuscarListaClick
                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_BtnGeraTransClick -

            case event_BtnGeraTransClick:
            {
                //InitEventCode event_BtnGeraTransClick
                //EndEventCode
                return(true);
            }

                #endregion

                #region - event_BtnRankingClick -

            case event_BtnRankingClick:
            {
                //InitEventCode event_BtnRankingClick
                //EndEventCode
                return(true);
            }

                #endregion

            default: break;
            }

            return(false);
        }
Example #19
0
        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);
            }
        }
Example #20
0
    protected void ZedGraphWebPlayerCountStatistic_RenderGraph(ZedGraph.Web.ZedGraphWeb webObject, Graphics g, MasterPane masterPane)
    {
        if (!WebUtil.CheckPrivilege(TheAdminServer.GameServerManager.SecurityObject, OpType.READ, Session))
        {
            return;
        }

        GameServer server = ServerDropDownList.SelectedGameServer;

        //不再只对GameServer进行人数的查询,而是对所有的Server进行查询
        if (server == null || server.Type != GameServer.ServerType.gameserver && server.Type != GameServer.ServerType.gamecenter)
        {
            ZedGraphWebPlayerCount.Visible = false;
            return;
        }

        LordControl.PlayerCountStatisticInfo[] infoArray = server.GetPlugInData(CurrentUser.Id, LordControl.PlugInGuid, LordControl.DataKeyPlayerCountStatistic, DateTime.Now.Subtract(new TimeSpan(1 - _dayIndex, 0, 0, 0)), DateTime.Now.Subtract(new TimeSpan(-_dayIndex, 0, 0, 0))) as LordControl.PlayerCountStatisticInfo[];
        if (infoArray == null)
        {
            ZedGraphWebPlayerCount.Visible = false;
            return;
        }

        double[] maxCountArray     = new double[infoArray.Length];
        double[] minCountArray     = new double[infoArray.Length];
        double[] averageCountArray = new double[infoArray.Length];
        double[] timeArray         = new double[infoArray.Length];

        for (int i = 0; i < infoArray.Length; i++)
        {
            LordControl.PlayerCountStatisticInfo info = infoArray[i];
            maxCountArray[i]     = info.MaxCount;
            minCountArray[i]     = info.MinCount;
            averageCountArray[i] = info.AverageCount;
            timeArray[i]         = new XDate(info.Time);
        }

        GraphPane graphPane = masterPane[0];

        graphPane.Fill = new Fill(WebConfig.GraphPaneBgColor);

        graphPane.Legend.Fill.IsVisible          = false;
        graphPane.Legend.Border.IsVisible        = false;
        graphPane.Legend.FontSpec.Fill.IsVisible = false;

        graphPane.XAxis.Title.Text          = StringDef.Time;
        graphPane.XAxis.MajorGrid.Color     = WebConfig.GraphXAxisGridColor;
        graphPane.XAxis.Type                = AxisType.Date;
        graphPane.XAxis.Scale.FontSpec.Size = 11;

        graphPane.YAxis.Title.Text = StringDef.PlayerCount;
        //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} ]", StringDef.PlayerCount, DateTime.Now.Subtract(new TimeSpan(1 - _dayIndex, 0, 0, 0)), DateTime.Now.Subtract(new TimeSpan(-_dayIndex, 0, 0, 0)));

        graphPane.AddCurve(StringDef.Maximum, timeArray, maxCountArray, Color.Red, SymbolType.Triangle);
        graphPane.AddCurve(StringDef.Minimum, timeArray, minCountArray, Color.Green, SymbolType.TriangleDown);
        graphPane.AddCurve(StringDef.Average, timeArray, averageCountArray, Color.Orange, SymbolType.Diamond);
    }
Example #21
0
        private void generateSimpleGraph()
        {
            DataTable dtGraph;
            int       rndSymb   = 0;
            int       SelectedS = ddlStock.SelectedIndex;

            Cursor = Cursors.WaitCursor;
            try
            {
                //Loading points in a collection//
                PointPairList list = new PointPairList();
                if (gCurve[SelectedS] == null) //Checking if collection already created
                {
                    //Loading Avg. Daily Stock Rates//ddlStock.SelectedIndex
                    dtGraph = pDalGraph.GraphSingle((int)ddlStock.SelectedValue);

                    // Set the titles and axis labels
                    //pgSimple.Title.Text = "DoubleM Simple Graph [ " + ddlStock.Text + " ]";
                    pgSimple.Title.Text       = "";
                    pgSimple.XAxis.Title.Text = "";
                    pgSimple.YAxis.Title.Text = "";
                    theParent.lblDMMsg.Text   = ddlStock.Text + " data loading..";
                    //CommonDoubleM.LogDM("DoubleM Simple Graph [ " + ddlStock.Text + " ]");
                    theParent.pBarDM.Visible = true;
                    theParent.pBarDM.Maximum = dtGraph.Rows.Count;
                    for (int ii = 0; ii < dtGraph.Rows.Count; ii++)
                    {
                        DateTime dt = Convert.ToDateTime(dtGraph.Rows[ii][1].ToString());
                        //CommonDoubleM.LogDM(dtGraph.Rows[ii][1].ToString() + " - " + dtGraph.Rows[ii][0].ToString());
                        double x = new XDate(dt.Year, dt.Month, dt.Day);
                        list.Add(x, Convert.ToDouble(dtGraph.Rows[ii][0].ToString()));
                        Application.DoEvents();
                        theParent.pBarDM.Value = ii;
                        //ii++;
                    }
                    rndSymb = CommonDoubleM.RandomNumber(0, 255);
                    theParent.pBarDM.Visible = false;

                    gCurve[SelectedS]             = pgSimple.AddCurve(ddlStock.Text, list, colSymb[SelectedS % colSymb.Length], SymbolType.Circle);
                    gCurve[SelectedS].Symbol.Size = 3;
                    //gCurve[(int)ddlStock.SelectedValue].Label.FontSpec.Size = 8;

                    // Fill the area under the curve
                    //gCurve[SelectedS].Line.Fill = new Fill(Color.White, Color.LightGray, 45F);

                    // Fill Symbol  opaque by filling them with white
                    gCurve[SelectedS].Symbol.Fill = new Fill(Color.White, colSymb[rndSymb % colSymb.Length], 180F);

                    //Pointing tradings//
                    DataRow[] drTrads = pDalGraph.TradingValue().Select("StockID=" + ddlStock.SelectedValue.ToString());
                    list = new PointPairList();
                    for (int ii = 0; ii < drTrads.Length; ii++)
                    {
                        DateTime dt = Convert.ToDateTime(drTrads[ii][0].ToString());
                        double   x  = new XDate(dt.Year, dt.Month, dt.Day);
                        list.Add(x, Convert.ToDouble(drTrads[ii][3].ToString()), Convert.ToDouble(drTrads[ii][4].ToString()));
                        //Application.DoEvents();
                    }

                    gCurve[SelectedS + ddlStock.Items.Count]                         = pgSimple.AddCurve("", list, Color.Red, SymbolType.Diamond);
                    gCurve[SelectedS + ddlStock.Items.Count].Symbol.Size             = 8;
                    gCurve[SelectedS + ddlStock.Items.Count].Symbol.Fill             = new Fill(Color.Green, Color.Red);
                    gCurve[SelectedS + ddlStock.Items.Count].Symbol.Border.IsVisible = false;
                    gCurve[SelectedS + ddlStock.Items.Count].Symbol.Fill.Type        = FillType.GradientByZ;
                    //gCurve[SelectedS + ddlStock.Items.Count].Symbol.Fill.SecondaryValueGradientColor = Color.Empty;


                    //gCurve[SelectedS].Symbol.Fill.RangeDefault = 0;
                    gCurve[SelectedS + ddlStock.Items.Count].Symbol.Fill.RangeMin = -10;
                    gCurve[SelectedS + ddlStock.Items.Count].Symbol.Fill.RangeMax = 10;
                    gCurve[SelectedS + ddlStock.Items.Count].Line.IsVisible       = false;

                    // Set the XAxis to date type
                    pgSimple.XAxis.Type = AxisType.Date;

                    GraphPaint();
                    // Fill the axis background with a color gradient
                    //pgSimple.Chart.Fill = new Fill(Color.White, Color.FromArgb(220, 220, 255), 270F);

                    // Fill the pane background with a color gradient
                    //pgSimple.Fill = new Fill(Color.Wheat, Color.LightYellow, 45F);
                    zg1.AxisChange();
                    zg1.Refresh();
                }
                else
                {
                    gCurve[ddlStock.SelectedIndex].IsVisible       = true;
                    gCurve[ddlStock.SelectedIndex].Label.IsVisible = true;
                    gCurve[ddlStock.SelectedIndex + ddlStock.Items.Count].IsVisible       = true;
                    gCurve[ddlStock.SelectedIndex + ddlStock.Items.Count].Label.IsVisible = true;
                }
                // Calculate the Axis Scale Ranges
                theParent.lblDMMsg.Text = ddlStock.Text + " data loaded.";
                zg1.ZoomOutAll(pgSimple);
                zg1.AxisChange();
            }
            catch (Exception ex)
            {
                theParent.lblDMMsg.Text = ex.Message;
                CommonDoubleM.LogDM(ex.Message);
            }
            Cursor = Cursors.Default;
        }
Example #22
0
    protected void ZedGraphWebPlayerCount_RenderGraph(ZedGraph.Web.ZedGraphWeb webObject, Graphics g, MasterPane masterPane)
    {
        if (!WebUtil.CheckPrivilege(TheAdminServer.GameServerManager.SecurityObject, OpType.READ, Session))
        {
            return;
        }

        GameServer server = ServerDropDownList.SelectedGameServer;

        //不再只对GameServer进行人数的查询,而是对所有的Server进行查询
        if (server == null || server.Type != GameServer.ServerType.gameserver && server.Type != GameServer.ServerType.gamecenter)
        {
            ZedGraphWebPlayerCount.Visible = false;
            return;
        }


        Queue <LordControl.PlayerCountInfo> playerCountInfoQueue = server.GetPlugInData(CurrentUser.Id, LordControl.PlugInGuid, LordControl.DataKeyPlayerCountQueue) as Queue <LordControl.PlayerCountInfo>;

        if (playerCountInfoQueue == null)
        {
            ZedGraphWebPlayerCount.Visible = false;
            return;
        }

        LordControl.PlayerCountInfo[] infoArray = playerCountInfoQueue.ToArray();
        double[] countArray = new double[infoArray.Length];
        double[] timeArray  = new double[infoArray.Length];

        for (int i = 0; i < infoArray.Length; i++)
        {
            LordControl.PlayerCountInfo info = infoArray[i];
            countArray[i] = info.Count;
            timeArray[i]  = new XDate(info.Time);
        }

        GraphPane graphPane = masterPane[0];

        graphPane.Fill = new Fill(WebConfig.GraphPaneBgColor);

        graphPane.Legend.Fill.IsVisible          = false;
        graphPane.Legend.Border.IsVisible        = false;
        graphPane.Legend.FontSpec.Fill.IsVisible = false;

        graphPane.XAxis.Title.Text          = StringDef.Time;
        graphPane.XAxis.MajorGrid.Color     = WebConfig.GraphXAxisGridColor;
        graphPane.XAxis.Type                = AxisType.Date;
        graphPane.XAxis.Scale.FontSpec.Size = 11;

        graphPane.YAxis.Title.Text = StringDef.PlayerCount;
        //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}", StringDef.PlayerCount, StringDef.Last1Hour);

        graphPane.AddCurve(StringDef.PlayerCount, timeArray, countArray, Color.Red, SymbolType.Diamond);
    }
Example #23
0
        /// <summary>
        /// Called when button to split the data is pressed
        /// checks for the number of chunbks wanted and if it is a valid integer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chunkButton_Click(object sender, EventArgs e)
        {
            int numberChunks = 0;

            try
            {
                numberChunks = Convert.ToInt32(chunkNum.Text);
                //if it works then we can add data on here
                //we need to pass back where the markers are needed
                //first we need to split the data up into a number chunks
            }
            catch (Exception e1)
            {
                MessageBox.Show("Error", "Data entered is not in correct format", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
            }


            int chunkSize = data[0].Count / numberChunks;
            //we can then go through and ge thte start and end points or create markers
            Marker m     = new Marker();
            XDate  start = new XDate(2018, 10, 10, 0, 0, 0);

            m.Min = start;
            bool startBool = false;
            int  x         = 0;

            for (int i = 0; i < data[0].Count; i++)
            {
                if (startBool)
                {
                    m.GenColour();
                    markers.Add(m);
                    m = new Marker();
                    XDate temp = new XDate(2018, 10, 10, 0, 0, 0);
                    temp.AddSeconds(i * interval);
                    m.Min     = temp;
                    startBool = false;
                }
                if (x == chunkSize - 1)
                {
                    if (i == numberChunks - 1)
                    {
                        //means final chunk add rest if odd number
                        startBool = true;
                        XDate temp = new XDate(2018, 10, 10, 0, 0, 0);
                        temp.AddSeconds(data[0].Count / interval);
                        m.Max = temp;
                        x     = 0;
                    }
                    else
                    {
                        startBool = true;
                        XDate temp = new XDate(2018, 10, 10, 0, 0, 0);
                        temp.AddSeconds(i * interval);
                        m.Max = temp;
                        x     = 0;
                    }
                }



                x += 1;
            }



            //we need to pass the markers back and then generate the summaries
            //we need a control type thing to edit........



            Console.WriteLine("We have " + markers.Count + " chunks");

            //we then need the markers to be drawn

            dv.AddMarkers(markers);
            dv.AddGraphs();

            this.Close();
        }
Example #24
0
        private void dataGridView1_SelectionChanged(object sender, EventArgs xx)
        {
            if (dataGridView1.SelectedRows.Count <= 0)
            {
                return;
            }
            var    row      = dataGridView1.SelectedRows[0];
            string pairName = (string)row.Cells[0].Value;
            var    pair     = _pairs.FirstOrDefault(e => e.Symbol.NiceName == pairName);

            if (pair != null)
            {
                var candleStickPoints = new StockPointList();
                var candles           = pair.Symbol.Candles;
                var lastCandle        = candles.Count - 1;

                for (int i = lastCandle; i >= 0; i--)
                {
                    var    candle = candles[i];
                    double x      = new XDate(candles[lastCandle].OpenTime);

                    StockPt pt = new StockPt(new XDate(candle.OpenTime),
                                             (double)candle.High,
                                             (double)candle.Low,
                                             (double)candle.Open,
                                             (double)candle.Close,
                                             100000);
                    candleStickPoints.Add(pt);
                }

                var masterPane = zedGraphControl1.MasterPane;
                // while (masterPane.PaneList.Count < 2) masterPane.PaneList.Add(new GraphPane());
                var mainPane = masterPane.PaneList[0];
                // var mbfxPane = masterPane.PaneList[1];
                //mbfxPane.

                mainPane.Title.Text = pair.Symbol.NiceName + " " + pair.Symbol.NiceTimeFrame;
                mainPane.CurveList.Clear();
                var candleSticks = mainPane.AddJapaneseCandleStick("candles", candleStickPoints);
                candleSticks.Stick.FallingFill = new Fill(Color.Red);
                candleSticks.Stick.RisingFill  = new Fill(Color.Blue);

                mainPane.XAxis.Type = AxisType.DateAsOrdinal;

                var trendLine = new TrendLine();
                trendLine.Refresh(pair.Symbol);

                var zigZag = new ZigZag();
                zigZag.Refresh(pair.Symbol);

                var ma15Points       = new PointPairList();
                var trendPoints      = new PointPairList();
                var zigzagBuyPoints  = new PointPairList();
                var zigzagSellPoints = new PointPairList();
                for (int i = lastCandle; i >= 0; i--)
                {
                    var candle = candles[i];
                    ma15Points.Add(new XDate(candle.OpenTime),
                                   (double)MovingAverage.Get(pair.Symbol, i, 15, MaMethod.Sma, AppliedPrice.Close));

                    trendPoints.Add(new XDate(candle.OpenTime),
                                    (double)trendLine.GetValue(i)
                                    );

                    var arrow = zigZag.GetArrow(i);
                    if (arrow == ArrowType.Buy)
                    {
                        zigzagBuyPoints.Add(new XDate(candle.OpenTime), (double)candle.Low);
                    }
                    else
                    {
                        zigzagBuyPoints.Add(new XDate(candle.OpenTime), (double)0);
                    }

                    if (arrow == ArrowType.Sell)
                    {
                        zigzagSellPoints.Add(new XDate(candle.OpenTime), (double)candle.High);
                    }
                    else
                    {
                        zigzagSellPoints.Add(new XDate(candle.OpenTime), (double)0);
                    }
                }
                var ma15Curve  = mainPane.AddCurve("MA15", ma15Points, Color.DarkGray, SymbolType.None);
                var trendCurve = mainPane.AddCurve("Trend", trendPoints, Color.Green, SymbolType.None);

                var zigZagCurveBuy  = mainPane.AddCurve("", zigzagBuyPoints, Color.Green, SymbolType.Triangle);
                var zigZagCurveSell = mainPane.AddCurve("", zigzagSellPoints, Color.Red, SymbolType.TriangleDown);
                zigZagCurveBuy.Line.StepType  = StepType.ForwardSegment;
                zigZagCurveSell.Line.StepType = StepType.ForwardSegment;

                // pretty it up a little
                mainPane.Chart.Fill = new Fill(Color.LightGray, Color.LightGray, 45.0f);
                mainPane.Fill       = new Fill(Color.LightGray, Color.LightGray, 45.0f);

                // Tell ZedGraph to calculate the axis ranges
                zedGraphControl1.AxisChange();
                zedGraphControl1.Invalidate();
                if (_currentPair != pairName)
                {
                    _currentPair = pairName;
                    zedGraphControl1.RestoreScale(mainPane);
                }
            }
        }
Example #25
0
        /// <summary>
        /// Internal routine to determine the ordinals of the first and last major axis label.
        /// </summary>
        /// <returns>
        /// This is the total number of major tics for this axis.
        /// </returns>
        internal override int CalcNumTics()
        {
            int nTics;

            int year1, year2, month1, month2, day1, day2, hour1, hour2, minute1, minute2;
            int second1, second2, millisecond1, millisecond2;

            XDate.XLDateToCalendarDate(
                _min,
                out year1,
                out month1,
                out day1,
                out hour1,
                out minute1,
                out second1,
                out millisecond1);
            XDate.XLDateToCalendarDate(
                _max,
                out year2,
                out month2,
                out day2,
                out hour2,
                out minute2,
                out second2,
                out millisecond2);

            switch (_majorUnit)
            {
            default:
                nTics = (int)((year2 - year1) / _majorStep + 1.001);
                break;

            case DateUnit.Month:
                nTics = (int)((month2 - month1 + 12.0 * (year2 - year1)) / _majorStep + 1.001);
                break;

            case DateUnit.Day:
                nTics = (int)((_max - _min) / _majorStep + 1.001);
                break;

            case DateUnit.Hour:
                nTics = (int)((_max - _min) / (_majorStep / XDate.HoursPerDay) + 1.001);
                break;

            case DateUnit.Minute:
                nTics = (int)((_max - _min) / (_majorStep / XDate.MinutesPerDay) + 1.001);
                break;

            case DateUnit.Second:
                nTics = (int)((_max - _min) / (_majorStep / XDate.SecondsPerDay) + 1.001);
                break;

            case DateUnit.Millisecond:
                nTics = (int)((_max - _min) / (_majorStep / XDate.MillisecondsPerDay) + 1.001);
                break;
            }

            if (nTics < 1)
            {
                nTics = 1;
            }
            else if (nTics > 1000)
            {
                nTics = 1000;
            }

            return(nTics);
        }
Example #26
0
 /// <summary>
 /// 获取刻度值
 /// </summary>
 /// <param name="index"></param>
 /// <param name="dVal"></param>
 /// <returns></returns>
 private string MakeLabel(int index, double dVal)
 {
     return(XDate.ToString(dVal, _format));
 }
Example #27
0
        private void drawtempline(string name, int ID)
        {
            string    sql = "select dt,GT1,BT1,GT2,BT2,GTB2,OT,WI1,OD from tblGRData where DeviceID =" + ID + " and dt>='" + this.dateTimePicker4.Value.ToString() + "' and dt<'" + dateTimePicker3.Value.ToString() + "' order by dt ";
            DataTable dt  = Tool.DB.getDt(sql);

            PointPairList list1 = new PointPairList();
            PointPairList list2 = new PointPairList();
            PointPairList list3 = new PointPairList();
            PointPairList list4 = new PointPairList();
            PointPairList list5 = new PointPairList();
            PointPairList list6 = new PointPairList();
            PointPairList list7 = new PointPairList();
            PointPairList list8 = new PointPairList();

            for (int j = 0; j < dt.Rows.Count; j++)
            {
                DateTime time = (DateTime)dt.Rows[j][0];
                double   x    = new XDate(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second);
                double   y    = Convert.ToDouble(dt.Rows[j][1]);
                list1.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][2]);
                list2.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][3]);
                list3.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][4]);
                list4.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][5]);
                list5.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][6]);
                list6.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][7]);
                list7.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][8]);
                list8.Add(x, y);
            }

            GraphPane myPane = zedGraphControl3.GraphPane;

            myPane.CurveList.Clear();
            this.zedGraphControl3.ZoomOutAll(myPane);
            myPane.Title.Text                = name + " " + dateTimePicker4.Value.ToString() + " 至 " + dateTimePicker3.Value.ToString() + " 温度曲线";
            myPane.XAxis.Title.Text          = "时间(h)";
            myPane.YAxis.Title.Text          = "温度(℃)";
            myPane.XAxis.Type                = AxisType.Date;
            myPane.XAxis.MajorGrid.IsVisible = true;  //珊格子
            myPane.YAxis.MajorGrid.IsVisible = true;
            myPane.XAxis.Scale.Format        = "MM/dd HH:mm";

            LineItem myCurve1 = null;

            if (checkBox2.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("一次供温℃", list1, panel3.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox10.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("一次回温℃", list2, panel20.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox12.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("二次供温℃", list3, panel24.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox11.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("二次回温℃", list4, panel26.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox9.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("供温基准℃", list5, panel22.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox1.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("室外温度℃", list6, panel18.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox14.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("一次流量m3/h", list7, panel29.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox18.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("阀位反馈%", list8, panel37.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (myCurve1 == null)
            {
                MessageBox.Show("请选择某条曲线!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                return;
            }

            zedGraphControl3.IsShowPointValues = true;
            zedGraphControl3.PointValueEvent  += new ZedGraphControl.PointValueHandler(MyPointValueHandler);

            zedGraphControl3.AxisChange();
            zedGraphControl3.Invalidate();
        }
Example #28
0
 public double LocalTransform(DateTime time, out bool IsOverMin, out bool IsOverMax)
 {
     return(LocalTransform(XDate.DateTimeToXLDate(time), out IsOverMin, out IsOverMax));
 }
Example #29
0
        private void drawpressline(string name, int ID)
        {
            string    sql = "select dt,GP1,BP1 ,GP2,BP2,PA2,BPB2 from tblGRData where DeviceID =" + ID + " and dt>='" + this.dateTimePicker2.Value.ToString() + "' and dt<'" + dateTimePicker1.Value.ToString() + "' order by dt ";
            DataTable dt  = Tool.DB.getDt(sql);

            PointPairList list1 = new PointPairList();
            PointPairList list2 = new PointPairList();
            PointPairList list3 = new PointPairList();
            PointPairList list4 = new PointPairList();
            PointPairList list5 = new PointPairList();
            PointPairList list6 = new PointPairList();

            for (int j = 0; j < dt.Rows.Count; j++)
            {
                DateTime time = (DateTime)dt.Rows[j][0];
                double   x    = new XDate(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second);
                double   y    = Convert.ToDouble(dt.Rows[j][1]);
                list1.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][2]);
                list2.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][3]);
                list3.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][4]);
                list4.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][5]);
                list5.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][6]);
                list6.Add(x, y);
            }

            GraphPane myPane = zedGraphControl2.GraphPane;

            myPane.CurveList.Clear();
            this.zedGraphControl2.ZoomOutAll(myPane);
            myPane.Title.Text                = name + " " + dateTimePicker2.Value.ToString() + " 至 " + dateTimePicker1.Value.ToString() + " 压力曲线";
            myPane.XAxis.Title.Text          = "时间(h)";
            myPane.YAxis.Title.Text          = "压力(MPa)";
            myPane.XAxis.Type                = AxisType.Date;
            myPane.XAxis.MajorGrid.IsVisible = true;  //珊格子
            myPane.YAxis.MajorGrid.IsVisible = true;
            myPane.YAxis.Scale.Max           = 1;
            myPane.YAxis.Scale.Min           = 0;
            myPane.YAxis.Scale.MajorStep     = 0.1;
            myPane.XAxis.Scale.Format        = "MM/dd HH:mm";

            LineItem myCurve1 = null;

            if (checkBox3.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("一次供压MPa", list1, panel7.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox4.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("一次回压MPa", list2, panel9.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox5.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("二供次压MPa", list3, panel11.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox6.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("二次回压MPa", list4, panel13.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox7.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("压差设定MPa", list5, panel15.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox8.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("补水设定MPa", list6, panel17.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (myCurve1 == null)
            {
                MessageBox.Show("请选择某条曲线!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                return;
            }

            zedGraphControl2.IsShowPointValues = true;
            zedGraphControl2.PointValueEvent  += new ZedGraphControl.PointValueHandler(MyPointValueHandler);

            zedGraphControl2.AxisChange();
            zedGraphControl2.Invalidate();
        }
Example #30
0
 public TimeSpan GetMoveTs(double pix)
 {
     return(XDate.XLDateToDateTime((_max - _min) / (_maxPix - _minPix) * pix + _min) - _minTime);
 }
Example #31
0
        /// <summary>
        /// Determine the value for the first major tic.
        /// </summary>
        /// <remarks>
        /// This is done by finding the first possible value that is an integral multiple of
        /// the step size, taking into account the date/time units if appropriate.
        /// This method properly accounts for <see cref="Scale.IsLog"/>, <see cref="Scale.IsText"/>,
        /// and other axis format settings.
        /// </remarks>
        /// <returns>
        /// First major tic value (floating point double).
        /// </returns>
        override internal double CalcBaseTic()
        {
            if (_baseTic != PointPair.Missing)
            {
                return(_baseTic);
            }
            else
            {
                int year, month, day, hour, minute, second, millisecond;
                XDate.XLDateToCalendarDate(_min, out year, out month, out day, out hour, out minute,
                                           out second, out millisecond);
                switch (_majorUnit)
                {
                case DateUnit.Year:
                default:
                    month = 1; day = 1; hour = 0; minute = 0; second = 0; millisecond = 0;
                    break;

                case DateUnit.Month:
                    day = 1; hour = 0; minute = 0; second = 0; millisecond = 0;
                    break;

                case DateUnit.Day:
                    hour = 0; minute = 0; second = 0; millisecond = 0;
                    break;

                case DateUnit.Hour:
                    minute = 0; second = 0; millisecond = 0;
                    break;

                case DateUnit.Minute:
                    second = 0; millisecond = 0;
                    break;

                case DateUnit.Second:
                    millisecond = 0;
                    break;

                case DateUnit.Millisecond:
                    break;
                }

                double xlDate = XDate.CalendarDateToXLDate(year, month, day, hour, minute, second, millisecond);
                if (xlDate < _min)
                {
                    switch (_majorUnit)
                    {
                    case DateUnit.Year:
                    default:
                        year++;
                        break;

                    case DateUnit.Month:
                        month++;
                        break;

                    case DateUnit.Day:
                        day++;
                        break;

                    case DateUnit.Hour:
                        hour++;
                        break;

                    case DateUnit.Minute:
                        minute++;
                        break;

                    case DateUnit.Second:
                        second++;
                        break;

                    case DateUnit.Millisecond:
                        millisecond++;
                        break;
                    }

                    xlDate = XDate.CalendarDateToXLDate(year, month, day, hour, minute, second, millisecond);
                }

                return(xlDate);
            }
        }
Example #32
0
 public DateTime GetTime(double pix)
 {
     return(XDate.XLDateToDateTime((_max - _min) / (_maxPix - _minPix) * (pix - _minPix) + _min));
 }
Example #33
0
        void UpdatePointList()
        {
            x1 = DateTime.Now;
            x0 = x1.AddSeconds(-DisplayTimeSpan);

            var x = x0;
            int i;

            for (i = 1; i < DisplayTimeSpan / timeGap; i++)
            {
                TopTemp[i - 1] = TopTemp[i];
                BMTTemp[i - 1] = BMTTemp[i];
                TopHR[i - 1]   = TopHR[i];
                BMTHR[i - 1]   = BMTHR[i];
                date[i - 1]    = date[i];
            }
            TopTemp[i - 1] = double.Parse(myOPC.Items[PLCTagName.TopTemp.ToString()].Value.ToString());
            BMTTemp[i - 1] = double.Parse(myOPC.Items[PLCTagName.BTMTemp.ToString()].Value.ToString());
            TopHR[i - 1]   = double.Parse(myOPC.Items[PLCTagName.TopHR.ToString()].Value.ToString());
            BMTHR[i - 1]   = double.Parse(myOPC.Items[PLCTagName.BTMHR.ToString()].Value.ToString());
            date[i - 1]    = new XDate(x1).XLDate;

            for (var j = 0; j < DisplayTimeSpan / timeGap; j++)
            {
                TempAVG[j] = (TopTemp[j] + BMTTemp[j]) / 2.0;
                HRAVG[j]   = (TopHR[j] + BMTHR[j]) / 2.0;
            }

            var r = new RealData();

            r.T1   = (float)TopTemp[i - 1];
            r.T2   = (float)BMTTemp[i - 1];
            r.H1   = (float)TopHR[i - 1];
            r.H2   = (float)BMTHR[i - 1];
            r.Time = x1;
            rdo.Add(r);

            LTopTemp = new PointPairList(date, TopTemp);
            LBMTTemp = new PointPairList(date, BMTTemp);
            LTopHR   = new PointPairList(date, TopHR);
            LBMTHR   = new PointPairList(date, BMTHR);



            var g1 = GC.MasterPane[0];
            var g2 = GC.MasterPane[1];

            g1.CurveList.Clear();
            g2.CurveList.Clear();


            CurveItem c = g1.AddCurve("温度上", LTopTemp, Color.Blue, SymbolType.None);

            c = g1.AddCurve("温度下", LBMTTemp, Color.YellowGreen, SymbolType.None);
            c = g1.AddCurve("温度", new PointPairList(date, TempAVG), Color.DarkRed, SymbolType.None);


            c = g2.AddCurve("湿度上", LTopHR, Color.MediumVioletRed, SymbolType.None);
            //  c.IsY2Axis = true;
            c = g2.AddCurve("湿度下", LBMTHR, Color.BlueViolet, SymbolType.None);

            c = g2.AddCurve("湿度", new PointPairList(date, HRAVG), Color.Blue, SymbolType.None);
            //  c.IsY2Axis = true;
            g1.XAxis.Scale.Max = date[i - 1];
            g1.XAxis.Scale.Min = date[minIndex];
            g2.XAxis.Scale.Max = date[i - 1];
            g2.XAxis.Scale.Min = date[minIndex];

            g1.AxisChange();
            g2.AxisChange();

            SetScalFormat(g1.XAxis, g1);
            SetScalFormat(g2.XAxis, g2);

            if (checkBox1.Checked)
            {
                GC.MasterPane[0].CurveList["温度"].IsVisible = true;
                GC.MasterPane[1].CurveList["湿度"].IsVisible = true;
            }
            else
            {
                GC.MasterPane[0].CurveList["温度"].IsVisible = false;
                GC.MasterPane[1].CurveList["湿度"].IsVisible = false;
            }

            GC.Refresh();
        }
Example #34
0
        void BtnCpuClick(object sender, EventArgs e)
        {
            PointPairList list  = new PointPairList();
            PointPairList list2 = new PointPairList();

            if (File.Exists(var_data.pathDir + "\\cpu_stats.log"))
            {
                long lines = 0;

                {
                    StreamReader st = new StreamReader(var_data.pathDir + "\\cpu_stats.log");

                    while (!st.EndOfStream)
                    {
                        st.ReadLine();
                        ++lines;
                    }

                    st.Close();
                }

                {
                    StreamReader st = new StreamReader(var_data.pathDir + "\\cpu_stats.log");

                    long start = lines - 60;

                    while (start > 0)
                    {
                        st.ReadLine();
                        --start;
                    }

                    while (!st.EndOfStream)
                    {
                        string line = st.ReadLine();

                        int start_c = 0;
                        int len_c   = 0;

                        for (int t = 0; t < line.Length; ++t)
                        {
                            if (line[t] == '(')
                            {
                                start_c = t + 1;
                            }
                            else if (line[t] == '%')
                            {
                                len_c = t - start_c;
                                break;
                            }
                        }

                        string idle = line.Substring(start_c, len_c);

                        int par = 0;

                        for (int t = 40; t < line.Length; ++t)
                        {
                            if (line[t] == '(')
                            {
                                ++par;

                                if (par == 2)
                                {
                                    start_c = t + 1;
                                }
                            }
                            else if (line[t] == '%')
                            {
                                len_c = t - start_c;
                                break;
                            }
                        }

                        string database = line.Substring(start_c, len_c);

                        XDate x = new XDate(Convert.ToInt32(line.Substring(0, 4)),                                 // ano
                                            Convert.ToInt32(line.Substring(5, 2)),                                 // mes
                                            Convert.ToInt32(line.Substring(8, 2)),                                 // dia
                                            Convert.ToInt32(line.Substring(11, 2)),                                // hora
                                            Convert.ToInt32(line.Substring(14, 2)), 0, 0);                         // minuto


                        list.Add((double)x, Convert.ToDouble(database));
                        list2.Add((double)x, Convert.ToDouble(idle));
                    }

                    st.Close();
                }
            }

            CreateGraph2(zed, ref list, ref list2, "CPU usage from server", "Time of day", "Percentage %", "database", "idle");
        }
Example #35
0
        public void WriteDate(XDate date)
        {
            writer.Write('"');

            if (date.ToDateTime().Year == 1)
            {
                WriteNull();
            }
            else
            {
                writer.Write(date.ToIsoString());
            }

            writer.Write('"');
        }
Example #36
0
 public string Format(XDate date) => date.ToIsoString();