public static bool Run(Plugin plugin, ICore core)
    {
        int[,] DTMatrix = new int[9, 9];
        int numMissing=9*9;
        int count=0;
        int prog=0;
        
        List<Geocache> gcList = null;
        gcList = DataAccess.GetFoundGeocaches(core.Geocaches,core.Logs,core.GeocachingComAccount);
        
        using (ProgressBlock progress = new ProgressBlock(plugin,
            "Creating S/T Matrix", "Seeking for Neo", gcList.Count, 0))
        {
          foreach (Geocache gc in gcList)
          {
              int ixD=(int)(gc.Difficulty*2+0.001)-2;
              int ixT=(int)(gc.Terrain*2+0.001)-2;
              //range checking is for cowards!
              if (DTMatrix[ixD,ixT]==0) {numMissing--;}            
              DTMatrix[ixD,ixT]++;
              
              prog++;
              if (prog % 10 == 0) {progress.UpdateProgress("Creating S/T Matrix", "Seeking for Neo", gcList.Count, prog);}
          }
        }
        
        prog=0;
        using (ProgressBlock progress = new ProgressBlock(plugin,
            "Selecting Caches", "", core.Geocaches.Count, 0))
        {
          //reset current selection
          foreach (Geocache gc in core.Geocaches)
          {
              int ixD=(int)(gc.Difficulty*2+0.001)-2;
              int ixT=(int)(gc.Terrain*2+0.001)-2;
             
              gc.Selected = (DTMatrix[ixD,ixT]==0);
              if (DTMatrix[ixD,ixT]==0) {count++;}
              prog++;
              if (prog % 50 == 0) {progress.UpdateProgress("Selecting Caches", "", core.Geocaches.Count, prog);}
          }
        }

        System.Windows.Forms.MessageBox.Show("Selected: "+count.ToString()+
                     "; Missing combinations in D/T Matrix: "+numMissing.ToString()+
                     " of "+gcList.Count.ToString()+" found Geocaches.");
        
        return true;
    }
Exemplo n.º 2
0
    private void threadMethod()
    {
        try
        {
            using (ProgressBlock progress = new ProgressBlock(_plugin, "Update archived geocaches", "Downloading data from globalcaching.eu", 1, 0))
            {
                using (System.Net.WebClient wc = new System.Net.WebClient())
                {
                    byte[] data = wc.DownloadData(string.Format("http://www.globalcaching.eu/Service/Archived.aspx?country=Belgium&prefix=GC&token={0}", System.Web.HttpUtility.UrlEncode(_core.GeocachingComAccount.APIToken)));
                    string sdoc = CompressText.UnzipText(data);
                    //_core.DebugLog(DebugLogLevel.Info, _plugin, null, sdoc);
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(sdoc);
                    XmlElement root = doc.DocumentElement;
                    XmlNodeList strngs = root.SelectNodes("wp");
                    if (strngs != null)
                    {
                        progress.UpdateProgress("Update archived geocaches", "Updating geocaches...", strngs.Count, 0);
                        Geocache gc;
                        int index = 0;
                        foreach (XmlNode sn in strngs)
                        {
                            gc = DataAccess.GetGeocache(_core.Geocaches, sn.InnerText);
                            if (gc != null)
                            {
                                gc.Archived = true;
                                gc.Available = false;
                            }
                            index++;
                            if (index % 50 == 0)
                            {
                                //_core.DebugLog(DebugLogLevel.Info, _plugin, null, index.ToString());
                                progress.UpdateProgress("Update archived geocaches", "Updating geocaches...", strngs.Count, index);
                            }
                        }
                    }

                }
            }
        }
        catch(Exception e)
        {
            _errormessage = e.Message;
        }
        _actionReady.Set();
    }
    private void threadMethod()
    {
        try
        {
            using (ProgressBlock progress = new ProgressBlock(_plugin, "Update Favorite for Netherlands, Belgium and Italy", "Downloading data from globalcaching.eu", 1, 0))
            {
                using (System.Net.WebClient wc = new System.Net.WebClient())
                {
                    string doc = wc.DownloadString(string.Format("http://www.globalcaching.eu/Service/CacheFavorites.aspx?token={0}", System.Web.HttpUtility.UrlEncode(_core.GeocachingComAccount.APIToken)));
                    if (doc != null)
                    {
                        string[] lines = doc.Replace("\r","").Split(new char[]{'\n'});
                        progress.UpdateProgress("Update Favorite of geocaches", "Updating geocaches...", lines.Length, 0);
                        Geocache gc;
                        char[] sep = new char[]{','};
                        string[] parts;
                        foreach (string s in lines)
                        {
                            parts = s.Split(sep);
                            if (parts.Length>0)
                            {
                                gc = DataAccess.GetGeocache(_core.Geocaches, parts[0]);
                                if (gc != null)
                                {
                                    gc.Favorites = int.Parse(parts[1]);
                                }
                            }
                        }
                    }

                }
            }
        }
        catch (Exception e)
        {
            _errormessage = e.Message;
        }
        _actionReady.Set();
    }
Exemplo n.º 4
0
        public override bool Load(bool geocachesOnly)
        {
            bool result = true;

            if (File.Exists(_fileCollection.DatabaseInfoFilename))
            {
                int lsize = sizeof(long);
                byte[] memBuffer = new byte[10 * 1024 * 1024];
                using (MemoryStream ms = new MemoryStream(memBuffer))
                using (BinaryReader br = new BinaryReader(ms))
                {

                    int gcCount = 0;
                    int logCount = 0;
                    int logimgCount = 0;
                    int geocacheimgCount = 0;
                    int wptCount = 0;
                    int usrwptCount = 0;

                    XmlDocument doc = new XmlDocument();
                    doc.Load(_fileCollection.DatabaseInfoFilename);
                    XmlElement root = doc.DocumentElement;
                    gcCount = int.Parse(root.SelectSingleNode("GeocacheCount").InnerText);
                    logCount = int.Parse(root.SelectSingleNode("LogCount").InnerText);
                    logimgCount = int.Parse(root.SelectSingleNode("LogImagesCount").InnerText);
                    wptCount = int.Parse(root.SelectSingleNode("WaypointCount").InnerText);
                    usrwptCount = int.Parse(root.SelectSingleNode("UserWaypointCount").InnerText);
                    if (root.SelectSingleNode("GeocacheImagesCount") != null)
                    {
                        geocacheimgCount = int.Parse(root.SelectSingleNode("GeocacheImagesCount").InnerText);
                    }

                    DateTime nextUpdateTime = DateTime.MinValue;
                    using (Utils.ProgressBlock fixscr = new Utils.ProgressBlock(this, STR_LOADING, STR_LOADINGDATA, 1, 0))
                    {
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_LOADING, STR_LOADINGGEOCACHES, gcCount, 0))
                        {
                            int index = 0;
                            //int procStep = 0;
                            List<Framework.Data.Geocache> gcList = new List<Framework.Data.Geocache>();

                            FileStream fs = _fileCollection._fsGeocaches;
                            fs.Position = 0;
                            long eof = fs.Length;
                            while (fs.Position < eof)
                            {
                                RecordInfo ri = new RecordInfo();
                                ri.Offset = fs.Position;
                                fs.Read(memBuffer, 0, lsize + 1);
                                ms.Position = 0;
                                ri.Length = br.ReadInt64();
                                if (memBuffer[lsize] == 0)
                                {
                                    //free
                                    ri.FreeSlot = true;
                                    ri.ID = string.Concat("_", ri.Offset.ToString());
                                    fs.Position = ri.Offset + ri.Length;
                                }
                                else if (memBuffer[lsize] == 2)
                                {
                                    //lazy loading
                                    ri.FreeSlot = false;
                                    int readCount = Math.Min(32, (int)(ri.Length - lsize - 1));
                                    fs.Read(memBuffer, 0, readCount);
                                    ms.Position = 0;
                                    ri.ID = br.ReadString();
                                    fs.Position = ri.Offset + ri.Length;
                                }
                                else
                                {
                                    //read
                                    ri.FreeSlot = false;
                                    Framework.Data.Geocache gc = new Framework.Data.Geocache();

                                    fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                    ms.Position = 0;
                                    gc.Code = br.ReadString();
                                    ri.ID = gc.Code;

                                    gc.Archived = br.ReadBoolean();
                                    gc.AttributeIds = ReadIntegerArray(br);
                                    gc.Available = br.ReadBoolean();
                                    gc.City = br.ReadString();
                                    gc.Container = Utils.DataAccess.GetGeocacheContainer(Core.GeocacheContainers, br.ReadInt32());
                                    gc.CustomCoords = 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();
                                    gc.GeocacheType = Utils.DataAccess.GetGeocacheType(Core.GeocacheTypes, br.ReadInt32());
                                    gc.ID = br.ReadString();
                                    gc.Lat = br.ReadDouble();
                                    gc.Lon = br.ReadDouble();
                                    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.PersonaleNote = br.ReadString();
                                    gc.PlacedBy = br.ReadString();
                                    gc.PublishedTime = DateTime.Parse(br.ReadString());
                                    gc.State = br.ReadString();
                                    gc.Terrain = br.ReadDouble();
                                    gc.Title = br.ReadString();
                                    gc.Url = br.ReadString();
                                    gc.DataFromDate = DateTime.Parse(br.ReadString());
                                    gc.Locked = br.ReadBoolean();

                                    Calculus.SetDistanceAndAngleGeocacheFromLocation(gc, Core.CenterLocation);
                                    gc.Saved = true;
                                    gc.IsDataChanged = false;
                                    //gcList.Add(gc);
                                    Core.Geocaches.Add(gc);

                                    index++;
                                    //procStep++;
                                    //if (procStep >= 1000)
                                    if (DateTime.Now>=nextUpdateTime)
                                    {
                                        progress.UpdateProgress(STR_LOADING, STR_LOADINGGEOCACHES, gcCount, index);
                                        nextUpdateTime = DateTime.Now.AddSeconds(1);
                                        //procStep = 0;
                                    }
                                }
                                _fileCollection._geocachesInDB.Add(ri.ID, ri);
                            }
                            //Core.Geocaches.Add(gcList);
                        }

                        if (!geocachesOnly)
                        {
                            using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGLOGS, logCount, 0))
                            {
                                int index = 0;
                                nextUpdateTime = DateTime.MinValue;

                                List<Framework.Data.Log> lgList = new List<Framework.Data.Log>();

                                FileStream fs = _fileCollection._fsLogs;
                                fs.Position = 0;
                                long eof = fs.Length;
                                while (fs.Position < eof)
                                {
                                    RecordInfo ri = new RecordInfo();
                                    ri.Offset = fs.Position;
                                    fs.Read(memBuffer, 0, lsize + 1);
                                    ms.Position = 0;
                                    ri.Length = br.ReadInt64();
                                    if (memBuffer[lsize] == 0)
                                    {
                                        //free
                                        ri.FreeSlot = true;
                                        ri.ID = string.Concat("_", ri.Offset.ToString());
                                        fs.Position = ri.Offset + ri.Length;
                                    }
                                    else if (memBuffer[lsize] == 2)
                                    {
                                        //lazy loading
                                        ri.FreeSlot = false;
                                        int readCount = Math.Min(32, (int)(ri.Length - lsize - 1));
                                        fs.Read(memBuffer, 0, readCount);
                                        ms.Position = 0;
                                        ri.ID = br.ReadString();
                                        fs.Position = ri.Offset + ri.Length;
                                    }
                                    else
                                    {
                                        //read
                                        ri.FreeSlot = false;
                                        Framework.Data.Log log = new Framework.Data.Log();

                                        fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                        ms.Position = 0;
                                        log.ID = br.ReadString();
                                        ri.ID = log.ID;

                                        log.DataFromDate = DateTime.Parse(br.ReadString());
                                        log.Date = DateTime.Parse(br.ReadString());
                                        log.Finder = br.ReadString();
                                        log.GeocacheCode = br.ReadString();
                                        log.ID = br.ReadString();
                                        log.LogType = Utils.DataAccess.GetLogType(Core.LogTypes, br.ReadInt32());

                                        log.Saved = true;
                                        log.IsDataChanged = false;
                                        lgList.Add(log);

                                        index++;
                                        //procStep++;
                                        //if (procStep >= 1000)
                                        if (DateTime.Now >= nextUpdateTime)
                                        {
                                            progress.UpdateProgress(STR_LOADING, STR_LOADINGLOGS, logCount, index);
                                            nextUpdateTime = DateTime.Now.AddSeconds(1);
                                            //procStep = 0;
                                        }
                                    }
                                    _fileCollection._logsInDB.Add(ri.ID, ri);
                                }
                                Core.Logs.Add(lgList);
                            }


                            using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGWAYPOINTS, wptCount, 0))
                            {
                                int index = 0;
                                int procStep = 0;

                                List<Framework.Data.Waypoint> wptList = new List<Framework.Data.Waypoint>();

                                using (FileStream fs = File.Open(_fileCollection.WaypointsFilename, FileMode.OpenOrCreate, FileAccess.Read))
                                {
                                    fs.Position = 0;
                                    long eof = fs.Length;
                                    while (fs.Position < eof)
                                    {
                                        RecordInfo ri = new RecordInfo();
                                        ri.Offset = fs.Position;
                                        fs.Read(memBuffer, 0, lsize + 1);
                                        ms.Position = 0;
                                        ri.Length = br.ReadInt64();
                                        if (memBuffer[lsize] == 0)
                                        {
                                            //free
                                            ri.FreeSlot = true;
                                            ri.ID = string.Concat("_", ri.Offset.ToString());
                                            fs.Position = ri.Offset + ri.Length;
                                        }
                                        else
                                        {
                                            //read
                                            ri.FreeSlot = false;
                                            Framework.Data.Waypoint wp = new Framework.Data.Waypoint();

                                            fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                            ms.Position = 0;
                                            wp.Code = br.ReadString();
                                            ri.ID = wp.Code;

                                            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(Core.WaypointTypes, br.ReadInt32());

                                            wp.Saved = true;
                                            wp.IsDataChanged = false;
                                            wptList.Add(wp);

                                            index++;
                                            procStep++;
                                            if (procStep >= 1000)
                                            {
                                                progress.UpdateProgress(STR_LOADING, STR_LOADINGWAYPOINTS, wptCount, index);
                                                procStep = 0;
                                            }
                                        }
                                        _fileCollection._wptsInDB.Add(ri.ID, ri);
                                    }
                                }
                                Core.Waypoints.Add(wptList);
                            }

                            using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGLOGIMAGES, logimgCount, 0))
                            {
                                int index = 0;
                                int procStep = 0;

                                List<Framework.Data.LogImage> lgiList = new List<Framework.Data.LogImage>();

                                using (FileStream fs = File.Open(_fileCollection.LogImagesFilename, FileMode.OpenOrCreate, FileAccess.Read))
                                {
                                    fs.Position = 0;
                                    long eof = fs.Length;
                                    while (fs.Position < eof)
                                    {
                                        RecordInfo ri = new RecordInfo();
                                        ri.Offset = fs.Position;
                                        fs.Read(memBuffer, 0, lsize + 1);
                                        ms.Position = 0;
                                        ri.Length = br.ReadInt64();
                                        if (memBuffer[lsize] == 0)
                                        {
                                            //free
                                            ri.FreeSlot = true;
                                            ri.ID = string.Concat("_", ri.Offset.ToString());
                                            fs.Position = ri.Offset + ri.Length;
                                        }
                                        else
                                        {
                                            //read
                                            ri.FreeSlot = false;
                                            Framework.Data.LogImage li = new Framework.Data.LogImage();

                                            fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                            ms.Position = 0;
                                            li.ID = br.ReadString();
                                            ri.ID = li.ID;

                                            li.DataFromDate = DateTime.Parse(br.ReadString());
                                            li.LogID = br.ReadString();
                                            li.Name = br.ReadString();
                                            li.Url = br.ReadString();

                                            li.Saved = true;
                                            li.IsDataChanged = false;
                                            lgiList.Add(li);

                                            index++;
                                            procStep++;
                                            if (procStep >= 1000)
                                            {
                                                progress.UpdateProgress(STR_LOADING, STR_LOADINGLOGIMAGES, logimgCount, index);
                                                procStep = 0;
                                            }
                                        }
                                        _fileCollection._logimgsInDB.Add(ri.ID, ri);
                                    }
                                }
                                Core.LogImages.Add(lgiList);
                            }

                            using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGGEOCACHEIMAGES, geocacheimgCount, 0))
                            {
                                int index = 0;
                                int procStep = 0;

                                List<Framework.Data.GeocacheImage> lgiList = new List<Framework.Data.GeocacheImage>();

                                using (FileStream fs = File.Open(_fileCollection.GeocacheImagesFilename, FileMode.OpenOrCreate, FileAccess.Read))
                                {
                                    fs.Position = 0;
                                    long eof = fs.Length;
                                    while (fs.Position < eof)
                                    {
                                        RecordInfo ri = new RecordInfo();
                                        ri.Offset = fs.Position;
                                        fs.Read(memBuffer, 0, lsize + 1);
                                        ms.Position = 0;
                                        ri.Length = br.ReadInt64();
                                        if (memBuffer[lsize] == 0)
                                        {
                                            //free
                                            ri.FreeSlot = true;
                                            ri.ID = string.Concat("_", ri.Offset.ToString());
                                            fs.Position = ri.Offset + ri.Length;
                                        }
                                        else
                                        {
                                            //read
                                            ri.FreeSlot = false;
                                            Framework.Data.GeocacheImage li = new Framework.Data.GeocacheImage();

                                            fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                            ms.Position = 0;
                                            li.ID = br.ReadString();
                                            ri.ID = li.ID;

                                            li.DataFromDate = DateTime.Parse(br.ReadString());
                                            li.GeocacheCode = br.ReadString();
                                            li.Description = br.ReadString();
                                            li.Name = br.ReadString();
                                            li.Url = br.ReadString();
                                            li.MobileUrl = br.ReadString();
                                            li.ThumbUrl = br.ReadString();

                                            li.Saved = true;
                                            li.IsDataChanged = false;
                                            lgiList.Add(li);

                                            index++;
                                            procStep++;
                                            if (procStep >= 1000)
                                            {
                                                progress.UpdateProgress(STR_LOADING, STR_LOADINGGEOCACHEIMAGES, geocacheimgCount, index);
                                                procStep = 0;
                                            }
                                        }
                                        _fileCollection._geocacheimgsInDB.Add(ri.ID, ri);
                                    }
                                }
                                Core.GeocacheImages.Add(lgiList);
                            }

                            //using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGLOGIMAGES, logimgCount, 0))
                            {
                                int index = 0;
                                int procStep = 0;

                                List<Framework.Data.UserWaypoint> uwplList = new List<Framework.Data.UserWaypoint>();

                                using (FileStream fs = File.Open(_fileCollection.UserWaypointsFilename, FileMode.OpenOrCreate, FileAccess.Read))
                                {
                                    fs.Position = 0;
                                    long eof = fs.Length;
                                    while (fs.Position < eof)
                                    {
                                        RecordInfo ri = new RecordInfo();
                                        ri.Offset = fs.Position;
                                        fs.Read(memBuffer, 0, lsize + 1);
                                        ms.Position = 0;
                                        ri.Length = br.ReadInt64();
                                        if (memBuffer[lsize] == 0)
                                        {
                                            //free
                                            ri.FreeSlot = true;
                                            ri.ID = string.Concat("_", ri.Offset.ToString());
                                            fs.Position = ri.Offset + ri.Length;
                                        }
                                        else
                                        {
                                            //read
                                            ri.FreeSlot = false;
                                            Framework.Data.UserWaypoint wp = new Framework.Data.UserWaypoint();

                                            fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                            ms.Position = 0;
                                            ri.ID = br.ReadString();
                                            wp.ID = int.Parse(ri.ID);

                                            wp.Description = br.ReadString();
                                            wp.GeocacheCode = br.ReadString();
                                            wp.Lat = br.ReadDouble();
                                            wp.Lon = br.ReadDouble();
                                            wp.Date = DateTime.Parse(br.ReadString());

                                            wp.Saved = true;
                                            wp.IsDataChanged = false;
                                            uwplList.Add(wp);

                                            index++;
                                            procStep++;
                                            if (procStep >= 1000)
                                            {
                                                //progress.UpdateProgress(STR_LOADING, STR_LOADINGLOGIMAGES, logimgCount, index);
                                                procStep = 0;
                                            }
                                        }
                                        _fileCollection._usrwptsInDB.Add(ri.ID, ri);
                                    }
                                }
                                Core.UserWaypoints.Add(uwplList);
                            }

                        }
                    }
                }
            }

            return result;
        }
