public void TemporaryFile_has_FileAttributes_Temporary_by_default() { string path = string.Empty; using( TemporaryFile temporaryFile = new TemporaryFile( true, null ) ) { path = temporaryFile.Path; Assert.That( File.Exists( temporaryFile.Path ), Is.True ); Assert.That( (File.GetAttributes( temporaryFile.Path ) & FileAttributes.Temporary) == FileAttributes.Temporary, Is.True ); } Assert.That( File.Exists( path ), Is.False ); using( TemporaryFile temporaryFile = new TemporaryFile() ) { path = temporaryFile.Path; Assert.That( File.Exists( temporaryFile.Path ), Is.True ); Assert.That( (File.GetAttributes( temporaryFile.Path ) & FileAttributes.Temporary) == FileAttributes.Temporary, Is.True ); } Assert.That( File.Exists( path ), Is.False ); using( TemporaryFile temporaryFile = new TemporaryFile( true ) ) { path = temporaryFile.Path; Assert.That( File.Exists( temporaryFile.Path ), Is.True ); Assert.That( (File.GetAttributes( temporaryFile.Path ) & FileAttributes.Temporary) == FileAttributes.Temporary, Is.True ); } Assert.That( File.Exists( path ), Is.False ); }
public TempFileBuffer(byte[] data) { _file = new TemporaryFile(); using (var stream = File.OpenWrite(_file.Name)) { stream.Write(data, 0, data.Length); } _size = (uint)data.Length; }
public void File_can_be_initialized() { ////Arrange & Act using (var file = new TemporaryFile(new MemoryStream(new byte[] {1,2,3}))) { ////Assert file.Info.Refresh(); Assert.That(file.Info.Length, Is.EqualTo(3)); } }
public GarminCommunicatorForm(Framework.Interfaces.ICore core, List<Framework.Data.Geocache> gcList) { InitializeComponent(); _core = core; _gcList = gcList; if (Properties.Settings.Default.UpgradeNeeded) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.UpgradeNeeded = false; Properties.Settings.Default.Save(); } numericUpDown1.Value = Properties.Settings.Default.MaxGeocacheNameLength; numericUpDown2.Value = Properties.Settings.Default.MinStartOfGeocacheName; checkBox1.Checked = Properties.Settings.Default.AddFieldNotesToDescription; checkBox2.Checked = Properties.Settings.Default.AddChildWaypoints; checkBox3.Checked = Properties.Settings.Default.UseNameAndNotCode; checkBox4.Checked = Properties.Settings.Default.AddWaypointsToDescription; checkBox5.Checked = Properties.Settings.Default.UseHintsForDescription; comboBox2.Items.Add(Utils.GPXGenerator.V100); comboBox2.Items.Add(Utils.GPXGenerator.V101); comboBox2.Items.Add(Utils.GPXGenerator.V102); textBox1.Text = Properties.Settings.Default.CorrectedNamePrefix ?? ""; if (!string.IsNullOrEmpty(Properties.Settings.Default.GPXVersionStr)) { comboBox2.SelectedItem = Version.Parse(Properties.Settings.Default.GPXVersionStr); } else { comboBox2.SelectedIndex = 0; } button1.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_START); this.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_TITLE); this.checkBox1.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_INCLNOTES); this.checkBox2.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_ADDCHILDWAYPOINTS); this.checkBox3.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_USENAME); this.checkBox4.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_ADDWPTTODESCR); this.checkBox5.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_USEHINTSDESCR); this.label1.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_MAXNAMELENGTH); this.label2.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_MINSTARTNAME); this.label6.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_GPXVERSION); this.label10.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_EXTRACOORDNAMEPREFIX); tmpFile = new TemporaryFile(true); using (StreamReader textStreamReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("GlobalcachingApplication.Plugins.ExportGarmin.GarminCommunicator.html"))) { File.WriteAllText(tmpFile.Path, textStreamReader.ReadToEnd()); } webBrowser1.Navigate(string.Format("file://{0}", tmpFile.Path)); toolStripStatusLabel1.Text = string.Format("0/{0}", gcList.Count); toolStripProgressBar1.Maximum = gcList.Count; }
public void an_empty_extension_is_like_no_extension() { string path = string.Empty; using( TemporaryFile temporaryFile = new TemporaryFile( " " ) ) { path = temporaryFile.Path; Assert.That( File.Exists( temporaryFile.Path ), Is.True ); Assert.That( (File.GetAttributes( temporaryFile.Path ) & FileAttributes.Temporary) == FileAttributes.Temporary, Is.True ); } Assert.That( File.Exists( path ), Is.False ); }
public GarminCommunicatorForm() { InitializeComponent(); this.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_TITLE); tmpFile = new TemporaryFile(true); using (StreamReader textStreamReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("GlobalcachingApplication.Plugins.APILOGC.GarminCommunicator.html"))) { File.WriteAllText(tmpFile.Path, textStreamReader.ReadToEnd()); } webBrowser1.Navigate(string.Format("file://{0}", tmpFile.Path)); }
public void TestFile() { TestData testData1 = new TestData {Data = "Hello"}, testData2; using (var tempFile = new TemporaryFile("unit-tests")) { // Write and read file testData1.SaveXml(tempFile); testData2 = XmlStorage.LoadXml<TestData>(tempFile); } // Ensure data stayed the same testData2.Data.Should().Be(testData1.Data); }
public void Constructor1_LockedFileAsCodeBaseArgument_ShouldThrowFileLoad() { using (TemporaryFile file = new TemporaryFile()) { using (FileStream stream = new FileStream(file.FileName, FileMode.Open, FileAccess.Read, FileShare.None)) { ExceptionAssert.Throws<FileLoadException>(() => { new AssemblyCatalog(file.FileName); }); } } }
/// <summary> /// Verify that data is validly signed. /// </summary> /// <param name="data_to_verify">Stream to verify signature of.</param> /// <returns>true if the stream is signed with a key in the keyring, false otherwise.</returns> public Tuple<bool, string> Verify(Stream data_to_verify, Stream signature) { // We could avoid hitting the filesystem, and ideally we'd be using GPGME instead of shelling out, but this is... far easier. using (var tmp = new TemporaryFile("")) { using (var f = new FileStream(tmp.Path, FileMode.OpenOrCreate)) { signature.CopyTo(f); f.Flush(); } var res = Exec("--verify --no-permission-warning --keyring \"" + homedir + "\\rust-key.gpg\" " + tmp.Path + " -", data_to_verify); return Tuple.Create(res.Item1 == 0, res.Item2); } }
public void File_is_deleted_after_use() { ////Arrange FileInfo fileInfo; ////Act using (var file = new TemporaryFile()) using (var stream = file.Info.OpenWrite()) { fileInfo = file.Info; stream.WriteByte(1); } ////Assert fileInfo.Refresh(); Assert.That(!fileInfo.Exists); }
public void Can_copy_to_stream() { ////Arrange Stream result = new MemoryStream(); ////Act using (var file = new TemporaryFile()) { using (var stream = file.Info.OpenWrite()) stream.WriteByte(1); file.CopyTo(result); } ////Assert Assert.That(result.Length, Is.EqualTo(1)); }
public void TemporaryFileExtensionTest() { string path = string.Empty; using( TemporaryFile temporaryFile = new TemporaryFile( " " ) ) { path = temporaryFile.Path; Assert.That( File.Exists( temporaryFile.Path ), Is.True ); Assert.That( (File.GetAttributes( temporaryFile.Path ) & FileAttributes.Temporary) == FileAttributes.Temporary, Is.True ); } Assert.That( File.Exists( path ), Is.False ); using( TemporaryFile temporaryFile = new TemporaryFile( true, "." ) ) { path = temporaryFile.Path; Assert.That( File.Exists( temporaryFile.Path ), Is.True ); Assert.That( path.EndsWith( ".tmp." ), Is.True ); Assert.That( (File.GetAttributes( temporaryFile.Path ) & FileAttributes.Temporary) == FileAttributes.Temporary, Is.True ); } Assert.That( File.Exists( path ), Is.False ); using( TemporaryFile temporaryFile = new TemporaryFile( true, "tst" ) ) { path = temporaryFile.Path; Assert.That( File.Exists( temporaryFile.Path ), Is.True ); Assert.That( path.EndsWith( ".tmp.tst" ), Is.True ); Assert.That( (File.GetAttributes( temporaryFile.Path ) & FileAttributes.Temporary) == FileAttributes.Temporary, Is.True ); } Assert.That( File.Exists( path ), Is.False ); using( TemporaryFile temporaryFile = new TemporaryFile( true, ".tst" ) ) { path = temporaryFile.Path; Assert.That( File.Exists( temporaryFile.Path ), Is.True ); Assert.That( path.EndsWith( ".tmp.tst" ), Is.True ); Assert.That( (File.GetAttributes( temporaryFile.Path ) & FileAttributes.Temporary) == FileAttributes.Temporary, Is.True ); } Assert.That( File.Exists( path ), Is.False ); }
public void Clear() { if (tmpFile != null) { tmpFile.Dispose(); tmpFile = null; } }
private void getImageResult() { if (_busy || _originalImage==null) return; _busy = true; try { if (tmpFile == null) { tmpFile = new TemporaryFile(true); } //max size Size sz1 = Utils.ImageUtilities.GetNewSize(_originalImage.Size, new Size(PluginSettings.Instance.MaxImageWidth, PluginSettings.Instance.MaxImageHeight)); //scale size double f = (double)numericUpDown5.Value / 100.0; Size sz2 = Utils.ImageUtilities.GetNewSize(_originalImage.Size, new Size((int)((double)_originalImage.Width * f), (int)((double)_originalImage.Height * f))); //take smaller picture as result if (sz1.Width < sz2.Width || sz1.Height < sz2.Height) { //the limit is smaller than scaled image //adjust scale Utils.ImageUtilities.SaveJpeg(tmpFile.Path, Utils.ImageUtilities.ResizeImage(_originalImage, sz1.Width, sz1.Height), PluginSettings.Instance.ImageQuality); f = ((double)sz1.Width / (double)_originalImage.Size.Width); numericUpDown5.Value = (int)(f * 100.0); label19.Text = string.Format("{0} x {1}", sz1.Width, sz1.Height); } else { Utils.ImageUtilities.SaveJpeg(tmpFile.Path, Utils.ImageUtilities.ResizeImage(_originalImage, sz2.Width, sz2.Height), PluginSettings.Instance.ImageQuality); label19.Text = string.Format("{0} x {1}", sz2.Width, sz2.Height); } FileInfo fi = new FileInfo(tmpFile.Path); double MBcnt = (double)fi.Length / (1024.0 * 1024.0); label22.Text = string.Format("{0:0.000} MB", MBcnt); if (MBcnt <= PluginSettings.Instance.MaxImageSizeMB) { label22.ForeColor = Color.Black; } else { label22.ForeColor = Color.Red; } button2.Enabled = true; } catch { } _busy = false; return; }
private void getImagesThreadMethod() { Framework.Data.Geocache gc = null; lock (_gcList) { if (_gcList.Count > 0) { gc = _gcList[0]; _gcList.RemoveAt(0); } } using (System.Net.WebClient wc = new System.Net.WebClient()) { string fnp = System.IO.Path.Combine(PluginSettings.Instance.ActiveDataPath, IMG_SUBFOLDER); bool grabOnlyNew = _grabOnlyNew; while (gc != null) { //todo: get images try { StringBuilder sb = new StringBuilder(); lock (_lockDBObject) { if (gc.ShortDescriptionInHtml && gc.ShortDescription != null) { sb.Append(gc.ShortDescription); } if (gc.LongDescriptionInHtml && gc.LongDescription != null) { sb.Append(gc.LongDescription); } } if (sb.Length > 0) { List<string> linkList = new List<string>(); Regex r = new Regex(@"</?\w+\s+[^>]*>", RegexOptions.Multiline); MatchCollection mc = r.Matches(sb.ToString()); foreach (Match m in mc) { string s = m.Value.Substring(1).Replace('\r', ' ').Replace('\n', ' ').Trim(); if (s.StartsWith("img ", StringComparison.OrdinalIgnoreCase)) { int pos = s.IndexOf(" src", StringComparison.OrdinalIgnoreCase); pos = s.IndexOfAny(new char[] { '\'', '"' }, pos); int pos2 = s.IndexOfAny(new char[] { '\'', '"' }, pos + 1); linkList.Add(s.Substring(pos + 1, pos2 - pos - 1)); } } List<Framework.Data.GeocacheImage> imgList = DataAccess.GetGeocacheImages(Core.GeocacheImages, gc.Code); if (imgList != null) { foreach (Framework.Data.GeocacheImage img in imgList) { if (!linkList.Contains(img.Url)) { linkList.Add(img.Url); } } } foreach (string link in linkList) { string fn = string.Format("{0}.jpg", Guid.NewGuid().ToString("N")); bool skipInsert = false; //if it fails, just ignore this image try { //check if link already is in database //if so, use this filename lock (_lockDBObject) { object o = _dbcon.ExecuteScalar(string.Format("select local_file from images where gccode='{0}' and org_url='{1}'", gc.Code.Replace("'", "''"), link.Replace("'", "''"))); if (o != null && o.GetType() != typeof(DBNull)) { fn = (string)o; skipInsert = true; } } if (grabOnlyNew && skipInsert) { if (System.IO.File.Exists(System.IO.Path.Combine(fnp, fn))) { continue; } } using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true)) { wc.DownloadFile(link, tmp.Path); using (System.Drawing.Image img = System.Drawing.Image.FromFile(tmp.Path)) { img.Save(System.IO.Path.Combine(fnp, fn), System.Drawing.Imaging.ImageFormat.Jpeg); if (!skipInsert) { lock (_lockDBObject) { _dbcon.ExecuteNonQuery(string.Format("insert into images (gccode, org_url, local_file) values ('{0}', '{1}', '{2}')", gc.Code.Replace("'", "''"), link.Replace("'", "''"), fn)); } } } } } catch { } } } } catch { } gc = null; lock (_gcList) { if (_gcList.Count > 0) { gc = _gcList[0]; _gcList.RemoveAt(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 { } } }
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; } }
public void Constructor1_NonAssemblyFileNameAsCodeBaseArgument_ShouldThrowBadImageFormat() { using (TemporaryFile temporaryFile = new TemporaryFile()) { ExceptionAssert.Throws<BadImageFormatException>(() => { new AssemblyCatalog(temporaryFile.FileName); }); } }
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(); } } }
/// <summary> /// Checks whether the <paramref name="formula" /> holds in all states of the <paramref name="model" />. /// </summary> /// <param name="model">The model that should be checked.</param> /// <param name="formula">The formula that should be checked.</param> /// <param name="checkArgument">The argument passed to LtsMin that indicates which kind of check to perform.</param> private AnalysisResult Check(ModelBase model, Formula formula, string checkArgument) { try { using (var modelFile = new TemporaryFile("ssharp")) { File.WriteAllBytes(modelFile.FilePath, RuntimeModelSerializer.Save(model, formula)); try { CreateProcess(modelFile.FilePath, checkArgument); Run(); } catch (Win32Exception e) { throw new InvalidOperationException( "Failed to start LTSMin. Ensure that pins2lts-seq.exe can be found by either copying it next " + "to the executing assembly or by adding it to the system path. The required cygwin dependencies " + $"must also be available. The original error message was: {e.Message}", e); } var success = InterpretExitCode(_ltsMin.ExitCode); return new AnalysisResult { FormulaHolds = success }; } } finally { _ltsMin = null; } }
public ActionScriptAction(Framework.Interfaces.ICore core) : base(STR_NAME, core) { _scriptFile = new System.IO.TemporaryFile(); }
public async Task DownloadImagesAsync(List <Core.Data.Geocache> gcList, bool updateExisting) { await Task.Run(async() => { bool cancel = false; ConcurrentQueue <Core.Data.Geocache> cq = new ConcurrentQueue <Core.Data.Geocache>(); foreach (var gc in gcList) { cq.Enqueue(gc); } using (Utils.ProgressBlock prog = new ProgressBlock("DownloadingImages", "DownloadingImages", gcList.Count, 0, true)) { Action actionUpdateProgress = () => { DateTime updateAt = DateTime.MinValue; int cnt = cq.Count; while (cnt > 0) { if (DateTime.Now >= updateAt) { if (!prog.Update("DownloadingImages", gcList.Count, gcList.Count - cnt)) { cancel = true; break; } updateAt = DateTime.Now.AddSeconds(1); } System.Threading.Thread.Sleep(200); cnt = cq.Count; } ; }; Action actionDownload = () => { Core.Data.Geocache gc; using (System.Net.WebClient wc = new System.Net.WebClient()) { while (!cancel && cq.TryDequeue(out gc)) { string fnp = System.IO.Path.Combine(_imageFolder, IMG_SUBFOLDER); bool grabOnlyNew = !updateExisting; try { List <string> linkList; lock (_lockObject) { linkList = DataAccess.GetImagesOfGeocache(gc.Database, gc.Code); } foreach (string link in linkList) { string fn = string.Format("{0}.jpg", Guid.NewGuid().ToString("N")); bool skipInsert = false; //if it fails, just ignore this image try { //check if link already is in database //if so, use this filename lock (_lockObject) { object o = _dbcon.ExecuteScalar(string.Format("select local_file from images where gccode='{0}' and org_url='{1}'", gc.Code.Replace("'", "''"), link.Replace("'", "''"))); if (o != null && o.GetType() != typeof(DBNull)) { fn = (string)o; skipInsert = true; } } if (grabOnlyNew && skipInsert) { if (System.IO.File.Exists(System.IO.Path.Combine(fnp, fn))) { continue; } } using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true)) { wc.DownloadFile(link, tmp.Path); if (new FileInfo(tmp.Path).Length < 10 * 1024 * 1024) { using (System.Drawing.Image img = System.Drawing.Image.FromFile(tmp.Path)) { img.Save(System.IO.Path.Combine(fnp, fn), System.Drawing.Imaging.ImageFormat.Jpeg); if (!skipInsert) { lock (_lockObject) { _dbcon.ExecuteNonQuery(string.Format("insert into images (gccode, org_url, local_file) values ('{0}', '{1}', '{2}')", gc.Code.Replace("'", "''"), link.Replace("'", "''"), fn)); } } } } } } catch //(Exception e) { //Core.ApplicationData.Instance.Logger.AddLog(this, e); } } } catch (Exception e) { Core.ApplicationData.Instance.Logger.AddLog(this, e); //skip and go to next one } } }; }; List <Task> tasks = new List <Task>(); tasks.Add(Task.Factory.StartNew(actionUpdateProgress)); for (int i = 0; i < 4 && i < gcList.Count; i++) { tasks.Add(Task.Factory.StartNew(actionDownload)); } await Task.WhenAll(tasks.ToArray()); } }); }
private bool LoadDatabaseFile() { //index file not available //create one //this is an exception. (should be anyway) //first create it in a temporary file and copy to target if finished bool result = false; bool cancelled = false; try { string fn = string.Concat(FileName, ".gsx"); if (File.Exists(fn)) { File.Delete(fn); } byte[] buffer = new byte[117]; using (TemporaryFile tf = new TemporaryFile()) using (FileStream fsIdx = File.Open(tf.Path, FileMode.OpenOrCreate, FileAccess.Write)) using (MemoryStream ms = new MemoryStream(buffer)) using (BinaryWriter bw = new BinaryWriter(ms)) { long max = this.FileStream.Length; DateTime nextUpdate = DateTime.Now.AddSeconds(1); using (Utils.ProgressBlock prog = new ProgressBlock("LoadingDatabase", "Loading", 100, 0, true)) { this.FileStream.Position = DATABASE_CONTENT_OFFSET; long eof = this.FileStream.Length; while (this.FileStream.Position < eof) { RecordInfo ri = new RecordInfo(); ri.Database = this; ri.Offset = this.FileStream.Position; this.FileStream.Position = ri.Offset + RECORD_POS_LENGTH; ri.Length = BinaryReader.ReadInt64(); this.FileStream.Position = ri.Offset + RECORD_POS_FIELDTYPE; ri.FieldType = BinaryReader.ReadByte(); if (ri.FieldType == RECORD_EMPTY) { _emptyRecords.Add(ri); _emptyRecordListSorted = false; } else { this.FileStream.Position = ri.Offset + RECORD_POS_ID; ri.ID = BinaryReader.ReadString(); ri.SubID = BinaryReader.ReadString(); switch (ri.FieldType) { case RECORD_GEOCACHE: this.GeocacheCollection.Add(new Data.Geocache(ri)); break; case RECORD_LOG: this.LogCollection.Add(new Data.Log(ri)); break; case RECORD_WAYPOINT: this.WaypointCollection.Add(new Data.Waypoint(ri)); break; case RECORD_USERWAYPOINT: this.UserWaypointCollection.Add(new Data.UserWaypoint(ri)); break; case RECORD_LOGIMAGE: this.LogImageCollection.Add(new Data.LogImage(ri)); break; case RECORD_GEOCACHEIMAGE: this.GeocacheImageCollection.Add(new Data.GeocacheImage(ri)); break; } } this.FileStream.Position = ri.Offset + ri.Length; ri.OffsetIdx = fsIdx.Position; ms.Position = 0; bw.Write(ri.Offset); bw.Write(ri.Length); bw.Write(ri.FieldType); if (ri.FieldType != RECORD_EMPTY) { bw.Write(ri.ID); bw.Write(ri.SubID); } else { bw.Write(""); bw.Write(""); } fsIdx.Write(buffer, 0, 117); if (DateTime.Now >= nextUpdate) { if (!prog.Update("Loading", 100, (int)(100.0 * (double)this.FileStream.Position / (double)max))) { cancelled = true; break; } nextUpdate = DateTime.Now.AddSeconds(1); } } //if all OK and not canceled fsIdx.Close(); if (!cancelled) { File.Copy(tf.Path, fn); _fileStreamIdx = File.Open(fn, FileMode.OpenOrCreate, FileAccess.ReadWrite); Utils.Calculus.SetDistanceAndAngleGeocacheFromLocation(this.GeocacheCollection, ApplicationData.Instance.CenterLocation); result = true; } } } } catch(Exception e) { Core.ApplicationData.Instance.Logger.AddLog(this, e); } return result; }
private void getImagesThreadMethod() { Framework.Data.Geocache gc = null; lock (_gcList) { if (_gcList.Count > 0) { gc = _gcList[0]; _gcList.RemoveAt(0); } } using (System.Net.WebClient wc = new System.Net.WebClient()) { string fnp = System.IO.Path.Combine(PluginSettings.Instance.ActiveDataPath, IMG_SUBFOLDER); bool grabOnlyNew = _grabOnlyNew; while (gc != null) { //todo: get images try { StringBuilder sb = new StringBuilder(); lock (_lockDBObject) { if (gc.ShortDescriptionInHtml && gc.ShortDescription != null) { sb.Append(gc.ShortDescription); } if (gc.LongDescriptionInHtml && gc.LongDescription != null) { sb.Append(gc.LongDescription); } } if (sb.Length > 0) { List <string> linkList = new List <string>(); Regex r = new Regex(@"</?\w+\s+[^>]*>", RegexOptions.Multiline); MatchCollection mc = r.Matches(sb.ToString()); foreach (Match m in mc) { string s = m.Value.Substring(1).Replace('\r', ' ').Replace('\n', ' ').Trim(); if (s.StartsWith("img ", StringComparison.OrdinalIgnoreCase)) { int pos = s.IndexOf(" src", StringComparison.OrdinalIgnoreCase); pos = s.IndexOfAny(new char[] { '\'', '"' }, pos); int pos2 = s.IndexOfAny(new char[] { '\'', '"' }, pos + 1); linkList.Add(s.Substring(pos + 1, pos2 - pos - 1)); } } List <Framework.Data.GeocacheImage> imgList = DataAccess.GetGeocacheImages(Core.GeocacheImages, gc.Code); if (imgList != null) { foreach (Framework.Data.GeocacheImage img in imgList) { if (!linkList.Contains(img.Url)) { linkList.Add(img.Url); } } } foreach (string link in linkList) { string fn = string.Format("{0}.jpg", Guid.NewGuid().ToString("N")); bool skipInsert = false; //if it fails, just ignore this image try { //check if link already is in database //if so, use this filename lock (_lockDBObject) { object o = _dbcon.ExecuteScalar(string.Format("select local_file from images where gccode='{0}' and org_url='{1}'", gc.Code.Replace("'", "''"), link.Replace("'", "''"))); if (o != null && o.GetType() != typeof(DBNull)) { fn = (string)o; skipInsert = true; } } if (grabOnlyNew && skipInsert) { if (System.IO.File.Exists(System.IO.Path.Combine(fnp, fn))) { continue; } } using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true)) { wc.DownloadFile(link, tmp.Path); using (System.Drawing.Image img = System.Drawing.Image.FromFile(tmp.Path)) { img.Save(System.IO.Path.Combine(fnp, fn), System.Drawing.Imaging.ImageFormat.Jpeg); if (!skipInsert) { lock (_lockDBObject) { _dbcon.ExecuteNonQuery(string.Format("insert into images (gccode, org_url, local_file) values ('{0}', '{1}', '{2}')", gc.Code.Replace("'", "''"), link.Replace("'", "''"), fn)); } } } } } catch { } } } } catch { } gc = null; lock (_gcList) { if (_gcList.Count > 0) { gc = _gcList[0]; _gcList.RemoveAt(0); } } } } }
private void buttonInstall_Click(object sender, EventArgs e) { //download package PackageItem pkg = null; if (listView1.SelectedItems != null && listView1.SelectedItems.Count > 0) { pkg = listView1.SelectedItems[0].Tag as PackageItem; if (pkg != null) { toolStripStatusLabelAction.Text = Utils.LanguageSupport.Instance.GetTranslation("Downloading package..."); statusStrip1.Refresh(); using (System.Net.WebClient wc = new System.Net.WebClient()) { if (pkg.packagetype == "script") { //download to a temp file using (TemporaryFile tmp = new TemporaryFile(false)) { //unzip to appdata scripts folder string fn = Path.GetFileName(pkg.link); try { wc.DownloadFile(pkg.link, tmp.Path); string scriptsPath = Core.CSScriptsPath; UnZipFiles(tmp.Path, scriptsPath, false); MessageBox.Show(Utils.LanguageSupport.Instance.GetTranslation(STR_SCRIPTINSTALLED)); } catch { MessageBox.Show(Utils.LanguageSupport.Instance.GetTranslation(STR_ERRORDOWNLOADFILE), Utils.LanguageSupport.Instance.GetTranslation(STR_ERROR), MessageBoxButtons.OK, MessageBoxIcon.Error); } //done } } else { string updatePath = System.IO.Path.Combine(new string[] { System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "GAPP" }); try { if (!Directory.Exists(updatePath)) { Directory.CreateDirectory(updatePath); } } catch { } updatePath = System.IO.Path.Combine(new string[] { updatePath, "Update" }); try { if (!Directory.Exists(updatePath)) { Directory.CreateDirectory(updatePath); } } catch { } string[] files = Directory.GetFiles(updatePath); if (files != null) { foreach (string s in files) { File.Delete(s); } } string fn = Path.GetFileName(pkg.link); try { wc.DownloadFile(pkg.link, Path.Combine(updatePath, fn)); Core.InitiateUpdaterAndExit(); } catch { MessageBox.Show(Utils.LanguageSupport.Instance.GetTranslation(STR_ERRORDOWNLOADFILE), Utils.LanguageSupport.Instance.GetTranslation(STR_ERROR), MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } } toolStripStatusLabelAction.Text = ""; }
public TempFileBuffer(byte[] data) { _file = new TemporaryFile(); File.WriteAllBytes(_file.Name, data); _size = (uint)data.Length; }
private void compileScripts() { if (Scripts.Count > 0) { StringBuilder sb = new StringBuilder(); sb.AppendLine(UsingNamespaces ?? ""); sb.AppendLine(); sb.AppendLine("namespace GlobalcachingApplication.Plugins.Browser"); sb.AppendLine("{"); foreach (Script script in Scripts) { if (script.Enabled) { sb.AppendLine(script.ClassCode); } } sb.AppendLine("}"); try { using (TemporaryFile tmpFile = new TemporaryFile(true)) { File.WriteAllText(tmpFile.Path, sb.ToString()); _compiledAssembly = CSScript.Load(tmpFile.Path); } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message, "Error"); } } _isCompiled = true; }
//Form Load Event private void Display_Load(object sender, EventArgs e) { string[] args = Environment.GetCommandLineArgs(); //If command line arguments exist, they are stored here if (args.Length <= 1) //If there are no command line arguments, open a file dialog for the user { if (openFileDialog1.ShowDialog() == DialogResult.OK) { if ([email protected](".NC") && [email protected](".nc")) { MessageBox.Show("NOT A .NC FILE" + args); Application.Exit(); return; } try { FileStream NcReader = new FileStream(openFileDialog1.FileName, FileMode.Open); NCFIN = new StreamReader(NcReader); } catch (Exception ex) { this.SendToBack(); MessageBox.Show(ex.ToString() + " occured."); Application.Exit(); } } else { Application.Exit(); return; } } else if (args.Length > 1) //If command line arguments are found { if (args[1] == "/h" || args[1] == "/H") { MessageBox.Show("Help:\n\nPossible Arguments:\n Argument 1: Thisfile.exe\n Argument 2: NCFILE\n Argument 3: /G0|/X\n" + " Argument 4: /PointCheck|/X\n Argument 5: /RadiusCheck|/X\n Argument 6: /OriginCheck|/X\n Argument 7: /NoFBB\n " + "Example: >Display.exe Test /G0 /X /RadiusCheck /OriginCheck /NoFBB"); Application.Exit(); } if (File.Exists(args[1] + ".NC")) //If an NC file exists { args[1] += ".NC"; } // The following is not right but I'm not fixing it now. else if (!args[1].Contains(".NC") && !args[1].Contains(".nc")) //If an NC file does not exist { MessageBox.Show("NOT A .NC FILE or file not found. " + String.Join(", ", args)); Application.Exit(); return; } else { MessageBox.Show("FILE DOES NOT EXIST. " + String.Join(", ", args)); Application.Exit(); return; } try { FileStream NcReader = new FileStream(args[1], FileMode.Open); NCFIN = new StreamReader(NcReader); } catch (Exception ex) { this.SendToBack(); MessageBox.Show(ex.ToString() + " occured."); Application.Exit(); } } //If the user enters /NoFBB as the 7th argument, fast burn bridges are not shown if (args.Length > 6) { if (args[6] == "/NoFBB") ShowFBB = false; } try { Read_And_Parse(); } catch (Exception ex) { this.SendToBack(); MessageBox.Show("Exception " + ex.ToString() + " occurred. \n\nThis error is generally caused by a bad NC command and sometimes a blank line in the NC Code. Please take a look at the NC Code."); Application.Exit(); } //Title the Display window as (Display - [NCFile]) if (args.Length > 1) this.Text = "File: " + args[1].Substring(0, args[1].Length - 3); else this.Text = "File: " + Path.GetFileNameWithoutExtension(@openFileDialog1.FileName); FILENAME = this.Text; try { Scale_Window(); } catch (Exception ex) { this.SendToBack(); MessageBox.Show("Exception " + ex.ToString() + " occurred. \n\nThis error is generally caused by a bad NC command and sometimes a blank line in the NC Code. Please take a look at the NC Code."); Application.Exit(); } Graphics g = Graphics.FromImage(mainCanvas); g.Clear(Color.Black); //Sets the position of the last BURN and the position of the second to last BURN (Used for coloring the last and second to last line) try { for (int i = NCList.Count - 1; i >= 0; i--) { if ((NCList[i].ContainsX || NCList[i].ContainsY) && (NCList[i].G != "0" && NCList[i].G != "00")) { Last = NCList[i].LineNumber; for (int j = i - 1; j > 0; j--) { if (NCList[j].ContainsX || NCList[j].ContainsY && (NCList[j].G != "0" && NCList[j].G != "00")) { SecondToLast = NCList[j].LineNumber; break; } } break; } } } catch (Exception ex) { this.SendToBack(); MessageBox.Show("Exception " + ex.ToString() + " occurred. \n\nThis error is generally caused by a bad NC command and sometimes a blank line in the NC Code. Please take a look at the NC Code."); Application.Exit(); } //Sets the X and Y back to the origin and draws the design X = Math.Abs(XMIN); Y = Math.Abs(YMAX); G0Show = false; // MessageBox.Show("Count of NCList = " + NCList.Count); try { for (int j = 0; j < NCList.Count; j++) draw_design(j); } catch (Exception ex) { this.SendToBack(); MessageBox.Show("Exception " + ex.ToString() + " occurred. \n\nThis error is generally caused by a bad NC command and sometimes a blank line in the NC Code. Please take a look at the NC Code."); Application.Exit(); } // Draw_Meta(); G0CanvasCopy = new TemporaryFile(); //Saves the NO G0 canvas to a temporary file mainCanvas.Save(@G0CanvasCopy.FilePath); G0Show = true; ArcDirection = true; for (int j = 0; j < NCList.Count; j++) draw_design(j); //Saves the Arc Direction canvas to a temorary file ArcDirectionCanvasCopy = new TemporaryFile(); mainCanvas.Save(@ArcDirectionCanvasCopy.FilePath); ArcDirection = false; for (int j = 0; j < NCList.Count; j++) draw_design(j); #region Dynamic Labels /******************************************* * CREATE DYNAMIC LABELS */ ProgramDetails = new Label(); ProgramDetails.Text = "CNC (.NC) DISPLAY BY ZACH SAMUELS\n" + String.Format("{0, 30}", "VERSION ") + Constants.Version; ProgramDetails.Location = new Point((int)(SCREENWIDTH * .75), 10); ProgramDetails.AutoSize = true; ProgramDetails.Font = new Font("Times New Roman", 9.0F); this.Controls.Add(ProgramDetails); RainbowTimer.Start(); Label Controls = new Label(); Controls.Text = "Controls:\nD - Redraw the object\nT - Trace the design\nG - Make G0 Moves Transparent\nA - Show Arc Directions\n" + "Z - Open zoom window\nL - Select a line from line number\nN - Add Notes\nP - Print\nV - Print Preview\nO - Open new file (If not opened from command)\nX - Stop all commands\nESC - Quit"; Controls.Location = new Point((int)(SCREENWIDTH * .75), 60); Controls.AutoSize = true; Controls.Font = new Font("Times New Roman", 9.0F); Controls.ForeColor = Color.White; this.Controls.Add(Controls); GCODE = new Label(); GCODE.Text = "GCODE:\nSpeed:\nPoint:\nLine Number:"; GCODE.Location = new Point((int)(SCREENWIDTH * .75), 270); GCODE.AutoSize = true; GCODE.ForeColor = Color.OrangeRed; GCODE.Font = new Font("Times New Roman", 9.0F); this.Controls.Add(GCODE); /// NOTE: DUE TO THE DESIGN BEING DRAW TO 3 FILES, POINTINCHES MUST BE DIVIDED BY 3 /// Inch_Calculator = new Label(); Inch_Calculator.Font = new Font("Times New Roman", 9.0F); Inch_Calculator.Location = new Point((int)(SCREENWIDTH * .75), 440); Inch_Calculator.Text = "Inch Calculator\n\nG0 Inches: " + (PointInches["G0"]/3).ToString("0.0"); double TotalInches = 0; foreach (string Key in PointInches.Keys) { if (Key != "G0" && PointInches[Key] != 0) { Burn_Inches += Key + " inches: " + (PointInches[Key]/3).ToString("0.0") + "\n"; Inch_Calculator.Text += "\n" + Key + ": " + (PointInches[Key]/3).ToString("0.0"); TotalInches += PointInches[Key]/3; } } TotalInches += PointInches["G0"]/3; Inch_Calculator.Text += "\nTotal Inches Moved: " + TotalInches.ToString("0.0") + "\nEfficiency Ratio Burn/Travel: " + (((TotalInches - PointInches["G0"]/3) / TotalInches) * 100).ToString("0.0") + "%\n\nSize of Design: " + (XMAX - XMIN).ToString("0.0") + " X " + (YMAX - YMIN).ToString("0.0"); SizeDesign = (XMAX - XMIN).ToString("0.0") + " x " + (YMAX - YMIN).ToString("0.0"); Inch_Calculator.AutoSize = true; Inch_Calculator.ForeColor = Color.White; Inch_Calculator.Font = new Font("Times New Roman", 9.0F); this.Controls.Add(Inch_Calculator); int InchColorY = 620; InchColor = new Label[11]; for (int i = 0; i < 11; i++) InchColor[i] = new Label(); InchColor[0].Text = "G0 Move"; InchColor[0].ForeColor = Color.BlueViolet; InchColor[0].Location = new Point((int)(SCREENWIDTH * .75), InchColorY); InchColor[1].Text = "Etching"; InchColor[1].ForeColor = Color.Blue; InchColor[1].Location = new Point((InchColor[0].Location.X + 60), InchColorY); InchColor[2].Text = "2 Point"; InchColor[2].ForeColor = Color.Green; InchColor[2].Location = new Point((InchColor[1].Location.X + 50), InchColorY); InchColor[3].Text = "3 Point"; InchColor[3].ForeColor = Color.Cyan; InchColor[3].Location = new Point((InchColor[0].Location.X), InchColorY + 20); InchColor[4].Text = "1 Pass"; InchColor[4].ForeColor = Color.WhiteSmoke; InchColor[4].Location = new Point((InchColor[3].Location.X + 50), InchColorY + 20); InchColor[5].Text = "1.5 Point"; InchColor[5].ForeColor = Color.LightCyan; InchColor[5].Location = new Point((InchColor[4].Location.X + 50), InchColorY + 20); InchColor[6].Text = "Buffer"; InchColor[6].ForeColor = Color.LightBlue; InchColor[6].Location = new Point((InchColor[0].Location.X), InchColorY + 40); InchColor[7].Text = "Snug"; InchColor[7].ForeColor = Color.Gray; InchColor[7].Location = new Point((InchColor[6].Location.X + 50), InchColorY + 40); InchColor[8].Text = "Wide"; InchColor[8].ForeColor = Color.LightGreen; InchColor[8].Location = new Point((InchColor[7].Location.X + 50), InchColorY + 40); InchColor[9].Text = "Pulsing"; InchColor[9].ForeColor = Color.Salmon; InchColor[9].Location = new Point((InchColor[0].Location.X), InchColorY + 60); if (ShowFBB == true) { InchColor[10].Text = "FBB"; InchColor[10].ForeColor = Color.Red; InchColor[10].Location = new Point((InchColor[9].Location.X + 50), InchColorY + 60); } foreach (Label l in InchColor) { l.AutoSize = true; l.Font = new Font("Times New Roman", 9.0F); this.Controls.Add(l); } drawingBarLabel = new Label(); drawingBarLabel.Text = "Slow Down/Speed Up Drawing"; drawingBarLabel.Location = new Point((int)(SCREENWIDTH * .75), 360); drawingBarLabel.AutoSize = true; drawingBarLabel.ForeColor = Color.White; drawingBarLabel.Font = new Font("Times New Roman", 9.0F); drawingBarLabel.Hide(); this.Controls.Add(drawingBarLabel); drawingBar.Location = new Point((int)(SCREENWIDTH * .75), 375); drawingBar.Width = 300; drawingBar.TickStyle = TickStyle.None; drawingBar.Hide(); /* * ******************************************/ #endregion this.BackColor = Color.Black; this.ForeColor = Color.Black; this.Location = new Point(0, 0); //Saves the canvas to a temporary file CanvasCopy = new TemporaryFile(); mainCanvas.Save(@CanvasCopy.FilePath); ArgsCommands(args); full_maximize(sender, e); this.Refresh(); //Refreshes the form g.Dispose(); //Releases the resources used by Graphics g this.TopMost = true; this.Activate(); }
private void downloadShapefileThreadMethod() { try { //download zip file using (TemporaryFile tmpFile = new TemporaryFile(false)) { using (Utils.ProgressBlock prog = new Utils.ProgressBlock(_plugin, STR_DOWNLOADINGSHAPEFILE, _downloadUrl, _zipFileSize, 0)) { byte[] buffer = new byte[20*1024]; int totalRead = 0; HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create(_downloadUrl); using (System.IO.BinaryReader sr = new System.IO.BinaryReader(wr.GetResponse().GetResponseStream())) using (FileStream fs = File.OpenWrite(tmpFile.Path)) { while (totalRead < _zipFileSize) { int bytesRead = sr.Read(buffer, 0, buffer.Length); if (bytesRead > 0) { fs.Write(buffer, 0, bytesRead); } totalRead += bytesRead; prog.UpdateProgress(STR_DOWNLOADINGSHAPEFILE, _downloadUrl, _zipFileSize, totalRead); } } } UnZipFiles(tmpFile.Path, Properties.Settings.Default.DefaultShapeFilesFolder, false); } } catch { _error = true; } _actionReady.Set(); }
public void TemporaryFileDetachTest() { string path = string.Empty; using( TemporaryFile temporaryFile = new TemporaryFile( true, null ) ) { path = temporaryFile.Path; Assert.That( File.Exists( temporaryFile.Path ), Is.True ); Assert.That( (File.GetAttributes( temporaryFile.Path ) & FileAttributes.Temporary) == FileAttributes.Temporary, Is.True ); temporaryFile.Detach(); } Assert.That( File.Exists( path ), Is.True ); File.Delete( path ); }
public async Task DownloadImagesAsync(List<Core.Data.Geocache> gcList, bool updateExisting) { await Task.Run(async () => { bool cancel = false; ConcurrentQueue<Core.Data.Geocache> cq = new ConcurrentQueue<Core.Data.Geocache>(); foreach (var gc in gcList) { cq.Enqueue(gc); } using (Utils.ProgressBlock prog = new ProgressBlock("DownloadingImages", "DownloadingImages", gcList.Count, 0, true)) { Action actionUpdateProgress = () => { DateTime updateAt = DateTime.MinValue; int cnt = cq.Count; while (cnt > 0) { if (DateTime.Now >= updateAt) { if (!prog.Update("DownloadingImages", gcList.Count, gcList.Count - cnt)) { cancel = true; break; } updateAt = DateTime.Now.AddSeconds(1); } System.Threading.Thread.Sleep(200); cnt = cq.Count; }; }; Action actionDownload = () => { Core.Data.Geocache gc; using (System.Net.WebClient wc = new System.Net.WebClient()) { while (!cancel && cq.TryDequeue(out gc)) { string fnp = System.IO.Path.Combine(_imageFolder, IMG_SUBFOLDER); bool grabOnlyNew = !updateExisting; try { List<string> linkList; lock (_lockObject) { linkList = DataAccess.GetImagesOfGeocache(gc.Database, gc.Code); } foreach (string link in linkList) { string fn = string.Format("{0}.jpg", Guid.NewGuid().ToString("N")); bool skipInsert = false; //if it fails, just ignore this image try { //check if link already is in database //if so, use this filename lock (_lockObject) { object o = _dbcon.ExecuteScalar(string.Format("select local_file from images where gccode='{0}' and org_url='{1}'", gc.Code.Replace("'", "''"), link.Replace("'", "''"))); if (o != null && o.GetType() != typeof(DBNull)) { fn = (string)o; skipInsert = true; } } if (grabOnlyNew && skipInsert) { if (System.IO.File.Exists(System.IO.Path.Combine(fnp, fn))) { continue; } } using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true)) { wc.DownloadFile(link, tmp.Path); if (new FileInfo(tmp.Path).Length < 10 * 1024 * 1024) { using (System.Drawing.Image img = System.Drawing.Image.FromFile(tmp.Path)) { img.Save(System.IO.Path.Combine(fnp, fn), System.Drawing.Imaging.ImageFormat.Jpeg); if (!skipInsert) { lock (_lockObject) { _dbcon.ExecuteNonQuery(string.Format("insert into images (gccode, org_url, local_file) values ('{0}', '{1}', '{2}')", gc.Code.Replace("'", "''"), link.Replace("'", "''"), fn)); } } } } } } catch //(Exception e) { //Core.ApplicationData.Instance.Logger.AddLog(this, e); } } } catch (Exception e) { Core.ApplicationData.Instance.Logger.AddLog(this, e); //skip and go to next one } } }; }; List<Task> tasks = new List<Task>(); tasks.Add(Task.Factory.StartNew(actionUpdateProgress)); for (int i = 0; i < 4 && i < gcList.Count; i++) { tasks.Add(Task.Factory.StartNew(actionDownload)); } await Task.WhenAll(tasks.ToArray()); } }); }
private void exportToGPX() { string filename; if (Core.Settings.Default.GPXFileName.ToLower().EndsWith(".gpx")) { filename = Core.Settings.Default.GPXFileName; } else if (Core.Settings.Default.GPXFileName.ToLower().EndsWith(".")) { filename = string.Concat(Core.Settings.Default.GPXFileName, "gpx"); } else { filename = string.Concat(Core.Settings.Default.GPXFileName, ".gpx"); } using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ExportingGPX", "CreatingFile", _gcList.Count, 0)) { using (System.IO.TemporaryFile gpxFile = new System.IO.TemporaryFile(false)) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(gpxFile.Path, false, Encoding.UTF8)) { GPX.Export gpxGenerator = new Export(_gcList, Version.Parse(Core.Settings.Default.GPXVersion)); 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++) { sw.WriteLine(gpxGenerator.Next()); if (Core.Settings.Default.GPXAddChildWaypoints) { string s = gpxGenerator.WaypointData(); if (!string.IsNullOrEmpty(s)) { sw.WriteLine(s); } } if (DateTime.Now >= nextUpdate) { progress.Update("CreatingFile", gpxGenerator.Count, i + 1); nextUpdate = DateTime.Now.AddSeconds(1); } } //finalize sw.Write(gpxGenerator.Finish()); } if (Core.Settings.Default.GPXTargetDevice == TargetDevice.Garmin) { progress.Update("CopyingFileToDevice", 1, 0); System.IO.File.Copy(gpxFile.Path, System.IO.Path.Combine(new string[] { SelectedGarminDevice.DriveName, "garmin", "gpx", filename }), true); } else { System.IO.File.Copy(gpxFile.Path, System.IO.Path.Combine(Core.Settings.Default.GPXTargetFolder, filename), true); } } } }
private void exportToGGZ() { string filename; if (Core.Settings.Default.GPXFileName.ToLower().EndsWith(".ggz")) { filename = Core.Settings.Default.GPXFileName; } else if (Core.Settings.Default.GPXFileName.ToLower().EndsWith(".")) { filename = string.Concat(Core.Settings.Default.GPXFileName, "ggz"); } else { filename = string.Concat(Core.Settings.Default.GPXFileName, ".ggz"); } DateTime dt = DateTime.Now.AddSeconds(2); using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ExportingGPX", "CreatingFile", _gcList.Count, 0)) { 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.Crc16 crc16 = new Utils.Crc16(); GPX.Export gpxGenerator = new Export(_gcList, Version.Parse(Core.Settings.Default.GPXVersion)); 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 <Core.Data.Geocache> gpxBatchList = new List <Core.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.Update("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(); } if (Core.Settings.Default.GPXTargetDevice == TargetDevice.Garmin) { progress.Update("CopyingFileToDevice", 1, 0); string p = System.IO.Path.Combine(new string[] { SelectedGarminDevice.DriveName, "garmin", "ggz" }); if (!System.IO.Directory.Exists(p)) { System.IO.Directory.CreateDirectory(p); } System.IO.File.Copy(gpxFile.Path, System.IO.Path.Combine(p, filename), true); } else { System.IO.File.Copy(gpxFile.Path, System.IO.Path.Combine(Core.Settings.Default.GPXTargetFolder, filename), true); } } } }
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; } }
static TemporaryFile[] CompileFiles(string[] sourceFiles, string extension) { // Each subsequent file may refer to the previous one var compiledPathNames = sourceFiles.Select((sourceFile, i) => { if (i == sourceFiles.Length - 1) { // The main (final entry) source is compiled according to the passed in extension return Path.ChangeExtension(sourceFile, extension); } else { // All dependencies are compiled as dlls return Path.ChangeExtension(sourceFile, ".dll"); } }).ToArray(); TemporaryFile[] compiledFiles = sourceFiles.Select((sourceFile, i) => { string[] alreadyCompiledDependencies = compiledPathNames.Take(i).ToArray(); // get the sequence [0, i - 1] inclusive var assemblyPath = CompileFileWithDependencies(sourceFile, compiledPathNames[i], alreadyCompiledDependencies); var temp = new TemporaryFile(); temp.Path = assemblyPath; return temp; }).ToArray(); return compiledFiles; }
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 { } } }