예제 #1
0
파일: GpxImport.cs 프로젝트: RH-Code/GAPP
 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);
         }
     }
 }
예제 #2
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;
                }
            }
        }
예제 #3
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;
            }
        }
예제 #4
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;
                        }
                    }
                }
            }
        }
예제 #5
0
파일: Updater.cs 프로젝트: RH-Code/GAPP
        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;
            }
        }
예제 #6
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();
 }
예제 #7
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;
        }
예제 #8
0
        protected override void ImportMethod()
        {
            /*
             * [{"latitude":"52.383607",
             * "longitude":"4.641646",
             * "created_at":"2012-05-15 07:02:53",
             * "deployed_at":"2013-03-16 05:15:56",
             * "notes":"hint: bankje",
             * "friendly_name":"NN# 147. Molen de Adriaan",
             * "location":",  ",
             * "username":"******",
             * "code":"147",
             * "capture_type_id":"http:\/\/www.munzee.com\/images\/pins\/munzee.png",
             * "special_logo":"",
             * "updated":"1365761293",
             * "archived":"0",
             * "type":"",
             * "country":"The Netherlands",
             * "region":"",
             * "country_2":null,
             * "region_2":null,
             * "munzee_id":"233744",
             * "owned":"0",
             * "captured":"0",
             * "captured_at":null,
             * "special":"0"}
             *
             *
             *
             * {"latitude":"52.234168",
             * "longitude":"5.185743",
             * "created_at":"2012-11-17 15:41:03",
             * "deployed_at":"2012-11-18 06:06:29",
             * "notes":"Hint: geel\n\nHeilig Hartkerk - Heilig Joseph kerk \nDeze kerk werd in 1928 ontworpen door H.W. Valk, die behoorde tot de traditionalistische stroming in de architectuur. Het gebouw kenmerkt zich door zijn robuuste bakstenen bouw en de combinatie van gotische en romaanse stijlelementen.\n\nHet was de eerste rooms-katholieke kerk in de arbeiderswijk Over het Spoor. Dat leidde in het begin nog wel eens tot uitingen van ongenoegen zoals het bekladden van de muren. Het interieur is sober. De imposante apostelkoppen van J. Cantre vormen de belangrijkste decoraties. Hij ontwierp ook het H. Hartbeeld aan de achterzijde. De gebrandschilderde ramen zijn van J. Nicolas.",
             * "friendly_name":"Heilig Hartkerk",
             * "location":"Hilversum, North Holland The Netherlands",
             * "username":"******",
             * "code":"65",
             * "capture_type_id":"http:\/\/www.munzee.com\/images\/pins\/munzee.png",
             * "special_logo":"",
             * "updated":"1365761293",
             * "archived":"0",
             * "type":"", //virtual
             * "country":"The Netherlands",
             * "region":"",
             * "country_2":null,
             * "region_2":null,
             * "munzee_id":"486901",
             * "owned":"0",
             * "captured":"0", //"captured":"1"
             * "captured_at":null, //"captured_at":"1364119020"
             * "special":"0"}
             * */

            using (Utils.ProgressBlock fixpr = new Utils.ProgressBlock(this, STR_IMPORTING, STR_DOWNLOADINGDATA, 1, 0))
            {
                int            index = 0;
                MunzeeDataList munzl;
                try
                {
                    System.Net.HttpWebRequest webRequest;
                    webRequest           = System.Net.WebRequest.Create(_selectedUrl) as System.Net.HttpWebRequest;
                    webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.17 Safari/533.4";
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MunzeeDataList));
                    using (System.IO.Stream stream = webRequest.GetResponse().GetResponseStream())
                    {
                        munzl = ser.ReadObject(stream) as MunzeeDataList;
                    }
                    DateTime nextProgUpdate = DateTime.MinValue;
                    string   usrname        = Properties.Settings.Default.AccountName.ToLower();
                    using (Utils.ProgressBlock prog = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTING, munzl.Count, 0))
                    {
                        foreach (MunzeeData md in munzl)
                        {
                            Framework.Data.Geocache gc = new Framework.Data.Geocache();

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

                            Utils.Calculus.SetDistanceAndAngleGeocacheFromLocation(gc, Core.CenterLocation);

                            if (AddGeocache(gc, null))
                            {
                                //check if found and if so, if log present
                                if (gc.Found && !string.IsNullOrEmpty(md.captured_at))
                                {
                                    //foud and no log, add log
                                    bool foundLogPresent          = false;
                                    List <Framework.Data.Log> lgs = Core.Logs.GetLogs(gc.Code);
                                    if (lgs != null)
                                    {
                                        Framework.Data.Log l = (from Framework.Data.Log lg in lgs where lg.LogType.AsFound && lg.Finder == Core.GeocachingAccountNames.GetAccountName(gc.Code) select lg).FirstOrDefault();
                                        foundLogPresent = (l != null);
                                    }
                                    if (!foundLogPresent)
                                    {
                                        Framework.Data.Log l = new Framework.Data.Log();
                                        l.DataFromDate = DateTime.Now;
                                        l.Date         = new DateTime(1970, 1, 1);
                                        l.Date         = l.Date.AddSeconds(long.Parse(md.captured_at.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[0]));
                                        l.Encoded      = false;
                                        l.Finder       = Core.GeocachingAccountNames.GetAccountName(gc.Code);
                                        l.FinderId     = "0";
                                        l.GeocacheCode = gc.Code;
                                        l.ID           = string.Format("ML{0}", gc.Code.Substring(2));
                                        l.LogType      = Utils.DataAccess.GetLogType(Core.LogTypes, 2);
                                        l.Text         = "Captured";
                                        AddLog(l);
                                    }
                                }
                            }

                            index++;
                            if (DateTime.Now >= nextProgUpdate)
                            {
                                prog.UpdateProgress(STR_IMPORTING, STR_IMPORTING, munzl.Count, index);
                                nextProgUpdate = DateTime.Now.AddSeconds(0.5);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _errorMessage = e.Message;
                }
            }
        }
예제 #9
0
파일: Viewer.cs 프로젝트: RH-Code/GAPP
        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
            {
            }
        }
예제 #10
0
        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);
            }
        }
예제 #11
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;
        }
예제 #12
0
파일: ChatForm.cs 프로젝트: RH-Code/GAPP
 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);
 }
예제 #13
0
        private void logThreadMethod()
        {
            try
            {
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(_plugin, STR_LOGGING, STR_LOGGING, _gcList.Count, 0, true))
                {
                    int index = 0;

                    foreach (var gc in _gcList)
                    {
                        _context.Send(new SendOrPostCallback(delegate(object state)
                        {
                            toolStripStatusLabel1.Visible = true;
                            toolStripStatusLabel1.Text    = gc.Code;
                        }), null);

                        var req = new Utils.API.LiveV6.CreateFieldNoteAndPublishRequest();
                        req.AccessToken       = _client.Token;
                        req.CacheCode         = gc.Code;
                        req.EncryptLogText    = false;
                        req.FavoriteThisCache = false;
                        req.Note          = _logText.Replace("#foundcount", _foundcount.ToString());
                        req.PromoteToLog  = true;
                        req.WptLogTypeId  = _logType.ID;
                        req.UTCDateLogged = _logDate.AddHours(12).ToUniversalTime();
                        var resp = _client.Client.CreateFieldNoteAndPublish(req);
                        if (resp.Status.StatusCode == 0)
                        {
                            if (Utils.DataAccess.GetGeocache(_core.Geocaches, gc.Code) != null)
                            {
                                //add log tot database
                                //if found, update cache as found
                                if (_logType.AsFound)
                                {
                                    gc.Found = true;
                                }
                                _core.Logs.Add(Utils.API.Convert.Log(_core, resp.Log));
                                gc.ResetCachedLogData();
                            }

                            _foundcount++;
                            //log the trackables
                            if (_tbTrackingNumbers.Count > 0)
                            {
                                List <Utils.API.LiveV6.Trackable> tb = new List <Utils.API.LiveV6.Trackable>();
                                foreach (string t in _tbs75)
                                {
                                    tb.Add((Utils.API.LiveV6.Trackable)_tbTrackingNumbers[t]);
                                }
                                logTrackables(tb, 75, gc);
                            }
                            _context.Send(new SendOrPostCallback(delegate(object state)
                            {
                                (from ListViewItem a in listView1.Items where (a.Tag as Framework.Data.Geocache) == gc select a).FirstOrDefault().Checked = false;
                            }), null);
                        }
                        else
                        {
                            _errormessage = resp.Status.StatusMessage;
                            break;
                        }
                        index++;
                        if (!progress.UpdateProgress(STR_LOGGING, STR_LOGGING, _gcList.Count, index))
                        {
                            break;
                        }

                        Thread.Sleep(3000);
                    }
                }
            }
            catch (Exception e)
            {
                _errormessage = e.Message;
            }
        }
