Exemple #1
0
 public async void ExportToGGZ(string filename, List<Framework.Data.Geocache> gcList, Utils.GPXGenerator gpxGenerator)
 {
     _filename = filename;
     _gcList = gcList;
     _gpxGenerator = gpxGenerator;
     await PerformExport();
     _gcList = null;
 }
Exemple #2
0
        public async void ExportToGGZ(string filename, List <Framework.Data.Geocache> gcList, Utils.GPXGenerator gpxGenerator)
        {
            _filename     = filename;
            _gcList       = gcList;
            _gpxGenerator = gpxGenerator;
            await PerformExport();

            _gcList = null;
        }
Exemple #3
0
        public async override Task <bool> ActionAsync(string action)
        {
            bool result = base.Action(action);

            if (result)
            {
                if (action == ACTION_EXPORT_ALL || action == ACTION_EXPORT_SELECTED || action == ACTION_EXPORT_ACTIVE)
                {
                    if (action == ACTION_EXPORT_ALL)
                    {
                        _gcList = (from Framework.Data.Geocache a in Core.Geocaches select a).ToList();
                    }
                    else if (action == ACTION_EXPORT_SELECTED)
                    {
                        _gcList = Utils.DataAccess.GetSelectedGeocaches(Core.Geocaches);
                    }
                    else
                    {
                        if (Core.ActiveGeocache != null)
                        {
                            _gcList = new List <Framework.Data.Geocache>();
                            _gcList.Add(Core.ActiveGeocache);
                        }
                    }
                    if (_gcList == null || _gcList.Count == 0)
                    {
                        System.Windows.Forms.MessageBox.Show(Utils.LanguageSupport.Instance.GetTranslation(STR_NOGEOCACHESELECTED), Utils.LanguageSupport.Instance.GetTranslation(STR_ERROR), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    }
                    else
                    {
                        using (System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog())
                        {
                            dlg.FileName = "";
                            dlg.Filter   = "*.ggz|*.ggz";
                            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                _filename     = dlg.FileName;
                                _gpxGenerator = new Utils.GPXGenerator(Core, _gcList, string.IsNullOrEmpty(PluginSettings.Instance.GPXVersionStr) ? Utils.GPXGenerator.V101 : Version.Parse(PluginSettings.Instance.GPXVersionStr));
                                _gpxGenerator.MaxNameLength    = PluginSettings.Instance.MaxGeocacheNameLength;
                                _gpxGenerator.MinStartOfname   = PluginSettings.Instance.MinStartOfGeocacheName;
                                _gpxGenerator.UseNameForGCCode = PluginSettings.Instance.UseNameAndNotCode;
                                _gpxGenerator.AddAdditionWaypointsToDescription = PluginSettings.Instance.AddWaypointsToDescription;
                                _gpxGenerator.UseHintsForDescription            = PluginSettings.Instance.UseHintsForDescription;
                                _gpxGenerator.AddFieldnotesToDescription        = PluginSettings.Instance.AddFieldNotesToDescription;
                                _gpxGenerator.ExtraCoordPrefix          = PluginSettings.Instance.CorrectedNamePrefix;
                                _gpxGenerator.AddExtraInfoToDescription = PluginSettings.Instance.AddExtraInfoToDescription;
                                _gpxGenerator.MaxLogCount = PluginSettings.Instance.MaximumNumberOfLogs;
                                await PerformExport();
                            }
                        }
                    }
                    _gcList = null;
                }
            }
            return(result);
        }