Exemplo n.º 5
0
        public bool Save(FileCollection fc, bool forceFullData)
        {
            bool result = true;
            using (Utils.ProgressBlock fixpr = new Utils.ProgressBlock(this, STR_SAVING, STR_SAVINGDATA, 1, 0))
            {
                byte[] memBuffer = new byte[10 * 1024 * 1024];
                byte isFree = 0;
                byte notFree = 1;
                byte notFreeF = 2;
                using (MemoryStream ms = new MemoryStream(memBuffer))
                using (BinaryWriter bw = new BinaryWriter(ms))
                {

                    //**********************************************
                    //fc.DatabaseInfoFilename
                    //**********************************************
                    XmlDocument doc = new XmlDocument();
                    XmlElement root = doc.CreateElement("info");
                    doc.AppendChild(root);

                    XmlElement el = doc.CreateElement("IsLittleEndian");
                    XmlText txt = doc.CreateTextNode(BitConverter.IsLittleEndian.ToString());
                    el.AppendChild(txt);
                    root.AppendChild(el);

                    el = doc.CreateElement("GAPPVersion");
                    txt = doc.CreateTextNode(Core.Version.ToString());
                    el.AppendChild(txt);
                    root.AppendChild(el);

                    el = doc.CreateElement("StorageVersion");
                    txt = doc.CreateTextNode("1");
                    el.AppendChild(txt);
                    root.AppendChild(el);

                    el = doc.CreateElement("GeocacheCount");
                    txt = doc.CreateTextNode(Core.Geocaches.Count.ToString());
                    el.AppendChild(txt);
                    root.AppendChild(el);

                    el = doc.CreateElement("LogCount");
                    txt = doc.CreateTextNode(Core.Logs.Count.ToString());
                    el.AppendChild(txt);
                    root.AppendChild(el);

                    el = doc.CreateElement("LogImagesCount");
                    txt = doc.CreateTextNode(Core.LogImages.Count.ToString());
                    el.AppendChild(txt);
                    root.AppendChild(el);

                    el = doc.CreateElement("WaypointCount");
                    txt = doc.CreateTextNode(Core.Waypoints.Count.ToString());
                    el.AppendChild(txt);
                    root.AppendChild(el);

                    el = doc.CreateElement("UserWaypointCount");
                    txt = doc.CreateTextNode(Core.UserWaypoints.Count.ToString());
                    el.AppendChild(txt);
                    root.AppendChild(el);

                    el = doc.CreateElement("GeocacheImagesCount");
                    txt = doc.CreateTextNode(Core.GeocacheImages.Count.ToString());
                    el.AppendChild(txt);
                    root.AppendChild(el);

                    doc.Save(fc.DatabaseInfoFilename);
                    //**********************************************
                    //**********************************************

                    //**********************************************
                    //          GEOCACHES
                    //**********************************************

                    //delete geocaches that are not in the list anymore.
                    List<RecordInfo> deletedRecords = (from RecordInfo ri in fc._geocachesInDB.Values where !ri.FreeSlot && ri.ID[0] != 'F' && Core.Geocaches.GetGeocache(ri.ID) == null select ri).ToList();
                    List<RecordInfo> deletedFRecords = new List<RecordInfo>();
                    foreach (RecordInfo ri in deletedRecords)
                    {
                        string id = ri.ID;

                        //mark current record as free (change id)
                        fc._geocachesInDB.Remove(ri.ID);
                        ri.ID = string.Concat("_", ri.ID);
                        ri.FreeSlot = true;
                        fc._geocachesInDB.Add(ri.ID, ri);

                        //scratch file to mark it as free
                        fc._fsGeocaches.Position = ri.Offset + sizeof(long);
                        fc._fsGeocaches.WriteByte(isFree);

                        //get the F_ record too
                        RecordInfo fri = fc._geocachesInDB[string.Concat("F_", id)] as RecordInfo;
                        if (fri != null && !fri.FreeSlot)
                        {
                            //mark current record as free (change id)
                            fc._geocachesInDB.Remove(fri.ID);
                            fri.ID = string.Concat("_", fri.ID);
                            fri.FreeSlot = true;
                            fc._geocachesInDB.Add(fri.ID, fri);

                            //scratch file to mark it as free
                            fc._fsGeocaches.Position = fri.Offset + sizeof(long);
                            fc._fsGeocaches.WriteByte(isFree);

                            deletedFRecords.Add(fri);
                        }
                    }
                    deletedRecords.AddRange(deletedFRecords);

                    //now get all the selected and data changed geocaches
                    List<Framework.Data.Geocache> gclist = (from Framework.Data.Geocache wp in Core.Geocaches
                                                            where !wp.Saved
                                                            select wp).ToList();
                    if (gclist.Count > 0)
                    {
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_SAVING, STR_SAVINGGEOCACHES, gclist.Count, 0))
                        {
                            //fix block > ID = GC12345
                            //fulldata > ID = F_GC12345

                            long recordLength = 0;
                            byte[] extraBuffer = new byte[200];
                            List<RecordInfo> freeRecords = (from RecordInfo ri in fc._geocachesInDB.Values where ri.FreeSlot select ri).OrderByDescending(x=>x.Length).ToList();

                            int index = 0;
                            int procStep = 0;
                            foreach (Framework.Data.Geocache gc in gclist)
                            {
                                //write to block
                                ms.Position = 0;

                                //block header
                                bw.Write(recordLength); //overwrite afterwards
                                bw.Write(notFree);
                                bw.Write(gc.Code);

                                bw.Write(gc.Archived);
                                WriteIntegerArray(bw, gc.AttributeIds);
                                bw.Write(gc.Available);
                                bw.Write(gc.City ?? "");
                                bw.Write(gc.Container.ID);
                                bw.Write(gc.CustomCoords);
                                bw.Write(gc.Country ?? "");
                                bw.Write(gc.ContainsCustomLatLon);
                                if (gc.ContainsCustomLatLon)
                                {
                                    bw.Write((double)gc.CustomLat);
                                    bw.Write((double)gc.CustomLon);
                                }
                                bw.Write(gc.Difficulty);
                                bw.Write(gc.EncodedHints ?? "");
                                bw.Write(gc.Favorites);
                                bw.Write(gc.Flagged);
                                bw.Write(gc.Found);
                                bw.Write(gc.GeocacheType.ID);
                                bw.Write(gc.ID ?? "");
                                bw.Write(gc.Lat);
                                bw.Write(gc.Lon);
                                bw.Write(gc.MemberOnly);
                                bw.Write(gc.Municipality ?? "");
                                bw.Write(gc.Name ?? "");
                                bw.Write(gc.Notes ?? "");
                                bw.Write(gc.Owner ?? "");
                                bw.Write(gc.OwnerId ?? "");
                                bw.Write(gc.PersonaleNote ?? "");
                                bw.Write(gc.PlacedBy ?? "");
                                bw.Write(((DateTime)gc.PublishedTime).ToString("s"));
                                bw.Write(gc.State ?? "");
                                bw.Write(gc.Terrain);
                                bw.Write(gc.Title ?? "");
                                bw.Write(gc.Url ?? "");
                                bw.Write(gc.DataFromDate.ToString("s"));
                                bw.Write(gc.Locked);

                                writeRecord(fc._geocachesInDB, gc.Code, ms, bw, fc._fsGeocaches, memBuffer, extraBuffer, freeRecords);

                                //other record
                                if (forceFullData || gc.FullDataLoaded)
                                {
                                    string id = string.Concat("F_", gc.Code);
                                    //write to block
                                    ms.Position = 0;

                                    //block header
                                    bw.Write(recordLength); //overwrite afterwards
                                    bw.Write(notFreeF);
                                    bw.Write(id);

                                    bw.Write(gc.ShortDescription ?? "");
                                    bw.Write(gc.ShortDescriptionInHtml);
                                    bw.Write(gc.LongDescription ?? "");
                                    bw.Write(gc.LongDescriptionInHtml);

                                    writeRecord(fc._geocachesInDB, id, ms, bw, fc._fsGeocaches, memBuffer, extraBuffer, freeRecords);
                                }
                                gc.Saved = true;

                                index++;
                                procStep++;
                                if (procStep >= 1000)
                                {
                                    progress.UpdateProgress(STR_SAVING, STR_SAVINGGEOCACHES, gclist.Count, index);
                                    procStep = 0;
                                }
                            }
                        }
                        fc._fsGeocaches.Flush();
                    }

                    //**********************************************
                    //          LOGS
                    //**********************************************

                    //delete geocaches that are not in the list anymore.
                    deletedRecords = (from RecordInfo ri in fc._logsInDB.Values where !ri.FreeSlot && ri.ID[0] != 'F' && Core.Logs.GetLog(ri.ID) == null select ri).ToList();
                    deletedFRecords.Clear();
                    foreach (RecordInfo ri in deletedRecords)
                    {
                        string id = ri.ID;

                        //mark current record as free (change id)
                        fc._logsInDB.Remove(ri.ID);
                        ri.ID = string.Concat("_", ri.ID);
                        ri.FreeSlot = true;
                        fc._logsInDB.Add(ri.ID, ri);

                        //scratch file to mark it as free
                        fc._fsLogs.Position = ri.Offset + sizeof(long);
                        fc._fsLogs.WriteByte(isFree);

                        //get the F_ record too
                        RecordInfo fri = fc._logsInDB[string.Concat("F_", id)] as RecordInfo;
                        if (fri != null && !fri.FreeSlot)
                        {
                            //mark current record as free (change id)
                            fc._logsInDB.Remove(fri.ID);
                            fri.ID = string.Concat("_", fri.ID);
                            fri.FreeSlot = true;
                            fc._logsInDB.Add(fri.ID, fri);

                            //scratch file to mark it as free
                            fc._fsLogs.Position = fri.Offset + sizeof(long);
                            fc._fsLogs.WriteByte(isFree);

                            deletedFRecords.Add(fri);
                        }
                    }
                    deletedRecords.AddRange(deletedFRecords);

                    List<Framework.Data.Log> lglist = (from Framework.Data.Log wp in Core.Logs
                                                       where !wp.Saved
                                                       select wp).ToList();
                    if (lglist.Count > 0)
                    {
                        List<RecordInfo> freeRecords = (from RecordInfo ri in fc._logsInDB.Values where ri.FreeSlot select ri).OrderByDescending(x => x.Length).ToList();

                        int index = 0;
                        int procStep = 0;
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGLOGS, lglist.Count, 0))
                        {
                            long recordLength = 0;
                            byte[] extraBuffer = new byte[50];
                            foreach (Framework.Data.Log l in lglist)
                            {
                                //write to block
                                ms.Position = 0;

                                //block header
                                bw.Write(recordLength); //overwrite afterwards
                                bw.Write(notFree);
                                bw.Write(l.ID);

                                bw.Write(l.DataFromDate.ToString("s"));
                                bw.Write(l.Date.ToString("s"));
                                bw.Write(l.Finder ?? "");
                                bw.Write(l.GeocacheCode ?? "");
                                bw.Write(l.ID);
                                bw.Write(l.LogType.ID);

                                writeRecord(fc._logsInDB, l.ID, ms, bw, fc._fsLogs, memBuffer, extraBuffer, freeRecords);

                                if (forceFullData || l.FullDataLoaded)
                                {
                                    string id = string.Concat("F_", l.ID);
                                    //write to block
                                    ms.Position = 0;

                                    //block header
                                    bw.Write(recordLength); //overwrite afterwards
                                    bw.Write(notFreeF);
                                    bw.Write(id);

                                    bw.Write(l.TBCode ?? "");
                                    bw.Write(l.FinderId ?? "");
                                    bw.Write(l.Text ?? "");
                                    bw.Write(l.Encoded);

                                    writeRecord(fc._logsInDB, id, ms, bw, fc._fsLogs, memBuffer, extraBuffer, freeRecords);
                                }

                                l.Saved = true;

                                index++;
                                procStep++;
                                if (procStep >= 1000)
                                {
                                    progress.UpdateProgress(STR_SAVING, STR_SAVINGLOGS, lglist.Count, index);
                                    procStep = 0;
                                }
                            }
                        }
                        fc._fsLogs.Flush();
                    }

                    //**********************************************
                    //          WAYPOINTS
                    //**********************************************

                    using (FileStream fs = File.Open(fc.WaypointsFilename, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        //delete geocaches that are not in the list anymore.
                        deletedRecords = (from RecordInfo ri in fc._wptsInDB.Values where !ri.FreeSlot && Core.Waypoints.getWaypoint(ri.ID) == null select ri).ToList();
                        foreach (RecordInfo ri in deletedRecords)
                        {
                            //mark current record as free (change id)
                            fc._wptsInDB.Remove(ri.ID);
                            ri.ID = string.Concat("_", ri.ID);
                            ri.FreeSlot = true;
                            fc._wptsInDB.Add(ri.ID, ri);

                            //scratch file to mark it as free
                            fs.Position = ri.Offset + sizeof(long);
                            fs.WriteByte(isFree);
                        }

                        List<Framework.Data.Waypoint> wptlist = (from Framework.Data.Waypoint wp in Core.Waypoints
                                                                 where !wp.Saved
                                                                 select wp).ToList();
                        if (wptlist.Count > 0)
                        {
                            List<RecordInfo> freeRecords = (from RecordInfo ri in fc._wptsInDB.Values where ri.FreeSlot select ri).OrderByDescending(x => x.Length).ToList();

                            int index = 0;
                            int procStep = 0;
                            using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGWAYPOINTS, wptlist.Count, 0))
                            {
                                long recordLength = 0;
                                byte[] extraBuffer = new byte[10];
                                foreach (Framework.Data.Waypoint wp in wptlist)
                                {
                                    //write to block
                                    ms.Position = 0;

                                    //block header
                                    bw.Write(recordLength); //overwrite afterwards
                                    bw.Write(notFree);
                                    bw.Write(wp.Code);

                                    bw.Write(wp.Comment ?? "");
                                    bw.Write(wp.DataFromDate.ToString("s"));
                                    bw.Write(wp.Description ?? "");
                                    bw.Write(wp.GeocacheCode ?? "");
                                    bw.Write(wp.ID ?? "");
                                    if (wp.Lat == null || wp.Lon == null)
                                    {
                                        bw.Write(false);
                                    }
                                    else
                                    {
                                        bw.Write(true);
                                        bw.Write((double)wp.Lat);
                                        bw.Write((double)wp.Lon);
                                    }
                                    bw.Write(wp.Name ?? "");
                                    bw.Write(wp.Time.ToString("s"));
                                    bw.Write(wp.Url ?? "");
                                    bw.Write(wp.UrlName ?? "");
                                    bw.Write(wp.WPType.ID);

                                    writeRecord(fc._wptsInDB, wp.Code, ms, bw, fs, memBuffer, extraBuffer, freeRecords);

                                    wp.Saved = true;

                                    index++;
                                    procStep++;
                                    if (procStep >= 1000)
                                    {
                                        progress.UpdateProgress(STR_SAVING, STR_SAVINGWAYPOINTS, lglist.Count, index);
                                        procStep = 0;
                                    }
                                }
                            }
                        }
                        fs.Flush();
                    }

                    //**********************************************
                    //          LOGIMAGES
                    //**********************************************

                    using (FileStream fs = File.Open(fc.LogImagesFilename, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        //delete geocaches that are not in the list anymore.
                        deletedRecords = (from RecordInfo ri in fc._logimgsInDB.Values where !ri.FreeSlot && Core.LogImages.GetLogImage(ri.ID) == null select ri).ToList();
                        foreach (RecordInfo ri in deletedRecords)
                        {
                            //mark current record as free (change id)
                            fc._logimgsInDB.Remove(ri.ID);
                            ri.ID = string.Concat("_", ri.ID);
                            ri.FreeSlot = true;
                            fc._logimgsInDB.Add(ri.ID, ri);

                            //scratch file to mark it as free
                            fs.Position = ri.Offset + sizeof(long);
                            fs.WriteByte(isFree);
                        }

                        List<Framework.Data.LogImage> lgimglist = (from Framework.Data.LogImage wp in Core.LogImages
                                                                   where !wp.Saved
                                                                   select wp).ToList();
                        if (lgimglist.Count > 0)
                        {
                            List<RecordInfo> freeRecords = (from RecordInfo ri in fc._logimgsInDB.Values where ri.FreeSlot select ri).OrderByDescending(x => x.Length).ToList();

                            int index = 0;
                            int procStep = 0;
                            using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGLOGIMAGES, lgimglist.Count, 0))
                            {
                                long recordLength = 0;
                                byte[] extraBuffer = new byte[10];
                                foreach (Framework.Data.LogImage li in lgimglist)
                                {
                                    //write to block
                                    ms.Position = 0;

                                    //block header
                                    bw.Write(recordLength); //overwrite afterwards
                                    bw.Write(notFree);
                                    bw.Write(li.ID);
                                    bw.Write(li.DataFromDate.ToString("s"));
                                    bw.Write(li.LogID ?? "");
                                    bw.Write(li.Name ?? "");
                                    bw.Write(li.Url ?? "");

                                    writeRecord(fc._logimgsInDB, li.ID, ms, bw, fs, memBuffer, extraBuffer, freeRecords);

                                    li.Saved = true;

                                    index++;
                                    procStep++;
                                    if (procStep >= 1000)
                                    {
                                        progress.UpdateProgress(STR_SAVING, STR_SAVINGLOGIMAGES, lgimglist.Count, index);
                                        procStep = 0;
                                    }
                                }
                            }
                        }
                        fs.Flush();
                    }

                    //**********************************************
                    //          GEOCACHEIMAGES
                    //**********************************************

                    using (FileStream fs = File.Open(fc.GeocacheImagesFilename, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        //delete geocaches that are not in the list anymore.
                        deletedRecords = (from RecordInfo ri in fc._geocacheimgsInDB.Values where !ri.FreeSlot && Core.GeocacheImages.GetGeocacheImage(ri.ID) == null select ri).ToList();
                        foreach (RecordInfo ri in deletedRecords)
                        {
                            //mark current record as free (change id)
                            fc._geocacheimgsInDB.Remove(ri.ID);
                            ri.ID = string.Concat("_", ri.ID);
                            ri.FreeSlot = true;
                            fc._geocacheimgsInDB.Add(ri.ID, ri);

                            //scratch file to mark it as free
                            fs.Position = ri.Offset + sizeof(long);
                            fs.WriteByte(isFree);
                        }

                        List<Framework.Data.GeocacheImage> lgimglist = (from Framework.Data.GeocacheImage wp in Core.GeocacheImages
                                                                   where !wp.Saved
                                                                   select wp).ToList();
                        if (lgimglist.Count > 0)
                        {
                            List<RecordInfo> freeRecords = (from RecordInfo ri in fc._geocacheimgsInDB.Values where ri.FreeSlot select ri).OrderByDescending(x => x.Length).ToList();

                            int index = 0;
                            int procStep = 0;
                            using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGGEOCACHEIMAGES, lgimglist.Count, 0))
                            {
                                long recordLength = 0;
                                byte[] extraBuffer = new byte[100];
                                foreach (Framework.Data.GeocacheImage li in lgimglist)
                                {
                                    //write to block
                                    ms.Position = 0;

                                    //block header
                                    bw.Write(recordLength); //overwrite afterwards
                                    bw.Write(notFree);
                                    bw.Write(li.ID);
                                    bw.Write(li.DataFromDate.ToString("s"));
                                    bw.Write(li.GeocacheCode ?? "");
                                    bw.Write(li.Description ?? "");
                                    bw.Write(li.Name ?? "");
                                    bw.Write(li.Url ?? "");
                                    bw.Write(li.MobileUrl ?? "");
                                    bw.Write(li.ThumbUrl ?? "");

                                    writeRecord(fc._geocacheimgsInDB, li.ID, ms, bw, fs, memBuffer, extraBuffer, freeRecords);

                                    li.Saved = true;

                                    index++;
                                    procStep++;
                                    if (procStep >= 1000)
                                    {
                                        progress.UpdateProgress(STR_SAVING, STR_SAVINGGEOCACHEIMAGES, lgimglist.Count, index);
                                        procStep = 0;
                                    }
                                }
                            }
                        }
                        fs.Flush();
                    }

                    //**********************************************
                    //          USER WAYPOINTS
                    //**********************************************

                    using (FileStream fs = File.Open(fc.UserWaypointsFilename, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        //delete geocaches that are not in the list anymore.
                        deletedRecords = (from RecordInfo ri in fc._usrwptsInDB.Values where !ri.FreeSlot && Core.UserWaypoints.getWaypoint(int.Parse(ri.ID)) == null select ri).ToList();
                        foreach (RecordInfo ri in deletedRecords)
                        {
                            //mark current record as free (change id)
                            fc._usrwptsInDB.Remove(ri.ID);
                            ri.ID = string.Concat("_", ri.ID);
                            ri.FreeSlot = true;
                            fc._usrwptsInDB.Add(ri.ID, ri);

                            //scratch file to mark it as free
                            fs.Position = ri.Offset + sizeof(long);
                            fs.WriteByte(isFree);
                        }

                        List<Framework.Data.UserWaypoint> usrwptlist = (from Framework.Data.UserWaypoint wp in Core.UserWaypoints
                                                                        where !wp.Saved
                                                                        select wp).ToList();
                        if (usrwptlist.Count > 0)
                        {
                            List<RecordInfo> freeRecords = (from RecordInfo ri in fc._usrwptsInDB.Values where ri.FreeSlot select ri).OrderByDescending(x => x.Length).ToList();

                            long recordLength = 0;
                            byte[] extraBuffer = new byte[10];
                            foreach (Framework.Data.UserWaypoint wp in usrwptlist)
                            {
                                //write to block
                                ms.Position = 0;

                                //block header
                                bw.Write(recordLength); //overwrite afterwards
                                bw.Write(notFree);
                                bw.Write(wp.ID.ToString());
                                bw.Write(wp.Description ?? "");
                                bw.Write(wp.GeocacheCode ?? "");
                                bw.Write(wp.Lat);
                                bw.Write(wp.Lon);
                                bw.Write(wp.Date.ToString("s"));

                                writeRecord(fc._usrwptsInDB, wp.ID.ToString(), ms, bw, fs, memBuffer, extraBuffer, freeRecords);

                                wp.Saved = true;

                            }

                        }
                        fs.Flush();
                    }


                }
            }
            return result;
        }
