Example #1
0
        protected override void ImportMethod()
        {
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORT, STR_DOWNLOAD, 1, 0))
            {
                using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                using (System.Net.WebClient wc = new System.Net.WebClient())
                {
                    wc.DownloadFile("http://www.globalcaching.eu/service/cachedistance.aspx?country=Netherlands&prefix=GC", tmp.Path);

                    using (var fs = System.IO.File.OpenRead(tmp.Path))
                    using (ZipInputStream s = new ZipInputStream(fs))
                    {
                        ZipEntry theEntry = s.GetNextEntry();
                        byte[] data = new byte[1024];
                        if (theEntry != null)
                        {
                            StringBuilder sb = new StringBuilder();
                            while (true)
                            {
                                int size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    if (sb.Length == 0 && data[0] == 0xEF && size > 2)
                                    {
                                        sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 3, size - 3));
                                    }
                                    else
                                    {
                                        sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 0, size));
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }

                            XmlDocument doc = new XmlDocument();
                            doc.LoadXml(sb.ToString());
                            XmlElement root = doc.DocumentElement;
                            XmlNodeList nl = root.SelectNodes("wp");
                            if (nl != null)
                            {
                                Core.Geocaches.AddCustomAttribute(CUSTOM_ATTRIBUTE);
                                foreach (XmlNode n in nl)
                                {
                                    var gc = Utils.DataAccess.GetGeocache(Core.Geocaches, n.Attributes["code"].InnerText);
                                    if (gc != null)
                                    {
                                        string dist = Utils.Conversion.StringToDouble(n.Attributes["dist"].InnerText).ToString("000.0");
                                        gc.SetCustomAttribute(CUSTOM_ATTRIBUTE, dist);
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
Example #2
0
        protected override void ImportMethod()
        {
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORT, STR_DOWNLOAD, 1, 0))
            {
                using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                    using (System.Net.WebClient wc = new System.Net.WebClient())
                    {
                        wc.DownloadFile(string.Format("http://www.globalcaching.eu/service/cachedistance.aspx?country=Netherlands&prefix=GC&token={0}", System.Web.HttpUtility.UrlEncode(Core.GeocachingComAccount.APIToken)), tmp.Path);

                        using (var fs = System.IO.File.OpenRead(tmp.Path))
                            using (ZipInputStream s = new ZipInputStream(fs))
                            {
                                ZipEntry theEntry = s.GetNextEntry();
                                byte[]   data     = new byte[1024];
                                if (theEntry != null)
                                {
                                    StringBuilder sb = new StringBuilder();
                                    while (true)
                                    {
                                        int size = s.Read(data, 0, data.Length);
                                        if (size > 0)
                                        {
                                            if (sb.Length == 0 && data[0] == 0xEF && size > 2)
                                            {
                                                sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 3, size - 3));
                                            }
                                            else
                                            {
                                                sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 0, size));
                                            }
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }

                                    XmlDocument doc = new XmlDocument();
                                    doc.LoadXml(sb.ToString());
                                    XmlElement  root = doc.DocumentElement;
                                    XmlNodeList nl   = root.SelectNodes("wp");
                                    if (nl != null)
                                    {
                                        Core.Geocaches.AddCustomAttribute(CUSTOM_ATTRIBUTE);
                                        foreach (XmlNode n in nl)
                                        {
                                            var gc = Utils.DataAccess.GetGeocache(Core.Geocaches, n.Attributes["code"].InnerText);
                                            if (gc != null)
                                            {
                                                string dist = Utils.Conversion.StringToDouble(n.Attributes["dist"].InnerText).ToString("000.0");
                                                gc.SetCustomAttribute(CUSTOM_ATTRIBUTE, dist);
                                            }
                                        }
                                    }
                                }
                            }
                    }
            }
        }
        public void garminPluginReady()
        {
            Dispatcher.BeginInvoke((Action)(() =>
            {
                _pluginready = true;
                if (_started && !_cancled)
                {
                    if (_index >= _gcList.Count)
                    {
                        Close();
                    }
                    else
                    {
                        List <Core.Data.Geocache> gcList = new List <Core.Data.Geocache>();
                        gcList.Add(_gcList[_index]);

                        GPX.Export gpxGenerator = new Export(gcList, Version.Parse(Core.Settings.Default.GPXVersion));
                        using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(true))
                        {
                            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.UTF8))
                            {
                                //generate header
                                sw.Write(gpxGenerator.Start());
                                //preserve mem and do for each cache the export
                                for (int i = 0; i < gpxGenerator.Count; i++)
                                {
                                    sw.WriteLine(gpxGenerator.Next());
                                    if (Core.Settings.Default.GPXAddChildWaypoints)
                                    {
                                        string s = gpxGenerator.WaypointData();
                                        if (!string.IsNullOrEmpty(s))
                                        {
                                            sw.WriteLine(s);
                                        }
                                    }
                                }
                                //finalize
                                sw.Write(gpxGenerator.Finish());
                            }
                            _index++;
                            progBar.Value = _index;
                            _pluginready = false;
                            executeScript("uploadGpx", new object[] { System.IO.File.ReadAllText(gpxFile.Path), string.Format("{0}.gpx", gcList[0].Code) });
                        }
                    }
                }
            }));
        }
 private void button2_Click(object sender, EventArgs e)
 {
     using (GarminCommunicatorForm dlg = new GarminCommunicatorForm())
     {
         if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         {
             try
             {
                 using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                 {
                     System.IO.File.WriteAllText(tmp.Path, dlg.FileContents);
                     processGeocacheVisitsFile(System.IO.File.ReadAllLines((tmp.Path)));
                 }
             }
             catch
             {
             }
         }
     }
 }
        public ExportGarminCommunicatorWindow(List <Core.Data.Geocache> gcList)
            : this()
        {
            _gcList         = gcList;
            progBar.Maximum = gcList.Count();
            webBrowser1.ObjectForScripting = new webBrowserScriptingCallback(this);
            webBrowser1.LoadCompleted     += webBrowser1_LoadCompleted;
            webBrowser1.Navigated         += webBrowser1_Navigated;

            //DisplayHtml(Utils.ResourceHelper.GetEmbeddedTextFile("/GPX/ExportGarminCommunicatorWindow.html"));
            try
            {
                System.IO.TemporaryFile tmpFile = new System.IO.TemporaryFile(true);
                Utils.ResourceHelper.SaveToFile("/GPX/ExportGarminCommunicatorWindow.html", tmpFile.Path, true);
                webBrowser1.Navigate(string.Format("file://{0}", tmpFile.Path));
            }
            catch (Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }
        }
        public ExportGarminCommunicatorWindow(List<Core.Data.Geocache> gcList)
            : this()
        {
            _gcList = gcList;
            progBar.Maximum = gcList.Count();
            webBrowser1.ObjectForScripting = new webBrowserScriptingCallback(this);
            webBrowser1.LoadCompleted += webBrowser1_LoadCompleted;
            webBrowser1.Navigated += webBrowser1_Navigated;

            //DisplayHtml(Utils.ResourceHelper.GetEmbeddedTextFile("/GPX/ExportGarminCommunicatorWindow.html"));
            try
            {
                System.IO.TemporaryFile tmpFile = new System.IO.TemporaryFile(true);
                Utils.ResourceHelper.SaveToFile("/GPX/ExportGarminCommunicatorWindow.html", tmpFile.Path, true);
                webBrowser1.Navigate(string.Format("file://{0}", tmpFile.Path));
            }
            catch(Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }
        }
Example #7
0
        public string WaypointData()
        {
            if (_activeGcg == null)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                sb.AppendLine("<gpx xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" version=\"1.0\" creator=\"Globalcaching. http://www.globalcaching.eu\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0 http://www.groundspeak.com/cache/1/0/cache.xsd\" xmlns=\"http://www.topografix.com/GPX/1/0\">");
                sb.AppendLine("  <name>Waypoints for Cache Listings Generated by Globalcaching Application</name>");
                sb.AppendLine("  <desc>This is a list of supporting waypoints for caches generated by Globalcaching App</desc>");
                sb.AppendLine("  <author>Globalcaching</author>");
                sb.AppendLine("  <url>http://www.globalcaching.eu</url>");
                sb.AppendLine("  <urlname>Geocaching - High Tech Treasure Hunting</urlname>");
                sb.AppendLine("  <email>[email protected]</email>");
                sb.AppendLine(string.Format("  <time>{0}Z</time>", DateTime.Now.ToUniversalTime().ToString("s")));
                sb.AppendLine("  <keywords>cache, geocache, waypoints</keywords>");
                sb.AppendLine(string.Format("  <bounds minlat=\"{0}\" minlon=\"{1}\" maxlat=\"{2}\" maxlon=\"{3}\" />",
                     _gcList.Min(x => x.Lat).ToString().Replace(',', '.'),
                     _gcList.Min(x => x.Lon).ToString().Replace(',', '.'),
                     _gcList.Max(x => x.Lat).ToString().Replace(',', '.'),
                     _gcList.Max(x => x.Lon).ToString().Replace(',', '.')));
                return sb.ToString();
            }
            else
            {
                /*
                 *   <wpt lat="50.908867" lon="5.435833">
                        <time>2010-06-22T11:05:21.31</time>
                        <name>0026K5Z</name>
                        <cmt>Laat hier je cachemobiel even uitrusten en doe het laatste stukje te voet</cmt>
                        <desc>Parking</desc>
                        <url>http://www.geocaching.com/seek/wpt.aspx?WID=565497fc-1de4-4f36-8661-da9d0f7848e5</url>
                        <urlname>Parking</urlname>
                        <sym>Parking Area</sym>
                        <type>Waypoint|Parking Area</type>
                      </wpt>
                 */
                string result = "";
                bool hasContent = false;
                XmlDocument doc = new XmlDocument();
                XmlElement root = doc.CreateElement("root");
                doc.AppendChild(root);
                List<Framework.Data.Waypoint> wpts = Utils.DataAccess.GetWaypointsFromGeocache(_core.Waypoints, _activeGcg.Code);
                foreach (var wp in wpts)
                {
                    if (wp.Lat != null && wp.Lon != null)
                    {
                        hasContent = true;

                        XmlElement wpt = doc.CreateElement("wpt");
                        XmlAttribute attr = doc.CreateAttribute("lat");
                        XmlText txt = doc.CreateTextNode(wp.Lat.ToString().Replace(',', '.'));
                        attr.AppendChild(txt);
                        wpt.Attributes.Append(attr);
                        attr = doc.CreateAttribute("lon");
                        txt = doc.CreateTextNode(wp.Lon.ToString().Replace(',', '.'));
                        attr.AppendChild(txt);
                        wpt.Attributes.Append(attr);
                        root.AppendChild(wpt);

                        XmlElement el = doc.CreateElement("time");
                        txt = doc.CreateTextNode(string.Format("{0}Z",wp.Time.ToString("s")));
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("name");
                        txt = doc.CreateTextNode(wp.Code);
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("desc");
                        if (string.IsNullOrEmpty(wp.Description))
                        {
                            txt = doc.CreateTextNode(wp.Description);
                        }
                        else
                        {
                            txt = doc.CreateTextNode(wp.WPType.Name);
                        }
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("url");
                        txt = doc.CreateTextNode(wp.Url);
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("urlname");
                        if (string.IsNullOrEmpty(wp.UrlName))
                        {
                            txt = doc.CreateTextNode(wp.Description);
                        }
                        else
                        {
                            txt = doc.CreateTextNode(wp.UrlName);
                        }
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("sym");
                        txt = doc.CreateTextNode(wp.WPType.Name);
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("type");
                        txt = doc.CreateTextNode(string.Format("Waypoint|{0}", wp.WPType.Name));
                        el.AppendChild(txt);
                        wpt.AppendChild(el);
                    }
                }
                if (hasContent)
                {
                    using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                    {
                        doc.Save(tmp.Path);
                        result = System.IO.File.ReadAllText(tmp.Path).Replace("</root>", "").Replace("<root>\r\n", "").Trim();
                    }
                }
                return validateXml(result);
            }
        }
        public string WaypointData()
        {
            if (_activeGcg == null)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                sb.AppendLine("<gpx xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" version=\"1.0\" creator=\"Globalcaching. http://www.globalcaching.eu\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0 http://www.groundspeak.com/cache/1/0/cache.xsd\" xmlns=\"http://www.topografix.com/GPX/1/0\">");
                sb.AppendLine("  <name>Waypoints for Cache Listings Generated by Globalcaching Application</name>");
                sb.AppendLine("  <desc>This is a list of supporting waypoints for caches generated by Globalcaching App</desc>");
                sb.AppendLine("  <author>Globalcaching</author>");
                sb.AppendLine("  <url>http://www.globalcaching.eu</url>");
                sb.AppendLine("  <urlname>Geocaching - High Tech Treasure Hunting</urlname>");
                sb.AppendLine("  <email>[email protected]</email>");
                sb.AppendLine(string.Format("  <time>{0}Z</time>", DateTime.Now.ToUniversalTime().ToString("s")));
                sb.AppendLine("  <keywords>cache, geocache, waypoints</keywords>");
                sb.AppendLine(string.Format("  <bounds minlat=\"{0}\" minlon=\"{1}\" maxlat=\"{2}\" maxlon=\"{3}\" />",
                 _minLat.ToString(CultureInfo.InvariantCulture),
                 _minLon.ToString(CultureInfo.InvariantCulture),
                 _maxLat.ToString(CultureInfo.InvariantCulture),
                 _maxLon.ToString(CultureInfo.InvariantCulture)
                ));
                return sb.ToString();
            }
            else
            {
                /*
                 *   <wpt lat="50.908867" lon="5.435833">
                        <time>2010-06-22T11:05:21.31</time>
                        <name>0026K5Z</name>
                        <cmt>Laat hier je cachemobiel even uitrusten en doe het laatste stukje te voet</cmt>
                        <desc>Parking</desc>
                        <url>http://www.geocaching.com/seek/wpt.aspx?WID=565497fc-1de4-4f36-8661-da9d0f7848e5</url>
                        <urlname>Parking</urlname>
                        <sym>Parking Area</sym>
                        <type>Waypoint|Parking Area</type>
                      </wpt>
                 */
                string result = "";
                bool hasContent = false;
                XmlDocument doc = new XmlDocument();
                XmlElement root = doc.CreateElement("root");
                doc.AppendChild(root);
                var wpts = _db.Fetch<DataTypes.GSAKWaypoints, DataTypes.GSAKWayMemo, WaypointPoco>((a, b) => { return new WaypointPoco() { Waypoints = a, WayMemo = b }; }, "select Waypoints.*, WayMemo.* from Waypoints left join WayMemo on Waypoints.cParent = WayMemo.cParent where Waypoints.cParent=@0", _activeGcg.Caches.Code);
                foreach (var wp in wpts)
                {
                    if (wp.Waypoints != null
                        && string.IsNullOrEmpty(wp.Waypoints.cLat)
                        && string.IsNullOrEmpty(wp.Waypoints.cLon)
                        && !wp.Waypoints.cLat.StartsWith("0.0")
                        && !wp.Waypoints.cLon.StartsWith("0.0")
                        )
                    {
                        hasContent = true;

                        XmlElement wpt = doc.CreateElement("wpt");
                        XmlAttribute attr = doc.CreateAttribute("lat");
                        XmlText txt = doc.CreateTextNode(wp.Waypoints.cLat);
                        attr.AppendChild(txt);
                        wpt.Attributes.Append(attr);
                        attr = doc.CreateAttribute("lon");
                        txt = doc.CreateTextNode(wp.Waypoints.cLon);
                        attr.AppendChild(txt);
                        wpt.Attributes.Append(attr);
                        root.AppendChild(wpt);

                        XmlElement el = doc.CreateElement("time");
                        txt = doc.CreateTextNode(string.Format("{0}Z",wp.Waypoints.cDate.ToString("s")));
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("name");
                        txt = doc.CreateTextNode(wp.Waypoints.cCode);
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("cmt");
                        txt = doc.CreateTextNode(wp.WayMemo == null ? "" : wp.WayMemo.cComment ?? "");
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("desc");
                        txt = doc.CreateTextNode(wp.Waypoints.cType);
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("url");
                        txt = doc.CreateTextNode(wp.WayMemo == null ? "" : wp.WayMemo.cUrl ?? "");
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("urlname");
                        txt = doc.CreateTextNode(wp.Waypoints.cType);
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("sym");
                        txt = doc.CreateTextNode(wp.Waypoints.cType);
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("type");
                        txt = doc.CreateTextNode(string.Format("Waypoint|{0}", wp.Waypoints.cType));
                        el.AppendChild(txt);
                        wpt.AppendChild(el);
                    }
                }
                if (hasContent)
                {
                    using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                    {
                        doc.Save(tmp.Path);
                        result = System.IO.File.ReadAllText(tmp.Path).Replace("</root>", "").Replace("<root>\r\n", "").Trim();
                    }
                }
                return validateXml(result);
            }
        }
