Beispiel #1
0
 protected override void ImportMethod()
 {
     using (Utils.ProgressBlock fixpr = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTINGDATA, _filenames.Length, 0))
     {
         for (int fileindex = 0; fileindex < _filenames.Length; fileindex++)
         {
             List <Framework.Data.Geocache> res = ProcessWaymarkComGPXFile(_filenames[fileindex]);
             if (res != null && res.Count > 0)
             {
                 using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTINGGEOCACHES, res.Count, 0))
                 {
                     int index    = 0;
                     int procStep = 0;
                     foreach (Framework.Data.Geocache gc in res)
                     {
                         AddGeocache(gc, Framework.Data.Geocache.V1);
                         index++;
                         procStep++;
                         if (procStep >= 100)
                         {
                             progress.UpdateProgress(STR_IMPORTING, STR_IMPORTINGGEOCACHES, res.Count, index);
                             procStep = 0;
                         }
                     }
                 }
             }
             fixpr.UpdateProgress(STR_IMPORTING, STR_IMPORTINGDATA, _filenames.Length, fileindex + 1);
         }
     }
 }
Beispiel #2
0
        private void deleteSelectionThreadMethod()
        {
            try
            {
                DateTime dt = DateTime.Now.AddSeconds(2);
                using (Utils.ProgressBlock prog = new Utils.ProgressBlock(this, STR_DELETINGGEOCACHES, STR_DELETINGGEOCACHES, _gcList.Count, 0, true))
                {
                    int index = 0;
                    foreach (Framework.Data.Geocache gc in _gcList)
                    {
                        Utils.DataAccess.DeleteGeocache(Core, gc);

                        index++;
                        if (DateTime.Now >= dt)
                        {
                            if (!prog.UpdateProgress(STR_DELETINGGEOCACHES, STR_DELETINGGEOCACHES, _gcList.Count, index))
                            {
                                break;
                            }
                            dt = DateTime.Now.AddSeconds(2);
                        }
                    }
                }
            }
            catch
            {
            }
        }
Beispiel #3
0
        protected override void ImportMethod()
        {
            using (Utils.ProgressBlock blockprogress = new Utils.ProgressBlock(this, STR_IMPORTINGCACHES, STR_IMPORTINGCACHES, 1, 0))
            {
                try
                {
                    //first get a list of geocache codes
                    List<string> gcList = OKAPIService.GetGeocachesWithinRadius(SiteManager.Instance.ActiveSite, _centerLoc, _radiusKm, _filter);
                    using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTINGCACHES, STR_IMPORTINGCACHES, gcList.Count, 0, true))
                    {
                        int gcupdatecount = 1;
                        int max = gcList.Count;
                        while (gcList.Count > 0)
                        {
                            List<string> lcs = gcList.Take(gcupdatecount).ToList();
                            gcList.RemoveRange(0, lcs.Count);
                            List<OKAPIService.Geocache> caches = OKAPIService.GetGeocaches(SiteManager.Instance.ActiveSite, lcs);
                            Import.AddGeocaches(Core, caches);

                            if (!progress.UpdateProgress(STR_IMPORTINGCACHES, STR_IMPORTINGCACHES, max, max - gcList.Count))
                            {
                                break;
                            }
                        }

                    }
                }
                catch (Exception e)
                {
                    _errormessage = e.Message;
                }
            }
        }
Beispiel #4
0
        protected override void ImportMethod()
        {
            //for now, we just use the active site
            //howver, in the future it is better to automatically switcg according geocode prefix
            //at this moment, the user is responsible for selecting the geocaches and the active site
            try
            {
                //first get a list of geocache codes
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_UPDATINGGEOCACHES, STR_UPDATINGGEOCACHES, _gcList.Count, 0, true))
                {
                    int gcupdatecount = 1;
                    int max = _gcList.Count;
                    while (_gcList.Count > 0)
                    {
                        List<string> lcs = (from Framework.Data.Geocache g in _gcList select g.Code).Take(gcupdatecount).ToList();
                        _gcList.RemoveRange(0, lcs.Count);
                        List<OKAPIService.Geocache> caches = OKAPIService.GetGeocaches(SiteManager.Instance.ActiveSite, lcs);
                        Import.AddGeocaches(Core, caches);

                        if (!progress.UpdateProgress(STR_UPDATINGGEOCACHES, STR_UPDATINGGEOCACHES, max, max - _gcList.Count))
                        {
                            break;
                        }
                    }

                }
            }
            catch (Exception e)
            {
                _errormessage = e.Message;
            }
        }
Beispiel #5
0
        protected override void ImportMethod()
        {
            try
            {
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTINGCACHES, STR_IMPORTINGCACHES, _gcList.Count, 0, true))
                {
                    int gcupdatecount = 1;
                    int max = _gcList.Count;
                    while (_gcList.Count > 0)
                    {
                        List<string> lcs = _gcList.Take(gcupdatecount).ToList();
                        _gcList.RemoveRange(0, lcs.Count);
                        List<OKAPIService.Geocache> caches = OKAPIService.GetGeocaches(SiteManager.Instance.ActiveSite, lcs);
                        Import.AddGeocaches(Core, caches);

                        if (!progress.UpdateProgress(STR_IMPORTINGCACHES, STR_IMPORTINGCACHES, max, max - _gcList.Count))
                        {
                            break;
                        }
                    }

                }
            }
            catch (Exception e)
            {
                _errormessage = e.Message;
            }
        }
Beispiel #6
0
        protected override void ImportMethod()
        {
            try
            {
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTINGCACHES, STR_IMPORTINGCACHES, _gcList.Count, 0, true))
                {
                    int gcupdatecount = 1;
                    int max           = _gcList.Count;
                    while (_gcList.Count > 0)
                    {
                        List <string> lcs = _gcList.Take(gcupdatecount).ToList();
                        _gcList.RemoveRange(0, lcs.Count);
                        List <OKAPIService.Geocache> caches = OKAPIService.GetGeocaches(SiteManager.Instance.ActiveSite, lcs);
                        Import.AddGeocaches(Core, caches);

                        if (!progress.UpdateProgress(STR_IMPORTINGCACHES, STR_IMPORTINGCACHES, max, max - _gcList.Count))
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _errormessage = e.Message;
            }
        }
 private void searchInDescriptionThreadMethod()
 {
     using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_ACTIONTITLE, STR_ACTIONTEXT, _gcSearchList.Count, 0, true))
     {
         try
         {
             int block = 0;
             int index = 0;
             foreach (Framework.Data.Geocache wp in _gcSearchList)
             {
                 wp.Selected = (wp.ShortDescription.IndexOf(_txt, _scType) >= 0 || wp.LongDescription.IndexOf(_txt, _scType) >= 0);
                 block++;
                 index++;
                 if (block > 1000)
                 {
                     block = 0;
                     if (!progress.UpdateProgress(STR_ACTIONTITLE, STR_ACTIONTEXT, _gcSearchList.Count, index))
                     {
                         break;
                     }
                 }
             }
         }
         catch
         {
         }
         //signal finished
     }
 }
Beispiel #8
0
        private void performSelection()
        {
            CachesAlongRoute pin = (OwnerPlugin as CachesAlongRoute);

            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(pin, STR_SEARCHING, STR_PROCESSINGSTEP, _lat.Length, 0))
            {
                _gcAlongRoute = new List <Framework.Data.Geocache>();
                try
                {
                    int step = 0;
                    for (int i = 0; i < _lat.Length - 1; i += 2)
                    {
                        //process line
                        double minLat = Math.Min(_lat[i], _lat[i + 1]) - _difLat;
                        double maxLat = Math.Max(_lat[i], _lat[i + 1]) + _difLat;
                        double minLon = Math.Min(_lon[i], _lon[i + 1]) - _difLon;
                        double maxLon = Math.Max(_lon[i], _lon[i + 1]) + _difLon;

                        _gcAlongRoute.AddRange((from Framework.Data.Geocache wp in Core.Geocaches
                                                where !_gcAlongRoute.Contains(wp) && wp.Lat >= minLat && wp.Lat <= maxLat && wp.Lon >= minLon && wp.Lon <= maxLon
                                                select wp).ToList());

                        step++;
                        if (step > 50)
                        {
                            step = 0;
                            progress.UpdateProgress(STR_SEARCHING, STR_PROCESSINGSTEP, _lat.Length, i);
                        }
                    }
                }
                catch
                {
                }
            }
        }
Beispiel #9
0
        protected override void ImportMethod()
        {
            int max = _gcList.Count; //caches, waypoints, logs
            int index = 0;
            DateTime nextUpdate = DateTime.Now.AddSeconds(1);
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_ASSIGNCITY, STR_ASSIGNCITY, max, 0, true))
            {
                foreach (Framework.Data.Geocache gc in _gcList)
                {
                    if (index>0)
                    {
                        System.Threading.Thread.Sleep(1000); //OSM policy
                    }
                    gc.City = Utils.Geocoder.GetCityName(gc.Lat, gc.Lon);

                    index++;
                    if (DateTime.Now >= nextUpdate)
                    {
                        if (!progress.UpdateProgress(STR_ASSIGNCITY, STR_ASSIGNCITY, max, index))
                        {
                            break;
                        }
                    }
                }
            }
        }
Beispiel #10
0
 private void processMethod()
 {
     using (Utils.ProgressBlock progress = new Utils.ProgressBlock(_ownerPlugin, STR_IMPORTINGPOLY, STR_IMPORTINGFILE, _filenames.Length, 0))
     {
         int index = 0;
         try
         {
             foreach (string fn in _filenames)
             {
                 progress.UpdateProgress(STR_IMPORTINGPOLY, STR_IMPORTINGFILE, _filenames.Length, index);
                 if (fn.ToLower().EndsWith(".txt"))
                 {
                     if (!_ownerPlugin.processTextFile(_selectedAreaType, fn, _selectedParent))
                     {
                         break;
                     }
                 }
                 else if (fn.ToLower().EndsWith(".gpx"))
                 {
                     if (!_ownerPlugin.processGpxFile(_selectedAreaType, fn, _selectedParent))
                     {
                         break;
                     }
                 }
                 index++;
             }
         }
         catch
         {
         }
     }
     _actionReady.Set();
 }
Beispiel #11
0
        protected override void ImportMethod()
        {
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORT, STR_DOWNLOAD, 1, 0))
            {
                using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                using (System.Net.WebClient wc = new System.Net.WebClient())
                {
                    wc.DownloadFile("http://www.globalcaching.eu/service/cachedistance.aspx?country=Netherlands&prefix=GC", tmp.Path);

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

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

                }
            }
        }
Beispiel #12
0
        protected override void ImportMethod()
        {
            int      max        = _gcList.Count; //caches, waypoints, logs
            int      index      = 0;
            DateTime nextUpdate = DateTime.Now.AddSeconds(1);

            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_ASSIGNCITY, STR_ASSIGNCITY, max, 0, true))
            {
                foreach (Framework.Data.Geocache gc in _gcList)
                {
                    if (index > 0)
                    {
                        System.Threading.Thread.Sleep(1000); //OSM policy
                    }
                    gc.City = Utils.Geocoder.GetCityName(gc.Lat, gc.Lon);

                    index++;
                    if (DateTime.Now >= nextUpdate)
                    {
                        if (!progress.UpdateProgress(STR_ASSIGNCITY, STR_ASSIGNCITY, max, index))
                        {
                            break;
                        }
                    }
                }
            }
        }
Beispiel #13
0
        protected override void ImportMethod()
        {
            using (Utils.ProgressBlock blockprogress = new Utils.ProgressBlock(this, STR_IMPORTINGCACHES, STR_IMPORTINGCACHES, 1, 0))
            {
                try
                {
                    //first get a list of geocache codes
                    List <string> gcList = OKAPIService.GetGeocachesWithinRadius(SiteManager.Instance.ActiveSite, _centerLoc, _radiusKm, _filter);
                    using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTINGCACHES, STR_IMPORTINGCACHES, gcList.Count, 0, true))
                    {
                        int gcupdatecount = 1;
                        int max           = gcList.Count;
                        while (gcList.Count > 0)
                        {
                            List <string> lcs = gcList.Take(gcupdatecount).ToList();
                            gcList.RemoveRange(0, lcs.Count);
                            List <OKAPIService.Geocache> caches = OKAPIService.GetGeocaches(SiteManager.Instance.ActiveSite, lcs);
                            Import.AddGeocaches(Core, caches);

                            if (!progress.UpdateProgress(STR_IMPORTINGCACHES, STR_IMPORTINGCACHES, max, max - gcList.Count))
                            {
                                break;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _errormessage = e.Message;
                }
            }
        }
Beispiel #14
0
        protected override void ImportMethod()
        {
            //for now, we just use the active site
            //howver, in the future it is better to automatically switcg according geocode prefix
            //at this moment, the user is responsible for selecting the geocaches and the active site
            try
            {
                //first get a list of geocache codes
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_UPDATINGGEOCACHES, STR_UPDATINGGEOCACHES, _gcList.Count, 0, true))
                {
                    int gcupdatecount = 1;
                    int max           = _gcList.Count;
                    while (_gcList.Count > 0)
                    {
                        List <string> lcs = (from Framework.Data.Geocache g in _gcList select g.Code).Take(gcupdatecount).ToList();
                        _gcList.RemoveRange(0, lcs.Count);
                        List <OKAPIService.Geocache> caches = OKAPIService.GetGeocaches(SiteManager.Instance.ActiveSite, lcs);
                        Import.AddGeocaches(Core, caches);

                        if (!progress.UpdateProgress(STR_UPDATINGGEOCACHES, STR_UPDATINGGEOCACHES, max, max - _gcList.Count))
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _errormessage = e.Message;
            }
        }
        public override async Task ExecuteAsync(object parameter)
        {
            Core.ApplicationData.Instance.BeginActiviy();
            Core.Storage.Database db = Core.ApplicationData.Instance.ActiveDatabase;
            if (db != null)
            {
                using (Utils.DataUpdater upd = new Utils.DataUpdater(db))
                {
                    await Task.Run(() =>
                    {
                        Utils.ProgressBlock prog = null;
                        int max = Core.ApplicationData.Instance.MainWindow.GeocacheSelectionCount;
                        DateTime nextUpdate = DateTime.Now.AddSeconds(1);
                        if (_showProgress)
                        {
                            prog = new Utils.ProgressBlock("PerfomingAction", "PerfomingAction", max, 0, true);
                        }
                        try
                        {
                            int index = 0;
                            foreach (Core.Data.Geocache gc in db.GeocacheCollection)
                            {
                                if (gc.Selected)
                                {
                                    _geocacheAction(gc);

                                    if (prog != null)
                                    {
                                        index++;
                                        if (DateTime.Now >= nextUpdate)
                                        {
                                            if (!prog.Update("PerfomingAction", max, index))
                                            {
                                                break;
                                            }
                                            nextUpdate = DateTime.Now.AddSeconds(1);
                                        }
                                    }
                                }
                            }
                            if (prog != null)
                            {
                                prog.Dispose();
                                prog = null;
                            }
                        }
                        catch(Exception e)
                        {
                            Core.ApplicationData.Instance.Logger.AddLog(this, e);
                            if (prog!=null)
                            {
                                prog.Dispose();
                                prog = null;
                            }
                        }
                    });
                }
            };
            Core.ApplicationData.Instance.EndActiviy();
        }
 private void downloadShapefileThreadMethod()
 {
     try
     {
         //download zip file
         using (TemporaryFile tmpFile = new TemporaryFile(false))
         {
             using (Utils.ProgressBlock prog = new Utils.ProgressBlock(_plugin, STR_DOWNLOADINGSHAPEFILE, _downloadUrl, _zipFileSize, 0))
             {
                 byte[]         buffer    = new byte[20 * 1024];
                 int            totalRead = 0;
                 HttpWebRequest wr        = (HttpWebRequest)HttpWebRequest.Create(_downloadUrl);
                 using (System.IO.BinaryReader sr = new System.IO.BinaryReader(wr.GetResponse().GetResponseStream()))
                     using (FileStream fs = File.OpenWrite(tmpFile.Path))
                     {
                         while (totalRead < _zipFileSize)
                         {
                             int bytesRead = sr.Read(buffer, 0, buffer.Length);
                             if (bytesRead > 0)
                             {
                                 fs.Write(buffer, 0, bytesRead);
                             }
                             totalRead += bytesRead;
                             prog.UpdateProgress(STR_DOWNLOADINGSHAPEFILE, _downloadUrl, _zipFileSize, totalRead);
                         }
                     }
             }
             UnZipFiles(tmpFile.Path, PluginSettings.Instance.DefaultShapeFilesFolder, false);
         }
     }
     catch
     {
         _error = true;
     }
 }
Beispiel #17
0
 protected override void ImportMethod()
 {
     using (Utils.ProgressBlock fixpr = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTINGDATA, _filenames.Length, 0))
     {
         for (int fileindex = 0; fileindex < _filenames.Length; fileindex++)
         {
             List<Framework.Data.Geocache> res = ProcessWaymarkComGPXFile(_filenames[fileindex]);
             if (res != null && res.Count > 0)
             {
                 using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTINGGEOCACHES, res.Count, 0))
                 {
                     int index = 0;
                     int procStep = 0;
                     foreach (Framework.Data.Geocache gc in res)
                     {
                         AddGeocache(gc, Framework.Data.Geocache.V1);
                         index++;
                         procStep++;
                         if (procStep >= 100)
                         {
                             progress.UpdateProgress(STR_IMPORTING, STR_IMPORTINGGEOCACHES, res.Count, index);
                             procStep = 0;
                         }
                     }
                 }
             }
             fixpr.UpdateProgress(STR_IMPORTING, STR_IMPORTINGDATA, _filenames.Length, fileindex + 1);
         }
     }
 }