Exemplo n.º 6
0
        public override bool Load(bool geocachesOnly)
        {
            bool result = true;
            if (_dbcon != null)
            {
                List<string> activeAttr = new List<string>();
                using (MySqlCommand cmd = new MySqlCommand("select field_name from geocache_cfields", _dbcon))
                using (MySqlDataReader dr = cmd.ExecuteReader())
                    while (dr.Read())
                    {
                        string s = string.Format("{0}", dr["field_name"]);
                        activeAttr.Add(s);
                        Core.Geocaches.AddCustomAttribute(s);
                    }

                int gcCount = 0;
                int logCount = 0;
                int logimgCount = 0;
                int wptCount = 0;
                using (MySqlCommand cmd = new MySqlCommand("select geocache, log, waypoint, logimage from counter", _dbcon))
                using (MySqlDataReader dr = cmd.ExecuteReader())
                    if (dr.Read())
                    {
                        gcCount = (int)dr["geocache"];
                        logCount = (int)dr["log"];
                        logimgCount = (int)dr["waypoint"];
                        wptCount = (int)dr["logimage"];
                    }

                using (Utils.ProgressBlock fixscr = new ProgressBlock(this, STR_LOADING, STR_LOADINGDATA, 1, 0))
                {
                    using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGGEOCACHES, gcCount, 0))
                    {
                        int index = 0;
                        int procStep = 0;
                        using (MySqlCommand cmd = new MySqlCommand("select id, code, name, datafromdate, lat, lon, disttocent, angletocent, available, archived, country, state, cachetype, placedby, owner, ownerid, container, terrain, difficulty, encodedhints, url, memberonly, customcoords, attrids, favorites, selected, municipality, city, customlat, customlon, notes, publiceddate, personalnote, flagged, found, locked from geocache", _dbcon))
                        {
                            cmd.CommandTimeout = 0;
                            using (MySqlDataReader dr = cmd.ExecuteReader())
                                while (dr.Read())
                                {
                                    Framework.Data.Geocache gc = new Framework.Data.Geocache();

                                    gc.ID = (string)dr["id"];
                                    gc.Code = (string)dr["code"];
                                    if (string.IsNullOrEmpty(gc.ID) && !string.IsNullOrEmpty(gc.Code) && gc.Code.ToUpper().StartsWith("GC"))
                                    {
                                        gc.ID = Utils.Conversion.GetCacheIDFromCacheCode(gc.Code).ToString();
                                    }
                                    gc.Name = (string)dr["name"];
                                    gc.DataFromDate = DateTime.Parse((string)dr["datafromdate"]).ToLocalTime();
                                    gc.Lat = (double)(float)dr["lat"];
                                    gc.Lon = (double)(float)dr["lon"];
                                    //gc.DistanceToCenter = (int)dr["disttocent"];
                                    //gc.AngleToCenter = (int)dr["angletocent"];
                                    gc.Available = (int)dr["available"] != 0;
                                    gc.Archived = (int)dr["archived"] != 0;
                                    gc.Country = (string)dr["country"];
                                    gc.State = (string)dr["state"];
                                    gc.GeocacheType = Utils.DataAccess.GetGeocacheType(Core.GeocacheTypes, (int)dr["cachetype"]);
                                    gc.PlacedBy = (string)dr["placedby"];
                                    gc.Owner = (string)dr["owner"];
                                    gc.OwnerId = (string)dr["ownerid"];
                                    gc.Container = Utils.DataAccess.GetGeocacheContainer(Core.GeocacheContainers, (int)dr["container"]);
                                    gc.Terrain = (double)(float)dr["terrain"];
                                    gc.Difficulty = (double)(float)dr["difficulty"];
                                    gc.EncodedHints = (string)dr["encodedhints"];
                                    gc.Url = (string)dr["url"];
                                    gc.MemberOnly = (int)dr["memberonly"] != 0;
                                    gc.CustomCoords = (int)dr["customcoords"] != 0;
                                    string s = (string)dr["attrids"];
                                    string[] parts = s.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                                    List<int> attrList = new List<int>();
                                    if (parts != null)
                                    {
                                        foreach (string si in parts)
                                        {
                                            attrList.Add(int.Parse(si));
                                        }
                                    }
                                    gc.AttributeIds = attrList;

                                    gc.Municipality = (string)dr["municipality"];
                                    gc.City = (string)dr["city"];
                                    object o = dr["customlat"];
                                    if (o == null || o.GetType() == typeof(DBNull))
                                    {
                                        gc.CustomLat = null;
                                    }
                                    else
                                    {
                                        gc.CustomLat = (double?)(float)o;
                                    }
                                    o = dr["customlon"];
                                    if (o == null || o.GetType() == typeof(DBNull))
                                    {
                                        gc.CustomLon = null;
                                    }
                                    else
                                    {
                                        gc.CustomLon = (double?)(float)o;
                                    }
                                    gc.Notes = (string)dr["notes"];
                                    gc.PublishedTime = DateTime.Parse((string)dr["publiceddate"]).ToLocalTime();
                                    gc.PersonaleNote = (string)dr["personalnote"];
                                    gc.Flagged = (int)dr["flagged"] != 0;
                                    gc.Locked = (int)dr["locked"] != 0;
                                    gc.Found = (int)dr["found"] != 0;

                                    gc.Favorites = (int)dr["favorites"];
                                    gc.Selected = (int)dr["selected"] != 0;

                                    foreach (string attrField in activeAttr)
                                    {
                                        object objValue = null;
                                        try
                                        {
                                            objValue = dr[string.Format("_{0}", attrField)];
                                        }
                                        catch
                                        {
                                        }
                                        gc.SetCustomAttribute(attrField, objValue);
                                    }

                                    Calculus.SetDistanceAndAngleGeocacheFromLocation(gc, Core.CenterLocation);

                                    gc.Saved = true;
                                    gc.IsDataChanged = false;

                                    _geocachesInDB[gc.Code] = gc.Code;
                                    Core.Geocaches.Add(gc);

                                    index++;
                                    procStep++;
                                    if (procStep >= 1000)
                                    {
                                        progress.UpdateProgress(STR_LOADING, STR_LOADINGGEOCACHES, gcCount, index);
                                        procStep = 0;
                                    }
                                }
                        }
                    }

                    if (!geocachesOnly)
                    {

                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGLOGS, logCount, 0))
                        {
                            int index = 0;
                            int procStep = 0;
                            using (MySqlCommand cmd = new MySqlCommand("select ID, gccode, Finder, DataFromDate, LogType, Date from log", _dbcon))
                            {
                                cmd.CommandTimeout = 0;
                                using (MySqlDataReader dr = cmd.ExecuteReader())
                                    while (dr.Read())
                                    {
                                        Framework.Data.Log lg = new Framework.Data.Log();

                                        //id text, gccode text, tbcode text, date text, finder text, finderid text, logtext text, encoded integer, datafromdate text, logtype integer
                                        lg.ID = (string)dr["id"];
                                        lg.GeocacheCode = (string)dr["gccode"];
                                        lg.Date = DateTime.Parse((string)dr["date"]).ToLocalTime();
                                        lg.Finder = (string)dr["finder"];
                                        lg.DataFromDate = DateTime.Parse((string)dr["datafromdate"]).ToLocalTime();
                                        lg.LogType = Utils.DataAccess.GetLogType(Core.LogTypes, (int)dr["logtype"]);

                                        lg.Saved = true;
                                        lg.IsDataChanged = false;

                                        _logsInDB[lg.ID] = lg.ID;
                                        Core.Logs.Add(lg);

                                        index++;
                                        procStep++;
                                        if (procStep >= 20000)
                                        {
                                            progress.UpdateProgress(STR_LOADING, STR_LOADINGLOGS, logCount, index);
                                            procStep = 0;
                                        }
                                    }
                            }
                        }


                        //(id text, logid text, url text, name text, datafromdate text)
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGLOGIMAGES, logimgCount, 0))
                        {
                            int index = 0;
                            int procStep = 0;
                            using (MySqlCommand cmd = new MySqlCommand("select * from logimage", _dbcon))
                            using (MySqlDataReader dr = cmd.ExecuteReader())
                                while (dr.Read())
                                {
                                    Framework.Data.LogImage lg = new Framework.Data.LogImage();

                                    lg.ID = (string)dr["id"];
                                    lg.LogID = (string)dr["logid"];
                                    lg.Url = (string)dr["url"];
                                    lg.Name = (string)dr["name"];
                                    lg.DataFromDate = DateTime.Parse((string)dr["datafromdate"]).ToLocalTime();

                                    lg.Saved = true;
                                    lg.IsDataChanged = false;

                                    _logimgsInDB[lg.ID] = lg.ID;
                                    Core.LogImages.Add(lg);

                                    index++;
                                    procStep++;
                                    if (procStep >= 2000)
                                    {
                                        progress.UpdateProgress("Loading...", "Loading log images...", logimgCount, index);
                                        procStep = 0;
                                    }
                                }
                        }


                        //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
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGWAYPOINTS, wptCount, 0))
                        {
                            int index = 0;
                            int procStep = 0;
                            using (MySqlCommand cmd = new MySqlCommand("select * from waypoint", _dbcon))
                            {
                                cmd.CommandTimeout = 0;
                                using (MySqlDataReader dr = cmd.ExecuteReader())
                                    while (dr.Read())
                                    {
                                        Framework.Data.Waypoint wp = new Framework.Data.Waypoint();

                                        wp.ID = (string)dr["id"];
                                        wp.Code = (string)dr["code"];
                                        wp.Url = (string)dr["url"];
                                        wp.UrlName = (string)dr["urlname"];
                                        wp.Name = (string)dr["name"];
                                        wp.DataFromDate = DateTime.Parse((string)dr["datafromdate"]).ToLocalTime();
                                        wp.Comment = (string)dr["comment"];
                                        wp.GeocacheCode = (string)dr["geocachecode"];
                                        wp.Description = (string)dr["description"];
                                        wp.WPType = Utils.DataAccess.GetWaypointType(Core.WaypointTypes, (int)dr["wptype"]);
                                        object o = dr["lat"];
                                        if (o == null || o.GetType() == typeof(DBNull))
                                        {
                                            wp.Lat = null;
                                        }
                                        else
                                        {
                                            wp.Lat = (double?)(float)o;
                                        }
                                        o = dr["lon"];
                                        if (o == null || o.GetType() == typeof(DBNull))
                                        {
                                            wp.Lon = null;
                                        }
                                        else
                                        {
                                            wp.Lon = (double?)(float)o;
                                        }
                                        wp.Time = DateTime.Parse((string)dr["time"]).ToLocalTime();

                                        wp.Saved = true;
                                        wp.IsDataChanged = false;

                                        _wptsInDB[wp.Code] = wp.Code;
                                        Core.Waypoints.Add(wp);

                                        index++;
                                        procStep++;
                                        if (procStep >= 20000)
                                        {
                                            progress.UpdateProgress(STR_LOADING, STR_LOADINGWAYPOINTS, wptCount, index);
                                            procStep = 0;
                                        }
                                    }
                            }
                        }

                        using (MySqlCommand cmd = new MySqlCommand("select * from userwaypoint", _dbcon))
                        using (MySqlDataReader dr = cmd.ExecuteReader())
                            while (dr.Read())
                            {
                                Framework.Data.UserWaypoint wp = new Framework.Data.UserWaypoint();

                                wp.ID = (int)dr["id"];
                                wp.GeocacheCode = (string)dr["geocachecode"];
                                wp.Description = (string)dr["description"];
                                wp.Lat = (double)(float)dr["lat"];
                                wp.Lon = (double)(float)dr["lon"];
                                wp.Date = DateTime.Parse((string)dr["time"]).ToLocalTime();

                                wp.Saved = true;
                                wp.IsDataChanged = false;

                                _usrwptsInDB[wp.ID] = wp.ID;
                                Core.UserWaypoints.Add(wp);
                            }

                    }
                }
            }

            return result;
        }
