Changeset - 2f841e844536
[Not reviewed]
default
0 2 0
mkanning@CL-ENS241-10.cedarville.edu - 13 years ago 2013-02-14 15:21:33
mkanning@CL-ENS241-10.cedarville.edu
fixed the problem of two forms being created. still need to fix the addToChart()
and addMarker()
2 files changed with 7 insertions and 7 deletions:
0 comments (0 inline, 0 general)
Demo.WindowsForms/Forms/MainForm.cs
Show inline comments
 
@@ -1028,1794 +1028,1794 @@ namespace Demo.WindowsForms
 
        //        //               CountryStatusView.Clear();
 
        //        //            }
 
 
        //        //            foreach(var c in CountryStatus)
 
        //        //            {
 
        //        //               IpStatus s = new IpStatus();
 
        //        //               {
 
        //        //                  s.CountryName = c.Key;
 
        //        //                  s.ConnectionsCount = c.Value;
 
        //        //               }
 
 
        //        //               if(ComparerIpStatus.SortOnlyCountryName)
 
        //        //               {
 
        //        //                  int idx = CountryStatusView.FindIndex(p => p.CountryName == c.Key);
 
        //        //                  if(idx >= 0)
 
        //        //                  {
 
        //        //                     CountryStatusView[idx] = s;
 
        //        //                  }
 
        //        //               }
 
        //        //               else
 
        //        //               {
 
        //        //                  CountryStatusView.Add(s);
 
        //        //               }
 
        //        //            }
 
 
        //        //            CountryStatusView.Sort(ComparerIpStatus);
 
 
        //        //            GridConnections.RowCount = CountryStatusView.Count;
 
        //        //            GridConnections.Refresh();
 
 
        //        //            if(empty)
 
        //        //            {
 
        //        //               GridConnections.ClearSelection();
 
        //        //            }
 
        //        //         }
 
        //        //      }
 
 
        //        //      MainMap.Refresh();
 
        //        //   }
 
        //        //   catch(Exception ex)
 
        //        //   {
 
        //        //      Debug.WriteLine(ex.ToString());
 
        //        //   }
 
        //        //}
 
 
        //        //void GridConnections_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
 
        //        //{
 
        //        //   if(e.RowIndex >= CountryStatusView.Count)
 
        //        //      return;
 
 
        //        //   IpStatus val = CountryStatusView[e.RowIndex];
 
 
        //        //   switch(GridConnections.Columns[e.ColumnIndex].Name)
 
        //        //   {
 
        //        //      case "CountryName":
 
        //        //      e.Value = val.CountryName;
 
        //        //      break;
 
 
        //        //      case "ConnectionsCount":
 
        //        //      e.Value = val.ConnectionsCount;
 
        //        //      break;
 
        //        //   }
 
        //        //}
 
 
        //        Color GetRandomColor()
 
        //        {
 
        //            byte r = Convert.ToByte(rnd.Next(0, 111));
 
        //            byte g = Convert.ToByte(rnd.Next(0, 111));
 
        //            byte b = Convert.ToByte(rnd.Next(0, 111));
 
 
        //            return Color.FromArgb(144, r, g, b);
 
        //        }
 
 
        //        void UpdateMarkerTcpIpToolTip(GMapMarker marker, IpInfo tcp, string info)
 
        //        {
 
        //            marker.ToolTipText = tcp.State.ToString();
 
 
        //            if (!string.IsNullOrEmpty(tcp.ProcessName))
 
        //            {
 
        //                marker.ToolTipText += " by " + tcp.ProcessName;
 
        //            }
 
 
        //            if (!string.IsNullOrEmpty(tcp.CountryName))
 
        //            {
 
        //                marker.ToolTipText += "\n" + tcp.CountryName;
 
        //            }
 
 
        //            if (!string.IsNullOrEmpty(tcp.City))
 
        //            {
 
        //                marker.ToolTipText += ", " + tcp.City;
 
        //            }
 
        //            else
 
        //            {
 
        //                if (!string.IsNullOrEmpty(tcp.RegionName))
 
        //                {
 
        //                    marker.ToolTipText += ", " + tcp.RegionName;
 
        //                }
 
        //            }
 
 
        //            marker.ToolTipText += "\n" + tcp.Ip + ":" + tcp.Port + "\n" + info;
 
        //        }
 
 
        //        List<IpInfo> GetIpHostInfo(string iplist)
 
        //        {
 
        //            List<IpInfo> ret = new List<IpInfo>();
 
        //            bool retry = false;
 
 
        //            string iplistNew = string.Empty;
 
 
        //            string[] ips = iplist.Split(',');
 
        //            foreach (var ip in ips)
 
        //            {
 
        //                IpInfo val = IpCache.GetDataFromCache(ip);
 
        //                if (val != null)
 
        //                {
 
        //                    ret.Add(val);
 
        //                }
 
        //                else
 
        //                {
 
        //                    if (iplistNew.Length > 0)
 
        //                    {
 
        //                        iplistNew += ",";
 
        //                    }
 
        //                    iplistNew += ip;
 
        //                }
 
        //            }
 
 
        //            if (!string.IsNullOrEmpty(iplistNew))
 
        //            {
 
        //                Debug.WriteLine("GetIpHostInfo: " + iplist);
 
 
        //                string reqUrl = string.Format("http://api.ipinfodb.com/v2/ip_query.php?key=fbea1992ab11f7125064590a417a8461ccaf06728798c718dbd2809b31a7a5e0&ip={0}&timezone=false", iplistNew);
 
 
        //                while (true)
 
        //                {
 
        //                    ret.Clear();
 
        //                    try
 
        //                    {
 
        //                        HttpWebRequest httpReq = HttpWebRequest.Create(reqUrl) as HttpWebRequest;
 
        //                        {
 
        //                            string result = string.Empty;
 
        //                            using (HttpWebResponse response = httpReq.GetResponse() as HttpWebResponse)
 
        //                            {
 
        //                                using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
 
        //                                {
 
        //                                    result = reader.ReadToEnd();
 
        //                                }
 
        //                                response.Close();
 
        //                            }
 
 
        //                            XmlDocument x = new XmlDocument();
 
        //                            x.LoadXml(result);
 
 
        //                            XmlNodeList nodes = x.SelectNodes("/Response");
 
        //                            foreach (XmlNode node in nodes)
 
        //                            {
 
        //                                string Ip = node.SelectSingleNode("Ip").InnerText;
 
 
        //                                IpInfo info = new IpInfo();
 
        //                                {
 
        //                                    info.Ip = Ip;
 
        //                                    info.CountryName = node.SelectSingleNode("CountryName").InnerText;
 
        //                                    info.RegionName = node.SelectSingleNode("RegionName").InnerText;
 
        //                                    info.City = node.SelectSingleNode("City").InnerText;
 
        //                                    info.Latitude = double.Parse(node.SelectSingleNode("Latitude").InnerText, CultureInfo.InvariantCulture);
 
        //                                    info.Longitude = double.Parse(node.SelectSingleNode("Longitude").InnerText, CultureInfo.InvariantCulture);
 
        //                                    info.CacheTime = DateTime.Now;
 
 
        //                                    ret.Add(info);
 
        //                                }
 
 
        //                                IpCache.PutDataToCache(Ip, info);
 
        //                            }
 
        //                        }
 
 
        //                        break;
 
        //                    }
 
        //                    catch (Exception ex)
 
        //                    {
 
        //                        if (retry) // fail in retry too, full stop ;}
 
        //                        {
 
        //                            break;
 
        //                        }
 
        //                        retry = true;
 
        //                        reqUrl = string.Format("http://backup.ipinfodb.com/v2/ip_query.php?key=fbea1992ab11f7125064590a417a8461ccaf06728798c718dbd2809b31a7a5e0&ip={0}&timezone=false", iplist);
 
        //                        Debug.WriteLine("GetIpHostInfo: " + ex.Message + ", retry on backup server...");
 
        //                    }
 
        //                }
 
        //            }
 
        //            return ret;
 
        //        }
 
 
        #endregion
 
 
        #region -- some functions --
 
 
        //void RegeneratePolygon()
 
        //{
 
        //    List<PointLatLng> polygonPoints = new List<PointLatLng>();
 
 
        //    foreach (GMapMarker m in objects.Markers)
 
        //    {
 
        //        if (m is GMapMarkerRect)
 
        //        {
 
        //            m.Tag = polygonPoints.Count;
 
        //            polygonPoints.Add(m.Position);
 
        //        }
 
        //    }
 
 
        //    if (polygon == null)
 
        //    {
 
        //        polygon = new GMapPolygon(polygonPoints, "polygon test");
 
        //        polygon.IsHitTestVisible = true;
 
        //        polygons.Polygons.Add(polygon);
 
        //    }
 
        //    else
 
        //    {
 
        //        polygon.Points.Clear();
 
        //        polygon.Points.AddRange(polygonPoints);
 
 
        //        if (polygons.Polygons.Count == 0)
 
        //        {
 
        //            polygons.Polygons.Add(polygon);
 
        //        }
 
        //        else
 
        //        {
 
        //            MainMap.UpdatePolygonLocalPosition(polygon);
 
        //        }
 
        //    }
 
        //}
 
 
        // load mobile gps log
 
        void AddGpsMobileLogRoutes(string file)
 
        {
 
            try
 
            {
 
                DateTime? date = null;
 
                DateTime? dateEnd = null;
 
 
                if (MobileLogFrom.Checked)
 
                {
 
                    date = MobileLogFrom.Value.ToUniversalTime();
 
                }
 
 
                if (MobileLogTo.Checked)
 
                {
 
                    dateEnd = MobileLogTo.Value.ToUniversalTime();
 
                }
 
 
                var log = Stuff.GetRoutesFromMobileLog(file, date, dateEnd, 3.3);
 
 
                if (routes != null)
 
                {
 
                    List<PointLatLng> track = new List<PointLatLng>();
 
 
                    var sessions = new List<List<GpsLog>>(log);
 
 
                    PointLatLng lastPoint = PointLatLng.Empty;
 
 
                    foreach (var session in sessions)
 
                    {
 
                        // connect to last session with direct line
 
                        if (!lastPoint.IsEmpty && session.Count > 0)
 
                        {
 
                            track.Clear();
 
                            track.Add(lastPoint);
 
                            track.Add(session[0].Position);
 
 
                            GMapRoute grl = new GMapRoute(track, "");
 
                            grl.Stroke.Color = Color.Red;
 
                            grl.Stroke.Width = 2.0f;
 
                            routes.Routes.Add(grl);
 
                        }
 
 
                        track.Clear();
 
 
                        foreach (var point in session)
 
                        {
 
                            track.Add(point.Position);
 
                        }
 
 
                        if (track.Count > 0)
 
                        {
 
                            lastPoint = track[track.Count - 1];
 
                        }
 
                        else
 
                        {
 
                            lastPoint = PointLatLng.Empty;
 
                        }
 
 
                        GMapRoute gr = new GMapRoute(track, "");
 
                        routes.Routes.Add(gr);
 
                    }
 
 
                    sessions.Clear();
 
                    sessions = null;
 
 
                    track.Clear();
 
                    track = null;
 
                }
 
            }
 
            catch (Exception ex)
 
            {
 
                Debug.WriteLine("AddGpsMobileLogRoutes: " + ex.ToString());
 
            }
 
        }
 
 
        /// <summary>
 
        /// adds marker using geocoder
 
        /// </summary>
 
        /// <param name="place"></param>
 
        void AddLocationLithuania(string place)
 
        {
 
            GeoCoderStatusCode status = GeoCoderStatusCode.Unknow;
 
            PointLatLng? pos = GMapProviders.GoogleMap.GetPoint("Lithuania, " + place, out status);
 
            if (pos != null && status == GeoCoderStatusCode.G_GEO_SUCCESS)
 
            {
 
                GMarkerGoogle m = new GMarkerGoogle(pos.Value, GMarkerGoogleType.green);
 
                m.ToolTip = new GMapRoundedToolTip(m);
 
 
                GMapMarkerRect mBorders = new GMapMarkerRect(pos.Value);
 
                {
 
                    mBorders.InnerMarker = m;
 
                    mBorders.ToolTipText = place;
 
                    mBorders.ToolTipMode = MarkerTooltipMode.Always;
 
                }
 
 
                objects.Markers.Add(m);
 
                objects.Markers.Add(mBorders);
 
            }
 
        }
 
 
        #endregion
 
 
        #region -- map events --
 
 
        void OnTileCacheComplete()
 
        {
 
            Debug.WriteLine("OnTileCacheComplete");
 
            long size = 0;
 
            int db = 0;
 
            try
 
            {
 
                DirectoryInfo di = new DirectoryInfo(MainMap.CacheLocation);
 
                var dbs = di.GetFiles("*.gmdb", SearchOption.AllDirectories);
 
                foreach (var d in dbs)
 
                {
 
                    size += d.Length;
 
                    db++;
 
                }
 
            }
 
            catch
 
            {
 
            }
 
 
            if (!IsDisposed)
 
            {
 
                MethodInvoker m = delegate
 
                {
 
                    textBoxCacheSize.Text = string.Format(CultureInfo.InvariantCulture, "{0} db in {1:00} MB", db, size / (1024.0 * 1024.0));
 
                    textBoxCacheStatus.Text = "all tiles saved!";
 
                };
 
                Invoke(m);
 
            }
 
        }
 
 
        void OnTileCacheStart()
 
        {
 
            Debug.WriteLine("OnTileCacheStart");
 
 
            if (!IsDisposed)
 
            {
 
                MethodInvoker m = delegate
 
                {
 
                    textBoxCacheStatus.Text = "saving tiles...";
 
                };
 
                // MDKEdit
 
                //Invoke(m);
 
            }
 
        }
 
 
        void OnTileCacheProgress(int left)
 
        {
 
            if (!IsDisposed)
 
            {
 
                MethodInvoker m = delegate
 
                {
 
                    textBoxCacheStatus.Text = left + " tile to save...";
 
                };
 
                Invoke(m);
 
            }
 
        }
 
 
        void MainMap_OnMarkerLeave(GMapMarker item)
 
        {
 
            if (item is GMapMarkerRect)
 
            {
 
                CurentRectMarker = null;
 
 
                GMapMarkerRect rc = item as GMapMarkerRect;
 
                rc.Pen.Color = Color.Blue;
 
 
                Debug.WriteLine("OnMarkerLeave: " + item.Position);
 
            }
 
        }
 
 
        void MainMap_OnMarkerEnter(GMapMarker item)
 
        {
 
            if (item is GMapMarkerRect)
 
            {
 
                GMapMarkerRect rc = item as GMapMarkerRect;
 
                rc.Pen.Color = Color.Red;
 
 
                CurentRectMarker = rc;
 
 
                Debug.WriteLine("OnMarkerEnter: " + item.Position);
 
            }
 
        }
 
 
        GMapPolygon currentPolygon = null;
 
        void MainMap_OnPolygonLeave(GMapPolygon item)
 
        {
 
            currentPolygon = null;
 
            item.Stroke.Color = Color.MidnightBlue;
 
            Debug.WriteLine("OnPolygonLeave: " + item.Name);
 
        }
 
 
        void MainMap_OnPolygonEnter(GMapPolygon item)
 
        {
 
            currentPolygon = item;
 
            item.Stroke.Color = Color.Red;
 
            Debug.WriteLine("OnPolygonEnter: " + item.Name);
 
        }
 
 
        GMapRoute currentRoute = null;
 
        void MainMap_OnRouteLeave(GMapRoute item)
 
        {
 
            currentRoute = null;
 
            item.Stroke.Color = Color.MidnightBlue;
 
            Debug.WriteLine("OnRouteLeave: " + item.Name);
 
        }
 
 
        void MainMap_OnRouteEnter(GMapRoute item)
 
        {
 
            currentRoute = item;
 
            item.Stroke.Color = Color.Red;
 
            Debug.WriteLine("OnRouteEnter: " + item.Name);
 
        }
 
 
        void MainMap_OnMapTypeChanged(GMapProvider type)
 
        {
 
            comboBoxMapType.SelectedItem = type;
 
 
            trackBarZoomLevel.Minimum = MainMap.MinZoom * 100;
 
            trackBarZoomLevel.Maximum = MainMap.MaxZoom * 100;
 
 
            //if(rbtnFlight.Checked)
 
            //{
 
            //   MainMap.ZoomAndCenterMarkers("objects");
 
            //}
 
        }
 
 
        void MainMap_MouseUp(object sender, MouseEventArgs e)
 
        {
 
            // MDKAdd
 
            textBoxLatCurrent.Text = currentMarker.Position.Lat.ToString();
 
            textBoxLngCurrent.Text = currentMarker.Position.Lng.ToString();
 
            if (e.Button == MouseButtons.Left)
 
            {
 
                isMouseDown = false;
 
            }
 
        }
 
 
        // add demo circle
 
        void MainMap_MouseDoubleClick(object sender, MouseEventArgs e)
 
        {
 
            var cc = new GMapMarkerCircle(MainMap.FromLocalToLatLng(e.X, e.Y));
 
            objects.Markers.Add(cc);
 
        }
 
 
        void MainMap_MouseDown(object sender, MouseEventArgs e)
 
        {
 
            if (e.Button == MouseButtons.Left)
 
            {
 
                isMouseDown = true;
 
 
                if (currentMarker.IsVisible)
 
                {
 
                    currentMarker.Position = MainMap.FromLocalToLatLng(e.X, e.Y);
 
                    // MDKAdd
 
                    textBoxLatCurrent.Text = currentMarker.Position.Lat.ToString();
 
                    textBoxLngCurrent.Text = currentMarker.Position.Lng.ToString();
 
 
                    var px = MainMap.MapProvider.Projection.FromLatLngToPixel(currentMarker.Position.Lat, currentMarker.Position.Lng, (int)MainMap.Zoom);
 
                    var tile = MainMap.MapProvider.Projection.FromPixelToTileXY(px);
 
 
                    Debug.WriteLine("MouseDown: geo: " + currentMarker.Position + " | px: " + px + " | tile: " + tile);
 
                }
 
            }
 
        }
 
 
        // move current marker with left holding
 
        void MainMap_MouseMove(object sender, MouseEventArgs e)
 
        {
 
            if (e.Button == MouseButtons.Left && isMouseDown)
 
            {
 
                if (CurentRectMarker == null)
 
                {
 
                    if (currentMarker.IsVisible)
 
                    {
 
                        // MDKAdd
 
                        textBoxLatCurrent.Text = currentMarker.Position.Lat.ToString();
 
                        textBoxLngCurrent.Text = currentMarker.Position.Lng.ToString();
 
 
                        currentMarker.Position = MainMap.FromLocalToLatLng(e.X, e.Y);
 
                    }
 
                }
 
                else // move rect marker
 
                {
 
                    PointLatLng pnew = MainMap.FromLocalToLatLng(e.X, e.Y);
 
 
                    int? pIndex = (int?)CurentRectMarker.Tag;
 
                    if (pIndex.HasValue)
 
                    {
 
                        //if (pIndex < polygon.Points.Count)
 
                        //{
 
                        //    polygon.Points[pIndex.Value] = pnew;
 
                        //    MainMap.UpdatePolygonLocalPosition(polygon);
 
                        //}
 
                    }
 
 
                    if (currentMarker.IsVisible)
 
                    {
 
                        currentMarker.Position = pnew;
 
                        // MDKAdd
 
                        textBoxLatCurrent.Text = currentMarker.Position.Lat.ToString();
 
                        textBoxLngCurrent.Text = currentMarker.Position.Lng.ToString();
 
                    }
 
                    CurentRectMarker.Position = pnew;
 
 
                    if (CurentRectMarker.InnerMarker != null)
 
                    {
 
                        CurentRectMarker.InnerMarker.Position = pnew;
 
                    }
 
                }
 
 
                MainMap.Refresh(); // force instant invalidation
 
                // MDKAdd
 
                textBoxLatCurrent.Refresh();
 
                textBoxLngCurrent.Refresh();
 
            }
 
        }
 
 
        // MapZoomChanged
 
        void MainMap_OnMapZoomChanged()
 
        {
 
            trackBarZoomLevel.Value = (int)(MainMap.Zoom * 100.0);
 
            textBoxZoomCurrent.Text = MainMap.Zoom.ToString();
 
        }
 
 
        // click on some marker
 
        void MainMap_OnMarkerClick(GMapMarker item, MouseEventArgs e)
 
        {
 
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
 
            {
 
                if (item is GMapMarkerRect)
 
                {
 
                    GeoCoderStatusCode status;
 
                    var pos = GMapProviders.GoogleMap.GetPlacemark(item.Position, out status);
 
                    if (status == GeoCoderStatusCode.G_GEO_SUCCESS && pos != null)
 
                    {
 
                        GMapMarkerRect v = item as GMapMarkerRect;
 
                        {
 
                            v.ToolTipText = pos.Value.Address;
 
                        }
 
                        MainMap.Invalidate(false);
 
                    }
 
                }
 
                else
 
                {
 
                    //if (item.Tag != null)
 
                    //{
 
                    //    if (currentTransport != null)
 
                    //    {
 
                    //        currentTransport.ToolTipMode = MarkerTooltipMode.OnMouseOver;
 
                    //        currentTransport = null;
 
                    //    }
 
                    //    currentTransport = item;
 
                    //    currentTransport.ToolTipMode = MarkerTooltipMode.Always;
 
                    //}
 
                }
 
            }
 
        }
 
 
        // loader start loading tiles
 
        void MainMap_OnTileLoadStart()
 
        {
 
            MethodInvoker m = delegate()
 
            {
 
                panelMenu.Text = "Menu: loading tiles...";
 
            };
 
            try
 
            {
 
                BeginInvoke(m);
 
            }
 
            catch
 
            {
 
            }
 
        }
 
 
        // loader end loading tiles
 
        void MainMap_OnTileLoadComplete(long ElapsedMilliseconds)
 
        {
 
            MainMap.ElapsedMilliseconds = ElapsedMilliseconds;
 
 
            MethodInvoker m = delegate()
 
            {
 
                panelMenu.Text = "Menu, last load in " + MainMap.ElapsedMilliseconds + "ms";
 
 
                textBoxMemory.Text = string.Format(CultureInfo.InvariantCulture, "{0:0.00} MB of {1:0.00} MB", MainMap.Manager.MemoryCache.Size, MainMap.Manager.MemoryCache.Capacity);
 
            };
 
            try
 
            {
 
                BeginInvoke(m);
 
            }
 
            catch
 
            {
 
            }
 
        }
 
 
        // current point changed
 
        void MainMap_OnPositionChanged(PointLatLng point)
 
        {
 
            textBoxLatCurrent.Text = point.Lat.ToString(CultureInfo.InvariantCulture);
 
            textBoxLngCurrent.Text = point.Lng.ToString(CultureInfo.InvariantCulture);
 
 
            //lock (flights)
 
            //{
 
            //    lastPosition = point;
 
            //    lastZoom = (int)MainMap.Zoom;
 
            //}
 
        }
 
 
        //PointLatLng lastPosition;
 
        //int lastZoom;
 
 
        // center markers on start
 
        private void MainForm_Load(object sender, EventArgs e)
 
        {
 
            trackBarZoomLevel.Value = (int)MainMap.Zoom * 100;
 
            Activate();
 
            TopMost = true;
 
            TopMost = false;
 
 
            PrepareGraphs();
 
        }
 
        #endregion
 
 
        #region -- menu panels expanders --
 
        private void xPanderPanel1_Click(object sender, EventArgs e)
 
        {
 
            xPanderPanelList1.Expand(xPanderPanelMain);
 
        }
 
 
        private void xPanderPanelCache_Click(object sender, EventArgs e)
 
        {
 
            xPanderPanelList1.Expand(xPanderPanelCache);
 
        }
 
 
        private void xPanderPanelInfo_Click(object sender, EventArgs e)
 
        {
 
            xPanderPanelList1.Expand(xPanderPanelInfo);
 
        }
 
        #endregion
 
 
        #region -- ui events --
 
 
        bool UserAcceptedLicenseOnce = false;
 
 
        // change map type
 
        private void comboBoxMapType_DropDownClosed(object sender, EventArgs e)
 
        {
 
            if (!UserAcceptedLicenseOnce)
 
            {
 
                if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "License.txt"))
 
                {
 
                    string ctn = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "License.txt");
 
                    int li = ctn.IndexOf("License");
 
                    string txt = ctn.Substring(li);
 
 
                    var d = new Demo.WindowsForms.Forms.Message();
 
                    d.richTextBox1.Text = txt;
 
 
                    if (DialogResult.Yes == d.ShowDialog())
 
                    {
 
                        UserAcceptedLicenseOnce = true;
 
                        this.Text += " - license accepted by " + Environment.UserName + " at " + DateTime.Now;
 
                    }
 
                }
 
                else
 
                {
 
                    // user deleted License.txt ;}
 
                    UserAcceptedLicenseOnce = true;
 
                }
 
            }
 
 
            if (UserAcceptedLicenseOnce)
 
            {
 
                MainMap.MapProvider = comboBoxMapType.SelectedItem as GMapProvider;
 
            }
 
            else
 
            {
 
                MainMap.MapProvider = GMapProviders.OpenStreetMap;
 
                comboBoxMapType.SelectedItem = MainMap.MapProvider;
 
            }
 
        }
 
 
        // change mdoe
 
        private void comboBoxMode_DropDownClosed(object sender, EventArgs e)
 
        {
 
            MainMap.Manager.Mode = (AccessMode)comboBoxMode.SelectedValue;
 
            MainMap.ReloadMap();
 
        }
 
 
        // zoom
 
        private void trackBar1_ValueChanged(object sender, EventArgs e)
 
        {
 
            MainMap.Zoom = trackBarZoomLevel.Value / 100.0;
 
        }
 
 
        // go to
 
        private void btnGoToCoords_Click(object sender, EventArgs e)
 
        {
 
            try
 
            {
 
                double lat = double.Parse(textBoxLat.Text, CultureInfo.InvariantCulture);
 
                double lng = double.Parse(textBoxLng.Text, CultureInfo.InvariantCulture);
 
 
                MainMap.Position = new PointLatLng(lat, lng);
 
            }
 
            catch (Exception ex)
 
            {
 
                MessageBox.Show("incorrect coordinate format: " + ex.Message);
 
            }
 
        }
 
 
        // goto by geocoder
 
        private void textBoxGeo_KeyPress(object sender, KeyPressEventArgs e)
 
        {
 
            if ((Keys)e.KeyChar == Keys.Enter)
 
            {
 
                GeoCoderStatusCode status = MainMap.SetCurrentPositionByKeywords(textBoxGeo.Text);
 
                if (status != GeoCoderStatusCode.G_GEO_SUCCESS)
 
                {
 
                    MessageBox.Show("Google Maps Geocoder can't find: '" + textBoxGeo.Text + "', reason: " + status.ToString(), "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
 
                }
 
            }
 
        }
 
 
        // reload map
 
        private void btnReload_Click(object sender, EventArgs e)
 
        {
 
            MainMap.ReloadMap();
 
        }
 
 
        // cache config
 
        private void checkBoxUseCache_CheckedChanged(object sender, EventArgs e)
 
        {
 
            MainMap.Manager.UseRouteCache = checkBoxUseRouteCache.Checked;
 
            MainMap.Manager.UseGeocoderCache = checkBoxUseRouteCache.Checked;
 
            MainMap.Manager.UsePlacemarkCache = checkBoxUseRouteCache.Checked;
 
            MainMap.Manager.UseDirectionsCache = checkBoxUseRouteCache.Checked;
 
        }
 
 
        // clear cache
 
        private void button2_Click(object sender, EventArgs e)
 
        {
 
            if (MessageBox.Show("Are You sure?", "Clear GMap.NET cache?", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
 
            {
 
                try
 
                {
 
                    MainMap.Manager.PrimaryCache.DeleteOlderThan(DateTime.Now, null);
 
                    MessageBox.Show("Done. Cache is clear.");
 
                }
 
                catch (Exception ex)
 
                {
 
                    MessageBox.Show(ex.Message);
 
                }
 
            }
 
        }
 
 
        // add test route
 
        private void btnAddRoute_Click(object sender, EventArgs e)
 
        {
 
            RoutingProvider rp = MainMap.MapProvider as RoutingProvider;
 
            if (rp == null)
 
            {
 
                rp = GMapProviders.GoogleMap; // use google if provider does not implement routing
 
            }
 
 
            MapRoute route = rp.GetRoute(start, end, false, false, (int)MainMap.Zoom);
 
            if (route != null)
 
            {
 
                // add route
 
                GMapRoute r = new GMapRoute(route.Points, route.Name);
 
                r.IsHitTestVisible = true;
 
                routes.Routes.Add(r);
 
 
                // add route start/end marks
 
                GMapMarker m1 = new GMarkerGoogle(start, GMarkerGoogleType.green_big_go);
 
                m1.ToolTipText = "Start: " + route.Name;
 
                m1.ToolTipMode = MarkerTooltipMode.Always;
 
 
                GMapMarker m2 = new GMarkerGoogle(end, GMarkerGoogleType.red_big_stop);
 
                m2.ToolTipText = "End: " + end.ToString();
 
                m2.ToolTipMode = MarkerTooltipMode.Always;
 
 
                objects.Markers.Add(m1);
 
                objects.Markers.Add(m2);
 
 
                //MainMap.ZoomAndCenterRoute(r);
 
 
            }
 
        }
 
 
        // add marker on current position - MDKEdit
 
        private void btnAddMarker_Click(object sender, EventArgs e)
 
        {
 
            GMarkerGoogle m = new GMarkerGoogle(currentMarker.Position, GMarkerGoogleType.blue_small);
 
            //GMapMarkerRect mBorders = new GMapMarkerRect(currentMarker.Position);
 
            //{
 
            //   mBorders.InnerMarker = m;
 
            //   if(polygon != null)
 
            //   {
 
            //      mBorders.Tag = polygon.Points.Count;
 
            //   }
 
            //   mBorders.ToolTipMode = MarkerTooltipMode.Always;
 
            //}
 
 
            Placemark? p = null;
 
            if (xboxPlacemarkInfo.Checked)
 
            {
 
                GeoCoderStatusCode status;
 
                var ret = GMapProviders.GoogleMap.GetPlacemark(currentMarker.Position, out status);
 
                if (status == GeoCoderStatusCode.G_GEO_SUCCESS && ret != null)
 
                {
 
                    p = ret;
 
                }
 
            }
 
 
            //if(p != null)
 
            //{
 
            //   mBorders.ToolTipText = p.Value.Address;
 
            //}
 
            //else
 
            //{
 
            //   mBorders.ToolTipText = currentMarker.Position.ToString();
 
            //}
 
 
            objects.Markers.Add(m);
 
            //objects.Markers.Add(mBorders);
 
 
            //RegeneratePolygon();
 
        }
 
 
        // clear routes
 
        private void btnClearRoutes_Click(object sender, EventArgs e)
 
        {
 
            routes.Routes.Clear();
 
        }
 
 
        // clear polygons
 
        private void btnClearPolygons_Click(object sender, EventArgs e)
 
        {
 
            //polygons.Polygons.Clear();
 
        }
 
 
        // clear markers
 
        private void btnClearMarkers_Click(object sender, EventArgs e)
 
        {
 
            objects.Markers.Clear();
 
            hasEndMarker = false;
 
            hasStartMarker = false;
 
        }
 
 
        // show current marker
 
        private void checkBoxCurrentMarker_CheckedChanged(object sender, EventArgs e)
 
        {
 
            currentMarker.IsVisible = xboxCurrentMarker.Checked;
 
        }
 
 
        // can drag
 
        private void checkBoxCanDrag_CheckedChanged(object sender, EventArgs e)
 
        {
 
            MainMap.CanDragMap = xboxCanDrag.Checked;
 
        }
 
 
        bool hasStartMarker = false;
 
        // set route start 
 
        private void buttonSetStart_Click(object sender, EventArgs e)
 
        {
 
            start = currentMarker.Position;
 
            // - MDKAdd
 
            GMarkerGoogle m = new GMarkerGoogle(currentMarker.Position, GMarkerGoogleType.green_small);
 
            
 
            //prevent multiple start markers from existing
 
            if(hasStartMarker){
 
                objects.Markers.RemoveAt(0);
 
            }
 
 
            objects.Markers.Insert(0, m);
 
            if (hasEndMarker)
 
            {
 
                objects.Markers.Move(2, 1);
 
            }
 
            hasStartMarker = true; 
 
        }
 
 
        bool hasEndMarker = false;
 
        // set route end
 
        private void buttonSetEnd_Click(object sender, EventArgs e)
 
        {
 
            end = currentMarker.Position;
 
            // - MDKAdd
 
            GMarkerGoogle m = new GMarkerGoogle(currentMarker.Position, GMarkerGoogleType.red_small);
 
 
            //prevent multiple start markers from existing
 
            if (hasEndMarker)
 
            {
 
                objects.Markers.RemoveAt(1);
 
            }
 
            objects.Markers.Insert(1, m);
 
            hasEndMarker = true;
 
        }
 
 
        // zoom to max for markers
 
        private void button7_Click(object sender, EventArgs e)
 
        {
 
            MainMap.ZoomAndCenterMarkers("objects");
 
        }
 
 
        // export map data
 
        private void button9_Click(object sender, EventArgs e)
 
        {
 
            MainMap.ShowExportDialog();
 
        }
 
 
        // import map data
 
        private void button10_Click(object sender, EventArgs e)
 
        {
 
            MainMap.ShowImportDialog();
 
        }
 
 
        // prefetch
 
        private void button11_Click(object sender, EventArgs e)
 
        {
 
            RectLatLng area = MainMap.SelectedArea;
 
            if (!area.IsEmpty)
 
            {
 
                for (int i = (int)MainMap.Zoom; i <= MainMap.MaxZoom; i++)
 
                {
 
                    DialogResult res = MessageBox.Show("Ready ripp at Zoom = " + i + " ?", "GMap.NET", MessageBoxButtons.YesNoCancel);
 
 
                    if (res == DialogResult.Yes)
 
                    {
 
                        using (TilePrefetcher obj = new TilePrefetcher())
 
                        {
 
                            obj.Owner = this;
 
                            obj.ShowCompleteMessage = true;
 
                            obj.Start(area, i, MainMap.MapProvider, 100);
 
                        }
 
                    }
 
                    else if (res == DialogResult.No)
 
                    {
 
                        continue;
 
                    }
 
                    else if (res == DialogResult.Cancel)
 
                    {
 
                        break;
 
                    }
 
                }
 
            }
 
            else
 
            {
 
                MessageBox.Show("Select map area holding ALT", "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
 
            }
 
        }
 
 
        // saves current map view 
 
        private void btnSaveView_Click(object sender, EventArgs e)
 
        {
 
            try
 
            {
 
                using (SaveFileDialog sfd = new SaveFileDialog())
 
                {
 
                    sfd.Filter = "PNG (*.png)|*.png";
 
                    sfd.FileName = "GMap.NET image";
 
 
                    Image tmpImage = MainMap.ToImage();
 
                    if (tmpImage != null)
 
                    {
 
                        using (tmpImage)
 
                        {
 
                            if (sfd.ShowDialog() == DialogResult.OK)
 
                            {
 
                                tmpImage.Save(sfd.FileName);
 
 
                                MessageBox.Show("Image saved: " + sfd.FileName, "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Information);
 
                            }
 
                        }
 
                    }
 
                }
 
            }
 
            catch (Exception ex)
 
            {
 
                MessageBox.Show("Image failed to save: " + ex.Message, "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
 
            }
 
        }
 
 
        // debug tile grid
 
        private void checkBoxDebug_CheckedChanged(object sender, EventArgs e)
 
        {
 
            MainMap.ShowTileGridLines = xboxGrid.Checked;
 
        }
 
 
        // launch static map maker
 
        private void btnGetStatic_Click(object sender, EventArgs e)
 
        {
 
            StaticImage st = new StaticImage(this);
 
            st.Owner = this;
 
            st.Show();
 
        }
 
 
        // add gps log from mobile
 
        private void btnMobileLog_Click(object sender, EventArgs e)
 
        {
 
            using (FileDialog dlg = new OpenFileDialog())
 
            {
 
                dlg.CheckPathExists = true;
 
                dlg.CheckFileExists = false;
 
                dlg.AddExtension = true;
 
                dlg.DefaultExt = "gpsd";
 
                dlg.ValidateNames = true;
 
                dlg.Title = "GMap.NET: open gps log generated in your windows mobile";
 
                dlg.Filter = "GMap.NET gps log DB files (*.gpsd)|*.gpsd";
 
                dlg.FilterIndex = 1;
 
                dlg.RestoreDirectory = true;
 
 
                if (dlg.ShowDialog() == DialogResult.OK)
 
                {
 
                    routes.Routes.Clear();
 
 
                    mobileGpsLog = dlg.FileName;
 
 
                    // add routes
 
                    AddGpsMobileLogRoutes(dlg.FileName);
 
 
                    if (routes.Routes.Count > 0)
 
                    {
 
                        MainMap.ZoomAndCenterRoutes(null);
 
                    }
 
                }
 
            }
 
        }
 
 
        // key-up events
 
        private void MainForm_KeyUp(object sender, KeyEventArgs e)
 
        {
 
            int offset = -22;
 
 
            if (e.KeyCode == Keys.Left)
 
            {
 
                MainMap.Offset(-offset, 0);
 
            }
 
            else if (e.KeyCode == Keys.Right)
 
            {
 
                MainMap.Offset(offset, 0);
 
            }
 
            else if (e.KeyCode == Keys.Up)
 
            {
 
                MainMap.Offset(0, -offset);
 
            }
 
            else if (e.KeyCode == Keys.Down)
 
            {
 
                MainMap.Offset(0, offset);
 
            }
 
            else if (e.KeyCode == Keys.Delete)
 
            {
 
                //if (currentPolygon != null)
 
                //{
 
                //    polygons.Polygons.Remove(currentPolygon);
 
                //    currentPolygon = null;
 
                //}
 
 
                if (currentRoute != null)
 
                {
 
                    routes.Routes.Remove(currentRoute);
 
                    currentRoute = null;
 
                }
 
 
                if (CurentRectMarker != null)
 
                {
 
                    objects.Markers.Remove(CurentRectMarker);
 
 
                    if (CurentRectMarker.InnerMarker != null)
 
                    {
 
                        objects.Markers.Remove(CurentRectMarker.InnerMarker);
 
                    }
 
                    CurentRectMarker = null;
 
 
                    //RegeneratePolygon();
 
                }
 
            }
 
            else if (e.KeyCode == Keys.Escape)
 
            {
 
                MainMap.Bearing = 0;
 
 
                //if (currentTransport != null && !MainMap.IsMouseOverMarker)
 
                //{
 
                //    currentTransport.ToolTipMode = MarkerTooltipMode.OnMouseOver;
 
                //    currentTransport = null;
 
                //}
 
            }
 
        }
 
 
        // key-press events
 
        private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
 
        {
 
            if (MainMap.Focused)
 
            {
 
                if (e.KeyChar == '+')
 
                {
 
                    MainMap.Zoom = ((int)MainMap.Zoom) + 1;
 
                }
 
                else if (e.KeyChar == '-')
 
                {
 
                    MainMap.Zoom = ((int)(MainMap.Zoom + 0.99)) - 1;
 
                }
 
                else if (e.KeyChar == 'a')
 
                {
 
                    MainMap.Bearing--;
 
                }
 
                else if (e.KeyChar == 'z')
 
                {
 
                    MainMap.Bearing++;
 
                }
 
            }
 
        }
 
 
        private void buttonZoomUp_Click(object sender, EventArgs e)
 
        {
 
            MainMap.Zoom = ((int)MainMap.Zoom) + 1;
 
        }
 
 
        private void buttonZoomDown_Click(object sender, EventArgs e)
 
        {
 
            MainMap.Zoom = ((int)(MainMap.Zoom + 0.99)) - 1;
 
        }
 
 
        // engage some live demo
 
        //private void RealTimeChanged(object sender, EventArgs e)
 
        //{
 
        //   objects.Markers.Clear();
 
        //   polygons.Polygons.Clear();
 
        //   routes.Routes.Clear();
 
 
        //   //// start performance test
 
        //   //if(rbtnPerf.Checked)
 
        //   //{
 
        //   //   timerPerf.Interval = 44;
 
        //   //   timerPerf.Start();
 
        //   //}
 
        //   //else
 
        //   //{
 
        //   //   // stop performance test
 
        //   //   timerPerf.Stop();
 
        //   //}
 
 
        //   // start realtime transport tracking demo
 
        //   //if(rbtnFlight.Checked)
 
        //   //{
 
        //   //   if(!flightWorker.IsBusy)
 
        //   //   {
 
        //   //      firstLoadFlight = true;
 
        //   //      flightWorker.RunWorkerAsync();
 
        //   //   }
 
        //   //}
 
        //   //else
 
        //   //{
 
        //   //   if(flightWorker.IsBusy)
 
        //   //   {
 
        //   //      flightWorker.CancelAsync();
 
        //   //   }
 
        //   //}
 
 
        //   // vehicle demo
 
        //   //if(rbtnVehicle.Checked)
 
        //   //{
 
        //   //   if(!transportWorker.IsBusy)
 
        //   //   {
 
        //   //      firstLoadTrasport = true;
 
        //   //      transportWorker.RunWorkerAsync();
 
        //   //   }
 
        //   //}
 
        //   //else
 
        //   //{
 
        //   //   if(transportWorker.IsBusy)
 
        //   //   {
 
        //   //      transportWorker.CancelAsync();
 
        //   //   }
 
        //   //}
 
 
        //   // start live tcp/ip connections demo
 
        //   if(rbtnTcpIp.Checked)
 
        //   {
 
        //      GridConnections.Visible = true;
 
        //      checkBoxTcpIpSnap.Visible = true;
 
        //      checkBoxTraceRoute.Visible = true;
 
        //      GridConnections.Refresh();
 
 
        //      if(!connectionsWorker.IsBusy)
 
        //      {
 
        //         //if(MainMap.Provider != MapType.GoogleMap)
 
        //         //{
 
        //         //   MainMap.MapType = MapType.GoogleMap;
 
        //         //}
 
        //         MainMap.Zoom = 5;
 
 
        //         connectionsWorker.RunWorkerAsync();
 
        //      }
 
        //   }
 
        //   else
 
        //   {
 
        //      CountryStatusView.Clear();
 
        //      GridConnections.Visible = false;
 
        //      checkBoxTcpIpSnap.Visible = false;
 
        //      checkBoxTraceRoute.Visible = false;
 
 
        //      if(connectionsWorker.IsBusy)
 
        //      {
 
        //         connectionsWorker.CancelAsync();
 
        //      }
 
 
        //      if(ipInfoSearchWorker.IsBusy)
 
        //      {
 
        //         ipInfoSearchWorker.CancelAsync();
 
        //      }
 
 
        //      if(iptracerWorker.IsBusy)
 
        //      {
 
        //         iptracerWorker.CancelAsync();
 
        //      }
 
        //   }
 
        //}
 
 
        // export mobile gps log to gpx file
 
        private void buttonExportToGpx_Click(object sender, EventArgs e)
 
        {
 
            try
 
            {
 
                using (SaveFileDialog sfd = new SaveFileDialog())
 
                {
 
                    sfd.Filter = "GPX (*.gpx)|*.gpx";
 
                    sfd.FileName = "mobile gps log";
 
 
                    DateTime? date = null;
 
                    DateTime? dateEnd = null;
 
 
                    if (MobileLogFrom.Checked)
 
                    {
 
                        date = MobileLogFrom.Value.ToUniversalTime();
 
 
                        sfd.FileName += " from " + MobileLogFrom.Value.ToString("yyyy-MM-dd HH-mm");
 
                    }
 
 
                    if (MobileLogTo.Checked)
 
                    {
 
                        dateEnd = MobileLogTo.Value.ToUniversalTime();
 
 
                        sfd.FileName += " to " + MobileLogTo.Value.ToString("yyyy-MM-dd HH-mm");
 
                    }
 
 
                    if (sfd.ShowDialog() == DialogResult.OK)
 
                    {
 
                        var log = Stuff.GetRoutesFromMobileLog(mobileGpsLog, date, dateEnd, 3.3);
 
                        if (log != null)
 
                        {
 
                            if (MainMap.Manager.ExportGPX(log, sfd.FileName))
 
                            {
 
                                MessageBox.Show("GPX saved: " + sfd.FileName, "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Information);
 
                            }
 
                        }
 
                    }
 
                }
 
            }
 
            catch (Exception ex)
 
            {
 
                MessageBox.Show("GPX failed to save: " + ex.Message, "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
 
            }
 
        }
 
 
        // load gpx file
 
        private void btnLoadGPX_Click(object sender, EventArgs e)
 
        {
 
            using (FileDialog dlg = new OpenFileDialog())
 
            {
 
                dlg.CheckPathExists = true;
 
                dlg.CheckFileExists = false;
 
                dlg.AddExtension = true;
 
                dlg.DefaultExt = "gpx";
 
                dlg.ValidateNames = true;
 
                dlg.Title = "GMap.NET: open gpx log";
 
                dlg.Filter = "gpx files (*.gpx)|*.gpx";
 
                dlg.FilterIndex = 1;
 
                dlg.RestoreDirectory = true;
 
 
                if (dlg.ShowDialog() == DialogResult.OK)
 
                {
 
                    try
 
                    {
 
                        string gpx = File.ReadAllText(dlg.FileName);
 
 
                        gpxType r = MainMap.Manager.DeserializeGPX(gpx);
 
                        if (r != null)
 
                        {
 
                            if (r.trk.Length > 0)
 
                            {
 
                                foreach (var trk in r.trk)
 
                                {
 
                                    List<PointLatLng> points = new List<PointLatLng>();
 
 
                                    foreach (var seg in trk.trkseg)
 
                                    {
 
                                        foreach (var p in seg.trkpt)
 
                                        {
 
                                            points.Add(new PointLatLng((double)p.lat, (double)p.lon));
 
                                        }
 
                                    }
 
 
                                    GMapRoute rt = new GMapRoute(points, string.Empty);
 
                                    {
 
                                        rt.Stroke = new Pen(Color.FromArgb(144, Color.Red));
 
                                        rt.Stroke.Width = 5;
 
                                        rt.Stroke.DashStyle = System.Drawing.Drawing2D.DashStyle.DashDot;
 
                                    }
 
                                    routes.Routes.Add(rt);
 
                                }
 
 
                                MainMap.ZoomAndCenterRoutes(null);
 
                            }
 
                        }
 
                    }
 
                    catch (Exception ex)
 
                    {
 
                        Debug.WriteLine("GPX import: " + ex.ToString());
 
                        MessageBox.Show("Error importing gpx: " + ex.Message, "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Warning);
 
                    }
 
                }
 
            }
 
        }
 
 
        // enable/disable host tracing
 
        //private void checkBoxTraceRoute_CheckedChanged(object sender, EventArgs e)
 
        //{
 
        //   TryTraceConnection = checkBoxTraceRoute.Checked;
 
        //   if(!TryTraceConnection)
 
        //   {
 
        //      if(iptracerWorker.IsBusy)
 
        //      {
 
        //         iptracerWorker.CancelAsync();
 
        //      }
 
        //      routes.Routes.Clear();
 
        //   }
 
        //}
 
 
        //private void GridConnections_DoubleClick(object sender, EventArgs e)
 
        //{
 
        //   GridConnections.ClearSelection();
 
        //}
 
 
        // open disk cache location
 
        private void button17_Click(object sender, EventArgs e)
 
        {
 
            try
 
            {
 
                string argument = "/select, \"" + MainMap.CacheLocation + "TileDBv5\"";
 
                System.Diagnostics.Process.Start("explorer.exe", argument);
 
            }
 
            catch (Exception ex)
 
            {
 
                MessageBox.Show("Failed to open: " + ex.Message, "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
 
            }
 
        }
 
 
        #endregion
 
 
        #region graph functions
 
 
        #region chart coloring
 
        //this method clears the background of all charts
 
        private void ResetChartColors()
 
        {
 
            chrtTopLeft.BackColor = Color.LightGray;
 
            chrtTopRight.BackColor = Color.LightGray;
 
            chrtBottomLeft.BackColor = Color.LightGray;
 
            chrtBottomRight.BackColor = Color.LightGray;
 
        }
 
 
        //highlight Top Left chart on click
 
        //set text box values based on this chart
 
        private void chrtTopLeft_Click(object sender, EventArgs e)
 
        {
 
            ResetChartColors();
 
            chrtTopLeft.BackColor = Color.Gray;
 
            tboxChartData.Text = "Altitude";
 
            tboxCurrent.Text = "";
 
            tboxAverage.Text = "";
 
            tboxMax.Text = "";
 
            tboxMin.Text = "";
 
        }
 
 
        //highlight Top Right chart on click
 
        //set text box values based on this chart
 
        private void chrtTopRight_Click(object sender, EventArgs e)
 
        {
 
            ResetChartColors();
 
            chrtTopRight.BackColor = Color.Gray;
 
            tboxChartData.Text = "Humidity";
 
            tboxCurrent.Text = "";
 
            tboxAverage.Text = "";
 
            tboxMax.Text = "";
 
            tboxMin.Text = "";
 
        }
 
 
        //highlight Bottom Left chart on click
 
        //set text box values based on this chart
 
        private void chrtBottomLeft_Click(object sender, EventArgs e)
 
        {
 
            ResetChartColors();
 
            chrtBottomLeft.BackColor = Color.Gray;
 
            tboxChartData.Text = "Pressure";
 
            tboxCurrent.Text = "";
 
            tboxAverage.Text = "";
 
            tboxMax.Text = "";
 
            tboxMin.Text = "";
 
        }
 
 
        //highlight Bottom Right chart on click
 
        //set text box values based on this chart
 
        private void chrtBottomRight_Click(object sender, EventArgs e)
 
        {
 
            ResetChartColors();
 
            chrtBottomRight.BackColor = Color.Gray;
 
            tboxChartData.Text = "Map";
 
            tboxCurrent.Text = "";
 
            tboxAverage.Text = "";
 
            tboxMax.Text = "";
 
            tboxMin.Text = "";
 
        }
 
 
        #endregion
 
 
        public void PrepareGraphs(){
 
 
            //set up for graphs MDKEdit
 
            // http://www.youtube.com/watch?v=zTod4-Fg6Ew - split containers
 
            // http://www.youtube.com/watch?v=bMXtgPk875I - chart controls
 
 
            chrtTopLeft.ChartAreas.Add("altitudeArea");
 
            chrtTopLeft.Series.Add("altitudeTrend");
 
 
            chrtTopRight.ChartAreas.Add("humidityArea");
 
            chrtTopRight.Series.Add("humidityTrend");
 
 
            chrtBottomLeft.Series.Add("pressureTrend");
 
            chrtBottomLeft.ChartAreas.Add("pressureArea");
 
 
            chrtBottomRight.ChartAreas.Add("velocityArea");
 
            chrtBottomRight.Series.Add("velocityTrend");
 
 
            // declare all series, data points to be modified dynamically at run
 
 
            //---------prep altitude area BEGIN 
 
            chrtTopLeft.Series["altitudeTrend"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
 
            chrtTopLeft.Series["altitudeTrend"].Color = Color.Green;
 
            System.Windows.Forms.DataVisualization.Charting.AxisName.X.Equals("Time");
 
            System.Windows.Forms.DataVisualization.Charting.AxisName.Y.Equals("Altitude");
 
            
 
            ///required initial value
 
            chrtTopLeft.Series["altitudeTrend"].Points.AddXY(0, 0);
 
            //---------prep altitude area END 
 
 
 
            //-----------prep humidity area BEGIN
 
            chrtTopRight.Series["humidityTrend"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
 
            chrtTopRight.Series["humidityTrend"].Color = Color.Red;
 
            System.Windows.Forms.DataVisualization.Charting.AxisName.X.Equals("Time");
 
            System.Windows.Forms.DataVisualization.Charting.AxisName.Y.Equals("Humidity");
 
 
            ///required initial value
 
            chrtTopRight.Series["humidityTrend"].Points.AddXY(0, 0);
 
            //-----------prep humidity area END
 
 
 
            //-----------prep pressure area BEGIN
 
            chrtBottomLeft.Series["pressureTrend"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
 
            chrtBottomLeft.Series["pressureTrend"].Color = Color.Blue;
 
            System.Windows.Forms.DataVisualization.Charting.AxisName.X.Equals("Time");
 
            System.Windows.Forms.DataVisualization.Charting.AxisName.Y.Equals("Pressure");
 
 
            ///required initial value
 
            chrtBottomLeft.Series["pressureTrend"].Points.AddXY(0, 0);
 
            //-----------prep pressure area END
 
 
 
            //----------prep velocity area BEGIN
 
            chrtBottomRight.Series["velocityTrend"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
 
            chrtBottomRight.Series["velocityTrend"].Color = Color.Green;
 
            System.Windows.Forms.DataVisualization.Charting.AxisName.X.Equals("Time");
 
            System.Windows.Forms.DataVisualization.Charting.AxisName.Y.Equals("Altitude");
 
 
            ///required initial value
 
            chrtBottomRight.Series["velocityTrend"].Points.AddXY(0, 0);
 
            //----------prep velocity area END
 
 
            //put chart displays in a ready state
 
            ResetChartColors();
 
        }
 
        string latitude;
 
        string longitude;
 
        //handle line of input data and put into chart
 
 
        //parses transmissions and saves data to CSV file
 
        public void ParseIncomingData(string rawDataReceived)
 
        {
 
            //check to see if data should be processed
 
            if (!cboxCollectData.Checked)
 
            {
 
                return;
 
            }
 
            //if (!cboxCollectData.Checked)
 
            //{
 
            //    return;
 
            //}
 
            /* sample stansmission
 
            KD8TDF-9>APRS,WIDE2-1:/151916z3944.87N/08348.75WO005/0.013 SV:09 A-30.5 B45.64 C99542
 
                                          ^char 31 ^char 40            ^60
 
            */
 
 
            //TODO: verify index charcter accuracy with real transmission
 
            int indexStart = rawDataReceived.IndexOf("z");
 
            int indexEnd = rawDataReceived.IndexOf("N/");
 
            latitude = rawDataReceived.Substring(indexStart + 1, indexEnd - indexStart - 1);
 
 
            indexStart = rawDataReceived.IndexOf("N/");
 
            indexEnd = rawDataReceived.IndexOf("WO");
 
            longitude = rawDataReceived.Substring(indexStart + 2, indexEnd - indexStart - 2);
 
 
            addMarkerFromTransmit(latitude, longitude);
 
            //addMarkerFromTransmit(latitude, longitude);
 
            AddText(rawDataReceived + "\r\n");
 
 
            rawDataReceived = rawDataReceived.Substring(59); //remove APRS overhead from string
 
 
            //place each datum in its own variable
 
            string[] dataTransmission;
 
            dataTransmission = rawDataReceived.Split(' ');
 
 
            //parse out the data type - should be a single letter
 
            string typeCode;
 
            double data;
 
            string csvData = "";
 
 
            //loop through all datums in the transmission and send them to the chart builder
 
            for (int i = 1; i < dataTransmission.Length; i++)
 
            {
 
                typeCode = dataTransmission[i].Substring(0, 1);
 
                data = double.Parse(dataTransmission[i].Substring(1));
 
                addToChart(typeCode, data);
 
                //addToChart(typeCode, data);
 
                csvData += typeCode + data + ",";
 
            }
 
 
            //write the data to CSV file
 
            WriteToCSV(csvData);
 
        }
 
 
        //write the data to CSV file
 
        private void WriteToCSV(string data)
 
        {
 
            using (StreamWriter writer = new StreamWriter("debug.csv", true))
 
            {
 
                writer.WriteLine(data);
 
            }
 
        }
 
        //method to insert parsed data into the charts
 
        //TODO: add inserts for all charts. altitude is finished and is a template
 
        private void addToChart(string dataType, double data)
 
        {
 
            ///data types organized by listing in google doc
 
            //MASTER MODULE DATA VALUES
 
            if (dataType.Equals("t"))  //board temperature
 
            {
 
 
            }
 
            else if (dataType.Equals("L"))  //battery level
 
            {
 
 
            }
 
            else if (dataType.Equals("X"))  //Latitude accuracy
 
            {
 
 
            }
 
            else if (dataType.Equals("Y"))  //Longitude accuracy
 
            {
 
 
            }
 
            else if (dataType.Equals("V"))  //Velocity
 
            {
 
                chrtBottomRight.Series.FindByName("velocityTrend").Points.AddY(data);
 
            }
 
            else if (dataType.Equals("I"))  //Info/error Message
 
            {
 
 
            }
 
 
            //ATMOSPHERIC MODULE DATA VALUES
 
            else if (dataType.Equals("l"))  //battery level
 
            {
 
 
            }
 
            else if (dataType.Equals("C"))  //battery level
 
            {
 
 
            }
 
            else if (dataType.Equals("H"))  //Humidity
 
            {
 
                chrtTopRight.Series.FindByName("humidityTrend").Points.AddY(data);
 
            }
 
            else if (dataType.Equals("P"))  //Pressure
 
            {
 
                chrtBottomLeft.Series.FindByName("pressureTrend").Points.AddY(data);
 
            }
 
            else if (dataType.Equals("A"))  //Altitude
 
            {
 
                chrtTopLeft.Series.FindByName("altitudeTrend").Points.AddY(data);
 
            }
 
 
            //GEIGER MODULE DATA VALUES
 
            else if (dataType.Equals("l"))  //battery level
 
            {
 
 
            }
 
            else if (dataType.Equals("R"))  //radiation (CPM)
 
            {
 
 
            }
 
 
            // CAMERA MODULE DATA VALUES
 
            else if (dataType.Equals("l"))  //battery level
 
            {
 
 
            }
 
            else  //invalid data type
 
            {
 
 
            }
 
        }
 
 
        // add marker from an APRS transmission - MDKEdit
 
        private void addMarkerFromTransmit(string lat, string lng)
 
        {
 
            double latitude = double.Parse(lat), longitude = double.Parse(lng);
 
            PointLatLng APRSloc = new PointLatLng();
 
            APRSloc.Lat = latitude;
 
            APRSloc.Lng = longitude;
 
 
            GMarkerGoogle m = new GMarkerGoogle(APRSloc, GMarkerGoogleType.blue_small);
 
 
            Placemark? p = null;
 
            if (xboxPlacemarkInfo.Checked)
 
            {
 
                GeoCoderStatusCode status;
 
                var ret = GMapProviders.GoogleMap.GetPlacemark(currentMarker.Position, out status);
 
                if (status == GeoCoderStatusCode.G_GEO_SUCCESS && ret != null)
 
                {
 
                    p = ret;
 
                }
 
            }
 
 
            objects.Markers.Add(m);
 
        }
 
        #endregion
 
 
        #region cross theading
 
 
        //these are for function calls across threads
 
        delegate void SetTextDelegate(string value);
 
        public void AddText(string value)
 
        {
 
            if (InvokeRequired)
 
            {
 
                Invoke(new SetTextDelegate(AddText), value);
 
            }
 
            else
 
            {
 
                tboxMessageBox.AppendText(value);// += value;
 
            }
 
        }
 
 
        delegate void ChartDataDelegate(string dataType, double data);
 
        public void AddDataToChart(string dataType, double data)
 
        {
 
            if (InvokeRequired)
 
            {
 
                Invoke(new ChartDataDelegate(AddDataToChart), dataType, data);
 
            }
 
            else
 
            {
 
                addToChart(dataType, data);
 
            }
 
        }
 
 
        #endregion
 
 
        #region testing
 
        
 
        //click event on the test button
 
        //currently simulates serial inputs
 
        string testData;
 
        int testIteration = 0;
 
        double testLat = 39.751248, testLng = -83.809848, testVelocity = 5.8, testAltitude = 100, testPressure = 700, testHumidity = 38;
 
        private void btnTest_Click(object sender, EventArgs e)
 
        {
 
            testLat += GetRandomNumber(-.005, .015);
 
            testLng += GetRandomNumber(-.005, .015);
 
            testVelocity += GetRandomNumber(1, 15);
 
            testAltitude += GetRandomNumber(50, 150);
 
            testPressure -= GetRandomNumber(10, 50);
 
            testHumidity -= GetRandomNumber(1, 3);
 
 
            switch (testIteration)
 
            {
 
                case 0:
 
                    testData = "KD8TDF-9>APRS,WIDE2-1:/151916z" + testLat + "N/" + testLng + "WO005/0.013 V" + testVelocity + " A" + testAltitude+" H"+testHumidity+" P"+testPressure;
 
                    ParseIncomingData(testData);
 
                    break;
 
                case 1:
 
                    testData = "KD8TDF-9>APRS,WIDE2-1:/151916z" + testLat + "N/" + testLng + "WO005/0.013 V" + testVelocity + " A" + testAltitude + " H" + testHumidity + " P" + testPressure;
 
                    ParseIncomingData(testData);
 
                    break;
 
                case 2:
 
                    testData = "KD8TDF-9>APRS,WIDE2-1:/151916z" + testLat + "N/" + testLng + "WO005/0.013 V" + testVelocity + " A" + testAltitude + " H" + testHumidity + " P" + testPressure;
 
                    ParseIncomingData(testData);
 
                    break;
 
                case 3:
 
                    testData = "KD8TDF-9>APRS,WIDE2-1:/151916z" + testLat + "N/" + testLng + "WO005/0.013 V" + testVelocity + " A" + testAltitude + " H" + testHumidity + " P" + testPressure;
 
                    ParseIncomingData(testData);
 
                    break;
 
                case 4:
 
                    testData = "KD8TDF-9>APRS,WIDE2-1:/151916z" + testLat + "N/" + testLng + "WO005/0.013 V" + testVelocity + " A" + testAltitude + " H" + testHumidity + " P" + testPressure;
 
                    ParseIncomingData(testData);
 
                    break;
 
                case 5:
 
                    testData = "KD8TDF-9>APRS,WIDE2-1:/151916z" + testLat + "N/" + testLng + "WO005/0.013 V" + testVelocity + " A" + testAltitude + " H" + testHumidity + " P" + testPressure;
 
                    ParseIncomingData(testData);
 
                    break;
 
                case 6:
 
                    testData = "KD8TDF-9>APRS,WIDE2-1:/151916z" + testLat + "N/" + testLng + "WO005/0.013 V" + testVelocity + " A" + testAltitude + " H" + testHumidity + " P" + testPressure;
 
                    ParseIncomingData(testData);
 
                    break;
 
                case 7:
 
                    testData = "KD8TDF-9>APRS,WIDE2-1:/151916z" + testLat + "N/" + testLng + "WO005/0.013 V" + testVelocity + " A" + testAltitude + " H" + testHumidity + " P" + testPressure;
 
                    ParseIncomingData(testData);
 
                    break;
 
                case 8:
 
                    testData = "KD8TDF-9>APRS,WIDE2-1:/151916z" + testLat + "N/" + testLng + "WO005/0.013 V" + testVelocity + " A" + testAltitude + " H" + testHumidity + " P" + testPressure;
 
                    ParseIncomingData(testData);
 
                    break;
 
                case 9:
 
                    testData = "KD8TDF-9>APRS,WIDE2-1:/151916z" + testLat + "N/" + testLng + "WO005/0.013 V" + testVelocity + " A" + testAltitude + " H" + testHumidity + " P" + testPressure;
 
                    ParseIncomingData(testData);
 
                    break;
 
                default:
 
                    break;
 
            }
 
            testIteration++;
 
        }
 
 
        public double GetRandomNumber(double minimum, double maximum)
 
        {
 
            Random random = new Random();
 
            return random.NextDouble() * (maximum - minimum) + minimum;
 
        }
 
 
        #endregion
 
 
    }
 
}
 
//TODO: CSV logging, offline caching
Demo.WindowsForms/Source/Program.cs
Show inline comments
 
using System;
 
using System.Collections;
 
using System.Collections.Generic;
 
using System.Diagnostics;
 
using System.Net;
 
using System.Net.NetworkInformation;
 
using System.Runtime.InteropServices;
 
using System.Text;
 
using System.Windows.Forms;
 
using System.IO;
 
using System.IO.Ports;
 
using System.Threading;
 
 
namespace Demo.WindowsForms
 
{
 
   class Program
 
   {
 
      /// <summary>
 
      /// The main entry point for the application.
 
      /// </summary>
 
      /// 
 
       // Instantiate the communications port 
 
       private SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
 
       static MainForm windowGUI;
 
 
      [STAThread]
 
      static void Main()
 
      {
 
          Application.SetCompatibleTextRenderingDefault(false);
 
          var program = new Program();
 
          windowGUI = new MainForm();
 
          program.SerialInitialize();
 
         Application.EnableVisualStyles();
 
         
 
         Application.Run(new MainForm());
 
         Application.Run(windowGUI);
 
      }
 
 
      //inits the serial port and event handler
 
      private void SerialInitialize()
 
      {
 
          // http://msmvps.com/blogs/coad/archive/2005/03/23/SerialPort-_2800_RS_2D00_232-Serial-COM-Port_2900_-in-C_2300_-.NET.aspx
 
          // Attach a method to be called when there is data waiting in the port's buffer
 
          port.DataReceived += new SerialDataReceivedEventHandler(ReceiveData);
 
 
          // Open the port for communications
 
          port.Open();
 
 
      }
 
 
      //process received data
 
      private void ReceiveData(object sender, SerialDataReceivedEventArgs e)
 
      {
 
          // Show all the incoming data in the port's buffer
 
          string testChk = port.ReadLine();
 
          windowGUI.ParseIncomingData(testChk);
 
      }
 
   }
 
 
   public class Dummy
 
   {
 
 
   }
 
 
   class IpInfo
 
   {
 
      public string Ip;
 
      //public int Port;
 
      //public TcpState State;
 
      //public string ProcessName;
 
 
      public string CountryName;
 
      public string RegionName;
 
      public string City;
 
      public double Latitude;
 
      public double Longitude;
 
      public DateTime CacheTime;
 
 
      //public DateTime StatusTime;
 
      //public bool TracePoint;
 
   }
 
 
   struct IpStatus
 
   {
 
      private string countryName;
 
      public string CountryName
 
      {
 
         get
 
         {
 
            return countryName;
 
         }
 
         set
 
         {
 
            countryName = value;
 
         }
 
      }
 
 
      private int connectionsCount;
 
      public int ConnectionsCount
 
      {
 
         get
 
         {
 
            return connectionsCount;
 
         }
 
         set
 
         {
 
            connectionsCount = value;
 
         }
 
      }
 
   }
 
 
   class DescendingComparer : IComparer<IpStatus>
 
   {
 
      public bool SortOnlyCountryName = false;
 
 
      public int Compare(IpStatus x, IpStatus y)
 
      {
 
         int r = 0;
 
 
         if(!SortOnlyCountryName)
 
         {
 
            r = y.ConnectionsCount.CompareTo(x.ConnectionsCount);
 
         }
 
 
         if(r == 0)
 
         {
 
            return x.CountryName.CompareTo(y.CountryName);
 
         }
 
         return r;
 
      }
 
   }
 
 
   class TraceRoute
 
   {
 
      readonly static string Data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
 
      readonly static byte[] DataBuffer;
 
      readonly static int timeout = 8888;
 
 
      static TraceRoute()
 
      {
 
         DataBuffer = Encoding.ASCII.GetBytes(Data);
 
      }
 
 
      public static List<PingReply> GetTraceRoute(string hostNameOrAddress)
 
      {
 
         var ret = GetTraceRoute(hostNameOrAddress, 1);
 
 
         return ret;
 
      }
 
 
      private static List<PingReply> GetTraceRoute(string hostNameOrAddress, int ttl)
 
      {
 
         List<PingReply> result = new List<PingReply>();
 
 
         using(Ping pinger = new Ping())
 
         {
 
            PingOptions pingerOptions = new PingOptions(ttl, true);
 
 
            PingReply reply = pinger.Send(hostNameOrAddress, timeout, DataBuffer, pingerOptions);
 
 
            //Debug.WriteLine("GetTraceRoute[" + hostNameOrAddress + "]: " + reply.RoundtripTime + "ms " + reply.Address + " -> " + reply.Status);
 
 
            if(reply.Status == IPStatus.Success)
 
            {
 
               result.Add(reply);
 
            }
 
            else if(reply.Status == IPStatus.TtlExpired)
 
            {
 
               // add the currently returned address
 
               result.Add(reply);
 
 
               // recurse to get the next address...
 
               result.AddRange(GetTraceRoute(hostNameOrAddress, ttl + 1));
 
            }
 
            else
 
            {
 
               Debug.WriteLine("GetTraceRoute: " + hostNameOrAddress + " - " + reply.Status);
 
            }
 
         }
 
 
         return result;
 
      }
 
   }
 
 
 
#if !MONO
 
   #region Managed IP Helper API
 
 
   public struct TcpTable : IEnumerable<TcpRow>
 
   {
 
      #region Private Fields
 
 
      private IEnumerable<TcpRow> tcpRows;
 
 
      #endregion
 
 
      #region Constructors
 
 
      public TcpTable(IEnumerable<TcpRow> tcpRows)
 
      {
 
         this.tcpRows = tcpRows;
 
      }
 
 
      #endregion
 
 
      #region Public Properties
 
 
      public IEnumerable<TcpRow> Rows
 
      {
 
         get
 
         {
 
            return this.tcpRows;
 
         }
 
      }
 
 
      #endregion
 
 
      #region IEnumerable<TcpRow> Members
 
 
      public IEnumerator<TcpRow> GetEnumerator()
 
      {
 
         return this.tcpRows.GetEnumerator();
 
      }
 
 
      #endregion
 
 
      #region IEnumerable Members
 
 
      IEnumerator IEnumerable.GetEnumerator()
 
      {
 
         return this.tcpRows.GetEnumerator();
 
      }
 
 
      #endregion
 
   }
 
 
   public struct TcpRow
 
   {
 
      #region Private Fields
 
 
      private IPEndPoint localEndPoint;
 
      private IPEndPoint remoteEndPoint;
 
      private TcpState state;
 
      private int processId;
 
 
      #endregion
 
 
      #region Constructors
 
 
      public TcpRow(IpHelper.TcpRow tcpRow)
 
      {
 
         this.state = tcpRow.state;
 
         this.processId = tcpRow.owningPid;
 
 
         int localPort = (tcpRow.localPort1 << 8) + (tcpRow.localPort2) + (tcpRow.localPort3 << 24) + (tcpRow.localPort4 << 16);
 
         long localAddress = tcpRow.localAddr;
 
         this.localEndPoint = new IPEndPoint(localAddress, localPort);
 
 
         int remotePort = (tcpRow.remotePort1 << 8) + (tcpRow.remotePort2) + (tcpRow.remotePort3 << 24) + (tcpRow.remotePort4 << 16);
 
         long remoteAddress = tcpRow.remoteAddr;
 
         this.remoteEndPoint = new IPEndPoint(remoteAddress, remotePort);
 
      }
 
 
      #endregion
 
 
      #region Public Properties
 
 
      public IPEndPoint LocalEndPoint
 
      {
 
         get
 
         {
 
            return this.localEndPoint;
 
         }
 
      }
 
 
      public IPEndPoint RemoteEndPoint
 
      {
 
         get
 
         {
 
            return this.remoteEndPoint;
 
         }
 
      }
 
 
      public TcpState State
 
      {
 
         get
 
         {
 
            return this.state;
 
         }
 
      }
 
 
      public int ProcessId
 
      {
 
         get
 
         {
 
            return this.processId;
 
         }
 
      }
 
 
      #endregion
 
   }
 
 
   public static class ManagedIpHelper
 
   {
 
      public static readonly List<TcpRow> TcpRows = new List<TcpRow>();
 
 
      #region Public Methods
 
 
      public static void UpdateExtendedTcpTable(bool sorted)
 
      {
 
         TcpRows.Clear();
 
 
         IntPtr tcpTable = IntPtr.Zero;
 
         int tcpTableLength = 0;
 
 
         if(IpHelper.GetExtendedTcpTable(tcpTable, ref tcpTableLength, sorted, IpHelper.AfInet, IpHelper.TcpTableType.OwnerPidConnections, 0) != 0)
 
         {
 
            try
 
            {
 
               tcpTable = Marshal.AllocHGlobal(tcpTableLength);
 
               if(IpHelper.GetExtendedTcpTable(tcpTable, ref tcpTableLength, true, IpHelper.AfInet, IpHelper.TcpTableType.OwnerPidConnections, 0) == 0)
 
               {
 
                  IpHelper.TcpTable table = (IpHelper.TcpTable)Marshal.PtrToStructure(tcpTable, typeof(IpHelper.TcpTable));
 
 
                  IntPtr rowPtr = (IntPtr)((long)tcpTable + Marshal.SizeOf(table.Length));
 
                  for(int i = 0; i < table.Length; ++i)
 
                  {
 
                     TcpRows.Add(new TcpRow((IpHelper.TcpRow)Marshal.PtrToStructure(rowPtr, typeof(IpHelper.TcpRow))));
 
                     rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(typeof(IpHelper.TcpRow)));
 
                  }
 
               }
 
            }
 
            finally
 
            {
 
               if(tcpTable != IntPtr.Zero)
 
               {
 
                  Marshal.FreeHGlobal(tcpTable);
 
               }
 
            }
 
         }
 
      }
 
 
      #endregion
 
   }
 
 
   #endregion
 
 
   #region P/Invoke IP Helper API
 
 
   /// <summary>
 
   /// <see cref="http://msdn2.microsoft.com/en-us/library/aa366073.aspx"/>
 
   /// </summary>
 
   public static class IpHelper
 
   {
 
      #region Public Fields
 
 
      public const string DllName = "iphlpapi.dll";
 
      public const int AfInet = 2;
 
 
      #endregion
 
 
      #region Public Methods
 
 
      /// <summary>
 
      /// <see cref="http://msdn2.microsoft.com/en-us/library/aa365928.aspx"/>
 
      /// </summary>
 
      [DllImport(IpHelper.DllName, SetLastError = true)]
 
      public static extern uint GetExtendedTcpTable(IntPtr tcpTable, ref int tcpTableLength, bool sort, int ipVersion, TcpTableType tcpTableType, int reserved);
 
 
      #endregion
 
 
      #region Public Enums
 
 
      /// <summary>
 
      /// <see cref="http://msdn2.microsoft.com/en-us/library/aa366386.aspx"/>
 
      /// </summary>
 
      public enum TcpTableType
 
      {
 
         BasicListener,
 
         BasicConnections,
 
         BasicAll,
 
         OwnerPidListener,
 
         OwnerPidConnections,
 
         OwnerPidAll,
 
         OwnerModuleListener,
 
         OwnerModuleConnections,
 
         OwnerModuleAll,
 
      }
 
 
      #endregion
 
 
      #region Public Structs
 
 
      /// <summary>
 
      /// <see cref="http://msdn2.microsoft.com/en-us/library/aa366921.aspx"/>
 
      /// </summary>
 
      [StructLayout(LayoutKind.Sequential)]
 
      public struct TcpTable
 
      {
 
         public uint Length;
 
         public TcpRow row;
 
      }
 
 
      /// <summary>
 
      /// <see cref="http://msdn2.microsoft.com/en-us/library/aa366913.aspx"/>
 
      /// </summary>
 
      [StructLayout(LayoutKind.Sequential)]
 
      public struct TcpRow
 
      {
 
         public TcpState state;
 
         public uint localAddr;
 
         public byte localPort1;
 
         public byte localPort2;
 
         public byte localPort3;
 
         public byte localPort4;
 
         public uint remoteAddr;
 
         public byte remotePort1;
 
         public byte remotePort2;
 
         public byte remotePort3;
 
         public byte remotePort4;
 
         public int owningPid;
 
      }
 
 
      #endregion
 
   }
 
 
   #endregion
 
#endif
 
}
0 comments (0 inline, 0 general)