Example #9
0
        public string Next()
        {
            string      result = "";
            XmlDocument doc    = new XmlDocument();

            if (_index < _gcList.Count)
            {
                Core.Data.Geocache gc = _gcList[_index];
                _activeGcg = gc;

                XmlElement   wpt  = doc.CreateElement("wpt");
                XmlAttribute attr = doc.CreateAttribute("lat");
                XmlText      txt  = doc.CreateTextNode(gc.CustomLat == null ? gc.Lat.ToString().Replace(',', '.') : gc.CustomLat.ToString().Replace(',', '.'));
                attr.AppendChild(txt);
                wpt.Attributes.Append(attr);
                attr = doc.CreateAttribute("lon");
                txt  = doc.CreateTextNode(gc.CustomLon == null ? gc.Lon.ToString().Replace(',', '.') : gc.CustomLon.ToString().Replace(',', '.'));
                attr.AppendChild(txt);
                wpt.Attributes.Append(attr);
                doc.AppendChild(wpt);

                XmlElement el = doc.CreateElement("time");
                txt = doc.CreateTextNode(string.Format("{0}Z", gc.PublishedTime.ToString("s")));
                el.AppendChild(txt);
                wpt.AppendChild(el);

                string nameValue;
                if (Core.Settings.Default.GPXUseNameForGCCode)
                {
                    nameValue = transformedGeocacheName(gc.Name ?? "");
                }
                else
                {
                    nameValue = gc.Code;
                }
                el = doc.CreateElement("name");
                if (gc.ContainsCustomLatLon)
                {
                    txt = doc.CreateTextNode(string.Format("{0}{1}", Core.Settings.Default.GPXExtraCoordPrefix ?? "", nameValue));
                }
                else
                {
                    txt = doc.CreateTextNode(nameValue);
                }
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el = doc.CreateElement("desc");
                if (Core.Settings.Default.GPXUseHintsForDescription)
                {
                    txt = doc.CreateTextNode(gc.EncodedHints ?? "");
                }
                else
                {
                    txt = doc.CreateTextNode(string.Format("{0} by {1}, {2} ({3}/{4})", transformedGeocacheName(gc.Name), gc.Owner, gc.GeocacheType.GPXTag, gc.Difficulty.ToString("0.#").Replace(',', '.'), gc.Terrain.ToString("0.#").Replace(',', '.')));
                }
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el  = doc.CreateElement("url");
                txt = doc.CreateTextNode(gc.Url);
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el  = doc.CreateElement("urlname");
                txt = doc.CreateTextNode(transformedGeocacheName(gc.Name));
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el = doc.CreateElement("sym");
                if (gc.Found)
                {
                    txt = doc.CreateTextNode("Geocache Found");
                }
                else
                {
                    txt = doc.CreateTextNode("Geocache");
                }
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el  = doc.CreateElement("type");
                txt = doc.CreateTextNode(string.Format("Geocache|{0}", gc.GeocacheType.GPXTag));
                el.AppendChild(txt);
                wpt.AppendChild(el);

                XmlElement cache = doc.CreateElement("groundspeak_cache");
                wpt.AppendChild(cache);
                attr = doc.CreateAttribute("id");
                txt  = doc.CreateTextNode(Utils.Conversion.GetCacheIDFromCacheCode(gc.Code).ToString());
                attr.AppendChild(txt);
                cache.Attributes.Append(attr);

                attr = doc.CreateAttribute("available");
                txt  = doc.CreateTextNode(gc.Available.ToString().ToLower());
                attr.AppendChild(txt);
                cache.Attributes.Append(attr);

                attr = doc.CreateAttribute("archived");
                txt  = doc.CreateTextNode(gc.Archived.ToString().ToLower());
                attr.AppendChild(txt);
                cache.Attributes.Append(attr);

                if (_gpxVersion >= V102)
                {
                    attr = doc.CreateAttribute("memberonly");
                    txt  = doc.CreateTextNode(gc.MemberOnly.ToString().ToLower());
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);

                    attr = doc.CreateAttribute("customcoords");
                    txt  = doc.CreateTextNode(gc.ContainsCustomLatLon.ToString().ToLower());
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);

                    attr = doc.CreateAttribute("_xmlns_groundspeak");
                    txt  = doc.CreateTextNode("http://www.groundspeak.com/cache/1/0/2");
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);
                }
                else if (_gpxVersion == V101)
                {
                    attr = doc.CreateAttribute("_xmlns_groundspeak");
                    txt  = doc.CreateTextNode("http://www.groundspeak.com/cache/1/0/1");
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);
                }
                else
                {
                    attr = doc.CreateAttribute("_xmlns_groundspeak");
                    txt  = doc.CreateTextNode("http://www.groundspeak.com/cache/1/0");
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);
                }

                el  = doc.CreateElement("groundspeak_name");
                txt = doc.CreateTextNode(transformedGeocacheName(gc.Name));
                el.AppendChild(txt);
                cache.AppendChild(el);

                el  = doc.CreateElement("groundspeak_placed_by");
                txt = doc.CreateTextNode(gc.PlacedBy);
                el.AppendChild(txt);
                cache.AppendChild(el);

                el  = doc.CreateElement("groundspeak_owner");
                txt = doc.CreateTextNode(gc.Owner);
                el.AppendChild(txt);
                cache.AppendChild(el);
                if (_gpxVersion >= V102)
                {
                    attr = doc.CreateAttribute("id");
                    txt  = doc.CreateTextNode(gc.OwnerId);
                    attr.AppendChild(txt);
                    el.Attributes.Append(attr);
                }

                el  = doc.CreateElement("groundspeak_type");
                txt = doc.CreateTextNode(gc.GeocacheType.GPXTag);
                el.AppendChild(txt);
                cache.AppendChild(el);
                if (_gpxVersion >= V102)
                {
                    attr = doc.CreateAttribute("id");
                    txt  = doc.CreateTextNode(gc.GeocacheType.ID.ToString());
                    attr.AppendChild(txt);
                    el.Attributes.Append(attr);
                }

                el  = doc.CreateElement("groundspeak_container");
                txt = doc.CreateTextNode(gc.Container.Name);
                el.AppendChild(txt);
                cache.AppendChild(el);
                if (_gpxVersion >= V102)
                {
                    attr = doc.CreateAttribute("id");
                    txt  = doc.CreateTextNode(gc.Container.ID.ToString());
                    attr.AppendChild(txt);
                    el.Attributes.Append(attr);
                }

                if (_gpxVersion >= V101)
                {
                    if (gc.AttributeIds.Count > 0)
                    {
                        XmlElement attrs = doc.CreateElement("groundspeak_attributes");
                        cache.AppendChild(attrs);
                        foreach (int attrId in gc.AttributeIds)
                        {
                            int id = (int)Math.Abs(attrId);

                            el  = doc.CreateElement("groundspeak_attribute");
                            txt = doc.CreateTextNode(Utils.DataAccess.GetGeocacheAttribute(id).Name);
                            el.AppendChild(txt);
                            attrs.AppendChild(el);
                            attr = doc.CreateAttribute("id");
                            txt  = doc.CreateTextNode(id.ToString());
                            attr.AppendChild(txt);
                            el.Attributes.Append(attr);

                            attr = doc.CreateAttribute("inc");
                            if (attrId < 0)
                            {
                                txt = doc.CreateTextNode("0");
                            }
                            else
                            {
                                txt = doc.CreateTextNode("1");
                            }
                            attr.AppendChild(txt);
                            el.Attributes.Append(attr);
                        }
                    }
                }

                el  = doc.CreateElement("groundspeak_difficulty");
                txt = doc.CreateTextNode(gc.Difficulty.ToString("0.#").Replace(',', '.'));
                el.AppendChild(txt);
                cache.AppendChild(el);

                el  = doc.CreateElement("groundspeak_terrain");
                txt = doc.CreateTextNode(gc.Terrain.ToString("0.#").Replace(',', '.'));
                el.AppendChild(txt);
                cache.AppendChild(el);

                el  = doc.CreateElement("groundspeak_country");
                txt = doc.CreateTextNode(gc.Country ?? "");
                el.AppendChild(txt);
                cache.AppendChild(el);

                el  = doc.CreateElement("groundspeak_state");
                txt = doc.CreateTextNode(gc.State ?? "");
                el.AppendChild(txt);
                cache.AppendChild(el);

                el = doc.CreateElement("groundspeak_short_description");
                StringBuilder sb = new StringBuilder();
                if (Core.Settings.Default.GPXAddExtraInfo)
                {
                    //cachetype
                    //placed by
                    //last updated
                    //last found (not added yet)
                    //atributes
                    if (gc.ShortDescriptionInHtml)
                    {
                        sb.Append("<p>");
                        sb.AppendFormat("<b>{0}</b>: {1}<br />", System.Web.HttpUtility.HtmlEncode(Localization.TranslationManager.Instance.Translate("CacheType")), System.Web.HttpUtility.HtmlEncode(Localization.TranslationManager.Instance.Translate(gc.GeocacheType.Name)));
                        sb.AppendFormat("<b>{0}</b>: {1}<br />", System.Web.HttpUtility.HtmlEncode(Localization.TranslationManager.Instance.Translate("Owner")), System.Web.HttpUtility.HtmlEncode(gc.Owner ?? ""));
                        sb.AppendFormat("<b>{0}</b>: {1}<br />", System.Web.HttpUtility.HtmlEncode(Localization.TranslationManager.Instance.Translate("LastUpdated")), System.Web.HttpUtility.HtmlEncode(gc.DataFromDate.ToString("d")));
                        sb.AppendFormat("<b>{0}</b>:<br />", System.Web.HttpUtility.HtmlEncode(Localization.TranslationManager.Instance.Translate("Attributes")));
                        foreach (int attrId in gc.AttributeIds)
                        {
                            int id = (int)Math.Abs(attrId);
                            if (attrId < 0)
                            {
                                sb.AppendFormat(string.Format("{0} {1}<br />", System.Web.HttpUtility.HtmlEncode(Localization.TranslationManager.Instance.Translate("No")), System.Web.HttpUtility.HtmlEncode(Localization.TranslationManager.Instance.Translate(Utils.DataAccess.GetGeocacheAttribute(id).Name))));
                            }
                            else
                            {
                                sb.AppendFormat(string.Format("{0} {1}<br />", System.Web.HttpUtility.HtmlEncode(Localization.TranslationManager.Instance.Translate("Yes")), System.Web.HttpUtility.HtmlEncode(Localization.TranslationManager.Instance.Translate(Utils.DataAccess.GetGeocacheAttribute(id).Name))));
                            }
                        }
                        sb.Append("</p>");
                    }
                    else
                    {
                        sb.AppendLine();
                        sb.AppendFormat("{0}: {1}\r\n", Localization.TranslationManager.Instance.Translate("CacheType"), Localization.TranslationManager.Instance.Translate(gc.GeocacheType.Name));
                        sb.AppendFormat("{0}: {1}\r\n", Localization.TranslationManager.Instance.Translate("Owner"), gc.Owner ?? "");
                        sb.AppendFormat("{0}: {1}\r\n", Localization.TranslationManager.Instance.Translate("LastUpdated"), gc.DataFromDate.ToString("d"));
                        sb.AppendFormat("{0}:\r\n", Localization.TranslationManager.Instance.Translate("Attributes"));
                        foreach (int attrId in gc.AttributeIds)
                        {
                            int id = (int)Math.Abs(attrId);
                            if (attrId < 0)
                            {
                                sb.AppendFormat(string.Format("{0} {1}\r\n", Localization.TranslationManager.Instance.Translate("No"), Localization.TranslationManager.Instance.Translate(Utils.DataAccess.GetGeocacheAttribute(id).Name)));
                            }
                            else
                            {
                                sb.AppendFormat(string.Format("{0} {1}\r\n", Localization.TranslationManager.Instance.Translate("Yes"), Localization.TranslationManager.Instance.Translate(Utils.DataAccess.GetGeocacheAttribute(id).Name)));
                            }
                        }
                        sb.AppendLine();
                    }
                }
                if (Core.Settings.Default.GPXAddFieldnotesToDescription && gc.ContainsNote)
                {
                    if (gc.ShortDescriptionInHtml)
                    {
                        if (!string.IsNullOrEmpty(gc.PersonalNote))
                        {
                            sb.AppendFormat("<p>{0}</p><br />", System.Web.HttpUtility.HtmlEncode(gc.PersonalNote));
                        }
                        if (!string.IsNullOrEmpty(gc.Notes))
                        {
                            if (gc.Notes.StartsWith("<p>", StringComparison.OrdinalIgnoreCase))
                            {
                                sb.AppendFormat("{0}<br />", gc.Notes);
                            }
                            else
                            {
                                sb.AppendFormat("<p>{0}</p><br />", gc.Notes);
                            }
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(gc.PersonalNote))
                        {
                            sb.AppendFormat("{0}\r\n\r\n", gc.PersonalNote);
                        }
                        if (!string.IsNullOrEmpty(gc.Notes))
                        {
                            sb.AppendFormat("{0}\r\n\r\n", gc.Notes);
                        }
                    }
                    sb.Append(gc.ShortDescription ?? "");
                }
                else
                {
                    sb.Append(gc.ShortDescription ?? "");
                }
                txt = doc.CreateTextNode(sb.ToString());
                el.AppendChild(txt);
                cache.AppendChild(el);
                attr = doc.CreateAttribute("html");
                txt  = doc.CreateTextNode(gc.ShortDescriptionInHtml.ToString().ToLower());
                attr.AppendChild(txt);
                el.Attributes.Append(attr);

                el = doc.CreateElement("groundspeak_long_description");
                if (Core.Settings.Default.GPXAddAdditionWaypointsToDescription)
                {
                    List <Core.Data.Waypoint> wpts = Utils.DataAccess.GetWaypointsFromGeocache(gc.Database, gc.Code);
                    if (wpts != null && wpts.Count > 0)
                    {
                        StringBuilder awp = new StringBuilder();
                        if (gc.LongDescriptionInHtml)
                        {
                            awp.AppendFormat("{0}<br /><br /><h2>Additiona Hidden Waypoints</h2>", gc.LongDescription ?? "");
                            awp.Append("<p>");
                            foreach (Core.Data.Waypoint wp in wpts)
                            {
                                awp.AppendFormat("{0} - {1} ({2})<br />", HttpUtility.HtmlEncode(wp.ID ?? ""), HttpUtility.HtmlEncode(wp.Description ?? ""), HttpUtility.HtmlEncode(Localization.TranslationManager.Instance.Translate(wp.WPType.Name)));
                                if (wp.Lat != null && wp.Lon != null)
                                {
                                    awp.AppendFormat("{0}<br />", HttpUtility.HtmlEncode(Utils.Conversion.GetCoordinatesPresentation((double)wp.Lat, (double)wp.Lon)));
                                }
                                else
                                {
                                    awp.Append("???<br />");
                                }
                                awp.AppendFormat("{0}<br /><br />", HttpUtility.HtmlEncode(wp.Comment ?? ""));
                            }
                            awp.Append("</p>");
                        }
                        else
                        {
                            awp.AppendFormat("{0}\r\n\r\nAdditiona Hidden Waypoints", gc.LongDescription ?? "");
                            foreach (Core.Data.Waypoint wp in wpts)
                            {
                                awp.AppendFormat("{0} - {1} ({2})\r\n", wp.ID ?? "", wp.Description ?? "", Localization.TranslationManager.Instance.Translate(wp.WPType.Name));
                                if (wp.Lat != null && wp.Lon != null)
                                {
                                    awp.AppendFormat("{0}\r\n", Utils.Conversion.GetCoordinatesPresentation((double)wp.Lat, (double)wp.Lon));
                                }
                                else
                                {
                                    awp.Append("???\r\n");
                                }
                                awp.AppendFormat("{0}\r\n\r\n", wp.Comment ?? "");
                            }
                        }
                        txt = doc.CreateTextNode(awp.ToString());
                    }
                    else
                    {
                        txt = doc.CreateTextNode(gc.LongDescription ?? "");
                    }
                }
                else
                {
                    txt = doc.CreateTextNode(gc.LongDescription ?? "");
                }
                el.AppendChild(txt);
                cache.AppendChild(el);
                attr = doc.CreateAttribute("html");
                txt  = doc.CreateTextNode(gc.LongDescriptionInHtml.ToString().ToLower());
                attr.AppendChild(txt);
                el.Attributes.Append(attr);

                el  = doc.CreateElement("groundspeak_encoded_hints");
                txt = doc.CreateTextNode(gc.EncodedHints ?? "");
                el.AppendChild(txt);
                cache.AppendChild(el);

                if (_gpxVersion >= V102)
                {
                    el  = doc.CreateElement("groundspeak_personal_note");
                    txt = doc.CreateTextNode(gc.PersonalNote ?? "");
                    el.AppendChild(txt);
                    cache.AppendChild(el);

                    el  = doc.CreateElement("groundspeak_favorite_points");
                    txt = doc.CreateTextNode(gc.Favorites.ToString());
                    el.AppendChild(txt);
                    cache.AppendChild(el);
                }

                List <Core.Data.Log> logs = Utils.DataAccess.GetLogs(gc.Database, gc.Code).Take(Core.Settings.Default.GPXMaxLogCount).ToList();
                if (logs.Count > 0)
                {
                    XmlElement logsel = doc.CreateElement("groundspeak_logs");
                    cache.AppendChild(logsel);
                    foreach (var l in logs)
                    {
                        XmlElement lel = doc.CreateElement("groundspeak_log");
                        logsel.AppendChild(lel);
                        attr = doc.CreateAttribute("id");
                        txt  = doc.CreateTextNode(l.ID);
                        attr.AppendChild(txt);
                        lel.Attributes.Append(attr);

                        el  = doc.CreateElement("groundspeak_date");
                        txt = doc.CreateTextNode(string.Format("{0}Z", l.Date.ToString("s")));
                        el.AppendChild(txt);
                        lel.AppendChild(el);

                        el  = doc.CreateElement("groundspeak_type");
                        txt = doc.CreateTextNode(l.LogType.Name);
                        el.AppendChild(txt);
                        lel.AppendChild(el);
                        if (_gpxVersion >= V102)
                        {
                            attr = doc.CreateAttribute("id");
                            txt  = doc.CreateTextNode(l.LogType.ID.ToString());
                            attr.AppendChild(txt);
                            el.Attributes.Append(attr);
                        }

                        el  = doc.CreateElement("groundspeak_finder");
                        txt = doc.CreateTextNode(l.Finder);
                        el.AppendChild(txt);
                        lel.AppendChild(el);
                        attr = doc.CreateAttribute("id");
                        txt  = doc.CreateTextNode(l.FinderId);
                        attr.AppendChild(txt);
                        el.Attributes.Append(attr);

                        el  = doc.CreateElement("groundspeak_text");
                        txt = doc.CreateTextNode(l.Text);
                        el.AppendChild(txt);
                        lel.AppendChild(el);
                        attr = doc.CreateAttribute("encoded");
                        txt  = doc.CreateTextNode(l.Encoded.ToString().ToLower());
                        attr.AppendChild(txt);
                        el.Attributes.Append(attr);
                    }
                }
                //todo, geocache images / trackables

                _index++;
            }
            using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
            {
                doc.Save(tmp.Path);
                result = System.IO.File.ReadAllText(tmp.Path);
                result = result.Replace("<groundspeak_", "<groundspeak:");
                result = result.Replace("</groundspeak_", "</groundspeak:");
                result = result.Replace("_xmlns_groundspeak", "xmlns:groundspeak");
            }
            return(validateXml(result));
        }