예제 #14
0
        protected override void ImportMethod()
        {
            try
            {
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_UPDATINGGEOCACHES, STR_UPDATINGGEOCACHE, _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;

                        while (_gcList.Count > 0)
                        {
                            if (PluginSettings.Instance.AdditionalDelayBetweenImageImport > 0)
                            {
                                Thread.Sleep(PluginSettings.Instance.AdditionalDelayBetweenImageImport);
                            }
                            var resp = client.Client.GetImagesForGeocache(client.Token, _gcList[0].Code);
                            if (resp.Status.StatusCode == 0)
                            {
                                if (resp.Images != null)
                                {
                                    List<string> ids = new List<string>();
                                    foreach (var img in resp.Images)
                                    {
                                        if (img.Url.IndexOf("/cache/log/") < 0)
                                        {
                                            Framework.Data.GeocacheImage gcImg = Utils.API.Convert.GeocacheImage(Core, img, _gcList[0].Code);
                                            AddGeocacheImage(gcImg);
                                            ids.Add(gcImg.ID);
                                        }
                                    }
                                    List<Framework.Data.GeocacheImage> allImages = Utils.DataAccess.GetGeocacheImages(Core.GeocacheImages, _gcList[0].Code);
                                    foreach (Framework.Data.GeocacheImage gim in allImages)
                                    {
                                        if (!ids.Contains(gim.ID))
                                        {
                                            Core.GeocacheImages.Remove(gim);
                                        }
                                    }
                                }

                                if (PluginSettings.Instance.DeselectGeocacheAfterUpdate)
                                {
                                    _gcList[0].Selected = false;
                                }

                                index++;
                                if (!progress.UpdateProgress(STR_UPDATINGGEOCACHES, STR_UPDATINGGEOCACHE, totalcount, index))
                                {
                                    break;
                                }
                                _gcList.RemoveAt(0);

                                if (_gcList.Count > 0)
                                {
                                    Thread.Sleep(3000);
                                }
                            }
                            else
                            {
                                _errormessage = resp.Status.StatusMessage;
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _errormessage = e.Message;
            }
        }
예제 #15
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;
        }
예제 #16
0
파일: MyFinds.cs 프로젝트: gahadzikwa/GAPP
        protected override void ImportMethod()
        {
            bool cancelled = false;
            using (Utils.ProgressBlock blockprogress = new Utils.ProgressBlock(this, STR_IMPORTINGMYF, STR_IMPORTINGMYF, 1, 0))
            {
                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, STR_IMPORTINGMYF, STR_IMPORTINGLOGS, 100, 0, true))
                        {
                            var req = new Utils.API.LiveV6.GetUsersGeocacheLogsRequest();
                            req.AccessToken = api.Token;
                            req.ExcludeArchived = false;
                            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)
                                if (resp.Logs.Count() > 0)
                                {
                                    logs.AddRange(resp.Logs);
                                    req.StartIndex = logs.Count;
                                    if (!progress.UpdateProgress(STR_IMPORTINGMYF, STR_IMPORTINGLOGS, logs.Count + req.MaxPerPage, logs.Count))
                                    {
                                        cancelled = true;
                                        break;
                                    }
                                    Thread.Sleep(4000);
                                    resp = api.Client.GetUsersGeocacheLogs(req);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            if (resp.Status.StatusCode != 0)
                            {
                                _errormessage = resp.Status.StatusMessage;
                            }
                        }

                        //ok, we have the logs
                        //get the geocaches
                        if (!cancelled && string.IsNullOrEmpty(_errormessage))
                        {
                            //we download the geocaches that are not present. But for the ones we have, we need to add the log and mark it as found
                            List<string> gcList = (from a in logs where Utils.DataAccess.GetGeocache(Core.Geocaches, a.CacheCode) != null select a.CacheCode).ToList();
                            foreach (string s in gcList)
                            {
                                Utils.DataAccess.GetGeocache(Core.Geocaches, s).Found = true;
                                var ls = (from a in logs where a.CacheCode == s && !a.IsArchived select a).ToList();
                                foreach (var l in ls)
                                {
                                    AddLog(Utils.API.Convert.Log(Core, l));
                                }
                            }

                            gcList = (from a in logs where Utils.DataAccess.GetGeocache(Core.Geocaches, a.CacheCode) == null && !a.IsArchived select a.CacheCode).ToList();
                            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTINGMYF, STR_IMPORTINGCACHES, gcList.Count, 0, true))
                            {
                                int index = 0;
                                int gcupdatecount = 20;

                                while (gcList.Count > 0)
                                {
                                    Utils.API.LiveV6.SearchForGeocachesRequest req = new Utils.API.LiveV6.SearchForGeocachesRequest();
                                    req.IsLite = Core.GeocachingComAccount.MemberTypeId == 1;
                                    req.AccessToken = api.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 = 0;
                                    index += req.CacheCode.CacheCodes.Length;
                                    gcList.RemoveRange(0, req.CacheCode.CacheCodes.Length);
                                    var resp = api.Client.SearchForGeocaches(req);
                                    if (resp.Status.StatusCode == 0 && resp.Geocaches != null)
                                    {
                                        if (resp.CacheLimits != null)
                                        {
                                            _apiLimit = resp.CacheLimits.MaxCacheCount;
                                            _apiLeft = resp.CacheLimits.CachesLeft;
                                        }
                                        Utils.API.Import.AddGeocaches(Core, resp.Geocaches);

                                        foreach (var g in resp.Geocaches)
                                        {
                                            var ls = (from a in logs where a.CacheCode == g.Code && !a.IsArchived select a).ToList();
                                            foreach (var l in ls)
                                            {
                                                AddLog(Utils.API.Convert.Log(Core, l));
                                            }
                                        }

                                        if (!progress.UpdateProgress(STR_IMPORTINGMYF, STR_IMPORTINGCACHES, logs.Count, logs.Count - gcList.Count))
                                        {
                                            cancelled = true;
                                            break;
                                        }

                                        if (gcList.Count > 0)
                                        {
                                            Thread.Sleep(3000);
                                        }
                                    }
                                    else
                                    {
                                        _errormessage = resp.Status.StatusMessage;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _errormessage = e.Message;
                }
            }
        }