Beispiel #18
0
 private void searchInDescriptionThreadMethod()
 {
     using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_ACTIONTITLE, STR_ACTIONTEXT, _gcSearchList.Count, 0, true))
     {
         try
         {
             int block = 0;
             int index = 0;
             foreach (Framework.Data.Geocache wp in _gcSearchList)
             {
                 wp.Selected = (wp.ShortDescription.IndexOf(_txt, _scType) >= 0 || wp.LongDescription.IndexOf(_txt, _scType) >= 0);
                 block++;
                 index++;
                 if (block > 1000)
                 {
                     block = 0;
                     if (!progress.UpdateProgress(STR_ACTIONTITLE, STR_ACTIONTEXT, _gcSearchList.Count, index))
                     {
                         break;
                     }
                 }
             }
         }
         catch
         {
         }
         //signal finished
     }
     _actionReady.Set();
 }
Beispiel #19
0
        protected override void ImportMethod()
        {
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORT, STR_DOWNLOAD, 1, 0))
            {
                using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                    using (System.Net.WebClient wc = new System.Net.WebClient())
                    {
                        wc.DownloadFile(string.Format("http://www.globalcaching.eu/service/cachedistance.aspx?country=Netherlands&prefix=GC&token={0}", System.Web.HttpUtility.UrlEncode(Core.GeocachingComAccount.APIToken)), tmp.Path);

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

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

                object o = executeScript("getCenterPosition", null);
                if (o != null && o.GetType() != typeof(DBNull))
                {
                    string s = o.ToString().Replace("(", "").Replace(")", "");
                    center = Utils.Conversion.StringToLocation(s);
                }
                o = executeScript("getRadius", null);
                if (o != null && o.GetType() != typeof(DBNull))
                {
                    string s = o.ToString();
                    radius = Utils.Conversion.StringToDouble(s) * 1000.0;
                }

                using (Utils.DataUpdater upd = new Utils.DataUpdater(Core.ApplicationData.Instance.ActiveDatabase))
                {
                    await Task.Run(new Action(() =>
                    {
                        try
                        {
                            //first get a list of geocache codes
                            List <string> gcList = OKAPIService.GetGeocachesWithinRadius(SiteManager.Instance.ActiveSite, center, radius, filter);
                            using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ImportingOpencachingGeocaches", "ImportingOpencachingGeocaches", gcList.Count, 0, true))
                            {
                                int gcupdatecount = 1;
                                int max = gcList.Count;
                                while (gcList.Count > 0)
                                {
                                    List <string> lcs = gcList.Take(gcupdatecount).ToList();
                                    gcList.RemoveRange(0, lcs.Count);
                                    List <OKAPIService.Geocache> caches = OKAPIService.GetGeocaches(SiteManager.Instance.ActiveSite, lcs);
                                    Import.AddGeocaches(Core.ApplicationData.Instance.ActiveDatabase, caches);

                                    if (!progress.Update("ImportingOpencachingGeocaches", max, max - gcList.Count))
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Core.ApplicationData.Instance.Logger.AddLog(this, e);
                        }
                    }));
                }
            }
            catch (Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }
        }
        public async Task SelectWithinBoundsAsync()
        {
            try
            {
                double minLat = 0.0;
                double minLon = 0.0;
                double maxLat = 0.0;
                double maxLon = 0.0;

                object o = executeScript("getBounds", null);
                if (o != null && o.GetType() != typeof(DBNull))
                {
                    string   s     = o.ToString().Replace("(", "").Replace(")", "");
                    string[] parts = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    minLat = Utils.Conversion.StringToDouble(parts[0]);
                    minLon = Utils.Conversion.StringToDouble(parts[1]);
                    maxLat = Utils.Conversion.StringToDouble(parts[2]);
                    maxLon = Utils.Conversion.StringToDouble(parts[3]);
                }

                using (Utils.DataUpdater upd = new Utils.DataUpdater(Core.ApplicationData.Instance.ActiveDatabase))
                {
                    await Task.Run(new Action(() =>
                    {
                        try
                        {
                            //first get a list of geocache codes
                            List <string> gcList = OKAPIService.GetGeocachesInBBox(SiteManager.Instance.ActiveSite, minLat, minLon, maxLat, maxLon);
                            using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ImportGeocaches", "ImportGeocaches", gcList.Count, 0, true))
                            {
                                int gcupdatecount = 1;
                                int max = gcList.Count;
                                while (gcList.Count > 0)
                                {
                                    List <string> lcs = gcList.Take(gcupdatecount).ToList();
                                    gcList.RemoveRange(0, lcs.Count);
                                    List <OKAPIService.Geocache> caches = OKAPIService.GetGeocaches(SiteManager.Instance.ActiveSite, lcs);
                                    Import.AddGeocaches(Core.ApplicationData.Instance.ActiveDatabase, caches);

                                    if (!progress.Update("ImportGeocaches", max, max - gcList.Count))
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Core.ApplicationData.Instance.Logger.AddLog(this, e);
                        }
                    }));
                }
            }
            catch (Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }
        }
Beispiel #22
0
        private void assignRegionsThreadMethod()
        {
            try
            {
                using (Utils.ProgressBlock prog = new Utils.ProgressBlock(_plugin, STR_ASSIGNINGREGION, STR_ASSIGNINGREGION, _gcList.Count, 0, true))
                {
                    List <Framework.Data.AreaInfo> areasFilter = Utils.GeometrySupport.Instance.GetAreasByLevel(_level);
                    if (areasFilter != null && areasFilter.Count > 0)
                    {
                        int index = 0;
                        foreach (var gc in _gcList)
                        {
                            List <Framework.Data.AreaInfo> areas = Utils.GeometrySupport.Instance.GetAreasOfLocation(new Framework.Data.Location(gc.Lat, gc.Lon), areasFilter);
                            if (areas != null && areas.Count > 0)
                            {
                                Framework.Data.AreaInfo ai = areas[0];
                                if (_prefix.Length > 0)
                                {
                                    ai = (from g in areas where g.Name.StartsWith(_prefix) select g).FirstOrDefault();
                                }
                                if (ai != null)
                                {
                                    switch (_level)
                                    {
                                    case Framework.Data.AreaType.Country:
                                        gc.Country = ai.Name;
                                        break;

                                    case Framework.Data.AreaType.State:
                                        gc.State = ai.Name;
                                        break;

                                    case Framework.Data.AreaType.Municipality:
                                        gc.Municipality = ai.Name;
                                        break;

                                    case Framework.Data.AreaType.City:
                                        gc.City = ai.Name;
                                        break;
                                    }
                                }
                            }
                            index++;
                            if (index % 50 == 0)
                            {
                                if (!prog.UpdateProgress(STR_ASSIGNINGREGION, STR_ASSIGNINGREGION, _gcList.Count, index))
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
Beispiel #23
0
        protected override void ImportMethod()
        {
            int max = _gcList.Count;
            int gcupdatecount = 50;
            int index = 0;
            TimeSpan interval = new TimeSpan(0, 0, 0, 2, 100);
            DateTime prevCall = DateTime.MinValue;
            bool dodelay = (_gcList.Count > 30);
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTING, max, 0, true))
            {
                try
                {
                    using (Utils.API.GeocachingLiveV6 client = new Utils.API.GeocachingLiveV6(Core, string.IsNullOrEmpty(Core.GeocachingComAccount.APIToken)))
                    {
                        while (_gcList.Count > 0)
                        {
                            if (dodelay)
                            {
                                TimeSpan ts = DateTime.Now - prevCall;
                                if (ts < interval)
                                {
                                    Thread.Sleep(interval - ts);
                                }
                            }

                            Utils.API.LiveV6.SearchForGeocachesRequest req = new Utils.API.LiveV6.SearchForGeocachesRequest();
                            req.IsLite = Core.GeocachingComAccount.MemberTypeId == 1;
                            req.AccessToken = client.Token;
                            req.CacheCode = new Utils.API.LiveV6.CacheCodeFilter();
                            req.CacheCode.CacheCodes = _gcList.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)
                            {
                                Utils.API.Import.AddGeocaches(Core, resp.Geocaches);
                            }
                            else
                            {
                                _errormessage = resp.Status.StatusMessage;
                                break;
                            }
                            if (!progress.UpdateProgress(STR_IMPORTING, STR_IMPORTING, max, index))
                            {
                                break;
                            }
                        }
                    }
                }
                catch(Exception e)
                {
                    _errormessage = e.Message;
                }
            }
        }
Beispiel #24
0
        public void AddOwnTrackables(TrackableGroup grp)
        {
            bool canceled = false;

            using (Utils.ProgressBlock progr = new Utils.ProgressBlock("GetTrackableData", "GetTrackableData", 1, 0, true))
                using (var api = new LiveAPI.GeocachingLiveV6())
                {
                    List <string> trkCodes = new List <string>();

                    var req = new LiveAPI.LiveV6.GetTrackablesByOwnerRequest();
                    req.AccessToken        = api.Token;
                    req.TrackableLogsCount = 0;
                    req.StartIndex         = 0;
                    req.MaxPerPage         = Core.Settings.Default.LiveAPIGetOwnedTrackablesBatchSize;
                    int total = 0;
                    while (true)
                    {
                        var resp = api.Client.GetOwnedTrackables(req);
                        if (resp.Status.StatusCode == 0)
                        {
                            if (resp.Trackables != null)
                            {
                                foreach (var t in resp.Trackables)
                                {
                                    trkCodes.Add(t.Code);
                                    Core.Settings.Default.AddUpdateTrackable(grp, GetTrackableItemFromLiveAPI(t));
                                    total++;
                                }
                                if (!progr.Update("GetTrackableData", total, 2 * total))
                                {
                                    canceled = true;
                                    break;
                                }
                            }
                            if (resp.Trackables.Count() < req.MaxPerPage)
                            {
                                break;
                            }
                            else
                            {
                                req.StartIndex = total;
                                System.Threading.Thread.Sleep(Core.Settings.Default.LiveAPIDelayGetOwnedTrackables);
                            }
                        }
                        else
                        {
                            Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp.Status.StatusMessage);
                            break;
                        }
                    }

                    if (!canceled)
                    {
                        progr.Update("GetTrackableData", total, total);
                        AddUpdateTrackables(grp, trkCodes);
                    }
                }
        }
Beispiel #25
0
        public void AddOwnTrackables(TrackableGroup grp)
        {
            bool canceled = false;
            using (Utils.ProgressBlock progr = new Utils.ProgressBlock("GetTrackableData", "GetTrackableData", 1, 0, true))
            using (var api = new LiveAPI.GeocachingLiveV6())
            {
                List<string> trkCodes = new List<string>();

                var req = new LiveAPI.LiveV6.GetTrackablesByOwnerRequest();
                req.AccessToken = api.Token;
                req.TrackableLogsCount = 0;
                req.StartIndex = 0;
                req.MaxPerPage = Core.Settings.Default.LiveAPIGetOwnedTrackablesBatchSize;
                int total = 0;
                while (true)
                {
                    var resp = api.Client.GetOwnedTrackables(req);
                    if (resp.Status.StatusCode == 0)
                    {
                        if (resp.Trackables != null)
                        {
                            foreach (var t in resp.Trackables)
                            {
                                trkCodes.Add(t.Code);
                                Core.Settings.Default.AddUpdateTrackable(grp, GetTrackableItemFromLiveAPI(t));
                                total++;
                            }
                            if (!progr.Update("GetTrackableData", total, 2 * total))
                            {
                                canceled = true;
                                break;
                            }
                        }
                        if (resp.Trackables.Count() < req.MaxPerPage)
                        {
                            break;
                        }
                        else
                        {
                            req.StartIndex = total;
                            System.Threading.Thread.Sleep(Core.Settings.Default.LiveAPIDelayGetOwnedTrackables);
                        }
                    }
                    else
                    {
                        Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp.Status.StatusMessage);
                        break;
                    }
                }

                if (!canceled)
                {
                    progr.Update("GetTrackableData", total, total);
                    AddUpdateTrackables(grp, trkCodes);
                }
            }
        }
        public override async Task ExecuteAsync(object parameter)
        {
            Core.ApplicationData.Instance.BeginActiviy();
            Core.Storage.Database db = Core.ApplicationData.Instance.ActiveDatabase;
            if (db != null)
            {
                using (Utils.DataUpdater upd = new Utils.DataUpdater(db))
                {
                    await Task.Run(() =>
                    {
                        Utils.ProgressBlock prog = null;
                        DateTime nextUpdate      = DateTime.Now.AddSeconds(1);
                        if (_showProgress)
                        {
                            prog = new Utils.ProgressBlock("PerfomingAction", "PerfomingAction", db.GeocacheCollection.Count, 0, true);
                        }
                        try
                        {
                            int index = 0;
                            foreach (Core.Data.Geocache gc in db.GeocacheCollection)
                            {
                                _geocacheAction(gc);

                                if (prog != null)
                                {
                                    index++;
                                    if (DateTime.Now >= nextUpdate)
                                    {
                                        if (!prog.Update("PerfomingAction", db.GeocacheCollection.Count, index))
                                        {
                                            break;
                                        }
                                        nextUpdate = DateTime.Now.AddSeconds(1);
                                    }
                                }
                            }
                            if (prog != null)
                            {
                                prog.Dispose();
                                prog = null;
                            }
                        }
                        catch (Exception e)
                        {
                            Core.ApplicationData.Instance.Logger.AddLog(this, e);
                            if (prog != null)
                            {
                                prog.Dispose();
                                prog = null;
                            }
                        }
                    });
                }
            }
            ;
            Core.ApplicationData.Instance.EndActiviy();
        }
Beispiel #27
0
        public async Task DeleteImagesFromFolder(List<Core.Data.Geocache> gcList, string folder)
        {
            await Task.Run(() =>
            {
                try
                {
                    DateTime nextUpdate = DateTime.Now.AddSeconds(1);
                    using (Utils.ProgressBlock progress = new Utils.ProgressBlock("DeletingImages", "DeletingImages", gcList.Count, 0, true))
                    {
                        string imgFolder;
                        string checkFolder = Path.Combine(folder, "GeocachePhotos");
                        if (Directory.Exists(checkFolder))
                        {
                            imgFolder = checkFolder;
                        }
                        else
                        {
                            imgFolder = folder;
                        }

                        int index = 0;
                        foreach (var gc in gcList)
                        {
                            string cacheFolder = Path.Combine(imgFolder, gc.Code[gc.Code.Length - 1].ToString());
                            if (Directory.Exists(cacheFolder))
                            {
                                cacheFolder = Path.Combine(cacheFolder, gc.Code[gc.Code.Length - 2].ToString());
                                if (Directory.Exists(cacheFolder))
                                {
                                    cacheFolder = Path.Combine(cacheFolder, gc.Code);
                                    if (Directory.Exists(cacheFolder))
                                    {
                                        Directory.Delete(cacheFolder, true);
                                    }
                                }
                            }


                            index++;
                            if (DateTime.Now >= nextUpdate)
                            {
                                if (!progress.Update("DeletingImages", gcList.Count, index))
                                {
                                    break;
                                }
                                nextUpdate = DateTime.Now.AddSeconds(1);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Core.ApplicationData.Instance.Logger.AddLog(this, e);
                }
            });
        }
Beispiel #28
0
 public async Task CreateImageFolderForGeocaches(List <Framework.Data.Geocache> gcList, string folder)
 {
     using (CopyToFolderForm dlg = new CopyToFolderForm(folder))
     {
         if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         {
             _gcList = (from a in gcList select a).ToList();
             if (PluginSettings.Instance.DownloadBeforeCreate)
             {
                 List <Framework.Data.Geocache>    tmpList = (from a in _gcList select a).ToList();
                 System.Windows.Forms.DialogResult dr      = System.Windows.Forms.MessageBox.Show(Utils.LanguageSupport.Instance.GetTranslation(STR_GRABNEW), Utils.LanguageSupport.Instance.GetTranslation(STR_GRABIMAGES), System.Windows.Forms.MessageBoxButtons.YesNoCancel);
                 _grabOnlyNew = (dr == System.Windows.Forms.DialogResult.Yes);
                 if (dr != System.Windows.Forms.DialogResult.Cancel)
                 {
                     using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_GRABBING_IMAGES, STR_GRABBING_IMAGES, _gcList.Count, 0, true))
                     {
                         int cnt = _gcList.Count;
                         _orgListCount = cnt;
                         Thread[] thrd = new Thread[4];
                         for (int i = 0; i < thrd.Length; i++)
                         {
                             thrd[i] = new Thread(new ThreadStart(this.getImagesThreadMethod));
                             thrd[i].Start();
                         }
                         while (cnt > 0)
                         {
                             Thread.Sleep(500);
                             System.Windows.Forms.Application.DoEvents();
                             lock (_gcList)
                             {
                                 cnt = _gcList.Count;
                             }
                             if (!progress.UpdateProgress(STR_GRABBING_IMAGES, STR_GRABBING_IMAGES, _orgListCount, _orgListCount - cnt))
                             {
                                 lock (_gcList)
                                 {
                                     _gcList.Clear();
                                     cnt = 0;
                                 }
                             }
                         }
                         for (int i = 0; i < thrd.Length; i++)
                         {
                             thrd[i].Join();
                         }
                     }
                 }
                 _gcList = tmpList;
             }
             await Task.Run(() =>
             {
                 this.copyToFolderThreadMethod();
             });
         }
     }
 }
Beispiel #29
0
        public async Task DeleteImagesFromFolder(List <Core.Data.Geocache> gcList, string folder)
        {
            await Task.Run(() =>
            {
                try
                {
                    DateTime nextUpdate = DateTime.Now.AddSeconds(1);
                    using (Utils.ProgressBlock progress = new Utils.ProgressBlock("DeletingImages", "DeletingImages", gcList.Count, 0, true))
                    {
                        string imgFolder;
                        string checkFolder = Path.Combine(folder, "GeocachePhotos");
                        if (Directory.Exists(checkFolder))
                        {
                            imgFolder = checkFolder;
                        }
                        else
                        {
                            imgFolder = folder;
                        }

                        int index = 0;
                        foreach (var gc in gcList)
                        {
                            string cacheFolder = Path.Combine(imgFolder, gc.Code[gc.Code.Length - 1].ToString());
                            if (Directory.Exists(cacheFolder))
                            {
                                cacheFolder = Path.Combine(cacheFolder, gc.Code[gc.Code.Length - 2].ToString());
                                if (Directory.Exists(cacheFolder))
                                {
                                    cacheFolder = Path.Combine(cacheFolder, gc.Code);
                                    if (Directory.Exists(cacheFolder))
                                    {
                                        Directory.Delete(cacheFolder, true);
                                    }
                                }
                            }


                            index++;
                            if (DateTime.Now >= nextUpdate)
                            {
                                if (!progress.Update("DeletingImages", gcList.Count, index))
                                {
                                    break;
                                }
                                nextUpdate = DateTime.Now.AddSeconds(1);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Core.ApplicationData.Instance.Logger.AddLog(this, e);
                }
            });
        }
Beispiel #30
0
 private void assignRegionsThreadMethod()
 {
     try
     {
         using (Utils.ProgressBlock prog = new Utils.ProgressBlock(_plugin, STR_ASSIGNINGREGION, STR_ASSIGNINGREGION, _gcList.Count, 0, true))
         {
             List<Framework.Data.AreaInfo> areasFilter = Utils.GeometrySupport.Instance.GetAreasByLevel(_level);
             if (areasFilter != null && areasFilter.Count > 0)
             {
                 int index = 0;
                 foreach (var gc in _gcList)
                 {
                     List<Framework.Data.AreaInfo> areas = Utils.GeometrySupport.Instance.GetAreasOfLocation(new Framework.Data.Location(gc.Lat, gc.Lon), areasFilter);
                     if (areas != null && areas.Count > 0)
                     {
                         Framework.Data.AreaInfo ai = areas[0];
                         if (_prefix.Length > 0)
                         {
                             ai = (from g in areas where g.Name.StartsWith(_prefix) select g).FirstOrDefault();
                         }
                         if (ai != null)
                         {
                             switch (_level)
                             {
                                 case Framework.Data.AreaType.Country:
                                     gc.Country = ai.Name;
                                     break;
                                 case Framework.Data.AreaType.State:
                                     gc.State = ai.Name;
                                     break;
                                 case Framework.Data.AreaType.Municipality:
                                     gc.Municipality = ai.Name;
                                     break;
                                 case Framework.Data.AreaType.City:
                                     gc.City = ai.Name;
                                     break;
                             }
                         }
                     }
                     index++;
                     if (index % 50 == 0)
                     {
                         if (!prog.UpdateProgress(STR_ASSIGNINGREGION, STR_ASSIGNINGREGION, _gcList.Count, index))
                         {
                             break;
                         }
                     }
                 }
             }
         }
     }
     catch
     {
     }
     _actionReady.Set();
 }
Beispiel #31
0
 public static void ImportGeocaches(Core.Storage.Database db, List <string> gcCodes)
 {
     try
     {
         using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ImportingGeocaches", "ImportingGeocaches", gcCodes.Count, 0, true))
         {
             int totalcount = gcCodes.Count;
             using (var client = new GeocachingLiveV6())
             {
                 int index = 0;
                 while (gcCodes.Count > 0)
                 {
                     LiveV6.SearchForGeocachesRequest req = new LiveV6.SearchForGeocachesRequest();
                     req.IsLite               = Core.Settings.Default.LiveAPIMemberTypeId == 1;
                     req.AccessToken          = client.Token;
                     req.CacheCode            = new LiveV6.CacheCodeFilter();
                     req.CacheCode.CacheCodes = (from a in gcCodes select a).Take(Core.Settings.Default.LiveAPIImportGeocachesBatchSize).ToArray();
                     req.MaxPerPage           = Core.Settings.Default.LiveAPIImportGeocachesBatchSize;
                     req.GeocacheLogCount     = 5;
                     index += req.CacheCode.CacheCodes.Length;
                     gcCodes.RemoveRange(0, req.CacheCode.CacheCodes.Length);
                     var resp = client.Client.SearchForGeocaches(req);
                     if (resp.Status.StatusCode == 0 && resp.Geocaches != null)
                     {
                         List <Core.Data.Geocache> upList = ImportGeocaches(db, resp.Geocaches);
                         if (Core.Settings.Default.LiveAPIDeselectAfterUpdate)
                         {
                             foreach (var g in upList)
                             {
                                 g.Selected = false;
                             }
                         }
                     }
                     else
                     {
                         Core.ApplicationData.Instance.Logger.AddLog(new Import(), new Exception(resp.Status.StatusMessage));
                         break;
                     }
                     if (!progress.Update("ImportingGeocaches", totalcount, index))
                     {
                         break;
                     }
                     if (gcCodes.Count > 0)
                     {
                         System.Threading.Thread.Sleep(Core.Settings.Default.LiveAPIDelaySearchForGeocaches);
                     }
                 }
             }
         }
     }
     catch (Exception e)
     {
         Core.ApplicationData.Instance.Logger.AddLog(new Import(), e);
     }
 }
Beispiel #32
0
        public override bool Action(string action)
        {
            bool result = base.Action(action);

            if (result && action == ACTION_SHOW)
            {
                try
                {
                    var logs = new List <Utils.API.LiveV6.GeocacheLog>();

                    using (var api = new Utils.API.GeocachingLiveV6(Core))
                    {
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, "Importing logs", "Importing logs...", 100, 0, true))
                        {
                            var req = new Utils.API.LiveV6.GetUsersGeocacheLogsRequest();
                            req.AccessToken     = api.Token;
                            req.Username        = "******";
                            req.ExcludeArchived = true;
                            req.MaxPerPage      = 30;
                            req.StartIndex      = 0;
                            req.LogTypes        = (from a in Core.LogTypes where a.AsFound select(long) a.ID).ToArray();
                            var resp = api.Client.GetUsersGeocacheLogs(req);
                            while (resp.Status.StatusCode == 0)
                            {
                                logs.AddRange(resp.Logs);

                                if (resp.Logs.Count() >= req.MaxPerPage)
                                {
                                    req.StartIndex = logs.Count;
                                    if (!progress.UpdateProgress("Importing logs", "Importing logs...", logs.Count + req.MaxPerPage, logs.Count))
                                    {
                                        break;
                                    }
                                    resp = api.Client.GetUsersGeocacheLogs(req);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            if (resp.Status.StatusCode != 0)
                            {
                                //_errormessage = resp.Status.StatusMessage;
                            }
                        }
                    }
                }
                catch
                {
                }
            }
            return(result);
        }
Beispiel #33
0
        private void deleteImagesFromFolderThreadMethod()
        {
            DateTime nextUpdate = DateTime.Now.AddSeconds(2);

            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_DELETING_IMAGES, STR_DELETING_IMAGES, _gcList.Count, 0, true))
            {
                try
                {
                    string imgFolder;
                    string checkFolder = Path.Combine(_imgFolder, "GeocachePhotos");
                    if (Directory.Exists(checkFolder))
                    {
                        imgFolder = checkFolder;
                    }
                    else
                    {
                        imgFolder = _imgFolder;
                    }

                    int index = 0;
                    foreach (Framework.Data.Geocache gc in _gcList)
                    {
                        string cacheFolder = Path.Combine(imgFolder, gc.Code[gc.Code.Length - 1].ToString());
                        if (Directory.Exists(cacheFolder))
                        {
                            cacheFolder = Path.Combine(cacheFolder, gc.Code[gc.Code.Length - 2].ToString());
                            if (Directory.Exists(cacheFolder))
                            {
                                cacheFolder = Path.Combine(cacheFolder, gc.Code);
                                if (Directory.Exists(cacheFolder))
                                {
                                    Directory.Delete(cacheFolder, true);
                                }
                            }
                        }


                        index++;
                        if (DateTime.Now >= nextUpdate)
                        {
                            if (!progress.UpdateProgress(STR_DELETING_IMAGES, STR_DELETING_IMAGES, _gcList.Count, index))
                            {
                                break;
                            }
                            nextUpdate = DateTime.Now.AddSeconds(2);
                        }
                    }
                }
                catch
                {
                }
            }
        }
Beispiel #34
0
        public async Task<List<LogInfo>> LogGeocachesAsync(List<LogInfo> logInfos)
        {
            List<LogInfo> result = new List<LogInfo>();
            Utils.DataUpdater upd = null;
            if (Core.ApplicationData.Instance.ActiveDatabase != null)
            {
                upd = new Utils.DataUpdater(Core.ApplicationData.Instance.ActiveDatabase);
            }
            using (Utils.ProgressBlock prog = new Utils.ProgressBlock("LogGeocache", "Logging", logInfos.Count, 0, true))
            {
                using (var api = new LiveAPI.GeocachingLiveV6())
                {
                    foreach (LogInfo li in logInfos)
                    {
                        int index = 0;
                        List<LiveAPI.LiveV6.Trackable> dropTbs = null;
                        List<string> retrieveTbs = null;

                        //todo: check if trackable dialog is needed
                        //fetch in background

                        bool ok = false;
                        await Task.Run(() =>
                        {
                            if (index > 0 && dropTbs == null && retrieveTbs == null)
                            {
                                System.Threading.Thread.Sleep(Core.Settings.Default.LiveAPIDelayCreateFieldNoteAndPublish);
                            }
                            ok = LogGeocache(api, li, dropTbs, retrieveTbs);
                        });
                        if (ok)
                        {
                            result.Add(li);
                            index++;
                            if (!prog.Update("Logging", logInfos.Count, index))
                            {
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            if (upd!=null)
            {
                upd.Dispose();
                upd = null;
            }
            return result;
        }
Beispiel #35
0
        public override bool Action(string action)
        {
            bool result = base.Action(action);
            if (result && action == ACTION_SHOW)
            {
                try
                {
                    var logs = new List<Utils.API.LiveV6.GeocacheLog>();

                    using (var api = new Utils.API.GeocachingLiveV6(Core))
                    {
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, "Importing logs", "Importing logs...", 100, 0, true))
                        {
                            var req = new Utils.API.LiveV6.GetUsersGeocacheLogsRequest();
                            req.AccessToken = api.Token;
                            req.Username = "******";
                            req.ExcludeArchived = true;
                            req.MaxPerPage = 100;
                            req.StartIndex = 0;
                            req.LogTypes = (from a in Core.LogTypes where a.AsFound select (long)a.ID).ToArray();
                            var resp = api.Client.GetUsersGeocacheLogs(req);
                            while (resp.Status.StatusCode == 0)
                            {
                                logs.AddRange(resp.Logs);

                                if (resp.Logs.Count() >= req.MaxPerPage)
                                {
                                    req.StartIndex = logs.Count;
                                    if (!progress.UpdateProgress("Importing logs", "Importing logs...", logs.Count + req.MaxPerPage, logs.Count))
                                    {
                                        break;
                                    }
                                    resp = api.Client.GetUsersGeocacheLogs(req);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            if (resp.Status.StatusCode != 0)
                            {
                                //_errormessage = resp.Status.StatusMessage;
                            }
                        }
                    }
                }
                catch
                {
                }
            }
            return result;
        }
Beispiel #36
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            FTPDirectoryItemInfo fi = e.Argument as FTPDirectoryItemInfo;

            DownloadedFileName = fi.Name;
            try
            {
                DownloadedFile = new TemporaryFile(false);

                string fn = "ftp://download.mapsforge.org/";
                for (int i = 0; i < _folder.Count; i++)
                {
                    fn = string.Format("{0}{1}/", fn, _folder[i]);
                }
                fn = string.Format("{0}{1}", fn, fi.Name);
                using (Utils.ProgressBlock prog = new Utils.ProgressBlock(_plugin, STR_DOWNLOADINGFILE, fn, (int)fi.Size, 0))
                {
                    FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(fn));
                    ftpRequest.Credentials = new NetworkCredential("anonymous", "*****@*****.**");
                    ftpRequest.Method      = WebRequestMethods.Ftp.DownloadFile;

                    int bytesTotal = 0;
                    using (FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse())
                        using (Stream responseStream = ftpResponse.GetResponseStream())
                            using (FileStream writeStream = new FileStream(DownloadedFile.Path, FileMode.Create))
                            {
                                int    Length    = 2048 * 1000;
                                Byte[] buffer    = new Byte[Length];
                                int    bytesRead = responseStream.Read(buffer, 0, Length);

                                while (bytesRead > 0)
                                {
                                    bytesTotal += bytesRead;// don't forget to increment bytesRead !
                                    writeStream.Write(buffer, 0, bytesRead);
                                    bytesRead = responseStream.Read(buffer, 0, Length);
                                    prog.UpdateProgress(STR_DOWNLOADINGFILE, fn, (int)fi.Size, bytesTotal);
                                }
                            }

                    if (bytesTotal != (int)fi.Size)
                    {
                        DownloadedFile     = null;
                        DownloadedFileName = "";
                    }
                }
            }
            catch
            {
                DownloadedFile     = null;
                DownloadedFileName = "";
            }
        }
Beispiel #37
0
 private void getAllTrackableLogsThreadMethod()
 {
     try
     {
         using (Utils.ProgressBlock progr = new Utils.ProgressBlock(_plugin as Utils.BasePlugin.Plugin, STR_GETTINGLOGS, STR_GETTINGLOGS, 30, 0, true))
         {
             using (var api = new Utils.API.GeocachingLiveV6(_core, _useTestSite))
             {
                 int maxPageSize = 30;
                 while (true)
                 {
                     var resp = api.Client.GetTrackableLogsByTBCode(api.Token, _activeTb.Code, _activeTbLogs.Count, maxPageSize);
                     if (resp.Status.StatusCode == 0)
                     {
                         if (resp.TrackableLogs != null)
                         {
                             _activeTbLogs.AddRange(resp.TrackableLogs);
                             if (resp.TrackableLogs.Count() < maxPageSize)
                             {
                                 break;
                             }
                             else
                             {
                                 if (!progr.UpdateProgress(STR_GETTINGLOGS, STR_GETTINGLOGS, _activeTbLogs.Count + maxPageSize, _activeTbLogs.Count))
                                 {
                                     break;
                                 }
                                 else
                                 {
                                     Thread.Sleep(2000);
                                 }
                             }
                         }
                         else
                         {
                             break;
                         }
                     }
                     else
                     {
                         _errormessage = resp.Status.StatusMessage;
                         break;
                     }
                 }
             }
         }
     }
     catch
     {
     }
 }
Beispiel #38
0
        private void importGeocachesThreadMethod()
        {
            int max           = _gcList.Count;
            int gcupdatecount = 20;
            int index         = 0;

            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(OwnerPlugin, STR_IMPORTING, STR_IMPORTING, max, 0, true))
            {
                try
                {
                    using (Utils.API.GeocachingLiveV6 client = new Utils.API.GeocachingLiveV6(Core, string.IsNullOrEmpty(Core.GeocachingComAccount.APIToken)))
                    {
                        while (_gcList.Count > 0)
                        {
                            Utils.API.LiveV6.SearchForGeocachesRequest req = new Utils.API.LiveV6.SearchForGeocachesRequest();
                            req.IsLite               = Core.GeocachingComAccount.MemberTypeId == 1;
                            req.AccessToken          = client.Token;
                            req.CacheCode            = new Utils.API.LiveV6.CacheCodeFilter();
                            req.CacheCode.CacheCodes = _gcList.Take(gcupdatecount).ToArray();
                            req.MaxPerPage           = gcupdatecount;
                            req.GeocacheLogCount     = 5;
                            index += req.CacheCode.CacheCodes.Length;
                            _gcList.RemoveRange(0, req.CacheCode.CacheCodes.Length);
                            var resp = client.Client.SearchForGeocaches(req);
                            if (resp.Status.StatusCode == 0 && resp.Geocaches != null)
                            {
                                Utils.API.Import.AddGeocaches(Core, resp.Geocaches);
                            }
                            else
                            {
                                _errormessage = resp.Status.StatusMessage;
                                break;
                            }
                            if (!progress.UpdateProgress(STR_IMPORTING, STR_IMPORTING, max, index))
                            {
                                break;
                            }

                            if (_gcList.Count > 0)
                            {
                                Thread.Sleep(3000);
                            }
                        }
                    }
                }
                catch
                {
                }
            }
            _actionReady.Set();
        }
        private void getGeocachesThreadMethod()
        {
            try
            {
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(_plugin, STR_IMPORTING, STR_IMPORTING, _geocacheCodes.Count, 0, true))
                {
                    int totalcount    = _geocacheCodes.Count;
                    int index         = 0;
                    int gcupdatecount = 20;
                    while (_geocacheCodes.Count > 0)
                    {
                        Utils.API.LiveV6.SearchForGeocachesRequest req = new Utils.API.LiveV6.SearchForGeocachesRequest();
                        req.IsLite               = _core.GeocachingComAccount.MemberTypeId == 1;
                        req.AccessToken          = _client.Token;
                        req.CacheCode            = new Utils.API.LiveV6.CacheCodeFilter();
                        req.CacheCode.CacheCodes = (from a in _geocacheCodes select a).Take(gcupdatecount).ToArray();
                        req.MaxPerPage           = gcupdatecount;
                        req.GeocacheLogCount     = 5;
                        index += req.CacheCode.CacheCodes.Length;
                        _geocacheCodes.RemoveRange(0, req.CacheCode.CacheCodes.Length);
                        var resp = _client.Client.SearchForGeocaches(req);
                        if (resp.Status.StatusCode == 0 && resp.Geocaches != null)
                        {
                            Utils.API.Import.AddGeocaches(_core, resp.Geocaches);
                        }
                        else
                        {
                            _errormessage = resp.Status.StatusMessage;
                            break;
                        }

                        if (!progress.UpdateProgress(STR_IMPORTING, STR_IMPORTING, totalcount, index))
                        {
                            break;
                        }

                        if (_geocacheCodes.Count > 0)
                        {
                            Thread.Sleep(3000);
                        }
                    }
                }
            }
            catch
            {
            }
        }
Beispiel #40
0
        private void buttonApply_Click(object sender, EventArgs e)
        {
            bool needRestart = false;

            if (_core != null)
            {
                _core.GeocachingComAccount.AccountName = textBoxUsername.Text;
                _core.LoadLogsInBackground             = checkBox1.Checked;
                _core.AutoSaveOnClose = checkBox2.Checked;
                PluginSettings.Instance.ShowOKAPIMenu = checkBox3.Checked;
                if (_ucList.Count > 0)
                {
                    using (Utils.ProgressBlock prog = new Utils.ProgressBlock(this._ownerPlugin, Utils.LanguageSupport.Instance.GetTranslation(STR_APPLYINGSETTINGS), Utils.LanguageSupport.Instance.GetTranslation(STR_APPLYINGSETTINGS), _pluginList.Count, 0))
                    {
                        Application.DoEvents();
                        int index = 0;
                        foreach (Framework.Interfaces.IPlugin p in _pluginList)
                        {
                            prog.UpdateProgress(Utils.LanguageSupport.Instance.GetTranslation(STR_APPLYINGSETTINGS), Utils.LanguageSupport.Instance.GetTranslation(p.FriendlyName), _pluginList.Count, index);
                            Application.DoEvents();
                            p.ApplySettings(_ucList);
                            index++;
                        }
                    }
                }
                List <string> sl = new List <string>();
                for (int index = 0; index < checkedListBoxPlugins.Items.Count; index++)
                {
                    if (!checkedListBoxPlugins.CheckedIndices.Contains(index))
                    {
                        sl.Add(checkedListBoxPlugins.Items[index].ToString());
                    }
                }
                needRestart = _core.SetDisabledPlugins(sl.ToArray());
                if ((string)comboBoxInternalStorage.SelectedItem != _core.ActiveInternalStoragePlugin)
                {
                    _core.ActiveInternalStoragePlugin = (string)comboBoxInternalStorage.SelectedItem;
                    needRestart = true;
                }
            }
            Close();
            DialogResult = System.Windows.Forms.DialogResult.OK;
            if (needRestart)
            {
                Application.Restart();
            }
        }
Beispiel #41
0
        private void runFlow(ActionFlow flow)
        {
            try
            {
                foreach (ActionImplementation ai in flow.Actions)
                {
                    ai.PrepareRun();
                }
                //find start and run
                ActionStart startAction          = (from a in flow.Actions where a is ActionStart select a).FirstOrDefault() as ActionStart;
                List <Core.Data.Geocache> gcList = startAction.PrepareFlow();

                DateTime nextUpdate = DateTime.Now.AddSeconds(1);
                int      index      = 0;
                bool     canceled   = false;
                using (Utils.ProgressBlock prog = new Utils.ProgressBlock("ActionBuilder", "Executing", gcList.Count, 0, true))
                {
                    foreach (Core.Data.Geocache gc in gcList)
                    {
                        startAction.Run(gc);
                        index++;
                        if (DateTime.Now >= nextUpdate)
                        {
                            if (!prog.Update("Executing", gcList.Count, index))
                            {
                                canceled = true;
                                break;
                            }
                            nextUpdate = DateTime.Now.AddSeconds(1);
                        }
                    }
                }

                if (!canceled)
                {
                    //wrap up
                    foreach (ActionImplementation ai in flow.Actions)
                    {
                        ai.FinalizeRun();
                    }
                }
            }
            catch (Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }
        }
Beispiel #42
0
 public void ImportFavorites(Core.Storage.Database db)
 {
     try
     {
         using (Utils.ProgressBlock progress = new Utils.ProgressBlock("GetFavoritesFromGlobalcaching", "DownloadingData", 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.Settings.Default.LiveAPIToken ?? "")));
                 if (doc != null)
                 {
                     string[] lines = doc.Replace("\r", "").Split(new char[] { '\n' });
                     progress.Update("SavingGeocaches", lines.Length, 0);
                     Core.Data.Geocache gc;
                     char[]             sep = new char[] { ',' };
                     string[]           parts;
                     DateTime           nextUpdate = DateTime.Now.AddSeconds(1);
                     int index = 0;
                     foreach (string s in lines)
                     {
                         parts = s.Split(sep);
                         if (parts.Length > 0)
                         {
                             gc = db.GeocacheCollection.GetGeocache(parts[0]);
                             if (gc != null)
                             {
                                 gc.Favorites = int.Parse(parts[1]);
                             }
                         }
                         index++;
                         if (DateTime.Now >= nextUpdate)
                         {
                             progress.Update("SavingGeocaches", lines.Length, index);
                             nextUpdate = DateTime.Now.AddSeconds(1);
                         }
                     }
                 }
             }
         }
     }
     catch (Exception e)
     {
         Core.ApplicationData.Instance.Logger.AddLog(this, e);
     }
 }
Beispiel #43
0
        public List <LiveAPI.LiveV6.GeocacheLog> GetLogsOfUser(string userName, List <Core.Data.LogType> logTypes)
        {
            List <LiveAPI.LiveV6.GeocacheLog> result = new List <LiveAPI.LiveV6.GeocacheLog>();

            using (var api = new LiveAPI.GeocachingLiveV6())
            {
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ImportingLogs", "ImportingLogs", 100, 0, true))
                {
                    var req = new LiveAPI.LiveV6.GetUsersGeocacheLogsRequest();
                    req.AccessToken     = api.Token;
                    req.ExcludeArchived = false;
                    req.MaxPerPage      = Core.Settings.Default.LiveAPIGetUsersGeocacheLogsBatchSize;
                    req.StartIndex      = 0;
                    req.LogTypes        = (from a in logTypes select(long) a.ID).ToArray();
                    var resp = api.Client.GetUsersGeocacheLogs(req);
                    while (resp.Status.StatusCode == 0)
                    {
                        //logs.AddRange(resp.Logs);
                        //if (resp.Logs.Count() >= req.MaxPerPage)
                        if (resp.Logs.Count() > 0)
                        {
                            result.AddRange(resp.Logs);
                            req.StartIndex = result.Count;
                            if (!progress.Update("ImportingLogs", result.Count + req.MaxPerPage, result.Count))
                            {
                                _cancelled = true;
                                break;
                            }
                            System.Threading.Thread.Sleep(Core.Settings.Default.LiveAPIDelayGetUsersGeocacheLogs);
                            resp = api.Client.GetUsersGeocacheLogs(req);
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (resp.Status.StatusCode != 0)
                    {
                        Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp.Status.StatusMessage);
                        _cancelled = true;
                    }
                }
            }
            return(result);
        }
Beispiel #44
0
 public List<LiveAPI.LiveV6.GeocacheLog> GetLogsOfUser(string userName, List<Core.Data.LogType> logTypes)
 {
     List<LiveAPI.LiveV6.GeocacheLog> result = new List<LiveAPI.LiveV6.GeocacheLog>();
     using (var api = new LiveAPI.GeocachingLiveV6())
     {
         using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ImportingLogs", "ImportingLogs", 100, 0, true))
         {
             var req = new LiveAPI.LiveV6.GetUsersGeocacheLogsRequest();
             req.AccessToken = api.Token;
             req.ExcludeArchived = false;
             req.MaxPerPage = Core.Settings.Default.LiveAPIGetUsersGeocacheLogsBatchSize;
             req.StartIndex = 0;
             req.LogTypes = (from a in logTypes select (long)a.ID).ToArray();
             var resp = api.Client.GetUsersGeocacheLogs(req);
             while (resp.Status.StatusCode == 0)
             {
                 //logs.AddRange(resp.Logs);
                 //if (resp.Logs.Count() >= req.MaxPerPage)
                 if (resp.Logs.Count() > 0)
                 {
                     result.AddRange(resp.Logs);
                     req.StartIndex = result.Count;
                     if (!progress.Update("ImportingLogs", result.Count + req.MaxPerPage, result.Count))
                     {
                         _cancelled = true;
                         break;
                     }
                     System.Threading.Thread.Sleep(Core.Settings.Default.LiveAPIDelayGetUsersGeocacheLogs);
                     resp = api.Client.GetUsersGeocacheLogs(req);
                 }
                 else
                 {
                     break;
                 }
             }
             if (resp.Status.StatusCode != 0)
             {
                 Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, resp.Status.StatusMessage);
                 _cancelled = true;
             }
         }
     }
     return result;
 }
Beispiel #45
0
        public void DownloadAllLogImages()
        {
            try
            {
                _logImagesToGrab = (from Framework.Data.LogImage li in Core.LogImages select li).ToList();

                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_GRABBING_IMAGES, STR_GRABBING_IMAGES, _logImagesToGrab.Count, 0, true))
                {
                    int cnt = _logImagesToGrab.Count;
                    int orgListCount = cnt;
                    Thread[] thrd = new Thread[6];
                    for (int i = 0; i < thrd.Length; i++)
                    {
                        thrd[i] = new Thread(new ThreadStart(this.getImagesThreadMethod));
                        thrd[i].Start();
                    }
                    while (cnt > 0)
                    {
                        Thread.Sleep(500);
                        System.Windows.Forms.Application.DoEvents();
                        lock (_logImagesToGrab)
                        {
                            cnt = _logImagesToGrab.Count;
                        }
                        if (!progress.UpdateProgress(STR_GRABBING_IMAGES, STR_GRABBING_IMAGES, orgListCount, orgListCount - cnt))
                        {
                            lock (_logImagesToGrab)
                            {
                                _logImagesToGrab.Clear();
                                cnt = 0;
                            }
                        }
                    }
                    for (int i = 0; i < thrd.Length; i++)
                    {
                        thrd[i].Join();
                    }
                }

            }
            catch
            {
            }
        }
Beispiel #46
0
        public void DownloadAllLogImages()
        {
            try
            {
                _logImagesToGrab = (from Framework.Data.LogImage li in Core.LogImages select li).ToList();

                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_GRABBING_IMAGES, STR_GRABBING_IMAGES, _logImagesToGrab.Count, 0, true))
                {
                    int      cnt          = _logImagesToGrab.Count;
                    int      orgListCount = cnt;
                    Thread[] thrd         = new Thread[6];
                    for (int i = 0; i < thrd.Length; i++)
                    {
                        thrd[i] = new Thread(new ThreadStart(this.getImagesThreadMethod));
                        thrd[i].Start();
                    }
                    while (cnt > 0)
                    {
                        Thread.Sleep(500);
                        System.Windows.Forms.Application.DoEvents();
                        lock (_logImagesToGrab)
                        {
                            cnt = _logImagesToGrab.Count;
                        }
                        if (!progress.UpdateProgress(STR_GRABBING_IMAGES, STR_GRABBING_IMAGES, orgListCount, orgListCount - cnt))
                        {
                            lock (_logImagesToGrab)
                            {
                                _logImagesToGrab.Clear();
                                cnt = 0;
                            }
                        }
                    }
                    for (int i = 0; i < thrd.Length; i++)
                    {
                        thrd[i].Join();
                    }
                }
            }
            catch
            {
            }
        }
Beispiel #47
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;
        }