Example #10
0
        protected override void ExportMethod()
        {
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_EXPORTINGGPX, STR_CREATINGFILE, _gcList.Count, 0))
            {
                if (_oneGeocachePerFile)
                {
                    Utils.GPXGenerator gpxGenerator = new Utils.GPXGenerator(Core, _gcList, string.IsNullOrEmpty(PluginSettings.Instance.GPXVersionStr) ? Utils.GPXGenerator.V101 : Version.Parse(PluginSettings.Instance.GPXVersionStr));
                    gpxGenerator.UseNameForGCCode = _useName;
                    gpxGenerator.AddAdditionWaypointsToDescription = PluginSettings.Instance.AddWaypointsToDescription;
                    gpxGenerator.UseHintsForDescription            = PluginSettings.Instance.UseHintsForDescription;
                    gpxGenerator.AddFieldnotesToDescription        = PluginSettings.Instance.AddFieldNotesToDescription;
                    gpxGenerator.MaxNameLength             = PluginSettings.Instance.MaxGeocacheNameLength;
                    gpxGenerator.MinStartOfname            = PluginSettings.Instance.MinStartOfGeocacheName;
                    gpxGenerator.ExtraCoordPrefix          = PluginSettings.Instance.CorrectedNamePrefix;
                    gpxGenerator.AddExtraInfoToDescription = PluginSettings.Instance.AddExtraInfoToDescription;
                    gpxGenerator.MaxLogCount = PluginSettings.Instance.MaximumNumberOfLogs;
                    using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(false))
                    {
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.UTF8))
                        {
                            int block = 0;
                            //generate header
                            sw.Write(gpxGenerator.Start());
                            //preserve mem and do for each cache the export
                            for (int i = 0; i < gpxGenerator.Count; i++)
                            {
                                sw.WriteLine(gpxGenerator.Next());
                                if (_addChildWaypoints)
                                {
                                    string s = gpxGenerator.WaypointData();
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        sw.WriteLine(s);
                                    }
                                }
                                block++;
                                if (block > 10)
                                {
                                    block = 0;
                                    progress.UpdateProgress(STR_EXPORTINGGPX, STR_CREATINGFILE, gpxGenerator.Count, i + 1);
                                }
                            }
                            //finalize
                            sw.Write(gpxGenerator.Finish());
                        }

                        progress.UpdateProgress(STR_EXPORTINGGPX, STR_COPYINGFILE, 1, 0);
                        string filename = "geocaches.gpx";
                        if (PluginSettings.Instance.UseDatabaseNameForFileName)
                        {
                            Framework.Interfaces.IPluginInternalStorage storage = (from Framework.Interfaces.IPluginInternalStorage a in Core.GetPlugin(Framework.PluginType.InternalStorage) select a).FirstOrDefault();
                            if (storage != null)
                            {
                                var si = storage.ActiveStorageDestination;
                                if (si != null)
                                {
                                    string s   = storage.ActiveStorageDestination.Name;
                                    int    pos = s.LastIndexOf('.');
                                    if (pos < 0)
                                    {
                                        filename = string.Format("{0}.gpx", s);
                                    }
                                    else
                                    {
                                        filename = string.Format("{0}.gpx", s.Substring(0, pos));
                                    }
                                }
                            }
                        }
                        System.IO.File.Copy(gpxFile.Path, System.IO.Path.Combine(new string[] { _drive, "garmin", "gpx", filename }), true);
                    }
                }
                else
                {
                    List <Framework.Data.Geocache> gcl = new List <Framework.Data.Geocache>();
                    for (int i = 0; i < _gcList.Count; i++)
                    {
                        gcl.Clear();
                        gcl.Add(_gcList[i]);
                        Utils.GPXGenerator gpxGenerator = new Utils.GPXGenerator(Core, gcl, string.IsNullOrEmpty(PluginSettings.Instance.GPXVersionStr) ? Utils.GPXGenerator.V101 : Version.Parse(PluginSettings.Instance.GPXVersionStr));
                        gpxGenerator.UseNameForGCCode = _useName;
                        gpxGenerator.AddAdditionWaypointsToDescription = PluginSettings.Instance.AddWaypointsToDescription;
                        gpxGenerator.UseHintsForDescription            = PluginSettings.Instance.UseHintsForDescription;
                        gpxGenerator.AddFieldnotesToDescription        = PluginSettings.Instance.AddFieldNotesToDescription;
                        gpxGenerator.MaxNameLength             = PluginSettings.Instance.MaxGeocacheNameLength;
                        gpxGenerator.MinStartOfname            = PluginSettings.Instance.MinStartOfGeocacheName;
                        gpxGenerator.ExtraCoordPrefix          = PluginSettings.Instance.CorrectedNamePrefix;
                        gpxGenerator.AddExtraInfoToDescription = PluginSettings.Instance.AddExtraInfoToDescription;
                        gpxGenerator.MaxLogCount = PluginSettings.Instance.MaximumNumberOfLogs;
                        using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(true))
                        {
                            int block = 0;

                            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.ASCII))
                            {
                                //generate header
                                sw.Write(gpxGenerator.Start());
                                //preserve mem and do for each cache the export
                                sw.WriteLine(gpxGenerator.Next());
                                if (_addChildWaypoints)
                                {
                                    string s = gpxGenerator.WaypointData();
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        sw.WriteLine(s);
                                    }
                                }
                                //finalize
                                sw.Write(gpxGenerator.Finish());
                            }
                            System.IO.File.Copy(gpxFile.Path, System.IO.Path.Combine(new string[] { _drive, "garmin", "gpx", string.Format("{0}.gpx", gcl[0].Code) }), true);

                            block++;
                            if (block > 10)
                            {
                                block = 0;
                                progress.UpdateProgress(STR_EXPORTINGGPX, STR_CREATINGFILE, _gcList.Count, i + 1);
                            }
                        }
                    }
                }
            }
        }
Example #11
0
        public async Task DownloadSelectedPQ()
        {
            List <LiveAPI.LiveV6.PQData> pqs = new List <LiveAPI.LiveV6.PQData>();

            foreach (PQData p in listItems.SelectedItems)
            {
                pqs.Add(p.LiveAPIData);
            }

            using (Utils.DataUpdater upd = new Utils.DataUpdater(Core.ApplicationData.Instance.ActiveDatabase))
            {
                await Task.Run(new Action(() =>
                {
                    try
                    {
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock("DownloadingPQ", "DownloadingPQ", pqs.Count, 0, true))
                        {
                            int index = 0;
                            try
                            {
                                using (var api = new LiveAPI.GeocachingLiveV6())
                                {
                                    Import imp = new Import();
                                    foreach (LiveAPI.LiveV6.PQData pq in pqs)
                                    {
                                        if (progress.Update(pq.Name, pqs.Count, index))
                                        {
                                            LiveAPI.LiveV6.GetPocketQueryZippedFileResponse resp = api.Client.GetPocketQueryZippedFile(api.Token, pq.GUID);
                                            if (resp.Status.StatusCode == 0)
                                            {
                                                using (System.IO.TemporaryFile tf = new System.IO.TemporaryFile(true))
                                                {
                                                    System.IO.File.WriteAllBytes(tf.Path, Convert.FromBase64String(resp.ZippedFile));
                                                    imp.ImportFile(tf.Path, true);
                                                    updateProcessedPq(pq.GUID);
                                                }
                                            }
                                            else
                                            {
                                                Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp.Status.StatusMessage);
                                                break;
                                            }
                                            index++;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Core.ApplicationData.Instance.Logger.AddLog(this, e);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Core.ApplicationData.Instance.Logger.AddLog(this, e);
                    }
                }));
            }
            Close();
        }
        public void garminPluginReady()
        {
            Dispatcher.BeginInvoke((Action)(() =>
            {
                _pluginready = true;
                if (_started && !_cancled)
                {
                    if (_index >= _gcList.Count)
                    {
                        Close();
                    }
                    else
                    {
                        List<Core.Data.Geocache> gcList = new List<Core.Data.Geocache>();
                        gcList.Add(_gcList[_index]);

                        GPX.Export gpxGenerator = new Export(gcList, Version.Parse(Core.Settings.Default.GPXVersion));
                        using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(true))
                        {
                            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.UTF8))
                            {
                                //generate header
                                sw.Write(gpxGenerator.Start());
                                //preserve mem and do for each cache the export
                                for (int i = 0; i < gpxGenerator.Count; i++)
                                {
                                    sw.WriteLine(gpxGenerator.Next());
                                    if (Core.Settings.Default.GPXAddChildWaypoints)
                                    {
                                        string s = gpxGenerator.WaypointData();
                                        if (!string.IsNullOrEmpty(s))
                                        {
                                            sw.WriteLine(s);
                                        }
                                    }
                                }
                                //finalize
                                sw.Write(gpxGenerator.Finish());
                            }
                            _index++;
                            progBar.Value = _index;
                            _pluginready = false;
                            executeScript("uploadGpx", new object[] { System.IO.File.ReadAllText(gpxFile.Path), string.Format("{0}.gpx", gcList[0].Code) });
                        }
                    }
                }
            })); 
        }
 private void button2_Click(object sender, EventArgs e)
 {
     using (GarminCommunicatorForm dlg = new GarminCommunicatorForm())
     {
         if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         {
             try
             {
                 using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                 {
                     System.IO.File.WriteAllText(tmp.Path, dlg.FileContents);
                     processGeocacheVisitsFile(System.IO.File.ReadAllLines((tmp.Path)));
                 }
             }
             catch
             {
             }
         }
     }
 }
Example #14
0
        public bool LogGeocache(LiveAPI.GeocachingLiveV6 api, LogInfo logInfo, List <LiveAPI.LiveV6.Trackable> dropTbs, List <string> retrieveTbs)
        {
            bool result = false;

            try
            {
                var req = new LiveAPI.LiveV6.CreateFieldNoteAndPublishRequest();
                req.AccessToken       = api.Token;
                req.CacheCode         = logInfo.GeocacheCode;
                req.EncryptLogText    = false;
                req.FavoriteThisCache = logInfo.AddToFavorites;
                req.Note          = logInfo.LogText;
                req.PromoteToLog  = true;
                req.WptLogTypeId  = logInfo.LogType.ID;
                req.UTCDateLogged = logInfo.VisitDate.Date.AddHours(12).ToUniversalTime();
                var resp = api.Client.CreateFieldNoteAndPublish(req);
                if (resp.Status.StatusCode == 0)
                {
                    bool error = false;

                    if (Core.ApplicationData.Instance.ActiveDatabase != null)
                    {
                        var gc = Core.ApplicationData.Instance.ActiveDatabase.GeocacheCollection.GetGeocache(logInfo.GeocacheCode);
                        if (gc != null)
                        {
                            if (logInfo.LogType.AsFound)
                            {
                                gc.Found = true;
                            }
                        }
                        LiveAPI.Import.ImportLog(Core.ApplicationData.Instance.ActiveDatabase, resp.Log);
                        if (gc != null)
                        {
                            gc.ResetCachedLogData();
                        }
                    }

                    //log trackables (14=drop off, 13=retrieve from cache, 75=visited)
                    if (dropTbs != null && dropTbs.Count > 0)
                    {
                        var reqT = new LiveAPI.LiveV6.CreateTrackableLogRequest();
                        reqT.AccessToken   = api.Token;
                        reqT.LogType       = 14;
                        reqT.UTCDateLogged = logInfo.VisitDate.Date.AddHours(12).ToUniversalTime();
                        foreach (var tb in dropTbs)
                        {
                            reqT.TrackingNumber = tb.TrackingCode;
                            reqT.CacheCode      = logInfo.GeocacheCode;
                            var resp2 = api.Client.CreateTrackableLog(reqT);
                            if (resp2.Status.StatusCode != 0)
                            {
                                Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp2.Status.StatusMessage);
                                error = true;
                                //break;
                            }
                        }
                    }

                    if (retrieveTbs != null && retrieveTbs.Count > 0)
                    {
                        var reqT = new LiveAPI.LiveV6.CreateTrackableLogRequest();
                        reqT.AccessToken   = api.Token;
                        reqT.LogType       = 13;
                        reqT.UTCDateLogged = logInfo.VisitDate.Date.AddHours(12).ToUniversalTime();
                        foreach (var tb in retrieveTbs)
                        {
                            reqT.TrackingNumber = tb;
                            reqT.CacheCode      = logInfo.GeocacheCode;
                            var resp2 = api.Client.CreateTrackableLog(reqT);
                            if (resp2.Status.StatusCode != 0)
                            {
                                Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp2.Status.StatusMessage);
                                error = true;
                                //break;
                            }
                        }
                    }

                    //add log images
                    foreach (var li in logInfo.Images)
                    {
                        var uplReq = new LiveAPI.LiveV6.UploadImageToGeocacheLogRequest();
                        uplReq.AccessToken               = api.Token;
                        uplReq.LogGuid                   = resp.Log.Guid;
                        uplReq.ImageData                 = new LiveAPI.LiveV6.UploadImageData();
                        uplReq.ImageData.FileCaption     = li.Caption;
                        uplReq.ImageData.FileDescription = li.Description;
                        uplReq.ImageData.FileName        = li.Uri;

                        using (System.IO.TemporaryFile tmpFile = new System.IO.TemporaryFile(true))
                        {
                            if (Utils.ResourceHelper.ScaleImage(li.Uri, tmpFile.Path, Core.Settings.Default.LiveAPILogGeocachesMaxImageWidth, Core.Settings.Default.LiveAPILogGeocachesMaxImageHeight, Core.Settings.Default.LiveAPILogGeocachesMaxImageSizeMB, Core.Settings.Default.LiveAPILogGeocachesImageQuality, li.RotationDeg))
                            {
                                uplReq.ImageData.base64ImageData = System.Convert.ToBase64String(System.IO.File.ReadAllBytes(tmpFile.Path));
                            }
                        }
                        if (!string.IsNullOrEmpty(uplReq.ImageData.base64ImageData))
                        {
                            var resp2 = api.Client.UploadImageToGeocacheLog(uplReq);
                            if (resp2.Status.StatusCode != 0)
                            {
                                Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp2.Status.StatusMessage);
                                error = true;
                                //break;
                            }
                        }
                        else
                        {
                            error = true;
                        }
                    }

                    if (logInfo.AddToFavorites)
                    {
                        Favorites.Manager.Instance.AddFavoritedGeocache(logInfo.GeocacheCode);
                    }

                    result = true;
                }
                else
                {
                    Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp.Status.StatusMessage);
                }
            }
            catch (Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }
            return(result);
        }