Exemple #4
0
 public async override Task<bool> ActionAsync(string action)
 {
     bool result = base.Action(action);
     if (result)
     {
         if (action == ACTION_EXPORT_ALL || action == ACTION_EXPORT_SELECTED || action == ACTION_EXPORT_ACTIVE)
         {
             if (action == ACTION_EXPORT_ALL)
             {
                 _gcList = (from Framework.Data.Geocache a in Core.Geocaches select a).ToList();
             }
             else if (action == ACTION_EXPORT_SELECTED)
             {
                 _gcList = Utils.DataAccess.GetSelectedGeocaches(Core.Geocaches);
             }
             else
             {
                 if (Core.ActiveGeocache != null)
                 {
                     _gcList = new List<Framework.Data.Geocache>();
                     _gcList.Add(Core.ActiveGeocache);
                 }
             }
             if (_gcList == null || _gcList.Count == 0)
             {
                 System.Windows.Forms.MessageBox.Show(Utils.LanguageSupport.Instance.GetTranslation(STR_NOGEOCACHESELECTED), Utils.LanguageSupport.Instance.GetTranslation(STR_ERROR), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
             }
             else
             {
                 using (System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog())
                 {
                     dlg.FileName = "";
                     dlg.Filter = "*.ggz|*.ggz";
                     if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                     {
                         _filename = dlg.FileName;
                         _gpxGenerator = new Utils.GPXGenerator(Core, _gcList, string.IsNullOrEmpty(PluginSettings.Instance.GPXVersionStr) ? Utils.GPXGenerator.V101 : Version.Parse(PluginSettings.Instance.GPXVersionStr));
                         _gpxGenerator.MaxNameLength = PluginSettings.Instance.MaxGeocacheNameLength;
                         _gpxGenerator.MinStartOfname = PluginSettings.Instance.MinStartOfGeocacheName;
                         _gpxGenerator.UseNameForGCCode = PluginSettings.Instance.UseNameAndNotCode;
                         _gpxGenerator.AddAdditionWaypointsToDescription = PluginSettings.Instance.AddWaypointsToDescription;
                         _gpxGenerator.UseHintsForDescription = PluginSettings.Instance.UseHintsForDescription;
                         _gpxGenerator.AddFieldnotesToDescription = PluginSettings.Instance.AddFieldNotesToDescription;
                         _gpxGenerator.ExtraCoordPrefix = PluginSettings.Instance.CorrectedNamePrefix;
                         _gpxGenerator.AddExtraInfoToDescription = PluginSettings.Instance.AddExtraInfoToDescription;
                         _gpxGenerator.MaxLogCount = PluginSettings.Instance.MaximumNumberOfLogs;
                         await PerformExport();
                     }
                 }
             }
             _gcList = null;
         }
     }
     return result;
 }
        protected override void ExportMethod()
        {
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_EXPORTINGGPX, STR_CREATINGFILE, _gcList.Count, 0))
            {
                if (_oneGeocachePerFile)
                {
                    Utils.GPXGenerator gpxGenerator = new Utils.GPXGenerator(Core, _gcList, string.IsNullOrEmpty(PluginSettings.Instance.GPXVersionStr) ? Utils.GPXGenerator.V101 : Version.Parse(PluginSettings.Instance.GPXVersionStr));
                    gpxGenerator.UseNameForGCCode = _useName;
                    gpxGenerator.AddAdditionWaypointsToDescription = PluginSettings.Instance.AddWaypointsToDescription;
                    gpxGenerator.UseHintsForDescription            = PluginSettings.Instance.UseHintsForDescription;
                    gpxGenerator.AddFieldnotesToDescription        = PluginSettings.Instance.AddFieldNotesToDescription;
                    gpxGenerator.MaxNameLength             = PluginSettings.Instance.MaxGeocacheNameLength;
                    gpxGenerator.MinStartOfname            = PluginSettings.Instance.MinStartOfGeocacheName;
                    gpxGenerator.ExtraCoordPrefix          = PluginSettings.Instance.CorrectedNamePrefix;
                    gpxGenerator.AddExtraInfoToDescription = PluginSettings.Instance.AddExtraInfoToDescription;
                    gpxGenerator.MaxLogCount = PluginSettings.Instance.MaximumNumberOfLogs;
                    using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(false))
                    {
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.UTF8))
                        {
                            int block = 0;
                            //generate header
                            sw.Write(gpxGenerator.Start());
                            //preserve mem and do for each cache the export
                            for (int i = 0; i < gpxGenerator.Count; i++)
                            {
                                sw.WriteLine(gpxGenerator.Next());
                                if (_addChildWaypoints)
                                {
                                    string s = gpxGenerator.WaypointData();
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        sw.WriteLine(s);
                                    }
                                }
                                block++;
                                if (block > 10)
                                {
                                    block = 0;
                                    progress.UpdateProgress(STR_EXPORTINGGPX, STR_CREATINGFILE, gpxGenerator.Count, i + 1);
                                }
                            }
                            //finalize
                            sw.Write(gpxGenerator.Finish());
                        }

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

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

                            block++;
                            if (block > 10)
                            {
                                block = 0;
                                progress.UpdateProgress(STR_EXPORTINGGPX, STR_CREATINGFILE, _gcList.Count, i + 1);
                            }
                        }
                    }
                }
            }
        }
        public async override Task <bool> ActionAsync(string action)
        {
            bool result = base.Action(action);

            if (result)
            {
                if (action == ACTION_EXPORT_ALL || action == ACTION_EXPORT_SELECTED || action == ACTION_EXPORT_ACTIVE)
                {
                    if (action == ACTION_EXPORT_ALL)
                    {
                        _gcList = (from Framework.Data.Geocache a in Core.Geocaches select a).ToList();
                    }
                    else if (action == ACTION_EXPORT_SELECTED)
                    {
                        _gcList = Utils.DataAccess.GetSelectedGeocaches(Core.Geocaches);
                    }
                    else
                    {
                        if (Core.ActiveGeocache != null)
                        {
                            _gcList = new List <Framework.Data.Geocache>();
                            _gcList.Add(Core.ActiveGeocache);
                        }
                    }
                    if (_gcList == null || _gcList.Count == 0)
                    {
                        System.Windows.Forms.MessageBox.Show(Utils.LanguageSupport.Instance.GetTranslation(STR_NOGEOCACHESELECTED), Utils.LanguageSupport.Instance.GetTranslation(STR_ERROR), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    }
                    else
                    {
                        using (SelectDeviceForm dlg = new SelectDeviceForm())
                        {
                            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                if (PluginSettings.Instance.CreateGGZFile)
                                {
                                    Utils.BasePlugin.Plugin p = Utils.PluginSupport.PluginByName(Core, "GlobalcachingApplication.Plugins.ExportGPX.GgzExport") as Utils.BasePlugin.Plugin;
                                    if (p != null)
                                    {
                                        var m = p.GetType().GetMethod("ExportToGGZ");
                                        if (m != null)
                                        {
                                            Utils.GPXGenerator gpxGenerator = new Utils.GPXGenerator(Core, _gcList, string.IsNullOrEmpty(PluginSettings.Instance.GPXVersionStr) ? Utils.GPXGenerator.V101 : Version.Parse(PluginSettings.Instance.GPXVersionStr));
                                            gpxGenerator.UseNameForGCCode = _useName;
                                            gpxGenerator.AddAdditionWaypointsToDescription = PluginSettings.Instance.AddWaypointsToDescription;
                                            gpxGenerator.UseHintsForDescription            = PluginSettings.Instance.UseHintsForDescription;
                                            gpxGenerator.AddFieldnotesToDescription        = PluginSettings.Instance.AddFieldNotesToDescription;
                                            gpxGenerator.MaxNameLength             = PluginSettings.Instance.MaxGeocacheNameLength;
                                            gpxGenerator.MinStartOfname            = PluginSettings.Instance.MinStartOfGeocacheName;
                                            gpxGenerator.ExtraCoordPrefix          = PluginSettings.Instance.CorrectedNamePrefix;
                                            gpxGenerator.AddExtraInfoToDescription = PluginSettings.Instance.AddExtraInfoToDescription;
                                            gpxGenerator.MaxLogCount = PluginSettings.Instance.MaximumNumberOfLogs;

                                            string filename = "geocaches.ggz";
                                            if (PluginSettings.Instance.UseDatabaseNameForFileName)
                                            {
                                                Framework.Interfaces.IPluginInternalStorage storage = (from Framework.Interfaces.IPluginInternalStorage a in Core.GetPlugin(Framework.PluginType.InternalStorage) select a).FirstOrDefault();
                                                if (storage != null)
                                                {
                                                    var si = storage.ActiveStorageDestination;
                                                    if (si != null)
                                                    {
                                                        string s   = storage.ActiveStorageDestination.Name;
                                                        int    pos = s.LastIndexOf('.');
                                                        if (pos < 0)
                                                        {
                                                            filename = string.Format("{0}.ggz", s);
                                                        }
                                                        else
                                                        {
                                                            filename = string.Format("{0}.ggz", s.Substring(0, pos));
                                                        }
                                                    }
                                                }
                                            }
                                            try
                                            {
                                                if (!System.IO.Directory.Exists(System.IO.Path.Combine(new string[] { dlg.SelectedDrive, "garmin", "ggz" })))
                                                {
                                                    System.IO.Directory.CreateDirectory(System.IO.Path.Combine(new string[] { dlg.SelectedDrive, "garmin", "ggz" }));
                                                }
                                            }
                                            catch
                                            {
                                            }
                                            m.Invoke(p, new object[] { System.IO.Path.Combine(new string[] { dlg.SelectedDrive, "garmin", "ggz", filename }), _gcList, gpxGenerator });
                                        }
                                    }
                                }
                                else
                                {
                                    _oneGeocachePerFile = !dlg.SeperateFilePerGeocache;
                                    _drive             = dlg.SelectedDrive;
                                    _addChildWaypoints = dlg.AddChildWaypoints;
                                    _useName           = dlg.UseName;
                                    if (!string.IsNullOrEmpty(_drive))
                                    {
                                        await PerformExport();
                                    }
                                }

                                if (PluginSettings.Instance.AddImages)
                                {
                                    Utils.BasePlugin.Plugin p = Utils.PluginSupport.PluginByName(Core, "GlobalcachingApplication.Plugins.ImgGrab.ImageGrabber") as Utils.BasePlugin.Plugin;
                                    if (p != null)
                                    {
                                        var m = p.GetType().GetMethod("CreateImageFolderForGeocaches");
                                        if (m != null)
                                        {
                                            m.Invoke(p, new object[] { _gcList, System.IO.Path.Combine(new string[] { dlg.SelectedDrive, "garmin" }) });
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(result);
        }
        protected override void PerformExport(object settings)
        {
            var gpxSetting = settings as ExportGPXSettings;
            if (gpxSetting != null && !string.IsNullOrEmpty(gpxSetting.FileName))
            {
                bool canceled = false;
                try
                {
                    using (var db = new NPoco.Database(this.DatabaseConnection.Connection, NPoco.DatabaseType.SQLite))
                    {
                        double minLat = 0, minLon = 0, maxLat = 0, maxLon = 0;
                        var dr = DatabaseConnection.ExecuteReader(string.Format("select Min(Latitude), Max(Latitude), Min(Longitude), Max(Longitude) from Caches inner join {0} on Caches.Code={0}.gccode", ActionInputTableName));
                        if (dr.Read())
                        {
                            minLat = Utils.Conversion.StringToDouble(dr.GetString(0));
                            maxLat = Utils.Conversion.StringToDouble(dr.GetString(1));
                            minLon = Utils.Conversion.StringToDouble(dr.GetString(2));
                            maxLon = Utils.Conversion.StringToDouble(dr.GetString(3));
                        }
                        dr.Close();
                        var gcList = db.Fetch<string>(string.Format("select gccode from {0}", ActionInputTableName));
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ExportingGPX", "CreatingFile", gcList.Count, 0, true))
                        {
                            using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(false))
                            {
                                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.UTF8))
                                {
                                    Utils.GPXGenerator gpxGenerator = new Utils.GPXGenerator(
                                        db
                                        , gcList
                                        , gpxSetting.Version
                                        , minLat
                                        , maxLat
                                        , minLon
                                        , maxLon
                                        );

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

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

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

                                if (!canceled)
                                {
                                    if (gpxSetting.FileName.ToLower().EndsWith(".zip"))
                                    {
                                        using (FileStream zipToOpen = new FileStream(gpxSetting.FileName, FileMode.Create))
                                        {
                                            using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                                            {
                                                ZipArchiveEntry gpxEntry = archive.CreateEntry("geocaches.gpx");
                                                using (StreamWriter writer = new StreamWriter(gpxEntry.Open()))
                                                {
                                                    writer.Write(File.ReadAllText(gpxFile.Path));
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        System.IO.File.Copy(gpxFile.Path, gpxSetting.FileName, true);
                                    }
                                }
                            }
                        }
                    }
                }
                catch
                {
                }
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (Visible)
            {
                try
                {
                    bool ready = (bool)executeScript("isReady", null);
                    if (ready)
                    {
                        if (_running)
                        {
                            if (_nextIndex < _gcList.Count)
                            {
                                List<Framework.Data.Geocache> gcList = new List<Framework.Data.Geocache>();
                                gcList.Add(_gcList[_nextIndex]);

                                Utils.GPXGenerator gpxGenerator = new Utils.GPXGenerator(_core, gcList, string.IsNullOrEmpty(Properties.Settings.Default.GPXVersionStr) ? Utils.GPXGenerator.V101 : Version.Parse(Properties.Settings.Default.GPXVersionStr));
                                gpxGenerator.AddFieldnotesToDescription = Properties.Settings.Default.AddFieldNotesToDescription;
                                gpxGenerator.MaxNameLength = Properties.Settings.Default.MaxGeocacheNameLength;
                                gpxGenerator.MinStartOfname = Properties.Settings.Default.MinStartOfGeocacheName;
                                gpxGenerator.UseNameForGCCode = Properties.Settings.Default.UseNameAndNotCode;
                                gpxGenerator.AddAdditionWaypointsToDescription = Properties.Settings.Default.AddWaypointsToDescription;
                                gpxGenerator.UseHintsForDescription = Properties.Settings.Default.UseHintsForDescription;
                                gpxGenerator.ExtraCoordPrefix = Properties.Settings.Default.CorrectedNamePrefix;
                                
                                using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(true))
                                {
                                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.UTF8))
                                    {
                                        int block = 0;
                                        //generate header
                                        sw.Write(gpxGenerator.Start());
                                        //preserve mem and do for each cache the export
                                        for (int i = 0; i < gpxGenerator.Count; i++)
                                        {
                                            sw.WriteLine(gpxGenerator.Next());
                                            if (Properties.Settings.Default.AddChildWaypoints)
                                            {
                                                string s = gpxGenerator.WaypointData();
                                                if (!string.IsNullOrEmpty(s))
                                                {
                                                    sw.WriteLine(s);
                                                }
                                            }
                                            block++;
                                            if (block > 10)
                                            {
                                                block = 0;
                                            }
                                        }
                                        //finalize
                                        sw.Write(gpxGenerator.Finish());
                                    }
                                    executeScript("uploadGpx", new object[] { System.IO.File.ReadAllText(gpxFile.Path), string.Format("{0}.gpx", gcList[0].Code) });
                                }
                                _nextIndex++;
                                toolStripStatusLabel1.Text = string.Format("{0}/{1}", _nextIndex, _gcList.Count);
                                toolStripProgressBar1.Value = _nextIndex;
                            }
                            else
                            {
                                //done, close
                                timer1.Enabled = false;
                                Close();
                            }
                        }
                        else
                        {
                            button1.Enabled = true;
                        }
                    }
                }
                catch
                {
                }
            }
            else
            {
                timer1.Enabled = false;
            }
        }
        protected override void PerformExport(object settings)
        {
            var gpxSetting = settings as ExportGPXSettings;

            if (gpxSetting != null && !string.IsNullOrEmpty(gpxSetting.FileName))
            {
                bool canceled = false;
                try
                {
                    using (var db = new NPoco.Database(this.DatabaseConnection.Connection, NPoco.DatabaseType.SQLite))
                    {
                        double minLat = 0, minLon = 0, maxLat = 0, maxLon = 0;
                        if (DatabaseConnection.CurrentDataReader != null && !DatabaseConnection.CurrentDataReader.IsClosed)
                        {
                            DatabaseConnection.CurrentDataReader.Close();
                        }
                        var gcList = db.Fetch <GeocacheEntryInfo>(string.Format("select Code, Name, CacheType, Difficulty, Terrain, Found, Container, Latitude, Longitude, kAfterLat, kAfterLon from Caches inner join {0} on Caches.Code={0}.gccode left join Corrected on Caches.Code = Corrected.kCode", ActionInputTableName));
                        minLat = (from a in gcList select Utils.Conversion.StringToDouble(a.Latitude)).Min();
                        maxLat = (from a in gcList select Utils.Conversion.StringToDouble(a.Latitude)).Max();
                        minLon = (from a in gcList select Utils.Conversion.StringToDouble(a.Longitude)).Min();
                        maxLon = (from a in gcList select Utils.Conversion.StringToDouble(a.Longitude)).Max();
                        DateTime dt = DateTime.Now.AddSeconds(2);
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ExportingGPX", "CreatingFile", gcList.Count, 0, true))
                        {
                            using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(false))
                            {
                                using (ZipOutputStream s = new ZipOutputStream(System.IO.File.Create(gpxFile.Path)))
                                {
                                    s.SetLevel(9); // 0-9, 9 being the highest compression
                                    s.UseZip64 = UseZip64.Off;

                                    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.GPXGenerator gpxGenerator = new Utils.GPXGenerator(
                                        db
                                        , (from a in gcList select a.Code).ToList()
                                        , gpxSetting.Version
                                        , minLat
                                        , maxLat
                                        , minLon
                                        , maxLon
                                        );

                                    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(gpxSetting.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 <GeocacheEntryInfo> gpxBatchList = new List <GeocacheEntryInfo>();
                                        List <GeocacheEntryInfo> geiList      = new List <GeocacheEntryInfo>();
                                        geocacheIndex = 0;
                                        minLat        = (from a in gcList select Utils.Conversion.StringToDouble(a.Latitude)).Min();
                                        maxLat        = (from a in gcList select Utils.Conversion.StringToDouble(a.Latitude)).Max();
                                        minLon        = (from a in gcList select Utils.Conversion.StringToDouble(a.Longitude)).Min();
                                        maxLon        = (from a in gcList select Utils.Conversion.StringToDouble(a.Longitude)).Max();
                                        gpxGenerator.SetGeocacheList((from a in gcList select a.Code).ToList(), minLat, maxLat, minLon, maxLon);
                                        StringBuilder sb = new StringBuilder();
                                        gpxGenerator.Start();
                                        while (sb.Length < gpxSizeLimit && geocacheIndex < gpxGenerator.Count)
                                        {
                                            gpxBatchList.Add(gcList[geocacheIndex]);
                                            string gpxText = gpxGenerator.Next();

                                            gcList[geocacheIndex].FileLen = System.Text.UTF8Encoding.UTF8.GetBytes(gpxText).Length + 2;
                                            geiList.Add(gcList[geocacheIndex]);

                                            sb.AppendLine(gpxText);

                                            totalProcessed++;
                                            geocacheIndex++;

                                            if (DateTime.Now >= dt)
                                            {
                                                if (!progress.Update("CreatingFile", totalGeocaches, totalProcessed))
                                                {
                                                    canceled = true;
                                                    break;
                                                }
                                                dt = DateTime.Now.AddSeconds(2);
                                            }
                                        }
                                        sb.AppendLine(gpxGenerator.Finish());
                                        //insert gpx header
                                        minLat = (from a in gpxBatchList select Utils.Conversion.StringToDouble(a.Latitude)).Min();
                                        maxLat = (from a in gpxBatchList select Utils.Conversion.StringToDouble(a.Latitude)).Max();
                                        minLon = (from a in gpxBatchList select Utils.Conversion.StringToDouble(a.Longitude)).Min();
                                        maxLon = (from a in gpxBatchList select Utils.Conversion.StringToDouble(a.Longitude)).Max();
                                        gpxGenerator.SetGeocacheList((from a in gpxBatchList select a.Code).ToList(), minLat, maxLat, minLon, maxLon);
                                        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(gpxSetting.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.Code ?? "");
                                            el.AppendChild(txt);
                                            chgEl.AppendChild(el);

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

                                            el  = doc.CreateElement("type");
                                            txt = doc.CreateTextNode((from a in ApplicationData.Instance.GeocacheTypes where a.GSAK == gei.CacheType select a.GPXTag).FirstOrDefault() ?? "");
                                            el.AppendChild(txt);
                                            chgEl.AppendChild(el);

                                            el  = doc.CreateElement("lat");
                                            txt = doc.CreateTextNode(gei.kAfterLat ?? gei.Latitude);
                                            el.AppendChild(txt);
                                            chgEl.AppendChild(el);

                                            el  = doc.CreateElement("lon");
                                            txt = doc.CreateTextNode(gei.kAfterLon ?? gei.Longitude);
                                            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.Difficulty.ToString("0.#").Replace(',', '.'));
                                            el.AppendChild(txt);
                                            ratingsEl.AppendChild(el);

                                            el = doc.CreateElement("size");
                                            switch ((from a in ApplicationData.Instance.GeocacheContainers where a.Name == gei.Container select a.ID).FirstOrDefault())
                                            {
                                            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.Terrain.ToString("0.#").Replace(',', '.'));
                                            el.AppendChild(txt);
                                            ratingsEl.AppendChild(el);

                                            if (gei.Found != 0)
                                            {
                                                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();
                                }

                                if (!canceled)
                                {
                                    System.IO.File.Copy(gpxFile.Path, gpxSetting.FileName, true);
                                }
                            }
                        }
                    }
                }
                catch
                {
                }
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (Visible)
            {
                try
                {
                    bool ready = (bool)executeScript("isReady", null);
                    if (ready)
                    {
                        if (_running)
                        {
                            if (_nextIndex < _gcList.Count)
                            {
                                List <Framework.Data.Geocache> gcList = new List <Framework.Data.Geocache>();
                                gcList.Add(_gcList[_nextIndex]);

                                Utils.GPXGenerator gpxGenerator = new Utils.GPXGenerator(_core, gcList, string.IsNullOrEmpty(PluginSettings.Instance.GPXVersionStr) ? Utils.GPXGenerator.V101 : Version.Parse(PluginSettings.Instance.GPXVersionStr));
                                gpxGenerator.AddFieldnotesToDescription = PluginSettings.Instance.AddFieldNotesToDescription;
                                gpxGenerator.MaxNameLength    = PluginSettings.Instance.MaxGeocacheNameLength;
                                gpxGenerator.MinStartOfname   = PluginSettings.Instance.MinStartOfGeocacheName;
                                gpxGenerator.UseNameForGCCode = PluginSettings.Instance.UseNameAndNotCode;
                                gpxGenerator.AddAdditionWaypointsToDescription = PluginSettings.Instance.AddWaypointsToDescription;
                                gpxGenerator.UseHintsForDescription            = PluginSettings.Instance.UseHintsForDescription;
                                gpxGenerator.ExtraCoordPrefix          = PluginSettings.Instance.CorrectedNamePrefix;
                                gpxGenerator.AddExtraInfoToDescription = PluginSettings.Instance.AddExtraInfoToDescription;
                                gpxGenerator.MaxLogCount = PluginSettings.Instance.MaximumNumberOfLogs;

                                using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(true))
                                {
                                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.UTF8))
                                    {
                                        int block = 0;
                                        //generate header
                                        sw.Write(gpxGenerator.Start());
                                        //preserve mem and do for each cache the export
                                        for (int i = 0; i < gpxGenerator.Count; i++)
                                        {
                                            sw.WriteLine(gpxGenerator.Next());
                                            if (PluginSettings.Instance.AddChildWaypoints)
                                            {
                                                string s = gpxGenerator.WaypointData();
                                                if (!string.IsNullOrEmpty(s))
                                                {
                                                    sw.WriteLine(s);
                                                }
                                            }
                                            block++;
                                            if (block > 10)
                                            {
                                                block = 0;
                                            }
                                        }
                                        //finalize
                                        sw.Write(gpxGenerator.Finish());
                                    }
                                    executeScript("uploadGpx", new object[] { System.IO.File.ReadAllText(gpxFile.Path), string.Format("{0}.gpx", gcList[0].Code) });
                                }
                                _nextIndex++;
                                toolStripStatusLabel1.Text  = string.Format("{0}/{1}", _nextIndex, _gcList.Count);
                                toolStripProgressBar1.Value = _nextIndex;
                            }
                            else
                            {
                                //done, close
                                timer1.Enabled = false;
                                Close();
                            }
                        }
                        else
                        {
                            button1.Enabled = true;
                        }
                    }
                }
                catch
                {
                }
            }
            else
            {
                timer1.Enabled = false;
            }
        }
Exemple #11
0
        protected override void ExportMethod()
        {
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_EXPORTINGGPX, STR_CREATINGFILE, _gcList.Count, 0))
            {
                if (_oneGeocachePerFile)
                {
                    Utils.GPXGenerator gpxGenerator = new Utils.GPXGenerator(Core, _gcList, string.IsNullOrEmpty(PluginSettings.Instance.GPXVersionStr) ? Utils.GPXGenerator.V101 : Version.Parse(PluginSettings.Instance.GPXVersionStr));
                    gpxGenerator.UseNameForGCCode = _useName;
                    gpxGenerator.AddAdditionWaypointsToDescription = PluginSettings.Instance.AddWaypointsToDescription;
                    gpxGenerator.UseHintsForDescription = PluginSettings.Instance.UseHintsForDescription;
                    gpxGenerator.AddFieldnotesToDescription = PluginSettings.Instance.AddFieldNotesToDescription;
                    gpxGenerator.MaxNameLength = PluginSettings.Instance.MaxGeocacheNameLength;
                    gpxGenerator.MinStartOfname = PluginSettings.Instance.MinStartOfGeocacheName;
                    gpxGenerator.ExtraCoordPrefix = PluginSettings.Instance.CorrectedNamePrefix;
                    gpxGenerator.AddExtraInfoToDescription = PluginSettings.Instance.AddExtraInfoToDescription;
                    gpxGenerator.MaxLogCount = PluginSettings.Instance.MaximumNumberOfLogs;
                    using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(false))
                    {
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.UTF8))
                        {
                            int block = 0;
                            //generate header
                            sw.Write(gpxGenerator.Start());
                            //preserve mem and do for each cache the export
                            for (int i = 0; i < gpxGenerator.Count; i++)
                            {
                                sw.WriteLine(gpxGenerator.Next());
                                if (_addChildWaypoints)
                                {
                                    string s = gpxGenerator.WaypointData();
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        sw.WriteLine(s);
                                    }
                                }
                                block++;
                                if (block > 10)
                                {
                                    block = 0;
                                    progress.UpdateProgress(STR_EXPORTINGGPX, STR_CREATINGFILE, gpxGenerator.Count, i + 1);
                                }
                            }
                            //finalize
                            sw.Write(gpxGenerator.Finish());
                        }

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

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

                            block++;
                            if (block > 10)
                            {
                                block = 0;
                                progress.UpdateProgress(STR_EXPORTINGGPX, STR_CREATINGFILE, _gcList.Count, i + 1);
                            }
                        }
                    }
                }
            }
        }