예제 #17
0
파일: Import.cs 프로젝트: gahadzikwa/GAPP
        protected override void ImportMethod()
        {
            bool cancelled = false;
            using (Utils.ProgressBlock blockprogress = new Utils.ProgressBlock(this, STR_IMPORTINGMYF, STR_IMPORTINGMYF, _users.Count, 0))
            {
                try
                {
                    using (var api = new Utils.API.GeocachingLiveV6(Core))
                    {
                        foreach (string usr in _users)
                        {
                            var logs = new List<Utils.API.LiveV6.GeocacheLog>();
                            int page = 0;
                            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTINGMYF, STR_IMPORTINGLOGS, 100, 0, true))
                            {
                                var req = new Utils.API.LiveV6.GetUsersGeocacheLogsRequest();
                                req.AccessToken = api.Token;
                                req.ExcludeArchived = true;
                                req.Username = usr;
                                req.MaxPerPage = 30;
                                req.StartIndex = 0;
                                if (PluginSettings.Instance.BetweenDates)
                                {
                                    req.Range = new Utils.API.LiveV6.DateRange();
                                    req.Range.StartDate = _fromDate < _toDate? _fromDate:_toDate;
                                    req.Range.EndDate = _toDate > _fromDate ? _toDate : _fromDate;
                                }
                                req.LogTypes = _logTypes.ToArray();
                                //req.LogTypes = new long[] { 2 };
                                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)
                                    {
                                        page++;
                                        //req.StartIndex = logs.Count;
                                        req.StartIndex = page * req.MaxPerPage;
                                        if (!progress.UpdateProgress(STR_IMPORTINGMYF, STR_IMPORTINGLOGS, logs.Count + req.MaxPerPage, logs.Count))
                                        {
                                            cancelled = true;
                                            break;
                                        }
                                        System.Threading.Thread.Sleep(2100);
                                        resp = api.Client.GetUsersGeocacheLogs(req);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                if (resp.Status.StatusCode != 0)
                                {
                                    _errormessage = resp.Status.StatusMessage;
                                }
                            }

                            if (!cancelled)
                            {
                                foreach (var l in logs)
                                {
                                    AddLog(Utils.API.Convert.Log(Core, l));
                                }
                            }

                            //ok, we have the logs
                            //get the geocaches
                            if (PluginSettings.Instance.ImportMissingCaches && !cancelled && string.IsNullOrEmpty(_errormessage))
                            {
                                List<string> gcList = (from a in logs where a.CacheCode!=null && Utils.DataAccess.GetGeocache(Core.Geocaches, a.CacheCode) == null select a.CacheCode).ToList();
                                int maxToGet = gcList.Count;
                                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTINGMYF, STR_IMPORTINGCACHES, maxToGet, 0, true))
                                {
                                    int index = 0;
                                    int gcupdatecount = 20;

                                    while (gcList.Count > 0)
                                    {
                                        Utils.API.LiveV6.SearchForGeocachesRequest req = new Utils.API.LiveV6.SearchForGeocachesRequest();
                                        req.IsLite = Core.GeocachingComAccount.MemberTypeId == 1;
                                        req.AccessToken = api.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 = 0;
                                        index += req.CacheCode.CacheCodes.Length;
                                        gcList.RemoveRange(0, req.CacheCode.CacheCodes.Length);
                                        var resp = api.Client.SearchForGeocaches(req);
                                        if (resp.Status.StatusCode == 0 && resp.Geocaches != null)
                                        {
                                            if (resp.CacheLimits != null)
                                            {
                                                _apiLimit = resp.CacheLimits.MaxCacheCount;
                                                _apiLeft = resp.CacheLimits.CachesLeft;
                                            }
                                            Utils.API.Import.AddGeocaches(Core, resp.Geocaches);

                                            if (!progress.UpdateProgress(STR_IMPORTINGMYF, STR_IMPORTINGCACHES, maxToGet, maxToGet - gcList.Count))
                                            {
                                                cancelled = true;
                                                break;
                                            }
                                            if (gcList.Count > 0)
                                            {
                                                Thread.Sleep(3000);
                                            }

                                        }
                                        else
                                        {
                                            _errormessage = resp.Status.StatusMessage;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _errormessage = e.Message;
                }
            }
        }
예제 #18
0
파일: CopyTo.cs 프로젝트: gahadzikwa/GAPP
        private bool copyToSave(FileCollection fc)
        {
            bool result = true;
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_SAVING, STR_SAVINGGEOCACHES, CopyToList.Count, 0))
            {
                byte[] memBuffer = new byte[10 * 1024 * 1024];
                byte notFree = 1;
                byte notFreeF = 2;

                List<RecordInfo> freeGeocacheRecords = (from RecordInfo ri in fc._geocachesInDB.Values where ri.FreeSlot select ri).OrderByDescending(x => x.Length).ToList();
                List<RecordInfo> freeLogImageRecords = (from RecordInfo ri in fc._logimgsInDB.Values where ri.FreeSlot select ri).OrderByDescending(x => x.Length).ToList();
                List<RecordInfo> freeLogRecords = (from RecordInfo ri in fc._logsInDB.Values where ri.FreeSlot select ri).OrderByDescending(x => x.Length).ToList();
                List<RecordInfo> freeWaypointRecords = (from RecordInfo ri in fc._wptsInDB.Values where ri.FreeSlot select ri).OrderByDescending(x => x.Length).ToList();
                List<RecordInfo> freeUserWaypointRecords = (from RecordInfo ri in fc._usrwptsInDB.Values where ri.FreeSlot select ri).OrderByDescending(x => x.Length).ToList();
                List<RecordInfo> freeGeocacheImageRecords = (from RecordInfo ri in fc._geocacheimgsInDB.Values where ri.FreeSlot select ri).OrderByDescending(x => x.Length).ToList();

                using (MemoryStream ms = new MemoryStream(memBuffer))
                using (BinaryWriter bw = new BinaryWriter(ms))
                using (FileStream fsLogImages = File.Open(fc.LogImagesFilename, FileMode.OpenOrCreate, FileAccess.Write))
                using (FileStream fsWaypoints = File.Open(fc.WaypointsFilename, FileMode.OpenOrCreate, FileAccess.Write))
                using (FileStream fsUserWaypoints = File.Open(fc.UserWaypointsFilename, FileMode.OpenOrCreate, FileAccess.Write))
                using (FileStream fsGeocacheImages = File.Open(fc.GeocacheImagesFilename, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    //**********************************************
                    //          GEOCACHES
                    //**********************************************
                    long recordLength = 0;
                    byte[] extraBuffer = new byte[200];

                    int index = 0;
                    int procStep = 0;
                    foreach (Framework.Data.Geocache gc in CopyToList)
                    {
                        //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, freeGeocacheRecords);

                        //other record
                        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, freeGeocacheRecords);

                        List<Framework.Data.Log> lglist = Utils.DataAccess.GetLogs(Core.Logs, gc.Code);
                        if (lglist.Count > 0)
                        {
                            recordLength = 0;
                            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, freeLogRecords);

                                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, freeLogRecords);

                                List<Framework.Data.LogImage> lgimglist = Utils.DataAccess.GetLogImages(Core.LogImages, l.ID);
                                if (lgimglist.Count > 0)
                                {
                                    recordLength = 0;
                                    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, fsLogImages, memBuffer, extraBuffer, freeLogImageRecords);

                                    }
                                }
                            }
                        }

                        List<Framework.Data.Waypoint> wptlist = Utils.DataAccess.GetWaypointsFromGeocache(Core.Waypoints, gc.Code);
                        if (wptlist.Count > 0)
                        {
                            recordLength = 0;
                            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, fsWaypoints, memBuffer, extraBuffer, freeWaypointRecords);
                            }
                        }

                        List<Framework.Data.UserWaypoint> usrwptlist = Utils.DataAccess.GetUserWaypointsFromGeocache(Core.UserWaypoints, gc.Code);
                        if (usrwptlist.Count > 0)
                        {
                            recordLength = 0;
                            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, fsUserWaypoints, memBuffer, extraBuffer, freeUserWaypointRecords);
                            }
                        }

                        List<Framework.Data.GeocacheImage> geocacheimglist = Utils.DataAccess.GetGeocacheImages(Core.GeocacheImages, gc.Code);
                        if (geocacheimglist.Count > 0)
                        {
                            recordLength = 0;
                            extraBuffer = new byte[100];
                            foreach (Framework.Data.GeocacheImage li in geocacheimglist)
                            {
                                //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.ToString(), ms, bw, fsGeocacheImages, memBuffer, extraBuffer, freeGeocacheImageRecords);
                            }
                        }


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

            //**********************************************
            //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((from RecordInfo ri in fc._geocachesInDB.Values where !ri.FreeSlot && !ri.ID.StartsWith("F_") select ri).Count().ToString());
            el.AppendChild(txt);
            root.AppendChild(el);

            el = doc.CreateElement("LogCount");
            txt = doc.CreateTextNode((from RecordInfo ri in fc._logsInDB.Values where !ri.FreeSlot && !ri.ID.StartsWith("F_") select ri).Count().ToString());
            el.AppendChild(txt);
            root.AppendChild(el);

            el = doc.CreateElement("LogImagesCount");
            txt = doc.CreateTextNode((from RecordInfo ri in fc._logimgsInDB.Values where !ri.FreeSlot select ri).Count().ToString());
            el.AppendChild(txt);
            root.AppendChild(el);

            el = doc.CreateElement("WaypointCount");
            txt = doc.CreateTextNode((from RecordInfo ri in fc._wptsInDB.Values where !ri.FreeSlot select ri).Count().ToString());
            el.AppendChild(txt);
            root.AppendChild(el);

            el = doc.CreateElement("UserWaypointCount");
            txt = doc.CreateTextNode((from RecordInfo ri in fc._usrwptsInDB.Values where !ri.FreeSlot select ri).Count().ToString());
            el.AppendChild(txt);
            root.AppendChild(el);

            el = doc.CreateElement("GeocacheImagesCount");
            txt = doc.CreateTextNode((from RecordInfo ri in fc._geocacheimgsInDB.Values where !ri.FreeSlot select ri).Count().ToString());
            el.AppendChild(txt);
            root.AppendChild(el);

            doc.Save(fc.DatabaseInfoFilename);
            return result;
        }