Example #15
0
        protected override void ExportMethod()
        {
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_EXPORTINGGPX, STR_CREATINGFILE, _gcList.Count, 0))
            {
                if (_oneGeocachePerFile)
                {
                    Utils.GPXGenerator gpxGenerator = new Utils.GPXGenerator(Core, _gcList, string.IsNullOrEmpty(PluginSettings.Instance.GPXVersionStr) ? Utils.GPXGenerator.V101 : Version.Parse(PluginSettings.Instance.GPXVersionStr));
                    gpxGenerator.UseNameForGCCode = _useName;
                    gpxGenerator.AddAdditionWaypointsToDescription = PluginSettings.Instance.AddWaypointsToDescription;
                    gpxGenerator.UseHintsForDescription = PluginSettings.Instance.UseHintsForDescription;
                    gpxGenerator.AddFieldnotesToDescription = PluginSettings.Instance.AddFieldNotesToDescription;
                    gpxGenerator.MaxNameLength = PluginSettings.Instance.MaxGeocacheNameLength;
                    gpxGenerator.MinStartOfname = PluginSettings.Instance.MinStartOfGeocacheName;
                    gpxGenerator.ExtraCoordPrefix = PluginSettings.Instance.CorrectedNamePrefix;
                    gpxGenerator.AddExtraInfoToDescription = PluginSettings.Instance.AddExtraInfoToDescription;
                    gpxGenerator.MaxLogCount = PluginSettings.Instance.MaximumNumberOfLogs;
                    using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(false))
                    {
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.UTF8))
                        {
                            int block = 0;
                            //generate header
                            sw.Write(gpxGenerator.Start());
                            //preserve mem and do for each cache the export
                            for (int i = 0; i < gpxGenerator.Count; i++)
                            {
                                sw.WriteLine(gpxGenerator.Next());
                                if (_addChildWaypoints)
                                {
                                    string s = gpxGenerator.WaypointData();
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        sw.WriteLine(s);
                                    }
                                }
                                block++;
                                if (block > 10)
                                {
                                    block = 0;
                                    progress.UpdateProgress(STR_EXPORTINGGPX, STR_CREATINGFILE, gpxGenerator.Count, i + 1);
                                }
                            }
                            //finalize
                            sw.Write(gpxGenerator.Finish());
                        }

                        progress.UpdateProgress(STR_EXPORTINGGPX, STR_COPYINGFILE, 1, 0);
                        string filename = "geocaches.gpx";
                        if (PluginSettings.Instance.UseDatabaseNameForFileName)
                        {
                            Framework.Interfaces.IPluginInternalStorage storage = (from Framework.Interfaces.IPluginInternalStorage a in Core.GetPlugin(Framework.PluginType.InternalStorage) select a).FirstOrDefault();
                            if (storage!=null)
                            {
                                var si = storage.ActiveStorageDestination;
                                if (si != null)
                                {
                                    string s = storage.ActiveStorageDestination.Name;
                                    int pos = s.LastIndexOf('.');
                                    if (pos < 0)
                                    {
                                        filename = string.Format("{0}.gpx",s);
                                    }
                                    else
                                    {
                                        filename = string.Format("{0}.gpx",s.Substring(0,pos));
                                    }
                                }
                            }
                        }
                        System.IO.File.Copy(gpxFile.Path, System.IO.Path.Combine(new string[] { _drive, "garmin", "gpx", filename }), true);
                    }
                }
                else
                {
                    List<Framework.Data.Geocache> gcl = new List<Framework.Data.Geocache>();
                    for (int i = 0; i < _gcList.Count; i++)
                    {
                        gcl.Clear();
                        gcl.Add(_gcList[i]);
                        Utils.GPXGenerator gpxGenerator = new Utils.GPXGenerator(Core, gcl, string.IsNullOrEmpty(PluginSettings.Instance.GPXVersionStr) ? Utils.GPXGenerator.V101 : Version.Parse(PluginSettings.Instance.GPXVersionStr));
                        gpxGenerator.UseNameForGCCode = _useName;
                        gpxGenerator.AddAdditionWaypointsToDescription = PluginSettings.Instance.AddWaypointsToDescription;
                        gpxGenerator.UseHintsForDescription = PluginSettings.Instance.UseHintsForDescription;
                        gpxGenerator.AddFieldnotesToDescription = PluginSettings.Instance.AddFieldNotesToDescription;
                        gpxGenerator.MaxNameLength = PluginSettings.Instance.MaxGeocacheNameLength;
                        gpxGenerator.MinStartOfname = PluginSettings.Instance.MinStartOfGeocacheName;
                        gpxGenerator.ExtraCoordPrefix = PluginSettings.Instance.CorrectedNamePrefix;
                        gpxGenerator.AddExtraInfoToDescription = PluginSettings.Instance.AddExtraInfoToDescription;
                        gpxGenerator.MaxLogCount = PluginSettings.Instance.MaximumNumberOfLogs;
                        using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(true))
                        {
                            int block = 0;

                            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.ASCII))
                            {
                                //generate header
                                sw.Write(gpxGenerator.Start());
                                //preserve mem and do for each cache the export
                                sw.WriteLine(gpxGenerator.Next());
                                if (_addChildWaypoints)
                                {
                                    string s = gpxGenerator.WaypointData();
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        sw.WriteLine(s);
                                    }
                                }
                                //finalize
                                sw.Write(gpxGenerator.Finish());
                            }
                            System.IO.File.Copy(gpxFile.Path, System.IO.Path.Combine(new string[] { _drive, "garmin", "gpx", string.Format("{0}.gpx", gcl[0].Code) }), true);

                            block++;
                            if (block > 10)
                            {
                                block = 0;
                                progress.UpdateProgress(STR_EXPORTINGGPX, STR_CREATINGFILE, _gcList.Count, i + 1);
                            }
                        }
                    }
                }
            }
        }
Example #16
0
        public void ImportGeocacheDistance(Core.Storage.Database db)
        {
            try
            {
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ImportNLGeocacheDistance", "DownloadingData", 1, 0))
                {
                    using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                    using (System.Net.WebClient wc = new System.Net.WebClient())
                    {
                        wc.DownloadFile("http://www.globalcaching.eu/service/cachedistance.aspx?country=Netherlands&prefix=GC", tmp.Path);

                        using (var fs = System.IO.File.OpenRead(tmp.Path))
                        using (ZipInputStream s = new ZipInputStream(fs))
                        {
                            ZipEntry theEntry = s.GetNextEntry();
                            byte[] data = new byte[1024];
                            if (theEntry != null)
                            {
                                StringBuilder sb = new StringBuilder();
                                while (true)
                                {
                                    int size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        if (sb.Length == 0 && data[0] == 0xEF && size > 2)
                                        {
                                            sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 3, size - 3));
                                        }
                                        else
                                        {
                                            sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 0, size));
                                        }
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                                XmlDocument doc = new XmlDocument();
                                doc.LoadXml(sb.ToString());
                                XmlElement root = doc.DocumentElement;
                                XmlNodeList nl = root.SelectNodes("wp");
                                if (nl != null)
                                {
                                    progress.Update("SavingGeocaches", nl.Count, 0);
                                    DateTime nextUpdate = DateTime.Now.AddSeconds(1);
                                    int index = 0;
                                    foreach (XmlNode n in nl)
                                    {
                                        var gc = db.GeocacheCollection.GetGeocache(n.Attributes["code"].InnerText);
                                        if (gc != null)
                                        {
                                            gc.GeocacheDistance = Utils.Conversion.StringToDouble(n.Attributes["dist"].InnerText);
                                        }
                                        else
                                        {
                                            Core.Settings.Default.SetGeocacheDistance(n.Attributes["code"].InnerText, Utils.Conversion.StringToDouble(n.Attributes["dist"].InnerText));
                                        }
                                        index++;
                                        if (DateTime.Now>=nextUpdate)
                                        {
                                            progress.Update("SavingGeocaches", nl.Count, index);
                                            nextUpdate = DateTime.Now.AddSeconds(1);
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            }
            catch(Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }
        }
Example #17
0
        protected override void ExportMethod()
        {
            string gpxFile;
            string wptFile;
            System.IO.TemporaryFile tmp = null;
            System.IO.TemporaryFile tmpwpt = null;
            if (Properties.Settings.Default.ZipFile)
            {
                tmp = new System.IO.TemporaryFile(false);
                gpxFile = tmp.Path;
                tmpwpt = new System.IO.TemporaryFile(false);
                wptFile = tmpwpt.Path;
            }
            else
            {
                gpxFile = _filename;
                wptFile = string.Format("{0}-wpts.gpx", gpxFile.Substring(0,gpxFile.Length-4));
            }
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_EXPORTINGGPX, STR_CREATINGFILE, _gpxGenerator.Count, 0))
            {
                //create file stream (if not zipped actual file and if zipped tmp file
                using (System.IO.StreamWriter sw = System.IO.File.CreateText(gpxFile))
                using (System.IO.StreamWriter swwp = System.IO.File.CreateText(wptFile))
                {
                    int block = 0;
                    //generate header
                    sw.Write(_gpxGenerator.Start());
                    if (Properties.Settings.Default.AddWaypoints)
                    {
                        swwp.Write(_gpxGenerator.WaypointData());
                    }
                    //preserve mem and do for each cache the export
                    for (int i = 0; i < _gpxGenerator.Count; i++)
                    {
                        sw.WriteLine(_gpxGenerator.Next());
                        if (Properties.Settings.Default.AddWaypoints)
                        {
                            string s = _gpxGenerator.WaypointData();
                            if (!string.IsNullOrEmpty(s))
                            {
                                swwp.WriteLine(s);
                            }
                        }
                        block++;
                        if (block > 50)
                        {
                            block = 0;
                            progress.UpdateProgress(STR_EXPORTINGGPX, STR_CREATINGFILE, _gpxGenerator.Count, i + 1);
                        }
                    }
                    //finalize
                    sw.Write(_gpxGenerator.Finish());
                    if (Properties.Settings.Default.AddWaypoints)
                    {
                        swwp.Write(_gpxGenerator.Finish());
                    }
                }

                if (Properties.Settings.Default.ZipFile)
                {
                    try
                    {
                        List<string> filenames = new List<string>();
                        filenames.Add(gpxFile);
                        if (Properties.Settings.Default.AddWaypoints)
                        {
                            filenames.Add(wptFile);
                        }

                        using (ZipOutputStream s = new ZipOutputStream(System.IO.File.Create(_filename)))
                        {
                            s.SetLevel(9); // 0-9, 9 being the highest compression

                            byte[] buffer = new byte[4096];
                            bool wpt = false;

                            foreach (string file in filenames)
                            {

                                ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(wpt ? _filename.ToLower().Replace(".zip", "-wpts.gpx") : _filename.ToLower().Replace(".zip", ".gpx")));

                                entry.DateTime = DateTime.Now;
                                s.PutNextEntry(entry);

                                using (System.IO.FileStream fs = System.IO.File.OpenRead(file))
                                {
                                    int sourceBytes;
                                    do
                                    {
                                        sourceBytes = fs.Read(buffer, 0,
                                        buffer.Length);

                                        s.Write(buffer, 0, sourceBytes);

                                    } while (sourceBytes > 0);
                                }

                                wpt = true;
                            }
                            s.Finish();
                            s.Close();
                        }
                    }
                    catch
                    {
                    }
                }
                else
                {
                    if (!Properties.Settings.Default.AddWaypoints)
                    {
                        System.IO.File.Delete(wptFile);
                    }
                }
            }
            if (tmp != null)
            {
                tmp.Dispose();
                tmp = null;
            }
            if (tmpwpt != null)
            {
                tmpwpt.Dispose();
                tmpwpt = null;
            }
        }
Example #18
0
 protected override void ImportMethod()
 {
     using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_DOWNLOADING_PQ, STR_DOWNLOADING_PQ, _pqs.Count, 0))
     {
         int index = 0;
         try
         {
             foreach (Utils.API.LiveV6.PQData pq in _pqs)
             {
                 progress.UpdateProgress(STR_DOWNLOADING_PQ, STR_DOWNLOADING_PQ, _pqs.Count, index);
                 Utils.API.LiveV6.GetPocketQueryZippedFileResponse resp = _client.Client.GetPocketQueryZippedFile(_client.Token, pq.GUID);
                 if (resp.Status.StatusCode == 0)
                 {
                     using (System.IO.TemporaryFile tf = new System.IO.TemporaryFile(true))
                     {
                         System.IO.File.WriteAllBytes(tf.Path, Convert.FromBase64String(resp.ZippedFile));
                         processFile(tf.Path);
                         updateProcessedPq(pq.Name);
                     }
                 }
                 else
                 {
                     System.Windows.Forms.MessageBox.Show(resp.Status.StatusMessage, Utils.LanguageSupport.Instance.GetTranslation("Error"), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                     break;
                 }
                 index++;
             }
         }
         catch(Exception e)
         {
             System.Windows.Forms.MessageBox.Show(e.Message, Utils.LanguageSupport.Instance.GetTranslation("Error"), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
         }
     }
 }
Example #19
0
        public string WaypointData()
        {
            if (_activeGcg == null)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                sb.AppendLine("<gpx xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" version=\"1.0\" creator=\"Globalcaching. http://www.globalcaching.eu\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0 http://www.groundspeak.com/cache/1/0/cache.xsd\" xmlns=\"http://www.topografix.com/GPX/1/0\">");
                sb.AppendLine("  <name>Waypoints for Cache Listings Generated by Globalcaching Application</name>");
                sb.AppendLine("  <desc>This is a list of supporting waypoints for caches generated by Globalcaching App</desc>");
                sb.AppendLine("  <author>Globalcaching</author>");
                sb.AppendLine("  <url>http://www.globalcaching.eu</url>");
                sb.AppendLine("  <urlname>Geocaching - High Tech Treasure Hunting</urlname>");
                sb.AppendLine("  <email>[email protected]</email>");
                sb.AppendLine(string.Format("  <time>{0}Z</time>", DateTime.Now.ToUniversalTime().ToString("s")));
                sb.AppendLine("  <keywords>cache, geocache, waypoints</keywords>");
                sb.AppendLine(string.Format("  <bounds minlat=\"{0}\" minlon=\"{1}\" maxlat=\"{2}\" maxlon=\"{3}\" />",
                                            _minLat.ToString(CultureInfo.InvariantCulture),
                                            _minLon.ToString(CultureInfo.InvariantCulture),
                                            _maxLat.ToString(CultureInfo.InvariantCulture),
                                            _maxLon.ToString(CultureInfo.InvariantCulture)
                                            ));
                return(sb.ToString());
            }
            else
            {
                /*
                 *   <wpt lat="50.908867" lon="5.435833">
                 *      <time>2010-06-22T11:05:21.31</time>
                 *      <name>0026K5Z</name>
                 *      <cmt>Laat hier je cachemobiel even uitrusten en doe het laatste stukje te voet</cmt>
                 *      <desc>Parking</desc>
                 *      <url>http://www.geocaching.com/seek/wpt.aspx?WID=565497fc-1de4-4f36-8661-da9d0f7848e5</url>
                 *      <urlname>Parking</urlname>
                 *      <sym>Parking Area</sym>
                 *      <type>Waypoint|Parking Area</type>
                 *    </wpt>
                 */
                string      result     = "";
                bool        hasContent = false;
                XmlDocument doc        = new XmlDocument();
                XmlElement  root       = doc.CreateElement("root");
                doc.AppendChild(root);
                var wpts = _db.Fetch <DataTypes.GSAKWaypoints, DataTypes.GSAKWayMemo, WaypointPoco>((a, b) => { return(new WaypointPoco()
                    {
                        Waypoints = a, WayMemo = b
                    }); }, "select Waypoints.*, WayMemo.* from Waypoints left join WayMemo on Waypoints.cParent = WayMemo.cParent where Waypoints.cParent=@0", _activeGcg.Caches.Code);
                foreach (var wp in wpts)
                {
                    if (wp.Waypoints != null &&
                        string.IsNullOrEmpty(wp.Waypoints.cLat) &&
                        string.IsNullOrEmpty(wp.Waypoints.cLon) &&
                        !wp.Waypoints.cLat.StartsWith("0.0") &&
                        !wp.Waypoints.cLon.StartsWith("0.0")
                        )
                    {
                        hasContent = true;

                        XmlElement   wpt  = doc.CreateElement("wpt");
                        XmlAttribute attr = doc.CreateAttribute("lat");
                        XmlText      txt  = doc.CreateTextNode(wp.Waypoints.cLat);
                        attr.AppendChild(txt);
                        wpt.Attributes.Append(attr);
                        attr = doc.CreateAttribute("lon");
                        txt  = doc.CreateTextNode(wp.Waypoints.cLon);
                        attr.AppendChild(txt);
                        wpt.Attributes.Append(attr);
                        root.AppendChild(wpt);

                        XmlElement el = doc.CreateElement("time");
                        txt = doc.CreateTextNode(string.Format("{0}Z", wp.Waypoints.cDate.ToString("s")));
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el  = doc.CreateElement("name");
                        txt = doc.CreateTextNode(wp.Waypoints.cCode);
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el  = doc.CreateElement("cmt");
                        txt = doc.CreateTextNode(wp.WayMemo == null ? "" : wp.WayMemo.cComment ?? "");
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el  = doc.CreateElement("desc");
                        txt = doc.CreateTextNode(wp.Waypoints.cType);
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el  = doc.CreateElement("url");
                        txt = doc.CreateTextNode(wp.WayMemo == null ? "" : wp.WayMemo.cUrl ?? "");
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el  = doc.CreateElement("urlname");
                        txt = doc.CreateTextNode(wp.Waypoints.cType);
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el  = doc.CreateElement("sym");
                        txt = doc.CreateTextNode(wp.Waypoints.cType);
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el  = doc.CreateElement("type");
                        txt = doc.CreateTextNode(string.Format("Waypoint|{0}", wp.Waypoints.cType));
                        el.AppendChild(txt);
                        wpt.AppendChild(el);
                    }
                }
                if (hasContent)
                {
                    using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                    {
                        doc.Save(tmp.Path);
                        result = System.IO.File.ReadAllText(tmp.Path).Replace("</root>", "").Replace("<root>\r\n", "").Trim();
                    }
                }
                return(validateXml(result));
            }
        }