Exemple #12
0
        public async override Task<bool> ActionAsync(string action)
        {
            bool result = base.Action(action);
            if (result)
            {
                if (action == ACTION_EXPORT_ALL || action == ACTION_EXPORT_SELECTED || action == ACTION_EXPORT_ACTIVE)
                {
                    if (action == ACTION_EXPORT_ALL)
                    {
                        _gcList = (from Framework.Data.Geocache a in Core.Geocaches select a).ToList();
                    }
                    else if (action == ACTION_EXPORT_SELECTED)
                    {
                        _gcList = Utils.DataAccess.GetSelectedGeocaches(Core.Geocaches);
                    }
                    else
                    {
                        if (Core.ActiveGeocache != null)
                        {
                            _gcList = new List<Framework.Data.Geocache>();
                            _gcList.Add(Core.ActiveGeocache);
                        }
                    }
                    if (_gcList == null || _gcList.Count == 0)
                    {
                        System.Windows.Forms.MessageBox.Show(Utils.LanguageSupport.Instance.GetTranslation(STR_NOGEOCACHESELECTED), Utils.LanguageSupport.Instance.GetTranslation(STR_ERROR), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    }
                    else
                    {
                        using (SelectDeviceForm dlg = new SelectDeviceForm())
                        {
                            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                if (PluginSettings.Instance.CreateGGZFile)
                                {
                                    Utils.BasePlugin.Plugin p = Utils.PluginSupport.PluginByName(Core, "GlobalcachingApplication.Plugins.ExportGPX.GgzExport") as Utils.BasePlugin.Plugin;
                                    if (p != null)
                                    {
                                        var m = p.GetType().GetMethod("ExportToGGZ");
                                        if (m != null)
                                        {
                                            Utils.GPXGenerator gpxGenerator = new Utils.GPXGenerator(Core, _gcList, string.IsNullOrEmpty(PluginSettings.Instance.GPXVersionStr) ? Utils.GPXGenerator.V101 : Version.Parse(PluginSettings.Instance.GPXVersionStr));
                                            gpxGenerator.UseNameForGCCode = _useName;
                                            gpxGenerator.AddAdditionWaypointsToDescription = PluginSettings.Instance.AddWaypointsToDescription;
                                            gpxGenerator.UseHintsForDescription = PluginSettings.Instance.UseHintsForDescription;
                                            gpxGenerator.AddFieldnotesToDescription = PluginSettings.Instance.AddFieldNotesToDescription;
                                            gpxGenerator.MaxNameLength = PluginSettings.Instance.MaxGeocacheNameLength;
                                            gpxGenerator.MinStartOfname = PluginSettings.Instance.MinStartOfGeocacheName;
                                            gpxGenerator.ExtraCoordPrefix = PluginSettings.Instance.CorrectedNamePrefix;
                                            gpxGenerator.AddExtraInfoToDescription = PluginSettings.Instance.AddExtraInfoToDescription;
                                            gpxGenerator.MaxLogCount = PluginSettings.Instance.MaximumNumberOfLogs;

                                            string filename = "geocaches.ggz";
                                            if (PluginSettings.Instance.UseDatabaseNameForFileName)
                                            {
                                                Framework.Interfaces.IPluginInternalStorage storage = (from Framework.Interfaces.IPluginInternalStorage a in Core.GetPlugin(Framework.PluginType.InternalStorage) select a).FirstOrDefault();
                                                if (storage != null)
                                                {
                                                    var si = storage.ActiveStorageDestination;
                                                    if (si != null)
                                                    {
                                                        string s = storage.ActiveStorageDestination.Name;
                                                        int pos = s.LastIndexOf('.');
                                                        if (pos < 0)
                                                        {
                                                            filename = string.Format("{0}.ggz", s);
                                                        }
                                                        else
                                                        {
                                                            filename = string.Format("{0}.ggz", s.Substring(0, pos));
                                                        }
                                                    }
                                                }
                                            }
                                            try
                                            {
                                                if (!System.IO.Directory.Exists(System.IO.Path.Combine(new string[] { dlg.SelectedDrive, "garmin", "ggz" })))
                                                {
                                                    System.IO.Directory.CreateDirectory(System.IO.Path.Combine(new string[] { dlg.SelectedDrive, "garmin", "ggz" }));
                                                }
                                            }
                                            catch
                                            {
                                            }
                                            m.Invoke(p, new object[] { System.IO.Path.Combine(new string[] { dlg.SelectedDrive, "garmin", "ggz", filename }), _gcList, gpxGenerator });
                                        }
                                    }
                                }
                                else
                                {
                                    _oneGeocachePerFile = !dlg.SeperateFilePerGeocache;
                                    _drive = dlg.SelectedDrive;
                                    _addChildWaypoints = dlg.AddChildWaypoints;
                                    _useName = dlg.UseName;
                                    if (!string.IsNullOrEmpty(_drive))
                                    {
                                        await PerformExport();
                                    }
                                }

                                if (PluginSettings.Instance.AddImages)
                                {
                                    Utils.BasePlugin.Plugin p = Utils.PluginSupport.PluginByName(Core, "GlobalcachingApplication.Plugins.ImgGrab.ImageGrabber") as Utils.BasePlugin.Plugin;
                                    if (p != null)
                                    {
                                        var m = p.GetType().GetMethod("CreateImageFolderForGeocaches");
                                        if (m != null)
                                        {
                                            m.Invoke(p, new object[] { _gcList, System.IO.Path.Combine(new string[] { dlg.SelectedDrive, "garmin" }) });
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return result;
        }
Exemple #13
0
        protected override void PerformExport(object settings)
        {
            var gpxSetting = settings as ExportGPXSettings;

            if (gpxSetting != null && !string.IsNullOrEmpty(gpxSetting.FileName))
            {
                bool canceled = false;
                try
                {
                    using (var db = new NPoco.Database(this.DatabaseConnection.Connection, NPoco.DatabaseType.SQLite))
                    {
                        double minLat = 0, minLon = 0, maxLat = 0, maxLon = 0;
                        var    dr = DatabaseConnection.ExecuteReader(string.Format("select Min(Latitude), Max(Latitude), Min(Longitude), Max(Longitude) from Caches inner join {0} on Caches.Code={0}.gccode", ActionInputTableName));
                        if (dr.Read())
                        {
                            minLat = Utils.Conversion.StringToDouble(dr.GetString(0));
                            maxLat = Utils.Conversion.StringToDouble(dr.GetString(1));
                            minLon = Utils.Conversion.StringToDouble(dr.GetString(2));
                            maxLon = Utils.Conversion.StringToDouble(dr.GetString(3));
                        }
                        dr.Close();
                        var gcList = db.Fetch <string>(string.Format("select gccode from {0}", ActionInputTableName));
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ExportingGPX", "CreatingFile", gcList.Count, 0, true))
                        {
                            using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(false))
                            {
                                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.UTF8))
                                {
                                    Utils.GPXGenerator gpxGenerator = new Utils.GPXGenerator(
                                        db
                                        , gcList
                                        , gpxSetting.Version
                                        , minLat
                                        , maxLat
                                        , minLon
                                        , maxLon
                                        );

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

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

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

                                if (!canceled)
                                {
                                    if (gpxSetting.FileName.ToLower().EndsWith(".zip"))
                                    {
                                        using (FileStream zipToOpen = new FileStream(gpxSetting.FileName, FileMode.Create))
                                        {
                                            using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                                            {
                                                ZipArchiveEntry gpxEntry = archive.CreateEntry("geocaches.gpx");
                                                using (StreamWriter writer = new StreamWriter(gpxEntry.Open()))
                                                {
                                                    writer.Write(File.ReadAllText(gpxFile.Path));
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        System.IO.File.Copy(gpxFile.Path, gpxSetting.FileName, true);
                                    }
                                }
                            }
                        }
                    }
                }
                catch
                {
                }
            }
        }