private void viewOnEDSMToolStripMenuItem1_Click(object sender, EventArgs e) { IEnumerable <DataGridViewRow> selectedRows = dataGridViewClosestSystems.SelectedCells.Cast <DataGridViewCell>() .Select(cell => cell.OwningRow) .Distinct() .OrderBy(cell => cell.Index); this.Cursor = Cursors.WaitCursor; string sysName = selectedRows.First <DataGridViewRow>().Cells[1].Value.ToString(); EDSMClass edsm = new EDSMClass(); if (!edsm.ShowSystemInEDSM(sysName)) { LogTextHighlight("System could not be found - has not been synched or EDSM is unavailable" + Environment.NewLine); } this.Cursor = Cursors.Default; }
private void buttonToEDSM_Click(object sender, EventArgs e) { ISystem ds1 = discoveryform.history.FindSystem(SystemNameOnly(textBox_To.Text), discoveryform.galacticMapping); string sysname = ds1?.Name ?? SystemNameOnly(textBox_To.Text); long? edsmid = ds1?.EDSMID; EDSMClass edsm = new EDSMClass(); string url = edsm.GetUrlToEDSMSystem(sysname, edsmid); if (url.Length > 0) // may pass back empty string if not known, this solves another exception { Process.Start(url); } else { ExtendedControls.MessageBoxTheme.Show(FindForm(), "System unknown to EDSM"); } }
public void NotedSystem(string name, string note, bool istarget) // from target, a system with notes { this.Text = "System Information".Tx(this, "SI"); ISystem s = SystemCache.FindSystem(name); textBoxName.Text = name; textBoxName.ReturnPressed += (ctrl) => { return(true); }; textBoxTravelNote.Text = (note != null) ? note : ""; checkBoxTarget.Checked = istarget; HideTime(); HideBookmarkNotes(); HideSurfaceBookmarks(); var edsm = new EDSMClass(); edsmurl = edsm.GetUrlToEDSMSystem(s?.Name ?? name, s?.EDSMID); }
/* Tries to load the system data for the given name. If no system data is available, but the system is known, * it creates a new System entity, otherwise logs it and returns null. */ private ISystem getSystemForTrilateration(string systemName, bool fromEDSM) { var system = SystemClassDB.GetSystem(systemName); if (system == null) { EDSMClass edsm = new EDSMClass(); if (fromEDSM || edsm.IsKnownSystem(systemName)) { system = new SystemClass(systemName); } else { LogTextHighlight("Only systems with coordinates or already known to EDSM can be added".Tx(this, "Co") + Environment.NewLine); } } return(system); }
private void viewOnEDSMToolStripMenuItem_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; EliteDangerousCore.EDSM.EDSMClass edsm = new EDSMClass(); long?id_edsm = rightclicksystem.System?.EDSMID; if (id_edsm <= 0) { id_edsm = null; } if (!edsm.ShowSystemInEDSM(rightclicksystem.System.Name, id_edsm)) { ExtendedControls.MessageBoxTheme.Show(FindForm(), "System could not be found - has not been synched or EDSM is unavailable"); } this.Cursor = Cursors.Default; }
/* Tries to load the system data for the given name. If no system data is available, but the system is known, * it creates a new System entity, otherwise logs it and returns null. */ private ISystem getSystemForTrilateration(string systemName, bool fromEDSM) { var system = discoveryform.history.FindSystem(systemName, discoveryform.galacticMapping, false); if (system == null) { EDSMClass edsm = new EDSMClass(); if (fromEDSM || edsm.IsKnownSystem(systemName)) { system = new SystemClass(systemName); } else { LogTextHighlight("Only systems with coordinates or already known to EDSM can be added".T(EDTx.UserControlTrilateration_Co) + Environment.NewLine); } } return(system); }
private void viewOnEDSMToolStripMenuItem1_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; EDSMClass edsm = new EDSMClass(); long? id_edsm = rightclicksystem.EDSMID; if (id_edsm == 0) { id_edsm = null; } if (!edsm.ShowSystemInEDSM(rightclicksystem.Name, id_edsm)) { ExtendedControls.MessageBoxTheme.Show(FindForm(), "System could not be found - has not been synched or EDSM is unavailable".T(EDTx.UserControlStarDistance_NoEDSMSys)); } this.Cursor = Cursors.Default; }
public void buttonSync_Click(object sender, EventArgs e) { EDSMClass edsm = new EDSMClass(); if (!edsm.IsApiKeySet) { ExtendedControls.MessageBoxTheme.Show("Please ensure a commander is selected and it has a EDSM API key set"); return; } try { _discoveryForm.EdsmSync.StartSync(edsm, EDCommander.Current.SyncToEdsm, EDCommander.Current.SyncFromEdsm, EDDConfig.Instance.DefaultMapColour); } catch (Exception ex) { _discoveryForm.LogLine($"EDSM Sync failed: {ex.Message}"); } }
private void viewOnEDSMToolStripMenuItem1_Click(object sender, EventArgs e) { if (dataGridViewNearest.RightClickRowValid) { var rightclicksystem = (ISystem)dataGridViewNearest.Rows[dataGridViewNearest.RightClickRow].Tag; if (rightclicksystem != null) { this.Cursor = Cursors.WaitCursor; EDSMClass edsm = new EDSMClass(); if (!edsm.ShowSystemInEDSM(rightclicksystem.Name)) { ExtendedControls.MessageBoxTheme.Show(FindForm(), "System could not be found - has not been synched or EDSM is unavailable".T(EDTx.UserControlStarDistance_NoEDSMSys)); } this.Cursor = Cursors.Default; } } }
public void Execute(String systemName, double radius) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "SphereSystems export| *.txt"; dlg.Title = TITLE; dlg.FileName = "SphereSystems.txt"; if (dlg.ShowDialog() != DialogResult.OK) { return; } String fileName = dlg.FileName; EDSMClass edsm = new EDSMClass(); Task taskEDSM = Task <List <String> > .Factory.StartNew(() => { return(edsm.GetSphereSystems(systemName, radius)); }).ContinueWith(task => ExportFile(task, fileName)); }
public void InitControl(EDDiscoveryForm discoveryForm) { _discoveryForm = discoveryForm; _savedRoutes = SavedRouteClass.GetAllSavedRoutes(); foreach (var initroute in InitialRoutes) { if (!_savedRoutes.Any(r => r.Name == initroute.Name || r.Name == "\x7F" + initroute.Name)) { initroute.Add(); _savedRoutes.Add(initroute); } } _savedRoutes = _savedRoutes.Where(r => !r.Name.StartsWith("\x7F")).ToList(); UpdateComboBox(); _currentRoute = new SavedRouteClass(""); edsm = new EDSMClass(); }
private void showInEDSMToolStripMenuItem_Click(object sender, EventArgs e) { if (dataGridViewRoute.RightClickRowValid) { ISystem sys = dataGridViewRoute.Rows[dataGridViewRoute.RightClickRow].Tag as ISystem; if (sys != null) // paranoia because it should not be enabled otherwise { this.Cursor = Cursors.WaitCursor; EliteDangerousCore.EDSM.EDSMClass edsm = new EDSMClass(); if (!edsm.ShowSystemInEDSM(sys.Name)) { ExtendedControls.MessageBoxTheme.Show(FindForm(), "System could not be found - has not been synched or EDSM is unavailable"); } this.Cursor = Cursors.Default; } } }
private void buttonExtEDSMSphere_Click(object sender, EventArgs e) { double radius = textBoxRadius.Text.InvariantParseDouble(20); if (radius > 100) { if (ExtendedControls.MessageBoxTheme.Show(FindForm(), "This is a large radius, it make take a long time or not work, are you sure?", "Warning - Large radius", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.Cancel) { return; } } Cursor = Cursors.WaitCursor; Task taskEDSM = Task <List <Tuple <ISystem, double> > > .Factory.StartNew(() => { EDSMClass edsm = new EDSMClass(); return(edsm.GetSphereSystems(textBoxSystemName.Text, radius)); }).ContinueWith(task => this.Invoke(new Action(() => { SphereGrid(task); }))); }
private void viewOnEDSMToolStripMenuItem_Click(object sender, EventArgs e) { IEnumerable <DataGridViewRow> selectedRows = dataGridViewDistances.SelectedCells.Cast <DataGridViewCell>() .Select(cell => cell.OwningRow) .Distinct() .OrderBy(cell => cell.Index); this.Cursor = Cursors.WaitCursor; var cellVal = selectedRows.First <DataGridViewRow>().Cells[0].Value; if (cellVal != null) { string sysName = cellVal.ToString(); EDSMClass edsm = new EDSMClass(); if (!edsm.ShowSystemInEDSM(sysName)) { LogTextHighlight("System could not be found - has not been synched or EDSM is unavailable".T(EDTx.UserControlTrilateration_NoEDSM) + Environment.NewLine); } } this.Cursor = Cursors.Default; }
void PresentSystem(ISystem sys) { SetControlText("No Entry"); if (sys != null) { EDSMClass edsm = new EDSMClass(); string url = edsm.GetUrlToEDSMSystem(sys.Name, sys.EDSMID); if (url.HasChars()) { SetControlText("Data on " + sys.Name); webBrowser.Navigate(url); } else { SetControlText("No Data on " + sys.Name); webBrowser.Navigate(EDSMClass.ServerAddress); } } }
private void Controller_RefreshComplete() { Trace.WriteLine(BaseUtils.AppTicks.TickCountLap() + " Refresh complete"); RefreshButton(true); actioncontroller.ActionRunOnRefresh(); if (EDCommander.Current.SyncToInara && history.GetLast != null) { EliteDangerousCore.Inara.InaraSync.Refresh(LogLine, history.GetLast, EDCommander.Current); } if (DLLManager.Count > 0) { HistoryEntry lastfileh = history.GetLastHistoryEntry(x => x.EntryType == JournalTypeEnum.Fileheader); if (lastfileh != null) { for (int i = lastfileh.EntryNumber - 1; i < history.Count; i++) // play thru last history entries up to last file position for the DLLs, indicating stored { //System.Diagnostics.Debug.WriteLine("{0} : {1} {2}", i, history.EntryOrder[i].EventTimeUTC, history.EntryOrder[i].EventSummary); DLLManager.NewJournalEntry(EliteDangerousCore.DLL.EDDDLLCallerHE.CreateFromHistoryEntry(history, history[i]), true); } } DLLManager.Refresh(EDCommander.Current.Name, EliteDangerousCore.DLL.EDDDLLCallerHE.CreateFromHistoryEntry(history, history.GetLast)); } Trace.WriteLine(BaseUtils.AppTicks.TickCountLap() + " Refresh complete finished"); if (EDCommander.Current.SyncToEdsm) // no sync, no credentials, no action { EDSMClass edsm = new EDSMClass(); if (edsm.ValidCredentials) { EDSMSend(); } } }
private void Autoupdateedsm_Tick(object sender, EventArgs e) // tick tock to get edsm data very slowly! { if (dataGridViewStarList.FirstDisplayedCell != null && checkBoxEDSM.Checked) { int top = dataGridViewStarList.FirstDisplayedCell.RowIndex; if (top != autoupdaterowstart) { autoupdaterowstart = top; autoupdaterowoffset = 0; } while (true) { int row = autoupdaterowstart + autoupdaterowoffset; DataGridViewRow rw = (row >= 0 && row < dataGridViewStarList.Rows.Count) ? dataGridViewStarList.Rows[row] : null; if (rw == null || rw.Displayed == false) // don't go beyond end or beyond displayed area { //System.Diagnostics.Debug.WriteLine("Stop at " + row + " " + autoupdaterowoffset); break; } autoupdaterowoffset++; HistoryEntry he = rw.Tag as HistoryEntry; if (!EDSMClass.HasBodyLookupOccurred(he.System.Name)) // this tells us if a body lookup has occurred { System.Diagnostics.Debug.WriteLine("StarList EDSM Update row" + row); CheckEDSM(rw); break; } else { System.Diagnostics.Debug.WriteLine("StarList Skip row as already checked " + row); } } } }
private void dataGridViewRouteSystems_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex == 0) { string sysname = e.FormattedValue.ToString(); var row = dataGridViewExplore.Rows[e.RowIndex]; var cell = dataGridViewExplore[e.ColumnIndex, e.RowIndex]; ISystem sys = SystemCache.FindSystem(sysname); EDSMClass edsm = new EDSMClass(); if (sysname != "" && sys == null && !edsm.IsKnownSystem(sysname)) { row.ErrorText = "System not known to EDSM".T(EDTx.UserControlExploration_EDSMUnk); } else { row.ErrorText = ""; } } }
private void textBox_TextChanged(object sender, EventArgs e) { if (validatestarname) { ISystem f = SystemCache.FindSystem(textBoxName.Text); if (f != null && f.HasCoordinate) { InitialisePos(f); var edsm = new EDSMClass(); edsmurl = edsm.GetUrlToEDSMSystem(f.Name, f.EDSMID); SurfaceBookmarks.Init(f.Name); } else { textBoxX.Text = textBoxY.Text = textBoxZ.Text = ""; } buttonEDSM.Enabled = buttonOK.Enabled = ValidateData() && f != null; } else { buttonOK.Enabled = ValidateData(); } }
private void textBox_TextChanged(object sender, EventArgs e) { if (validatestarname) { ISystem f = SystemCache.FindSystem(textBoxName.Text, null, false); // no edsm lookup, too slow to do interactively. if (f != null && f.HasCoordinate) { InitialisePos(f); var edsm = new EDSMClass(); edsmurl = edsm.GetUrlToSystem(f.Name); SurfaceBookmarks.Init(f.Name, helist); } else { textBoxX.Text = textBoxY.Text = textBoxZ.Text = ""; } buttonEDSM.Enabled = buttonOK.Enabled = ValidateData() && f != null; } else { buttonOK.Enabled = ValidateData(); } }
private void Controller_NewEntrySecond(HistoryEntry he, HistoryList hl) // called after all UI's have had their chance { BaseUtils.AppTicks.TickCountLapDelta("DFS", true); actioncontroller.ActionRunOnEntry(he, Actions.ActionEventEDList.NewEntry(he)); var t1 = BaseUtils.AppTicks.TickCountLapDelta("DFS"); if (t1.Item2 >= 80) { System.Diagnostics.Trace.WriteLine("NE Second Actions slow " + t1.Item1); } // all notes committed SystemNoteClass.CommitDirtyNotes((snc) => { if (EDCommander.Current.SyncToEdsm && snc.FSDEntry) { EDSMClass.SendComments(snc.SystemName, snc.Note, 0, he.Commander); } }); var lastent = history.GetLast; if (!object.ReferenceEquals(he, lastent)) { LogLineHighlight(string.Format("Current history entry is not last in history - possible re-entrancy.\nAlert the EDDiscovery developers using either discord or Github (see help) and attach log file {0}", BaseUtils.TraceLog.LogFileName)); Trace.WriteLine($"Current history entry is not last in history"); Trace.WriteLine($"Current entry: {he.journalEntry?.GetJsonString()}"); Trace.WriteLine($"Last entry: {lastent.journalEntry?.GetJsonString()}"); Trace.WriteLine($"Stack Trace:"); Trace.WriteLine(new StackTrace(true).ToString()); } if (he.IsFSDCarrierJump) { int count = history.GetVisitsCount(he.System.Name); LogLine(string.Format("Arrived at system {0} Visit No. {1}".T(EDTx.EDDiscoveryForm_Arrived), he.System.Name, count)); System.Diagnostics.Trace.WriteLine("Arrived at system: " + he.System.Name + " " + count + ":th visit."); } if (EDCommander.Current.SyncToEdsm && EDSMJournalSync.OkayToSend(he)) // send this one, if allowed. { EDSMJournalSync.SendEDSMEvents(LogLine, new List <HistoryEntry>() { he }); // send, if bad credentials, EDSM will moan alerting the user } if (EDCommander.Current.SyncToInara) { EliteDangerousCore.Inara.InaraSync.NewEvent(LogLine, hl, he); } if (EDCommander.Current.SyncToIGAU) { EliteDangerousCore.IGAU.IGAUSync.NewEvent(LogLine, he); } if (EDCommander.Current.SyncToEDAstro) { EliteDangerousCore.EDAstro.EDAstroSync.SendEDAstroEvents(new List <HistoryEntry>() { he }); } if (EDDNClass.IsEDDNMessage(he.EntryType) && he.AgeOfEntry() < TimeSpan.FromDays(1.0) && EDCommander.Current.SyncToEddn == true) { EDDNSync.SendEDDNEvents(LogLine, he); } DLLManager.NewJournalEntry(EliteDangerousCore.DLL.EDDDLLCallerHE.CreateFromHistoryEntry(history, he), false); screenshotconverter.NewJournalEntry(he.journalEntry); // tell the screenshotter. CheckActionProfile(he); }
private void buttonExtExcel_Click(object sender, EventArgs e) { Forms.ExportForm frm = new Forms.ExportForm(); frm.Init(new string[] { "All", "Stars only", "Planets only", //2 "Exploration List Stars", //3 "Exploration List Planets", //4 "Sold Exploration Data", // 5 }); if (frm.ShowDialog(FindForm()) == DialogResult.OK) { BaseUtils.CSVWrite csv = new BaseUtils.CSVWrite(); csv.SetCSVDelimiter(frm.Comma); try { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(frm.Path)) { if (frm.SelectedIndex == 5) { int count; List <HistoryEntry> data = HistoryList.FilterByJournalEvent(discoveryform.history.ToList(), "Sell Exploration Data", out count); data = (from he in data where he.EventTimeLocal >= frm.StartTime && he.EventTimeLocal <= frm.EndTime orderby he.EventTimeUTC descending select he).ToList(); List <HistoryEntry> scans = HistoryList.FilterByJournalEvent(discoveryform.history.ToList(), "Scan", out count); if (frm.IncludeHeader) { writer.Write(csv.Format("Time")); writer.Write(csv.Format("System")); writer.Write(csv.Format("Star type")); writer.Write(csv.Format("Planet type", false)); writer.WriteLine(); } foreach (HistoryEntry he in data) { JournalSellExplorationData jsed = he.journalEntry as JournalSellExplorationData; if (jsed == null || jsed.Discovered == null) { continue; } foreach (String system in jsed.Discovered) { writer.Write(csv.Format(jsed.EventTimeLocal)); writer.Write(csv.Format(system)); EDStar star = EDStar.Unknown; EDPlanet planet = EDPlanet.Unknown_Body_Type; foreach (HistoryEntry scanhe in scans) { JournalScan scan = scanhe.journalEntry as JournalScan; if (scan.BodyName.Equals(system, StringComparison.OrdinalIgnoreCase)) { star = scan.StarTypeID; planet = scan.PlanetTypeID; break; } } writer.Write(csv.Format((star != EDStar.Unknown) ? Enum.GetName(typeof(EDStar), star) : "")); writer.Write(csv.Format((planet != EDPlanet.Unknown_Body_Type) ? Enum.GetName(typeof(EDPlanet), planet) : "", false)); writer.WriteLine(); } } } else { List <JournalScan> scans = null; if (frm.SelectedIndex < 3) { var entries = JournalEntry.GetByEventType(JournalTypeEnum.Scan, EDCommander.CurrentCmdrID, frm.StartTime, frm.EndTime); scans = entries.ConvertAll(x => (JournalScan)x); } else { ExplorationSetClass currentExplorationSet = new ExplorationSetClass(); string file = currentExplorationSet.DialogLoad(FindForm()); if (file != null) { scans = new List <JournalScan>(); foreach (string system in currentExplorationSet.Systems) { ISystem sys = SystemCache.FindSystem(system); if (sys != null) { List <JournalScan> sysscans = EDSMClass.GetBodiesList(sys.EDSMID); if (sysscans != null) { scans.AddRange(sysscans); } } } } else { return; } } bool ShowStars = frm.SelectedIndex < 2 || frm.SelectedIndex == 3; bool ShowPlanets = frm.SelectedIndex == 0 || frm.SelectedIndex == 2 || frm.SelectedIndex == 4; List <JournalSAAScanComplete> mappings = ShowPlanets ? JournalEntry.GetByEventType(JournalTypeEnum.SAAScanComplete, EDCommander.CurrentCmdrID, frm.StartTime, frm.EndTime) .ConvertAll(x => (JournalSAAScanComplete)x) : null; if (frm.IncludeHeader) { // Write header writer.Write(csv.Format("Time")); writer.Write(csv.Format("BodyName")); writer.Write(csv.Format("Estimated Value")); writer.Write(csv.Format("DistanceFromArrivalLS")); writer.Write(csv.Format("WasMapped")); writer.Write(csv.Format("WasDiscovered")); if (ShowStars) { writer.Write(csv.Format("StarType")); writer.Write(csv.Format("StellarMass")); writer.Write(csv.Format("AbsoluteMagnitude")); writer.Write(csv.Format("Age MY")); writer.Write(csv.Format("Luminosity")); } writer.Write(csv.Format("Radius")); writer.Write(csv.Format("RotationPeriod")); writer.Write(csv.Format("SurfaceTemperature")); if (ShowPlanets) { writer.Write(csv.Format("TidalLock")); writer.Write(csv.Format("TerraformState")); writer.Write(csv.Format("PlanetClass")); writer.Write(csv.Format("Atmosphere")); writer.Write(csv.Format("Iron")); writer.Write(csv.Format("Silicates")); writer.Write(csv.Format("SulphurDioxide")); writer.Write(csv.Format("CarbonDioxide")); writer.Write(csv.Format("Nitrogen")); writer.Write(csv.Format("Oxygen")); writer.Write(csv.Format("Water")); writer.Write(csv.Format("Argon")); writer.Write(csv.Format("Ammonia")); writer.Write(csv.Format("Methane")); writer.Write(csv.Format("Hydrogen")); writer.Write(csv.Format("Helium")); writer.Write(csv.Format("Volcanism")); writer.Write(csv.Format("SurfaceGravity")); writer.Write(csv.Format("SurfacePressure")); writer.Write(csv.Format("Landable")); writer.Write(csv.Format("EarthMasses")); writer.Write(csv.Format("IcePercent")); writer.Write(csv.Format("RockPercent")); writer.Write(csv.Format("MetalPercent")); } // Common orbital param writer.Write(csv.Format("SemiMajorAxis")); writer.Write(csv.Format("Eccentricity")); writer.Write(csv.Format("OrbitalInclination")); writer.Write(csv.Format("Periapsis")); writer.Write(csv.Format("OrbitalPeriod")); writer.Write(csv.Format("AxialTilt")); if (ShowPlanets) { writer.Write(csv.Format("Carbon")); writer.Write(csv.Format("Iron")); writer.Write(csv.Format("Nickel")); writer.Write(csv.Format("Phosphorus")); writer.Write(csv.Format("Sulphur")); writer.Write(csv.Format("Arsenic")); writer.Write(csv.Format("Chromium")); writer.Write(csv.Format("Germanium")); writer.Write(csv.Format("Manganese")); writer.Write(csv.Format("Selenium")); writer.Write(csv.Format("Vanadium")); writer.Write(csv.Format("Zinc")); writer.Write(csv.Format("Zirconium")); writer.Write(csv.Format("Cadmium")); writer.Write(csv.Format("Mercury")); writer.Write(csv.Format("Molybdenum")); writer.Write(csv.Format("Niobium")); writer.Write(csv.Format("Tin")); writer.Write(csv.Format("Tungsten")); writer.Write(csv.Format("Antimony")); writer.Write(csv.Format("Polonium")); writer.Write(csv.Format("Ruthenium")); writer.Write(csv.Format("Technetium")); writer.Write(csv.Format("Tellurium")); writer.Write(csv.Format("Yttrium")); } writer.WriteLine(); } foreach (JournalScan je in scans) { JournalScan scan = je as JournalScan; if (ShowPlanets == true && !string.IsNullOrEmpty(scan.PlanetClass)) { var mapping = mappings?.FirstOrDefault(m => m.BodyID == scan.BodyID); if (mapping != null) { scan.SetMapped(true, mapping.ProbesUsed <= mapping.EfficiencyTarget); } } if (ShowPlanets == false) // Then only show stars. { if (String.IsNullOrEmpty(scan.StarType)) { continue; } } if (ShowStars == false) // Then only show planets { if (String.IsNullOrEmpty(scan.PlanetClass)) { continue; } } writer.Write(csv.Format(scan.EventTimeUTC)); writer.Write(csv.Format(scan.BodyName)); writer.Write(csv.Format(scan.EstimatedValue)); writer.Write(csv.Format(scan.DistanceFromArrivalLS)); writer.Write(csv.Format(scan.WasMapped)); writer.Write(csv.Format(scan.WasDiscovered)); if (ShowStars) { writer.Write(csv.Format(scan.StarType)); writer.Write(csv.Format((scan.nStellarMass.HasValue) ? scan.nStellarMass.Value : 0)); writer.Write(csv.Format((scan.nAbsoluteMagnitude.HasValue) ? scan.nAbsoluteMagnitude.Value : 0)); writer.Write(csv.Format((scan.nAge.HasValue) ? scan.nAge.Value : 0)); writer.Write(csv.Format(scan.Luminosity)); } writer.Write(csv.Format(scan.nRadius.HasValue ? scan.nRadius.Value : 0)); writer.Write(csv.Format(scan.nRotationPeriod.HasValue ? scan.nRotationPeriod.Value : 0)); writer.Write(csv.Format(scan.nSurfaceTemperature.HasValue ? scan.nSurfaceTemperature.Value : 0)); if (ShowPlanets) { writer.Write(csv.Format(scan.nTidalLock.HasValue ? scan.nTidalLock.Value : false)); writer.Write(csv.Format((scan.TerraformState != null) ? scan.TerraformState : "")); writer.Write(csv.Format((scan.PlanetClass != null) ? scan.PlanetClass : "")); writer.Write(csv.Format((scan.Atmosphere != null) ? scan.Atmosphere : "")); writer.Write(csv.Format(scan.GetAtmosphereComponent("Iron"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Silicates"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("SulphurDioxide"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("CarbonDioxide"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Nitrogen"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Oxygen"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Water"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Argon"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Ammonia"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Methane"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Hydrogen"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Helium"))); writer.Write(csv.Format((scan.Volcanism != null) ? scan.Volcanism : "")); writer.Write(csv.Format(scan.nSurfaceGravity.HasValue ? scan.nSurfaceGravity.Value : 0)); writer.Write(csv.Format(scan.nSurfacePressure.HasValue ? scan.nSurfacePressure.Value : 0)); writer.Write(csv.Format(scan.nLandable.HasValue ? scan.nLandable.Value : false)); writer.Write(csv.Format((scan.nMassEM.HasValue) ? scan.nMassEM.Value : 0)); writer.Write(csv.Format(scan.GetCompositionPercent("Ice"))); writer.Write(csv.Format(scan.GetCompositionPercent("Rock"))); writer.Write(csv.Format(scan.GetCompositionPercent("Metal"))); } // Common orbital param writer.Write(csv.Format(scan.nSemiMajorAxis.HasValue ? scan.nSemiMajorAxis.Value : 0)); writer.Write(csv.Format(scan.nEccentricity.HasValue ? scan.nEccentricity.Value : 0)); writer.Write(csv.Format(scan.nOrbitalInclination.HasValue ? scan.nOrbitalInclination.Value : 0)); writer.Write(csv.Format(scan.nPeriapsis.HasValue ? scan.nPeriapsis.Value : 0)); writer.Write(csv.Format(scan.nOrbitalPeriod.HasValue ? scan.nOrbitalPeriod.Value : 0)); writer.Write(csv.Format(scan.nAxialTilt.HasValue ? scan.nAxialTilt : null)); if (ShowPlanets) { writer.Write(csv.Format(scan.GetMaterial("Carbon"))); writer.Write(csv.Format(scan.GetMaterial("Iron"))); writer.Write(csv.Format(scan.GetMaterial("Nickel"))); writer.Write(csv.Format(scan.GetMaterial("Phosphorus"))); writer.Write(csv.Format(scan.GetMaterial("Sulphur"))); writer.Write(csv.Format(scan.GetMaterial("Arsenic"))); writer.Write(csv.Format(scan.GetMaterial("Chromium"))); writer.Write(csv.Format(scan.GetMaterial("Germanium"))); writer.Write(csv.Format(scan.GetMaterial("Manganese"))); writer.Write(csv.Format(scan.GetMaterial("Selenium"))); writer.Write(csv.Format(scan.GetMaterial("Vanadium"))); writer.Write(csv.Format(scan.GetMaterial("Zinc"))); writer.Write(csv.Format(scan.GetMaterial("Zirconium"))); writer.Write(csv.Format(scan.GetMaterial("Cadmium"))); writer.Write(csv.Format(scan.GetMaterial("Mercury"))); writer.Write(csv.Format(scan.GetMaterial("Molybdenum"))); writer.Write(csv.Format(scan.GetMaterial("Niobium"))); writer.Write(csv.Format(scan.GetMaterial("Tin"))); writer.Write(csv.Format(scan.GetMaterial("Tungsten"))); writer.Write(csv.Format(scan.GetMaterial("Antimony"))); writer.Write(csv.Format(scan.GetMaterial("Polonium"))); writer.Write(csv.Format(scan.GetMaterial("Ruthenium"))); writer.Write(csv.Format(scan.GetMaterial("Technetium"))); writer.Write(csv.Format(scan.GetMaterial("Tellurium"))); writer.Write(csv.Format(scan.GetMaterial("Yttrium"))); } writer.WriteLine(); } } writer.Close(); if (frm.AutoOpen) { System.Diagnostics.Process.Start(frm.Path); } } } catch { ExtendedControls.MessageBoxTheme.Show(FindForm(), "Failed to write to " + frm.Path, "Export Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } }
private void StoreSystemNote() { string txt; try { EDSMClass edsm = new EDSMClass(); SQLiteDBClass db = new SQLiteDBClass(); edsm.apiKey = EDDiscoveryForm.EDDConfig.CurrentCommander.APIKey; edsm.commanderName = EDDiscoveryForm.EDDConfig.CurrentCommander.Name; if (currentSysPos == null || currentSysPos.curSystem == null) { return; } txt = richTextBoxNote.Text; if (currentSysPos.curSystem.Note == null) { currentSysPos.curSystem.Note = ""; } if (currentSysPos != null && !txt.Equals(currentSysPos.curSystem.Note)) { SystemNoteClass sn; List <SystemClass> systems = new List <SystemClass>(); if (SQLiteDBClass.globalSystemNotes.ContainsKey(currentSysPos.curSystem.SearchName)) { sn = SQLiteDBClass.globalSystemNotes[currentSysPos.curSystem.SearchName]; sn.Note = txt; sn.Time = DateTime.Now; sn.Update(); } else { sn = new SystemNoteClass(); sn.Name = currentSysPos.curSystem.name; sn.Note = txt; sn.Time = DateTime.Now; sn.Add(); } currentSysPos.curSystem.Note = txt; if (dataGridViewTravel.SelectedCells.Count > 0) // if we have selected (we should!) { dataGridViewTravel.Rows[dataGridViewTravel.SelectedCells[0].OwningRow.Index].Cells[3].Value = txt; } if (edsm.commanderName == null || edsm.apiKey == null) { return; } if (edsm.commanderName.Length > 1 && edsm.apiKey.Length > 1) { edsm.SetComment(sn); } } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Exception : " + ex.Message); System.Diagnostics.Trace.WriteLine(ex.StackTrace); LogTextHighlight("Exception : " + ex.Message); LogTextHighlight(ex.StackTrace); } }
private void buttonExtEDSMClick(object sender, EventArgs e) { if (numberBoxMaxRadius.Value > 100) { if (ExtendedControls.MessageBoxTheme.Show(FindForm(), "This is a large radius, it make take a long time or not work, are you sure?", "Warning - Large radius", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.Cancel) { return; } } Cursor = Cursors.WaitCursor; bool spherical = !checkBoxCustomCube.Checked; Task taskEDSM = Task <List <Tuple <ISystem, double> > > .Factory.StartNew(() => { EDSMClass edsm = new EDSMClass(); // cube: use *1.412 (sqrt(2)) to reach out to far corner of cube // cube: must get centre system, to know what co-ords it is.. return(edsm.GetSphereSystems(textBoxSystemName.Text, numberBoxMaxRadius.Value * (spherical ? 1.00 : 1.412), spherical ? numberBoxMinRadius.Value : 0)); }).ContinueWith(task => this.Invoke(new Action(() => { List <Tuple <ISystem, double> > listsphere = task.Result; if (!spherical && listsphere != null) // if cubed, need to filter them out { ISystem centre = listsphere.Find(x => x.Item2 <= 1)?.Item1; // find centre, i.e less 1 ly distance if (centre != null) { //System.Diagnostics.Debug.WriteLine("From " + listsphere.Count()); //foreach (var x in listsphere) System.Diagnostics.Debug.WriteLine("<" + x.Item1.ToString()); double mindistsq = numberBoxMinRadius.Value * numberBoxMinRadius.Value; // mindist is the square line distance, per stardistance use listsphere = (from s in listsphere where (s.Item1.X - centre.X) * (s.Item1.X - centre.X) + (s.Item1.Y - centre.Y) * (s.Item1.Y - centre.Y) + (s.Item1.Z - centre.Z) * (s.Item1.Z - centre.Z) >= mindistsq && Math.Abs(s.Item1.X - centre.X) <= numberBoxMaxRadius.Value && Math.Abs(s.Item1.Y - centre.Y) <= numberBoxMaxRadius.Value && Math.Abs(s.Item1.Z - centre.Z) <= numberBoxMaxRadius.Value select s).ToList(); //System.Diagnostics.Debug.WriteLine("To " + listsphere.Count()); //foreach (var x in listsphere) System.Diagnostics.Debug.WriteLine(">" + x.Item1.ToString()); } else { listsphere = null; } } if (listsphere == null) { ExtendedControls.MessageBoxTheme.Show(this.FindForm(), "EDSM did not return any data on " + textBoxSystemName.Text + Environment.NewLine + "It may be a galactic object that it does not know about", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } Cursor = Cursors.Default; ReturnSystems(listsphere); } ))); }
private void StoreSystemNote() { string txt; try { EDSMClass edsm = new EDSMClass(); SQLiteDBClass db = new SQLiteDBClass(); edsm.apiKey = EDDiscoveryForm.EDDConfig.CurrentCommander.APIKey; edsm.commanderName = EDDiscoveryForm.EDDConfig.CurrentCommander.Name; if (currentSysPos == null || currentSysPos.curSystem == null) { return; } //SystemPosition sp = (SystemPosition)dataGridView1.Rows[lastRowIndex].Cells[1].Tag; txt = richTextBoxNote.Text; if (currentSysPos.curSystem.Note == null) { currentSysPos.curSystem.Note = ""; } if (currentSysPos != null && !txt.Equals(currentSysPos.curSystem.Note)) { SystemNoteClass sn; List <SystemClass> systems = new List <SystemClass>(); if (SQLiteDBClass.globalSystemNotes.ContainsKey(currentSysPos.curSystem.SearchName)) { sn = SQLiteDBClass.globalSystemNotes[currentSysPos.curSystem.SearchName]; sn.Note = txt; sn.Time = DateTime.Now; sn.Update(); } else { sn = new SystemNoteClass(); sn.Name = currentSysPos.curSystem.name; sn.Note = txt; sn.Time = DateTime.Now; sn.Add(); } currentSysPos.curSystem.Note = txt; dataGridView1.Rows[lastRowIndex].Cells[3].Value = txt; if (edsm.commanderName == null || edsm.apiKey == null) { return; } if (edsm.commanderName.Length > 1 && edsm.apiKey.Length > 1) { edsm.SetComment(sn); } } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Exception : " + ex.Message); System.Diagnostics.Trace.WriteLine(ex.StackTrace); LogText("Exception : " + ex.Message, Color.Red); LogText(ex.StackTrace, Color.Red); } }
public long UpdateSync(bool[] grididallow, Func <bool> PendingClose, Action <string> ReportProgress) { DateTime lastrecordtime = SystemsDatabase.Instance.GetLastEDSMRecordTimeUTC(); DateTime maximumupdatetimewindow = DateTime.UtcNow.AddDays(-ForcedFullDownloadDays); // limit download to this amount of days if (lastrecordtime < maximumupdatetimewindow) { lastrecordtime = maximumupdatetimewindow; // this stops crazy situations where somehow we have a very old date but the full sync did not take care of it } long updates = 0; double fetchmult = 1; DateTime minimumfetchspan = DateTime.UtcNow.AddHours(-UpdateFetchHours / 2); // we don't bother fetching if last record time is beyond this point while (lastrecordtime < minimumfetchspan) // stop at X mins before now, so we don't get in a condition { // where we do a set, the time moves to just before now, // and we then do another set with minimum amount of hours if (PendingClose()) { return(updates); } if (updates == 0) { LogLine("Checking for updated EDSM systems (may take a few moments)."); } EDSMClass edsm = new EDSMClass(); double hourstofetch = UpdateFetchHours; //EDSM new server feb 2021, more capable, DateTime enddate = lastrecordtime + TimeSpan.FromHours(hourstofetch * fetchmult); if (enddate > DateTime.UtcNow) { enddate = DateTime.UtcNow; } LogLine($"Downloading systems from UTC {lastrecordtime.ToUniversalTime().ToString()} to {enddate.ToUniversalTime().ToString()}"); System.Diagnostics.Debug.WriteLine($"Downloading systems from UTC {lastrecordtime.ToUniversalTime().ToString()} to {enddate.ToUniversalTime().ToString()} {hourstofetch}"); string json = null; BaseUtils.ResponseData response; try { Stopwatch sw = new Stopwatch(); response = edsm.RequestSystemsData(lastrecordtime, enddate, timeout: 20000); fetchmult = Math.Max(0.1, Math.Min(Math.Min(fetchmult * 1.1, 1.0), 5000.0 / sw.ElapsedMilliseconds)); } catch (WebException ex) { ReportProgress($"EDSM request failed"); if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null && ex.Response is HttpWebResponse) { string status = ((HttpWebResponse)ex.Response).StatusDescription; LogLine($"Download of EDSM systems from the server failed ({status}), will try next time program is run"); } else { LogLine($"Download of EDSM systems from the server failed ({ex.Status.ToString()}), will try next time program is run"); } return(updates); } catch (Exception ex) { ReportProgress($"EDSM request failed"); LogLine($"Download of EDSM systems from the server failed ({ex.Message}), will try next time program is run"); return(updates); } if (response.Error) { if ((int)response.StatusCode == 429) { LogLine($"EDSM rate limit hit - waiting 2 minutes"); for (int sec = 0; sec < 120; sec++) { if (!PendingClose()) { System.Threading.Thread.Sleep(1000); } } } else { LogLine($"Download of EDSM systems from the server failed ({response.StatusCode.ToString()}), will try next time program is run"); return(updates); } } json = response.Body; if (json == null) { ReportProgress("EDSM request failed"); LogLine("Download of EDSM systems from the server failed (no data returned), will try next time program is run"); return(updates); } // debug File.WriteAllText(@"c:\code\json.txt", json); DateTime prevrectime = lastrecordtime; System.Diagnostics.Debug.WriteLine("Last record time {0} JSON size {1}", lastrecordtime.ToUniversalTime(), json.Length); long updated = 0; try { ReportProgress($"EDSM star database update from UTC " + lastrecordtime.ToUniversalTime().ToString()); updated = SystemsDB.ParseEDSMJSONString(json, grididallow, ref lastrecordtime, PendingClose, ReportProgress, ""); System.Diagnostics.Debug.WriteLine($".. Updated {updated} to {lastrecordtime.ToUniversalTime().ToString()}"); System.Diagnostics.Debug.WriteLine("Updated to time {0}", lastrecordtime.ToUniversalTime()); // if lastrecordtime did not change (=) or worse still, EDSM somehow moved the time back (unlikely) if (lastrecordtime <= prevrectime) { lastrecordtime += TimeSpan.FromHours(12); // Lets move on manually so we don't get stuck } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("SysClassEDSM.2 Exception " + e.ToString()); ReportProgress("EDSM request failed"); LogLine("Processing EDSM systems download failed, will try next time program is run"); return(updates); } updates += updated; SystemsDatabase.Instance.SetLastEDSMRecordTimeUTC(lastrecordtime); // keep on storing this in case next time we get an exception int delay = 10; // Anthor's normal delay int ratelimitlimit; int ratelimitremain; int ratelimitreset; if (response.Headers != null && response.Headers["X-Rate-Limit-Limit"] != null && response.Headers["X-Rate-Limit-Remaining"] != null && response.Headers["X-Rate-Limit-Reset"] != null && Int32.TryParse(response.Headers["X-Rate-Limit-Limit"], out ratelimitlimit) && Int32.TryParse(response.Headers["X-Rate-Limit-Remaining"], out ratelimitremain) && Int32.TryParse(response.Headers["X-Rate-Limit-Reset"], out ratelimitreset)) { if (ratelimitremain < ratelimitlimit * 3 / 4) // lets keep at least X remaining for other purposes later.. { delay = ratelimitreset / (ratelimitlimit - ratelimitremain); // slow down to its pace now.. example 878/(360-272) = 10 seconds per quota } else { delay = 0; } System.Diagnostics.Debug.WriteLine("EDSM Delay Parameters {0} {1} {2} => {3}s", ratelimitlimit, ratelimitremain, ratelimitreset, delay); } for (int sec = 0; sec < delay; sec++) { if (!PendingClose()) { System.Threading.Thread.Sleep(1000); } } } return(updates); }
private void DoPerformSync() // in Background worker { InvokeAsyncOnUiThread.Invoke(() => OnSyncStarting?.Invoke()); // tell listeners sync is starting resyncEDSMRequestedFlag = 1; // sync is happening, stop any async requests.. // check for 102, if so, upgrade it.. SystemsDatabase.Instance.UpgradeSystemTableFrom102TypeDB(() => PendingClose, ReportSyncProgress, syncstate.perform_edsm_fullsync); if (EDDConfig.Instance.EDSMDownload) // if no system off, and EDSM download on { Debug.WriteLine(BaseUtils.AppTicks.TickCountLap() + " Perform System Data Download from EDSM"); try { bool[] grids = new bool[GridId.MaxGridID]; foreach (int i in GridId.FromString(EDDConfig.Instance.EDSMGridIDs)) { grids[i] = true; } syncstate.ClearCounters(); if (syncstate.perform_edsm_fullsync || syncstate.perform_edsm_alias_sync) { if (syncstate.perform_edsm_fullsync && !PendingClose) { // Download new systems try { string edsmsystems = Path.Combine(EDDOptions.Instance.AppDataDirectory, "edsmsystems.json.gz"); ReportSyncProgress("Performing full download of System Data from EDSM"); Debug.WriteLine(BaseUtils.AppTicks.TickCountLap() + " Full system download using URL " + EDDConfig.Instance.EDSMFullSystemsURL); bool success = BaseUtils.DownloadFile.HTTPDownloadFile(EDDConfig.Instance.EDSMFullSystemsURL, edsmsystems, false, out bool newfile); syncstate.perform_edsm_fullsync = false; if (success) { syncstate.edsm_fullsync_count = SystemsDatabase.Instance.UpgradeSystemTableFromFile(edsmsystems, grids, () => PendingClose, ReportSyncProgress); if (syncstate.edsm_fullsync_count < 0) // this should always update something, the table is replaced. If its not, its been cancelled { return; } BaseUtils.FileHelpers.DeleteFileNoError(edsmsystems); // remove file - don't hold in storage } else { ReportSyncProgress(""); LogLineHighlight("Failed to download full EDSM systems file. Try re-running EDD later"); BaseUtils.FileHelpers.DeleteFileNoError(edsmsystems); // remove file - don't hold in storage return; // new! if we failed to download, fail here, wait for another time } } catch (Exception ex) { LogLineHighlight("GetAllEDSMSystems exception:" + ex.Message); } } if (!PendingClose && syncstate.perform_edsm_alias_sync) { try { EDSMClass edsm = new EDSMClass(); string edsmhiddensystems = Path.Combine(EDDOptions.Instance.AppDataDirectory, "edsmhiddensystems.json"); string jsonhidden = edsm.GetHiddenSystems(edsmhiddensystems); if (jsonhidden != null) { SystemsDB.ParseAliasString(jsonhidden); syncstate.perform_edsm_alias_sync = false; SystemsDatabase.Instance.SetLastEDSMAliasDownloadTime(); } } catch (Exception ex) { LogLineHighlight("GetEDSMAlias exception: " + ex.Message); } } } if (!PendingClose) // perform an update sync to get any new EDSM data { syncstate.edsm_updatesync_count = UpdateSync(grids, () => PendingClose, ReportSyncProgress); } } catch (OperationCanceledException) { // Swallow Operation Cancelled exceptions } catch (Exception ex) { LogLineHighlight("Check Systems exception: " + ex.Message + Environment.NewLine + "Trace: " + ex.StackTrace); } } InvokeAsyncOnUiThread(() => PerformSyncCompletedonUI()); }
private void SubmitToEDSM() { try { EDSMClass edsm = new EDSMClass(); // current commander credentials if (!edsm.ValidCredentials) { this.BeginInvoke(new MethodInvoker(() => { ExtendedControls.MessageBoxTheme.Show(FindForm(), "Please enter commander name before submitting the system!".T(EDTx.UserControlTrilateration_Cmdr)); UnfreezeTrilaterationUI(); })); return; } var distances = new Dictionary <string, double>(); for (int i = 0, count = dataGridViewDistances.Rows.Count - 1; i < count; i++) { var systemCell = dataGridViewDistances[0, i]; var distanceCell = dataGridViewDistances[1, i]; if (systemCell.Value != null && distanceCell.Value != null) { var system = systemCell.Value.ToString(); var value = distanceCell.Value.ToString().Trim(); var parsedDistance = BaseUtils.DistanceParser.ParseInterstellarDistance(value); if (parsedDistance.HasValue) { // can over-ride drop down now if it's a real system so you could add duplicates if you wanted (even once I've figured out issue #81 which makes it easy if not likely...) if (!distances.Keys.Contains(system)) { distances.Add(system, parsedDistance.Value); } } } } bool trilatOk = false; bool respOk = true; List <KeyValuePair <string, double> > distlist = distances.ToList(); for (int i = 0; i < distances.Count; i += 20) { var dists = new Dictionary <string, double>(); for (int j = i; j < i + 20 && j < distances.Count; j++) { dists[distlist[j].Key] = distlist[j].Value; } var responseM = edsm.SubmitDistances(targetsystem.Name, dists); Console.WriteLine(responseM); string infoM; bool trilaterationOkM; var responseOkM = edsm.ShowDistanceResponse(responseM, out infoM, out trilaterationOkM); if (trilaterationOkM) { trilatOk = true; } if (!responseOkM) { respOk = false; } Console.WriteLine(infoM); } BeginInvoke((MethodInvoker) delegate { UnfreezeTrilaterationUI(); if (respOk && trilatOk) { LogTextSuccess("EDSM submission succeeded, trilateration successful.".T(EDTx.UserControlTrilateration_Horray) + Environment.NewLine); discoveryform.RefreshHistoryAsync(); checkForUnknownSystemsNowKnown(); } else if (respOk) { LogTextHighlight("EDSM submission succeeded, but trilateration failed. Try adding more distances.".T(EDTx.UserControlTrilateration_Failed) + Environment.NewLine); } else { LogTextHighlight("EDSM submission failed.".T(EDTx.UserControlTrilateration_Dead) + Environment.NewLine); } }); } catch (Exception ex) { this.BeginInvoke(new MethodInvoker(() => { LogTextHighlight("SubmitToEDSM Exception:" + ex.Message); LogText(ex.StackTrace); })); } }
private void buttonExtExcel_Click(object sender, EventArgs e) { Forms.ExportForm frm = new Forms.ExportForm(); frm.Init(new string[] { "All", "Stars only", "Planets only", //2 "Exploration List Stars", //3 "Exploration List Planets", //4 "Ring Scans", //5 }); if (frm.ShowDialog(FindForm()) == DialogResult.OK) { BaseUtils.CSVWrite csv = new BaseUtils.CSVWrite(); csv.SetCSVDelimiter(frm.Comma); try { if (frm.SelectedIndex == 5) { var saaentries = JournalEntry.GetByEventType(JournalTypeEnum.SAASignalsFound, EDCommander.CurrentCmdrID, frm.StartTimeUTC, frm.EndTimeUTC).ConvertAll(x => (JournalSAASignalsFound)x); var scanentries = JournalEntry.GetByEventType(JournalTypeEnum.Scan, EDCommander.CurrentCmdrID, frm.StartTimeUTC, frm.EndTimeUTC).ConvertAll(x => (JournalScan)x); BaseUtils.CSVWriteGrid grd = new BaseUtils.CSVWriteGrid(); grd.SetCSVDelimiter(frm.Comma); string[] headers1 = { "", "", "", "", "", "", "Icy Ring", "", "", "", "", "","", "", "", "", "Rocky", "", "", "", "", "","", "", "Metal Rich", "", "", "", "", "Metalic", "", "", "", "", "Other" }; string[] headers2 = { "Time", "BodyName", "Ring Types", "Mass MT", "Inner Rad (ls)", "Outer Rad (ls)", // icy ring "Water", "Liquid Oxygen", "Methanol Mono", "Methane", "Bromellite", "Grandidierite", "Low Temp Diamonds","Void Opals", "Alexandrite", "Tritium", // rocky "Bauxite", "Indite", "Alexandrite", "Monazite", "Musgravite", "Benitoite", "Serendibite", "Rhodplumsite", // metal rich "Rhodplumsite", "Serendibite", "Platinum", "Monazite", "Painite", // metalic "Rhodplumsite", "Serendibite", "Platinum", "Monazite", "Painite", // others "Geological", "Biological", "Thargoid", "Human", "Guardian", }; string[] fdname = { "Water", "LiquidOxygen", "methanolmonohydratecrystals", "MethaneClathrate", // icy "Bromellite", "Grandidierite", "lowtemperaturediamond", "Opal", "Alexandrite", "Tritium", "Bauxite", "Indite", "Alexandrite", "Monazite", "Musgravite","Benitoite", "Serendibite", "Rhodplumsite", // rocky "Rhodplumsite", "Serendibite", "Platinum", "Monazite", "Painite", // metal rich "Rhodplumsite", "Serendibite", "Platinum", "Monazite", "Painite", // metalic "$SAA_SignalType_Geological;", "$SAA_SignalType_Biological;", "$SAA_SignalType_Thargoid;", "$SAA_SignalType_Human;","$SAA_SignalType_Guardian;" }; grd.GetLineHeader = (row) => { return(row == 1 ? headers2 : row == 0 ? headers1 : null); }; grd.GetLineStatus = (row) => { if (row < saaentries.Count) { for (int rp = row + 1; rp < saaentries.Count; rp++) { if (saaentries[rp].BodyName == saaentries[row].BodyName && (saaentries[rp].EventTimeUTC - saaentries[row].EventTimeUTC) < new TimeSpan(30, 0, 0, 0)) { return(CSVWriteGrid.LineStatus.Skip); // if matches one in front, and its less than 30 days from it, ignore } } return(CSVWriteGrid.LineStatus.OK); } else { return(CSVWriteGrid.LineStatus.EOF); } }; grd.GetLine = (r) => { var entry = saaentries[r]; string signals = string.Join(",", entry.Signals.Select(x => x.Type_Localised)); JournalScan scanof = scanentries.Find(x => x.FindRing(entry.BodyName) != null); bool showrocky = true, showmr = true, showmetalic = true, showicy = true; // only used if item appears more than once below string ringtype = "", mass = "", innerrad = "", outerrad = ""; if (scanof != null) { var ri = scanof.FindRing(entry.BodyName); ringtype = ri.RingClassNormalised(); if (ringtype.Contains("metalic", StringComparison.InvariantCultureIgnoreCase)) { showicy = showrocky = showmr = false; } else if (ringtype.Contains("Metal", StringComparison.InvariantCultureIgnoreCase)) { showicy = showrocky = showmetalic = false; } else if (ringtype.Contains("rocky", StringComparison.InvariantCultureIgnoreCase)) { showicy = showmetalic = showmr = false; } else if (ringtype.Contains("icy", StringComparison.InvariantCultureIgnoreCase)) { showrocky = showmetalic = showmr = false; } mass = ri.MassMT.ToStringInvariant(); innerrad = (ri.InnerRad / JournalScan.oneLS_m).ToStringInvariant("N3"); outerrad = (ri.OuterRad / JournalScan.oneLS_m).ToStringInvariant("N3"); } //string sig = string.Join(",", entry.Signals.Select(x=>x.Type)); // debug return(new object[] { EDDConfig.Instance.ConvertTimeToSelectedFromUTC(entry.EventTimeUTC), entry.BodyName, ringtype, mass, innerrad, outerrad, entry.ContainsStr(fdname[0]), entry.ContainsStr(fdname[1]), entry.ContainsStr(fdname[2]), entry.ContainsStr(fdname[3]), entry.ContainsStr(fdname[4]), entry.ContainsStr(fdname[5]), entry.ContainsStr(fdname[6]), entry.ContainsStr(fdname[7]), entry.ContainsStr(fdname[8], showicy), entry.ContainsStr(fdname[9]), // "Bauxite","Indite","Alexandrite","Monazite", // rocky entry.ContainsStr(fdname[10]), entry.ContainsStr(fdname[11]), entry.ContainsStr(fdname[12], showrocky), entry.ContainsStr(fdname[13], showrocky), // "Musgravite","Benitoite","Serendibite","Rhodplumsite", // rocky entry.ContainsStr(fdname[14]), entry.ContainsStr(fdname[15]), entry.ContainsStr(fdname[16], showrocky), entry.ContainsStr(fdname[17], showrocky), // "Rhodplumsite","Serendibite","Platinum","Monazite","Painite", // metal rich entry.ContainsStr(fdname[18], showmr), entry.ContainsStr(fdname[19], showmr), entry.ContainsStr(fdname[20], showmr), entry.ContainsStr(fdname[21], showmr), entry.ContainsStr(fdname[22], showmr), // "Rhodplumsite","Serendibite","Platinum","Monazite","Painite", // metalic entry.ContainsStr(fdname[23], showmetalic), entry.ContainsStr(fdname[24], showmetalic), entry.ContainsStr(fdname[25], showmetalic), entry.ContainsStr(fdname[26], showmetalic), entry.ContainsStr(fdname[27], showmetalic), entry.ContainsStr(fdname[28]), entry.ContainsStr(fdname[29]), entry.ContainsStr(fdname[30]), entry.ContainsStr(fdname[31]), entry.ContainsStr(fdname[32]), }); }; grd.WriteGrid(frm.Path, frm.AutoOpen, FindForm()); } else { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(frm.Path)) { List <JournalScan> scans = null; if (frm.SelectedIndex < 3) { var entries = JournalEntry.GetByEventType(JournalTypeEnum.Scan, EDCommander.CurrentCmdrID, frm.StartTimeUTC, frm.EndTimeUTC); scans = entries.ConvertAll(x => (JournalScan)x); } else { ExplorationSetClass currentExplorationSet = new ExplorationSetClass(); string file = currentExplorationSet.DialogLoad(FindForm()); if (file != null) { scans = new List <JournalScan>(); foreach (string system in currentExplorationSet.Systems) { ISystem sys = SystemCache.FindSystem(system); if (sys != null) { var jl = EDSMClass.GetBodiesList(sys); List <JournalScan> sysscans = jl.Item1; if (sysscans != null) { scans.AddRange(sysscans); } } } } else { return; } } bool ShowStars = frm.SelectedIndex < 2 || frm.SelectedIndex == 3; bool ShowPlanets = frm.SelectedIndex == 0 || frm.SelectedIndex == 2 || frm.SelectedIndex == 4; bool ShowBeltClusters = frm.SelectedIndex == 0; List <JournalSAAScanComplete> mappings = ShowPlanets ? JournalEntry.GetByEventType(JournalTypeEnum.SAAScanComplete, EDCommander.CurrentCmdrID, frm.StartTimeUTC, frm.EndTimeUTC).ConvertAll(x => (JournalSAAScanComplete)x) : null; if (frm.IncludeHeader) { // Write header writer.Write(csv.Format("Time")); writer.Write(csv.Format("BodyName")); writer.Write(csv.Format("Estimated Value")); writer.Write(csv.Format("DistanceFromArrivalLS")); writer.Write(csv.Format("WasMapped")); writer.Write(csv.Format("WasDiscovered")); if (ShowStars) { writer.Write(csv.Format("StarType")); writer.Write(csv.Format("StellarMass")); writer.Write(csv.Format("AbsoluteMagnitude")); writer.Write(csv.Format("Age MY")); writer.Write(csv.Format("Luminosity")); } writer.Write(csv.Format("Radius")); writer.Write(csv.Format("RotationPeriod")); writer.Write(csv.Format("SurfaceTemperature")); if (ShowPlanets) { writer.Write(csv.Format("TidalLock")); writer.Write(csv.Format("TerraformState")); writer.Write(csv.Format("PlanetClass")); writer.Write(csv.Format("Atmosphere")); writer.Write(csv.Format("Iron")); writer.Write(csv.Format("Silicates")); writer.Write(csv.Format("SulphurDioxide")); writer.Write(csv.Format("CarbonDioxide")); writer.Write(csv.Format("Nitrogen")); writer.Write(csv.Format("Oxygen")); writer.Write(csv.Format("Water")); writer.Write(csv.Format("Argon")); writer.Write(csv.Format("Ammonia")); writer.Write(csv.Format("Methane")); writer.Write(csv.Format("Hydrogen")); writer.Write(csv.Format("Helium")); writer.Write(csv.Format("Volcanism")); writer.Write(csv.Format("SurfaceGravity")); writer.Write(csv.Format("SurfacePressure")); writer.Write(csv.Format("Landable")); writer.Write(csv.Format("EarthMasses")); writer.Write(csv.Format("IcePercent")); writer.Write(csv.Format("RockPercent")); writer.Write(csv.Format("MetalPercent")); } // Common orbital param writer.Write(csv.Format("SemiMajorAxis")); writer.Write(csv.Format("Eccentricity")); writer.Write(csv.Format("OrbitalInclination")); writer.Write(csv.Format("Periapsis")); writer.Write(csv.Format("OrbitalPeriod")); writer.Write(csv.Format("AxialTilt")); if (ShowPlanets) { writer.Write(csv.Format("Carbon")); writer.Write(csv.Format("Iron")); writer.Write(csv.Format("Nickel")); writer.Write(csv.Format("Phosphorus")); writer.Write(csv.Format("Sulphur")); writer.Write(csv.Format("Arsenic")); writer.Write(csv.Format("Chromium")); writer.Write(csv.Format("Germanium")); writer.Write(csv.Format("Manganese")); writer.Write(csv.Format("Selenium")); writer.Write(csv.Format("Vanadium")); writer.Write(csv.Format("Zinc")); writer.Write(csv.Format("Zirconium")); writer.Write(csv.Format("Cadmium")); writer.Write(csv.Format("Mercury")); writer.Write(csv.Format("Molybdenum")); writer.Write(csv.Format("Niobium")); writer.Write(csv.Format("Tin")); writer.Write(csv.Format("Tungsten")); writer.Write(csv.Format("Antimony")); writer.Write(csv.Format("Polonium")); writer.Write(csv.Format("Ruthenium")); writer.Write(csv.Format("Technetium")); writer.Write(csv.Format("Tellurium")); writer.Write(csv.Format("Yttrium")); } writer.WriteLine(); } foreach (JournalScan je in scans) { JournalScan scan = je as JournalScan; if ((je.IsPlanet && ShowPlanets) || (je.IsStar && ShowStars) || (je.IsBeltCluster && ShowBeltClusters)) { if (je.IsPlanet) { var mapping = mappings?.FirstOrDefault(m => m.BodyID == scan.BodyID && m.BodyName == scan.BodyName); if (mapping != null) { scan.SetMapped(true, mapping.ProbesUsed <= mapping.EfficiencyTarget); } } writer.Write(csv.Format(EDDConfig.Instance.ConvertTimeToSelectedFromUTC(scan.EventTimeUTC))); writer.Write(csv.Format(scan.BodyName)); writer.Write(csv.Format(scan.EstimatedValue)); writer.Write(csv.Format(scan.DistanceFromArrivalLS)); writer.Write(csv.Format(scan.WasMapped)); writer.Write(csv.Format(scan.WasDiscovered)); if (ShowStars) { writer.Write(csv.Format(scan.StarType)); writer.Write(csv.Format((scan.nStellarMass.HasValue) ? scan.nStellarMass.Value : 0)); writer.Write(csv.Format((scan.nAbsoluteMagnitude.HasValue) ? scan.nAbsoluteMagnitude.Value : 0)); writer.Write(csv.Format((scan.nAge.HasValue) ? scan.nAge.Value : 0)); writer.Write(csv.Format(scan.Luminosity)); } writer.Write(csv.Format(scan.nRadius.HasValue ? scan.nRadius.Value : 0)); writer.Write(csv.Format(scan.nRotationPeriod.HasValue ? scan.nRotationPeriod.Value : 0)); writer.Write(csv.Format(scan.nSurfaceTemperature.HasValue ? scan.nSurfaceTemperature.Value : 0)); if (ShowPlanets) { writer.Write(csv.Format(scan.nTidalLock.HasValue ? scan.nTidalLock.Value : false)); writer.Write(csv.Format((scan.TerraformState != null) ? scan.TerraformState : "")); writer.Write(csv.Format((scan.PlanetClass != null) ? scan.PlanetClass : "")); writer.Write(csv.Format((scan.Atmosphere != null) ? scan.Atmosphere : "")); writer.Write(csv.Format(scan.GetAtmosphereComponent("Iron"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Silicates"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("SulphurDioxide"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("CarbonDioxide"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Nitrogen"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Oxygen"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Water"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Argon"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Ammonia"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Methane"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Hydrogen"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Helium"))); writer.Write(csv.Format((scan.Volcanism != null) ? scan.Volcanism : "")); writer.Write(csv.Format(scan.nSurfaceGravity.HasValue ? scan.nSurfaceGravity.Value : 0)); writer.Write(csv.Format(scan.nSurfacePressure.HasValue ? scan.nSurfacePressure.Value : 0)); writer.Write(csv.Format(scan.nLandable.HasValue ? scan.nLandable.Value : false)); writer.Write(csv.Format((scan.nMassEM.HasValue) ? scan.nMassEM.Value : 0)); writer.Write(csv.Format(scan.GetCompositionPercent("Ice"))); writer.Write(csv.Format(scan.GetCompositionPercent("Rock"))); writer.Write(csv.Format(scan.GetCompositionPercent("Metal"))); } // Common orbital param writer.Write(csv.Format(scan.nSemiMajorAxis.HasValue ? scan.nSemiMajorAxis.Value : 0)); writer.Write(csv.Format(scan.nEccentricity.HasValue ? scan.nEccentricity.Value : 0)); writer.Write(csv.Format(scan.nOrbitalInclination.HasValue ? scan.nOrbitalInclination.Value : 0)); writer.Write(csv.Format(scan.nPeriapsis.HasValue ? scan.nPeriapsis.Value : 0)); writer.Write(csv.Format(scan.nOrbitalPeriod.HasValue ? scan.nOrbitalPeriod.Value : 0)); writer.Write(csv.Format(scan.nAxialTilt.HasValue ? scan.nAxialTilt : null)); if (ShowPlanets) { writer.Write(csv.Format(scan.GetMaterial("Carbon"))); writer.Write(csv.Format(scan.GetMaterial("Iron"))); writer.Write(csv.Format(scan.GetMaterial("Nickel"))); writer.Write(csv.Format(scan.GetMaterial("Phosphorus"))); writer.Write(csv.Format(scan.GetMaterial("Sulphur"))); writer.Write(csv.Format(scan.GetMaterial("Arsenic"))); writer.Write(csv.Format(scan.GetMaterial("Chromium"))); writer.Write(csv.Format(scan.GetMaterial("Germanium"))); writer.Write(csv.Format(scan.GetMaterial("Manganese"))); writer.Write(csv.Format(scan.GetMaterial("Selenium"))); writer.Write(csv.Format(scan.GetMaterial("Vanadium"))); writer.Write(csv.Format(scan.GetMaterial("Zinc"))); writer.Write(csv.Format(scan.GetMaterial("Zirconium"))); writer.Write(csv.Format(scan.GetMaterial("Cadmium"))); writer.Write(csv.Format(scan.GetMaterial("Mercury"))); writer.Write(csv.Format(scan.GetMaterial("Molybdenum"))); writer.Write(csv.Format(scan.GetMaterial("Niobium"))); writer.Write(csv.Format(scan.GetMaterial("Tin"))); writer.Write(csv.Format(scan.GetMaterial("Tungsten"))); writer.Write(csv.Format(scan.GetMaterial("Antimony"))); writer.Write(csv.Format(scan.GetMaterial("Polonium"))); writer.Write(csv.Format(scan.GetMaterial("Ruthenium"))); writer.Write(csv.Format(scan.GetMaterial("Technetium"))); writer.Write(csv.Format(scan.GetMaterial("Tellurium"))); writer.Write(csv.Format(scan.GetMaterial("Yttrium"))); } writer.WriteLine(); } } writer.Close(); } if (frm.AutoOpen) { System.Diagnostics.Process.Start(frm.Path); } } } catch { ExtendedControls.MessageBoxTheme.Show(FindForm(), "Failed to write to " + frm.Path, "Export Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } }
private void DoPerformSync() // in Background worker { InvokeAsyncOnUiThread.Invoke(() => OnSyncStarting?.Invoke()); // tell listeners sync is starting resyncEDSMEDDBRequestedFlag = 1; // sync is happening, stop any async requests.. Debug.WriteLine(BaseUtils.AppTicks.TickCountLap() + " Perform EDSM/EDDB sync"); try { bool[] grids = new bool[GridId.MaxGridID]; foreach (int i in GridId.FromString(EDDConfig.Instance.EDSMGridIDs)) { grids[i] = true; } syncstate.ClearCounters(); if (syncstate.perform_edsm_fullsync || syncstate.perform_eddb_edsmalias_sync) { if (syncstate.perform_edsm_fullsync && !PendingClose) { // Download new systems try { string edsmsystems = Path.Combine(EliteConfigInstance.InstanceOptions.AppDataDirectory, "edsmsystems.json"); ReportSyncProgress("Performing full download of EDSM Database from server"); bool success = BaseUtils.DownloadFile.HTTPDownloadFile(EliteConfigInstance.InstanceConfig.EDSMFullSystemsURL, edsmsystems, false, out bool newfile); syncstate.perform_edsm_fullsync = false; if (success) { syncstate.edsm_fullsync_count = SQLiteConnectionSystem.UpgradeSystemTableFromFile(edsmsystems, grids, () => PendingClose, ReportSyncProgress); if (syncstate.edsm_fullsync_count < 0) // this should always update something, the table is replaced. If its not, its been cancelled { return; } BaseUtils.FileHelpers.DeleteFileNoError(edsmsystems); // remove file - don't hold in storage } } catch (Exception ex) { LogLineHighlight("GetAllEDSMSystems exception:" + ex.Message); } } if (!PendingClose) { try { EDSMClass edsm = new EDSMClass(); string jsonhidden = edsm.GetHiddenSystems(); if (jsonhidden != null) { SystemsDB.ParseAliasString(jsonhidden); string eddbsystems = Path.Combine(EliteConfigInstance.InstanceOptions.AppDataDirectory, "eddbsystems.json"); bool success = BaseUtils.DownloadFile.HTTPDownloadFile(EliteConfigInstance.InstanceConfig.EDDBSystemsURL, eddbsystems, false, out bool newfile); syncstate.perform_eddb_edsmalias_sync = false; if (success) { syncstate.eddb_sync_count = SystemsDB.ParseEDDBJSONFile(eddbsystems, () => PendingClose); if (syncstate.eddb_sync_count < 0) // on a cancel or error { return; } SQLiteConnectionSystem.SetLastEDDBDownloadTime(); BaseUtils.FileHelpers.DeleteFileNoError(eddbsystems); // remove file - don't hold in storage } } } catch (Exception ex) { LogLineHighlight("GetEDDBUpdate exception: " + ex.Message); } } } if (!PendingClose) { syncstate.edsm_updatesync_count = UpdateSync(grids, () => PendingClose, ReportSyncProgress); } } catch (OperationCanceledException) { // Swallow Operation Cancelled exceptions } catch (Exception ex) { LogLineHighlight("Check Systems exception: " + ex.Message + Environment.NewLine + "Trace: " + ex.StackTrace); } InvokeAsyncOnUiThread(() => PerformSyncCompletedonUI()); }