Exemplo n.º 1
0
        public static Core.Data.Log AddLog(Core.Storage.Database db, OKAPIService.Log lg, string finder, string finderId)
        {
            Core.Data.Log result = null;
            if (lg != null)
            {
                result = db.LogCollection.GetLog(lg.uuid);

                Core.Data.ILogData lgData;
                if (result == null)
                {
                    lgData    = new Core.Data.LogData();
                    lgData.ID = lg.uuid;
                }
                else
                {
                    lgData = result;
                }

                lgData.DataFromDate = DateTime.Now;
                lgData.Date         = DateTime.Parse(lg.date);
                lgData.Encoded      = false;
                if (lg.user == null)
                {
                    lgData.Finder   = finder;
                    lgData.FinderId = finderId;
                }
                else
                {
                    lgData.Finder   = lg.user.username;
                    lgData.FinderId = lg.user.uuid;
                }
                lgData.GeocacheCode = lg.cache_code;
                lgData.Text         = lg.comment;
                lgData.LogType      = Utils.DataAccess.GetLogType(lg.type);

                if (lgData is Core.Data.LogData)
                {
                    if (Utils.DataAccess.AddLog(db, lgData as Core.Data.LogData))
                    {
                        result = db.LogCollection.GetLog(lgData.ID);
                    }
                }
            }
            return(result);
        }
Exemplo n.º 2
0
        public static Core.Data.Log ImportLog(Core.Storage.Database db, LiveV6.GeocacheLog lg)
        {
            Core.Data.Log result = null;
            if (lg != null)
            {
                result = db.LogCollection.GetLog(lg.Code);

                Core.Data.ILogData lgData;
                if (result == null)
                {
                    lgData    = new Core.Data.LogData();
                    lgData.ID = lg.Code;
                }
                else
                {
                    lgData = result;
                }

                lgData.DataFromDate = DateTime.Now;
                lgData.Date         = lg.VisitDate;
                lgData.Encoded      = lg.LogIsEncoded;
                lgData.Finder       = lg.Finder.UserName;
                lgData.FinderId     = lg.Finder.Id.ToString();
                lgData.GeocacheCode = lg.CacheCode;
                lgData.LogType      = Utils.DataAccess.GetLogType((int)lg.LogType.WptLogTypeId);
                lgData.Text         = lg.LogText;

                if (lgData is Core.Data.LogData)
                {
                    if (Utils.DataAccess.AddLog(db, lgData as Core.Data.LogData))
                    {
                        result = db.LogCollection.GetLog(lgData.ID);

                        if (result != null)
                        {
                            ImportLogImages(db, lg.Images, result.ID);
                        }
                    }
                }
            }
            return(result);
        }