예제 #19
0
        private bool insertFromDatabase(bool overwrite)
        {
            bool result = false;

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

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

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

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

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

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

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

                                    bool newGeocache;
                                    Framework.Data.Geocache gc = Utils.DataAccess.GetGeocache(Core.Geocaches, ri.ID);
                                    if (gc == null)
                                    {
                                        gc = new Framework.Data.Geocache();
                                        htInsertedGeocaches.Add(ri.ID, gc);
                                        newGeocache = true;
                                    }
                                    else
                                    {
                                        if (overwrite || htInsertedGeocaches[ri.ID] != null)
                                        {
                                            newGeocache = false;
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    gc.BeginUpdate();
                                    try
                                    {
                                        gc.Code = ri.ID;
                                        gc.Archived = br.ReadBoolean();
                                        gc.AttributeIds = ReadIntegerArray(br);
                                        gc.Available = br.ReadBoolean();
                                        gc.City = br.ReadString();
                                        gc.Container = Utils.DataAccess.GetGeocacheContainer(Core.GeocacheContainers, br.ReadInt32());
                                        gc.CustomCoords = br.ReadBoolean();
                                        gc.Country = br.ReadString();
                                        if (br.ReadBoolean())
                                        {
                                            gc.CustomLat = br.ReadDouble();
                                            gc.CustomLon = br.ReadDouble();
                                        }
                                        gc.Difficulty = br.ReadDouble();
                                        gc.EncodedHints = br.ReadString();
                                        gc.Favorites = br.ReadInt32();
                                        gc.Flagged = br.ReadBoolean();
                                        gc.Found = br.ReadBoolean();
                                        gc.GeocacheType = Utils.DataAccess.GetGeocacheType(Core.GeocacheTypes, br.ReadInt32());
                                        gc.ID = br.ReadString();
                                        gc.Lat = br.ReadDouble();
                                        gc.Lon = br.ReadDouble();
                                        gc.MemberOnly = br.ReadBoolean();
                                        gc.Municipality = br.ReadString();
                                        gc.Name = br.ReadString();
                                        gc.Notes = br.ReadString();
                                        gc.Owner = br.ReadString();
                                        gc.OwnerId = br.ReadString();
                                        gc.PersonaleNote = br.ReadString();
                                        gc.PlacedBy = br.ReadString();
                                        gc.PublishedTime = DateTime.Parse(br.ReadString());
                                        gc.State = br.ReadString();
                                        gc.Terrain = br.ReadDouble();
                                        gc.Title = br.ReadString();
                                        gc.Url = br.ReadString();
                                        gc.DataFromDate = DateTime.Parse(br.ReadString());
                                        gc.Locked = br.ReadBoolean();

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

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

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

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

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

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

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

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

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

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


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

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

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

                                        wp.BeginUpdate();
                                        try
                                        {
                                            wp.Code = ri.ID;
                                            wp.Comment = br.ReadString();
                                            wp.DataFromDate = DateTime.Parse(br.ReadString());
                                            wp.Description = br.ReadString();
                                            wp.GeocacheCode = br.ReadString();
                                            wp.ID = br.ReadString();
                                            if (br.ReadBoolean())
                                            {
                                                wp.Lat = br.ReadDouble();
                                                wp.Lon = br.ReadDouble();
                                            }
                                            wp.Name = br.ReadString();
                                            wp.Time = DateTime.Parse(br.ReadString());
                                            wp.Url = br.ReadString();
                                            wp.UrlName = br.ReadString();
                                            wp.WPType = Utils.DataAccess.GetWaypointType(Core.WaypointTypes, br.ReadInt32());
                                        }
                                        catch
                                        {
                                        }
                                        wp.EndUpdate();
                                        if (newWp)
                                        {
                                            if (Utils.DataAccess.GetGeocache(Core.Geocaches, wp.GeocacheCode ?? "") != null)
                                            {
                                                Core.Waypoints.Add(wp);
                                            }
                                        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                        wp.EndUpdate();
                                    }
                                }
                            }
                        }
                    }
                }
                result = true;
            }
            catch
            {
            }
            return result;
        }
예제 #20
0
        private void getImagesThreadMethod()
        {
            try
            {
                using (Utils.ProgressBlock blockprogress = new Utils.ProgressBlock(OwnerPlugin as Utils.BasePlugin.Plugin, STR_IMPORTINGMYF, STR_IMPORTINGMYF, 1, 0))
                {
                    try
                    {
                        Utils.DBCon dbcon = initDatabase();

                        var logs = new List <Utils.API.LiveV6.GeocacheLog>();

                        using (System.Net.WebClient wc = new System.Net.WebClient())
                            using (var api = new Utils.API.GeocachingLiveV6(Core))
                            {
                                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(OwnerPlugin as Utils.BasePlugin.Plugin, STR_IMPORTINGMYF, STR_IMPORTINGLOGS, 100, 0, true))
                                {
                                    var req = new Utils.API.LiveV6.GetUsersGeocacheLogsRequest();
                                    req.AccessToken     = api.Token;
                                    req.ExcludeArchived = false;
                                    req.MaxPerPage      = 50;
                                    req.StartIndex      = 0;
                                    req.LogTypes        = (from a in Core.LogTypes select(long) a.ID).ToArray();
                                    var resp = api.Client.GetUsersGeocacheLogs(req);
                                    while (resp.Status.StatusCode == 0)
                                    {
                                        logs.AddRange(resp.Logs);
                                        foreach (var log in resp.Logs)
                                        {
                                            if (log.Images != null && !log.IsArchived)
                                            {
                                                foreach (var li in log.Images)
                                                {
                                                    string    imgGuid = li.ImageGuid.ToString("N");
                                                    ImageInfo ii      = (from a in _imageInfoList where a.ImageGuid == imgGuid select a).FirstOrDefault();
                                                    if (ii == null)
                                                    {
                                                        ii              = new ImageInfo();
                                                        ii.Description  = li.Description;
                                                        ii.ImageGuid    = imgGuid;
                                                        ii.MobileUrl    = li.MobileUrl ?? "";
                                                        ii.Name         = li.Name ?? "";
                                                        ii.ThumbUrl     = li.ThumbUrl;
                                                        ii.Url          = li.Url;
                                                        ii.LogCacheCode = log.CacheCode;
                                                        ii.LogCode      = log.Code;
                                                        ii.LogUrl       = log.Url;
                                                        ii.LogVisitDate = log.VisitDate;

                                                        ii.ThumbFile = Path.Combine(_thumbFolder, Path.GetFileName(li.ThumbUrl));
                                                        ii.ImgFile   = Path.Combine(_imgFolder, Path.GetFileName(li.Url));

                                                        _imageInfoList.Add(ii);

                                                        dbcon.ExecuteNonQuery(string.Format("insert into gallery (ImageGuid, ThumbUrl, Description, Name, MobileUrl, Url, LogCacheCode, LogCode, LogUrl, LogVisitDate, ThumbFile, ImgFile) values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')", ii.ImageGuid.Replace("'", "''"), ii.ThumbUrl.Replace("'", "''"), ii.Description.Replace("'", "''"), ii.Name.Replace("'", "''"), ii.MobileUrl.Replace("'", "''"), ii.Url.Replace("'", "''"), ii.LogCacheCode.Replace("'", "''"), ii.LogCode.Replace("'", "''"), ii.LogUrl.Replace("'", "''"), ii.LogVisitDate.ToString("s").Replace("'", "''"), ii.ThumbFile.Replace("'", "''"), ii.ImgFile.Replace("'", "''")));
                                                    }
                                                    //check if local file(s) exist(s)
                                                    //not fail on img download!
                                                    try
                                                    {
                                                        if (!File.Exists(ii.ThumbFile))
                                                        {
                                                            wc.DownloadFile(li.ThumbUrl, ii.ThumbFile);
                                                        }
                                                        if (!File.Exists(ii.ImgFile))
                                                        {
                                                            wc.DownloadFile(li.Url, ii.ImgFile);
                                                        }
                                                    }
                                                    catch
                                                    {
                                                    }
                                                }
                                            }
                                        }

                                        if (resp.Logs.Count() >= req.MaxPerPage)
                                        {
                                            req.StartIndex = logs.Count;
                                            if (!progress.UpdateProgress(STR_IMPORTINGMYF, STR_IMPORTINGLOGS, logs.Count + req.MaxPerPage, logs.Count))
                                            {
                                                break;
                                            }
                                            Thread.Sleep(1500);
                                            resp = api.Client.GetUsersGeocacheLogs(req);
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                    if (resp.Status.StatusCode != 0)
                                    {
                                        _errormessage = resp.Status.StatusMessage;
                                    }
                                }
                            }
                        if (dbcon != null)
                        {
                            dbcon.Dispose();
                            dbcon = null;
                        }
                    }
                    catch (Exception e)
                    {
                        _errormessage = e.Message;
                    }
                }
            }
            catch
            {
            }
            _actionReady.Set();
        }
예제 #21
0
        protected override void ExportMethod()
        {
            string gpxFile;
            string wptFile;

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

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

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

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

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

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

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

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

                                wpt = true;
                            }
                            s.Finish();
                            s.Close();
                        }
                    }
                    catch
                    {
                    }
                }
                else
                {
                    if (!PluginSettings.Instance.AddWaypoints)
                    {
                        System.IO.File.Delete(wptFile);
                    }
                }
            }
            if (tmp != null)
            {
                tmp.Dispose();
                tmp = null;
            }
            if (tmpwpt != null)
            {
                tmpwpt.Dispose();
                tmpwpt = null;
            }
        }
예제 #22
0
파일: Repository.cs 프로젝트: RH-Code/GAPP
        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();
        }