Example #20
0
        public string WaypointData()
        {
            if (_activeGcg == null)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                sb.AppendLine("<gpx xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" version=\"1.0\" creator=\"Globalcaching. http://www.globalcaching.eu\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0 http://www.groundspeak.com/cache/1/0/cache.xsd\" xmlns=\"http://www.topografix.com/GPX/1/0\">");
                sb.AppendLine("  <name>Waypoints for Cache Listings Generated by Globalcaching Application</name>");
                sb.AppendLine("  <desc>This is a list of supporting waypoints for caches generated by Globalcaching App</desc>");
                sb.AppendLine("  <author>Globalcaching</author>");
                sb.AppendLine("  <url>http://www.globalcaching.eu</url>");
                sb.AppendLine("  <urlname>Geocaching - High Tech Treasure Hunting</urlname>");
                sb.AppendLine("  <email>[email protected]</email>");
                sb.AppendLine(string.Format("  <time>{0}Z</time>", DateTime.Now.ToUniversalTime().ToString("s")));
                sb.AppendLine("  <keywords>cache, geocache, waypoints</keywords>");
                sb.AppendLine(string.Format("  <bounds minlat=\"{0}\" minlon=\"{1}\" maxlat=\"{2}\" maxlon=\"{3}\" />",
                                            _gcList.Min(x => x.Lat).ToString().Replace(',', '.'),
                                            _gcList.Min(x => x.Lon).ToString().Replace(',', '.'),
                                            _gcList.Max(x => x.Lat).ToString().Replace(',', '.'),
                                            _gcList.Max(x => x.Lon).ToString().Replace(',', '.')));
                return(sb.ToString());
            }
            else
            {
                /*
                 *   <wpt lat="50.908867" lon="5.435833">
                 *      <time>2010-06-22T11:05:21.31</time>
                 *      <name>0026K5Z</name>
                 *      <cmt>Laat hier je cachemobiel even uitrusten en doe het laatste stukje te voet</cmt>
                 *      <desc>Parking</desc>
                 *      <url>http://www.geocaching.com/seek/wpt.aspx?WID=565497fc-1de4-4f36-8661-da9d0f7848e5</url>
                 *      <urlname>Parking</urlname>
                 *      <sym>Parking Area</sym>
                 *      <type>Waypoint|Parking Area</type>
                 *    </wpt>
                 */
                string      result     = "";
                bool        hasContent = false;
                XmlDocument doc        = new XmlDocument();
                XmlElement  root       = doc.CreateElement("root");
                doc.AppendChild(root);
                List <Core.Data.Waypoint> wpts = Utils.DataAccess.GetWaypointsFromGeocache(_activeGcg.Database, _activeGcg.Code);
                foreach (var wp in wpts)
                {
                    if (wp.Lat != null && wp.Lon != null)
                    {
                        hasContent = true;

                        XmlElement   wpt  = doc.CreateElement("wpt");
                        XmlAttribute attr = doc.CreateAttribute("lat");
                        XmlText      txt  = doc.CreateTextNode(wp.Lat.ToString().Replace(',', '.'));
                        attr.AppendChild(txt);
                        wpt.Attributes.Append(attr);
                        attr = doc.CreateAttribute("lon");
                        txt  = doc.CreateTextNode(wp.Lon.ToString().Replace(',', '.'));
                        attr.AppendChild(txt);
                        wpt.Attributes.Append(attr);
                        root.AppendChild(wpt);

                        XmlElement el = doc.CreateElement("time");
                        txt = doc.CreateTextNode(string.Format("{0}Z", wp.Time.ToString("s")));
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el  = doc.CreateElement("name");
                        txt = doc.CreateTextNode(wp.Code);
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el  = doc.CreateElement("cmt");
                        txt = doc.CreateTextNode(wp.Comment ?? "");
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("desc");
                        if (!string.IsNullOrEmpty(wp.Description))
                        {
                            txt = doc.CreateTextNode(wp.Description);
                        }
                        else
                        {
                            txt = doc.CreateTextNode(wp.WPType.Name);
                        }
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el  = doc.CreateElement("url");
                        txt = doc.CreateTextNode(wp.Url);
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el = doc.CreateElement("urlname");
                        if (string.IsNullOrEmpty(wp.UrlName))
                        {
                            txt = doc.CreateTextNode(wp.Description);
                        }
                        else
                        {
                            txt = doc.CreateTextNode(wp.UrlName);
                        }
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el  = doc.CreateElement("sym");
                        txt = doc.CreateTextNode(getWaypointTagName(wp.WPType));
                        el.AppendChild(txt);
                        wpt.AppendChild(el);

                        el  = doc.CreateElement("type");
                        txt = doc.CreateTextNode(string.Format("Waypoint|{0}", getWaypointTagName(wp.WPType)));
                        el.AppendChild(txt);
                        wpt.AppendChild(el);
                    }
                }
                if (hasContent)
                {
                    using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                    {
                        doc.Save(tmp.Path);
                        result = System.IO.File.ReadAllText(tmp.Path).Replace("</root>", "").Replace("<root>\r\n", "").Trim();
                    }
                }
                return(validateXml(result));
            }
        }
Example #21
0
        public string Next()
        {
            string      result = "";
            XmlDocument doc    = new XmlDocument();

            if (_index < _gcList.Count)
            {
                var gc = _db.Fetch <DataTypes.GSAKCaches, DataTypes.GSAKCacheMemo, DataTypes.GSAKCorrected, GeocachePoco>((a, b, c) => { return(new GeocachePoco()
                    {
                        Caches = a, CacheMemo = b, Corrected = c
                    }); }, "select Caches.*, CacheMemo.*, Corrected.* from Caches left join CacheMemo on Caches.Code = CacheMemo.Code left join Corrected on Caches.Code = Corrected.kCode where Caches.Code=@0", _gcList[_index]).FirstOrDefault();
                _activeGcg = gc;

                string GPXTag = (from a in ApplicationData.Instance.GeocacheTypes where a.GSAK == gc.Caches.CacheType select a.GPXTag).FirstOrDefault() ?? "";

                XmlElement   wpt  = doc.CreateElement("wpt");
                XmlAttribute attr = doc.CreateAttribute("lat");
                XmlText      txt  = doc.CreateTextNode(gc.Corrected == null ? gc.Caches.Latitude : gc.Corrected.kAfterLat);
                attr.AppendChild(txt);
                wpt.Attributes.Append(attr);
                attr = doc.CreateAttribute("lon");
                txt  = doc.CreateTextNode(gc.Corrected == null ? gc.Caches.Longitude : gc.Corrected.kAfterLon);
                attr.AppendChild(txt);
                wpt.Attributes.Append(attr);
                doc.AppendChild(wpt);

                XmlElement el = doc.CreateElement("time");
                txt = doc.CreateTextNode(string.Format("{0}Z", DateTime.ParseExact(gc.Caches.PlacedDate, "yyyy-MM-dd", CultureInfo.InvariantCulture).AddHours(12).ToString("s")));
                el.AppendChild(txt);
                wpt.AppendChild(el);

                string nameValue = gc.Caches.Code;
                el  = doc.CreateElement("name");
                txt = doc.CreateTextNode(gc.Caches.Code);
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el  = doc.CreateElement("desc");
                txt = doc.CreateTextNode(string.Format("{0} by {1}, {2} ({3}/{4})", gc.Caches.Name, gc.Caches.OwnerName, GPXTag, gc.Caches.Difficulty, gc.Caches.Terrain));
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el  = doc.CreateElement("url");
                txt = doc.CreateTextNode(gc.CacheMemo == null ? "" : gc.CacheMemo.Url);
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el  = doc.CreateElement("urlname");
                txt = doc.CreateTextNode(gc.Caches.Name);
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el = doc.CreateElement("sym");
                if (gc.Caches.Found != 0)
                {
                    txt = doc.CreateTextNode("Geocache Found");
                }
                else
                {
                    txt = doc.CreateTextNode("Geocache");
                }
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el  = doc.CreateElement("type");
                txt = doc.CreateTextNode(string.Format("Geocache|{0}", GPXTag));
                el.AppendChild(txt);
                wpt.AppendChild(el);

                XmlElement cache = doc.CreateElement("groundspeak_cache");
                wpt.AppendChild(cache);
                attr = doc.CreateAttribute("id");
                txt  = doc.CreateTextNode(gc.Caches.CacheId);
                attr.AppendChild(txt);
                cache.Attributes.Append(attr);

                attr = doc.CreateAttribute("available");
                txt  = doc.CreateTextNode((gc.Caches.TempDisabled == 0).ToString().ToLower());
                attr.AppendChild(txt);
                cache.Attributes.Append(attr);

                attr = doc.CreateAttribute("archived");
                txt  = doc.CreateTextNode((gc.Caches.Archived != 0).ToString().ToLower());
                attr.AppendChild(txt);
                cache.Attributes.Append(attr);

                if (_gpxVersion >= V102)
                {
                    attr = doc.CreateAttribute("memberonly");
                    txt  = doc.CreateTextNode((gc.Caches.IsPremium != 0).ToString().ToLower());
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);

                    attr = doc.CreateAttribute("customcoords");
                    txt  = doc.CreateTextNode((gc.Corrected != null).ToString().ToLower());
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);

                    attr = doc.CreateAttribute("_xmlns_groundspeak");
                    txt  = doc.CreateTextNode("http://www.groundspeak.com/cache/1/0/2");
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);
                }
                else if (_gpxVersion == V101)
                {
                    attr = doc.CreateAttribute("_xmlns_groundspeak");
                    txt  = doc.CreateTextNode("http://www.groundspeak.com/cache/1/0/1");
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);
                }
                else
                {
                    attr = doc.CreateAttribute("_xmlns_groundspeak");
                    txt  = doc.CreateTextNode("http://www.groundspeak.com/cache/1/0");
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);
                }

                el  = doc.CreateElement("groundspeak_name");
                txt = doc.CreateTextNode(gc.Caches.Name);
                el.AppendChild(txt);
                cache.AppendChild(el);

                el  = doc.CreateElement("groundspeak_placed_by");
                txt = doc.CreateTextNode(gc.Caches.PlacedBy);
                el.AppendChild(txt);
                cache.AppendChild(el);

                el  = doc.CreateElement("groundspeak_owner");
                txt = doc.CreateTextNode(gc.Caches.OwnerName);
                el.AppendChild(txt);
                cache.AppendChild(el);
                if (_gpxVersion >= V102)
                {
                    attr = doc.CreateAttribute("id");
                    txt  = doc.CreateTextNode(gc.Caches.OwnerId);
                    attr.AppendChild(txt);
                    el.Attributes.Append(attr);
                }

                el  = doc.CreateElement("groundspeak_type");
                txt = doc.CreateTextNode(GPXTag);
                el.AppendChild(txt);
                cache.AppendChild(el);
                if (_gpxVersion >= V102)
                {
                    string GeocacheTypeID = (from a in ApplicationData.Instance.GeocacheTypes where a.GSAK == gc.Caches.CacheType select a.ID.ToString()).FirstOrDefault() ?? "";

                    attr = doc.CreateAttribute("id");
                    txt  = doc.CreateTextNode(GeocacheTypeID);
                    attr.AppendChild(txt);
                    el.Attributes.Append(attr);
                }

                el  = doc.CreateElement("groundspeak_container");
                txt = doc.CreateTextNode(gc.Caches.Container);
                el.AppendChild(txt);
                cache.AppendChild(el);
                if (_gpxVersion >= V102)
                {
                    string containerID = (from a in ApplicationData.Instance.GeocacheContainers where a.Name == gc.Caches.Container select a.ID.ToString()).FirstOrDefault() ?? "";

                    attr = doc.CreateAttribute("id");
                    txt  = doc.CreateTextNode(containerID);
                    attr.AppendChild(txt);
                    el.Attributes.Append(attr);
                }

                if (_gpxVersion >= V101)
                {
                    var attributes = _db.Fetch <DataTypes.GSAKAttributes>("select * from Attributes where aCode=@0", gc.Caches.Code);
                    if (attributes.Count > 0)
                    {
                        XmlElement attrs = doc.CreateElement("groundspeak_attributes");
                        cache.AppendChild(attrs);
                        foreach (var att in attributes)
                        {
                            var attrName = (from a in ApplicationData.Instance.GeocacheAttributes where a.ID == att.aId select a.Name).FirstOrDefault() ?? "";

                            el  = doc.CreateElement("groundspeak_attribute");
                            txt = doc.CreateTextNode(attrName);
                            el.AppendChild(txt);
                            attrs.AppendChild(el);
                            attr = doc.CreateAttribute("id");
                            txt  = doc.CreateTextNode(att.aId.ToString());
                            attr.AppendChild(txt);
                            el.Attributes.Append(attr);

                            attr = doc.CreateAttribute("inc");
                            txt  = doc.CreateTextNode(att.aInc.ToString());
                            attr.AppendChild(txt);
                            el.Attributes.Append(attr);
                        }
                    }
                }

                el  = doc.CreateElement("groundspeak_difficulty");
                txt = doc.CreateTextNode(gc.Caches.Difficulty.ToString(CultureInfo.InvariantCulture));
                el.AppendChild(txt);
                cache.AppendChild(el);

                el  = doc.CreateElement("groundspeak_terrain");
                txt = doc.CreateTextNode(gc.Caches.Terrain.ToString(CultureInfo.InvariantCulture));
                el.AppendChild(txt);
                cache.AppendChild(el);

                el  = doc.CreateElement("groundspeak_country");
                txt = doc.CreateTextNode(gc.Caches.Country ?? "");
                el.AppendChild(txt);
                cache.AppendChild(el);

                el  = doc.CreateElement("groundspeak_state");
                txt = doc.CreateTextNode(gc.Caches.State ?? "");
                el.AppendChild(txt);
                cache.AppendChild(el);

                el  = doc.CreateElement("groundspeak_short_description");
                txt = doc.CreateTextNode(gc.CacheMemo == null ? "" : gc.CacheMemo.ShortDescription);
                el.AppendChild(txt);
                cache.AppendChild(el);
                attr = doc.CreateAttribute("html");
                txt  = doc.CreateTextNode((gc.Caches.ShortHtm != 0).ToString().ToLower());
                attr.AppendChild(txt);
                el.Attributes.Append(attr);

                el  = doc.CreateElement("groundspeak_long_description");
                txt = doc.CreateTextNode(gc.CacheMemo == null ? "" : gc.CacheMemo.LongDescription);
                el.AppendChild(txt);
                cache.AppendChild(el);
                attr = doc.CreateAttribute("html");
                txt  = doc.CreateTextNode((gc.Caches.LongHtm != 0).ToString().ToLower());
                attr.AppendChild(txt);
                el.Attributes.Append(attr);

                el  = doc.CreateElement("groundspeak_encoded_hints");
                txt = doc.CreateTextNode(gc.CacheMemo == null ? "" : gc.CacheMemo.Hints);
                el.AppendChild(txt);
                cache.AppendChild(el);

                if (_gpxVersion >= V102)
                {
                    el  = doc.CreateElement("groundspeak_personal_note");
                    txt = doc.CreateTextNode(gc.CacheMemo == null ? "" : gc.CacheMemo.UserNote ?? "");
                    el.AppendChild(txt);
                    cache.AppendChild(el);

                    el  = doc.CreateElement("groundspeak_favorite_points");
                    txt = doc.CreateTextNode(gc.Caches.FavPoints.ToString());
                    el.AppendChild(txt);
                    cache.AppendChild(el);
                }

                var logs = _db.Fetch <DataTypes.GSAKLogs, DataTypes.GSAKLogMemo, GeocacheLogPoco>((a, b) => { return(new GeocacheLogPoco()
                    {
                        Logs = a, LogMemo = b
                    }); }, "select Logs.*, LogMemo.* from Logs left join LogMemo on Logs.lLogId=LogMemo.lLogId where Logs.lParent=@0", gc.Caches.Code);
                if (logs.Count > 0)
                {
                    XmlElement logsel = doc.CreateElement("groundspeak_logs");
                    cache.AppendChild(logsel);
                    foreach (var l in logs)
                    {
                        XmlElement lel = doc.CreateElement("groundspeak_log");
                        logsel.AppendChild(lel);
                        attr = doc.CreateAttribute("id");
                        txt  = doc.CreateTextNode(l.Logs.lLogId.ToString());
                        attr.AppendChild(txt);
                        lel.Attributes.Append(attr);

                        el  = doc.CreateElement("groundspeak_date");
                        txt = doc.CreateTextNode(string.Format("{0}Z", (l.Logs.lDate ?? DateTime.Now).Date.ToString("s")));
                        el.AppendChild(txt);
                        lel.AppendChild(el);

                        el  = doc.CreateElement("groundspeak_type");
                        txt = doc.CreateTextNode(l.Logs.lType);
                        el.AppendChild(txt);
                        lel.AppendChild(el);
                        if (_gpxVersion >= V102)
                        {
                            var logtypeid = (from a in ApplicationData.Instance.LogTypes where a.Name == l.Logs.lType select a.ID.ToString()).FirstOrDefault() ?? "";

                            attr = doc.CreateAttribute("id");
                            txt  = doc.CreateTextNode(logtypeid);
                            attr.AppendChild(txt);
                            el.Attributes.Append(attr);
                        }

                        el  = doc.CreateElement("groundspeak_finder");
                        txt = doc.CreateTextNode(l.Logs.lBy ?? "");
                        el.AppendChild(txt);
                        lel.AppendChild(el);
                        attr = doc.CreateAttribute("id");
                        txt  = doc.CreateTextNode((l.Logs.lownerid ?? 1).ToString());
                        attr.AppendChild(txt);
                        el.Attributes.Append(attr);

                        el  = doc.CreateElement("groundspeak_text");
                        txt = doc.CreateTextNode(l.LogMemo == null ? "" : l.LogMemo.lText ?? "");
                        el.AppendChild(txt);
                        lel.AppendChild(el);
                        attr = doc.CreateAttribute("encoded");
                        txt  = doc.CreateTextNode((l.Logs.lEncoded ?? 0).ToString().ToLower());
                        attr.AppendChild(txt);
                        el.Attributes.Append(attr);
                    }
                }
                //todo, geocache images / trackables

                _index++;
            }
            using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
            {
                doc.Save(tmp.Path);
                result = System.IO.File.ReadAllText(tmp.Path);
                result = result.Replace("<groundspeak_", "<groundspeak:");
                result = result.Replace("</groundspeak_", "</groundspeak:");
                result = result.Replace("_xmlns_groundspeak", "xmlns:groundspeak");
            }
            return(validateXml(result));
        }