Exemplo n.º 3
0
        public void ImportGPX(string gpxDoc)
        {
            bool isGeoSpy = false;
            try
            {
                string firstPart;
                if (gpxDoc.Length < 2000)
                {
                    firstPart = gpxDoc;
                }
                else
                {
                    firstPart = gpxDoc.Substring(0, 2000);
                }
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(gpxDoc);
                XmlElement root = doc.DocumentElement;
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

                if (firstPart.IndexOf("http://www.topografix.com/GPX/1/1", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    nsmgr.AddNamespace("x", "http://www.topografix.com/GPX/1/1");
                }
                else
                {
                    nsmgr.AddNamespace("x", "http://www.topografix.com/GPX/1/0");
                }

                if (firstPart.IndexOf("http://geoget.ararat.cz/GpxExtensions/v2", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    //GeoSpy
                    isGeoSpy = true;
                    _cachesGpxVersion = new Version(1, 0, 0);
                    nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0");
                }
                else if (firstPart.IndexOf("http://www.groundspeak.com/cache/1/0/2", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0/2");
                    _cachesGpxVersion = new Version(1, 0, 2);
                }
                else if (firstPart.IndexOf("http://www.groundspeak.com/cache/1/0/1", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    if (firstPart.IndexOf("creator=\"Opencaching.de - http://www.opencaching.de\"") > 0)
                    {
                        nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0");
                    }
                    else if (firstPart.IndexOf("http://www.opencaching.com/xmlschemas/opencaching/1/0") > 0)
                    {
                        nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0");
                    }
                    else
                    {
                        nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0/1");
                    }
                    _cachesGpxVersion = new Version(1, 0, 1);
                }
                else if (firstPart.IndexOf("http://www.groundspeak.com/cache/1/1", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/1");
                    _cachesGpxVersion = new Version(1, 1, 0);
                }
                else
                {
                    nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0");
                    _cachesGpxVersion = new Version(1, 0, 0);
                }

                if (isGeoSpy)
                {
                    _gpxDataTime = DateTime.Parse(root.SelectSingleNode("x:metadata", nsmgr).SelectSingleNode("x:time", nsmgr).InnerText);
                }
                else
                {
                    _gpxDataTime = DateTime.Parse(root.SelectSingleNode("x:time", nsmgr).InnerText);
                }

                XmlNodeList wps = root.SelectNodes("x:wpt", nsmgr);
                if (wps != null)
                {
                    Version V102 = new Version(1, 0, 2);
                    foreach (XmlNode wp in wps)
                    {
                        XmlNode n;
                        if (isGeoSpy)
                        {
                            n = wp.SelectSingleNode("x:extensions", nsmgr).SelectSingleNode("y:cache", nsmgr);
                        }
                        else
                        {
                            n = wp.SelectSingleNode("y:cache", nsmgr);
                        }
                        if (n == null)
                        {
                            //assume Child waypoint and yeah, well....multiple sources like GC or OB should be handled
                            //TODO: check source and don't assume GC
                            //check if it is a child waypoint by checking the name
                            string fullwpname = wp.SelectSingleNode("x:name", nsmgr).InnerText;
                            string wpname = fullwpname.Substring(2);

                            Core.Data.Geocache parentGeocache = null;
                            string parentCode;
                            parentGeocache = (from g in Core.ApplicationData.Instance.ActiveDatabase.GeocacheCollection where g.Code.Substring(2) == wpname select g).FirstOrDefault();
                            if (parentGeocache == null)
                            {
                                //parent is not available
                                //now what?
                                //just add it
                                //continue;
                                parentCode = string.Concat("GC", wpname);
                            }
                            else
                            {
                                parentCode = parentGeocache.Code;
                            }

                            Core.Data.IWaypointData cwp = null;
                            cwp = (from a in Utils.DataAccess.GetWaypointsFromGeocache(Core.ApplicationData.Instance.ActiveDatabase, parentCode) where a.Code == fullwpname select a).FirstOrDefault();
                            if (cwp == null)
                            {
                                cwp = new Core.Data.WaypointData();
                            }
                            else
                            {
                                if (cwp.DataFromDate >= _gpxDataTime)
                                {
                                    continue;
                                }
                            }

                            cwp.Code = wp.SelectSingleNode("x:name", nsmgr).InnerText;
                            cwp.GeocacheCode = string.Concat(parentCode.Substring(0, 2), cwp.Code.Substring(2));
                            cwp.DataFromDate = _gpxDataTime;
                            cwp.Comment = wp.SelectSingleNode("x:cmt", nsmgr).InnerText;
                            if (SafeAttributeInnerText(wp, "lat", "").Length > 0)
                            {
                                cwp.Lat = Utils.Conversion.StringToDouble(wp.Attributes["lat"].InnerText);
                                cwp.Lon = Utils.Conversion.StringToDouble(wp.Attributes["lon"].InnerText);
                                if (Math.Abs((double)cwp.Lat) < 0.0001 && Math.Abs((double)cwp.Lon) < 0.0001)
                                {
                                    cwp.Lat = null;
                                    cwp.Lon = null;
                                }
                            }
                            else
                            {
                                cwp.Lat = null;
                                cwp.Lon = null;
                            }
                            cwp.Description = wp.SelectSingleNode("x:desc", nsmgr).InnerText;
                            cwp.ID = cwp.Code;
                            cwp.Name = cwp.Code;
                            cwp.Comment = wp.SelectSingleNode("x:cmt", nsmgr).InnerText;
                            cwp.Time = DateTime.Parse(wp.SelectSingleNode("x:time", nsmgr).InnerText);
                            cwp.Url = SafeInnerText(wp.SelectSingleNode("x:url", nsmgr), "");
                            cwp.UrlName = SafeInnerText(wp.SelectSingleNode("x:urlname", nsmgr), "");
                            cwp.WPType = Utils.DataAccess.GetWaypointType(wp.SelectSingleNode("x:sym", nsmgr).InnerText);

                            if (cwp is Core.Data.WaypointData)
                            {
                                Utils.DataAccess.AddWaypoint(Core.ApplicationData.Instance.ActiveDatabase, cwp as Core.Data.WaypointData);
                            }
                            continue;
                        }

                        string code = wp.SelectSingleNode("x:name", nsmgr).InnerText;

                        Core.Data.IGeocacheData gc = null;
                        gc = (from a in Core.ApplicationData.Instance.ActiveDatabase.GeocacheCollection where a.Code == code select a).FirstOrDefault();
                        if (gc == null)
                        {
                            gc = new Core.Data.GeocacheData();
                        }
                        else
                        {
                            if (gc.DataFromDate >= _gpxDataTime)
                            {
                                continue;
                            }
                        }

                        gc.Available = bool.Parse(n.Attributes["available"].InnerText);
                        gc.Archived = bool.Parse(SafeInnerText(n.Attributes["archived"], "False"));

                        if (!(gc is Core.Data.Geocache) || !(gc as Core.Data.Geocache).Locked)
                        {
                            gc.Lat = Utils.Conversion.StringToDouble(SafeAttributeInnerText(wp, "lat", "0.0"));
                            gc.Lon = Utils.Conversion.StringToDouble(SafeAttributeInnerText(wp, "lon", "0.0"));
                            gc.Code = code;
                            gc.DataFromDate = _gpxDataTime;
                            gc.Name = n.SelectSingleNode("y:name", nsmgr).InnerText;
                            gc.PublishedTime = DateTime.Parse(wp.SelectSingleNode("x:time", nsmgr).InnerText);
                            if (isGeoSpy)
                            {
                                gc.Url = wp.SelectSingleNode("x:link", nsmgr).Attributes["href"].Value;
                            }
                            else
                            {
                                gc.Url = SafeInnerText(wp.SelectSingleNode("x:url", nsmgr), "");
                            }
                            if (SafeInnerText(wp.SelectSingleNode("x:sym", nsmgr), "").EndsWith(" Found"))
                            {
                                gc.Found = true;
                            }
                            gc.Country = SafeInnerText(n.SelectSingleNode("y:country", nsmgr), "");
                            gc.State = SafeInnerText(n.SelectSingleNode("y:state", nsmgr), "");
                            gc.OwnerId = SafeAttributeInnerText(n.SelectSingleNode("y:owner", nsmgr), "id", "");
                            if (_cachesGpxVersion >= V102)
                            {
                                gc.GeocacheType = Utils.DataAccess.GetGeocacheType(int.Parse(SafeAttributeInnerText(n.SelectSingleNode("y:type", nsmgr), "id", "-1")));
                                gc.Container = Utils.DataAccess.GetGeocacheContainer(int.Parse(SafeAttributeInnerText(n.SelectSingleNode("y:container", nsmgr), "id", "-1")));
                                gc.Favorites = int.Parse(SafeInnerText(n.SelectSingleNode("y:favorite_points", nsmgr), "0"));
                                gc.MemberOnly = bool.Parse(SafeInnerText(n.Attributes["memberonly"], "False"));
                                //gc.CustomCoords = bool.Parse(SafeInnerText(n.Attributes["customcoords"], "False"));
                                gc.PersonalNote = SafeInnerText(n.Attributes["personal_note"], "");
                            }
                            else
                            {
                                string srchTxt = SafeInnerText(n.SelectSingleNode("y:type", nsmgr), "Unknown");
                                if (!srchTxt.StartsWith("Groundspeak"))
                                {
                                    if (srchTxt.Contains("Trash"))
                                    {
                                        srchTxt = "Trash";
                                    }
                                    else
                                    {
                                        int pos = srchTxt.IndexOf(' ');
                                        if (pos > 0)
                                        {
                                            srchTxt = srchTxt.Substring(0, pos);
                                        }
                                    }
                                }
                                gc.GeocacheType = Utils.DataAccess.GetGeocacheType(srchTxt);
                                if (isGeoSpy)
                                {
                                    gc.Container = Utils.DataAccess.GetGeocacheContainer("Virtual");
                                }
                                else
                                {
                                    gc.Container = Utils.DataAccess.GetGeocacheContainer(SafeInnerText(n.SelectSingleNode("y:container", nsmgr), "Unknown"));
                                }
                            }
                            gc.PlacedBy = SafeInnerText(n.SelectSingleNode("y:placed_by", nsmgr), "");
                            gc.Owner = SafeInnerText(n.SelectSingleNode("y:owner", nsmgr), "");
                            gc.Terrain = Utils.Conversion.StringToDouble(SafeInnerText(n.SelectSingleNode("y:terrain", nsmgr), "1"));
                            gc.Difficulty = Utils.Conversion.StringToDouble(SafeInnerText(n.SelectSingleNode("y:difficulty", nsmgr), "1"));
                            gc.ShortDescription = SafeInnerText(n.SelectSingleNode("y:short_description", nsmgr), "");
                            gc.ShortDescriptionInHtml = bool.Parse(SafeAttributeInnerText(n.SelectSingleNode("y:short_description", nsmgr), "html", "False"));
                            gc.LongDescription = SafeInnerText(n.SelectSingleNode("y:long_description", nsmgr), "");
                            gc.LongDescriptionInHtml = bool.Parse(SafeAttributeInnerText(n.SelectSingleNode("y:long_description", nsmgr), "html", "False"));
                            gc.EncodedHints = SafeInnerText(n.SelectSingleNode("y:encoded_hints", nsmgr), "");

                            gc.AttributeIds = new List<int>();
                            XmlNode attrs = n.SelectSingleNode("y:attributes", nsmgr);
                            if (attrs != null && attrs.ChildNodes != null)
                            {
                                foreach (XmlNode attr in attrs.ChildNodes)
                                {
                                    int attrId = int.Parse(attr.Attributes["id"].InnerText);
                                    int attrInc = int.Parse(SafeAttributeInnerText(attr, "inc", "1"));
                                    if (attrInc == 1)
                                    {
                                        gc.AttributeIds.Add(attrId);
                                    }
                                    else
                                    {
                                        gc.AttributeIds.Add(-1 * attrId);
                                    }
                                }
                            }

                            bool gcAdded = true;
                            if (gc is Core.Data.GeocacheData)
                            {
                                gcAdded = Utils.DataAccess.AddGeocache(Core.ApplicationData.Instance.ActiveDatabase, gc as Core.Data.GeocacheData);
                            }
                            if (gcAdded)
                            {
                                gc = (from a in Core.ApplicationData.Instance.ActiveDatabase.GeocacheCollection where a.Code == code select a).FirstOrDefault();
                                Utils.Calculus.SetDistanceAndAngleGeocacheFromLocation(gc as Core.Data.Geocache, Core.ApplicationData.Instance.CenterLocation);


                                //Logs
                                XmlNode ln = n.SelectSingleNode("y:logs", nsmgr);
                                if (ln != null)
                                {
                                    XmlNodeList logs = ln.SelectNodes("y:log", nsmgr);
                                    if (logs != null)
                                    {
                                        foreach (XmlNode l in logs)
                                        {

                                            string lid = SafeAttributeInnerText(l, "id", "");

                                            if (lid.StartsWith("GL"))
                                            {
                                                //lg.ID = lid;
                                            }
                                            else
                                            {
                                                if (string.IsNullOrEmpty(lid) || lid.StartsWith("-"))
                                                {
                                                    continue;
                                                }
                                                try
                                                {
                                                    lid = string.Concat("GL", Utils.Conversion.GetCacheCodeFromCacheID(int.Parse(lid)).Substring(2));
                                                }
                                                catch
                                                {
                                                    continue;
                                                }
                                            }

                                            Core.Data.ILogData lg = null;
                                            lg = (from a in Utils.DataAccess.GetLogs(Core.ApplicationData.Instance.ActiveDatabase, gc.Code) where a.ID == lid select a).FirstOrDefault();
                                            if (lg == null)
                                            {
                                                lg = new Core.Data.LogData();
                                            }

                                            lg.ID = lid;
                                            lg.GeocacheCode = gc.Code;
                                            lg.DataFromDate = _gpxDataTime;
                                            lg.Date = DateTime.Parse(l.SelectSingleNode("y:date", nsmgr).InnerText);
                                            lg.Encoded = bool.Parse(l.SelectSingleNode("y:text", nsmgr).Attributes["encoded"].InnerText);
                                            if (isGeoSpy)
                                            {
                                                lg.Text = GAPPSF.Utils.Conversion.StripHtmlTags(System.Web.HttpUtility.HtmlDecode(l.SelectSingleNode("y:text", nsmgr).InnerText).Replace("</p>", "\r\n\r\n"));
                                            }
                                            else
                                            {
                                                lg.Text = l.SelectSingleNode("y:text", nsmgr).InnerText;
                                            }
                                            lg.Finder = l.SelectSingleNode("y:finder", nsmgr).InnerText;
                                            if (l.SelectSingleNode("y:finder", nsmgr).Attributes["id"] != null)
                                            {
                                                lg.FinderId = l.SelectSingleNode("y:finder", nsmgr).Attributes["id"].InnerText;
                                            }
                                            else
                                            {
                                                //GCTour has no finder id
                                                lg.FinderId = "1";
                                            }
                                            if (_cachesGpxVersion >= V102)
                                            {
                                                lg.LogType = Utils.DataAccess.GetLogType(int.Parse(l.SelectSingleNode("y:type", nsmgr).Attributes["id"].InnerText));
                                            }
                                            else
                                            {
                                                lg.LogType = Utils.DataAccess.GetLogType(l.SelectSingleNode("y:type", nsmgr).InnerText);
                                            }

                                            if (lg is Core.Data.LogData)
                                            {
                                                Utils.DataAccess.AddLog(Core.ApplicationData.Instance.ActiveDatabase, lg as Core.Data.LogData);
                                            }

                                            //log images
                                            XmlNode lni = l.SelectSingleNode("y:images", nsmgr);
                                            if (lni != null)
                                            {
                                                XmlNodeList logis = lni.SelectNodes("y:image", nsmgr);
                                                if (logis != null)
                                                {
                                                    foreach (XmlNode li in logis)
                                                    {
                                                        string url = li.SelectSingleNode("y:url", nsmgr).InnerText;

                                                        Core.Data.ILogImageData lgi = null;
                                                        lgi = (from a in Utils.DataAccess.GetLogImages(Core.ApplicationData.Instance.ActiveDatabase, lg.ID) where a.ID == url select a).FirstOrDefault();
                                                        if (lgi == null)
                                                        {
                                                            lgi = new Core.Data.LogImageData();
                                                        }
                                                        lgi.Url = url;
                                                        lgi.ID = lgi.Url;
                                                        lgi.LogId = lg.ID;
                                                        lgi.Name = li.SelectSingleNode("y:name", nsmgr).InnerText;
                                                        lgi.DataFromDate = _gpxDataTime;

                                                        if (lgi is Core.Data.LogImageData)
                                                        {
                                                            Utils.DataAccess.AddLogImage(Core.ApplicationData.Instance.ActiveDatabase, lgi as Core.Data.LogImageData);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch(Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }
        }
Exemplo n.º 4
0
        private static bool Import(Database database, string filename)
        {
            try
            {
                using (Utils.ProgressBlock allprog = new ProgressBlock("ImportGSAKDatabase", "Importing", 6, 0))
                {
                    System.Collections.Hashtable logTypes = new System.Collections.Hashtable();
                    String connect = String.Format("data source=file:{0}", filename);
                    using (SqliteConnection dbcon = new SqliteConnection(connect))
                    {
                        //System.Diagnostics.Debugger.Break();
                        logTypes.Add("Found it", 2);
                        logTypes.Add("Didn't find it", 3);
                        logTypes.Add("Write note", 4);
                        logTypes.Add("Archive", 5);
                        logTypes.Add("Needs Archived", 7);
                        logTypes.Add("Will Attend", 9);
                        logTypes.Add("Attended", 10);
                        logTypes.Add("Webcam Photo Taken", 11);
                        logTypes.Add("Unarchive", 12);
                        logTypes.Add("Temporarily Disable Listing", 22);
                        logTypes.Add("Temporarily Disable", 22);
                        logTypes.Add("Enable Listing", 23);
                        logTypes.Add("Enable", 23);
                        logTypes.Add("Publish Listing", 24);
                        logTypes.Add("Publish", 24);
                        logTypes.Add("Retract Listing", 25);
                        logTypes.Add("Retract", 25);
                        logTypes.Add("Needs Maintenance", 45);
                        logTypes.Add("Owner Maintenance", 46);
                        logTypes.Add("Update Coordinates", 47);
                        logTypes.Add("Post Reviewer Note", 68);
                        logTypes.Add("Announcement", 74);

                        dbcon.Open();

                        SqliteCommand lookup = new SqliteCommand("select aId, aInc from attributes where aCode = @Code", dbcon);
                        lookup.CommandType = CommandType.Text;
                        DbParameter par = lookup.CreateParameter();
                        par.Direction     = ParameterDirection.Input;
                        par.ParameterName = "@Code";
                        lookup.Parameters.Add(par);
                        lookup.Prepare();

                        SqliteCommand import = new SqliteCommand("select count(1) from caches", dbcon);
                        import.CommandType = CommandType.Text;

                        int index   = 0;
                        int gcCount = (int)(long)import.ExecuteScalar();
                        if (gcCount > 0)
                        {
                            DateTime progShow = DateTime.Now.AddSeconds(1);
                            using (Utils.ProgressBlock prog = new ProgressBlock("ImportingGeocaches", 1, 0))
                            {
                                bool isPremiumAvailable  = false;
                                bool isFavPointAvailable = false;
                                bool isGCNoteAvailable   = false;

                                try
                                {
                                    import.CommandText = "select IsPremium from Caches limit 1";
                                    using (SqliteDataReader checkdr = import.ExecuteReader())
                                    {
                                        isPremiumAvailable = true;
                                    }
                                }
                                catch
                                {
                                }

                                try
                                {
                                    import.CommandText = "select FavPoints from Caches limit 1";
                                    using (SqliteDataReader checkdr = import.ExecuteReader())
                                    {
                                        isFavPointAvailable = true;
                                    }
                                }
                                catch
                                {
                                }

                                try
                                {
                                    import.CommandText = "select gcnote from Caches limit 1";
                                    using (SqliteDataReader checkdr = import.ExecuteReader())
                                    {
                                        isGCNoteAvailable = true;
                                    }
                                }
                                catch
                                {
                                }

                                import.CommandText = "select caches.Code, Name, LastGPXDate, PlacedDate, Latitude, Longitude, Status, " +
                                                     "Archived, Country, State, County, CacheType, PlacedBy, OwnerName, OwnerId, Container, Terrain, Difficulty, ShortHTM" +
                                                     ", LongHTM, " +
                                                     string.Format("{0}", isPremiumAvailable ? "IsPremium, " : "") +
                                                     " HasCorrected, LatOriginal, LonOriginal, UserFlag, Found, " +
                                                     string.Format("{0}", isFavPointAvailable ? "FavPoints, " : "") +
                                                     " ShortDescription, LongDescription, Hints, Url, UserNote" +
                                                     string.Format("{0}", isGCNoteAvailable ? ", gcnote" : "") +
                                                     " from caches" +
                                                     " inner join cachememo on cachememo.code = caches.code";

                                SqliteDataReader dr = import.ExecuteReader();

                                while (dr.Read())
                                {
                                    GeocacheData gc = new GeocacheData();
                                    int          cacheType;
                                    try
                                    {
                                        cacheType = getCacheType(((String)dr["CacheType"])[0]);
                                    }
                                    catch (ArgumentOutOfRangeException)
                                    {
                                        continue;
                                    }
                                    int container = getContainer(((String)dr["Container"])[0]);

                                    gc.Code = (string)dr["code"];
                                    gc.Name = (string)dr["name"];
                                    if (string.IsNullOrEmpty((string)dr["LastGPXDate"]))
                                    {
                                        gc.DataFromDate = DateTime.Now.Date;
                                    }
                                    else
                                    {
                                        gc.DataFromDate = DateTime.Parse((string)dr["LastGPXDate"]);
                                    }
                                    gc.Available    = ((String)dr["Status"]).Equals("A");
                                    gc.Archived     = (int)dr["archived"] != 0;
                                    gc.Country      = (string)dr["country"];
                                    gc.State        = (string)dr["state"];
                                    gc.Municipality = (string)dr["county"];

                                    gc.GeocacheType           = Utils.DataAccess.GetGeocacheType(cacheType);
                                    gc.PlacedBy               = (string)dr["placedby"];
                                    gc.Owner                  = (string)dr["OwnerName"];
                                    gc.OwnerId                = dr["ownerid"].GetType() == typeof(DBNull) ? "" : dr["ownerid"].ToString();
                                    gc.Container              = Utils.DataAccess.GetGeocacheContainer(container);
                                    gc.Terrain                = (double)dr["terrain"];
                                    gc.Difficulty             = (double)dr["difficulty"];
                                    gc.ShortDescription       = (string)dr["ShortDescription"];
                                    gc.ShortDescriptionInHtml = (int)dr["ShortHTM"] != 0;
                                    gc.LongDescription        = (string)dr["LongDescription"];
                                    gc.LongDescriptionInHtml  = (int)dr["LongHTM"] != 0;
                                    gc.EncodedHints           = (string)dr["Hints"];
                                    gc.Url = (string)dr["url"];
                                    if (isPremiumAvailable)
                                    {
                                        gc.MemberOnly = (int)dr["IsPremium"] != 0;
                                    }
                                    else
                                    {
                                        gc.MemberOnly = false;
                                    }
                                    bool customCoords = (int)dr["HasCorrected"] != 0;
                                    if (customCoords)
                                    {
                                        gc.CustomLat = Utils.Conversion.StringToDouble(dr["Latitude"] as String);
                                        gc.CustomLon = Utils.Conversion.StringToDouble(dr["Longitude"] as String);
                                        gc.Lat       = Utils.Conversion.StringToDouble(dr["LatOriginal"] as string);
                                        gc.Lon       = Utils.Conversion.StringToDouble(dr["LonOriginal"] as string);
                                    }
                                    else
                                    {
                                        gc.Lat = Utils.Conversion.StringToDouble(dr["Latitude"] as string);
                                        gc.Lon = Utils.Conversion.StringToDouble(dr["Longitude"] as string);
                                    }

                                    par.Value = gc.Code;
                                    DbDataReader attrs    = lookup.ExecuteReader();
                                    List <int>   attrList = new List <int>();
                                    while (attrs.Read())
                                    {
                                        int attr = (int)(int)attrs["aId"];
                                        if (attrs["aInc"].ToString() == "0")
                                        {
                                            attr *= -1;
                                        }
                                        attrList.Add(attr);
                                    }
                                    attrs.Close();
                                    gc.AttributeIds = attrList;

                                    gc.Notes         = (string)dr["UserNote"];
                                    gc.PublishedTime = DateTime.Parse((string)dr["PlacedDate"]);
                                    if (isGCNoteAvailable)
                                    {
                                        gc.PersonalNote = (string)dr["gcnote"];
                                    }
                                    else
                                    {
                                        gc.PersonalNote = "";
                                    }
                                    gc.Flagged = (int)dr["UserFlag"] != 0;
                                    gc.Found   = (int)dr["Found"] != 0;

                                    if (isFavPointAvailable)
                                    {
                                        gc.Favorites = (int)(int)dr["FavPoints"];
                                    }
                                    else
                                    {
                                        gc.Favorites = 0;
                                    }

                                    DataAccess.AddGeocache(database, gc);

                                    index++;
                                    if (DateTime.Now >= progShow)
                                    {
                                        prog.Update("ImportingGeocaches", gcCount, index);
                                        progShow = DateTime.Now.AddSeconds(1);
                                    }
                                }
                                dr.Close();
                            }
                        }
                        allprog.Update("Importing", 5, 1);

                        import.CommandText = "select count(1) from logs";
                        int logCount = (int)(long)import.ExecuteScalar();
                        if (logCount > 0)
                        {
                            DateTime progShow = DateTime.Now.AddSeconds(1);
                            using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ImportingLogs", logCount, 0))
                            {
                                index = 0;
                                import.CommandText = "select l.lLogId, l.lParent, lDate, lTime, lBy, lownerid, lEncoded, lType, lText " +
                                                     " from logs l" +
                                                     " inner join logmemo m on m.lLogId = l.lLogId and m.lParent = l.lParent";
                                DbDataReader dr = import.ExecuteReader();
                                while (dr.Read())
                                {
                                    Core.Data.LogData lg = new Core.Data.LogData();

                                    String type    = (String)dr["lType"];
                                    int    logType = (int)logTypes[type];

                                    //id text, gccode text, tbcode text, date text, finder text, finderid text, logtext text, encoded integer, datafromdate text, logtype integer
                                    lg.ID           = dr["lLogiD"].ToString();
                                    lg.GeocacheCode = (string)dr["lParent"];
                                    lg.TBCode       = "";
                                    lg.Date         = (DateTime)dr["lDate"];
                                    lg.Finder       = (string)dr["lBy"];
                                    lg.FinderId     = dr["lownerid"].ToString();
                                    lg.Text         = (string)dr["lText"];
                                    lg.Encoded      = (long)dr["lEncoded"] != 0;
                                    lg.DataFromDate = DateTime.Now;
                                    lg.LogType      = Utils.DataAccess.GetLogType(logType);

                                    DataAccess.AddLog(database, lg);

                                    index++;
                                    if (DateTime.Now >= progShow)
                                    {
                                        progress.Update("ImportingLogs", logCount, index);
                                        progShow = DateTime.Now.AddSeconds(1);
                                    }
                                }
                                dr.Close();
                            }
                        }
                        allprog.Update("Importing", 5, 2);

                        import.CommandText = "select count(1) from logimages";
                        int logimgCount = 0;
                        try
                        {
                            logimgCount = (int)(long)import.ExecuteScalar();
                        }
                        catch
                        {
                            //table does not exists
                        }
                        if (logimgCount > 0)
                        {
                            DateTime progShow = DateTime.Now.AddSeconds(1);
                            using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ImportingLogImages", logimgCount, 0))
                            {
                                index = 0;
                                import.CommandText = "select iCode, iLogId, iImage, iName from logimages";
                                DbDataReader dr = import.ExecuteReader();
                                while (dr.Read())
                                {
                                    Core.Data.LogImageData lg = new Core.Data.LogImageData();

                                    lg.ID    = (string)dr["iCode"];
                                    lg.LogId = dr["iLogID"].ToString();
                                    lg.Url   = (string)dr["iImage"];
                                    lg.Name  = (string)dr["iName"];

                                    DataAccess.AddLogImage(database, lg);

                                    index++;
                                    if (DateTime.Now >= progShow)
                                    {
                                        progress.Update("ImportingLogImages", logimgCount, index);
                                        progShow = DateTime.Now.AddSeconds(1);
                                    }
                                }
                                dr.Close();
                            }
                        }
                        allprog.Update("Importing", 5, 3);

                        //id text, code text, geocachecode text, name text, datafromdate text, comment text, description text, url text, urlname text, wptype integer, lat real, lon real, time text
                        import.CommandText = "select count(1) from waypoints";

                        int wptCount = (int)(long)import.ExecuteScalar();
                        if (wptCount > 0)
                        {
                            DateTime progShow = DateTime.Now.AddSeconds(1);
                            using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ImportingWaypoints", wptCount, 0))
                            {
                                index = 0;
                                import.CommandText = "select w.cParent, w.cCode, cName, cDate, cType, cLat, cLon," +
                                                     " cComment, cUrl" +
                                                     " from waypoints w" +
                                                     " inner join wayMemo m on w.cParent = m.cParent and w.cCode=m.cCode";
                                DbDataReader dr = import.ExecuteReader();
                                while (dr.Read())
                                {
                                    Core.Data.WaypointData wp = new Core.Data.WaypointData();

                                    int wpType = getWPType(((string)dr["cType"])[0]);

                                    wp.ID   = (string)dr["cCode"];
                                    wp.Code = (string)dr["cCode"];
                                    wp.Url  = (string)dr["cUrl"];
                                    //wp.UrlName = (string)dr["urlname"];
                                    wp.Name         = (string)dr["cName"];
                                    wp.DataFromDate = (DateTime)dr["cDate"];
                                    wp.Comment      = (string)dr["cComment"];
                                    wp.GeocacheCode = (string)dr["cParent"];
                                    //wp.Description = (string)dr["description"];
                                    wp.WPType = Utils.DataAccess.GetWaypointType(wpType);
                                    double lat = Utils.Conversion.StringToDouble(dr["clat"] as string);
                                    double lon = Utils.Conversion.StringToDouble(dr["clon"] as string);
                                    if (Math.Abs(lat) < 0.00001)
                                    {
                                        wp.Lat = null;
                                    }
                                    else
                                    {
                                        wp.Lat = lat;
                                    }
                                    if (Math.Abs(lon) < 0.00001)
                                    {
                                        wp.Lon = null;
                                    }
                                    else
                                    {
                                        wp.Lon = lon;
                                    }
                                    wp.Time = (DateTime)dr["cDate"];

                                    wp.Description = wp.WPType.Name;
                                    wp.UrlName     = wp.WPType.Name;

                                    DataAccess.AddWaypoint(database, wp);

                                    index++;
                                    if (DateTime.Now >= progShow)
                                    {
                                        progress.Update("ImportingWaypoints", wptCount, index);
                                        progShow = DateTime.Now.AddSeconds(1);
                                    }
                                }
                                dr.Close();
                            }
                        }
                        allprog.Update("Importing", 5, 4);

                        try
                        {
                            //import corrected if table exists
                            import.CommandText = "select kCode, kAfterLat, kAfterLon from Corrected";
                            DbDataReader dr = import.ExecuteReader();
                            while (dr.Read())
                            {
                                string             gcCode = dr["kCode"] as string ?? "";
                                Core.Data.Geocache gc     = database.GeocacheCollection.GetGeocache(gcCode);
                                if (gc != null)
                                {
                                    object oLat = dr["kAfterLat"];
                                    object oLon = dr["kAfterLon"];
                                    if (oLat != null && oLat.GetType() != typeof(DBNull) &&
                                        oLon != null && oLon.GetType() != typeof(DBNull))
                                    {
                                        string sLat = oLat as string;
                                        string sLon = oLon as string;
                                        if (sLat.Length > 0 && sLon.Length > 0)
                                        {
                                            gc.CustomLat = Utils.Conversion.StringToDouble(sLat);
                                            gc.CustomLon = Utils.Conversion.StringToDouble(sLon);
                                        }
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                        allprog.Update("Importing", 5, 5);
                    }
                }
            }
            catch (Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(new Importer(), e);
            }
            return(true);
        }
Exemplo n.º 5
0
        public void ImportGPX(string gpxDoc)
        {
            bool isGeoSpy = false;

            try
            {
                string firstPart;
                if (gpxDoc.Length < 2000)
                {
                    firstPart = gpxDoc;
                }
                else
                {
                    firstPart = gpxDoc.Substring(0, 2000);
                }
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(gpxDoc);
                XmlElement          root  = doc.DocumentElement;
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

                if (firstPart.IndexOf("http://www.topografix.com/GPX/1/1", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    nsmgr.AddNamespace("x", "http://www.topografix.com/GPX/1/1");
                }
                else
                {
                    nsmgr.AddNamespace("x", "http://www.topografix.com/GPX/1/0");
                }

                if (firstPart.IndexOf("http://geoget.ararat.cz/GpxExtensions/v2", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    //GeoSpy
                    isGeoSpy          = true;
                    _cachesGpxVersion = new Version(1, 0, 0);
                    nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0");
                }
                else if (firstPart.IndexOf("http://www.groundspeak.com/cache/1/0/2", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0/2");
                    _cachesGpxVersion = new Version(1, 0, 2);
                }
                else if (firstPart.IndexOf("http://www.groundspeak.com/cache/1/0/1", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    if (firstPart.IndexOf("creator=\"Opencaching.de - http://www.opencaching.de\"") > 0)
                    {
                        nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0");
                    }
                    else if (firstPart.IndexOf("http://www.opencaching.com/xmlschemas/opencaching/1/0") > 0)
                    {
                        nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0");
                    }
                    else
                    {
                        nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0/1");
                    }
                    _cachesGpxVersion = new Version(1, 0, 1);
                }
                else if (firstPart.IndexOf("http://www.groundspeak.com/cache/1/1", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/1");
                    _cachesGpxVersion = new Version(1, 1, 0);
                }
                else
                {
                    nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0");
                    _cachesGpxVersion = new Version(1, 0, 0);
                }

                if (isGeoSpy)
                {
                    _gpxDataTime = DateTime.Parse(root.SelectSingleNode("x:metadata", nsmgr).SelectSingleNode("x:time", nsmgr).InnerText);
                }
                else
                {
                    _gpxDataTime = DateTime.Parse(root.SelectSingleNode("x:time", nsmgr).InnerText);
                }

                XmlNodeList wps = root.SelectNodes("x:wpt", nsmgr);
                if (wps != null)
                {
                    Version V102 = new Version(1, 0, 2);
                    foreach (XmlNode wp in wps)
                    {
                        XmlNode n;
                        if (isGeoSpy)
                        {
                            n = wp.SelectSingleNode("x:extensions", nsmgr).SelectSingleNode("y:cache", nsmgr);
                        }
                        else
                        {
                            n = wp.SelectSingleNode("y:cache", nsmgr);
                        }
                        if (n == null)
                        {
                            //assume Child waypoint and yeah, well....multiple sources like GC or OB should be handled
                            //TODO: check source and don't assume GC
                            //check if it is a child waypoint by checking the name
                            string fullwpname = wp.SelectSingleNode("x:name", nsmgr).InnerText;
                            string wpname     = fullwpname.Substring(2);

                            Core.Data.Geocache parentGeocache = null;
                            string             parentCode;
                            parentGeocache = (from g in Core.ApplicationData.Instance.ActiveDatabase.GeocacheCollection where g.Code.Substring(2) == wpname select g).FirstOrDefault();
                            if (parentGeocache == null)
                            {
                                //parent is not available
                                //now what?
                                //just add it
                                //continue;
                                parentCode = string.Concat("GC", wpname);
                            }
                            else
                            {
                                parentCode = parentGeocache.Code;
                            }

                            Core.Data.IWaypointData cwp = null;
                            cwp = (from a in Utils.DataAccess.GetWaypointsFromGeocache(Core.ApplicationData.Instance.ActiveDatabase, parentCode) where a.Code == fullwpname select a).FirstOrDefault();
                            if (cwp == null)
                            {
                                cwp = new Core.Data.WaypointData();
                            }
                            else
                            {
                                if (cwp.DataFromDate >= _gpxDataTime)
                                {
                                    continue;
                                }
                            }

                            cwp.Code         = wp.SelectSingleNode("x:name", nsmgr).InnerText;
                            cwp.GeocacheCode = string.Concat(parentCode.Substring(0, 2), cwp.Code.Substring(2));
                            cwp.DataFromDate = _gpxDataTime;
                            cwp.Comment      = wp.SelectSingleNode("x:cmt", nsmgr).InnerText;
                            if (SafeAttributeInnerText(wp, "lat", "").Length > 0)
                            {
                                cwp.Lat = Utils.Conversion.StringToDouble(wp.Attributes["lat"].InnerText);
                                cwp.Lon = Utils.Conversion.StringToDouble(wp.Attributes["lon"].InnerText);
                                if (Math.Abs((double)cwp.Lat) < 0.0001 && Math.Abs((double)cwp.Lon) < 0.0001)
                                {
                                    cwp.Lat = null;
                                    cwp.Lon = null;
                                }
                            }
                            else
                            {
                                cwp.Lat = null;
                                cwp.Lon = null;
                            }
                            cwp.Description = wp.SelectSingleNode("x:desc", nsmgr).InnerText;
                            cwp.ID          = cwp.Code;
                            cwp.Name        = cwp.Code;
                            cwp.Comment     = wp.SelectSingleNode("x:cmt", nsmgr).InnerText;
                            cwp.Time        = DateTime.Parse(wp.SelectSingleNode("x:time", nsmgr).InnerText);
                            cwp.Url         = SafeInnerText(wp.SelectSingleNode("x:url", nsmgr), "");
                            cwp.UrlName     = SafeInnerText(wp.SelectSingleNode("x:urlname", nsmgr), "");
                            cwp.WPType      = Utils.DataAccess.GetWaypointType(wp.SelectSingleNode("x:sym", nsmgr).InnerText);

                            if (cwp is Core.Data.WaypointData)
                            {
                                Utils.DataAccess.AddWaypoint(Core.ApplicationData.Instance.ActiveDatabase, cwp as Core.Data.WaypointData);
                            }
                            continue;
                        }

                        string code = wp.SelectSingleNode("x:name", nsmgr).InnerText;

                        Core.Data.IGeocacheData gc = null;
                        gc = (from a in Core.ApplicationData.Instance.ActiveDatabase.GeocacheCollection where a.Code == code select a).FirstOrDefault();
                        if (gc == null)
                        {
                            gc = new Core.Data.GeocacheData();
                        }
                        else
                        {
                            if (gc.DataFromDate >= _gpxDataTime)
                            {
                                continue;
                            }
                        }

                        gc.Available = bool.Parse(n.Attributes["available"].InnerText);
                        gc.Archived  = bool.Parse(SafeInnerText(n.Attributes["archived"], "False"));

                        if (!(gc is Core.Data.Geocache) || !(gc as Core.Data.Geocache).Locked)
                        {
                            gc.Lat           = Utils.Conversion.StringToDouble(SafeAttributeInnerText(wp, "lat", "0.0"));
                            gc.Lon           = Utils.Conversion.StringToDouble(SafeAttributeInnerText(wp, "lon", "0.0"));
                            gc.Code          = code;
                            gc.DataFromDate  = _gpxDataTime;
                            gc.Name          = n.SelectSingleNode("y:name", nsmgr).InnerText;
                            gc.PublishedTime = DateTime.Parse(wp.SelectSingleNode("x:time", nsmgr).InnerText);
                            if (isGeoSpy)
                            {
                                gc.Url = wp.SelectSingleNode("x:link", nsmgr).Attributes["href"].Value;
                            }
                            else
                            {
                                gc.Url = SafeInnerText(wp.SelectSingleNode("x:url", nsmgr), "");
                            }
                            if (SafeInnerText(wp.SelectSingleNode("x:sym", nsmgr), "").EndsWith(" Found"))
                            {
                                gc.Found = true;
                            }
                            gc.Country = SafeInnerText(n.SelectSingleNode("y:country", nsmgr), "");
                            gc.State   = SafeInnerText(n.SelectSingleNode("y:state", nsmgr), "");
                            gc.OwnerId = SafeAttributeInnerText(n.SelectSingleNode("y:owner", nsmgr), "id", "");
                            if (_cachesGpxVersion >= V102)
                            {
                                gc.GeocacheType = Utils.DataAccess.GetGeocacheType(int.Parse(SafeAttributeInnerText(n.SelectSingleNode("y:type", nsmgr), "id", "-1")));
                                gc.Container    = Utils.DataAccess.GetGeocacheContainer(int.Parse(SafeAttributeInnerText(n.SelectSingleNode("y:container", nsmgr), "id", "-1")));
                                gc.Favorites    = int.Parse(SafeInnerText(n.SelectSingleNode("y:favorite_points", nsmgr), "0"));
                                gc.MemberOnly   = bool.Parse(SafeInnerText(n.Attributes["memberonly"], "False"));
                                //gc.CustomCoords = bool.Parse(SafeInnerText(n.Attributes["customcoords"], "False"));
                                gc.PersonalNote = SafeInnerText(n.Attributes["personal_note"], "");
                            }
                            else
                            {
                                string srchTxt = SafeInnerText(n.SelectSingleNode("y:type", nsmgr), "Unknown");
                                if (!srchTxt.StartsWith("Groundspeak"))
                                {
                                    if (srchTxt.Contains("Trash"))
                                    {
                                        srchTxt = "Trash";
                                    }
                                    else
                                    {
                                        int pos = srchTxt.IndexOf(' ');
                                        if (pos > 0)
                                        {
                                            srchTxt = srchTxt.Substring(0, pos);
                                        }
                                    }
                                }
                                gc.GeocacheType = Utils.DataAccess.GetGeocacheType(srchTxt);
                                if (isGeoSpy)
                                {
                                    gc.Container = Utils.DataAccess.GetGeocacheContainer("Virtual");
                                }
                                else
                                {
                                    gc.Container = Utils.DataAccess.GetGeocacheContainer(SafeInnerText(n.SelectSingleNode("y:container", nsmgr), "Unknown"));
                                }
                            }
                            gc.PlacedBy               = SafeInnerText(n.SelectSingleNode("y:placed_by", nsmgr), "");
                            gc.Owner                  = SafeInnerText(n.SelectSingleNode("y:owner", nsmgr), "");
                            gc.Terrain                = Utils.Conversion.StringToDouble(SafeInnerText(n.SelectSingleNode("y:terrain", nsmgr), "1"));
                            gc.Difficulty             = Utils.Conversion.StringToDouble(SafeInnerText(n.SelectSingleNode("y:difficulty", nsmgr), "1"));
                            gc.ShortDescription       = SafeInnerText(n.SelectSingleNode("y:short_description", nsmgr), "");
                            gc.ShortDescriptionInHtml = bool.Parse(SafeAttributeInnerText(n.SelectSingleNode("y:short_description", nsmgr), "html", "False"));
                            gc.LongDescription        = SafeInnerText(n.SelectSingleNode("y:long_description", nsmgr), "");
                            gc.LongDescriptionInHtml  = bool.Parse(SafeAttributeInnerText(n.SelectSingleNode("y:long_description", nsmgr), "html", "False"));
                            gc.EncodedHints           = SafeInnerText(n.SelectSingleNode("y:encoded_hints", nsmgr), "");

                            gc.AttributeIds = new List <int>();
                            XmlNode attrs = n.SelectSingleNode("y:attributes", nsmgr);
                            if (attrs != null && attrs.ChildNodes != null)
                            {
                                foreach (XmlNode attr in attrs.ChildNodes)
                                {
                                    int attrId  = int.Parse(attr.Attributes["id"].InnerText);
                                    int attrInc = int.Parse(SafeAttributeInnerText(attr, "inc", "1"));
                                    if (attrInc == 1)
                                    {
                                        gc.AttributeIds.Add(attrId);
                                    }
                                    else
                                    {
                                        gc.AttributeIds.Add(-1 * attrId);
                                    }
                                }
                            }

                            bool gcAdded = true;
                            if (gc is Core.Data.GeocacheData)
                            {
                                gcAdded = Utils.DataAccess.AddGeocache(Core.ApplicationData.Instance.ActiveDatabase, gc as Core.Data.GeocacheData);
                            }
                            if (gcAdded)
                            {
                                gc = (from a in Core.ApplicationData.Instance.ActiveDatabase.GeocacheCollection where a.Code == code select a).FirstOrDefault();
                                Utils.Calculus.SetDistanceAndAngleGeocacheFromLocation(gc as Core.Data.Geocache, Core.ApplicationData.Instance.CenterLocation);


                                //Logs
                                XmlNode ln = n.SelectSingleNode("y:logs", nsmgr);
                                if (ln != null)
                                {
                                    XmlNodeList logs = ln.SelectNodes("y:log", nsmgr);
                                    if (logs != null)
                                    {
                                        foreach (XmlNode l in logs)
                                        {
                                            string lid = SafeAttributeInnerText(l, "id", "");

                                            if (lid.StartsWith("GL"))
                                            {
                                                //lg.ID = lid;
                                            }
                                            else
                                            {
                                                if (string.IsNullOrEmpty(lid) || lid.StartsWith("-"))
                                                {
                                                    continue;
                                                }
                                                try
                                                {
                                                    lid = string.Concat("GL", Utils.Conversion.GetCacheCodeFromCacheID(int.Parse(lid)).Substring(2));
                                                }
                                                catch
                                                {
                                                    continue;
                                                }
                                            }

                                            Core.Data.ILogData lg = null;
                                            lg = (from a in Utils.DataAccess.GetLogs(Core.ApplicationData.Instance.ActiveDatabase, gc.Code) where a.ID == lid select a).FirstOrDefault();
                                            if (lg == null)
                                            {
                                                lg = new Core.Data.LogData();
                                            }

                                            lg.ID           = lid;
                                            lg.GeocacheCode = gc.Code;
                                            lg.DataFromDate = _gpxDataTime;
                                            lg.Date         = DateTime.Parse(l.SelectSingleNode("y:date", nsmgr).InnerText);
                                            lg.Encoded      = bool.Parse(l.SelectSingleNode("y:text", nsmgr).Attributes["encoded"].InnerText);
                                            if (isGeoSpy)
                                            {
                                                lg.Text = GAPPSF.Utils.Conversion.StripHtmlTags(System.Web.HttpUtility.HtmlDecode(l.SelectSingleNode("y:text", nsmgr).InnerText).Replace("</p>", "\r\n\r\n"));
                                            }
                                            else
                                            {
                                                lg.Text = l.SelectSingleNode("y:text", nsmgr).InnerText;
                                            }
                                            lg.Finder = l.SelectSingleNode("y:finder", nsmgr).InnerText;
                                            if (l.SelectSingleNode("y:finder", nsmgr).Attributes["id"] != null)
                                            {
                                                lg.FinderId = l.SelectSingleNode("y:finder", nsmgr).Attributes["id"].InnerText;
                                            }
                                            else
                                            {
                                                //GCTour has no finder id
                                                lg.FinderId = "1";
                                            }
                                            if (_cachesGpxVersion >= V102)
                                            {
                                                lg.LogType = Utils.DataAccess.GetLogType(int.Parse(l.SelectSingleNode("y:type", nsmgr).Attributes["id"].InnerText));
                                            }
                                            else
                                            {
                                                lg.LogType = Utils.DataAccess.GetLogType(l.SelectSingleNode("y:type", nsmgr).InnerText);
                                            }

                                            if (lg is Core.Data.LogData)
                                            {
                                                Utils.DataAccess.AddLog(Core.ApplicationData.Instance.ActiveDatabase, lg as Core.Data.LogData);
                                            }

                                            //log images
                                            XmlNode lni = l.SelectSingleNode("y:images", nsmgr);
                                            if (lni != null)
                                            {
                                                XmlNodeList logis = lni.SelectNodes("y:image", nsmgr);
                                                if (logis != null)
                                                {
                                                    foreach (XmlNode li in logis)
                                                    {
                                                        string url = li.SelectSingleNode("y:url", nsmgr).InnerText;

                                                        Core.Data.ILogImageData lgi = null;
                                                        lgi = (from a in Utils.DataAccess.GetLogImages(Core.ApplicationData.Instance.ActiveDatabase, lg.ID) where a.ID == url select a).FirstOrDefault();
                                                        if (lgi == null)
                                                        {
                                                            lgi = new Core.Data.LogImageData();
                                                        }
                                                        lgi.Url          = url;
                                                        lgi.ID           = lgi.Url;
                                                        lgi.LogId        = lg.ID;
                                                        lgi.Name         = li.SelectSingleNode("y:name", nsmgr).InnerText;
                                                        lgi.DataFromDate = _gpxDataTime;

                                                        if (lgi is Core.Data.LogImageData)
                                                        {
                                                            Utils.DataAccess.AddLogImage(Core.ApplicationData.Instance.ActiveDatabase, lgi as Core.Data.LogImageData);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }
        }
Exemplo n.º 6
0
        public async Task ImportFile(Core.Storage.Database db, string filename)
        {
            using (Utils.DataUpdater upd = new DataUpdater(db))
            {
                await Task.Run(() =>
                {
                    try
                    {
                        DateTime nextUpdate = DateTime.Now.AddSeconds(1);
                        using (FileStream fs = File.OpenRead(filename))
                            using (BinaryReader br = new BinaryReader(fs))
                            {
                                string tag = br.ReadString();
                                if (tag == "GAPP")
                                {
                                    bool IsLittleEndian = br.ReadBoolean();
                                    int version         = br.ReadInt32();
                                    if (IsLittleEndian == BitConverter.IsLittleEndian && version <= 3)
                                    {
                                        int count = br.ReadInt32();
                                        using (Utils.ProgressBlock prog = new Utils.ProgressBlock("ImportGAPPDataExchangeFile", "ImportGeocaches", count, 0))
                                        {
                                            for (int index = 0; index < count; index++)
                                            {
                                                Core.Data.GeocacheData gc = new Core.Data.GeocacheData();
                                                gc.Archived     = br.ReadBoolean();
                                                gc.AttributeIds = ReadIntegerArray(br);
                                                gc.Available    = br.ReadBoolean();
                                                gc.City         = br.ReadString();
                                                gc.Code         = br.ReadString();
                                                gc.Container    = Utils.DataAccess.GetGeocacheContainer(br.ReadInt32());
                                                bool dummyb     = br.ReadBoolean();
                                                gc.Country      = br.ReadString();
                                                if (br.ReadBoolean())
                                                {
                                                    gc.CustomLat = br.ReadDouble();
                                                    gc.CustomLon = br.ReadDouble();
                                                }
                                                gc.Difficulty             = br.ReadDouble();
                                                gc.EncodedHints           = br.ReadString();
                                                gc.Favorites              = br.ReadInt32();
                                                gc.Flagged                = br.ReadBoolean();
                                                gc.Found                  = br.ReadBoolean();
                                                string s                  = br.ReadString();
                                                gc.GeocacheType           = Utils.DataAccess.GetGeocacheType(br.ReadInt32());
                                                string dummystr           = br.ReadString();
                                                gc.Lat                    = br.ReadDouble();
                                                gc.Lon                    = br.ReadDouble();
                                                gc.LongDescription        = br.ReadString();
                                                gc.LongDescriptionInHtml  = br.ReadBoolean();
                                                gc.MemberOnly             = br.ReadBoolean();
                                                gc.Municipality           = br.ReadString();
                                                gc.Name                   = br.ReadString();
                                                gc.Notes                  = br.ReadString();
                                                gc.Owner                  = br.ReadString();
                                                gc.OwnerId                = br.ReadString();
                                                gc.PersonalNote           = br.ReadString();
                                                gc.PlacedBy               = br.ReadString();
                                                gc.PublishedTime          = DateTime.Parse(br.ReadString());
                                                dummyb                    = br.ReadBoolean();
                                                gc.ShortDescription       = br.ReadString();
                                                gc.ShortDescriptionInHtml = br.ReadBoolean();
                                                gc.State                  = br.ReadString();
                                                gc.Terrain                = br.ReadDouble();
                                                dummystr                  = br.ReadString();
                                                gc.Url                    = br.ReadString();
                                                gc.DataFromDate           = DateTime.Parse(br.ReadString());
                                                if (version > 1)
                                                {
                                                    gc.Locked = br.ReadBoolean();
                                                }

                                                bool gcAdded = Utils.DataAccess.AddGeocache(db, gc);

                                                int logcount = br.ReadInt32();
                                                for (int lc = 0; lc < logcount; lc++)
                                                {
                                                    Core.Data.LogData log = new Core.Data.LogData();
                                                    log.DataFromDate      = DateTime.Parse(br.ReadString());
                                                    log.Date         = DateTime.Parse(br.ReadString());
                                                    log.Encoded      = br.ReadBoolean();
                                                    log.Finder       = br.ReadString();
                                                    log.FinderId     = br.ReadString();
                                                    log.GeocacheCode = br.ReadString();
                                                    log.ID           = br.ReadString();
                                                    log.LogType      = Utils.DataAccess.GetLogType(br.ReadInt32());
                                                    log.TBCode       = br.ReadString();
                                                    log.Text         = br.ReadString();

                                                    if (gcAdded)
                                                    {
                                                        Utils.DataAccess.AddLog(db, log);
                                                    }

                                                    int logimgcount = br.ReadInt32();
                                                    for (int lic = 0; lic < logimgcount; lic++)
                                                    {
                                                        Core.Data.LogImageData li = new Core.Data.LogImageData();
                                                        li.DataFromDate           = DateTime.Parse(br.ReadString());
                                                        li.ID    = br.ReadString();
                                                        li.LogId = br.ReadString();
                                                        li.Name  = br.ReadString();
                                                        li.Url   = br.ReadString();

                                                        if (gcAdded)
                                                        {
                                                            Utils.DataAccess.AddLogImage(db, li);
                                                        }
                                                    }
                                                }

                                                int wpcount = br.ReadInt32();
                                                for (int wpc = 0; wpc < wpcount; wpc++)
                                                {
                                                    Core.Data.WaypointData wp = new Core.Data.WaypointData();
                                                    wp.Code         = br.ReadString();
                                                    wp.Comment      = br.ReadString();
                                                    wp.DataFromDate = DateTime.Parse(br.ReadString());
                                                    wp.Description  = br.ReadString();
                                                    wp.GeocacheCode = br.ReadString();
                                                    wp.ID           = br.ReadString();
                                                    if (br.ReadBoolean())
                                                    {
                                                        wp.Lat = br.ReadDouble();
                                                        wp.Lon = br.ReadDouble();
                                                    }
                                                    wp.Name    = br.ReadString();
                                                    wp.Time    = DateTime.Parse(br.ReadString());
                                                    wp.Url     = br.ReadString();
                                                    wp.UrlName = br.ReadString();
                                                    wp.WPType  = Utils.DataAccess.GetWaypointType(br.ReadInt32());

                                                    if (gcAdded)
                                                    {
                                                        Utils.DataAccess.AddWaypoint(db, wp);
                                                    }
                                                }

                                                if (version > 2)
                                                {
                                                    int usrwpcount = br.ReadInt32();
                                                    for (int wpc = 0; wpc < usrwpcount; wpc++)
                                                    {
                                                        Core.Data.UserWaypointData wp = new Core.Data.UserWaypointData();
                                                        wp.ID           = br.ReadInt32().ToString();
                                                        wp.Description  = br.ReadString();
                                                        wp.GeocacheCode = br.ReadString();
                                                        wp.Lat          = br.ReadDouble();
                                                        wp.Lon          = br.ReadDouble();
                                                        wp.Date         = DateTime.Parse(br.ReadString());

                                                        if (gcAdded)
                                                        {
                                                            Utils.DataAccess.AddUserWaypoint(db, wp);
                                                        }
                                                    }
                                                }

                                                index++;
                                                if (DateTime.Now >= nextUpdate)
                                                {
                                                    prog.Update("ImportGeocaches", count, index);
                                                    nextUpdate = DateTime.Now.AddSeconds(1);
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, "Version not supported");
                                    }
                                }
                                else
                                {
                                    Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, "Wrong file signature");
                                }
                            }
                    }
                    catch (Exception e)
                    {
                        Core.ApplicationData.Instance.Logger.AddLog(this, e);
                    }
                });
            }
        }
Exemplo n.º 7
0
        public async Task ImportFile(Core.Storage.Database db, string filename)
        {
            using (Utils.DataUpdater upd = new DataUpdater(db))
            {
                await Task.Run(() =>
                {
                    try
                    {
                        DateTime nextUpdate = DateTime.Now.AddSeconds(1);
                        using (FileStream fs = File.OpenRead(filename))
                        using (BinaryReader br = new BinaryReader(fs))
                        {
                            string tag = br.ReadString();
                            if (tag == "GAPP")
                            {
                                bool IsLittleEndian = br.ReadBoolean();
                                int version = br.ReadInt32();
                                if (IsLittleEndian == BitConverter.IsLittleEndian && version <= 3)
                                {
                                    int count = br.ReadInt32();
                                    using (Utils.ProgressBlock prog = new Utils.ProgressBlock("ImportGAPPDataExchangeFile", "ImportGeocaches", count, 0))
                                    {
                                        for (int index = 0; index < count; index++)
                                        {
                                            Core.Data.GeocacheData gc = new Core.Data.GeocacheData();
                                            gc.Archived = br.ReadBoolean();
                                            gc.AttributeIds = ReadIntegerArray(br);
                                            gc.Available = br.ReadBoolean();
                                            gc.City = br.ReadString();
                                            gc.Code = br.ReadString();
                                            gc.Container = Utils.DataAccess.GetGeocacheContainer(br.ReadInt32());
                                            bool dummyb = br.ReadBoolean();
                                            gc.Country = br.ReadString();
                                            if (br.ReadBoolean())
                                            {
                                                gc.CustomLat = br.ReadDouble();
                                                gc.CustomLon = br.ReadDouble();
                                            }
                                            gc.Difficulty = br.ReadDouble();
                                            gc.EncodedHints = br.ReadString();
                                            gc.Favorites = br.ReadInt32();
                                            gc.Flagged = br.ReadBoolean();
                                            gc.Found = br.ReadBoolean();
                                            string s = br.ReadString();
                                            gc.GeocacheType = Utils.DataAccess.GetGeocacheType(br.ReadInt32());
                                            string dummystr = br.ReadString();
                                            gc.Lat = br.ReadDouble();
                                            gc.Lon = br.ReadDouble();
                                            gc.LongDescription = br.ReadString();
                                            gc.LongDescriptionInHtml = br.ReadBoolean();
                                            gc.MemberOnly = br.ReadBoolean();
                                            gc.Municipality = br.ReadString();
                                            gc.Name = br.ReadString();
                                            gc.Notes = br.ReadString();
                                            gc.Owner = br.ReadString();
                                            gc.OwnerId = br.ReadString();
                                            gc.PersonalNote = br.ReadString();
                                            gc.PlacedBy = br.ReadString();
                                            gc.PublishedTime = DateTime.Parse(br.ReadString());
                                            dummyb = br.ReadBoolean();
                                            gc.ShortDescription = br.ReadString();
                                            gc.ShortDescriptionInHtml = br.ReadBoolean();
                                            gc.State = br.ReadString();
                                            gc.Terrain = br.ReadDouble();
                                            dummystr = br.ReadString();
                                            gc.Url = br.ReadString();
                                            gc.DataFromDate = DateTime.Parse(br.ReadString());
                                            if (version > 1)
                                            {
                                                gc.Locked = br.ReadBoolean();
                                            }

                                            bool gcAdded = Utils.DataAccess.AddGeocache(db, gc);

                                            int logcount = br.ReadInt32();
                                            for (int lc = 0; lc < logcount; lc++)
                                            {
                                                Core.Data.LogData log = new Core.Data.LogData();
                                                log.DataFromDate = DateTime.Parse(br.ReadString());
                                                log.Date = DateTime.Parse(br.ReadString());
                                                log.Encoded = br.ReadBoolean();
                                                log.Finder = br.ReadString();
                                                log.FinderId = br.ReadString();
                                                log.GeocacheCode = br.ReadString();
                                                log.ID = br.ReadString();
                                                log.LogType = Utils.DataAccess.GetLogType(br.ReadInt32());
                                                log.TBCode = br.ReadString();
                                                log.Text = br.ReadString();

                                                if (gcAdded)
                                                {
                                                    Utils.DataAccess.AddLog(db, log);
                                                }

                                                int logimgcount = br.ReadInt32();
                                                for (int lic = 0; lic < logimgcount; lic++)
                                                {
                                                    Core.Data.LogImageData li = new Core.Data.LogImageData();
                                                    li.DataFromDate = DateTime.Parse(br.ReadString());
                                                    li.ID = br.ReadString();
                                                    li.LogId = br.ReadString();
                                                    li.Name = br.ReadString();
                                                    li.Url = br.ReadString();

                                                    if (gcAdded)
                                                    {
                                                        Utils.DataAccess.AddLogImage(db, li);
                                                    }
                                                }
                                            }

                                            int wpcount = br.ReadInt32();
                                            for (int wpc = 0; wpc < wpcount; wpc++)
                                            {
                                                Core.Data.WaypointData wp = new Core.Data.WaypointData();
                                                wp.Code = br.ReadString();
                                                wp.Comment = br.ReadString();
                                                wp.DataFromDate = DateTime.Parse(br.ReadString());
                                                wp.Description = br.ReadString();
                                                wp.GeocacheCode = br.ReadString();
                                                wp.ID = br.ReadString();
                                                if (br.ReadBoolean())
                                                {
                                                    wp.Lat = br.ReadDouble();
                                                    wp.Lon = br.ReadDouble();
                                                }
                                                wp.Name = br.ReadString();
                                                wp.Time = DateTime.Parse(br.ReadString());
                                                wp.Url = br.ReadString();
                                                wp.UrlName = br.ReadString();
                                                wp.WPType = Utils.DataAccess.GetWaypointType(br.ReadInt32());

                                                if (gcAdded)
                                                {
                                                    Utils.DataAccess.AddWaypoint(db, wp);
                                                }
                                            }

                                            if (version > 2)
                                            {
                                                int usrwpcount = br.ReadInt32();
                                                for (int wpc = 0; wpc < usrwpcount; wpc++)
                                                {
                                                    Core.Data.UserWaypointData wp = new Core.Data.UserWaypointData();
                                                    wp.ID = br.ReadInt32().ToString();
                                                    wp.Description = br.ReadString();
                                                    wp.GeocacheCode = br.ReadString();
                                                    wp.Lat = br.ReadDouble();
                                                    wp.Lon = br.ReadDouble();
                                                    wp.Date = DateTime.Parse(br.ReadString());

                                                    if (gcAdded)
                                                    {
                                                        Utils.DataAccess.AddUserWaypoint(db, wp);
                                                    }
                                                }
                                            }

                                            index++;
                                            if (DateTime.Now >= nextUpdate)
                                            {
                                                prog.Update("ImportGeocaches", count, index);
                                                nextUpdate = DateTime.Now.AddSeconds(1);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, "Version not supported");
                                }
                            }
                            else
                            {
                                Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, "Wrong file signature");
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Core.ApplicationData.Instance.Logger.AddLog(this, e);
                    }
                });
            }
        }
Exemplo n.º 8
0
        public static Core.Data.Log AddLog(Core.Storage.Database db, OKAPIService.Log lg, string finder, string finderId)
        {
            Core.Data.Log result = null;
            if (lg != null)
            {
                result = db.LogCollection.GetLog(lg.uuid);

                Core.Data.ILogData lgData;
                if (result == null)
                {
                    lgData = new Core.Data.LogData();
                    lgData.ID = lg.uuid;
                }
                else
                {
                    lgData = result;
                }

                lgData.DataFromDate = DateTime.Now;
                lgData.Date = DateTime.Parse(lg.date);
                lgData.Encoded = false;
                if (lg.user == null)
                {
                    lgData.Finder = finder;
                    lgData.FinderId = finderId;
                }
                else
                {
                    lgData.Finder = lg.user.username;
                    lgData.FinderId = lg.user.uuid;
                }
                lgData.GeocacheCode = lg.cache_code;
                lgData.Text = lg.comment;
                lgData.LogType = Utils.DataAccess.GetLogType(lg.type);

                if (lgData is Core.Data.LogData)
                {
                    if (Utils.DataAccess.AddLog(db, lgData as Core.Data.LogData))
                    {
                        result = db.LogCollection.GetLog(lgData.ID);
                    }
                }

            }
            return result;
        }
Exemplo n.º 9
0
        public static Core.Data.Log ImportLog(Core.Storage.Database db, LiveV6.GeocacheLog lg)
        {
            Core.Data.Log result = null;
            if (lg != null)
            {
                result = db.LogCollection.GetLog(lg.Code);

                Core.Data.ILogData lgData;
                if (result == null)
                {
                    lgData = new Core.Data.LogData();
                    lgData.ID = lg.Code;
                }
                else
                {
                    lgData = result;
                }

                lgData.DataFromDate = DateTime.Now;
                lgData.Date = lg.VisitDate;
                lgData.Encoded = lg.LogIsEncoded;
                lgData.Finder = lg.Finder.UserName;
                lgData.FinderId = lg.Finder.Id.ToString();
                lgData.GeocacheCode = lg.CacheCode;
                lgData.LogType = Utils.DataAccess.GetLogType((int)lg.LogType.WptLogTypeId);
                lgData.Text = lg.LogText;

                if (lgData is Core.Data.LogData)
                {
                    if (Utils.DataAccess.AddLog(db, lgData as Core.Data.LogData))
                    {
                        result = db.LogCollection.GetLog(lgData.ID);

                        if (result!=null)
                        {
                            ImportLogImages(db, lg.Images, result.ID);
                        }
                    }
                }

            }
            return result;
        }
Exemplo n.º 10
0
        private static bool Import(Database database, string filename)
        {
            try
            {
                using (Utils.ProgressBlock allprog = new ProgressBlock("ImportGSAKDatabase", "Importing", 6, 0))
                {
                    System.Collections.Hashtable logTypes = new System.Collections.Hashtable();
                    String connect = String.Format("data source=file:{0}", filename);
                    using (SqliteConnection dbcon = new SqliteConnection(connect))
                    {

                        //System.Diagnostics.Debugger.Break();
                        logTypes.Add("Found it", 2);
                        logTypes.Add("Didn't find it", 3);
                        logTypes.Add("Write note", 4);
                        logTypes.Add("Archive", 5);
                        logTypes.Add("Needs Archived", 7);
                        logTypes.Add("Will Attend", 9);
                        logTypes.Add("Attended", 10);
                        logTypes.Add("Webcam Photo Taken", 11);
                        logTypes.Add("Unarchive", 12);
                        logTypes.Add("Temporarily Disable Listing", 22);
                        logTypes.Add("Enable Listing", 23);
                        logTypes.Add("Publish Listing", 24);
                        logTypes.Add("Retract Listing", 25);
                        logTypes.Add("Needs Maintenance", 45);
                        logTypes.Add("Owner Maintenance", 46);
                        logTypes.Add("Update Coordinates", 47);
                        logTypes.Add("Post Reviewer Note", 68);
                        logTypes.Add("Announcement", 74);

                        dbcon.Open();

                        SqliteCommand lookup = new SqliteCommand("select aId, aInc from attributes where aCode = @Code", dbcon);
                        lookup.CommandType = CommandType.Text;
                        DbParameter par = lookup.CreateParameter();
                        par.Direction = ParameterDirection.Input;
                        par.ParameterName = "@Code";
                        lookup.Parameters.Add(par);
                        lookup.Prepare();

                        SqliteCommand import = new SqliteCommand("select count(1) from caches", dbcon);
                        import.CommandType = CommandType.Text;

                        int index = 0;
                        int gcCount = (int)(long)import.ExecuteScalar();
                        if (gcCount > 0)
                        {
                            DateTime progShow = DateTime.Now.AddSeconds(1);
                            using (Utils.ProgressBlock prog = new ProgressBlock("ImportingGeocaches", 1, 0))
                            {
                                bool isPremiumAvailable = false;
                                bool isFavPointAvailable = false;
                                bool isGCNoteAvailable = false;

                                try
                                {
                                    import.CommandText = "select IsPremium from Caches limit 1";
                                    using (SqliteDataReader checkdr = import.ExecuteReader())
                                    {
                                        isPremiumAvailable = true;
                                    }
                                }
                                catch
                                {
                                }

                                try
                                {
                                    import.CommandText = "select FavPoints from Caches limit 1";
                                    using (SqliteDataReader checkdr = import.ExecuteReader())
                                    {
                                        isFavPointAvailable = true;
                                    }
                                }
                                catch
                                {
                                }

                                try
                                {
                                    import.CommandText = "select gcnote from Caches limit 1";
                                    using (SqliteDataReader checkdr = import.ExecuteReader())
                                    {
                                        isGCNoteAvailable = true;
                                    }
                                }
                                catch
                                {
                                }

                                import.CommandText = "select caches.Code, Name, LastGPXDate, PlacedDate, Latitude, Longitude, Status, " +
                                    "Archived, Country, State, CacheType, PlacedBy, OwnerName, OwnerId, Container, Terrain, Difficulty, ShortHTM" +
                                    ", LongHTM, " +
                                    string.Format("{0}", isPremiumAvailable ? "IsPremium, " : "") +
                                    " HasCorrected, LatOriginal, LonOriginal, UserFlag, Found, " +
                                    string.Format("{0}", isFavPointAvailable ? "FavPoints, " : "") +
                                    " ShortDescription, LongDescription, Hints, Url, UserNote" +
                                    string.Format("{0}", isGCNoteAvailable ? ", gcnote" : "") +
                                    " from caches" +
                                    " inner join cachememo on cachememo.code = caches.code";

                                SqliteDataReader dr = import.ExecuteReader();

                                while (dr.Read())
                                {
                                    GeocacheData gc = new GeocacheData();
                                    int cacheType;
                                    try
                                    {
                                        cacheType = getCacheType(((String)dr["CacheType"])[0]);
                                    }
                                    catch (ArgumentOutOfRangeException)
                                    {
                                        continue;
                                    }
                                    int container = getContainer(((String)dr["Container"])[0]);

                                    gc.Code = (string)dr["code"];
                                    gc.Name = (string)dr["name"];
                                    if (string.IsNullOrEmpty((string)dr["LastGPXDate"]))
                                    {
                                        gc.DataFromDate = DateTime.Now.Date;
                                    }
                                    else
                                    {
                                        gc.DataFromDate = DateTime.Parse((string)dr["LastGPXDate"]);
                                    }
                                    gc.Available = ((String)dr["Status"]).Equals("A");
                                    gc.Archived = (int)dr["archived"] != 0;
                                    gc.Country = (string)dr["country"];
                                    gc.State = (string)dr["state"];

                                    gc.GeocacheType = Utils.DataAccess.GetGeocacheType(cacheType);
                                    gc.PlacedBy = (string)dr["placedby"];
                                    gc.Owner = (string)dr["OwnerName"];
                                    gc.OwnerId = dr["ownerid"].GetType() == typeof(DBNull) ? "" : dr["ownerid"].ToString();
                                    gc.Container = Utils.DataAccess.GetGeocacheContainer(container);
                                    gc.Terrain = (double)dr["terrain"];
                                    gc.Difficulty = (double)dr["difficulty"];
                                    gc.ShortDescription = (string)dr["ShortDescription"];
                                    gc.ShortDescriptionInHtml = (int)dr["ShortHTM"] != 0;
                                    gc.LongDescription = (string)dr["LongDescription"];
                                    gc.LongDescriptionInHtml = (int)dr["LongHTM"] != 0;
                                    gc.EncodedHints = (string)dr["Hints"];
                                    gc.Url = (string)dr["url"];
                                    if (isPremiumAvailable)
                                    {
                                        gc.MemberOnly = (int)dr["IsPremium"] != 0;
                                    }
                                    else
                                    {
                                        gc.MemberOnly = false;
                                    }
                                    bool customCoords = (int)dr["HasCorrected"] != 0;
                                    if (customCoords)
                                    {
                                        gc.CustomLat = Utils.Conversion.StringToDouble(dr["Latitude"] as String);
                                        gc.CustomLon = Utils.Conversion.StringToDouble(dr["Longitude"] as String);
                                        gc.Lat = Utils.Conversion.StringToDouble(dr["LatOriginal"] as string);
                                        gc.Lon = Utils.Conversion.StringToDouble(dr["LonOriginal"] as string);
                                    }
                                    else
                                    {
                                        gc.Lat = Utils.Conversion.StringToDouble(dr["Latitude"] as string);
                                        gc.Lon = Utils.Conversion.StringToDouble(dr["Longitude"] as string);
                                    }

                                    par.Value = gc.Code;
                                    DbDataReader attrs = lookup.ExecuteReader();
                                    List<int> attrList = new List<int>();
                                    while (attrs.Read())
                                    {
                                        int attr = (int)(int)attrs["aId"];
                                        if (attrs["aInc"].ToString() == "0")
                                        {
                                            attr *= -1;
                                        }
                                        attrList.Add(attr);
                                    }
                                    attrs.Close();
                                    gc.AttributeIds = attrList;

                                    gc.Notes = (string)dr["UserNote"];
                                    gc.PublishedTime = DateTime.Parse((string)dr["PlacedDate"]);
                                    if (isGCNoteAvailable)
                                    {
                                        gc.PersonalNote = (string)dr["gcnote"];
                                    }
                                    else
                                    {
                                        gc.PersonalNote = "";
                                    }
                                    gc.Flagged = (int)dr["UserFlag"] != 0;
                                    gc.Found = (int)dr["Found"] != 0;

                                    if (isFavPointAvailable)
                                    {
                                        gc.Favorites = (int)(int)dr["FavPoints"];
                                    }
                                    else
                                    {
                                        gc.Favorites = 0;
                                    }

                                    DataAccess.AddGeocache(database, gc);

                                    index++;
                                    if (DateTime.Now >= progShow)
                                    {
                                        prog.Update("ImportingGeocaches", gcCount, index);
                                        progShow = DateTime.Now.AddSeconds(1);
                                    }
                                }
                                dr.Close();

                            }
                        }
                        allprog.Update("Importing", 5, 1);

                        import.CommandText = "select count(1) from logs";
                        int logCount = (int)(long)import.ExecuteScalar();
                        if (logCount > 0)
                        {
                            DateTime progShow = DateTime.Now.AddSeconds(1);
                            using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ImportingLogs", logCount, 0))
                            {
                                index = 0;
                                import.CommandText = "select l.lLogId, l.lParent, lDate, lTime, lBy, lownerid, lEncoded, lType, lText " +
                                    " from logs l" +
                                    " inner join logmemo m on m.lLogId = l.lLogId and m.lParent = l.lParent";
                                DbDataReader dr = import.ExecuteReader();
                                while (dr.Read())
                                {
                                    Core.Data.LogData lg = new Core.Data.LogData();

                                    String type = (String)dr["lType"];
                                    int logType = (int)logTypes[type];

                                    //id text, gccode text, tbcode text, date text, finder text, finderid text, logtext text, encoded integer, datafromdate text, logtype integer
                                    lg.ID = dr["lLogiD"].ToString();
                                    lg.GeocacheCode = (string)dr["lParent"];
                                    lg.TBCode = "";
                                    lg.Date = (DateTime)dr["lDate"];
                                    lg.Finder = (string)dr["lBy"];
                                    lg.FinderId = dr["lownerid"].ToString();
                                    lg.Text = (string)dr["lText"];
                                    lg.Encoded = (long)dr["lEncoded"] != 0;
                                    lg.DataFromDate = DateTime.Now;
                                    lg.LogType = Utils.DataAccess.GetLogType(logType);

                                    DataAccess.AddLog(database, lg);

                                    index++;
                                    if (DateTime.Now >= progShow)
                                    {
                                        progress.Update("ImportingLogs", logCount, index);
                                        progShow = DateTime.Now.AddSeconds(1);
                                    }
                                }
                                dr.Close();
                            }
                        }
                        allprog.Update("Importing", 5, 2);

                        import.CommandText = "select count(1) from logimages";
                        int logimgCount = 0;
                        try
                        {
                            logimgCount = (int)(long)import.ExecuteScalar();
                        }
                        catch
                        {
                            //table does not exists
                        }
                        if (logimgCount > 0)
                        {
                            DateTime progShow = DateTime.Now.AddSeconds(1);
                            using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ImportingLogImages", logimgCount, 0))
                            {
                                index = 0;
                                import.CommandText = "select iCode, iLogId, iImage, iName from logimages";
                                DbDataReader dr = import.ExecuteReader();
                                while (dr.Read())
                                {
                                    Core.Data.LogImageData lg = new Core.Data.LogImageData();

                                    lg.ID = (string)dr["iCode"];
                                    lg.LogId = dr["iLogID"].ToString();
                                    lg.Url = (string)dr["iImage"];
                                    lg.Name = (string)dr["iName"];

                                    DataAccess.AddLogImage(database, lg);

                                    index++;
                                    if (DateTime.Now >= progShow)
                                    {
                                        progress.Update("ImportingLogImages", logimgCount, index);
                                        progShow = DateTime.Now.AddSeconds(1);
                                    }
                                }
                                dr.Close();
                            }
                        }
                        allprog.Update("Importing", 5, 3);

                        //id text, code text, geocachecode text, name text, datafromdate text, comment text, description text, url text, urlname text, wptype integer, lat real, lon real, time text
                        import.CommandText = "select count(1) from waypoints";

                        int wptCount = (int)(long)import.ExecuteScalar();
                        if (wptCount > 0)
                        {
                            DateTime progShow = DateTime.Now.AddSeconds(1);
                            using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ImportingWaypoints", wptCount, 0))
                            {
                                index = 0;
                                import.CommandText = "select w.cParent, w.cCode, cName, cDate, cType, cLat, cLon," +
                                    " cComment, cUrl" +
                                    " from waypoints w" +
                                    " inner join wayMemo m on w.cParent = m.cParent and w.cCode=m.cCode";
                                DbDataReader dr = import.ExecuteReader();
                                while (dr.Read())
                                {
                                    Core.Data.WaypointData wp = new Core.Data.WaypointData();

                                    int wpType = getWPType(((string)dr["cType"])[0]);

                                    wp.ID = (string)dr["cCode"];
                                    wp.Code = (string)dr["cCode"];
                                    wp.Url = (string)dr["cUrl"];
                                    //wp.UrlName = (string)dr["urlname"];
                                    wp.Name = (string)dr["cName"];
                                    wp.DataFromDate = (DateTime)dr["cDate"];
                                    wp.Comment = (string)dr["cComment"];
                                    wp.GeocacheCode = (string)dr["cParent"];
                                    //wp.Description = (string)dr["description"];
                                    wp.WPType = Utils.DataAccess.GetWaypointType(wpType);
                                    double lat = Utils.Conversion.StringToDouble(dr["clat"] as string);
                                    double lon = Utils.Conversion.StringToDouble(dr["clon"] as string);
                                    if (Math.Abs(lat) < 0.00001)
                                    {
                                        wp.Lat = null;
                                    }
                                    else
                                    {
                                        wp.Lat = lat;
                                    }
                                    if (Math.Abs(lon) < 0.00001)
                                    {
                                        wp.Lon = null;
                                    }
                                    else
                                    {
                                        wp.Lon = lon;
                                    }
                                    wp.Time = (DateTime)dr["cDate"];

                                    wp.Description = wp.WPType.Name;
                                    wp.UrlName = wp.WPType.Name;

                                    DataAccess.AddWaypoint(database, wp);

                                    index++;
                                    if (DateTime.Now >= progShow)
                                    {
                                        progress.Update("ImportingWaypoints", wptCount, index);
                                        progShow = DateTime.Now.AddSeconds(1);
                                    }
                                }
                                dr.Close();
                            }
                        }
                        allprog.Update("Importing", 5, 4);

                        try
                        {
                            //import corrected if table exists
                            import.CommandText = "select kCode, kAfterLat, kAfterLon from Corrected";
                            DbDataReader dr = import.ExecuteReader();
                            while (dr.Read())
                            {
                                string gcCode = dr["kCode"] as string ?? "";
                                Core.Data.Geocache gc = database.GeocacheCollection.GetGeocache(gcCode);
                                if (gc != null)
                                {
                                    object oLat = dr["kAfterLat"];
                                    object oLon = dr["kAfterLon"];
                                    if (oLat != null && oLat.GetType() != typeof(DBNull) &&
                                        oLon != null && oLon.GetType() != typeof(DBNull))
                                    {
                                        string sLat = oLat as string;
                                        string sLon = oLon as string;
                                        if (sLat.Length > 0 && sLon.Length > 0)
                                        {
                                            gc.CustomLat = Utils.Conversion.StringToDouble(sLat);
                                            gc.CustomLon = Utils.Conversion.StringToDouble(sLon);
                                        }
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                        allprog.Update("Importing", 5, 5);
                    }
                }
            }
            catch(Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(new Importer(), e);
            }
            return true;
        }
Exemplo n.º 11
0
        async public Task PasteGeocaches()
        {
            if (Core.ApplicationData.Instance.ActiveDatabase != null &&
                !string.IsNullOrEmpty(_sourceDatabaseFilename) &&
                Core.ApplicationData.Instance.ActiveDatabase.FileName != _sourceDatabaseFilename &&
                _gcCodes != null &&
                _gcCodes.Count > 0)
            {
                Core.Storage.Database srcDb = (from a in Core.ApplicationData.Instance.Databases where a.FileName == _sourceDatabaseFilename select a).FirstOrDefault();
                if (srcDb != null)
                {
                    using (Utils.DataUpdater upd = new Utils.DataUpdater(Core.ApplicationData.Instance.ActiveDatabase))
                    {
                        await Task.Run(() =>
                        {
                            DateTime nextUpdate = DateTime.Now.AddSeconds(1);
                            using (Utils.ProgressBlock prog = new Utils.ProgressBlock("CopyingGeocaches", "CopyingGeocaches", _gcCodes.Count, 0, true))
                            {
                                int index = 0;
                                Core.Data.GeocacheData gcData       = new Core.Data.GeocacheData();
                                Core.Data.LogData lgData            = new Core.Data.LogData();
                                Core.Data.WaypointData wpData       = new Core.Data.WaypointData();
                                Core.Data.UserWaypointData uwpData  = new Core.Data.UserWaypointData();
                                Core.Data.LogImageData lgiData      = new Core.Data.LogImageData();
                                Core.Data.GeocacheImageData gciData = new Core.Data.GeocacheImageData();
                                foreach (string gcCode in _gcCodes)
                                {
                                    Core.Data.Geocache gc = srcDb.GeocacheCollection.GetGeocache(gcCode);
                                    if (gc != null)
                                    {
                                        Core.Data.GeocacheData.Copy(gc, gcData);
                                        Utils.DataAccess.AddGeocache(Core.ApplicationData.Instance.ActiveDatabase, gcData);
                                        List <Core.Data.Log> lgs = Utils.DataAccess.GetLogs(srcDb, gc.Code);
                                        foreach (var l in lgs)
                                        {
                                            Core.Data.LogData.Copy(l, lgData);
                                            Utils.DataAccess.AddLog(Core.ApplicationData.Instance.ActiveDatabase, lgData);

                                            List <Core.Data.LogImage> lgis = Utils.DataAccess.GetLogImages(srcDb, l.ID);
                                            foreach (var li in lgis)
                                            {
                                                Core.Data.LogImageData.Copy(li, lgiData);
                                                Utils.DataAccess.AddLogImage(Core.ApplicationData.Instance.ActiveDatabase, lgiData);
                                            }
                                        }
                                        List <Core.Data.Waypoint> wps = Utils.DataAccess.GetWaypointsFromGeocache(srcDb, gc.Code);
                                        foreach (var wp in wps)
                                        {
                                            Core.Data.WaypointData.Copy(wp, wpData);
                                            Utils.DataAccess.AddWaypoint(Core.ApplicationData.Instance.ActiveDatabase, wpData);
                                        }
                                        List <Core.Data.UserWaypoint> uwps = Utils.DataAccess.GetUserWaypointsFromGeocache(srcDb, gc.Code);
                                        foreach (var wp in uwps)
                                        {
                                            Core.Data.UserWaypointData.Copy(wp, uwpData);
                                            Utils.DataAccess.AddUserWaypoint(Core.ApplicationData.Instance.ActiveDatabase, uwpData);
                                        }
                                        List <Core.Data.GeocacheImage> gcis = Utils.DataAccess.GetGeocacheImages(srcDb, gc.Code);
                                        foreach (var wp in gcis)
                                        {
                                            Core.Data.GeocacheImageData.Copy(wp, gciData);
                                            Utils.DataAccess.AddGeocacheImage(Core.ApplicationData.Instance.ActiveDatabase, gciData);
                                        }

                                        index++;
                                        if (DateTime.Now >= nextUpdate)
                                        {
                                            if (!prog.Update("CopyingGeocaches", _gcCodes.Count, index))
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
Exemplo n.º 12
0
        public void ImportMunzeesFromDfxAt(Core.Storage.Database db, string url)
        {
            using (Utils.ProgressBlock fixpr = new Utils.ProgressBlock("ImportingMunzees", "DownloadingData", 2, 0))
            {
                int            index = 0;
                MunzeeDataList munzl;
                try
                {
                    System.Net.HttpWebRequest webRequest;
                    webRequest           = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
                    webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.17 Safari/533.4";
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MunzeeDataList));
                    using (System.IO.Stream stream = webRequest.GetResponse().GetResponseStream())
                    {
                        munzl = ser.ReadObject(stream) as MunzeeDataList;
                    }
                    fixpr.Update("DownloadingData", 2, 1);
                    DateTime nextProgUpdate = DateTime.MinValue;
                    string   usrname        = (Core.ApplicationData.Instance.AccountInfos.GetAccountInfo("MZ").AccountName ?? "").ToLower();
                    using (Utils.ProgressBlock prog = new Utils.ProgressBlock("SavingGeocaches", "SavingGeocaches", munzl.Count, 0))
                    {
                        foreach (MunzeeData md in munzl)
                        {
                            string code = string.Format("MZ{0}", int.Parse(md.munzee_id).ToString("X4"));
                            Core.Data.IGeocacheData gc = db.GeocacheCollection.GetGeocache(code);
                            if (gc == null)
                            {
                                gc = new Core.Data.GeocacheData();
                            }

                            gc.Archived  = md.archived == "1";
                            gc.Available = !gc.Archived;
                            //gc.City = md.location.Split(new char[]{','})[0];
                            gc.City         = "";
                            gc.Code         = code;
                            gc.Container    = Utils.DataAccess.GetGeocacheContainer(1);
                            gc.Country      = md.country;
                            gc.DataFromDate = DateTime.Now;
                            gc.Difficulty   = 1.0;
                            gc.Found        = md.captured != "0";
                            if (md.type == "")
                            {
                                gc.GeocacheType = Utils.DataAccess.GetGeocacheType(95342);
                            }
                            else if (md.type == "virtual")
                            {
                                gc.GeocacheType = Utils.DataAccess.GetGeocacheType(95343);
                            }
                            else if (md.type == "maintenance")
                            {
                                gc.GeocacheType = Utils.DataAccess.GetGeocacheType(95344);
                            }
                            else if (md.type == "business")
                            {
                                gc.GeocacheType = Utils.DataAccess.GetGeocacheType(95345);
                            }
                            else if (md.type == "mystery")
                            {
                                gc.GeocacheType = Utils.DataAccess.GetGeocacheType(95346);
                            }
                            else if (md.type == "nfc")
                            {
                                gc.GeocacheType = Utils.DataAccess.GetGeocacheType(95347);
                            }
                            else if (md.type == "premium")
                            {
                                gc.GeocacheType = Utils.DataAccess.GetGeocacheType(95348);
                            }
                            else
                            {
                                gc.GeocacheType = Utils.DataAccess.GetGeocacheType(95342);
                            }
                            gc.Lat                   = Utils.Conversion.StringToDouble(md.latitude);
                            gc.Lon                   = Utils.Conversion.StringToDouble(md.longitude);
                            gc.LongDescription       = md.notes == null ? "" : md.notes.Replace("\r", "").Replace("\n", "\r\n");
                            gc.LongDescriptionInHtml = false;
                            gc.MemberOnly            = false;
                            gc.Municipality          = "";
                            gc.Name                  = md.friendly_name;
                            gc.Owner                 = md.username;
                            gc.OwnerId               = "";
                            gc.PlacedBy              = md.username;
                            try
                            {
                                gc.PublishedTime = DateTime.ParseExact(md.deployed_at, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
                            }
                            catch
                            {
                                gc.PublishedTime = DateTime.ParseExact(md.created_at, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
                            }
                            gc.ShortDescription       = "";
                            gc.ShortDescriptionInHtml = false;
                            gc.State   = "";
                            gc.Terrain = 1.0;
                            gc.Url     = string.Format("http://www.munzee.com/m/{0}/{1}/", md.username, md.code);

                            bool gcAdded = true;
                            if (gc is Core.Data.GeocacheData)
                            {
                                gcAdded = Utils.DataAccess.AddGeocache(Core.ApplicationData.Instance.ActiveDatabase, gc as Core.Data.GeocacheData);
                            }
                            if (gcAdded)
                            {
                                gc = (from a in Core.ApplicationData.Instance.ActiveDatabase.GeocacheCollection where a.Code == code select a).FirstOrDefault();
                                Utils.Calculus.SetDistanceAndAngleGeocacheFromLocation(gc as Core.Data.Geocache, Core.ApplicationData.Instance.CenterLocation);

                                //check if found and if so, if log present
                                if (gc.Found && !string.IsNullOrEmpty(md.captured_at))
                                {
                                    //foud and no log, add log
                                    bool foundLogPresent     = false;
                                    List <Core.Data.Log> lgs = db.LogCollection.GetLogs(gc.Code);
                                    if (lgs != null)
                                    {
                                        Core.Data.Log l = (from Core.Data.Log lg in lgs where lg.LogType.AsFound && string.Compare(usrname, lg.Finder, true) == 0 select lg).FirstOrDefault();
                                        foundLogPresent = (l != null);
                                    }
                                    if (!foundLogPresent)
                                    {
                                        Core.Data.LogData l = new Core.Data.LogData();

                                        l.DataFromDate = DateTime.Now;
                                        l.Date         = new DateTime(1970, 1, 1);
                                        l.Date         = l.Date.AddSeconds(long.Parse(md.captured_at.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[0]));
                                        l.Encoded      = false;
                                        l.Finder       = Core.ApplicationData.Instance.AccountInfos.GetAccountInfo("MZ").AccountName ?? "";
                                        l.FinderId     = "0";
                                        l.GeocacheCode = gc.Code;
                                        l.ID           = string.Format("ML{0}", gc.Code.Substring(2));
                                        l.LogType      = Utils.DataAccess.GetLogType(2);
                                        l.Text         = "Captured";

                                        Utils.DataAccess.AddLog(db, l);
                                    }
                                }
                            }

                            index++;
                            if (DateTime.Now >= nextProgUpdate)
                            {
                                prog.Update("SavingGeocaches", munzl.Count, index);
                                nextProgUpdate = DateTime.Now.AddSeconds(0.5);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Core.ApplicationData.Instance.Logger.AddLog(this, e);
                }
            }
        }