예제 #23
0
        protected override void ImportMethod()
        {
            try
            {
                using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_UPDATINGGEOCACHES, STR_UPDATINGGEOCACHE, _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;
                        bool cancel = false;

                        while (_gcList.Count > 0 && !cancel)
                        {
                            int logCount = 0;
                            int maxPerPage = 30;
                            bool done = false;

                            if (PluginSettings.Instance.UpdateLogsMaxLogCount > 0 && PluginSettings.Instance.UpdateLogsMaxLogCount < 30)
                            {
                                maxPerPage = PluginSettings.Instance.UpdateLogsMaxLogCount;
                            }
                            List<string> ids = new List<string>();
                            
                            Thread.Sleep(PluginSettings.Instance.AdditionalDelayBetweenLogImport);
                            var resp = client.Client.GetGeocacheLogsByCacheCode(client.Token, _gcList[0].Code, logCount, maxPerPage);
                            while (resp.Status.StatusCode == 0 && resp.Logs != null && resp.Logs.Count() > 0 && !done)
                            {
                                foreach (var lg in resp.Logs)
                                {
                                    if (!lg.IsArchived)
                                    {
                                        Framework.Data.Log gcLog = Utils.API.Convert.Log(Core, lg);
                                        AddLog(gcLog);
                                        if (PluginSettings.Instance.UpdateLogsMaxLogCount == 0)
                                        {
                                            ids.Add(gcLog.ID);
                                        }
                                    }
                                }

                                logCount += resp.Logs.Count();
                                if (PluginSettings.Instance.UpdateLogsMaxLogCount > 0)
                                {
                                    int left = PluginSettings.Instance.UpdateLogsMaxLogCount - logCount;
                                    if (left < maxPerPage)
                                    {
                                        maxPerPage = left;
                                    }
                                }
                                if (maxPerPage > 0)
                                {
                                    Thread.Sleep(3000 + PluginSettings.Instance.AdditionalDelayBetweenLogImport);
                                    resp = client.Client.GetGeocacheLogsByCacheCode(client.Token, _gcList[0].Code, logCount, maxPerPage);
                                }
                                else
                                {
                                    done = true;
                                }
                            }
                            if (resp.Status.StatusCode != 0)
                            {
                                _errormessage = resp.Status.StatusMessage;
                                break;
                            }
                            else
                            {
                                if (PluginSettings.Instance.DeselectGeocacheAfterUpdate)
                                {
                                    _gcList[0].Selected = false;
                                }
                                if (PluginSettings.Instance.UpdateLogsMaxLogCount == 0)
                                {
                                    List<Framework.Data.Log> allLogs = Utils.DataAccess.GetLogs(Core.Logs, _gcList[0].Code);
                                    foreach (Framework.Data.Log gim in allLogs)
                                    {
                                        if (!ids.Contains(gim.ID))
                                        {
                                            Core.Logs.Remove(gim);
                                        }
                                    }
                                }
                            }

                            index++;
                            if (!progress.UpdateProgress(STR_UPDATINGGEOCACHES, STR_UPDATINGGEOCACHE, totalcount, index))
                            {
                                break;
                            }
                            _gcList.RemoveAt(0);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _errormessage = e.Message;
            }
        }
예제 #24
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);
         }
     }
 }
예제 #25
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();
 }
예제 #26
0
파일: Actions.cs 프로젝트: RH-Code/GAPP
        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();
        }
예제 #27
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;
         Properties.Settings.Default.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();
     }
 }
예제 #28
0
        protected override void ExportMethod()
        {
            FileInfo fi = new FileInfo(PluginSettings.Instance.FilePath);

            if (fi.Exists)
            {
                fi.Delete();
            }
            int totalToDo = _sheets.Count * _gcList.Count;
            int totalDone = 0;

            using (Utils.ProgressBlock prog = new Utils.ProgressBlock(this, STR_EXPORTINGPOI, STR_CREATINGFILE, totalToDo, totalDone))
            {
                using (ExcelPackage package = new ExcelPackage(fi))
                {
                    foreach (ExportForm.Sheet sheet in _sheets)
                    {
                        // add a new worksheet to the empty workbook
                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(sheet.Name);
                        //Add the headers
                        int col = 1;
                        foreach (PropertyItem pi in sheet.SelectedItems)
                        {
                            worksheet.Cells[1, col].Value = pi.Name;
                            col++;
                        }
                        int row = 2;
                        foreach (Framework.Data.Geocache gc in _gcList)
                        {
                            col = 1;
                            foreach (PropertyItem pi in sheet.SelectedItems)
                            {
                                /*
                                 * object o = pi.GetValue(gc);
                                 * if (o != null && o.GetType() == typeof(string))
                                 * {
                                 *  o = validateXml((string)o);
                                 * }
                                 * worksheet.Cells[row, col].Value = o;
                                 * */
                                /*
                                 * object o = pi.GetValue(gc);
                                 * if (o != null)
                                 * {
                                 *  string s = o.ToString();
                                 *  worksheet.Cells[row, col].Value = s;
                                 * }
                                 */
                                worksheet.Cells[row, col].Value = pi.GetValue(gc);
                                col++;
                            }
                            row++;
                            totalDone++;

                            if (totalDone % 100 == 0)
                            {
                                prog.UpdateProgress(STR_EXPORTINGPOI, STR_CREATINGFILE, totalToDo, totalDone);
                            }
                        }
                    }
                    package.Workbook.Properties.Title    = "GAPP Geocache Export";
                    package.Workbook.Properties.Author   = "Globalcaching.eu";
                    package.Workbook.Properties.Comments = "This document has been created by GlobalcachingApplication (GAPP)";
                    package.Workbook.Properties.Company  = "Globalcaching.eu";
                    package.Save();
                }
            }
        }
예제 #29
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();
                }
            }
        }
예제 #30
0
파일: ImportPQ.cs 프로젝트: gahadzikwa/GAPP
 protected override void ImportMethod()
 {
     using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_DOWNLOADING_PQ, STR_DOWNLOADING_PQ, _pqs.Count, 0))
     {
         int index = 0;
         try
         {
             foreach (Utils.API.LiveV6.PQData pq in _pqs)
             {
                 progress.UpdateProgress(STR_DOWNLOADING_PQ, STR_DOWNLOADING_PQ, _pqs.Count, index);
                 Utils.API.LiveV6.GetPocketQueryZippedFileResponse resp = _client.Client.GetPocketQueryZippedFile(_client.Token, pq.GUID);
                 if (resp.Status.StatusCode == 0)
                 {
                     using (System.IO.TemporaryFile tf = new System.IO.TemporaryFile(true))
                     {
                         System.IO.File.WriteAllBytes(tf.Path, Convert.FromBase64String(resp.ZippedFile));
                         processFile(tf.Path);
                         updateProcessedPq(pq.Name);
                     }
                 }
                 else
                 {
                     System.Windows.Forms.MessageBox.Show(resp.Status.StatusMessage, Utils.LanguageSupport.Instance.GetTranslation("Error"), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                     break;
                 }
                 index++;
             }
         }
         catch(Exception e)
         {
             System.Windows.Forms.MessageBox.Show(e.Message, Utils.LanguageSupport.Instance.GetTranslation("Error"), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
         }
     }
 }
예제 #31
0
파일: LogPurger.cs 프로젝트: RH-Code/GAPP
 private void purgeLogsWithFilterThreadMethod()
 {
     try
     {
         int max = Core.Geocaches.Count;
         int index = 0;
         using (Utils.ProgressBlock prog = new Utils.ProgressBlock(this, STR_PURGINGLOGS, STR_PURGINGLOGS, max, index, true))
         {
             //first remove logs of a certain logger
             if (Properties.Settings.Default.RemoveAllLogsFrom != null && Properties.Settings.Default.RemoveAllLogsFrom.Count > 0)
             {
                 string[] names = (from string s in Properties.Settings.Default.RemoveAllLogsFrom select s.ToLower()).ToArray();
                 List<Framework.Data.Log> logs = (from Framework.Data.Log l in Core.Logs
                                                  where names.Contains(l.Finder.ToLower())
                                                  select l).ToList();
                 foreach (var l in logs)
                 {
                     Utils.DataAccess.DeleteLog(Core, l);
                 }
             }
             string me = Core.GeocachingComAccount.AccountName;
             string[] keeps;
             bool keepMine = Properties.Settings.Default.KeepOwnLogs;
             if (Properties.Settings.Default.KeepLogsOf == null)
             {
                 keeps = new string[0];
             }
             else
             {
                 keeps = (from string s in Properties.Settings.Default.KeepLogsOf select s.ToLower()).ToArray();
             }
             DateTime dt;
             if (Properties.Settings.Default.DaysMonths == 0)
             {
                 dt = DateTime.Now.AddDays(-Properties.Settings.Default.DaysMonthsCount);
             }
             else
             {
                 dt = DateTime.Now.AddMonths(-Properties.Settings.Default.DaysMonthsCount);
             }
             foreach (Framework.Data.Geocache gc in Core.Geocaches)
             {
                 if (!Properties.Settings.Default.KeepAllOfOwned || gc.Owner != me)
                 {
                     List<Framework.Data.Log> lgs = Utils.DataAccess.GetLogs(Core.Logs, gc.Code);
                     if (lgs != null)
                     {
                         var logs = (from l in lgs
                                     where (!keepMine || l.Finder != me) && !keeps.Contains(l.Finder.ToLower())
                                     select l).Skip(Properties.Settings.Default.KeepAtLeast);
                         foreach (var l in logs)
                         {
                             if (l.Date < dt)
                             {
                                 Utils.DataAccess.DeleteLog(Core, l);
                             }
                         }
                     }
                 }
                 index++;
                 if (index % 50 == 0)
                 {
                     if (!prog.UpdateProgress(STR_PURGINGLOGS, STR_PURGINGLOGS, max, index))
                     {
                         break;
                     }
                 }
             }
         }
     }
     catch
     {
     }
     _actionReady.Set();
 }
예제 #32
0
파일: LogPurger.cs 프로젝트: RH-Code/GAPP
 private void purgeLogsThreadMethod()
 {
     try
     {
         int max = Core.Geocaches.Count;
         int index = 0;
         using (Utils.ProgressBlock prog = new Utils.ProgressBlock(this, STR_PURGINGLOGS, STR_PURGINGLOGS, max, index, true))
         {
             string me = Core.GeocachingComAccount.AccountName;
             foreach (Framework.Data.Geocache gc in Core.Geocaches)
             {
                 /*
                 List<Framework.Data.Log> logs = (from Framework.Data.Log l in Core.Logs
                                                  where l.GeocacheCode == gc.Code && l.Finder != Core.GeocachingComAccount.AccountName
                                                  orderby l.Date descending
                                                  select l).Skip(5).ToList();
                  */
                 List<Framework.Data.Log> lgs = Utils.DataAccess.GetLogs(Core.Logs, gc.Code);
                 if (lgs != null)
                 {
                     var logs = (from l in lgs
                                 where l.Finder != me
                                 select l).Skip(5);
                     foreach (var l in logs)
                     {
                         Utils.DataAccess.DeleteLog(Core, l);
                     }
                 }
                 index++;
                 if (index % 50 == 0)
                 {
                     if (!prog.UpdateProgress(STR_PURGINGLOGS, STR_PURGINGLOGS, max, index))
                     {
                         break;
                     }
                 }
             }
         }
     }
     catch
     {
     }
     _actionReady.Set();
 }
예제 #33
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);
            }
        }