Example #22
0
        public bool LogGeocache(LiveAPI.GeocachingLiveV6 api, LogInfo logInfo, List<LiveAPI.LiveV6.Trackable> dropTbs, List<string> retrieveTbs)
        {
            bool result = false;
            try
            {
                var req = new LiveAPI.LiveV6.CreateFieldNoteAndPublishRequest();
                req.AccessToken = api.Token;
                req.CacheCode = logInfo.GeocacheCode;
                req.EncryptLogText = false;
                req.FavoriteThisCache = logInfo.AddToFavorites;
                req.Note = logInfo.LogText;
                req.PromoteToLog = true;
                req.WptLogTypeId = logInfo.LogType.ID;
                req.UTCDateLogged = logInfo.VisitDate.Date.AddHours(12).ToUniversalTime();
                var resp = api.Client.CreateFieldNoteAndPublish(req);
                if (resp.Status.StatusCode == 0)
                {
                    bool error = false;

                    if (Core.ApplicationData.Instance.ActiveDatabase!=null)
                    {
                        var gc = Core.ApplicationData.Instance.ActiveDatabase.GeocacheCollection.GetGeocache(logInfo.GeocacheCode);
                        if (gc != null)
                        {
                            if (logInfo.LogType.AsFound)
                            {
                                gc.Found = true;
                            }
                        }
                        LiveAPI.Import.ImportLog(Core.ApplicationData.Instance.ActiveDatabase, resp.Log);
                        if (gc!=null)
                        {
                            gc.ResetCachedLogData();
                        }
                    }

                    //log trackables (14=drop off, 13=retrieve from cache, 75=visited)
                    if (dropTbs != null && dropTbs.Count > 0)
                    {
                        var reqT = new LiveAPI.LiveV6.CreateTrackableLogRequest();
                        reqT.AccessToken = api.Token;
                        reqT.LogType = 14;
                        reqT.UTCDateLogged = logInfo.VisitDate.Date.AddHours(12).ToUniversalTime();
                        foreach (var tb in dropTbs)
                        {
                            reqT.TrackingNumber = tb.TrackingCode;
                            reqT.CacheCode = logInfo.GeocacheCode;
                            var resp2 = api.Client.CreateTrackableLog(reqT);
                            if (resp2.Status.StatusCode != 0)
                            {
                                Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp2.Status.StatusMessage);
                                error = true;
                                //break;
                            }
                        }
                    }

                    if (retrieveTbs != null && retrieveTbs.Count > 0)
                    {
                        var reqT = new LiveAPI.LiveV6.CreateTrackableLogRequest();
                        reqT.AccessToken = api.Token;
                        reqT.LogType = 13;
                        reqT.UTCDateLogged = logInfo.VisitDate.Date.AddHours(12).ToUniversalTime();
                        foreach (var tb in retrieveTbs)
                        {
                            reqT.TrackingNumber = tb;
                            reqT.CacheCode = logInfo.GeocacheCode;
                            var resp2 = api.Client.CreateTrackableLog(reqT);
                            if (resp2.Status.StatusCode != 0)
                            {
                                Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp2.Status.StatusMessage);
                                error = true;
                                //break;
                            }
                        }
                    }

                    //add log images
                    foreach (var li in logInfo.Images)
                    {
                        var uplReq = new LiveAPI.LiveV6.UploadImageToGeocacheLogRequest();
                        uplReq.AccessToken = api.Token;
                        uplReq.LogGuid = resp.Log.Guid;
                        uplReq.ImageData = new LiveAPI.LiveV6.UploadImageData();
                        uplReq.ImageData.FileCaption = li.Caption;
                        uplReq.ImageData.FileDescription = li.Description;
                        uplReq.ImageData.FileName = li.Uri;

                        using (System.IO.TemporaryFile tmpFile = new System.IO.TemporaryFile(true))
                        {
                            if (Utils.ResourceHelper.ScaleImage(li.Uri, tmpFile.Path, Core.Settings.Default.LiveAPILogGeocachesMaxImageWidth, Core.Settings.Default.LiveAPILogGeocachesMaxImageHeight, Core.Settings.Default.LiveAPILogGeocachesMaxImageSizeMB, Core.Settings.Default.LiveAPILogGeocachesImageQuality, li.RotationDeg))
                            {
                                uplReq.ImageData.base64ImageData = System.Convert.ToBase64String(System.IO.File.ReadAllBytes(tmpFile.Path));
                            }
                        }
                        if (!string.IsNullOrEmpty(uplReq.ImageData.base64ImageData))
                        {
                            var resp2 = api.Client.UploadImageToGeocacheLog(uplReq);
                            if (resp2.Status.StatusCode != 0)
                            {
                                Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp2.Status.StatusMessage);
                                error = true;
                                //break;
                            }
                        }
                        else
                        {
                            error = true;
                        }
                    }

                    if (logInfo.AddToFavorites)
                    {
                        Favorites.Manager.Instance.AddFavoritedGeocache(logInfo.GeocacheCode);
                    }

                    result = true;
                }
                else
                {
                    Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp.Status.StatusMessage);
                }
            }
            catch(Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }
            return result;
        }