Beispiel #48
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;
        }
Beispiel #49
0
        public override bool Backup()
        {
            bool result = true;
            _fileCollection.StartReleaseForCopy();
            try
            {
                BackupItem bi = new BackupItem();
                bi.BackupFile = Path.Combine(Properties.Settings.Default.BackupFolder, string.Concat(Path.GetFileNameWithoutExtension(_fileCollection.BaseFilename), "_", DateTime.Now.ToString("s").Replace(" ", "").Replace("T", "").Replace(":", "").Replace("-", ""),".zip"));
                bi.BackupDate = DateTime.Now;
                bi.OriginalPath = _fileCollection.BaseFilename;
                //zip all files
                string[] files = Directory.GetFiles(Path.GetDirectoryName(_fileCollection.BaseFilename), string.Concat(Path.GetFileNameWithoutExtension(_fileCollection.BaseFilename), ".*"));
                List<FileInfo> fil = new List<FileInfo>();
                long totalBytes = 0;
                foreach (string f in files)
                {
                    FileInfo fi = new FileInfo(f);
                    fil.Add(fi);
                    totalBytes += fi.Length;
                }
                int max = (int)Math.Max(1, totalBytes / (1024 * 1024));
                long processed = 0;
                DateTime progUpdate = DateTime.Now.AddSeconds(2);
                byte[] buffer = new byte[4 * 1024 * 1024];
                using (Utils.ProgressBlock prog = new Utils.ProgressBlock(this, STR_BACKINGUPDATA, STR_BACKINGUPDATA, max, 0))
                {
                    using (ZipOutputStream s = new ZipOutputStream(System.IO.File.Create(bi.BackupFile)))
                    {
                        s.SetLevel(9); // 0-9, 9 being the highest compression

                        foreach (FileInfo fi in fil)
                        {
                            ZipEntry entry = new ZipEntry(Path.GetFileName(fi.FullName));
                            entry.DateTime = DateTime.Now;
                            entry.Size = fi.Length;
                            s.PutNextEntry(entry);

                            using (FileStream fs = fi.OpenRead())
                            {
                                int i;
                                do
                                {
                                    i = fs.Read(buffer, 0, buffer.Length);
                                    if (i > 0)
                                    {
                                        s.Write(buffer, 0, i);
                                        processed += i;
                                    }

                                    if (DateTime.Now >= progUpdate)
                                    {
                                        int pos = (int)(processed / (1024 * 1024));
                                        prog.UpdateProgress(STR_BACKINGUPDATA, STR_BACKINGUPDATA, max, pos);
                                        progUpdate = DateTime.Now.AddSeconds(2);
                                    }
                                } while (i == buffer.Length);
                            }

                            if (DateTime.Now >= progUpdate)
                            {
                                int pos = (int)(processed / (1024 * 1024));
                                prog.UpdateProgress(STR_BACKINGUPDATA, STR_BACKINGUPDATA, max, pos);
                                progUpdate = DateTime.Now.AddSeconds(2);
                            }

                        }

                        s.Finish();
                        s.Close();
                    }
                }


                //check backup(s) te remove
                try
                {
                    if (Properties.Settings.Default.BackupKeepMaxDays > 0)
                    {
                        DateTime dt = DateTime.Now.AddDays(-1 * Properties.Settings.Default.BackupKeepMaxDays).Date;
                        List<BackupItem> bil = (from b in _backupItemList.BackupItems where b.BackupDate.Date < dt select b).ToList();
                        foreach (BackupItem b in bil)
                        {
                            if (File.Exists(b.BackupFile))
                            {
                                File.Delete(b.BackupFile);
                            }
                            _backupItemList.RemoveBackupItem(b);
                        }
                    }
                    if (Properties.Settings.Default.BackupKeepMaxCount > 0)
                    {
                        List<BackupItem> bil = (from b in _backupItemList.BackupItems where b.OriginalPath == bi.OriginalPath select b).OrderByDescending(x => x.BackupDate).Skip(Properties.Settings.Default.BackupKeepMaxCount-1).ToList();
                        foreach (BackupItem b in bil)
                        {
                            if (File.Exists(b.BackupFile))
                            {
                                File.Delete(b.BackupFile);
                            }
                            _backupItemList.RemoveBackupItem(b);
                        }
                    }
                }
                catch
                {
                }

                //save new backup info
                _backupItemList.AddBackupItem(bi);
                SaveBackupItemList();
            }
            finally
            {
                _fileCollection.EndReleaseForCopy();
            }
            return result;
        }