Exemplo n.º 7
0
        public bool Save(MySqlConnection dbcon, bool forceFullData)
        {
            bool result = true;
            using (Utils.ProgressBlock fixpr = new ProgressBlock(this, STR_SAVING, STR_SAVINGDATA, 1, 0))
            {
                if (dbcon != null)
                {
                    string[] custAttr = Core.Geocaches.CustomAttributes;
                    List<string> activeAttr = new List<string>();
                    using (MySqlCommand cmd = new MySqlCommand("select field_name from geocache_cfields", dbcon))
                    using (MySqlDataReader dr = cmd.ExecuteReader())
                        while (dr.Read())
                        {
                            activeAttr.Add(string.Format("{0}", dr["field_name"]));
                        }

                    foreach (string s in activeAttr)
                    {
                        if (!custAttr.Contains(s) && ColumnExists(dbcon, "geocache", string.Format("_{0}", s)))
                        {
                            //drop column not supported!
                        }
                    }
                    //geocache_cfields
                    using (MySqlCommand cmd = new MySqlCommand("delete from geocache_cfields", dbcon))
                        cmd.ExecuteNonQuery();
                    foreach (string s in custAttr)
                    {
                        if (!activeAttr.Contains(s))
                        {
                            using (MySqlCommand cmd = new MySqlCommand(string.Format("insert into geocache_cfields (field_name) values ('{0}')", s), dbcon))
                                cmd.ExecuteNonQuery();
                        }
                        if (!ColumnExists(dbcon, "geocache", string.Format("_{0}", s)))
                        {
                            using (MySqlCommand cmd = new MySqlCommand(string.Format("alter table geocache add _{0} text)", s), dbcon))
                                cmd.ExecuteNonQuery();
                        }
                    }

                    //delete geoacches that are not in the list anymore.
                    string[] c = (from string a in _geocachesInDB.Keys select a).ToArray();
                    using (MySqlCommand cmd = dbcon.CreateCommand())
                        for (int i = 0; i < c.Length; i++)
                        {
                            if (Utils.DataAccess.GetGeocache(Core.Geocaches, c[i]) == null)
                            {
                                cmd.CommandText = string.Format("delete from geocache where code='{0}'", c[i]);
                                cmd.ExecuteNonQuery();
                                _geocachesInDB.Remove(c[i]);
                            }
                        }

                    //reset selection
                    using (MySqlCommand cmd = new MySqlCommand("update geocache set selected=0", dbcon))
                        cmd.ExecuteNonQuery();

                    //now get all the selected and data changed geocaches
                    List<Framework.Data.Geocache> gclist = (from Framework.Data.Geocache wp in Core.Geocaches
                                                            where wp.Selected || !wp.Saved
                                                            select wp).ToList();
                    if (gclist.Count > 0)
                    {
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGGEOCACHES, gclist.Count, 0))
                        {
                            string updateSqlFull = "update geocache set id=@id, name=@name, datafromdate=@datafromdate, lat=@lat, lon=@lon, disttocent=@disttocent, angletocent=@angletocent, available=@available, archived=@archived, country=@country, state=@state, cachetype=@cachetype, placedby=@placedby, owner=@owner, ownerid=@ownerid, container=@container, terrain=@terrain, difficulty=@difficulty, shortdescr=@shortdescr, shortdescrhtml=@shortdescrhtml, longdescr=@longdescr, longdescrhtml=@longdescrhtml, encodedhints=@encodedhints, url=@url, memberonly=@memberonly, customcoords=@customcoords, attrids=@attrids, favorites=@favorites, selected=@selected, municipality=@municipality, city=@city, customlat=@customlat, customlon=@customlon, notes=@notes, publiceddate=@publiceddate, personalnote=@personalnote, flagged=@flagged, found=@found, locked=@locked where code=@code";
                            string insertSqlFull = "insert into geocache (id, code, name, datafromdate, lat, lon, disttocent, angletocent, available, archived, country, state, cachetype, placedby, owner, ownerid, container, terrain, difficulty, shortdescr, shortdescrhtml, longdescr, longdescrhtml, encodedhints, url, memberonly, customcoords, attrids, favorites, selected, municipality, city, customlat, customlon, notes, publiceddate, personalnote, flagged, found, locked) values (@id, @code, @name, @datafromdate, @lat, @lon, @disttocent, @angletocent, @available, @archived, @country, @state, @cachetype, @placedby, @owner, @ownerid, @container, @terrain, @difficulty, @shortdescr, @shortdescrhtml, @longdescr, @longdescrhtml, @encodedhints, @url, @memberonly, @customcoords, @attrids, @favorites, @selected, @municipality, @city, @customlat, @customlon, @notes, @publiceddate, @personalnote, @flagged, @found, @locked)";

                            string updateSqlShort = "update geocache set id=@id, name=@name, datafromdate=@datafromdate, lat=@lat, lon=@lon, disttocent=@disttocent, angletocent=@angletocent, available=@available, archived=@archived, country=@country, state=@state, cachetype=@cachetype, placedby=@placedby, owner=@owner, ownerid=@ownerid, container=@container, terrain=@terrain, difficulty=@difficulty, encodedhints=@encodedhints, url=@url, memberonly=@memberonly, customcoords=@customcoords, attrids=@attrids, favorites=@favorites, selected=@selected, municipality=@municipality, city=@city, customlat=@customlat, customlon=@customlon, notes=@notes, publiceddate=@publiceddate, personalnote=@personalnote, flagged=@flagged, found=@found, locked=@locked where code=@code";
                            string insertSqlShort = "insert into geocache (id, code, name, datafromdate, lat, lon, disttocent, angletocent, available, archived, country, state, cachetype, placedby, owner, ownerid, container, terrain, difficulty, encodedhints, url, memberonly, customcoords, attrids, favorites, selected, municipality, city, customlat, customlon, notes, publiceddate, personalnote, flagged, found, locked) values (@id, @code, @name, @datafromdate, @lat, @lon, @disttocent, @angletocent, @available, @archived, @country, @state, @cachetype, @placedby, @owner, @ownerid, @container, @terrain, @difficulty, @encodedhints, @url, @memberonly, @customcoords, @attrids, @favorites, @selected, @municipality, @city, @customlat, @customlon, @notes, @publiceddate, @personalnote, @flagged, @found, @locked)";

                            using (MySqlCommand cmd = dbcon.CreateCommand())
                            {
                                cmd.CommandType = CommandType.Text;
                                DbParameter par = cmd.CreateParameter();
                                par.ParameterName = "@id";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@code";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@name";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@datafromdate";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@lat";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@lon";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@disttocent";
                                par.DbType = DbType.Int64;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@angletocent";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@available";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@archived";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@country";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@state";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@cachetype";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@placedby";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@owner";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@ownerid";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@container";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@terrain";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@difficulty";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@shortdescr";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@shortdescrhtml";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@longdescr";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@longdescrhtml";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@encodedhints";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@url";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@memberonly";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@customcoords";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@attrids";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@favorites";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@selected";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@municipality";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@city";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@customlat";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@customlon";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@notes";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@publiceddate";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@personalnote";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@flagged";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@found";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@locked";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);

                                foreach (string s in custAttr)
                                {
                                    par = cmd.CreateParameter();
                                    par.ParameterName = string.Format("@_{0}", s);
                                    par.DbType = DbType.String;
                                    cmd.Parameters.Add(par);
                                }

                                cmd.Prepare();

                                StringBuilder sb = new StringBuilder();

                                //using (MySqlTransaction trans = dbcon.BeginTransaction())
                                {
                                    //cmd.Transaction = trans;

                                    int index = 0;
                                    int procStep = 0;
                                    foreach (Framework.Data.Geocache gc in gclist)
                                    {
                                        index++;
                                        procStep++;
                                        if (!gc.Saved)
                                        {
                                            cmd.Parameters["@id"].Value = gc.ID ?? "";
                                            cmd.Parameters["@code"].Value = gc.Code;
                                            cmd.Parameters["@name"].Value = gc.Name ?? "";
                                            cmd.Parameters["@datafromdate"].Value = gc.DataFromDate.ToUniversalTime().ToString("u");
                                            cmd.Parameters["@lat"].Value = gc.Lat;
                                            cmd.Parameters["@lon"].Value = gc.Lon;
                                            cmd.Parameters["@disttocent"].Value = gc.DistanceToCenter;
                                            cmd.Parameters["@angletocent"].Value = gc.AngleToCenter;
                                            cmd.Parameters["@available"].Value = gc.Available ? 1 : 0;
                                            cmd.Parameters["@archived"].Value = gc.Archived ? 1 : 0;
                                            cmd.Parameters["@country"].Value = gc.Country ?? "";
                                            cmd.Parameters["@state"].Value = gc.State ?? "";
                                            cmd.Parameters["@cachetype"].Value = gc.GeocacheType == null ? -1 : gc.GeocacheType.ID;
                                            cmd.Parameters["@placedby"].Value = gc.PlacedBy ?? "";
                                            cmd.Parameters["@owner"].Value = gc.Owner ?? "";
                                            cmd.Parameters["@ownerid"].Value = gc.OwnerId ?? "";
                                            cmd.Parameters["@container"].Value = gc.Container == null ? -1 : gc.Container.ID;
                                            cmd.Parameters["@terrain"].Value = gc.Terrain;
                                            cmd.Parameters["@difficulty"].Value = gc.Difficulty;
                                            if (forceFullData || gc.FullDataLoaded)
                                            {
                                                cmd.Parameters["@shortdescr"].Value = gc.ShortDescription ?? "";
                                                cmd.Parameters["@shortdescrhtml"].Value = gc.ShortDescriptionInHtml ? 1 : 0;
                                                cmd.Parameters["@longdescr"].Value = gc.LongDescription ?? "";
                                                cmd.Parameters["@longdescrhtml"].Value = gc.LongDescriptionInHtml ? 1 : 0;
                                            }
                                            cmd.Parameters["@encodedhints"].Value = gc.EncodedHints ?? "";
                                            cmd.Parameters["@url"].Value = gc.Url ?? "";
                                            cmd.Parameters["@memberonly"].Value = gc.MemberOnly ? 1 : 0;
                                            cmd.Parameters["@customcoords"].Value = gc.CustomCoords ? 1 : 0;
                                            sb.Length = 0;
                                            foreach (int attrId in gc.AttributeIds)
                                            {
                                                sb.AppendFormat("|{0}|", attrId);
                                            }
                                            cmd.Parameters["@attrids"].Value = sb.ToString();
                                            cmd.Parameters["@favorites"].Value = gc.Favorites;
                                            cmd.Parameters["@selected"].Value = gc.Selected ? 1 : 0;
                                            cmd.Parameters["@municipality"].Value = gc.Municipality ?? "";
                                            cmd.Parameters["@city"].Value = gc.City ?? "";
                                            if (gc.CustomLat == null)
                                            {
                                                cmd.Parameters["@customlat"].Value = DBNull.Value;
                                            }
                                            else
                                            {
                                                cmd.Parameters["@customlat"].Value = gc.CustomLat;
                                            }
                                            if (gc.CustomLon == null)
                                            {
                                                cmd.Parameters["@customlon"].Value = DBNull.Value;
                                            }
                                            else
                                            {
                                                cmd.Parameters["@customlon"].Value = gc.CustomLon;
                                            }
                                            cmd.Parameters["@notes"].Value = gc.Notes ?? "";
                                            cmd.Parameters["@publiceddate"].Value = gc.PublishedTime.ToUniversalTime().ToString("u");
                                            cmd.Parameters["@personalnote"].Value = gc.PersonaleNote ?? "";
                                            cmd.Parameters["@flagged"].Value = gc.Flagged ? 1 : 0;
                                            cmd.Parameters["@found"].Value = gc.Found ? 1 : 0;
                                            cmd.Parameters["@locked"].Value = gc.Locked ? 1 : 0;

                                            foreach (string s in custAttr)
                                            {
                                                object o = gc.GetCustomAttribute(s);
                                                if (o == null)
                                                {
                                                    cmd.Parameters[string.Format("@_{0}", s)].Value = DBNull.Value;
                                                }
                                                else
                                                {
                                                    cmd.Parameters[string.Format("@_{0}", s)].Value = o.ToString();
                                                }
                                            }

                                            bool indb = _geocachesInDB[gc.Code] != null;
                                            if (forceFullData || gc.FullDataLoaded)
                                            {
                                                cmd.CommandText = updateSqlFull;
                                                if (!indb || cmd.ExecuteNonQuery() == 0)
                                                {
                                                    cmd.CommandText = insertSqlFull;
                                                    cmd.ExecuteNonQuery();
                                                    if (!indb)
                                                    {
                                                        _geocachesInDB[gc.Code] = gc.Code;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                cmd.CommandText = updateSqlShort;
                                                if (!indb || cmd.ExecuteNonQuery() == 0)
                                                {
                                                    cmd.CommandText = insertSqlShort;
                                                    cmd.ExecuteNonQuery();
                                                    if (!indb)
                                                    {
                                                        _geocachesInDB[gc.Code] = gc.Code;
                                                    }
                                                }
                                            }
                                            gc.Saved = true;
                                        }
                                        else if (gc.Selected)
                                        {
                                            cmd.CommandText = string.Format("update geocache set selected=1 where code='{0}'", gc.Code);
                                            cmd.ExecuteNonQuery();
                                        }
                                        if (procStep >= 200)
                                        {
                                            progress.UpdateProgress(STR_SAVING, STR_SAVINGGEOCACHES, gclist.Count, index);
                                            procStep = 0;
                                        }
                                    }
                                    //trans.Commit();
                                }
                            }
                        }
                    }

                    //delete logs that are not in the list anymore.
                    c = (from string a in _logsInDB.Keys select a).ToArray();
                    using (MySqlCommand cmd = dbcon.CreateCommand())
                        for (int i = 0; i < c.Length; i++)
                        {
                            if (Utils.DataAccess.GetLog(Core.Logs, c[i]) == null)
                            {
                                cmd.CommandText = string.Format("delete from log where id='{0}'", c[i]);
                                cmd.ExecuteNonQuery();
                                _logsInDB.Remove(c[i]);
                            }
                        }

                    //now get all the selected and data changed geocaches
                    List<Framework.Data.Log> lglist = (from Framework.Data.Log wp in Core.Logs
                                                       where !wp.Saved
                                                       select wp).ToList();
                    if (lglist.Count > 0)
                    {
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGLOGS, lglist.Count, 0))
                        {
                            // tbcode, finderid, logtext, encoded
                            string updateSqlFull = "update log set gccode=@gccode, tbcode=@tbcode, date=@date, finder=@finder, finderid=@finderid, logtext=@logtext, encoded=@encoded, datafromdate=@datafromdate, logtype=@logtype where id=@id";
                            string insertSqlFull = "insert into log (id, gccode, tbcode, date, finder, finderid, logtext, encoded, datafromdate, logtype) values (@id, @gccode, @tbcode, @date, @finder, @finderid, @logtext, @encoded, @datafromdate, @logtype)";

                            string updateSqlShort = "update log set gccode=@gccode, date=@date, finder=@finder, datafromdate=@datafromdate, logtype=@logtype where id=@id";
                            string insertSqlShort = "insert into log (id, gccode, date, finder, datafromdate, logtype) values (@id, @gccode, @date, @finder, @datafromdate, @logtype)";

                            using (MySqlCommand cmd = dbcon.CreateCommand())
                            {
                                cmd.CommandType = CommandType.Text;
                                cmd.Parameters.Clear();
                                DbParameter par = cmd.CreateParameter();
                                par.ParameterName = "@id";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@gccode";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@tbcode";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@date";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@finder";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@finderid";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@logtext";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@encoded";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@datafromdate";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@logtype";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);

                                //cmd.Prepare();

                                //using (MySqlTransaction trans = dbcon.BeginTransaction())
                                {
                                    //cmd.Transaction = trans;

                                    int index = 0;
                                    int procStep = 0;
                                    foreach (Framework.Data.Log lg in lglist)
                                    {
                                        index++;
                                        procStep++;

                                        cmd.Parameters["@id"].Value = lg.ID;
                                        cmd.Parameters["@gccode"].Value = lg.GeocacheCode;
                                        cmd.Parameters["@date"].Value = lg.Date.ToUniversalTime().ToString("u");
                                        cmd.Parameters["@finder"].Value = lg.Finder ?? "";
                                        cmd.Parameters["@datafromdate"].Value = lg.DataFromDate.ToUniversalTime().ToString("u");
                                        cmd.Parameters["@logtype"].Value = lg.LogType == null ? -1 : lg.LogType.ID;
                                        if (forceFullData || lg.FullDataLoaded)
                                        {
                                            cmd.Parameters["@tbcode"].Value = lg.TBCode ?? "";
                                            cmd.Parameters["@finderid"].Value = lg.FinderId ?? "";
                                            cmd.Parameters["@logtext"].Value = lg.Text ?? "";
                                            cmd.Parameters["@encoded"].Value = lg.Encoded ? 1 : 0;
                                        }

                                        bool indb = _logsInDB[lg.ID] != null;
                                        if (forceFullData || lg.FullDataLoaded)
                                        {
                                            cmd.CommandText = updateSqlFull;
                                            if (!indb || cmd.ExecuteNonQuery() == 0)
                                            {
                                                cmd.CommandText = insertSqlFull;
                                                cmd.ExecuteNonQuery();
                                                if (!indb)
                                                {
                                                    _logsInDB[lg.ID] = lg.ID;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            cmd.CommandText = updateSqlShort;
                                            if (!indb || cmd.ExecuteNonQuery() == 0)
                                            {
                                                cmd.CommandText = insertSqlShort;
                                                cmd.ExecuteNonQuery();
                                                if (!indb)
                                                {
                                                    _logsInDB[lg.ID] = lg.ID;
                                                }
                                            }
                                        }
                                        lg.Saved = true;

                                        if (procStep >= 2000)
                                        {
                                            progress.UpdateProgress(STR_SAVING, STR_SAVINGLOGS, lglist.Count, index);
                                            procStep = 0;
                                        }
                                    }
                                    //trans.Commit();

                                }
                            }
                        }
                    }



                    //delete log images that are not in the list anymore.
                    c = (from string a in _logimgsInDB.Keys select a).ToArray();
                    using (MySqlCommand cmd = dbcon.CreateCommand())
                        for (int i = 0; i < c.Length; i++)
                        {
                            if (Utils.DataAccess.GetLogImage(Core.LogImages, c[i]) == null)
                            {
                                cmd.CommandText = string.Format("delete from logimage where id='{0}'", c[i]);
                                cmd.ExecuteNonQuery();
                                _logimgsInDB.Remove(c[i]);
                            }
                        }

                    //now get all the selected and data changed geocaches
                    List<Framework.Data.LogImage> imglist = (from Framework.Data.LogImage wp in Core.LogImages
                                                             where !wp.Saved
                                                             select wp).ToList();
                    if (imglist.Count > 0)
                    {
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGLOGIMAGES, imglist.Count, 0))
                        {
                            string updateSql = "update logimage set logid=@logid, url=@url, name=@name, datafromdate=@datafromdate where id=@id";
                            string insertSql = "insert into logimage (id, logid, url, name, datafromdate) values (@id, @logid, @url, @name, @datafromdate)";

                            using (MySqlCommand cmd = dbcon.CreateCommand())
                            {

                                cmd.CommandType = CommandType.Text;
                                cmd.Parameters.Clear();
                                DbParameter par = cmd.CreateParameter();
                                par.ParameterName = "@id";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@logid";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@url";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@name";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@datafromdate";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                //cmd.Prepare();

                                //using (SqlTransaction trans = dbcon.BeginTransaction())
                                {
                                    //cmd.Transaction = trans;

                                    int index = 0;
                                    int procStep = 0;
                                    foreach (Framework.Data.LogImage lg in imglist)
                                    {
                                        index++;
                                        procStep++;

                                        cmd.Parameters["@id"].Value = lg.ID;
                                        cmd.Parameters["@logid"].Value = lg.LogID ?? "";
                                        cmd.Parameters["@url"].Value = lg.Url ?? "";
                                        cmd.Parameters["@name"].Value = lg.Name ?? "";
                                        cmd.Parameters["@datafromdate"].Value = lg.DataFromDate.ToUniversalTime().ToString("u");

                                        bool indb = _logimgsInDB[lg.ID] != null;
                                        cmd.CommandText = updateSql;
                                        if (!indb || cmd.ExecuteNonQuery() == 0)
                                        {
                                            cmd.CommandText = insertSql;
                                            cmd.ExecuteNonQuery();
                                            if (!indb)
                                            {
                                                _logimgsInDB[lg.ID] = lg.ID;
                                            }
                                        }
                                        lg.Saved = true;

                                        if (procStep >= 500)
                                        {
                                            progress.UpdateProgress(STR_SAVING, STR_SAVINGLOGIMAGES, imglist.Count, index);
                                            procStep = 0;
                                        }
                                    }
                                    //trans.Commit();
                                }
                            }
                        }
                    }


                    c = (from string a in _wptsInDB.Keys select a).ToArray();
                    using (MySqlCommand cmd = dbcon.CreateCommand())
                        for (int i = 0; i < c.Length; i++)
                        {
                            if (Utils.DataAccess.GetWaypoint(Core.Waypoints, c[i]) == null)
                            {
                                cmd.CommandText = string.Format("delete from waypoint where code='{0}'", c[i]);
                                cmd.ExecuteNonQuery();
                                _wptsInDB.Remove(c[i]);
                            }
                        }

                    //now get all the selected and data changed geocaches
                    List<Framework.Data.Waypoint> wplist = (from Framework.Data.Waypoint wp in Core.Waypoints
                                                            where !wp.Saved
                                                            select wp).ToList();
                    if (wplist.Count > 0)
                    {
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGWAYPOINTS, wplist.Count, 0))
                        {
                            string updateSql = "update waypoint set id=@id, geocachecode=@geocachecode, name=@name, datafromdate=@datafromdate, comment=@comment, description=@description, url=@url, urlname=@urlname, wptype=@wptype, lat=@lat, lon=@lon, time=@time where code=@code";
                            string insertSql = "insert into waypoint (id, code, geocachecode, name, datafromdate, comment, description, url, urlname, wptype, lat, lon, time) values (@id, @code, @geocachecode, @name, @datafromdate, @comment, @description, @url, @urlname, @wptype, @lat, @lon, @time)";

                            using (MySqlCommand cmd = dbcon.CreateCommand())
                            {

                                cmd.CommandType = CommandType.Text;
                                cmd.Parameters.Clear();
                                DbParameter par = cmd.CreateParameter();
                                par.ParameterName = "@id";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@code";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@url";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@name";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@datafromdate";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@geocachecode";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@comment";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@description";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@urlname";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@wptype";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@lat";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@lon";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@time";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                //cmd.Prepare();

                                //using (SqlTransaction trans = dbcon.BeginTransaction())
                                {
                                    //cmd.Transaction = trans;

                                    int index = 0;
                                    int procStep = 0;
                                    foreach (Framework.Data.Waypoint wp in wplist)
                                    {
                                        index++;
                                        procStep++;

                                        cmd.Parameters["@id"].Value = wp.ID;
                                        cmd.Parameters["@code"].Value = wp.Code ?? "";
                                        cmd.Parameters["@url"].Value = wp.Url ?? "";
                                        cmd.Parameters["@urlname"].Value = wp.UrlName ?? "";
                                        cmd.Parameters["@name"].Value = wp.Name ?? "";
                                        cmd.Parameters["@comment"].Value = wp.Comment ?? "";
                                        cmd.Parameters["@geocachecode"].Value = wp.GeocacheCode ?? "";
                                        cmd.Parameters["@description"].Value = wp.Description ?? "";
                                        cmd.Parameters["@datafromdate"].Value = wp.DataFromDate.ToUniversalTime().ToString("u");
                                        cmd.Parameters["@time"].Value = wp.Time.ToUniversalTime().ToString("u");
                                        cmd.Parameters["@wptype"].Value = wp.WPType.ID;
                                        if (wp.Lat == null)
                                        {
                                            cmd.Parameters["@lat"].Value = DBNull.Value;
                                        }
                                        else
                                        {
                                            cmd.Parameters["@lat"].Value = (double)(float)wp.Lat;
                                        }
                                        if (wp.Lon == null)
                                        {
                                            cmd.Parameters["@lon"].Value = DBNull.Value;
                                        }
                                        else
                                        {
                                            cmd.Parameters["@lon"].Value = wp.Lon;
                                        }

                                        bool indb = _wptsInDB[wp.Code] != null;
                                        cmd.CommandText = updateSql;
                                        if (!indb || cmd.ExecuteNonQuery() == 0)
                                        {
                                            cmd.CommandText = insertSql;
                                            cmd.ExecuteNonQuery();
                                            if (!indb)
                                            {
                                                _wptsInDB[wp.Code] = wp.Code;
                                            }
                                        }
                                        wp.Saved = true;

                                        if (procStep >= 500)
                                        {
                                            progress.UpdateProgress(STR_SAVING, STR_SAVINGWAYPOINTS, wplist.Count, index);
                                            procStep = 0;
                                        }
                                    }
                                    //trans.Commit();
                                }
                            }
                        }
                    }

                    int[] ci = (from int a in _usrwptsInDB.Keys select a).ToArray();
                    using (MySqlCommand cmd = new MySqlCommand("", dbcon))
                        for (int i = 0; i < ci.Length; i++)
                        {
                            if (Utils.DataAccess.GetUserWaypoint(Core.UserWaypoints, ci[i]) == null)
                            {
                                cmd.CommandText = string.Format("delete from userwaypoint where id={0}", ci[i]);
                                cmd.ExecuteNonQuery();
                                _usrwptsInDB.Remove(ci[i]);
                            }
                        }

                    //now get all the selected and data changed geocaches
                    List<Framework.Data.UserWaypoint> usrwplist = (from Framework.Data.UserWaypoint wp in Core.UserWaypoints
                                                                   where !wp.Saved
                                                                   select wp).ToList();
                    if (usrwplist.Count > 0)
                    {
                        string updateSql = "update userwaypoint set geocachecode=@geocachecode, description=@description, lat=@lat, lon=@lon, time=@time where id=@id";
                        string insertSql = "insert into userwaypoint (id, geocachecode, description, lat, lon, time) values (@id, @geocachecode, @description, @lat, @lon, @time)";

                        using (MySqlCommand cmd = new MySqlCommand("", dbcon))
                        {

                            cmd.CommandType = CommandType.Text;
                            cmd.Parameters.Clear();
                            DbParameter par = cmd.CreateParameter();
                            par.ParameterName = "@id";
                            par.DbType = DbType.Int32;
                            cmd.Parameters.Add(par);
                            par = cmd.CreateParameter();
                            par.ParameterName = "@geocachecode";
                            par.DbType = DbType.String;
                            cmd.Parameters.Add(par);
                            par = cmd.CreateParameter();
                            par.ParameterName = "@description";
                            par.DbType = DbType.String;
                            cmd.Parameters.Add(par);
                            par = cmd.CreateParameter();
                            par.ParameterName = "@lat";
                            par.DbType = DbType.Double;
                            cmd.Parameters.Add(par);
                            par = cmd.CreateParameter();
                            par.ParameterName = "@lon";
                            par.DbType = DbType.Double;
                            cmd.Parameters.Add(par);
                            par = cmd.CreateParameter();
                            par.ParameterName = "@time";
                            par.DbType = DbType.String;
                            cmd.Parameters.Add(par);
                            //cmd.Prepare();

                            //using (DbTransaction trans = dbcon.BeginTransaction())
                            {
                                //cmd.Transaction = trans;
                                foreach (Framework.Data.UserWaypoint wp in usrwplist)
                                {
                                    cmd.Parameters["@id"].Value = wp.ID;
                                    cmd.Parameters["@geocachecode"].Value = wp.GeocacheCode ?? "";
                                    cmd.Parameters["@description"].Value = wp.Description ?? "";
                                    cmd.Parameters["@time"].Value = wp.Date.ToUniversalTime().ToString("u");
                                    cmd.Parameters["@lat"].Value = (double)wp.Lat;
                                    cmd.Parameters["@lon"].Value = wp.Lon;

                                    bool indb = _usrwptsInDB[wp.ID] != null;
                                    cmd.CommandText = updateSql;
                                    if (!indb || cmd.ExecuteNonQuery() == 0)
                                    {
                                        cmd.CommandText = insertSql;
                                        cmd.ExecuteNonQuery();
                                        if (!indb)
                                        {
                                            _usrwptsInDB[wp.ID] = wp.ID;
                                        }
                                    }
                                    wp.Saved = true;
                                }
                                //trans.Commit();
                            }
                        }
                    }

                    using (MySqlCommand cmd = new MySqlCommand(string.Format("update counter set geocache={0}, log={1}, waypoint={2}, logimage={3}", _geocachesInDB.Count, _logsInDB.Count, _wptsInDB.Count, _logimgsInDB.Count), dbcon))
                        cmd.ExecuteNonQuery();
                }
                else
                {
                    result = false;
                }
            }
            return result;
        }