Example #23
0
        public void ImportGeocacheDistance(Core.Storage.Database db)
        {
            try
            {
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ImportNLGeocacheDistance", "DownloadingData", 1, 0))
                {
                    using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                        using (System.Net.WebClient wc = new System.Net.WebClient())
                        {
                            wc.DownloadFile(string.Format("http://www.globalcaching.eu/service/cachedistance.aspx?country=Netherlands&prefix=GC&token{0}", System.Web.HttpUtility.UrlEncode(Core.Settings.Default.LiveAPIToken ?? "")), tmp.Path);

                            using (var fs = System.IO.File.OpenRead(tmp.Path))
                                using (ZipInputStream s = new ZipInputStream(fs))
                                {
                                    ZipEntry theEntry = s.GetNextEntry();
                                    byte[]   data     = new byte[1024];
                                    if (theEntry != null)
                                    {
                                        StringBuilder sb = new StringBuilder();
                                        while (true)
                                        {
                                            int size = s.Read(data, 0, data.Length);
                                            if (size > 0)
                                            {
                                                if (sb.Length == 0 && data[0] == 0xEF && size > 2)
                                                {
                                                    sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 3, size - 3));
                                                }
                                                else
                                                {
                                                    sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 0, size));
                                                }
                                            }
                                            else
                                            {
                                                break;
                                            }
                                        }

                                        XmlDocument doc = new XmlDocument();
                                        doc.LoadXml(sb.ToString());
                                        XmlElement  root = doc.DocumentElement;
                                        XmlNodeList nl   = root.SelectNodes("wp");
                                        if (nl != null)
                                        {
                                            progress.Update("SavingGeocaches", nl.Count, 0);
                                            DateTime nextUpdate = DateTime.Now.AddSeconds(1);
                                            int      index      = 0;
                                            foreach (XmlNode n in nl)
                                            {
                                                var gc = db.GeocacheCollection.GetGeocache(n.Attributes["code"].InnerText);
                                                if (gc != null)
                                                {
                                                    gc.GeocacheDistance = Utils.Conversion.StringToDouble(n.Attributes["dist"].InnerText);
                                                }
                                                else
                                                {
                                                    Core.Settings.Default.SetGeocacheDistance(n.Attributes["code"].InnerText, Utils.Conversion.StringToDouble(n.Attributes["dist"].InnerText));
                                                }
                                                index++;
                                                if (DateTime.Now >= nextUpdate)
                                                {
                                                    progress.Update("SavingGeocaches", nl.Count, index);
                                                    nextUpdate = DateTime.Now.AddSeconds(1);
                                                }
                                            }
                                        }
                                    }
                                }
                        }
                }
            }
            catch (Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }
        }
        public string Next()
        {
            string result = "";
            XmlDocument doc = new XmlDocument();
            if (_index < _gcList.Count)
            {
                var gc = _db.Fetch<DataTypes.GSAKCaches, DataTypes.GSAKCacheMemo, DataTypes.GSAKCorrected, GeocachePoco>((a, b, c) => { return new GeocachePoco() { Caches = a, CacheMemo = b, Corrected = c }; }, "select Caches.*, CacheMemo.*, Corrected.* from Caches left join CacheMemo on Caches.Code = CacheMemo.Code left join Corrected on Caches.Code = Corrected.kCode where Caches.Code=@0", _gcList[_index]).FirstOrDefault();
                _activeGcg = gc;

                string GPXTag = (from a in ApplicationData.Instance.GeocacheTypes where a.GSAK == gc.Caches.CacheType select a.GPXTag).FirstOrDefault() ?? "";

                XmlElement wpt = doc.CreateElement("wpt");
                XmlAttribute attr = doc.CreateAttribute("lat");
                XmlText txt = doc.CreateTextNode(gc.Corrected == null ? gc.Caches.Latitude : gc.Corrected.kAfterLat);
                attr.AppendChild(txt);
                wpt.Attributes.Append(attr);
                attr = doc.CreateAttribute("lon");
                txt = doc.CreateTextNode(gc.Corrected == null ? gc.Caches.Longitude : gc.Corrected.kAfterLon);
                attr.AppendChild(txt);
                wpt.Attributes.Append(attr);
                doc.AppendChild(wpt);

                XmlElement el = doc.CreateElement("time");
                txt = doc.CreateTextNode(string.Format("{0}Z",DateTime.ParseExact(gc.Caches.PlacedDate, "yyyy-MM-dd", CultureInfo.InvariantCulture).AddHours(12).ToString("s")));
                el.AppendChild(txt);
                wpt.AppendChild(el);

                string nameValue = gc.Caches.Code;
                el = doc.CreateElement("name");
                txt = doc.CreateTextNode(gc.Caches.Code);
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el = doc.CreateElement("desc");
                txt = doc.CreateTextNode(string.Format("{0} by {1}, {2} ({3}/{4})", gc.Caches.Name, gc.Caches.OwnerName, GPXTag, gc.Caches.Difficulty, gc.Caches.Terrain));
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el = doc.CreateElement("url");
                txt = doc.CreateTextNode(gc.CacheMemo == null ? "" : gc.CacheMemo.Url);
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el = doc.CreateElement("urlname");
                txt = doc.CreateTextNode(gc.Caches.Name);
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el = doc.CreateElement("sym");
                if (gc.Caches.Found!=0)
                {
                    txt = doc.CreateTextNode("Geocache Found");
                }
                else
                {
                    txt = doc.CreateTextNode("Geocache");
                }
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el = doc.CreateElement("type");
                txt = doc.CreateTextNode(string.Format("Geocache|{0}", GPXTag));
                el.AppendChild(txt);
                wpt.AppendChild(el);

                XmlElement cache = doc.CreateElement("groundspeak_cache");
                wpt.AppendChild(cache);
                attr = doc.CreateAttribute("id");
                txt = doc.CreateTextNode(gc.Caches.CacheId);
                attr.AppendChild(txt);
                cache.Attributes.Append(attr);

                attr = doc.CreateAttribute("available");
                txt = doc.CreateTextNode((gc.Caches.TempDisabled==0).ToString().ToLower());
                attr.AppendChild(txt);
                cache.Attributes.Append(attr);

                attr = doc.CreateAttribute("archived");
                txt = doc.CreateTextNode((gc.Caches.Archived != 0).ToString().ToLower());
                attr.AppendChild(txt);
                cache.Attributes.Append(attr);

                if (_gpxVersion >= V102)
                {
                    attr = doc.CreateAttribute("memberonly");
                    txt = doc.CreateTextNode((gc.Caches.IsPremium !=0).ToString().ToLower());
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);

                    attr = doc.CreateAttribute("customcoords");
                    txt = doc.CreateTextNode((gc.Corrected!=null).ToString().ToLower());
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);

                    attr = doc.CreateAttribute("_xmlns_groundspeak");
                    txt = doc.CreateTextNode("http://www.groundspeak.com/cache/1/0/2");
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);
                }
                else if (_gpxVersion == V101)
                {
                    attr = doc.CreateAttribute("_xmlns_groundspeak");
                    txt = doc.CreateTextNode("http://www.groundspeak.com/cache/1/0/1");
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);
                }
                else
                {
                    attr = doc.CreateAttribute("_xmlns_groundspeak");
                    txt = doc.CreateTextNode("http://www.groundspeak.com/cache/1/0");
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);
                }

                el = doc.CreateElement("groundspeak_name");
                txt = doc.CreateTextNode(gc.Caches.Name);
                el.AppendChild(txt);
                cache.AppendChild(el);

                el = doc.CreateElement("groundspeak_placed_by");
                txt = doc.CreateTextNode(gc.Caches.PlacedBy);
                el.AppendChild(txt);
                cache.AppendChild(el);

                el = doc.CreateElement("groundspeak_owner");
                txt = doc.CreateTextNode(gc.Caches.OwnerName);
                el.AppendChild(txt);
                cache.AppendChild(el);
                if (_gpxVersion >= V102)
                {
                    attr = doc.CreateAttribute("id");
                    txt = doc.CreateTextNode(gc.Caches.OwnerId);
                    attr.AppendChild(txt);
                    el.Attributes.Append(attr);
                }

                el = doc.CreateElement("groundspeak_type");
                txt = doc.CreateTextNode(GPXTag);
                el.AppendChild(txt);
                cache.AppendChild(el);
                if (_gpxVersion >= V102)
                {
                    string GeocacheTypeID = (from a in ApplicationData.Instance.GeocacheTypes where a.GSAK == gc.Caches.CacheType select a.ID.ToString()).FirstOrDefault() ?? "";

                    attr = doc.CreateAttribute("id");
                    txt = doc.CreateTextNode(GeocacheTypeID);
                    attr.AppendChild(txt);
                    el.Attributes.Append(attr);
                }

                el = doc.CreateElement("groundspeak_container");
                txt = doc.CreateTextNode(gc.Caches.Container);
                el.AppendChild(txt);
                cache.AppendChild(el);
                if (_gpxVersion >= V102)
                {
                    string containerID = (from a in ApplicationData.Instance.GeocacheContainers where a.Name == gc.Caches.Container select a.ID.ToString()).FirstOrDefault() ?? "";

                    attr = doc.CreateAttribute("id");
                    txt = doc.CreateTextNode(containerID);
                    attr.AppendChild(txt);
                    el.Attributes.Append(attr);
                }

                if (_gpxVersion >= V101)
                {
                    var attributes = _db.Fetch<DataTypes.GSAKAttributes>("select * from Attributes where aCode=@0", gc.Caches.Code);
                    if (attributes.Count > 0)
                    {
                        XmlElement attrs = doc.CreateElement("groundspeak_attributes");
                        cache.AppendChild(attrs);
                        foreach (var att in attributes)
                        {
                            var attrName = (from a in ApplicationData.Instance.GeocacheAttributes where a.ID == att.aId select a.Name).FirstOrDefault() ?? "";

                            el = doc.CreateElement("groundspeak_attribute");
                            txt = doc.CreateTextNode(attrName);
                            el.AppendChild(txt);
                            attrs.AppendChild(el);
                            attr = doc.CreateAttribute("id");
                            txt = doc.CreateTextNode(att.aId.ToString());
                            attr.AppendChild(txt);
                            el.Attributes.Append(attr);

                            attr = doc.CreateAttribute("inc");
                            txt = doc.CreateTextNode(att.aInc.ToString());
                            attr.AppendChild(txt);
                            el.Attributes.Append(attr);
                        }
                    }
                }

                el = doc.CreateElement("groundspeak_difficulty");
                txt = doc.CreateTextNode(gc.Caches.Difficulty.ToString(CultureInfo.InvariantCulture));
                el.AppendChild(txt);
                cache.AppendChild(el);

                el = doc.CreateElement("groundspeak_terrain");
                txt = doc.CreateTextNode(gc.Caches.Terrain.ToString(CultureInfo.InvariantCulture));
                el.AppendChild(txt);
                cache.AppendChild(el);

                el = doc.CreateElement("groundspeak_country");
                txt = doc.CreateTextNode(gc.Caches.Country ?? "");
                el.AppendChild(txt);
                cache.AppendChild(el);

                el = doc.CreateElement("groundspeak_state");
                txt = doc.CreateTextNode(gc.Caches.State ?? "");
                el.AppendChild(txt);
                cache.AppendChild(el);

                el = doc.CreateElement("groundspeak_short_description");
                txt = doc.CreateTextNode(gc.CacheMemo == null ? "" : gc.CacheMemo.ShortDescription);
                el.AppendChild(txt);
                cache.AppendChild(el);
                attr = doc.CreateAttribute("html");
                txt = doc.CreateTextNode((gc.Caches.ShortHtm != 0).ToString().ToLower());
                attr.AppendChild(txt);
                el.Attributes.Append(attr);

                el = doc.CreateElement("groundspeak_long_description");
                txt = doc.CreateTextNode(gc.CacheMemo == null ? "" : gc.CacheMemo.LongDescription);
                el.AppendChild(txt);
                cache.AppendChild(el);
                attr = doc.CreateAttribute("html");
                txt = doc.CreateTextNode((gc.Caches.LongHtm != 0).ToString().ToLower());
                attr.AppendChild(txt);
                el.Attributes.Append(attr);

                el = doc.CreateElement("groundspeak_encoded_hints");
                txt = doc.CreateTextNode(gc.CacheMemo == null ? "" : gc.CacheMemo.Hints);
                el.AppendChild(txt);
                cache.AppendChild(el);

                if (_gpxVersion >= V102)
                {
                    el = doc.CreateElement("groundspeak_personal_note");
                    txt = doc.CreateTextNode(gc.CacheMemo == null ? "" : gc.CacheMemo.UserNote ?? "");
                    el.AppendChild(txt);
                    cache.AppendChild(el);

                    el = doc.CreateElement("groundspeak_favorite_points");
                    txt = doc.CreateTextNode(gc.Caches.FavPoints.ToString());
                    el.AppendChild(txt);
                    cache.AppendChild(el);
                }

                var logs = _db.Fetch<DataTypes.GSAKLogs, DataTypes.GSAKLogMemo, GeocacheLogPoco>((a, b) => { return new GeocacheLogPoco() { Logs = a, LogMemo = b }; }, "select Logs.*, LogMemo.* from Logs left join LogMemo on Logs.lLogId=LogMemo.lLogId where Logs.lParent=@0", gc.Caches.Code);
                if (logs.Count > 0)
                {
                    XmlElement logsel = doc.CreateElement("groundspeak_logs");
                    cache.AppendChild(logsel);
                    foreach (var l in logs)
                    {
                        XmlElement lel = doc.CreateElement("groundspeak_log");
                        logsel.AppendChild(lel);
                        attr = doc.CreateAttribute("id");
                        txt = doc.CreateTextNode(l.Logs.lLogId.ToString());
                        attr.AppendChild(txt);
                        lel.Attributes.Append(attr);

                        el = doc.CreateElement("groundspeak_date");
                        txt = doc.CreateTextNode(string.Format("{0}Z",(l.Logs.lDate ?? DateTime.Now).Date.ToString("s")));
                        el.AppendChild(txt);
                        lel.AppendChild(el);

                        el = doc.CreateElement("groundspeak_type");
                        txt = doc.CreateTextNode(l.Logs.lType);
                        el.AppendChild(txt);
                        lel.AppendChild(el);
                        if (_gpxVersion >= V102)
                        {
                            var logtypeid = (from a in ApplicationData.Instance.LogTypes where a.Name == l.Logs.lType select a.ID.ToString()).FirstOrDefault() ?? "";

                            attr = doc.CreateAttribute("id");
                            txt = doc.CreateTextNode(logtypeid);
                            attr.AppendChild(txt);
                            el.Attributes.Append(attr);
                        }

                        el = doc.CreateElement("groundspeak_finder");
                        txt = doc.CreateTextNode(l.Logs.lBy ?? "");
                        el.AppendChild(txt);
                        lel.AppendChild(el);
                        attr = doc.CreateAttribute("id");
                        txt = doc.CreateTextNode((l.Logs.lownerid ?? 1).ToString());
                        attr.AppendChild(txt);
                        el.Attributes.Append(attr);

                        el = doc.CreateElement("groundspeak_text");
                        txt = doc.CreateTextNode(l.LogMemo == null ? "" : l.LogMemo.lText ?? "");
                        el.AppendChild(txt);
                        lel.AppendChild(el);
                        attr = doc.CreateAttribute("encoded");
                        txt = doc.CreateTextNode((l.Logs.lEncoded ?? 0).ToString().ToLower());
                        attr.AppendChild(txt);
                        el.Attributes.Append(attr);
                    }
                }
                //todo, geocache images / trackables

                _index++;
            }
            using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
            {
                doc.Save(tmp.Path);
                result = System.IO.File.ReadAllText(tmp.Path);
                result = result.Replace("<groundspeak_", "<groundspeak:");
                result = result.Replace("</groundspeak_", "</groundspeak:");
                result = result.Replace("_xmlns_groundspeak", "xmlns:groundspeak");
            }
            return validateXml(result);
        }