Beispiel #50
0
        public void ImporGCVotes(List<Core.Data.Geocache> gcList)
        {
            try
            {
                int max = gcList.Count;
                int pos = 0;
                int batch;
                StringBuilder wpList = new StringBuilder();
                string usrName = null;

                var ai = Core.ApplicationData.Instance.AccountInfos.GetAccountInfo("GC");
                if (ai != null)
                {
                    usrName = ai.AccountName;
                }
                if (string.IsNullOrEmpty(usrName))
                {
                    usrName = "uglyDUMMYusernamesolution";
                }
                using (Utils.ProgressBlock prog = new Utils.ProgressBlock("ImportingGCVotes", "ImportingGCVotes", max, pos, true))
                {
                    while (gcList.Count > 0)
                    {
                        wpList.Length = 0;
                        batch = 0;
                        while (batch < 200 && gcList.Count > 0)
                        {
                            if (batch > 0)
                            {
                                wpList.Append(",");
                            }
                            wpList.Append(gcList[0].Code);
                            gcList.RemoveAt(0);
                            pos++;
                            batch++;
                        }
                        string postData = String.Format("version=3.1b&userName={0}&waypoints={1}&password={2}", HttpUtility.UrlEncode(usrName), wpList.ToString(), ""); //"" => password: todo
                        System.Net.WebRequest webRequest = System.Net.WebRequest.Create("http://gcvote.com/getVotes.php") as System.Net.HttpWebRequest;
                        webRequest.Method = "POST";
                        webRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

                        string doc;
                        using (System.IO.StreamWriter requestWriter = new System.IO.StreamWriter(webRequest.GetRequestStream()))
                        {
                            requestWriter.Write(postData);
                        }
                        using (System.IO.StreamReader responseReader = new System.IO.StreamReader(webRequest.GetResponse().GetResponseStream()))
                        {
                            // and read the response
                            doc = responseReader.ReadToEnd();
                        }
                        /*
                            <votes userName='******' currentVersion='2.0c' securityState='locked' loggedIn='true'>
                            <vote userName='******' cacheId='26984595-b3a1-4aa2-9638-7612a3bf3d5f' voteMedian='4' voteAvg='3.75' voteCnt='4' voteUser='******' waypoint='GC12RBN' vote1='0' vote2='1' vote3='0' vote4='2' vote5='1' rawVotes='(2.0:1)(4.0:2)(5.0:1)'/>
                            <vote userName='******' cacheId='55d02838-01f6-4181-a080-517a3339ad40' voteMedian='4.5' voteAvg='4.0555555555556' voteCnt='9' voteUser='******' waypoint='GC12YQJ' vote1='1' vote2='0' vote3='1' vote4='3' vote5='4' rawVotes='(1.0:1)(3.0:1)(4.0:2)(4.5:1)(5.0:4)'/>
                            <vote userName='******' cacheId='562829a6-a111-4ccb-a511-76370b8005d2' voteMedian='3' voteAvg='2.7777777777778' voteCnt='9' voteUser='******' waypoint='GC135AX' vote1='1' vote2='1' vote3='7' vote4='0' vote5='0' rawVotes='(1.0:1)(2.5:1)(3.0:6)(3.5:1)'/>

                            <errorstring></errorstring>
                            </votes>
                         */
                        if (doc != null)
                        {
                                StringBuilder sb = new StringBuilder();
                                sb.AppendLine("<?xml version=\"1.0\"?>");
                                sb.Append(doc);

                                XmlDocument xmlDoc = new XmlDocument();
                                xmlDoc.LoadXml(sb.ToString());
                                XmlElement root = xmlDoc.DocumentElement;

                                XmlNodeList wpt = root.SelectNodes("vote");
                                if (wpt != null)
                                {
                                    foreach (XmlNode n in wpt)
                                    {
                                        double avg = Utils.Conversion.StringToDouble(n.Attributes["voteAvg"].Value);
                                        double median = Utils.Conversion.StringToDouble(n.Attributes["voteMedian"].Value);
                                        double? usrVote = Utils.Conversion.StringToDouble(n.Attributes["voteUser"].Value);
                                        int cnt = int.Parse(n.Attributes["voteCnt"].Value);
                                        string wp = n.Attributes["waypoint"].Value;
                                        if (usrVote <= 0.1)
                                        {
                                            usrVote = null;
                                        }

                                        Core.Settings.Default.SetGCVote(wp, median, avg, cnt, usrVote);
                                    }
                                }
                        }
                        else
                        {
                            Core.ApplicationData.Instance.Logger.AddLog(this, Core.Logger.Level.Error, "UnableToGetTheDataFromGCVoteCom");
                            break;
                        }
                        if (!prog.Update("ImportingGCVotes", max, pos))
                        {
                            break;
                        }
                        if (gcList.Count > 0)
                        {
                            //Thread.Sleep(500);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }
        }
        protected override void ImportMethod()
        {
            List<Utils.API.LiveV6.CacheNote> missingGeocaches = new List<Utils.API.LiveV6.CacheNote>();
            string errMessage = "";
            try
            {
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTING, 1, 0))
                {
                    //clear all notes
                    foreach (Framework.Data.Geocache gc in Core.Geocaches)
                    {
                        gc.PersonaleNote = "";
                    }

                    using (Utils.API.GeocachingLiveV6 client = new Utils.API.GeocachingLiveV6(Core, string.IsNullOrEmpty(Core.GeocachingComAccount.APIToken)))
                    {
                        int maxPerRequest = 100;
                        int startIndex = 0;
                        var resp = client.Client.GetUsersCacheNotes(client.Token, startIndex, maxPerRequest);
                        while (resp.Status.StatusCode == 0)
                        {
                            foreach (var n in resp.CacheNotes)
                            {
                                Framework.Data.Geocache gc = Utils.DataAccess.GetGeocache(Core.Geocaches, n.CacheCode);
                                if (gc != null)
                                {
                                    string s = n.Note ?? "";
                                    s = s.Replace("\r", "");
                                    s = s.Replace("\n", "\r\n");
                                    gc.PersonaleNote = s;
                                }
                                else
                                {
                                    missingGeocaches.Add(n);
                                }
                            }
                            if (resp.CacheNotes.Count() >= maxPerRequest)
                            {
                                startIndex += resp.CacheNotes.Count();
                                resp = client.Client.GetUsersCacheNotes(client.Token, startIndex, maxPerRequest);
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (resp.Status.StatusCode != 0)
                        {
                            if (!string.IsNullOrEmpty(resp.Status.StatusMessage))
                            {
                                errMessage = resp.Status.StatusMessage;
                            }
                        }
                    }
                }
                if (string.IsNullOrEmpty(errMessage) && missingGeocaches.Count > 0)
                {
                    List<string> gcList = (from a in missingGeocaches select a.CacheCode).ToList();
                    if (System.Windows.Forms.MessageBox.Show(string.Format("{0} {1}", missingGeocaches.Count, Utils.LanguageSupport.Instance.GetTranslation(Utils.LanguageSupport.Instance.GetTranslation(STR_IMPORTGEOCACHES))), Utils.LanguageSupport.Instance.GetTranslation(Utils.LanguageSupport.Instance.GetTranslation(STR_QUESTIONGEOCACHES)), System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTINGGEOCACHES, STR_IMPORTINGGEOCACHES, gcList.Count, 0, true))
                        {
                            int totalcount = gcList.Count;
                            using (Utils.API.GeocachingLiveV6 client = new Utils.API.GeocachingLiveV6(Core, string.IsNullOrEmpty(Core.GeocachingComAccount.APIToken)))
                            {
                                int index = 0;
                                int gcupdatecount;
                                TimeSpan interval = new TimeSpan(0, 0, 0, 2, 100);
                                DateTime prevCall = DateTime.MinValue;
                                bool dodelay;
                                gcupdatecount = 50;
                                dodelay = (gcList.Count > 30);
                                while (gcList.Count > 0)
                                {
                                    if (dodelay)
                                    {
                                        TimeSpan ts = DateTime.Now - prevCall;
                                        if (ts < interval)
                                        {
                                            Thread.Sleep(interval - ts);
                                        }
                                    }
                                    Utils.API.LiveV6.SearchForGeocachesRequest req = new Utils.API.LiveV6.SearchForGeocachesRequest();
                                    req.IsLite = Core.GeocachingComAccount.MemberTypeId == 1;
                                    req.AccessToken = client.Token;
                                    req.CacheCode = new 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)
                                    {
                                        Utils.API.Import.AddGeocaches(Core, resp.Geocaches);
                                    }
                                    else
                                    {
                                        errMessage = resp.Status.StatusMessage;
                                        break;
                                    }                                    
                                    if (!progress.UpdateProgress(STR_IMPORTINGGEOCACHES, STR_IMPORTINGGEOCACHES, totalcount, index))
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        foreach (var n in missingGeocaches)
                        {
                            Framework.Data.Geocache gc = Utils.DataAccess.GetGeocache(Core.Geocaches, n.CacheCode);
                            if (gc != null)
                            {
                                string s = n.Note ?? "";
                                s = s.Replace("\r", "");
                                s = s.Replace("\n", "\r\n");
                                gc.PersonaleNote = s;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                errMessage = e.Message;
            }
            if (!string.IsNullOrEmpty(errMessage))
            {
                System.Windows.Forms.MessageBox.Show(errMessage, Utils.LanguageSupport.Instance.GetTranslation(Utils.LanguageSupport.Instance.GetTranslation(STR_ERROR)), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            }
        }
Beispiel #52
0
        protected override void ExportMethod()
        {
            try
            {
                using (Utils.ProgressBlock fixscr = new Utils.ProgressBlock(this, STR_EXPORTINGGPX, STR_CREATINGFILE, 1, 0))
                {
                    System.Collections.Hashtable logTypes = new System.Collections.Hashtable();
                    logTypes.Add(2, "Found it");
                    logTypes.Add(3, "Didn't find it");
                    logTypes.Add(4, "Write note");
                    logTypes.Add(5, "Archive");
                    logTypes.Add(7, "Needs Archived");
                    logTypes.Add(9, "Will Attend");
                    logTypes.Add(10, "Attended");
                    logTypes.Add(11, "Webcam Photo Taken");
                    logTypes.Add(12, "Unarchive");
                    logTypes.Add(22, "Temporarily Disable Listing");
                    logTypes.Add(23, "Enable Listing");
                    logTypes.Add(24, "Publish Listing");
                    logTypes.Add(25, "Retract Listing");
                    logTypes.Add(45, "Needs Maintenance");
                    logTypes.Add(46, "Owner Maintenance");
                    logTypes.Add(47, "Update Coordinates");
                    logTypes.Add(68, "Post Reviewer Note");
                    logTypes.Add(74, "Announcement");

                    if (System.IO.File.Exists(_filename))
                    {
                        System.IO.File.Delete(_filename);
                    }

                    using (var strm = Assembly.GetExecutingAssembly().GetManifestResourceStream("GlobalcachingApplication.Plugins.Locus.sqlite.db3"))
                    {
                        byte[] data = new byte[strm.Length];
                        strm.Read(data, 0, data.Length);
                        File.WriteAllBytes(_filename, data);
                    }

                    SqliteConnection dbconFiles = null;
                    string basePath = null;
                    int imgFolderIndex = 0;
                    int imgInFolderCount = 0;
                    if (Properties.Settings.Default.ExportGrabbedImages)
                    {
                        basePath = System.IO.Path.GetDirectoryName(_filename);
                        basePath = System.IO.Path.Combine(basePath, ".GrabbedImages");
                        if (!System.IO.Directory.Exists(basePath))
                        {
                            System.IO.Directory.CreateDirectory(basePath);
                        }
                        if (Properties.Settings.Default.MaxFilesInFolder > 0)
                        {
                            string imgSubFolder = System.IO.Path.Combine(basePath, string.Format("batch{0}", imgFolderIndex));
                            while (System.IO.Directory.Exists(imgSubFolder))
                            {
                                imgFolderIndex++;
                                imgSubFolder = System.IO.Path.Combine(basePath, string.Format("batch{0}", imgFolderIndex));
                            }
                        }
                        dbconFiles = new SqliteConnection(string.Format("data source=file:{0}", System.IO.Path.Combine(basePath, "files.db3")));
                        dbconFiles.Open();
                        using (SqliteCommand cmd = new SqliteCommand("", dbconFiles))
                        {
                            cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='fdone'";
                            object o = cmd.ExecuteScalar();
                            if (o == null || o.GetType() == typeof(DBNull))
                            {
                                cmd.CommandText = "CREATE TABLE fdone (dlink text)";
                                cmd.ExecuteNonQuery();
                                cmd.CommandText = "CREATE INDEX ifdone on fdone (dlink)";
                                cmd.ExecuteNonQuery();
                            }

                            cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='files'";
                            o = cmd.ExecuteScalar();
                            if (o == null || o.GetType() == typeof(DBNull))
                            {
                                cmd.CommandText = "CREATE TABLE files (Link text collate nocase, Fname text collate nocase, Found integer)";
                                cmd.ExecuteNonQuery();
                                cmd.CommandText = "CREATE INDEX ilink on files (Link)";
                                cmd.ExecuteNonQuery();
                                cmd.CommandText = "CREATE INDEX ifname on files (Fname)";
                                cmd.ExecuteNonQuery();
                            }

                            cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='purge'";
                            o = cmd.ExecuteScalar();
                            if (o == null || o.GetType() == typeof(DBNull))
                            {
                                cmd.CommandText = "CREATE TABLE purge (pfile text)";
                                cmd.ExecuteNonQuery();
                            }
                        }
                    }


                    using (SqliteConnection dbcon = new SqliteConnection(string.Format("data source=file:{0}", _filename)))
                    {
                        dbcon.Open();

                        DbParameter par;
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_SAVING, STR_SAVINGGEOCACHES, _gcList.Count, 0))
                        {
                            using (SqliteCommand cmd = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd2 = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd3 = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd4 = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd5 = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd6 = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd7 = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd8 = new SqliteCommand("", dbcon))
                            {
                                cmd.CommandText = "drop index CachesSmart";
                                cmd.ExecuteNonQuery();

                                cmd.CommandText = "insert into Caches (Code, Name, PlacedBy, Archived, CacheId, CacheType, Container, Country, Difficulty, Found, HasCorrected, HasUserNote, Latitude, LongHtm, Longitude, OwnerName, PlacedDate, ShortHtm, State, Terrain, UserFlag, IsOwner, LatOriginal, LonOriginal, Status, GcNote, IsPremium, FavPoints) values (@Code, @Name, @PlacedBy, @Archived, @CacheId, @CacheType, @Container, @Country, @Difficulty, @Found, @HasCorrected, @HasUserNote, @Latitude, @LongHtm, @Longitude, @OwnerName, @PlacedDate, @ShortHtm, @State, @Terrain, @UserFlag, @IsOwner, @LatOriginal, @LonOriginal, @Status, @GcNote, @IsPremium, @FavPoints)";
                                cmd2.CommandText = "insert into CacheMemo (Code, LongDescription, ShortDescription, Url, Hints, UserNote) values (@Code, @LongDescription, @ShortDescription, @Url, @Hints, @UserNote)";
                                cmd3.CommandText = "insert into Attributes (aCode, aId, aInc) values (@aCode, @aId, @aInc)";
                                cmd4.CommandText = "insert into LogMemo (lParent, lLogId, lText) values (@lParent, @lLogId, @lText)";
                                cmd5.CommandText = "insert into Logs (lParent, lLogId, lType, lBy, lDate, lLat, lLon, lEncoded, lownerid, lHasHtml, lIsowner, lTime) values (@lParent, @lLogId, @lType, @lBy, @lDate, @lLat, @lLon, @lEncoded, @lownerid, @lHasHtml, @lIsowner, @lTime)";
                                cmd6.CommandText = "insert into WayMemo (cParent, cCode, cComment, cUrl) values (@cParent, @cCode, @cComment, @cUrl)";
                                cmd7.CommandText = "insert into Waypoints (cParent, cCode, cPrefix, cName, cType, cLat, cLon, cByuser, cDate, cFlag, sB1) values (@cParent, @cCode, @cPrefix, @cName, @cType, @cLat, @cLon, @cByuser, @cDate, @cFlag, @sB1)";
                                cmd8.CommandText = "insert into Corrected (kCode, kBeforeLat, kBeforeLon, kAfterLat, kAfterLon) values (@kCode, @kBeforeLat, @kBeforeLon, @kAfterLat, @kAfterLon)";

                                par = cmd8.CreateParameter();
                                par.ParameterName = "@kCode";
                                par.DbType = DbType.String;
                                cmd8.Parameters.Add(par);
                                par = cmd8.CreateParameter();
                                par.ParameterName = "@kBeforeLat";
                                par.DbType = DbType.String;
                                cmd8.Parameters.Add(par);
                                par = cmd8.CreateParameter();
                                par.ParameterName = "@kBeforeLon";
                                par.DbType = DbType.String;
                                cmd8.Parameters.Add(par);
                                par = cmd8.CreateParameter();
                                par.ParameterName = "@kAfterLat";
                                par.DbType = DbType.String;
                                cmd8.Parameters.Add(par);
                                par = cmd8.CreateParameter();
                                par.ParameterName = "@kAfterLon";
                                par.DbType = DbType.String;
                                cmd8.Parameters.Add(par);

                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cParent";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cCode";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cPrefix";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cName";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cType";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cLat";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cLon";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cByuser";
                                par.DbType = DbType.Boolean;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cDate";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cFlag";
                                par.DbType = DbType.Boolean;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@sB1";
                                par.DbType = DbType.Boolean;
                                cmd7.Parameters.Add(par);

                                par = cmd6.CreateParameter();
                                par.ParameterName = "@cParent";
                                par.DbType = DbType.String;
                                cmd6.Parameters.Add(par);
                                par = cmd6.CreateParameter();
                                par.ParameterName = "@cCode";
                                par.DbType = DbType.String;
                                cmd6.Parameters.Add(par);
                                par = cmd6.CreateParameter();
                                par.ParameterName = "@cComment";
                                par.DbType = DbType.String;
                                cmd6.Parameters.Add(par);
                                par = cmd6.CreateParameter();
                                par.ParameterName = "@cUrl";
                                par.DbType = DbType.String;
                                cmd6.Parameters.Add(par);

                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lParent";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lLogId";
                                par.DbType = DbType.Int32;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lType";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lBy";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lDate";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lLat";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lLon";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lEncoded";
                                par.DbType = DbType.Boolean;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lownerid";
                                par.DbType = DbType.Int32;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lHasHtml";
                                par.DbType = DbType.Boolean;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lIsowner";
                                par.DbType = DbType.Boolean;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lTime";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);

                                par = cmd4.CreateParameter();
                                par.ParameterName = "@lParent";
                                par.DbType = DbType.String;
                                cmd4.Parameters.Add(par);
                                par = cmd4.CreateParameter();
                                par.ParameterName = "@lLogId";
                                par.DbType = DbType.Int32;
                                cmd4.Parameters.Add(par);
                                par = cmd4.CreateParameter();
                                par.ParameterName = "@lText";
                                par.DbType = DbType.String;
                                cmd4.Parameters.Add(par);

                                par = cmd3.CreateParameter();
                                par.ParameterName = "@aCode";
                                par.DbType = DbType.String;
                                cmd3.Parameters.Add(par);
                                par = cmd3.CreateParameter();
                                par.ParameterName = "@aId";
                                par.DbType = DbType.Int32;
                                cmd3.Parameters.Add(par);
                                par = cmd3.CreateParameter();
                                par.ParameterName = "@aInc";
                                par.DbType = DbType.Int32;
                                cmd3.Parameters.Add(par);

                                par = cmd2.CreateParameter();
                                par.ParameterName = "@Code";
                                par.DbType = DbType.String;
                                cmd2.Parameters.Add(par);
                                par = cmd2.CreateParameter();
                                par.ParameterName = "@LongDescription";
                                par.DbType = DbType.String;
                                cmd2.Parameters.Add(par);
                                par = cmd2.CreateParameter();
                                par.ParameterName = "@ShortDescription";
                                par.DbType = DbType.String;
                                cmd2.Parameters.Add(par);
                                par = cmd2.CreateParameter();
                                par.ParameterName = "@Url";
                                par.DbType = DbType.String;
                                cmd2.Parameters.Add(par);
                                par = cmd2.CreateParameter();
                                par.ParameterName = "@Hints";
                                par.DbType = DbType.String;
                                cmd2.Parameters.Add(par);
                                par = cmd2.CreateParameter();
                                par.ParameterName = "@UserNote";
                                par.DbType = DbType.String;
                                cmd2.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 = "@PlacedBy";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Archived";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@CacheId";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@CacheType";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Container";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Country";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Difficulty";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Found";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@HasCorrected";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@HasUserNote";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Latitude";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@LongHtm";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Longitude";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@OwnerName";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@PlacedDate";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@ShortHtm";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@State";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Terrain";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@UserFlag";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@IsOwner";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@LatOriginal";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@LonOriginal";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Status";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@GcNote";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@IsPremium";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@FavPoints";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);

                                cmd.Prepare();
                                cmd2.Prepare();
                                cmd3.Prepare();
                                cmd4.Prepare();
                                cmd5.Prepare();
                                cmd6.Prepare();
                                cmd7.Prepare();
                                cmd8.Prepare();

                                //using (DbTransaction trans = dbcon.BeginTransaction())
                                //{
                                int index = 0;
                                int procStep = 0;
                                foreach (Framework.Data.Geocache gc in _gcList)
                                {
                                    string notes = "";
                                    if (!string.IsNullOrEmpty(gc.Notes))
                                    {
                                        notes = System.Web.HttpUtility.HtmlDecode(gc.Notes);
                                    }
                                    if (!string.IsNullOrEmpty(gc.PersonaleNote))
                                    {
                                        notes = string.Concat(notes, gc.PersonaleNote);
                                    }

                                    cmd2.Parameters["@Code"].Value = gc.Code;
                                    cmd2.Parameters["@LongDescription"].Value = gc.LongDescription ?? "";
                                    cmd2.Parameters["@ShortDescription"].Value = gc.ShortDescription ?? "";
                                    cmd2.Parameters["@Url"].Value = gc.Url ?? "";
                                    cmd2.Parameters["@Hints"].Value = gc.EncodedHints ?? "";
                                    cmd2.Parameters["@UserNote"].Value = notes;

                                    cmd.Parameters["@Code"].Value = gc.Code;
                                    cmd.Parameters["@Name"].Value = gc.Name ?? "";
                                    cmd.Parameters["@PlacedBy"].Value = gc.PlacedBy ?? "";
                                    cmd.Parameters["@Archived"].Value = gc.Archived ? 1 : 0;
                                    cmd.Parameters["@CacheId"].Value = gc.ID ?? "1";
                                    cmd.Parameters["@CacheType"].Value = getCacheType(gc.GeocacheType);
                                    cmd.Parameters["@Container"].Value = getContainer(gc.Container);
                                    cmd.Parameters["@Country"].Value = gc.Country ?? "";
                                    cmd.Parameters["@Difficulty"].Value = gc.Difficulty;
                                    cmd.Parameters["@Found"].Value = gc.Found ? 1 : 0;
                                    cmd.Parameters["@HasCorrected"].Value = (gc.CustomCoords || gc.ContainsCustomLatLon) ? 1 : 0;
                                    cmd.Parameters["@HasUserNote"].Value = gc.ContainsNote ? 1 : 0;
                                    cmd.Parameters["@LatOriginal"].Value = gc.Lat.ToString().Replace(',', '.');
                                    cmd.Parameters["@LonOriginal"].Value = gc.Lon.ToString().Replace(',', '.');
                                    if (gc.ContainsCustomLatLon)
                                    {
                                        cmd.Parameters["@Latitude"].Value = gc.CustomLat.ToString().Replace(',', '.');
                                        cmd.Parameters["@Longitude"].Value = gc.CustomLon.ToString().Replace(',', '.');
                                    }
                                    else
                                    {
                                        cmd.Parameters["@Latitude"].Value = gc.Lat.ToString().Replace(',', '.');
                                        cmd.Parameters["@Longitude"].Value = gc.Lon.ToString().Replace(',', '.');
                                    }
                                    cmd.Parameters["@LongHtm"].Value = gc.LongDescriptionInHtml ? 1 : 0;
                                    cmd.Parameters["@OwnerName"].Value = gc.Owner ?? "";
                                    cmd.Parameters["@PlacedDate"].Value = gc.PublishedTime.ToString("yyyy-MM-dd");
                                    cmd.Parameters["@ShortHtm"].Value = gc.ShortDescriptionInHtml ? 1 : 0;
                                    cmd.Parameters["@State"].Value = gc.State ?? "";
                                    cmd.Parameters["@Terrain"].Value = gc.Terrain;
                                    cmd.Parameters["@UserFlag"].Value = gc.Flagged ? 1 : 0;
                                    cmd.Parameters["@IsOwner"].Value = gc.IsOwn ? 1 : 0;
                                    cmd.Parameters["@Status"].Value = gc.Available ? "A" : gc.Archived ? "X" : "T";
                                    cmd.Parameters["@GcNote"].Value = notes;
                                    cmd.Parameters["@IsPremium"].Value = gc.MemberOnly ? 1 : 0;
                                    cmd.Parameters["@FavPoints"].Value = gc.Favorites;

                                    cmd.ExecuteNonQuery();
                                    cmd2.ExecuteNonQuery();

                                    if (gc.ContainsCustomLatLon)
                                    {
                                        cmd8.Parameters["@kCode"].Value = gc.Code;
                                        cmd8.Parameters["@kBeforeLat"].Value = gc.Lat.ToString().Replace(',', '.');
                                        cmd8.Parameters["@kBeforeLon"].Value = gc.Lon.ToString().Replace(',', '.');
                                        cmd8.Parameters["@kAfterLat"].Value = gc.CustomLat.ToString().Replace(',', '.');
                                        cmd8.Parameters["@kAfterLon"].Value = gc.CustomLon.ToString().Replace(',', '.');

                                        cmd8.ExecuteNonQuery();
                                    }

                                    List<int> attr = gc.AttributeIds;
                                    foreach (int att in attr)
                                    {
                                        cmd3.Parameters["@aCode"].Value = gc.Code;
                                        cmd3.Parameters["@aId"].Value = Math.Abs(att);
                                        cmd3.Parameters["@aInc"].Value = att < 0 ? 0 : 1;

                                        cmd3.ExecuteNonQuery();
                                    }

                                    List<Framework.Data.Log> logs = Utils.DataAccess.GetLogs(Core.Logs, gc.Code).Take(Properties.Settings.Default.MaxLogs).ToList();
                                    foreach (Framework.Data.Log l in logs)
                                    {
                                        try
                                        {
                                            int logid = 0;
                                            if (!int.TryParse(l.ID, out logid))
                                            {
                                                logid = Utils.Conversion.GetCacheIDFromCacheCode(l.ID);
                                            }
                                            cmd4.Parameters["@lLogId"].Value = logid;
                                            cmd4.Parameters["@lText"].Value = l.Text ?? "";
                                            cmd4.Parameters["@lParent"].Value = gc.Code;
                                            cmd4.ExecuteNonQuery();

                                            cmd5.Parameters["@lLogId"].Value = logid;
                                            cmd5.Parameters["@lParent"].Value = gc.Code;
                                            object o = logTypes[l.LogType.ID];
                                            if (o == null)
                                            {
                                                cmd5.Parameters["@lType"].Value = 4;
                                            }
                                            else
                                            {
                                                cmd5.Parameters["@lType"].Value = (string)o;
                                            }
                                            cmd5.Parameters["@lBy"].Value = l.Finder ?? "";
                                            cmd5.Parameters["@lDate"].Value = l.Date.ToString("yyyy-MM-dd HH:mm:ss");
                                            cmd5.Parameters["@lLat"].Value = DBNull.Value;
                                            cmd5.Parameters["@lLon"].Value = DBNull.Value;
                                            cmd5.Parameters["@lEncoded"].Value = l.Encoded;
                                            try
                                            {
                                                cmd5.Parameters["@lownerid"].Value = int.Parse(l.FinderId);
                                            }
                                            catch
                                            {
                                            }
                                            cmd5.Parameters["@lHasHtml"].Value = false;
                                            cmd5.Parameters["@lIsowner"].Value = (l.Finder == Core.GeocachingAccountNames.GetAccountName(gc.Code));
                                            cmd5.Parameters["@lTime"].Value = "";

                                            cmd5.ExecuteNonQuery();

                                        }
                                        catch
                                        {
                                        }
                                    }

                                    List<Framework.Data.Waypoint> wps = Utils.DataAccess.GetWaypointsFromGeocache(Core.Waypoints, gc.Code);
                                    foreach (Framework.Data.Waypoint w in wps)
                                    {
                                        try
                                        {
                                            cmd6.Parameters["@cParent"].Value = gc.Code;
                                            cmd6.Parameters["@cCode"].Value = w.Code;
                                            cmd6.Parameters["@cComment"].Value = w.Comment;
                                            cmd6.Parameters["@cUrl"].Value = w.Url;

                                            cmd7.Parameters["@cParent"].Value = gc.Code;
                                            cmd7.Parameters["@cCode"].Value = w.Code;
                                            cmd7.Parameters["@cPrefix"].Value = w.Code.Substring(0, 2);
                                            cmd7.Parameters["@cName"].Value = w.Name ?? "";
                                            cmd7.Parameters["@cType"].Value = getWPType(w.WPType);
                                            cmd7.Parameters["@cLat"].Value = w.Lat == null ? "0.0" : w.Lat.ToString().Replace(',', '.');
                                            cmd7.Parameters["@cLon"].Value = w.Lon == null ? "0.0" : w.Lon.ToString().Replace(',', '.');
                                            cmd7.Parameters["@cByuser"].Value = false;
                                            cmd7.Parameters["@cDate"].Value = w.Time.ToString("yyyy-MM-dd");
                                            cmd7.Parameters["@cFlag"].Value = false;
                                            cmd7.Parameters["@sB1"].Value = false;

                                            cmd7.ExecuteNonQuery();
                                            cmd6.ExecuteNonQuery();
                                        }
                                        catch
                                        {
                                        }
                                    }

                                    if (dbconFiles != null && (gc.LongDescriptionInHtml || gc.ShortDescriptionInHtml))
                                    {
                                        try
                                        {
                                            List<string> linksInDescr = Utils.ImageSupport.GetImageUrlsFromGeocache(gc);
                                            foreach (string link in linksInDescr)
                                            {

                                                string p = Utils.ImageSupport.Instance.GetImagePath(link);
                                                if (!string.IsNullOrEmpty(p) && IsLocalFile(p))
                                                {
                                                    using (SqliteCommand filescmd = new SqliteCommand("", dbconFiles))
                                                    {
                                                        filescmd.CommandText = string.Format("SELECT Fname FROM files WHERE Link='{0}'", link.Replace("'", "''"));
                                                        object o = filescmd.ExecuteScalar();
                                                        if (o == null || o.GetType() == typeof(DBNull))
                                                        {
                                                            filescmd.CommandText = string.Format("insert into files (Link, Fname, Found) values ('{0}', '{1}', 1)", link.Replace("'", "''"), System.IO.Path.GetFileName(p).Replace("'", "''"));
                                                            filescmd.ExecuteNonQuery();
                                                        }
                                                    }
                                                    if (Properties.Settings.Default.MaxFilesInFolder > 0)
                                                    {
                                                        imgInFolderCount++;
                                                        if (imgInFolderCount > Properties.Settings.Default.MaxFilesInFolder)
                                                        {
                                                            imgFolderIndex++;
                                                            imgInFolderCount = 1;
                                                        }
                                                        string imgSubFolder = System.IO.Path.Combine(basePath, string.Format("batch{0}", imgFolderIndex));
                                                        if (imgInFolderCount == 1)
                                                        {
                                                            if (!System.IO.Directory.Exists(imgSubFolder))
                                                            {
                                                                System.IO.Directory.CreateDirectory(imgSubFolder);
                                                            }
                                                        }
                                                        string dst = System.IO.Path.Combine(imgSubFolder, System.IO.Path.GetFileName(p));
                                                        if (!System.IO.File.Exists(dst))
                                                        {
                                                            System.IO.File.Copy(p, dst, true);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        string dst = System.IO.Path.Combine(basePath, System.IO.Path.GetFileName(p));
                                                        if (!System.IO.File.Exists(dst))
                                                        {
                                                            System.IO.File.Copy(p, dst, true);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        catch
                                        {
                                        }

                                    }

                                    index++;
                                    procStep++;
                                    if (procStep >= 200)
                                    {
                                        progress.UpdateProgress(STR_SAVING, STR_SAVINGGEOCACHES, _gcList.Count, index);
                                        procStep = 0;
                                    }
                                }
                                //trans.Commit();
                            }
                        }
                    }
                    if (dbconFiles != null)
                    {
                        dbconFiles.Dispose();
                        dbconFiles = null;
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, Utils.LanguageSupport.Instance.GetTranslation(Utils.LanguageSupport.Instance.GetTranslation(STR_ERROR)), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #53
0
        private void runFlow(ActionFlow flow)
        {
            try
            {
                foreach (ActionImplementation ai in flow.Actions)
                {
                    ai.PrepareRun();
                }
                //find start and run
                ActionStart startAction = (from a in flow.Actions where a is ActionStart select a).FirstOrDefault() as ActionStart;
                List<Core.Data.Geocache> gcList = startAction.PrepareFlow();

                DateTime nextUpdate = DateTime.Now.AddSeconds(1);
                int index = 0;
                bool canceled = false;
                using (Utils.ProgressBlock prog = new Utils.ProgressBlock("ActionBuilder", "Executing", gcList.Count, 0, true))
                {
                    foreach (Core.Data.Geocache gc in gcList)
                    {
                        startAction.Run(gc);
                        index++;
                        if (DateTime.Now>=nextUpdate)
                        {
                            if (!prog.Update("Executing", gcList.Count, index))
                            {
                                canceled = true;
                                break;
                            }
                            nextUpdate = DateTime.Now.AddSeconds(1);
                        }
                    }
                }

                if (!canceled)
                {
                    //wrap up
                    foreach (ActionImplementation ai in flow.Actions)
                    {
                        ai.FinalizeRun();
                    }
                }
            }
            catch (Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }
        }
Beispiel #54
0
 protected override void ImportMethod()
 {
     using (Utils.ProgressBlock fixpr = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTINGDATA, _filenames.Length, 0))
     {
         for (int fileindex = 0; fileindex < _filenames.Length; fileindex++)
         {
             Utils.GPXProcessor gpxProcessor = new Utils.GPXProcessor(Core);
             Utils.GPXProcessor.ResultData res = gpxProcessor.ProcessGeocachingComGPXFile(_filenames[fileindex]);
             List<string> ignoredGeocaches = new List<string>();
             List<string> ignoredLogs = new List<string>();
             if (res != null && res.Geocaches.Count > 0)
             {
                 using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTINGGEOCACHES, res.Geocaches.Count, 0))
                 {
                     int index = 0;
                     int procStep = 0;
                     foreach (Framework.Data.Geocache gc in res.Geocaches)
                     {
                         if (!AddGeocache(gc, gpxProcessor.CachesGPXVersion))
                         {
                             ignoredGeocaches.Add(gc.Code);
                         }
                         index++;
                         procStep++;
                         if (procStep >= 100)
                         {
                             progress.UpdateProgress(STR_IMPORTING, STR_IMPORTINGGEOCACHES, res.Geocaches.Count, index);
                             procStep = 0;
                         }
                     }
                 }
             }
             if (res != null && res.Waypoints.Count > 0)
             {
                 using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTINGWAYPOINTS, res.Geocaches.Count, 0))
                 {
                     int index = 0;
                     int procStep = 0;
                     foreach (Framework.Data.Waypoint wp in res.Waypoints)
                     {
                         if (!ignoredGeocaches.Contains(wp.GeocacheCode))
                         {
                             AddWaypoint(wp);
                         }
                         index++;
                         procStep++;
                         if (procStep >= 200)
                         {
                             progress.UpdateProgress(STR_IMPORTING, STR_IMPORTINGWAYPOINTS, res.Waypoints.Count, index);
                             procStep = 0;
                         }
                     }
                 }
             }
             if (res != null && res.Logs.Count > 0)
             {
                 using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTINGLOGS, res.Logs.Count, 0))
                 {
                     int index = 0;
                     int procStep = 0;
                     foreach (Framework.Data.Log l in res.Logs)
                     {
                         if (!ignoredGeocaches.Contains(l.GeocacheCode))
                         {
                             AddLog(l);
                         }
                         else
                         {
                             ignoredLogs.Add(l.ID);
                         }
                         index++;
                         procStep++;
                         if (procStep >= 500)
                         {
                             progress.UpdateProgress(STR_IMPORTING, STR_IMPORTINGLOGS, res.Logs.Count, index);
                             procStep = 0;
                         }
                     }
                 }
             }
             if (res != null && res.LogImages.Count > 0)
             {
                 using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTINGLOGIMAGES, res.LogImages.Count, 0))
                 {
                     int index = 0;
                     int procStep = 0;
                     foreach (Framework.Data.LogImage l in res.LogImages)
                     {
                         if (!ignoredLogs.Contains(l.LogID))
                         {
                             AddLogImage(l);
                         }
                         index++;
                         procStep++;
                         if (procStep >= 100)
                         {
                             progress.UpdateProgress(STR_IMPORTING, STR_IMPORTINGLOGIMAGES, res.LogImages.Count, index);
                             procStep = 0;
                         }
                     }
                 }
             }
             fixpr.UpdateProgress(STR_IMPORTING, STR_IMPORTINGDATA, _filenames.Length, fileindex + 1);
         }
     }
 }
Beispiel #55
0
        protected override void ExportMethod()
        {
            using (ZipOutputStream s = new ZipOutputStream(System.IO.File.Create(_filename)))
            {
                s.SetLevel(9); // 0-9, 9 being the highest compression
                s.UseZip64 = UseZip64.Off;

                DateTime dt = DateTime.Now.AddSeconds(2);
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_EXPORTINGGPX, STR_CREATINGFILE, _gcList.Count, 0))
                {
                    int totalGeocaches = _gcList.Count;
                    int totalProcessed = 0;
                    int fileIndex = 1;
                    int geocacheIndex = 0;
                    int gpxSizeLimit = 4500000; //appr. 4.5MB

                    XmlDocument doc = new XmlDocument();
                    XmlDeclaration pi = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
                    doc.InsertBefore(pi, doc.DocumentElement);
                    XmlElement root = doc.CreateElement("ggz");
                    doc.AppendChild(root);
                    XmlAttribute attr = doc.CreateAttribute("xmlns");
                    XmlText txt = doc.CreateTextNode("http://www.opencaching.com/xmlschemas/ggz/1/0");
                    attr.AppendChild(txt);
                    root.Attributes.Append(attr);

                    XmlElement el = doc.CreateElement("time");
                    txt = doc.CreateTextNode(string.Format("{0}Z", DateTime.Now.ToUniversalTime().ToString("s")));
                    el.AppendChild(txt);
                    root.AppendChild(el);

                    //Utils.Crc16 crc16 = new Utils.Crc16();

                    while (_gcList.Count>0)
                    {
                        XmlElement elFile = doc.CreateElement("file");
                        root.AppendChild(elFile);

                        el = doc.CreateElement("name");
                        txt = doc.CreateTextNode(string.Format("{0}_{1}.gpx", System.IO.Path.GetFileNameWithoutExtension(_filename), fileIndex));
                        el.AppendChild(txt);
                        elFile.AppendChild(el);

                        XmlElement elCRC = doc.CreateElement("crc");
                        elFile.AppendChild(elCRC);

                        el = doc.CreateElement("time");
                        txt = doc.CreateTextNode(string.Format("{0}Z", DateTime.Now.ToUniversalTime().ToString("s")));
                        el.AppendChild(txt);
                        elFile.AppendChild(el);

                        //create GPX wpt entries until max size is reached
                        List<Framework.Data.Geocache> gpxBatchList = new List<Framework.Data.Geocache>();
                        List<GeocacheEntryInfo> geiList = new List<GeocacheEntryInfo>();
                        geocacheIndex = 0;
                        _gpxGenerator.SetGeocacheList(_gcList);
                        StringBuilder sb = new StringBuilder();
                        _gpxGenerator.Start();
                        while (sb.Length < gpxSizeLimit && geocacheIndex < _gpxGenerator.Count)
                        {
                            gpxBatchList.Add(_gcList[geocacheIndex]);
                            string gpxText = _gpxGenerator.Next();

                            GeocacheEntryInfo gei = new GeocacheEntryInfo();
                            gei.GC = _gcList[geocacheIndex];
                            gei.FileLen = System.Text.UTF8Encoding.UTF8.GetBytes(gpxText).Length + 2;
                            geiList.Add(gei);

                            sb.AppendLine(gpxText);

                            totalProcessed++;
                            geocacheIndex++;

                            if (DateTime.Now >= dt)
                            {
                                progress.UpdateProgress(STR_EXPORTINGGPX, STR_CREATINGFILE, totalGeocaches, totalProcessed);
                                dt = DateTime.Now.AddSeconds(2);
                            }
                        }
                        sb.AppendLine(_gpxGenerator.Finish());
                        //insert gpx header
                        _gpxGenerator.SetGeocacheList(gpxBatchList);
                        string gpxHeader = _gpxGenerator.Start();
                        sb.Insert(0, gpxHeader);
                        _gcList.RemoveRange(0, gpxBatchList.Count);

                        //add gpx to zip
                        byte[] data;
                        using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                        {
                            using (System.IO.StreamWriter sw = System.IO.File.CreateText(tmp.Path))
                            {
                                sw.Write(sb.ToString());
                            }
                            data = File.ReadAllBytes(tmp.Path);
                        }
                        string fn = string.Format("data/{0}_{1}.gpx", System.IO.Path.GetFileNameWithoutExtension(_filename), fileIndex);
                        ZipEntry entry = new ZipEntry(fn);
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);
                        s.Write(data, 0, data.Length);

                        Crc32 crc = new Crc32();
                        crc.Update(data);
                        //txt = doc.CreateTextNode(crc16.ComputeChecksum(data).ToString("X8"));
                        txt = doc.CreateTextNode(crc.Value.ToString("X8"));
                        elCRC.AppendChild(txt);

                        int curPos = System.Text.UTF8Encoding.UTF8.GetBytes(gpxHeader).Length;
                        for (int i = 0; i < geiList.Count; i++ )
                        {
                            GeocacheEntryInfo gei = geiList[i];

                            XmlElement chgEl = doc.CreateElement("gch");
                            elFile.AppendChild(chgEl);

                            el = doc.CreateElement("code");
                            txt = doc.CreateTextNode(gei.GC.Code ?? "");
                            el.AppendChild(txt);
                            chgEl.AppendChild(el);

                            el = doc.CreateElement("name");
                            txt = doc.CreateTextNode(_gpxGenerator.validateXml(gei.GC.Name ?? ""));
                            el.AppendChild(txt);
                            chgEl.AppendChild(el);

                            el = doc.CreateElement("type");
                            txt = doc.CreateTextNode(gei.GC.GeocacheType.GPXTag);
                            el.AppendChild(txt);
                            chgEl.AppendChild(el);

                            el = doc.CreateElement("lat");
                            if (gei.GC.ContainsCustomLatLon)
                            {
                                txt = doc.CreateTextNode(gei.GC.CustomLat.ToString().Replace(',', '.'));
                            }
                            else
                            {
                                txt = doc.CreateTextNode(gei.GC.Lat.ToString().Replace(',', '.'));
                            }
                            el.AppendChild(txt);
                            chgEl.AppendChild(el);

                            el = doc.CreateElement("lon");
                            if (gei.GC.ContainsCustomLatLon)
                            {
                                txt = doc.CreateTextNode(gei.GC.CustomLon.ToString().Replace(',', '.'));
                            }
                            else
                            {
                                txt = doc.CreateTextNode(gei.GC.Lon.ToString().Replace(',', '.'));
                            }
                            el.AppendChild(txt);
                            chgEl.AppendChild(el);

                            el = doc.CreateElement("file_pos");
                            txt = doc.CreateTextNode(curPos.ToString());
                            curPos += gei.FileLen;
                            el.AppendChild(txt);
                            chgEl.AppendChild(el);

                            el = doc.CreateElement("file_len");
                            txt = doc.CreateTextNode(gei.FileLen.ToString());
                            el.AppendChild(txt);
                            chgEl.AppendChild(el);

                            XmlElement ratingsEl = doc.CreateElement("ratings");
                            chgEl.AppendChild(ratingsEl);

                            el = doc.CreateElement("awesomeness");
                            txt = doc.CreateTextNode("3.0");
                            el.AppendChild(txt);
                            ratingsEl.AppendChild(el);

                            el = doc.CreateElement("difficulty");
                            txt = doc.CreateTextNode(gei.GC.Difficulty.ToString("0.#").Replace(',', '.'));
                            el.AppendChild(txt);
                            ratingsEl.AppendChild(el);

                            el = doc.CreateElement("size");
                            switch (gei.GC.Container.ID)
                            {
                                case 1:
                                    txt = doc.CreateTextNode("2.0");
                                    break;
                                case 5:
                                    txt = doc.CreateTextNode("2.0");
                                    break;
                                case 6:
                                    txt = doc.CreateTextNode("2.0");
                                    break;
                                case 2:
                                    txt = doc.CreateTextNode("2.0");
                                    break;
                                case 3:
                                    txt = doc.CreateTextNode("4.0");
                                    break;
                                case 4:
                                    txt = doc.CreateTextNode("5.0");
                                    break;
                                case 8:
                                    txt = doc.CreateTextNode("3.0");
                                    break;
                                default:
                                    txt = doc.CreateTextNode("3.0");
                                    break;
                            }
                            el.AppendChild(txt);
                            ratingsEl.AppendChild(el);

                            el = doc.CreateElement("terrain");
                            txt = doc.CreateTextNode(gei.GC.Terrain.ToString("0.#").Replace(',', '.'));
                            el.AppendChild(txt);
                            ratingsEl.AppendChild(el);

                            if (gei.GC.Found)
                            {
                                el = doc.CreateElement("found");
                                txt = doc.CreateTextNode("true");
                                el.AppendChild(txt);
                                chgEl.AppendChild(el);
                            }
                        }

                        fileIndex++;
                    }

                    //add index file
                    // index\com\garmin\geocaches\v0\index.xml
                    /*
                    <gch>
                      <code>GC12345</code>
                      <name>Cache name</name>
                      <type>Traditional Cache</type>
                      <lat>33.550217</lat>
                      <lon>-117.660617</lon>
                      <file_pos>5875</file_pos>
                      <file_len>5783</file_len>
                      <ratings>
                         <awesomeness>3.0</awesomeness>
                         <difficulty>1.5</difficulty>
                         <size>5.0</size>
                         <terrain>1.5</terrain>
                      </ratings>
                      <found>true</found>
                    </gch>
                     * 
                     1 = Nano (not supported, unfortunately, by GC.com yet)
                    2 = Micro
                    3 = Small
                    4 = Regular
                    5 = Large 
                     * 
                     */
                    using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                    {
                        using (TextWriter sw = new StreamWriter(tmp.Path, false, Encoding.UTF8)) //Set encoding
                        {
                            doc.Save(sw);
                        }
                        byte[] data = File.ReadAllBytes(tmp.Path);
                        ZipEntry entry = new ZipEntry("index/com/garmin/geocaches/v0/index.xml");
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);
                        s.Write(data, 0, data.Length);
                    }

                    s.Finish();
                    s.Close();
                }
            }
        }
Beispiel #56
0
        public void LoadGCVoteDataThreadMethod()
        {
            try
            {
                using (Utils.ProgressBlock prog = new Utils.ProgressBlock(_activePlugin,Import.STR_IMPORT,Import.STR_IMPORT,_availableWaypoints.Count,0))
                {
                    int pos = 0;
                    DbDataReader dr = _dbcon.ExecuteReader("select Waypoint, VoteAvg, VoteCnt, VoteUser from votes");
                    while (dr.Read())
                    {
                        pos++;
                        string wp = (string)dr["Waypoint"];
                        Framework.Data.Geocache gc = Utils.DataAccess.GetGeocache(_core.Geocaches, wp);
                        if (gc != null)
                        {
                            double avg = (double)dr["VoteAvg"];
                            double usrVote = (double)dr["VoteUser"];
                            int cnt = (int)dr["VoteCnt"];

                            bool saved = gc.Saved;
                            if (usrVote > 0.1)
                            {
                                gc.SetCustomAttribute(Import.CUSTOM_ATTRIBUTE, string.Format("{0:0.0}/{1} ({2:0.0})", avg, cnt, usrVote));
                            }
                            else
                            {
                                gc.SetCustomAttribute(Import.CUSTOM_ATTRIBUTE, string.Format("{0:0.0}/{1}", avg, cnt));
                            }
                            gc.Saved = saved;
                            if (pos % 500 == 0)
                            {
                                prog.UpdateProgress(Import.STR_IMPORT, Import.STR_IMPORT, _availableWaypoints.Count, pos);
                            }
                        }
                    }
                }
            }
            catch
            {
            }
            _actionDone.Set();
        }
Beispiel #57
0
 private void getCopiedSelectionGeocacheInbackgroundMethod()
 {
     try
     {
         int max = _importGeocaches.Count;
         using (Utils.ProgressBlock prog = new Utils.ProgressBlock(OwnerPlugin as Utils.BasePlugin.Plugin, STR_COPYSELECTION, STR_RETRIEVING, max, 0, true))
         {
             using (Utils.API.GeocachingLiveV6 client = new Utils.API.GeocachingLiveV6(Core, string.IsNullOrEmpty(Core.GeocachingComAccount.APIToken)))
             {
                 var req = new Utils.API.LiveV6.SearchForGeocachesRequest();
                 req.AccessToken = client.Token;
                 while (_importGeocaches.Count > 0)
                 {
                     req.CacheCode = new Utils.API.LiveV6.CacheCodeFilter();
                     req.CacheCode.CacheCodes = (from gc in _importGeocaches select gc).Take(10).ToArray();
                     req.GeocacheLogCount = 5;
                     req.IsLite = Core.GeocachingComAccount.MemberTypeId == 1;
                     req.MaxPerPage = req.CacheCode.CacheCodes.Length;
                     var resp = client.Client.SearchForGeocaches(req);
                     if (resp.Status.StatusCode == 0 && resp.Geocaches != null)
                     {
                         _importGeocaches.RemoveRange(0, req.CacheCode.CacheCodes.Length);
                         Utils.API.Import.AddGeocaches(Core, resp.Geocaches);
                     }
                     else
                     {
                         break;
                     }
                     if (!prog.UpdateProgress(STR_COPYSELECTION, STR_RETRIEVING, max, max - _importGeocaches.Count))
                     {
                         break;
                     }
                 }
             }
         }
     }
     catch
     {
     }
     _context.Send(new SendOrPostCallback(delegate(object state)
     {
         _frameworkUpdater.Dispose();
         _frameworkUpdater = null;
     }), null);
 }
        protected override void PerformExport(object settings)
        {
            var gpxSetting = settings as ExportGPXSettings;
            if (gpxSetting != null && !string.IsNullOrEmpty(gpxSetting.FileName))
            {
                bool canceled = false;
                try
                {
                    using (var db = new NPoco.Database(this.DatabaseConnection.Connection, NPoco.DatabaseType.SQLite))
                    {
                        double minLat = 0, minLon = 0, maxLat = 0, maxLon = 0;
                        var dr = DatabaseConnection.ExecuteReader(string.Format("select Min(Latitude), Max(Latitude), Min(Longitude), Max(Longitude) from Caches inner join {0} on Caches.Code={0}.gccode", ActionInputTableName));
                        if (dr.Read())
                        {
                            minLat = Utils.Conversion.StringToDouble(dr.GetString(0));
                            maxLat = Utils.Conversion.StringToDouble(dr.GetString(1));
                            minLon = Utils.Conversion.StringToDouble(dr.GetString(2));
                            maxLon = Utils.Conversion.StringToDouble(dr.GetString(3));
                        }
                        dr.Close();
                        var gcList = db.Fetch<string>(string.Format("select gccode from {0}", ActionInputTableName));
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ExportingGPX", "CreatingFile", gcList.Count, 0, true))
                        {
                            using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(false))
                            {
                                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.UTF8))
                                {
                                    Utils.GPXGenerator gpxGenerator = new Utils.GPXGenerator(
                                        db
                                        , gcList
                                        , gpxSetting.Version
                                        , minLat
                                        , maxLat
                                        , minLon
                                        , maxLon
                                        );

                                    DateTime nextUpdate = DateTime.Now.AddSeconds(1);
                                    //generate header
                                    sw.Write(gpxGenerator.Start());
                                    //preserve mem and do for each cache the export
                                    for (int i = 0; i < gpxGenerator.Count; i++)
                                    {
                                        //write parent
                                        sw.WriteLine(gpxGenerator.Next());

                                        if (gpxSetting.AddChildWaypoints)
                                        {
                                            //write child waypoints
                                            string s = gpxGenerator.WaypointData();
                                            if (!string.IsNullOrEmpty(s))
                                            {
                                                sw.WriteLine(s);
                                            }
                                        }

                                        if (DateTime.Now >= nextUpdate)
                                        {
                                            if (!progress.Update("CreatingFile", gpxGenerator.Count, i + 1))
                                            {
                                                canceled = true;
                                                break;
                                            }
                                            nextUpdate = DateTime.Now.AddSeconds(1);
                                        }
                                    }
                                    //finalize
                                    sw.Write(gpxGenerator.Finish());
                                }

                                if (!canceled)
                                {
                                    if (gpxSetting.FileName.ToLower().EndsWith(".zip"))
                                    {
                                        using (FileStream zipToOpen = new FileStream(gpxSetting.FileName, FileMode.Create))
                                        {
                                            using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                                            {
                                                ZipArchiveEntry gpxEntry = archive.CreateEntry("geocaches.gpx");
                                                using (StreamWriter writer = new StreamWriter(gpxEntry.Open()))
                                                {
                                                    writer.Write(File.ReadAllText(gpxFile.Path));
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        System.IO.File.Copy(gpxFile.Path, gpxSetting.FileName, true);
                                    }
                                }
                            }
                        }
                    }
                }
                catch
                {
                }
            }
        }
Beispiel #59
0
        private void deleteSelectionThreadMethod()
        {
            try
            {
                DateTime dt = DateTime.Now.AddSeconds(2);
                using (Utils.ProgressBlock prog = new Utils.ProgressBlock(this, STR_DELETINGGEOCACHES, STR_DELETINGGEOCACHES, _gcList.Count, 0, true))
                {
                    int index = 0;
                    foreach (Framework.Data.Geocache gc in _gcList)
                    {
                        Utils.DataAccess.DeleteGeocache(Core, gc);

                        index++;
                        if (DateTime.Now >= dt)
                        {
                            if (!prog.UpdateProgress(STR_DELETINGGEOCACHES, STR_DELETINGGEOCACHES, _gcList.Count, index))
                            {
                                break;
                            }
                            dt = DateTime.Now.AddSeconds(2);
                        }
                    }
                }
            }
            catch
            {
            }
            _actionReady.Set();
        }
Beispiel #60
0
        public override bool Restore(bool geocachesOnly)
        {
            bool result = false;

            using (Utils.ProgressBlock prog = new Utils.ProgressBlock(this, STR_RESTORINGDATA, STR_RESTORINGDATA, 1, 0))
            {
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(_selectedBackupItem.BackupFile)))
                {
                    ZipEntry theEntry;
                    string tmpEntry = String.Empty;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string fileName = Path.GetFileName(theEntry.Name);
                        string fullPath = Path.Combine(_restorePath, theEntry.Name);
                        using (FileStream streamWriter = File.Create(fullPath))
                        {
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            streamWriter.Close();
                        }
                    }
                    s.Close();
                }
            }

            result = Open(geocachesOnly);

            return result;
        }