Exemplo n.º 8
0
    private void threadMethod()
    {
        try
        {
            bool cancel = false;
            using (ProgressBlock progress = new ProgressBlock(_plugin, "Bijwerken van status en nieuwe geocaches", "Download gegevens van globalcaching.eu", 1, 0, true))
            {
                using (System.Net.WebClient wc = new System.Net.WebClient())
                {
                    string doc = wc.DownloadString("http://www.globalcaching.eu/Service/GeocacheCodes.aspx?country=Netherlands");
                    if (doc != null)
                    {
                        List<string> gcList = new List<string>();

                        string[] lines = doc.Replace("\r", "").Split(new char[] { '\n' });
                        progress.UpdateProgress("Bijwerken van status en nieuwe geocaches", "Bijwerken van de status...", lines.Length, 0);
                        Geocache gc;
                        char[] sep = new char[] { ',' };
                        string[] parts;
                        foreach (string s in lines)
                        {
                            parts = s.Split(sep);
                            if (parts.Length > 2)
                            {
                                gc = DataAccess.GetGeocache(_core.Geocaches, parts[0]);
                                if (gc != null)
                                {
                                    gc.Archived = parts[1] != "0";
                                    gc.Available = parts[2] != "0";
                                }
                                else if (parts[1] == "0") //add only none archived
                                {
                                    gcList.Add(parts[0]);
                                }
                            }
                        }

                        if (gcList.Count == 0)
                        {
                            System.Windows.Forms.MessageBox.Show("Er zijn geen nieuwe geocaches gevonden", "Bericht", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                        }
                        else
                        {
                            if (System.Windows.Forms.MessageBox.Show(string.Format("Er zijn {0} nieuwe geocaches gevonden\r\nDeze downloaden?", gcList.Count), "Bericht", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                            {
                                progress.UpdateProgress("Bijwerken van status en nieuwe geocaches", "Importeren van geocaches...", gcList.Count, 0);

                                using (GeocachingLiveV6 client = new GeocachingLiveV6(_core, string.IsNullOrEmpty(_core.GeocachingComAccount.APIToken)))
                                {
                                    int index = 0;
                                    int total = gcList.Count;
                                    int gcupdatecount;
                                    TimeSpan interval = new TimeSpan(0, 0, 0, 2, 100);
                                    DateTime prevCall = DateTime.MinValue;
                                    bool dodelay;
                                    gcupdatecount = 30;
                                    dodelay = (gcList.Count > 30);
                                    while (gcList.Count > 0)
                                    {
                                        if (dodelay)
                                        {
                                            TimeSpan ts = DateTime.Now - prevCall;
                                            if (ts < interval)
                                            {
                                                Thread.Sleep(interval - ts);
                                            }
                                        }
                                        GlobalcachingApplication.Utils.API.LiveV6.SearchForGeocachesRequest req = new GlobalcachingApplication.Utils.API.LiveV6.SearchForGeocachesRequest();
                                        req.IsLite = false;
                                        req.AccessToken = client.Token;
                                        req.CacheCode = new GlobalcachingApplication.Utils.API.LiveV6.CacheCodeFilter();
                                        req.CacheCode.CacheCodes = (from a in gcList select a).Take(gcupdatecount).ToArray();
                                        req.MaxPerPage = gcupdatecount;
                                        req.GeocacheLogCount = 5;
                                        index += req.CacheCode.CacheCodes.Length;
                                        gcList.RemoveRange(0, req.CacheCode.CacheCodes.Length);
                                        prevCall = DateTime.Now;
                                        var resp = client.Client.SearchForGeocaches(req);
                                        if (resp.Status.StatusCode == 0 && resp.Geocaches != null)
                                        {
                                            Import.AddGeocaches(_core, resp.Geocaches);
                                        }
                                        else
                                        {
                                            _errormessage = resp.Status.StatusMessage;
                                            break;
                                        }
                                        if (!progress.UpdateProgress("Bijwerken van status en nieuwe geocaches", "Importeren van geocaches...", total, index))
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        catch(Exception e)
        {
            _errormessage = e.Message;
        }
        _actionReady.Set();
    }
Exemplo n.º 9
0
        private bool insertFromDatabase(bool overwrite)
        {
            bool result = false;

            try
            {
                int lsize = sizeof(long);
                byte[] memBuffer = new byte[10 * 1024 * 1024];
                using (MemoryStream ms = new MemoryStream(memBuffer))
                using (BinaryReader br = new BinaryReader(ms))
                using (FileCollection fc = new FileCollection(_selectedInsertFromFilename))
                {

                    int gcCount = 0;
                    int logCount = 0;
                    int logimgCount = 0;
                    int geocacheimgCount = 0;
                    int wptCount = 0;
                    int usrwptCount = 0;

                    Hashtable htInsertedGeocaches = new Hashtable();
                    Hashtable htInsertedLogs = new Hashtable();

                    XmlDocument doc = new XmlDocument();
                    doc.Load(fc.DatabaseInfoFilename);
                    XmlElement root = doc.DocumentElement;
                    gcCount = int.Parse(root.SelectSingleNode("GeocacheCount").InnerText);
                    logCount = int.Parse(root.SelectSingleNode("LogCount").InnerText);
                    logimgCount = int.Parse(root.SelectSingleNode("LogImagesCount").InnerText);
                    wptCount = int.Parse(root.SelectSingleNode("WaypointCount").InnerText);
                    usrwptCount = int.Parse(root.SelectSingleNode("UserWaypointCount").InnerText);
                    if (root.SelectSingleNode("GeocacheImagesCount") != null)
                    {
                        geocacheimgCount = int.Parse(root.SelectSingleNode("GeocacheImagesCount").InnerText);
                    }

                    DateTime nextUpdateTime = DateTime.MinValue;
                    RecordInfo ri = new RecordInfo();
                    using (Utils.ProgressBlock fixscr = new Utils.ProgressBlock(this, STR_LOADING, STR_LOADINGDATA, 1, 0))
                    {
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_LOADING, STR_LOADINGGEOCACHES, gcCount, 0))
                        {
                            int index = 0;

                            FileStream fs = fc._fsGeocaches;
                            fs.Position = 0;
                            long eof = fs.Length;
                            while (fs.Position < eof)
                            {
                                ri.Offset = fs.Position;
                                fs.Read(memBuffer, 0, lsize + 1);
                                ms.Position = 0;
                                ri.Length = br.ReadInt64();
                                if (memBuffer[lsize] == 0)
                                {
                                    //free
                                    //ignore
                                    fs.Position = ri.Offset + ri.Length;
                                }
                                else if (memBuffer[lsize] == 2)
                                {
                                    //read
                                    fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                    ms.Position = 0;
                                    ri.ID = br.ReadString().Substring(2);
                                    bool newGeocache;
                                    Framework.Data.Geocache gc = Utils.DataAccess.GetGeocache(Core.Geocaches, ri.ID);
                                    if (gc == null)
                                    {
                                        gc = new Framework.Data.Geocache();
                                        htInsertedGeocaches.Add(ri.ID, gc);
                                        newGeocache = true;
                                    }
                                    else
                                    {
                                        if (overwrite || htInsertedGeocaches[ri.ID] != null)
                                        {
                                            newGeocache = false;
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    gc.BeginUpdate();
                                    try
                                    {
                                        gc.Code = ri.ID;
                                        gc.ShortDescription = br.ReadString();
                                        gc.ShortDescriptionInHtml = br.ReadBoolean();
                                        gc.LongDescription = br.ReadString();
                                        gc.LongDescriptionInHtml = br.ReadBoolean();
                                    }
                                    catch
                                    {
                                    }
                                    gc.EndUpdate();
                                    if (newGeocache)
                                    {
                                        Core.Geocaches.Add(gc);
                                    }
                                }
                                else
                                {
                                    //read

                                    fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                    ms.Position = 0;
                                    ri.ID = br.ReadString();

                                    bool newGeocache;
                                    Framework.Data.Geocache gc = Utils.DataAccess.GetGeocache(Core.Geocaches, ri.ID);
                                    if (gc == null)
                                    {
                                        gc = new Framework.Data.Geocache();
                                        htInsertedGeocaches.Add(ri.ID, gc);
                                        newGeocache = true;
                                    }
                                    else
                                    {
                                        if (overwrite || htInsertedGeocaches[ri.ID] != null)
                                        {
                                            newGeocache = false;
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    gc.BeginUpdate();
                                    try
                                    {
                                        gc.Code = ri.ID;
                                        gc.Archived = br.ReadBoolean();
                                        gc.AttributeIds = ReadIntegerArray(br);
                                        gc.Available = br.ReadBoolean();
                                        gc.City = br.ReadString();
                                        gc.Container = Utils.DataAccess.GetGeocacheContainer(Core.GeocacheContainers, br.ReadInt32());
                                        gc.CustomCoords = 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();
                                        gc.GeocacheType = Utils.DataAccess.GetGeocacheType(Core.GeocacheTypes, br.ReadInt32());
                                        gc.ID = br.ReadString();
                                        gc.Lat = br.ReadDouble();
                                        gc.Lon = br.ReadDouble();
                                        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.PersonaleNote = br.ReadString();
                                        gc.PlacedBy = br.ReadString();
                                        gc.PublishedTime = DateTime.Parse(br.ReadString());
                                        gc.State = br.ReadString();
                                        gc.Terrain = br.ReadDouble();
                                        gc.Title = br.ReadString();
                                        gc.Url = br.ReadString();
                                        gc.DataFromDate = DateTime.Parse(br.ReadString());
                                        gc.Locked = br.ReadBoolean();

                                        Calculus.SetDistanceAndAngleGeocacheFromLocation(gc, Core.CenterLocation);
                                    }
                                    catch
                                    {
                                    }
                                    gc.EndUpdate();

                                    if (newGeocache)
                                    {
                                        Core.Geocaches.Add(gc);
                                    }

                                    index++;
                                    if (DateTime.Now >= nextUpdateTime)
                                    {
                                        progress.UpdateProgress(STR_LOADING, STR_LOADINGGEOCACHES, gcCount, index);
                                        nextUpdateTime = DateTime.Now.AddSeconds(1);
                                    }
                                }
                            }
                        }

                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGLOGS, logCount, 0))
                        {
                            int index = 0;
                            nextUpdateTime = DateTime.MinValue;

                            FileStream fs = fc._fsLogs;
                            fs.Position = 0;
                            long eof = fs.Length;
                            while (fs.Position < eof)
                            {
                                ri.Offset = fs.Position;
                                fs.Read(memBuffer, 0, lsize + 1);
                                ms.Position = 0;
                                ri.Length = br.ReadInt64();
                                if (memBuffer[lsize] == 0)
                                {
                                    //free
                                    fs.Position = ri.Offset + ri.Length;
                                }
                                else if (memBuffer[lsize] == 2)
                                {
                                    //read
                                    fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                    ms.Position = 0;
                                    ri.ID = br.ReadString().Substring(2);
                                    fs.Position = ri.Offset + ri.Length;

                                    bool newLog;
                                    bool logComplete = true;
                                    Framework.Data.Log log = Utils.DataAccess.GetLog(Core.Logs, ri.ID);
                                    if (log == null)
                                    {
                                        newLog = true;
                                        log = htInsertedLogs[ri.ID] as Framework.Data.Log;
                                        if (log == null)
                                        {
                                            log = new Framework.Data.Log();
                                            htInsertedLogs.Add(ri.ID, log);
                                            logComplete = false;
                                        }
                                        else
                                        {
                                            logComplete = true;
                                        }
                                    }
                                    else
                                    {
                                        if (overwrite)
                                        {
                                            newLog = false;
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    log.BeginUpdate();
                                    try
                                    {
                                        log.ID = ri.ID;
                                        log.TBCode = br.ReadString();
                                        log.FinderId = br.ReadString();
                                        log.Text = br.ReadString();
                                        log.Encoded = br.ReadBoolean();
                                    }
                                    catch
                                    {
                                    }
                                    log.EndUpdate();
                                    if (newLog && logComplete && htInsertedLogs[ri.ID] != null)
                                    {
                                        if (htInsertedGeocaches[log.GeocacheCode ?? ""] != null || Utils.DataAccess.GetGeocache(Core.Geocaches, log.GeocacheCode ?? "") != null)
                                        {
                                            Core.Logs.Add(log);
                                        }
                                        htInsertedLogs.Remove(ri.ID);
                                    }
                                }
                                else
                                {
                                    //read
                                    fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                    ms.Position = 0;
                                    ri.ID = br.ReadString();

                                    bool newLog;
                                    bool logComplete = true;
                                    Framework.Data.Log log = Utils.DataAccess.GetLog(Core.Logs, ri.ID);
                                    if (log == null)
                                    {
                                        newLog = true;
                                        log = htInsertedLogs[ri.ID] as Framework.Data.Log;
                                        if (log == null)
                                        {
                                            log = new Framework.Data.Log();
                                            htInsertedLogs.Add(ri.ID, log);
                                            logComplete = false;
                                        }
                                        else
                                        {
                                            logComplete = true;
                                        }
                                    }
                                    else
                                    {
                                        if (overwrite)
                                        {
                                            newLog = false;
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    log.BeginUpdate();
                                    try
                                    {

                                        log.ID = ri.ID;
                                        log.DataFromDate = DateTime.Parse(br.ReadString());
                                        log.Date = DateTime.Parse(br.ReadString());
                                        log.Finder = br.ReadString();
                                        log.GeocacheCode = br.ReadString();
                                        log.ID = br.ReadString();
                                        log.LogType = Utils.DataAccess.GetLogType(Core.LogTypes, br.ReadInt32());
                                    }
                                    catch
                                    {
                                    }
                                    log.EndUpdate();

                                    if (newLog && logComplete && htInsertedLogs[ri.ID] != null)
                                    {
                                        //check if geocache is present
                                        if (htInsertedGeocaches[log.GeocacheCode ?? ""] != null || Utils.DataAccess.GetGeocache(Core.Geocaches, log.GeocacheCode ?? "") != null)
                                        {
                                            Core.Logs.Add(log);
                                        }
                                        htInsertedLogs.Remove(ri.ID);
                                    }

                                    index++;
                                    if (DateTime.Now >= nextUpdateTime)
                                    {
                                        progress.UpdateProgress(STR_LOADING, STR_LOADINGLOGS, logCount, index);
                                        nextUpdateTime = DateTime.Now.AddSeconds(1);
                                    }
                                }
                            }
                        }


                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGWAYPOINTS, wptCount, 0))
                        {
                            int index = 0;
                            int procStep = 0;

                            using (FileStream fs = File.Open(fc.WaypointsFilename, FileMode.OpenOrCreate, FileAccess.Read))
                            {
                                fs.Position = 0;
                                long eof = fs.Length;
                                while (fs.Position < eof)
                                {
                                    ri.Offset = fs.Position;
                                    fs.Read(memBuffer, 0, lsize + 1);
                                    ms.Position = 0;
                                    ri.Length = br.ReadInt64();
                                    if (memBuffer[lsize] == 0)
                                    {
                                        //free
                                        fs.Position = ri.Offset + ri.Length;
                                    }
                                    else
                                    {
                                        //read
                                        fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                        ms.Position = 0;
                                        ri.ID = br.ReadString();

                                        bool newWp;
                                        Framework.Data.Waypoint wp = Utils.DataAccess.GetWaypoint(Core.Waypoints, ri.ID);
                                        if (wp == null)
                                        {
                                            newWp = true;
                                            wp = new Framework.Data.Waypoint();
                                        }
                                        else
                                        {
                                            if (overwrite)
                                            {
                                                newWp = false;
                                            }
                                            else
                                            {
                                                continue;
                                            }
                                        }

                                        wp.BeginUpdate();
                                        try
                                        {
                                            wp.Code = ri.ID;
                                            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(Core.WaypointTypes, br.ReadInt32());
                                        }
                                        catch
                                        {
                                        }
                                        wp.EndUpdate();
                                        if (newWp)
                                        {
                                            if (Utils.DataAccess.GetGeocache(Core.Geocaches, wp.GeocacheCode ?? "") != null)
                                            {
                                                Core.Waypoints.Add(wp);
                                            }
                                        }

                                        index++;
                                        procStep++;
                                        if (procStep >= 1000)
                                        {
                                            progress.UpdateProgress(STR_LOADING, STR_LOADINGWAYPOINTS, wptCount, index);
                                            procStep = 0;
                                        }
                                    }
                                }
                            }
                        }

                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGLOGIMAGES, logimgCount, 0))
                        {
                            int index = 0;
                            int procStep = 0;

                            using (FileStream fs = File.Open(fc.LogImagesFilename, FileMode.OpenOrCreate, FileAccess.Read))
                            {
                                fs.Position = 0;
                                long eof = fs.Length;
                                while (fs.Position < eof)
                                {
                                    ri.Offset = fs.Position;
                                    fs.Read(memBuffer, 0, lsize + 1);
                                    ms.Position = 0;
                                    ri.Length = br.ReadInt64();
                                    if (memBuffer[lsize] == 0)
                                    {
                                        //free
                                        fs.Position = ri.Offset + ri.Length;
                                    }
                                    else
                                    {
                                        //read
                                        fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                        ms.Position = 0;
                                        ri.ID = br.ReadString();

                                        bool newWp;
                                        Framework.Data.LogImage li = Utils.DataAccess.GetLogImage(Core.LogImages, ri.ID);
                                        if (li == null)
                                        {
                                            newWp = true;
                                            li = new Framework.Data.LogImage();
                                        }
                                        else
                                        {
                                            if (overwrite)
                                            {
                                                newWp = false;
                                            }
                                            else
                                            {
                                                continue;
                                            }
                                        }

                                        li.BeginUpdate();
                                        try
                                        {
                                            li.ID = ri.ID;
                                            li.DataFromDate = DateTime.Parse(br.ReadString());
                                            li.LogID = br.ReadString();
                                            li.Name = br.ReadString();
                                            li.Url = br.ReadString();
                                        }
                                        catch
                                        {
                                        }
                                        li.EndUpdate();

                                        if (newWp)
                                        {
                                            if (Utils.DataAccess.GetLog(Core.Logs, li.LogID ?? "") != null)
                                            {
                                                Core.LogImages.Add(li);
                                            }
                                        }

                                        index++;
                                        procStep++;
                                        if (procStep >= 1000)
                                        {
                                            progress.UpdateProgress(STR_LOADING, STR_LOADINGLOGIMAGES, logimgCount, index);
                                            procStep = 0;
                                        }
                                    }
                                }
                            }
                        }

                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGGEOCACHEIMAGES, geocacheimgCount, 0))
                        {
                            int index = 0;
                            int procStep = 0;

                            using (FileStream fs = File.Open(fc.GeocacheImagesFilename, FileMode.OpenOrCreate, FileAccess.Read))
                            {
                                fs.Position = 0;
                                long eof = fs.Length;
                                while (fs.Position < eof)
                                {
                                    ri.Offset = fs.Position;
                                    fs.Read(memBuffer, 0, lsize + 1);
                                    ms.Position = 0;
                                    ri.Length = br.ReadInt64();
                                    if (memBuffer[lsize] == 0)
                                    {
                                        //free
                                        fs.Position = ri.Offset + ri.Length;
                                    }
                                    else
                                    {
                                        //read
                                        fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                        ms.Position = 0;
                                        ri.ID = br.ReadString();

                                        bool newWp;
                                        Framework.Data.GeocacheImage wp = Utils.DataAccess.GetGeocacheImage(Core.GeocacheImages, ri.ID);
                                        if (wp == null)
                                        {
                                            newWp = true;
                                            wp = new Framework.Data.GeocacheImage();
                                        }
                                        else
                                        {
                                            if (overwrite)
                                            {
                                                newWp = false;
                                            }
                                            else
                                            {
                                                continue;
                                            }
                                        }

                                        wp.BeginUpdate();
                                        try
                                        {
                                            wp.ID = ri.ID;
                                            wp.DataFromDate = DateTime.Parse(br.ReadString());
                                            wp.GeocacheCode = br.ReadString();
                                            wp.Description = br.ReadString();
                                            wp.Name = br.ReadString();
                                            wp.Url = br.ReadString();
                                            wp.MobileUrl = br.ReadString();
                                            wp.ThumbUrl = br.ReadString();
                                        }
                                        catch
                                        {
                                        }
                                        wp.EndUpdate();
                                        if (newWp)
                                        {
                                            if (Utils.DataAccess.GetGeocache(Core.Geocaches, wp.GeocacheCode ?? "") != null)
                                            {
                                                Core.GeocacheImages.Add(wp);
                                            }
                                        }

                                        index++;
                                        procStep++;
                                        if (procStep >= 1000)
                                        {
                                            progress.UpdateProgress(STR_LOADING, STR_LOADINGGEOCACHEIMAGES, geocacheimgCount, index);
                                            procStep = 0;
                                        }
                                    }
                                }
                            }
                        }

                        {
                            using (FileStream fs = File.Open(fc.UserWaypointsFilename, FileMode.OpenOrCreate, FileAccess.Read))
                            {
                                fs.Position = 0;
                                long eof = fs.Length;
                                while (fs.Position < eof)
                                {
                                    ri.Offset = fs.Position;
                                    fs.Read(memBuffer, 0, lsize + 1);
                                    ms.Position = 0;
                                    ri.Length = br.ReadInt64();
                                    if (memBuffer[lsize] == 0)
                                    {
                                        //free
                                        fs.Position = ri.Offset + ri.Length;
                                    }
                                    else
                                    {
                                        //read
                                        fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                        ms.Position = 0;
                                        ri.ID = br.ReadString();

                                        bool newWp;
                                        Framework.Data.UserWaypoint wp = Utils.DataAccess.GetUserWaypoint(Core.UserWaypoints, int.Parse(ri.ID));
                                        if (wp == null)
                                        {
                                            newWp = true;
                                            wp = new Framework.Data.UserWaypoint();
                                        }
                                        else
                                        {
                                            if (overwrite)
                                            {
                                                newWp = false;
                                            }
                                            else
                                            {
                                                continue;
                                            }
                                        }

                                        wp.BeginUpdate();
                                        try
                                        {
                                            wp.ID = int.Parse(ri.ID);
                                            wp.Description = br.ReadString();
                                            wp.GeocacheCode = br.ReadString();
                                            wp.Lat = br.ReadDouble();
                                            wp.Lon = br.ReadDouble();
                                            wp.Date = DateTime.Parse(br.ReadString());
                                        }
                                        catch
                                        {
                                        }
                                        if (newWp)
                                        {
                                            if (Utils.DataAccess.GetGeocache(Core.Geocaches, wp.GeocacheCode ?? "") != null)
                                            {
                                                Core.UserWaypoints.Add(wp);
                                            }
                                        }

                                        wp.EndUpdate();
                                    }
                                }
                            }
                        }
                    }
                }
                result = true;
            }
            catch
            {
            }
            return result;
        }
    public static bool Run(Plugin plugin, ICore core)
    {
        string baseSite="http://xylanthrop.de/";
        string promptValue = MyURLPrompt.ShowDialog(baseSite,"2 Select a count(r)y to update the archived caches:", "Update Archived Caches from xylanthrop.de");
//        System.Windows.Forms.MessageBox.Show("promptValue: "+promptValue);
        if (promptValue!="") {
            //get page
            using (System.Net.WebClient wc = new System.Net.WebClient()) {
                string html = wc.DownloadString(baseSite+promptValue);
                int prog;
                int numgc=0;
                int updc=0;
                int foundc=0;
                int nonarc=0;//counter for caches "not" archived
                //parse GC-Codes from links
                Regex rgc = new Regex(@"<waypoint>(GC[A-Z0-9]*)<.*?<archived>([^<]*)<",RegexOptions.Singleline);
                MatchCollection mc = rgc.Matches(html);
                StringBuilder gcs = new StringBuilder();
                
                prog=0;
                using (ProgressBlock progress = new ProgressBlock(plugin,
                        "Retrieving GC-Codes", "", mc.Count, 0))
                {
                    foreach (Match m in mc) {
                        if (m.Groups[2].Value=="archived") {
                            gcs.Append(m.Groups[1].Value);
                            gcs.Append(" ");
                        } else {
                            nonarc++;
                        }
                        prog++;
                        if (prog % 10 == 0) {
                            progress.UpdateProgress("Retrieving GC-Codes", "", mc.Count, prog);
                        }

                    }
                    numgc=prog;
                }
                
                if (numgc>0) {
                    string gcstr=gcs.ToString();//searchable string of gc-codes
                    prog=0;
                    core.Geocaches.BeginUpdate();
                    
                    using (ProgressBlock progress = new ProgressBlock(plugin,
                        "Updating Caches", "", core.Geocaches.Count, 0))
                    {                                
                        foreach (Geocache gc in core.Geocaches)
                        {
                            if (gc.Code!="") {
                                if (gcstr.IndexOf(gc.Code+" ")>=0) {
                                    foundc++;
                                    if (!gc.Archived) {
                                        updc++;
                                        gc.Archived=true;//Set Cache to Archived state
                                        gc.Available=false;
                                    }
                                }
                            }
                            prog++;
                            if (prog % 100 == 0) {progress.UpdateProgress("Updating Caches", String.Format("Found: {0}",updc), core.Geocaches.Count, prog);}
                        }
                    }
                    core.Geocaches.EndUpdate();
                }
                System.Windows.Forms.MessageBox.Show(
                    "Update completed:\r"+
                    "Source URL: "+promptValue+"\r"+
                    String.Format("#Caches on page: {0}\r",numgc)+
                    String.Format("#Caches found in DB: {0}\r",foundc)+
                    String.Format("#Caches updated: {0}\r",updc)+
                    String.Format("#Caches non archived in src: {0}",nonarc));
                //System.Windows.Forms.MessageBox.Show("Val: "+html);
            }
        }
        //System.Windows.Forms.MessageBox.Show("Val: "+promptValue);
        return true;
    }
Exemplo n.º 11
0
        public bool RepairV1()
        {
            bool result = true;

            if (File.Exists(_fileCollection.DatabaseInfoFilename))
            {
                int lsize = sizeof(long);
                byte[] memBuffer = new byte[10 * 1024 * 1024];
                using (MemoryStream ms = new MemoryStream(memBuffer))
                using (BinaryReader br = new BinaryReader(ms))
                {

                    int gcCount = 0;
                    int logCount = 0;
                    int logimgCount = 0;
                    int wptCount = 0;
                    int usrwptCount = 0;

                    XmlDocument doc = new XmlDocument();
                    doc.Load(_fileCollection.DatabaseInfoFilename);
                    XmlElement root = doc.DocumentElement;
                    gcCount = int.Parse(root.SelectSingleNode("GeocacheCount").InnerText);
                    logCount = int.Parse(root.SelectSingleNode("LogCount").InnerText);
                    logimgCount = int.Parse(root.SelectSingleNode("LogImagesCount").InnerText);
                    wptCount = int.Parse(root.SelectSingleNode("WaypointCount").InnerText);
                    usrwptCount = int.Parse(root.SelectSingleNode("UserWaypointCount").InnerText);

                    DateTime nextUpdateTime = DateTime.MinValue;
                    using (Utils.ProgressBlock fixscr = new Utils.ProgressBlock(this, STR_LOADING, STR_LOADINGDATA, 1, 0))
                    {
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_LOADING, STR_LOADINGGEOCACHES, gcCount, 0))
                        {
                            int index = 0;

                            FileStream fs = _fileCollection._fsGeocaches;
                            fs.Position = 0;
                            long eof = fs.Length;
                            long lastOKPosition = 0;
                            RecordInfo ri = new RecordInfo();
                            try
                            {
                                while (fs.Position < eof)
                                {
                                    lastOKPosition = fs.Position;
                                    ri.Offset = fs.Position;
                                    fs.Read(memBuffer, 0, lsize + 1);
                                    ms.Position = 0;
                                    ri.Length = br.ReadInt64();
                                    if (memBuffer[lsize] == 0)
                                    {
                                        //free
                                        ri.FreeSlot = true;
                                        ri.ID = string.Concat("_", ri.Offset.ToString());
                                        fs.Position = ri.Offset + ri.Length;
                                    }
                                    else if (memBuffer[lsize] == 2)
                                    {
                                        ri.FreeSlot = false;
                                        fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                        ms.Position = 0;
                                        ri.ID = br.ReadString();
                                        br.ReadString();
                                        br.ReadBoolean();
                                        br.ReadString();
                                        br.ReadBoolean();
                                    }
                                    else
                                    {
                                        //read
                                        ri.FreeSlot = false;
                                        Framework.Data.Geocache gc = new Framework.Data.Geocache();

                                        fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                        ms.Position = 0;
                                        gc.Code = br.ReadString();
                                        ri.ID = gc.Code;

                                        gc.Archived = br.ReadBoolean();
                                        gc.AttributeIds = ReadIntegerArray(br);
                                        gc.Available = br.ReadBoolean();
                                        gc.City = br.ReadString();
                                        gc.Container = Utils.DataAccess.GetGeocacheContainer(Core.GeocacheContainers, br.ReadInt32());
                                        gc.CustomCoords = 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();
                                        gc.GeocacheType = Utils.DataAccess.GetGeocacheType(Core.GeocacheTypes, br.ReadInt32());
                                        gc.ID = br.ReadString();
                                        gc.Lat = br.ReadDouble();
                                        gc.Lon = br.ReadDouble();
                                        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.PersonaleNote = br.ReadString();
                                        gc.PlacedBy = br.ReadString();
                                        gc.PublishedTime = DateTime.Parse(br.ReadString());
                                        gc.State = br.ReadString();
                                        gc.Terrain = br.ReadDouble();
                                        gc.Title = br.ReadString();
                                        gc.Url = br.ReadString();
                                        gc.DataFromDate = DateTime.Parse(br.ReadString());
                                        gc.Locked = br.ReadBoolean();

                                        gc.Saved = true;
                                        gc.IsDataChanged = false;

                                        index++;
                                        if (DateTime.Now >= nextUpdateTime)
                                        {
                                            progress.UpdateProgress(STR_LOADING, STR_LOADINGGEOCACHES, gcCount, index);
                                            nextUpdateTime = DateTime.Now.AddSeconds(1);
                                        }
                                    }

                                    checkUniqueID(ri, fs);
                                }
                            }
                            catch
                            {
                                //error in file after lastOKPosition
                                fs.SetLength(lastOKPosition);
                            }
                        }

                        _uniqueCheckList.Clear();
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGLOGS, logCount, 0))
                        {
                            int index = 0;
                            nextUpdateTime = DateTime.MinValue;

                            FileStream fs = _fileCollection._fsLogs;
                            fs.Position = 0;
                            long lastOKPosition = 0;
                            long eof = fs.Length;
                            RecordInfo ri = new RecordInfo();
                            try
                            {
                                while (fs.Position < eof)
                                {
                                    lastOKPosition = fs.Position;
                                    ri.Offset = fs.Position;
                                    fs.Read(memBuffer, 0, lsize + 1);
                                    ms.Position = 0;
                                    ri.Length = br.ReadInt64();
                                    if (memBuffer[lsize] == 0)
                                    {
                                        //free
                                        ri.FreeSlot = true;
                                        ri.ID = string.Concat("_", ri.Offset.ToString());
                                        fs.Position = ri.Offset + ri.Length;
                                    }
                                    else if (memBuffer[lsize] == 2)
                                    {
                                        ri.FreeSlot = false;
                                        fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                        ms.Position = 0;
                                        ri.ID = br.ReadString();
                                        br.ReadString();
                                        br.ReadString();
                                        br.ReadString();
                                        br.ReadBoolean();
                                    }
                                    else
                                    {
                                        //read
                                        ri.FreeSlot = false;
                                        Framework.Data.Log log = new Framework.Data.Log();

                                        fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                        ms.Position = 0;
                                        log.ID = br.ReadString();
                                        ri.ID = log.ID;

                                        log.DataFromDate = DateTime.Parse(br.ReadString());
                                        log.Date = DateTime.Parse(br.ReadString());
                                        log.Finder = br.ReadString();
                                        log.GeocacheCode = br.ReadString();
                                        log.ID = br.ReadString();
                                        log.LogType = Utils.DataAccess.GetLogType(Core.LogTypes, br.ReadInt32());

                                        log.Saved = true;
                                        log.IsDataChanged = false;

                                        index++;
                                        if (DateTime.Now >= nextUpdateTime)
                                        {
                                            progress.UpdateProgress(STR_LOADING, STR_LOADINGLOGS, logCount, index);
                                            nextUpdateTime = DateTime.Now.AddSeconds(1);
                                        }
                                    }
                                    checkUniqueID(ri, fs);
                                }
                            }
                            catch
                            {
                                //error in file after lastOKPosition
                                fs.SetLength(lastOKPosition);
                            }
                        }

                        _uniqueCheckList.Clear();
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGWAYPOINTS, wptCount, 0))
                        {
                            int index = 0;
                            int procStep = 0;

                            using (FileStream fs = File.Open(_fileCollection.WaypointsFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                            {
                                fs.Position = 0;
                                long eof = fs.Length;
                                long lastOKPosition = 0;
                                RecordInfo ri = new RecordInfo();
                                try
                                {
                                    while (fs.Position < eof)
                                    {
                                        lastOKPosition = fs.Position;
                                        ri.Offset = fs.Position;
                                        fs.Read(memBuffer, 0, lsize + 1);
                                        ms.Position = 0;
                                        ri.Length = br.ReadInt64();
                                        if (memBuffer[lsize] == 0)
                                        {
                                            //free
                                            ri.FreeSlot = true;
                                            ri.ID = string.Concat("_", ri.Offset.ToString());
                                            fs.Position = ri.Offset + ri.Length;
                                        }
                                        else
                                        {
                                            //read
                                            ri.FreeSlot = false;
                                            Framework.Data.Waypoint wp = new Framework.Data.Waypoint();

                                            fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                            ms.Position = 0;
                                            wp.Code = br.ReadString();
                                            ri.ID = wp.Code;

                                            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(Core.WaypointTypes, br.ReadInt32());

                                            wp.Saved = true;
                                            wp.IsDataChanged = false;

                                            index++;
                                            procStep++;
                                            if (procStep >= 1000)
                                            {
                                                progress.UpdateProgress(STR_LOADING, STR_LOADINGWAYPOINTS, wptCount, index);
                                                procStep = 0;
                                            }
                                        }
                                        checkUniqueID(ri, fs);
                                    }
                                }
                                catch
                                {
                                    //error in file after lastOKPosition
                                    fs.SetLength(lastOKPosition);
                                }
                            }
                        }

                        _uniqueCheckList.Clear();
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_LOADING, STR_LOADINGLOGIMAGES, logimgCount, 0))
                        {
                            int index = 0;
                            int procStep = 0;

                            using (FileStream fs = File.Open(_fileCollection.LogImagesFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                            {
                                fs.Position = 0;
                                long eof = fs.Length;
                                long lastOKPosition = 0;
                                RecordInfo ri = new RecordInfo();
                                try
                                {
                                    while (fs.Position < eof)
                                    {
                                        lastOKPosition = fs.Position;
                                        ri.Offset = fs.Position;
                                        fs.Read(memBuffer, 0, lsize + 1);
                                        ms.Position = 0;
                                        ri.Length = br.ReadInt64();
                                        if (memBuffer[lsize] == 0)
                                        {
                                            //free
                                            ri.FreeSlot = true;
                                            ri.ID = string.Concat("_", ri.Offset.ToString());
                                            fs.Position = ri.Offset + ri.Length;
                                        }
                                        else
                                        {
                                            //read
                                            ri.FreeSlot = false;
                                            Framework.Data.LogImage li = new Framework.Data.LogImage();

                                            fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                            ms.Position = 0;
                                            li.ID = br.ReadString();
                                            ri.ID = li.ID;

                                            li.DataFromDate = DateTime.Parse(br.ReadString());
                                            li.LogID = br.ReadString();
                                            li.Name = br.ReadString();
                                            li.Url = br.ReadString();

                                            li.Saved = true;
                                            li.IsDataChanged = false;

                                            index++;
                                            procStep++;
                                            if (procStep >= 1000)
                                            {
                                                progress.UpdateProgress(STR_LOADING, STR_LOADINGLOGIMAGES, logimgCount, index);
                                                procStep = 0;
                                            }
                                        }
                                        checkUniqueID(ri, fs);
                                    }
                                }
                                catch
                                {
                                    //error in file after lastOKPosition
                                    fs.SetLength(lastOKPosition);
                                }
                            }
                        }

                        {
                            int index = 0;
                            _uniqueCheckList.Clear();
                            using (FileStream fs = File.Open(_fileCollection.UserWaypointsFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                            {
                                fs.Position = 0;
                                long eof = fs.Length;
                                long lastOKPosition = 0;
                                RecordInfo ri = new RecordInfo();
                                try
                                {
                                    while (fs.Position < eof)
                                    {
                                        lastOKPosition = fs.Position;
                                        ri.Offset = fs.Position;
                                        fs.Read(memBuffer, 0, lsize + 1);
                                        ms.Position = 0;
                                        ri.Length = br.ReadInt64();
                                        if (memBuffer[lsize] == 0)
                                        {
                                            //free
                                            ri.FreeSlot = true;
                                            ri.ID = string.Concat("_", ri.Offset.ToString());
                                            fs.Position = ri.Offset + ri.Length;
                                        }
                                        else
                                        {
                                            //read
                                            ri.FreeSlot = false;
                                            Framework.Data.UserWaypoint wp = new Framework.Data.UserWaypoint();

                                            fs.Read(memBuffer, 0, (int)(ri.Length - lsize - 1));
                                            ms.Position = 0;
                                            ri.ID = br.ReadString();
                                            wp.ID = int.Parse(ri.ID);

                                            wp.Description = br.ReadString();
                                            wp.GeocacheCode = br.ReadString();
                                            wp.Lat = br.ReadDouble();
                                            wp.Lon = br.ReadDouble();
                                            wp.Date = DateTime.Parse(br.ReadString());

                                            wp.Saved = true;
                                            wp.IsDataChanged = false;

                                            index++;
                                        }
                                        checkUniqueID(ri, fs);
                                    }
                                }
                                catch
                                {
                                    //error in file after lastOKPosition
                                    fs.SetLength(lastOKPosition);
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }
Exemplo n.º 12
0
    //********************************************************************************************
    //
    // Main 
    //
    //********************************************************************************************
    public static bool Run(Plugin plugin, ICore core)
    {
     List<Framework.Data.Geocache> gcList = null;
     List<Framework.Data.Waypoint> wpList = null;

     gcList = Utils.DataAccess.GetSelectedGeocaches(core.Geocaches);
     if (gcList.Count==0) {
       System.Windows.Forms.MessageBox.Show(Utils.LanguageSupport.Instance.GetTranslation("no geocache selected for export"));
       return true;
     }
     
     System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();
        
     dlg.FileName = "Traditional.csv";
     //dlg.OverwritePrompt=false;
     dlg.Filter = "*.csv|*.csv";
    
     //Select File
     if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
     {
       
        csvFile = dlg.FileName; 

        using (Utils.ProgressBlock progress = new Utils.ProgressBlock(plugin,
            STR_EXPORTINGCSV, STR_CREATINGFILE, gcList.Count, 0))
        {
            sd = new Dictionary<string, System.IO.StreamWriter>();
            { 
             int block = 0;
             int index = 0;
             //todo: clear all csv-files in path?
             
             //Iterate selected caches
             foreach (Framework.Data.Geocache gc in gcList)
             {
              //cache name made up of Name (others might prefer gc.Code)
              String name = ProcessName(gc.Name,INT_MAXNAMELEN);
              
              //1st part of description: GC-Code + basic cache info
              String desc = gc.Code + " "+
                     gc.GeocacheType.Name.Substring(0,2)+
                     "D" + gc.Difficulty.ToString("0.#").Replace(",",".").Replace(".5","5") + 
                     "T"+ gc.Terrain.ToString("0.#").Replace(",",".").Replace(".5","5") + 
                     gc.Container.Name.Substring(0,2)+" ";
              
              //2nd part of description, put hints, notes, personalnote as limits allow
              desc = desc + ProcessDescription(gc.EncodedHints+" "+
                                               gc.Notes+" "+
                                               gc.PersonaleNote,INT_MAXDESCLEN-desc.Length);
                                         //"PersonaleNote" is from the docs
              String lon=FmtCsvLatLon(gc.Lon);
              String lat=FmtCsvLatLon(gc.Lat);
              //use custom lat/lon if defined
              if (gc.CustomLat != null && gc.CustomLon != null) {
                lon=FmtCsvLatLon((double)gc.CustomLon);//double? -> double
                lat=FmtCsvLatLon((double)gc.CustomLat);
              }
              //write to CSV (file selected by gc type)
              CacheCsv(gc).WriteLine(lon + "," + lat + ",\"" + name + "\",\"" + desc + "\"");
              
              //Iterate all waypoints of cache
              wpList = Utils.DataAccess.GetWaypointsFromGeocache(core.Waypoints,gc.Code);
              foreach (Framework.Data.Waypoint wp in wpList)
              { //only export waypoints with coords
                if (wp.Lat != null && wp.Lon != null) {
                  //Make Wpt name of Cachename + # + "wpt-ID 2-letter prefix"
                  //others may prefer simply wp.Code
                  String wpname = ProcessName(gc.Name,INT_MAXNAMELEN-3)+"#"+wp.Code.Substring(0,2);
              
                  String wpdesc = wp.Code + " ";
                  //depending on source the "real" name of the wpt sometimes is either in "Name" or "Description"
                  String wpd= wp.Name;
                  if (wpd == wp.Code) {//use description if name only holds the wpcode
                    wpd=wp.Description;
                  }
                  //POI description = name + comment
                  wpdesc = wpdesc + ProcessDescription(wpd+": "+
                                                   wp.Comment,INT_MAXDESCLEN-wpdesc.Length);
                  String wplon=FmtCsvLatLon((double)wp.Lon);
                  String wplat=FmtCsvLatLon((double)wp.Lat);
                  //wpts have no custom lat/lon
              
                  WptCsv(gc,wp).WriteLine(wplon + "," + wplat + ",\"" + wpname + "\",\"" + wpdesc + "\"");
                }
              }              
              block++;
              index++;
              if (block > 5)
              {
               block = 0;               
               progress.UpdateProgress(STR_EXPORTINGCSV, STR_CREATINGFILE, gcList.Count, index);
              }
             }
            }
            foreach (var kv in sd) //close csv streams
            {
              kv.Value.Close();
            }
            sd = null;
        }
     }

     return true;
    }
Exemplo n.º 13
0
        public bool Save(FileStream fileStream, bool forceFullData)
        {
            if (fileStream == null) return false;

            bool result = true;
            byte isFree = RECORD_EMPTY;
            //todo
            //note: delete index file or create one? for now just delete
            try
            {
                byte[] memBuffer = new byte[10 * 1024 * 1024];
                using (Utils.ProgressBlock fixpr = new Utils.ProgressBlock(this, STR_SAVING, STR_SAVINGDATA, 1, 0))
                using (MemoryStream ms = new MemoryStream(memBuffer))
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    string fn = string.Concat(fileStream.Name, ".gsx");
                    if (File.Exists(fn))
                    {
                        File.Delete(fn);
                    }

                    //write header
                    if (fileStream.Length == 0)
                    {
                        BinaryWriter fbw = new BinaryWriter(fileStream);
                        //create meta data
                        fileStream.SetLength(DATABASE_CONTENT_OFFSET);
                        fileStream.Position = DATABASE_META_VERSION_POS;
                        long v = 1;
                        fbw.Write(v);
                        fileStream.Position = DATABASE_META_ACTIVEGEOCACHE_POS;
                        fbw.Write("");
                    }


                    //**********************************************
                    //          GEOCACHES
                    //**********************************************

                    //delete geocaches that are not in the list anymore.
                    List<RecordInfo> deletedRecords = (from RecordInfo ri in _geocachesInDB.Values where Core.Geocaches.GetGeocache(ri.ID) == null select ri).ToList();
                    foreach (RecordInfo ri in deletedRecords)
                    {
                        //scratch file to mark it as free
                        fileStream.Position = ri.Offset + RECORD_POS_FIELDTYPE;
                        fileStream.WriteByte(isFree);

                        //mark current record as free
                        _emptyRecords.Add(ri);
                        _emptyRecordsSorted = false;
                        _geocachesInDB.Remove(ri.ID);
                    }

                    List<Framework.Data.Geocache> gclist = (from Framework.Data.Geocache wp in Core.Geocaches
                                                            where !wp.Saved
                                                            select wp).ToList();
                    if (gclist.Count > 0)
                    {
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_SAVING, STR_SAVINGGEOCACHES, gclist.Count, 0))
                        {
                            int index = 0;
                            int procStep = 0;
                            foreach (Framework.Data.Geocache gc in gclist)
                            {
                                writeGeocacheData(gc, ms, bw);

                                RecordInfo ri = _geocachesInDB[gc.Code] as RecordInfo;
                                if (forceFullData || gc.FullDataLoaded || ri == null)
                                {
                                    ms.Position = 3000;
                                    bw.Write(gc.LongDescriptionInHtml); //3000
                                    bw.Write(gc.ShortDescriptionInHtml); //3001
                                    bw.Write(gc.ShortDescription ?? ""); //3002
                                    bw.Write(gc.LongDescription ?? "");

                                    //check length
                                    if (ri == null || ri.Length < ms.Position)
                                    {
                                        if (ri != null)
                                        {
                                            //scratch file to mark it as free
                                            fileStream.Position = ri.Offset + RECORD_POS_FIELDTYPE;
                                            fileStream.WriteByte(isFree);

                                            //mark current record as free
                                            _emptyRecords.Add(ri);
                                            _emptyRecordsSorted = false;
                                            _geocachesInDB.Remove(ri.ID);
                                        }
                                        ri = RequestGeocacheRecord(fileStream, gc.Code, "", memBuffer, ms.Position, 500);
                                        _geocachesInDB.Add(gc.Code, ri);
                                    }
                                    else
                                    {
                                        //still fits
                                        fileStream.Position = ri.Offset + 150;
                                        fileStream.Write(memBuffer, 150, (int)ms.Position - 150);
                                    }
                                }
                                else
                                {
                                    //always fits
                                    //skip first 150
                                    fileStream.Position = ri.Offset + 150;
                                    fileStream.Write(memBuffer, 150, (int)ms.Position - 150);
                                }

                                gc.Saved = true;

                                index++;
                                procStep++;
                                if (procStep >= 1000)
                                {
                                    progress.UpdateProgress(STR_SAVING, STR_SAVINGGEOCACHES, gclist.Count, index);
                                    procStep = 0;
                                }
                            }
                        }
                    }

                    //**********************************************
                    //          LOGS
                    //**********************************************

                    //delete items that are not in the list anymore.
                    deletedRecords = (from RecordInfo ri in _logsInDB.Values where Core.Logs.GetLog(ri.ID) == null select ri).ToList();
                    foreach (RecordInfo ri in deletedRecords)
                    {
                        //scratch file to mark it as free
                        fileStream.Position = ri.Offset + RECORD_POS_FIELDTYPE;
                        fileStream.WriteByte(isFree);

                        //mark current record as free
                        _emptyRecords.Add(ri);
                        _emptyRecordsSorted = false;
                        _logsInDB.Remove(ri.ID);
                    }

                    List<Framework.Data.Log> lglist = (from Framework.Data.Log wp in Core.Logs
                                                       where !wp.Saved
                                                       select wp).ToList();
                    if (lglist.Count > 0)
                    {
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_SAVING, STR_SAVINGLOGS, lglist.Count, 0))
                        {
                            int index = 0;
                            int procStep = 0;
                            foreach (Framework.Data.Log l in lglist)
                            {
                                writeLogData(l, ms, bw);

                                RecordInfo ri = _logsInDB[l.ID] as RecordInfo;
                                if (forceFullData || l.FullDataLoaded || ri == null)
                                {
                                    ms.Position = 320;
                                    bw.Write(l.FinderId ?? "");
                                    ms.Position = 350;
                                    bw.Write(l.TBCode ?? "");
                                    ms.Position = 380;
                                    bw.Write(l.Text ?? "");

                                    //check length
                                    if (ri == null || ri.Length < ms.Position)
                                    {
                                        if (ri != null)
                                        {
                                            //scratch file to mark it as free
                                            fileStream.Position = ri.Offset + RECORD_POS_FIELDTYPE;
                                            fileStream.WriteByte(isFree);

                                            //mark current record as free
                                            _emptyRecords.Add(ri);
                                            _emptyRecordsSorted = false;
                                            _logsInDB.Remove(ri.ID);
                                        }
                                        ri = RequestLogRecord(fileStream, l.ID, l.GeocacheCode, memBuffer, ms.Position, 100);
                                        _logsInDB.Add(l.ID, ri);
                                    }
                                    else
                                    {
                                        //still fits
                                        fileStream.Position = ri.Offset + 150;
                                        fileStream.Write(memBuffer, 150, (int)ms.Position - 150);
                                    }
                                }
                                else
                                {
                                    //always fits
                                    //skip first 150
                                    fileStream.Position = ri.Offset + 150;
                                    fileStream.Write(memBuffer, 150, (int)ms.Position - 150);
                                }

                                l.Saved = true;

                                index++;
                                procStep++;
                                if (procStep >= 1000)
                                {
                                    progress.UpdateProgress(STR_SAVING, STR_SAVINGLOGS, lglist.Count, index);
                                    procStep = 0;
                                }
                            }
                        }
                    }

                    //**********************************************
                    //          WAYPOINTS
                    //**********************************************

                    //delete items that are not in the list anymore.
                    deletedRecords = (from RecordInfo ri in _wptsInDB.Values where Core.Waypoints.getWaypoint(ri.ID) == null select ri).ToList();
                    foreach (RecordInfo ri in deletedRecords)
                    {
                        //scratch file to mark it as free
                        fileStream.Position = ri.Offset + RECORD_POS_FIELDTYPE;
                        fileStream.WriteByte(isFree);

                        //mark current record as free
                        _emptyRecords.Add(ri);
                        _emptyRecordsSorted = false;
                        _wptsInDB.Remove(ri.ID);
                    }
                    List<Framework.Data.Waypoint> wptlist = (from Framework.Data.Waypoint wp in Core.Waypoints
                                                             where !wp.Saved
                                                             select wp).ToList();
                    if (wptlist.Count > 0)
                    {
                        int index = 0;
                        int procStep = 0;
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGWAYPOINTS, wptlist.Count, 0))
                        {
                            foreach (Framework.Data.Waypoint wp in wptlist)
                            {
                                writeWaypointData(wp, ms, bw);

                                RecordInfo ri = _wptsInDB[wp.Code] as RecordInfo;
                                //check length
                                if (ri == null || ri.Length < ms.Position)
                                {
                                    if (ri != null)
                                    {
                                        //scratch file to mark it as free
                                        fileStream.Position = ri.Offset + RECORD_POS_FIELDTYPE;
                                        fileStream.WriteByte(isFree);

                                        //mark current record as free
                                        _emptyRecords.Add(ri);
                                        _emptyRecordsSorted = false;
                                        _wptsInDB.Remove(ri.ID);
                                    }
                                    ri = RequestWaypointRecord(fileStream, wp.Code, wp.GeocacheCode, memBuffer, ms.Position, 10);
                                    _wptsInDB.Add(wp.Code, ri);
                                }
                                else
                                {
                                    //still fits
                                    fileStream.Position = ri.Offset + 150;
                                    fileStream.Write(memBuffer, 150, (int)ms.Position - 150);
                                }

                                wp.Saved = true;

                                index++;
                                procStep++;
                                if (procStep >= 1000)
                                {
                                    progress.UpdateProgress(STR_SAVING, STR_SAVINGLOGS, wptlist.Count, index);
                                    procStep = 0;
                                }
                            }
                        }
                    }

                    //**********************************************
                    //          LOGIMAGES
                    //**********************************************
                    //delete items that are not in the list anymore.
                    deletedRecords = (from RecordInfo ri in _logimgsInDB.Values where Core.LogImages.GetLogImage(ri.ID) == null select ri).ToList();
                    foreach (RecordInfo ri in deletedRecords)
                    {
                        //scratch file to mark it as free
                        fileStream.Position = ri.Offset + RECORD_POS_FIELDTYPE;
                        fileStream.WriteByte(isFree);

                        //mark current record as free
                        _emptyRecords.Add(ri);
                        _emptyRecordsSorted = false;
                        _logimgsInDB.Add(ri.ID, ri);
                    }

                    List<Framework.Data.LogImage> lgimglist = (from Framework.Data.LogImage wp in Core.LogImages
                                                               where !wp.Saved
                                                               select wp).ToList();
                    if (lgimglist.Count > 0)
                    {
                        int index = 0;
                        int procStep = 0;
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGLOGIMAGES, lgimglist.Count, 0))
                        {
                            foreach (Framework.Data.LogImage li in lgimglist)
                            {
                                writeLogImageData(li, ms, bw);

                                RecordInfo ri = _logimgsInDB[li.ID] as RecordInfo;
                                //check length
                                if (ri == null || ri.Length < ms.Position)
                                {
                                    if (ri != null)
                                    {
                                        //scratch file to mark it as free
                                        fileStream.Position = ri.Offset + RECORD_POS_FIELDTYPE;
                                        fileStream.WriteByte(isFree);

                                        //mark current record as free
                                        _emptyRecords.Add(ri);
                                        _emptyRecordsSorted = false;
                                        _logimgsInDB.Remove(ri.ID);
                                    }
                                    ri = RequestLogImageRecord(fileStream, li.ID, li.LogID, memBuffer, ms.Position, 10);
                                    _logimgsInDB.Add(li.ID, ri);
                                }
                                else
                                {
                                    //still fits
                                    fileStream.Position = ri.Offset + 150;
                                    fileStream.Write(memBuffer, 150, (int)ms.Position - 150);
                                }

                                li.Saved = true;

                                index++;
                                procStep++;
                                if (procStep >= 1000)
                                {
                                    progress.UpdateProgress(STR_SAVING, STR_SAVINGLOGIMAGES, lgimglist.Count, index);
                                    procStep = 0;
                                }
                            }
                        }
                    }

                    //**********************************************
                    //          GEOCACHEIMAGES
                    //**********************************************
                    //delete items that are not in the list anymore.
                    deletedRecords = (from RecordInfo ri in _geocacheimgsInDB.Values where Core.GeocacheImages.GetGeocacheImage(ri.ID) == null select ri).ToList();
                    foreach (RecordInfo ri in deletedRecords)
                    {
                        //scratch file to mark it as free
                        fileStream.Position = ri.Offset + RECORD_POS_FIELDTYPE;
                        fileStream.WriteByte(isFree);

                        //mark current record as free
                        _emptyRecords.Add(ri);
                        _emptyRecordsSorted = false;
                        _geocacheimgsInDB.Add(ri.ID, ri);
                    }

                    List<Framework.Data.GeocacheImage> gcimglist = (from Framework.Data.GeocacheImage wp in Core.GeocacheImages
                                                                    where !wp.Saved
                                                                    select wp).ToList();
                    if (gcimglist.Count > 0)
                    {
                        int index = 0;
                        int procStep = 0;
                        using (Utils.ProgressBlock progress = new ProgressBlock(this, STR_SAVING, STR_SAVINGGEOCACHEIMAGES, gcimglist.Count, 0))
                        {
                            foreach (Framework.Data.GeocacheImage li in gcimglist)
                            {
                                writeGeocacheImageData(li, ms, bw);

                                RecordInfo ri = _geocacheimgsInDB[li.ID] as RecordInfo;
                                //check length
                                if (ri == null || ri.Length < ms.Position)
                                {
                                    if (ri != null)
                                    {
                                        //scratch file to mark it as free
                                        fileStream.Position = ri.Offset + RECORD_POS_FIELDTYPE;
                                        fileStream.WriteByte(isFree);

                                        //mark current record as free
                                        _emptyRecords.Add(ri);
                                        _emptyRecordsSorted = false;
                                        _geocacheimgsInDB.Remove(ri.ID);
                                    }
                                    ri = RequestGeocacheImageRecord(fileStream, li.ID, li.GeocacheCode, memBuffer, ms.Position, 10);
                                    _geocacheimgsInDB.Add(li.ID, ri);
                                }
                                else
                                {
                                    //still fits
                                    fileStream.Position = ri.Offset + 150;
                                    fileStream.Write(memBuffer, 150, (int)ms.Position - 150);
                                }

                                li.Saved = true;

                                index++;
                                procStep++;
                                if (procStep >= 1000)
                                {
                                    progress.UpdateProgress(STR_SAVING, STR_SAVINGGEOCACHEIMAGES, gcimglist.Count, index);
                                    procStep = 0;
                                }
                            }
                        }
                    }

                    //**********************************************
                    //          USER WAYPOINTS
                    //**********************************************
                    //delete items that are not in the list anymore.
                    deletedRecords = (from RecordInfo ri in _usrwptsInDB.Values where Core.UserWaypoints.getWaypoint(int.Parse(ri.ID)) == null select ri).ToList();
                    foreach (RecordInfo ri in deletedRecords)
                    {
                        //scratch file to mark it as free
                        fileStream.Position = ri.Offset + RECORD_POS_FIELDTYPE;
                        fileStream.WriteByte(isFree);

                        //mark current record as free
                        _emptyRecords.Add(ri);
                        _emptyRecordsSorted = false;
                        _usrwptsInDB.Add(ri.ID, ri);
                    }

                    List<Framework.Data.UserWaypoint> usrwptlist = (from Framework.Data.UserWaypoint wp in Core.UserWaypoints
                                                                    where !wp.Saved
                                                                    select wp).ToList();
                    if (usrwptlist.Count > 0)
                    {
                        foreach (Framework.Data.UserWaypoint wp in usrwptlist)
                        {
                            writeUserWaypointData(wp, ms, bw);

                            RecordInfo ri = _usrwptsInDB[wp.ID] as RecordInfo;
                            //check length
                            if (ri == null || ri.Length < ms.Position)
                            {
                                if (ri != null)
                                {
                                    //scratch file to mark it as free
                                    fileStream.Position = ri.Offset + RECORD_POS_FIELDTYPE;
                                    fileStream.WriteByte(isFree);

                                    //mark current record as free
                                    _emptyRecords.Add(ri);
                                    _emptyRecordsSorted = false;
                                    _usrwptsInDB.Remove(ri.ID);
                                }
                                ri = RequestUserWaypointRecord(fileStream, wp.ID.ToString(), wp.GeocacheCode, memBuffer, ms.Position, 10);
                                _usrwptsInDB.Add(wp.ID, ri);
                            }
                            else
                            {
                                //still fits
                                fileStream.Position = ri.Offset + 150;
                                fileStream.Write(memBuffer, 150, (int)ms.Position - 150);
                            }

                            wp.Saved = true;
                        }
                    }
                }
            }
            catch
            {

            }
            return result;
        }
Exemplo n.º 14
0
 public override bool Backup()
 {
     bool result = false;
     try
     {
         //file.bak01, file.bak02... file.bakNN where NN is the latest
         string fn = string.Format("{0}.bak{1}", PluginSettings.Instance.ActiveDataFile, PluginSettings.Instance.BackupKeepMaxCount.ToString("00"));
         if (File.Exists(fn))
         {
             //ok, maximum reached
             //delete the oldest and rename the others
             fn = string.Format("{0}.bak{1}", PluginSettings.Instance.ActiveDataFile, 1.ToString("00"));
             if (File.Exists(fn))
             {
                 File.Delete(fn);
             }
             for (int i = 1; i < PluginSettings.Instance.BackupKeepMaxCount; i++)
             {
                 string fns = string.Format("{0}.bak{1}", PluginSettings.Instance.ActiveDataFile, (i + 1).ToString("00"));
                 string fnd = string.Format("{0}.bak{1}", PluginSettings.Instance.ActiveDataFile, i.ToString("00"));
                 if (File.Exists(fns))
                 {
                     File.Move(fns, fnd);
                 }
             }
             fn = string.Format("{0}.bak{1}", PluginSettings.Instance.ActiveDataFile, PluginSettings.Instance.BackupKeepMaxCount.ToString("00"));
         }
         else
         {
             //look for latest
             int i = 1;
             fn = string.Format("{0}.bak{1}", PluginSettings.Instance.ActiveDataFile, i.ToString("00"));
             while (File.Exists(fn))
             {
                 i++;
                 fn = string.Format("{0}.bak{1}", PluginSettings.Instance.ActiveDataFile, i.ToString("00"));
             }
         }
         DateTime nextUpdate = DateTime.Now.AddSeconds(1);
         using (Utils.ProgressBlock prog = new ProgressBlock(this, STR_BACKINGUPDATA, STR_BACKINGUPDATA, 100, 0))
         {
             using (System.IO.FileStream fs = File.OpenWrite(fn))
             {
                 int read;
                 byte[] buffer = new byte[10 * 1024 * 1024];
                 fs.SetLength(_fileStream.Length);
                 _fileStream.Position = 0;
                 while (_fileStream.Position < _fileStream.Length)
                 {
                     read = _fileStream.Read(buffer, 0, buffer.Length);
                     fs.Write(buffer, 0, read);
                     if (DateTime.Now >= nextUpdate)
                     {
                         prog.UpdateProgress(STR_BACKINGUPDATA, STR_BACKINGUPDATA, 100, (int)(100.0 * (double)_fileStream.Position / (double)_fileStream.Length));
                         nextUpdate = DateTime.Now.AddSeconds(1);
                     }
                 }
             }
             _fileStream.Position = 0;
             result = true;
         }
     }
     catch
     {
     }
     return result;
 }