Example #25
0
        public async Task DownloadSelectedPQ()
        {
            List<LiveAPI.LiveV6.PQData> pqs = new List<LiveAPI.LiveV6.PQData>();
            foreach (PQData p in listItems.SelectedItems)
            {
                pqs.Add(p.LiveAPIData);
            }

            using (Utils.DataUpdater upd = new Utils.DataUpdater(Core.ApplicationData.Instance.ActiveDatabase))
            {
                await Task.Run(new Action(() =>
                {
                    try
                    {
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock("DownloadingPQ", "DownloadingPQ", pqs.Count, 0, true))
                        {
                            int index = 0;
                            try
                            {
                                using (var api = new LiveAPI.GeocachingLiveV6())
                                {
                                    Import imp = new Import();
                                    foreach (LiveAPI.LiveV6.PQData pq in pqs)
                                    {
                                        if (progress.Update(pq.Name, pqs.Count, index))
                                        {
                                            LiveAPI.LiveV6.GetPocketQueryZippedFileResponse resp = api.Client.GetPocketQueryZippedFile(api.Token, pq.GUID);
                                            if (resp.Status.StatusCode == 0)
                                            {
                                                using (System.IO.TemporaryFile tf = new System.IO.TemporaryFile(true))
                                                {
                                                    System.IO.File.WriteAllBytes(tf.Path, Convert.FromBase64String(resp.ZippedFile));
                                                    imp.ImportFile(tf.Path);
                                                    updateProcessedPq(pq.GUID);
                                                }
                                            }
                                            else
                                            {
                                                Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp.Status.StatusMessage);
                                                break;
                                            }
                                            index++;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Core.ApplicationData.Instance.Logger.AddLog(this, e);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Core.ApplicationData.Instance.Logger.AddLog(this, e);
                    }
                }));
            }
            Close();
        }
Example #26
0
        public string Next()
        {
            string result = "";
            XmlDocument doc = new XmlDocument();
            if (_index < _gcList.Count)
            {
                Framework.Data.Geocache gc = _gcList[_index];
                _activeGcg = gc;

                XmlElement wpt = doc.CreateElement("wpt");
                XmlAttribute attr = doc.CreateAttribute("lat");
                XmlText txt = doc.CreateTextNode(gc.CustomLat == null ? gc.Lat.ToString().Replace(',', '.') : gc.CustomLat.ToString().Replace(',', '.'));
                attr.AppendChild(txt);
                wpt.Attributes.Append(attr);
                attr = doc.CreateAttribute("lon");
                txt = doc.CreateTextNode(gc.CustomLon == null ? gc.Lon.ToString().Replace(',', '.') : gc.CustomLon.ToString().Replace(',', '.'));
                attr.AppendChild(txt);
                wpt.Attributes.Append(attr);
                doc.AppendChild(wpt);

                XmlElement el = doc.CreateElement("time");
                txt = doc.CreateTextNode(string.Format("{0}Z",gc.PublishedTime.ToString("s")));
                el.AppendChild(txt);
                wpt.AppendChild(el);

                string nameValue;
                if (_useNameForGCCode)
                {
                    nameValue = transformedGeocacheName(gc.Name ?? "");
                }
                else
                {
                    nameValue = gc.Code;
                }
                el = doc.CreateElement("name");
                if (gc.ContainsCustomLatLon)
                {
                    txt = doc.CreateTextNode(string.Format("{0}{1}", _extraCoordPrefix ?? "", nameValue));
                }
                else
                {
                    txt = doc.CreateTextNode(nameValue);
                }
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el = doc.CreateElement("desc");
                if (_useHintsForDescription)
                {
                    txt = doc.CreateTextNode(gc.EncodedHints ?? "");
                }
                else
                {
                    txt = doc.CreateTextNode(string.Format("{0} by {1}, {2} ({3}/{4})", transformedGeocacheName(gc.Name), gc.Owner, gc.GeocacheType.GPXTag, gc.Difficulty.ToString("0.#").Replace(',', '.'), gc.Terrain.ToString("0.#").Replace(',', '.')));
                }
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el = doc.CreateElement("url");
                txt = doc.CreateTextNode(gc.Url);
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el = doc.CreateElement("urlname");
                txt = doc.CreateTextNode(transformedGeocacheName(gc.Name));
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el = doc.CreateElement("sym");
                if (gc.Found)
                {
                    txt = doc.CreateTextNode("Geocache Found");
                }
                else
                {
                    txt = doc.CreateTextNode("Geocache");
                }
                el.AppendChild(txt);
                wpt.AppendChild(el);

                el = doc.CreateElement("type");
                txt = doc.CreateTextNode(string.Format("Geocache|{0}", gc.GeocacheType.GPXTag));
                el.AppendChild(txt);
                wpt.AppendChild(el);

                XmlElement cache = doc.CreateElement("groundspeak_cache");
                wpt.AppendChild(cache);
                attr = doc.CreateAttribute("id");
                txt = doc.CreateTextNode(gc.ID);
                attr.AppendChild(txt);
                cache.Attributes.Append(attr);

                attr = doc.CreateAttribute("available");
                txt = doc.CreateTextNode(gc.Available.ToString().ToLower());
                attr.AppendChild(txt);
                cache.Attributes.Append(attr);

                attr = doc.CreateAttribute("archived");
                txt = doc.CreateTextNode(gc.Archived.ToString().ToLower());
                attr.AppendChild(txt);
                cache.Attributes.Append(attr);

                if (_gpxVersion >= V102)
                {
                    attr = doc.CreateAttribute("memberonly");
                    txt = doc.CreateTextNode(gc.MemberOnly.ToString().ToLower());
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);

                    attr = doc.CreateAttribute("customcoords");
                    txt = doc.CreateTextNode(gc.CustomCoords.ToString().ToLower());
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);

                    attr = doc.CreateAttribute("_xmlns_groundspeak");
                    txt = doc.CreateTextNode("http://www.groundspeak.com/cache/1/0/2");
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);
                }
                else if (_gpxVersion == V101)
                {
                    attr = doc.CreateAttribute("_xmlns_groundspeak");
                    txt = doc.CreateTextNode("http://www.groundspeak.com/cache/1/0/1");
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);
                }
                else
                {
                    attr = doc.CreateAttribute("_xmlns_groundspeak");
                    txt = doc.CreateTextNode("http://www.groundspeak.com/cache/1/0");
                    attr.AppendChild(txt);
                    cache.Attributes.Append(attr);
                }

                el = doc.CreateElement("groundspeak_name");
                txt = doc.CreateTextNode(transformedGeocacheName(gc.Name));
                el.AppendChild(txt);
                cache.AppendChild(el);

                el = doc.CreateElement("groundspeak_placed_by");
                txt = doc.CreateTextNode(gc.PlacedBy);
                el.AppendChild(txt);
                cache.AppendChild(el);

                el = doc.CreateElement("groundspeak_owner");
                txt = doc.CreateTextNode(gc.Owner);
                el.AppendChild(txt);
                cache.AppendChild(el);
                if (_gpxVersion >= V102)
                {
                    attr = doc.CreateAttribute("id");
                    txt = doc.CreateTextNode(gc.OwnerId);
                    attr.AppendChild(txt);
                    el.Attributes.Append(attr);
                }

                el = doc.CreateElement("groundspeak_type");
                txt = doc.CreateTextNode(gc.GeocacheType.GPXTag);
                el.AppendChild(txt);
                cache.AppendChild(el);
                if (_gpxVersion >= V102)
                {
                    attr = doc.CreateAttribute("id");
                    txt = doc.CreateTextNode(gc.GeocacheType.ID.ToString());
                    attr.AppendChild(txt);
                    el.Attributes.Append(attr);
                }

                el = doc.CreateElement("groundspeak_container");
                txt = doc.CreateTextNode(gc.Container.Name);
                el.AppendChild(txt);
                cache.AppendChild(el);
                if (_gpxVersion >= V102)
                {
                    attr = doc.CreateAttribute("id");
                    txt = doc.CreateTextNode(gc.Container.ID.ToString());
                    attr.AppendChild(txt);
                    el.Attributes.Append(attr);
                }

                if (_gpxVersion >= V101)
                {
                    if (gc.AttributeIds.Count > 0)
                    {
                        XmlElement attrs = doc.CreateElement("groundspeak_attributes");
                        cache.AppendChild(attrs);
                        foreach (int attrId in gc.AttributeIds)
                        {
                            int id = (int)Math.Abs(attrId);

                            el = doc.CreateElement("groundspeak_attribute");
                            txt = doc.CreateTextNode(Utils.DataAccess.GetGeocacheAttribute(_core.GeocacheAttributes, id).Name);
                            el.AppendChild(txt);
                            attrs.AppendChild(el);
                            attr = doc.CreateAttribute("id");
                            txt = doc.CreateTextNode(id.ToString());
                            attr.AppendChild(txt);
                            el.Attributes.Append(attr);

                            attr = doc.CreateAttribute("inc");
                            if (attrId < 0)
                            {
                                txt = doc.CreateTextNode("0");
                            }
                            else
                            {
                                txt = doc.CreateTextNode("1");
                            }
                            attr.AppendChild(txt);
                            el.Attributes.Append(attr);
                        }
                    }
                }

                el = doc.CreateElement("groundspeak_difficulty");
                txt = doc.CreateTextNode(gc.Difficulty.ToString("0.#").Replace(',', '.'));
                el.AppendChild(txt);
                cache.AppendChild(el);

                el = doc.CreateElement("groundspeak_terrain");
                txt = doc.CreateTextNode(gc.Terrain.ToString("0.#").Replace(',', '.'));
                el.AppendChild(txt);
                cache.AppendChild(el);

                el = doc.CreateElement("groundspeak_country");
                txt = doc.CreateTextNode(gc.Country ?? "");
                el.AppendChild(txt);
                cache.AppendChild(el);

                el = doc.CreateElement("groundspeak_state");
                txt = doc.CreateTextNode(gc.State ?? "");
                el.AppendChild(txt);
                cache.AppendChild(el);

                el = doc.CreateElement("groundspeak_short_description");
                if (_addFieldnotesToDescription && gc.ContainsNote)
                {
                    StringBuilder sb = new StringBuilder();
                    if (gc.ShortDescriptionInHtml)
                    {
                        if (!string.IsNullOrEmpty(gc.PersonaleNote))
                        {
                            sb.AppendFormat("<p>{0}</p><br />", System.Web.HttpUtility.HtmlEncode(gc.PersonaleNote));
                        }
                        if (!string.IsNullOrEmpty(gc.Notes))
                        {
                            if (gc.Notes.StartsWith("<p>", StringComparison.OrdinalIgnoreCase))
                            {
                                sb.AppendFormat("{0}<br />", gc.Notes);
                            }
                            else
                            {
                                sb.AppendFormat("<p>{0}</p><br />", gc.Notes);
                            }
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(gc.PersonaleNote))
                        {
                            sb.AppendFormat("{0}\r\n\r\n", gc.PersonaleNote);
                        }
                        if (!string.IsNullOrEmpty(gc.Notes))
                        {
                            sb.AppendFormat("{0}\r\n\r\n", gc.Notes);
                        }
                    }
                    sb.Append(gc.ShortDescription ?? "");
                    txt = doc.CreateTextNode(sb.ToString());
                }
                else
                {
                    txt = doc.CreateTextNode(gc.ShortDescription ?? "");
                }
                el.AppendChild(txt);
                cache.AppendChild(el);
                attr = doc.CreateAttribute("html");
                txt = doc.CreateTextNode(gc.ShortDescriptionInHtml.ToString().ToLower());
                attr.AppendChild(txt);
                el.Attributes.Append(attr);

                el = doc.CreateElement("groundspeak_long_description");
                if (_addAdditionWaypointsToDescription)
                {
                    List<Framework.Data.Waypoint> wpts = Utils.DataAccess.GetWaypointsFromGeocache(_core.Waypoints, gc.Code);
                    if (wpts != null && wpts.Count > 0)
                    {
                        StringBuilder awp = new StringBuilder();
                        if (gc.LongDescriptionInHtml)
                        {
                            awp.AppendFormat("{0}<br /><br /><h2>Additiona Hidden Waypoints</h2>", gc.LongDescription ?? "");
                            awp.Append("<p>");
                            foreach (Framework.Data.Waypoint wp in wpts)
                            {
                                awp.AppendFormat("{0} - {1} ({2})<br />", HttpUtility.HtmlEncode(wp.ID ?? ""), HttpUtility.HtmlEncode(wp.Description ?? ""), HttpUtility.HtmlEncode(Utils.LanguageSupport.Instance.GetTranslation(wp.WPType.Name)));
                                if (wp.Lat != null && wp.Lon != null)
                                {
                                    awp.AppendFormat("{0}<br />", HttpUtility.HtmlEncode(Utils.Conversion.GetCoordinatesPresentation((double)wp.Lat, (double)wp.Lon)));
                                }
                                else
                                {
                                    awp.Append("???<br />");
                                }
                                awp.AppendFormat("{0}<br /><br />", HttpUtility.HtmlEncode(wp.Comment ?? ""));
                            }
                            awp.Append("</p>");
                        }
                        else
                        {
                            awp.AppendFormat("{0}\r\n\r\nAdditiona Hidden Waypoints", gc.LongDescription ?? "");
                            foreach (Framework.Data.Waypoint wp in wpts)
                            {
                                awp.AppendFormat("{0} - {1} ({2})\r\n", wp.ID ?? "", wp.Description ?? "", Utils.LanguageSupport.Instance.GetTranslation(wp.WPType.Name));
                                if (wp.Lat != null && wp.Lon != null)
                                {
                                    awp.AppendFormat("{0}\r\n", Utils.Conversion.GetCoordinatesPresentation((double)wp.Lat, (double)wp.Lon));
                                }
                                else
                                {
                                    awp.Append("???\r\n");
                                }
                                awp.AppendFormat("{0}\r\n\r\n", wp.Comment ?? "");
                            }
                        }
                        txt = doc.CreateTextNode(awp.ToString());
                    }
                    else
                    {
                        txt = doc.CreateTextNode(gc.LongDescription ?? "");
                    }
                }
                else
                {
                    txt = doc.CreateTextNode(gc.LongDescription ?? "");
                }
                el.AppendChild(txt);
                cache.AppendChild(el);
                attr = doc.CreateAttribute("html");
                txt = doc.CreateTextNode(gc.LongDescriptionInHtml.ToString().ToLower());
                attr.AppendChild(txt);
                el.Attributes.Append(attr);

                el = doc.CreateElement("groundspeak_encoded_hints");
                txt = doc.CreateTextNode(gc.EncodedHints ?? "");
                el.AppendChild(txt);
                cache.AppendChild(el);

                if (_gpxVersion >= V102)
                {
                    el = doc.CreateElement("groundspeak_personal_note");
                    txt = doc.CreateTextNode(gc.PersonaleNote ?? "");
                    el.AppendChild(txt);
                    cache.AppendChild(el);

                    el = doc.CreateElement("groundspeak_favorite_points");
                    txt = doc.CreateTextNode(gc.Favorites.ToString());
                    el.AppendChild(txt);
                    cache.AppendChild(el);
                }

                List<Framework.Data.Log> logs = Utils.DataAccess.GetLogs(_core.Logs, gc.Code).Take(_maxLogCount).ToList();
                if (logs.Count > 0)
                {
                    XmlElement logsel = doc.CreateElement("groundspeak_logs");
                    cache.AppendChild(logsel);
                    foreach (var l in logs)
                    {
                        XmlElement lel = doc.CreateElement("groundspeak_log");
                        logsel.AppendChild(lel);
                        attr = doc.CreateAttribute("id");
                        txt = doc.CreateTextNode(l.ID);
                        attr.AppendChild(txt);
                        lel.Attributes.Append(attr);

                        el = doc.CreateElement("groundspeak_date");
                        txt = doc.CreateTextNode(string.Format("{0}Z",l.Date.ToString("s")));
                        el.AppendChild(txt);
                        lel.AppendChild(el);

                        el = doc.CreateElement("groundspeak_type");
                        txt = doc.CreateTextNode(l.LogType.Name);
                        el.AppendChild(txt);
                        lel.AppendChild(el);
                        if (_gpxVersion >= V102)
                        {
                            attr = doc.CreateAttribute("id");
                            txt = doc.CreateTextNode(l.LogType.ID.ToString());
                            attr.AppendChild(txt);
                            el.Attributes.Append(attr);
                        }

                        el = doc.CreateElement("groundspeak_finder");
                        txt = doc.CreateTextNode(l.Finder);
                        el.AppendChild(txt);
                        lel.AppendChild(el);
                        attr = doc.CreateAttribute("id");
                        txt = doc.CreateTextNode(l.FinderId);
                        attr.AppendChild(txt);
                        el.Attributes.Append(attr);

                        el = doc.CreateElement("groundspeak_text");
                        txt = doc.CreateTextNode(l.Text);
                        el.AppendChild(txt);
                        lel.AppendChild(el);
                        attr = doc.CreateAttribute("encoded");
                        txt = doc.CreateTextNode(l.Encoded.ToString().ToLower());
                        attr.AppendChild(txt);
                        el.Attributes.Append(attr);
                    }
                }
                //todo, geocache images / trackables

                _index++;
            }
            using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
            {
                doc.Save(tmp.Path);
                result = System.IO.File.ReadAllText(tmp.Path);
                result = result.Replace("<groundspeak_", "<groundspeak:");
                result = result.Replace("</groundspeak_", "</groundspeak:");
                result = result.Replace("_xmlns_groundspeak", "xmlns:groundspeak");
            }
            return validateXml(result);
        }
Example #27
0
        protected override void ExportMethod()
        {
            string gpxFile;
            string wptFile;

            System.IO.TemporaryFile tmp    = null;
            System.IO.TemporaryFile tmpwpt = null;
            if (PluginSettings.Instance.ZipFile)
            {
                tmp     = new System.IO.TemporaryFile(false);
                gpxFile = tmp.Path;
                tmpwpt  = new System.IO.TemporaryFile(false);
                wptFile = tmpwpt.Path;
            }
            else
            {
                gpxFile = _filename;
                wptFile = string.Format("{0}-wpts.gpx", gpxFile.Substring(0, gpxFile.Length - 4));
            }
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_EXPORTINGGPX, STR_CREATINGFILE, _gpxGenerator.Count, 0))
            {
                DateTime nextUpdate = DateTime.Now.AddSeconds(2);
                //create file stream (if not zipped actual file and if zipped tmp file
                using (System.IO.StreamWriter sw = System.IO.File.CreateText(gpxFile))
                    using (System.IO.StreamWriter swwp = System.IO.File.CreateText(wptFile))
                    {
                        //generate header
                        sw.Write(_gpxGenerator.Start());
                        if (PluginSettings.Instance.AddWaypoints)
                        {
                            swwp.Write(_gpxGenerator.WaypointData());
                        }
                        //preserve mem and do for each cache the export
                        for (int i = 0; i < _gpxGenerator.Count; i++)
                        {
                            sw.WriteLine(_gpxGenerator.Next());
                            if (PluginSettings.Instance.AddWaypoints)
                            {
                                string s = _gpxGenerator.WaypointData();
                                if (!string.IsNullOrEmpty(s))
                                {
                                    swwp.WriteLine(s);
                                }
                            }
                            if (DateTime.Now >= nextUpdate)
                            {
                                progress.UpdateProgress(STR_EXPORTINGGPX, STR_CREATINGFILE, _gpxGenerator.Count, i + 1);
                                nextUpdate = DateTime.Now.AddSeconds(2);
                            }
                        }
                        //finalize
                        sw.Write(_gpxGenerator.Finish());
                        if (PluginSettings.Instance.AddWaypoints)
                        {
                            swwp.Write(_gpxGenerator.Finish());
                        }
                    }

                if (PluginSettings.Instance.ZipFile)
                {
                    try
                    {
                        List <string> filenames = new List <string>();
                        filenames.Add(gpxFile);
                        if (PluginSettings.Instance.AddWaypoints)
                        {
                            filenames.Add(wptFile);
                        }

                        using (ZipOutputStream s = new ZipOutputStream(System.IO.File.Create(_filename)))
                        {
                            s.SetLevel(9); // 0-9, 9 being the highest compression

                            byte[] buffer = new byte[4096];
                            bool   wpt    = false;

                            foreach (string file in filenames)
                            {
                                ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(wpt ? _filename.ToLower().Replace(".zip", "-wpts.gpx") : _filename.ToLower().Replace(".zip", ".gpx")));

                                entry.DateTime = DateTime.Now;
                                s.PutNextEntry(entry);

                                using (System.IO.FileStream fs = System.IO.File.OpenRead(file))
                                {
                                    int sourceBytes;
                                    do
                                    {
                                        sourceBytes = fs.Read(buffer, 0,
                                                              buffer.Length);

                                        s.Write(buffer, 0, sourceBytes);
                                    } while (sourceBytes > 0);
                                }

                                wpt = true;
                            }
                            s.Finish();
                            s.Close();
                        }
                    }
                    catch
                    {
                    }
                }
                else
                {
                    if (!PluginSettings.Instance.AddWaypoints)
                    {
                        System.IO.File.Delete(wptFile);
                    }
                }
            }
            if (tmp != null)
            {
                tmp.Dispose();
                tmp = null;
            }
            if (tmpwpt != null)
            {
                tmpwpt.Dispose();
                tmpwpt = null;
            }
        }