예제 #34
0
파일: Export.cs 프로젝트: pheijmans-zz/GAPP
        private bool addGeocaches(Utils.ProgressBlock progress, List <Framework.Data.Geocache> gcList, List <Framework.Data.GeocacheType> typeList, XmlDocument doc, XmlElement rootDoc, string folderName, string tempFolder, List <string> fileList)
        {
            bool result = true;

            //
            //folder
            XmlElement folder = doc.CreateElement("Folder");

            rootDoc.AppendChild(folder);

            XmlElement el  = doc.CreateElement("name");
            XmlText    txt = doc.CreateTextNode(Utils.LanguageSupport.Instance.GetTranslation(folderName));

            el.AppendChild(txt);
            folder.AppendChild(el);

            foreach (Framework.Data.Geocache g in gcList)
            {
                //check if style exists
                Framework.Data.GeocacheType gt = g.GeocacheType;
                string imgIcon = Utils.ImageSupport.Instance.GetImagePath(Core, Framework.Data.ImageSize.Default, gt);
                string destImg = Path.Combine(tempFolder, Path.GetFileName(imgIcon));

                if (!typeList.Contains(gt))
                {
                    typeList.Add(gt);
                    string mapIcon   = Utils.ImageSupport.Instance.GetImagePath(Core, Framework.Data.ImageSize.Map, gt);
                    string destFile  = Path.Combine(tempFolder, Path.GetFileName(mapIcon));
                    string mapIconC  = Utils.ImageSupport.Instance.GetImagePath(Core, Framework.Data.ImageSize.Map, gt, true);
                    string destFileC = Path.Combine(tempFolder, Path.GetFileName(mapIconC));
                    if (!File.Exists(destFile))
                    {
                        File.Copy(mapIcon, destFile);
                    }
                    if (!File.Exists(destFileC))
                    {
                        File.Copy(mapIconC, destFileC);
                    }
                    if (!File.Exists(destImg))
                    {
                        File.Copy(imgIcon, destImg);
                    }

                    if (!fileList.Contains(destFile))
                    {
                        fileList.Add(destFile);
                    }
                    if (!fileList.Contains(destFileC))
                    {
                        fileList.Add(destFileC);
                    }
                    if (!fileList.Contains(destImg))
                    {
                        fileList.Add(destImg);
                    }
                    //adding style

                    /*
                     * <Style id="TNA">
                     *  <IconStyle id="iconTNA">
                     *      <scale>1</scale>
                     *      <Icon>
                     *          <href>http://hulmgulm.de/gc/myGoogleEarth/mrk_traditional.png</href>
                     *      </Icon>
                     *  </IconStyle>
                     *  <LabelStyle id="labelTNA">
                     *      <scale>1</scale>
                     *  </LabelStyle>
                     * </Style>
                     */
                    XmlElement style = doc.CreateElement("Style");
                    rootDoc.AppendChild(style);
                    XmlAttribute attr = doc.CreateAttribute("id");
                    txt = doc.CreateTextNode(string.Format("id{0}", gt.ID));
                    attr.AppendChild(txt);
                    style.Attributes.Append(attr);

                    XmlElement iconstyle = doc.CreateElement("IconStyle");
                    style.AppendChild(iconstyle);
                    attr = doc.CreateAttribute("id");
                    txt  = doc.CreateTextNode(string.Format("iconid{0}", gt.ID));
                    attr.AppendChild(txt);
                    iconstyle.Attributes.Append(attr);

                    el  = doc.CreateElement("scale");
                    txt = doc.CreateTextNode("1");
                    el.AppendChild(txt);
                    iconstyle.AppendChild(el);

                    XmlElement icon = doc.CreateElement("Icon");
                    iconstyle.AppendChild(icon);
                    el  = doc.CreateElement("href");
                    txt = doc.CreateTextNode(string.Format("Images/{0}", Path.GetFileName(mapIcon)));
                    el.AppendChild(txt);
                    icon.AppendChild(el);


                    XmlElement labelstyle = doc.CreateElement("LabelStyle");
                    style.AppendChild(labelstyle);
                    attr = doc.CreateAttribute("id");
                    txt  = doc.CreateTextNode(string.Format("labelid{0}", gt.ID));
                    attr.AppendChild(txt);
                    labelstyle.Attributes.Append(attr);

                    el  = doc.CreateElement("scale");
                    txt = doc.CreateTextNode("1");
                    el.AppendChild(txt);
                    labelstyle.AppendChild(el);

                    //
                    //corrected
                    //
                    style = doc.CreateElement("Style");
                    rootDoc.AppendChild(style);
                    attr = doc.CreateAttribute("id");
                    txt  = doc.CreateTextNode(string.Format("idC{0}", gt.ID));
                    attr.AppendChild(txt);
                    style.Attributes.Append(attr);

                    iconstyle = doc.CreateElement("IconStyle");
                    style.AppendChild(iconstyle);
                    attr = doc.CreateAttribute("id");
                    txt  = doc.CreateTextNode(string.Format("iconidC{0}", gt.ID));
                    attr.AppendChild(txt);
                    iconstyle.Attributes.Append(attr);

                    el  = doc.CreateElement("scale");
                    txt = doc.CreateTextNode("1");
                    el.AppendChild(txt);
                    iconstyle.AppendChild(el);

                    icon = doc.CreateElement("Icon");
                    iconstyle.AppendChild(icon);
                    el  = doc.CreateElement("href");
                    txt = doc.CreateTextNode(string.Format("Images/{0}", Path.GetFileName(mapIconC)));
                    el.AppendChild(txt);
                    icon.AppendChild(el);


                    labelstyle = doc.CreateElement("LabelStyle");
                    style.AppendChild(labelstyle);
                    attr = doc.CreateAttribute("id");
                    txt  = doc.CreateTextNode(string.Format("labelidC{0}", gt.ID));
                    attr.AppendChild(txt);
                    labelstyle.Attributes.Append(attr);

                    el  = doc.CreateElement("scale");
                    txt = doc.CreateTextNode("1");
                    el.AppendChild(txt);
                    labelstyle.AppendChild(el);
                }

                XmlElement placemark = doc.CreateElement("Placemark");
                folder.AppendChild(placemark);

                el  = doc.CreateElement("name");
                txt = doc.CreateTextNode(g.Name ?? "");
                el.AppendChild(txt);
                placemark.AppendChild(el);

                el = doc.CreateElement("styleUrl");
                if (g.ContainsCustomLatLon)
                {
                    txt = doc.CreateTextNode(string.Format("#idC{0}", gt.ID));
                }
                else
                {
                    txt = doc.CreateTextNode(string.Format("#id{0}", gt.ID));
                }
                el.AppendChild(txt);
                placemark.AppendChild(el);

                el = doc.CreateElement("description");
                string descr = string.Format("<table width='250'><tr><td align='center'><a href='{0}'>{1}</a><br><font size='4'><b>{2}</b></font><br /><i>{3} {4}</i><br /><br /><img src='Images/{5}' /> <br /><br />{6}: {7}<br />{8}: {9}<br />{10}: {11}<br /><br />({12})<br><br></td></tr></table>", g.Url, g.Code, g.Name ?? "", HttpUtility.HtmlEncode(Utils.LanguageSupport.Instance.GetTranslation(STR_BY)), g.Owner ?? "", Path.GetFileName(destImg), HttpUtility.HtmlEncode(Utils.LanguageSupport.Instance.GetTranslation(STR_DIFFICULTY)), g.Difficulty.ToString("0.#"), HttpUtility.HtmlEncode(Utils.LanguageSupport.Instance.GetTranslation(STR_TERRAIN)), g.Terrain.ToString("0.#"), HttpUtility.HtmlEncode(Utils.LanguageSupport.Instance.GetTranslation(STR_CONTAINER)), HttpUtility.HtmlEncode(Utils.LanguageSupport.Instance.GetTranslation(g.Container.Name)), Utils.Conversion.GetCoordinatesPresentation(g.Lat, g.Lon));
                txt = doc.CreateTextNode(descr);
                el.AppendChild(txt);
                placemark.AppendChild(el);

                el  = doc.CreateElement("Snippet");
                txt = doc.CreateTextNode(string.Format("<a href='{0}'>{1}</a> {2}<br>{3} {4}", g.Url, g.Code, g.Name ?? "", Utils.LanguageSupport.Instance.GetTranslation(STR_BY), g.Owner ?? ""));
                el.AppendChild(txt);
                placemark.AppendChild(el);

                XmlElement point = doc.CreateElement("Point");
                placemark.AppendChild(point);
                el = doc.CreateElement("coordinates");
                if (g.ContainsCustomLatLon)
                {
                    txt = doc.CreateTextNode(string.Format("{0},{1}", g.CustomLon.ToString().Replace(',', '.'), g.CustomLat.ToString().Replace(',', '.')));
                }
                else
                {
                    txt = doc.CreateTextNode(string.Format("{0},{1}", g.Lon.ToString().Replace(',', '.'), g.Lat.ToString().Replace(',', '.')));
                }
                el.AppendChild(txt);
                point.AppendChild(el);

                _indexDone++;
                if (_indexDone % 100 == 0)
                {
                    if (!progress.UpdateProgress(STR_EXPORTINGGPX, STR_CREATINGFILE, _gcList.Count, _indexDone))
                    {
                        result = false;
                        break;
                    }
                }
            }
            return(result);
        }
예제 #35
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;
        }
예제 #36
0
파일: ImportGSAK.cs 프로젝트: RH-Code/GAPP
        protected override void ImportMethod()
        {
            System.Collections.Hashtable logTypes = new System.Collections.Hashtable();
            using (Utils.ProgressBlock fixpr = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTINGDATA, 1, 0))
            {
                String connect = String.Format("data source=file:{0}", _filename);
                using (SqliteConnection dbcon = new SqliteConnection(connect))
                {

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

                    dbcon.Open();

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

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


                    int gcCount = (int)(long)import.ExecuteScalar();
                    if (gcCount > 0)
                    {
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTINGGEOCACHES, gcCount, 0))
                        {

                            bool isPremiumAvailable = false;
                            bool isFavPointAvailable = false;
                            bool isGCNoteAvailable = false;

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

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

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

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

                            SqliteDataReader dr = import.ExecuteReader();

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

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

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

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

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

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

                                gc.Selected = false;

                                Calculus.SetDistanceAndAngleGeocacheFromLocation(gc, Core.CenterLocation);

                                AddGeocache(gc, null);
                                index++;
                                procStep++;
                                if (procStep >= 500)
                                {
                                    progress.UpdateProgress(STR_IMPORTING, STR_IMPORTINGGEOCACHES, gcCount, index);
                                    procStep = 0;
                                }
                            }
                            dr.Close();
                        }

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

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

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

                                    AddLog(lg);

                                    index++;
                                    procStep++;
                                    if (procStep >= 1000)
                                    {
                                        progress.UpdateProgress(STR_IMPORTING, STR_IMPORTINGLOGS, logCount, index);
                                        procStep = 0;
                                    }
                                }
                                dr.Close();
                            }
                        }
                        import.CommandText = "select count(1) from logimages";

                        int logimgCount = 0;
                        try
                        {
                            logimgCount = (int)(long)import.ExecuteScalar();
                        }
                        catch
                        {
                            //table does not exists
                        }
                        if (logimgCount > 0)
                        {
                            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTINGLOGIMAGES, logimgCount, 0))
                            {
                                index = 0;
                                procStep = 0;
                                import.CommandText = "select iCode, iLogId, iImage, iName from logimages";
                                DbDataReader dr = import.ExecuteReader();
                                while (dr.Read())
                                {
                                    Framework.Data.LogImage lg = new Framework.Data.LogImage();

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

                                    AddLogImage(lg);

                                    index++;
                                    procStep++;
                                    if (procStep >= 500)
                                    {
                                        progress.UpdateProgress(STR_IMPORTING, STR_IMPORTINGLOGIMAGES, logimgCount, index);
                                        procStep = 0;
                                    }
                                }
                                dr.Close();
                            }
                        }
                        //id text, code text, geocachecode text, name text, datafromdate text, comment text, description text, url text, urlname text, wptype integer, lat real, lon real, time text
                        import.CommandText = "select count(1) from waypoints";

                        int wptCount = (int)(long)import.ExecuteScalar();
                        if (wptCount > 0)
                        {
                            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTINGWAYPOINTS, wptCount, 0))
                            {
                                index = 0;
                                procStep = 0;
                                import.CommandText = "select w.cParent, w.cCode, cName, cDate, cType, cLat, cLon," +
                                    " cComment, cUrl" +
                                    " from waypoints w" +
                                    " inner join wayMemo m on w.cParent = m.cParent and w.cCode=m.cCode";
                                DbDataReader dr = import.ExecuteReader();
                                while (dr.Read())
                                {
                                    Framework.Data.Waypoint wp = new Framework.Data.Waypoint();

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

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

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

                                    AddWaypoint(wp);

                                    index++;
                                    procStep++;
                                    if (procStep >= 500)
                                    {
                                        progress.UpdateProgress(STR_IMPORTING, STR_IMPORTINGWAYPOINTS, wptCount, index);
                                        procStep = 0;
                                    }
                                }
                                dr.Close();
                            }
                        }

                        try
                        {
                            //import corrected if table exists
                            import.CommandText = "select kCode, kAfterLat, kAfterLon from Corrected";
                            DbDataReader dr = import.ExecuteReader();
                            while (dr.Read())
                            {
                                string gcCode = dr["kCode"] as string ?? "";
                                Framework.Data.Geocache gc = Utils.DataAccess.GetGeocache(Core.Geocaches, gcCode);
                                if (gc != null)
                                {
                                    object oLat = dr["kAfterLat"];
                                    object oLon = dr["kAfterLon"];
                                    if (oLat != null && oLat.GetType() != typeof(DBNull) &&
                                        oLon != null && oLon.GetType() != typeof(DBNull))
                                    {
                                        string sLat = oLat as string;
                                        string sLon = oLon as string;
                                        if (sLat.Length > 0 && sLon.Length > 0)
                                        {
                                            gc.CustomLat = Utils.Conversion.StringToDouble(sLat);
                                            gc.CustomLon = Utils.Conversion.StringToDouble(sLon);
                                        }
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }

                    }
                }
            }
        }
예제 #37
0
        protected override void ImportMethod()
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(_filename);

            XmlNodeList nl = doc.SelectNodes("/gccomment/comment");

            if (nl != null)
            {
                if (_importMissing)
                {
                    List <string> gcList = new List <string>();
                    foreach (XmlNode n in nl)
                    {
                        string gcCode = n.SelectSingleNode("gccode").InnerText;
                        Framework.Data.Geocache gc = Utils.DataAccess.GetGeocache(Core.Geocaches, gcCode);
                        if (gc == null)
                        {
                            gcList.Add(gcCode);
                        }
                    }
                    if (gcList.Count > 0)
                    {
                        Utils.GeocacheIgnoreSupport.Instance.FilterGeocaches(gcList);
                    }
                    if (gcList.Count > 0)
                    {
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORTING, STR_IMPORTING, gcList.Count, 0, true))
                        {
                            using (Utils.API.GeocachingLiveV6 client = new Utils.API.GeocachingLiveV6(Core, string.IsNullOrEmpty(Core.GeocachingComAccount.APIToken)))
                            {
                                int      index = 0;
                                int      total = gcList.Count;
                                int      gcupdatecount;
                                TimeSpan interval = new TimeSpan(0, 0, 0, 2, 100);
                                DateTime prevCall = DateTime.MinValue;
                                bool     dodelay;
                                gcupdatecount = 30;
                                dodelay       = (gcList.Count > 30);
                                while (gcList.Count > 0)
                                {
                                    if (dodelay)
                                    {
                                        TimeSpan ts = DateTime.Now - prevCall;
                                        if (ts < interval)
                                        {
                                            Thread.Sleep(interval - ts);
                                        }
                                    }
                                    GlobalcachingApplication.Utils.API.LiveV6.SearchForGeocachesRequest req = new GlobalcachingApplication.Utils.API.LiveV6.SearchForGeocachesRequest();
                                    req.IsLite               = Core.GeocachingComAccount.MemberTypeId == 1;
                                    req.AccessToken          = client.Token;
                                    req.CacheCode            = new GlobalcachingApplication.Utils.API.LiveV6.CacheCodeFilter();
                                    req.CacheCode.CacheCodes = (from a in gcList select a).Take(gcupdatecount).ToArray();
                                    req.MaxPerPage           = gcupdatecount;
                                    req.GeocacheLogCount     = 5;
                                    index += req.CacheCode.CacheCodes.Length;
                                    gcList.RemoveRange(0, req.CacheCode.CacheCodes.Length);
                                    prevCall = DateTime.Now;
                                    var resp = client.Client.SearchForGeocaches(req);
                                    if (resp.Status.StatusCode == 0 && resp.Geocaches != null)
                                    {
                                        Utils.API.Import.AddGeocaches(Core, resp.Geocaches);
                                    }
                                    else
                                    {
                                        _errormessage = resp.Status.StatusMessage;
                                        break;
                                    }
                                    if (!progress.UpdateProgress(STR_IMPORTING, STR_IMPORTING, total, index))
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                foreach (XmlNode n in nl)
                {
                    string gcCode = n.SelectSingleNode("gccode").InnerText;
                    Framework.Data.Geocache gc = Utils.DataAccess.GetGeocache(Core.Geocaches, gcCode);
                    if (gc != null)
                    {
                        gc.Notes = HttpUtility.HtmlEncode(n.SelectSingleNode("content").InnerText).Replace("\r", "").Replace("\n", "<br />");
                    }
                }
            }
        }
예제 #38
0
        private bool insertFromDatabase(bool overwrite)
        {
            bool result = false;

            try
            {
                int    lsize     = sizeof(long);
                byte[] memBuffer = new byte[10 * 1024 * 1024];
                using (MemoryStream ms = new MemoryStream(memBuffer))
                    using (BinaryReader br = new BinaryReader(ms))
                        using (FileCollection fc = new FileCollection(_selectedInsertFromFilename))
                        {
                            int gcCount          = 0;
                            int logCount         = 0;
                            int logimgCount      = 0;
                            int geocacheimgCount = 0;
                            int wptCount         = 0;
                            int usrwptCount      = 0;

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

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

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

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

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

                                            bool newGeocache;
                                            Framework.Data.Geocache gc = Utils.DataAccess.GetGeocache(Core.Geocaches, ri.ID);
                                            if (gc == null)
                                            {
                                                gc = new Framework.Data.Geocache();
                                                htInsertedGeocaches.Add(ri.ID, gc);
                                                newGeocache = true;
                                            }
                                            else
                                            {
                                                if (overwrite || htInsertedGeocaches[ri.ID] != null)
                                                {
                                                    newGeocache = false;
                                                }
                                                else
                                                {
                                                    continue;
                                                }
                                            }
                                            gc.BeginUpdate();
                                            try
                                            {
                                                gc.Code         = ri.ID;
                                                gc.Archived     = br.ReadBoolean();
                                                gc.AttributeIds = ReadIntegerArray(br);
                                                gc.Available    = br.ReadBoolean();
                                                gc.City         = br.ReadString();
                                                gc.Container    = Utils.DataAccess.GetGeocacheContainer(Core.GeocacheContainers, br.ReadInt32());
                                                gc.CustomCoords = br.ReadBoolean();
                                                gc.Country      = br.ReadString();
                                                if (br.ReadBoolean())
                                                {
                                                    gc.CustomLat = br.ReadDouble();
                                                    gc.CustomLon = br.ReadDouble();
                                                }
                                                gc.Difficulty    = br.ReadDouble();
                                                gc.EncodedHints  = br.ReadString();
                                                gc.Favorites     = br.ReadInt32();
                                                gc.Flagged       = br.ReadBoolean();
                                                gc.Found         = br.ReadBoolean();
                                                gc.GeocacheType  = Utils.DataAccess.GetGeocacheType(Core.GeocacheTypes, br.ReadInt32());
                                                gc.ID            = br.ReadString();
                                                gc.Lat           = br.ReadDouble();
                                                gc.Lon           = br.ReadDouble();
                                                gc.MemberOnly    = br.ReadBoolean();
                                                gc.Municipality  = br.ReadString();
                                                gc.Name          = br.ReadString();
                                                gc.Notes         = br.ReadString();
                                                gc.Owner         = br.ReadString();
                                                gc.OwnerId       = br.ReadString();
                                                gc.PersonaleNote = br.ReadString();
                                                gc.PlacedBy      = br.ReadString();
                                                gc.PublishedTime = DateTime.Parse(br.ReadString());
                                                gc.State         = br.ReadString();
                                                gc.Terrain       = br.ReadDouble();
                                                gc.Title         = br.ReadString();
                                                gc.Url           = br.ReadString();
                                                gc.DataFromDate  = DateTime.Parse(br.ReadString());
                                                gc.Locked        = br.ReadBoolean();

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

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

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

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

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

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

                                            bool newLog;
                                            bool logComplete       = true;
                                            Framework.Data.Log log = Utils.DataAccess.GetLog(Core.Logs, ri.ID);
                                            if (log == null)
                                            {
                                                newLog = true;
                                                log    = htInsertedLogs[ri.ID] as Framework.Data.Log;
                                                if (log == null)
                                                {
                                                    log = new Framework.Data.Log();
                                                    htInsertedLogs.Add(ri.ID, log);
                                                    logComplete = false;
                                                }
                                                else
                                                {
                                                    logComplete = true;
                                                }
                                            }
                                            else
                                            {
                                                if (overwrite)
                                                {
                                                    newLog = false;
                                                }
                                                else
                                                {
                                                    continue;
                                                }
                                            }
                                            log.BeginUpdate();
                                            try
                                            {
                                                log.ID           = ri.ID;
                                                log.DataFromDate = DateTime.Parse(br.ReadString());
                                                log.Date         = DateTime.Parse(br.ReadString());
                                                log.Finder       = br.ReadString();
                                                log.GeocacheCode = br.ReadString();
                                                log.ID           = br.ReadString();
                                                log.LogType      = Utils.DataAccess.GetLogType(Core.LogTypes, br.ReadInt32());
                                            }
                                            catch
                                            {
                                            }
                                            log.EndUpdate();

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

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


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

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

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

                                                wp.BeginUpdate();
                                                try
                                                {
                                                    wp.Code         = ri.ID;
                                                    wp.Comment      = br.ReadString();
                                                    wp.DataFromDate = DateTime.Parse(br.ReadString());
                                                    wp.Description  = br.ReadString();
                                                    wp.GeocacheCode = br.ReadString();
                                                    wp.ID           = br.ReadString();
                                                    if (br.ReadBoolean())
                                                    {
                                                        wp.Lat = br.ReadDouble();
                                                        wp.Lon = br.ReadDouble();
                                                    }
                                                    wp.Name    = br.ReadString();
                                                    wp.Time    = DateTime.Parse(br.ReadString());
                                                    wp.Url     = br.ReadString();
                                                    wp.UrlName = br.ReadString();
                                                    wp.WPType  = Utils.DataAccess.GetWaypointType(Core.WaypointTypes, br.ReadInt32());
                                                }
                                                catch
                                                {
                                                }
                                                wp.EndUpdate();
                                                if (newWp)
                                                {
                                                    if (Utils.DataAccess.GetGeocache(Core.Geocaches, wp.GeocacheCode ?? "") != null)
                                                    {
                                                        Core.Waypoints.Add(wp);
                                                    }
                                                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                                wp.EndUpdate();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                result = true;
            }
            catch
            {
            }
            return(result);
        }