public static void updateCheckMain(IProgressReporterDialogue frmProgressReporter) { var t = Type.GetType("Mono.Runtime"); MONO = (t != null); try { if (domaster) { CheckMD5(frmProgressReporter, ConfigurationManager.AppSettings["MasterUpdateLocationMD5"].ToString(), ConfigurationManager.AppSettings["MasterUpdateLocationZip"]); } else if (dobeta) { CheckMD5(frmProgressReporter, ConfigurationManager.AppSettings["BetaUpdateLocationMD5"].ToString(), ConfigurationManager.AppSettings["BetaUpdateLocationZip"]); } else { CheckMD5(frmProgressReporter, ConfigurationManager.AppSettings["UpdateLocationMD5"].ToString(), ConfigurationManager.AppSettings["UpdateLocation"]); } var process = new Process(); string exePath = Path.GetDirectoryName(Application.ExecutablePath); if (MONO) { process.StartInfo.FileName = "mono"; process.StartInfo.Arguments = " \"" + exePath + Path.DirectorySeparatorChar + "Updater.exe\"" + " \"" + Application.ExecutablePath + "\""; } else { process.StartInfo.FileName = exePath + Path.DirectorySeparatorChar + "Updater.exe"; process.StartInfo.Arguments = Application.ExecutablePath; } try { foreach (string newupdater in Directory.GetFiles(exePath, "Updater.exe*.new")) { File.Copy(newupdater, newupdater.Remove(newupdater.Length - 4), true); File.Delete(newupdater); } } catch (Exception ex) { log.Error("Exception during update", ex); } if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, "Starting Updater"); } log.Info("Starting new process: " + process.StartInfo.FileName + " with " + process.StartInfo.Arguments); process.Start(); log.Info("Quitting existing process"); if (frmProgressReporter != null) { frmProgressReporter.BeginInvoke((Action) delegate { Application.Exit(); }); } } catch (AggregateException ex) { log.Error("Update Failed", ex.InnerException); CustomMessageBox.Show("Update Failed " + ex.InnerException?.Message); } catch (Exception ex) { log.Error("Update Failed", ex); CustomMessageBox.Show("Update Failed " + ex.Message); } }
static void DoUpdateWorker_DoWork(IProgressReporterDialogue sender) { // TODO: Is this the right place? #region Fetch Parameter Meta Data var progressReporterDialogue = ((IProgressReporterDialogue)sender); /* * progressReporterDialogue.UpdateProgressAndStatus(-1, "Getting updated parameter documentation"); * * try * { * var dns = Dns.GetHostAddresses("github.com"); * var dns2 = Dns.GetHostAddresses("raw.githubusercontent.com"); * * if (dns.Length != 0) * { * if (MissionPlanner.Utilities.Update.dobeta) * ParameterMetaDataParser.GetParameterInformation( * ConfigurationManager.AppSettings["ParameterLocationsBleeding"], "ParameterMetaData.xml"); * else * ParameterMetaDataParser.GetParameterInformation( * ConfigurationManager.AppSettings["ParameterLocations"], "ParameterMetaData.xml"); * } * } * catch (Exception ex) * { * log.Error(ex.ToString()); * CustomMessageBox.Show("Error getting Parameter Information"); * } */ #endregion Fetch Parameter Meta Data progressReporterDialogue.UpdateProgressAndStatus(-1, "Getting Base URL"); try { File.WriteAllText( Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "writetest.txt", "this is a test"); } catch (Exception ex) { log.Info("Write test failed"); throw new Exception("Unable to write to the install directory", ex); } finally { try { File.Delete(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "writetest.txt"); } catch { log.Info("Write test cleanup failed"); } } updateCheckMain(progressReporterDialogue); }
static void CheckMD5(IProgressReporterDialogue frmProgressReporter, string md5url, string baseurl) { log.InfoFormat("get checksums {0} - base {1}", md5url, baseurl); string responseFromServer = ""; WebRequest request = WebRequest.Create(md5url); if (!String.IsNullOrEmpty(Settings.Instance.UserAgent)) { ((HttpWebRequest)request).UserAgent = Settings.Instance.UserAgent; } request.Timeout = 10000; // Set the Method property of the request to POST. request.Method = "GET"; // Get the response. // Get the stream containing content returned by the server. // Open the stream using a StreamReader for easy access. using (WebResponse response = request.GetResponse()) using (Stream dataStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(dataStream)) { // Display the status. log.Info(((HttpWebResponse)response).StatusDescription); // Read the content. responseFromServer = reader.ReadToEnd(); } Regex regex = new Regex(@"([^\s]+)\s+[^/]+/(.*)", RegexOptions.IgnoreCase); if (regex.IsMatch(responseFromServer)) { if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, "Hashing Files"); } // cleanup dll's with the same exe name var dlls = Directory.GetFiles(Settings.GetRunningDirectory(), "*.dll", SearchOption.TopDirectoryOnly); var exes = Directory.GetFiles(Settings.GetRunningDirectory(), "*.exe", SearchOption.TopDirectoryOnly); List <string> files = new List <string>(); // hash everything MatchCollection matchs = regex.Matches(responseFromServer); for (int i = 0; i < matchs.Count; i++) { string hash = matchs[i].Groups[1].Value.ToString(); string file = matchs[i].Groups[2].Value.ToString(); files.Add(file); } // cleanup unused dlls and exes dlls.ForEach(dll => { try { var result = files.Any(task => Path.Combine(Settings.GetRunningDirectory(), task).ToLower().Equals(dll.ToLower())); if (result == false) { File.Delete(dll); } } catch { } }); exes.ForEach(exe => { try { var result = files.Any(task => Path.Combine(Settings.GetRunningDirectory(), task).ToLower().Equals(exe.ToLower())); if (result == false) { File.Delete(exe); } } catch { } }); // background md5 List <Tuple <string, string, Task <bool> > > tasklist = new List <Tuple <string, string, Task <bool> > >(); for (int i = 0; i < matchs.Count; i++) { string hash = matchs[i].Groups[1].Value.ToString(); string file = matchs[i].Groups[2].Value.ToString(); Task <bool> ismatch = Task <bool> .Factory.StartNew(() => MD5File(file, hash)); tasklist.Add(new Tuple <string, string, Task <bool> >(file, hash, ismatch)); } // get count and wait for all hashing to be done int count = tasklist.Count(a => { a.Item3.Wait(); return(!a.Item3.Result); }); // parallel download ParallelOptions opt = new ParallelOptions() { MaxDegreeOfParallelism = 3 }; int done = 0; Parallel.ForEach(tasklist, opt, task => //foreach (var task in tasklist) { string file = task.Item1; string hash = task.Item2; // check if existing matchs hash task.Item3.Wait(); bool match = task.Item3.Result; if (!match) { done++; log.Info("Newer File " + file); if (frmProgressReporter != null && frmProgressReporter.doWorkArgs.CancelRequested) { frmProgressReporter.doWorkArgs.CancelAcknowledged = true; throw new Exception("User Request"); } // check is we have already downloaded and matchs hash if (!MD5File(file + ".new", hash)) { if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus((int)((done / (double)count) * 100), Strings.Getting + file + "\n" + done + " of " + count + " of total " + tasklist.Count); } string subdir = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar; subdir = subdir.Replace("" + Path.DirectorySeparatorChar + Path.DirectorySeparatorChar, "" + Path.DirectorySeparatorChar); if (baseurl.ToLower().Contains(".zip")) { GetNewFileZip(frmProgressReporter, baseurl, subdir, Path.GetFileName(file)); } else { GetNewFile(frmProgressReporter, baseurl + subdir.Replace('\\', '/'), subdir, Path.GetFileName(file)); } // check the new downloaded file matchs hash if (!MD5File(file + ".new", hash)) { throw new Exception("File downloaded does not match hash: " + file); } } else { log.Info("already got new File " + file); } } else { log.Info("Same File " + file); if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Checking + file); } } }); } }
static void CheckMD5(IProgressReporterDialogue frmProgressReporter, string md5url, string baseurl) { log.InfoFormat("get checksums {0} - base {1}", md5url, baseurl); string responseFromServer = ""; responseFromServer = client.GetStringAsync(md5url).GetAwaiter().GetResult(); File.WriteAllText(Settings.GetRunningDirectory() + "checksums.txt.new", responseFromServer); Regex regex = new Regex(@"([^\s]+)\s+[^/]+/(.*)", RegexOptions.IgnoreCase); if (regex.IsMatch(responseFromServer)) { if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, "Hashing Files"); } // cleanup dll's with the same exe name var dlls = Directory.GetFiles(Settings.GetRunningDirectory(), "*.dll", SearchOption.AllDirectories); var exes = Directory.GetFiles(Settings.GetRunningDirectory(), "*.exe", SearchOption.AllDirectories); List <string> files = new List <string>(); // hash everything MatchCollection matchs = regex.Matches(responseFromServer); for (int i = 0; i < matchs.Count; i++) { string hash = matchs[i].Groups[1].Value.ToString(); string file = matchs[i].Groups[2].Value.ToString(); files.Add(file); } // cleanup unused dlls and exes dlls.ForEach(dll => { try { var result = files.Any(task => Path.Combine(Settings.GetRunningDirectory(), task).ToLower().Equals(dll.ToLower())); if (result == false) { File.Delete(dll); } } catch { } }); exes.ForEach(exe => { try { var result = files.Any(task => Path.Combine(Settings.GetRunningDirectory(), task).ToLower().Equals(exe.ToLower())); if (result == false) { File.Delete(exe); } } catch { } }); // background md5 List <Tuple <string, string, Task <bool> > > tasklist = new List <Tuple <string, string, Task <bool> > >(); for (int i = 0; i < matchs.Count; i++) { string hash = matchs[i].Groups[1].Value.ToString(); string file = matchs[i].Groups[2].Value.ToString(); if (file.ToLower().EndsWith("files.html")) { continue; } Task <bool> ismatch = Task <bool> .Factory.StartNew(() => MD5File(file, hash)); tasklist.Add(new Tuple <string, string, Task <bool> >(file, hash, ismatch)); } // get count and wait for all hashing to be done int count = tasklist.Count(a => { a.Item3.Wait(); return(!a.Item3.GetAwaiter().GetResult()); }); // parallel download ParallelOptions opt = new ParallelOptions() { MaxDegreeOfParallelism = 3 }; tasklist.Sort((a, b) => { if (a == null || b == null) { return(0); } if (a.Item1.ToLower().EndsWith(".exe") && b.Item1.ToLower().EndsWith(".exe")) { return(a.Item1.CompareTo(b.Item1)); } if (a.Item1.ToLower().EndsWith(".exe")) { return(-1); } if (b.Item1.ToLower().EndsWith(".exe")) { return(1); } if (a.Item1.ToLower().EndsWith(".dll") && b.Item1.ToLower().EndsWith(".dll")) { return(a.Item1.CompareTo(b.Item1)); } if (a.Item1.ToLower().EndsWith(".dll")) { return(-1); } if (b.Item1.ToLower().EndsWith(".dll")) { return(1); } return(a.Item1.CompareTo(b.Item1)); }); int done = 0; Parallel.ForEach(tasklist, opt, task => //foreach (var task in tasklist) { string file = task.Item1; string hash = task.Item2; // check if existing matchs hash task.Item3.Wait(); bool match = task.Item3.GetAwaiter().GetResult(); if (!match) { done++; log.Info("Newer File " + file); if (frmProgressReporter != null && frmProgressReporter.doWorkArgs.CancelRequested) { frmProgressReporter.doWorkArgs.CancelAcknowledged = true; throw new Exception("User Request"); } // check is we have already downloaded and matchs hash if (!MD5File(file + ".new", hash)) { if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus((int)((done / (double)count) * 100), Strings.Getting + file + "\n" + done + " of " + count + " of total " + tasklist.Count); } string subdir = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar; subdir = subdir.Replace("" + Path.DirectorySeparatorChar + Path.DirectorySeparatorChar, "" + Path.DirectorySeparatorChar); if (baseurl.ToLower().Contains(".zip")) { GetNewFileZip(frmProgressReporter, baseurl, subdir, Path.GetFileName(file)); } else { GetNewFile(frmProgressReporter, baseurl + subdir.Replace('\\', '/'), subdir, Path.GetFileName(file)); } // check the new downloaded file matchs hash if (!MD5File(file + ".new", hash)) { throw new Exception("File downloaded does not match hash: " + file); } } else { log.Info("already got new File " + file); } } else { log.Info("Same File " + file); if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Checking + file); } } }); } }
static void GetNewFile(IProgressReporterDialogue frmProgressReporter, string baseurl, string subdir, string file) { // create dest dir string dir = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } // get dest path string path = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir + file; Exception fail = null; int attempt = 0; // attempt to get file while (attempt < 2) { // check if user canceled if (frmProgressReporter.doWorkArgs.CancelRequested) { frmProgressReporter.doWorkArgs.CancelAcknowledged = true; throw new Exception("Cancel"); } try { string url = baseurl + file + "?" + new Random().Next(); // Create a request using a URL that can receive a post. WebRequest request = WebRequest.Create(url); if (!String.IsNullOrEmpty(Settings.Instance.UserAgent)) { ((HttpWebRequest)request).UserAgent = Settings.Instance.UserAgent; } log.Info("GetNewFile " + url); // Set the Method property of the request to GET. request.Method = "GET"; // Allow compressed content ((HttpWebRequest)request).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; // tell server we allow compress content request.Headers.Add("Accept-Encoding", "gzip,deflate"); // Get the response. using (WebResponse response = request.GetResponse()) { // Display the status. log.Info(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. Stream dataStream = response.GetResponseStream(); // from head long bytes = response.ContentLength; long contlen = bytes; byte[] buf1 = new byte[4096]; // if the file doesnt exist. just save it inplace string fn = path + ".new"; using (FileStream fs = new FileStream(fn, FileMode.Create)) { DateTime dt = DateTime.Now; log.Debug("ContentLength: " + file + " " + bytes); while (dataStream.CanRead) { try { if (dt.Second != DateTime.Now.Second) { if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus( (int)(((double)(contlen - bytes) / (double)contlen) * 100), Strings.Getting + file + ": " + (((double)(contlen - bytes) / (double)contlen) * 100) .ToString("0.0") + "%"); //+ Math.Abs(bytes) + " bytes"); } dt = DateTime.Now; } } catch { } int len = dataStream.Read(buf1, 0, buf1.Length); if (len == 0) { log.Debug("GetNewFile: 0 byte read " + file); break; } bytes -= len; fs.Write(buf1, 0, len); } log.Info("GetNewFile: " + file + " Done with length: " + fs.Length); fs.Flush(true); fs.Dispose(); } } } catch (Exception ex) { log.Error(ex); fail = ex; attempt++; continue; } // break if we have no exception break; } if (attempt == 2) { throw fail; } }
static void DoUpdateWorker_DoWork(IProgressReporterDialogue sender) { // TODO: Is this the right place? #region Fetch Parameter Meta Data var progressReporterDialogue = ((IProgressReporterDialogue)sender); progressReporterDialogue.UpdateProgressAndStatus(-1, "Getting Updated Parameters"); try { if (MissionPlanner.Utilities.Update.dobeta) { ParameterMetaDataParser.GetParameterInformation(ConfigurationManager.AppSettings["ParameterLocationsBleeding"], String.Format("{0}{1}", Settings.GetUserDataDirectory(), "ParameterMetaDataBackup.xml")); } else { ParameterMetaDataParser.GetParameterInformation(ConfigurationManager.AppSettings["ParameterLocations"], String.Format("{0}{1}", Settings.GetUserDataDirectory(), "ParameterMetaDataBackup.xml")); } } catch (Exception ex) { log.Error(ex.ToString()); CustomMessageBox.Show("Error getting Parameter Information"); } #endregion Fetch Parameter Meta Data progressReporterDialogue.UpdateProgressAndStatus(-1, "Getting Base URL"); try { File.WriteAllText( Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "writetest.txt", "this is a test"); } catch (Exception ex) { log.Info("Write test failed"); throw new Exception("Unable to write to the install directory", ex); } finally { try { File.Delete(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "writetest.txt"); } catch { log.Info("Write test cleanup failed"); } } // check for updates // if (Debugger.IsAttached) { // log.Info("Skipping update test as it appears we are debugging"); } // else { updateCheckMain(progressReporterDialogue); } }
static void DoUpdateWorker_DoWork(IProgressReporterDialogue sender) { // TODO: Is this the right place? #region Fetch Parameter Meta Data var progressReporterDialogue = ((IProgressReporterDialogue)sender); progressReporterDialogue.UpdateProgressAndStatus(-1, "Getting updated parameter documentation"); try { var dns = Dns.GetHostAddresses("github.com"); var dns2 = Dns.GetHostAddresses("raw.githubusercontent.com"); // Go to the GitHub and make .xml file with parameters if (dns.Length != 0) { if (MissionPlanner.Utilities.Update.dobeta) { ParameterMetaDataParser.GetParameterInformation( "https://raw.githubusercontent.com/BogdanPal1/ardupilot/pmucan/ArduPlane/Parameters.cpp", "ParameterMetaData.xml"); } else { ParameterMetaDataParser.GetParameterInformation( "https://raw.githubusercontent.com/BogdanPal1/ardupilot/pmucan/ArduPlane/Parameters.cpp", "ParameterMetaData.xml"); } } } catch (Exception ex) { log.Error(ex.ToString()); CustomMessageBox.Show("Error getting Parameter Information"); } #endregion Fetch Parameter Meta Data progressReporterDialogue.UpdateProgressAndStatus(-1, "Getting Base URL"); try { File.WriteAllText( Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "writetest.txt", "this is a test"); } catch (Exception ex) { log.Info("Write test failed"); throw new Exception("Unable to write to the install directory", ex); } finally { try { File.Delete(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "writetest.txt"); } catch { log.Info("Write test cleanup failed"); } } updateCheckMain(progressReporterDialogue); }
static void CheckMD5(IProgressReporterDialogue frmProgressReporter, string md5url, string baseurl) { L10N.ReplaceMirrorUrl(ref baseurl); string responseFromServer = ""; WebRequest request = WebRequest.Create(md5url); request.Timeout = 10000; // Set the Method property of the request to POST. request.Method = "GET"; // Get the response. // Get the stream containing content returned by the server. // Open the stream using a StreamReader for easy access. using (WebResponse response = request.GetResponse()) using (Stream dataStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(dataStream)) { // Display the status. log.Info(((HttpWebResponse)response).StatusDescription); // Read the content. responseFromServer = reader.ReadToEnd(); } Regex regex = new Regex(@"([^\s]+)\s+[^/]+/(.*)", RegexOptions.IgnoreCase); if (regex.IsMatch(responseFromServer)) { // background md5 List <Tuple <string, string, Task <bool> > > tasklist = new List <Tuple <string, string, Task <bool> > >(); if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, "Hashing Files"); } // hash everything MatchCollection matchs = regex.Matches(responseFromServer); for (int i = 0; i < matchs.Count; i++) { string hash = matchs[i].Groups[1].Value.ToString(); string file = matchs[i].Groups[2].Value.ToString(); Task <bool> ismatch = Task <bool> .Factory.StartNew(() => MD5File(file, hash)); tasklist.Add(new Tuple <string, string, Task <bool> >(file, hash, ismatch)); } // get count and wait for all hashing to be done int count = tasklist.Count(a => { a.Item3.Wait(); return(!a.Item3.Result); }); // parallel download ParallelOptions opt = new ParallelOptions() { MaxDegreeOfParallelism = 3 }; int done = 0; Parallel.ForEach(tasklist, opt, task => //foreach (var task in tasklist) { string file = task.Item1; string hash = task.Item2; // check if existing matchs hash task.Item3.Wait(); bool match = task.Item3.Result; if (!match) { done++; log.Info("Newer File " + file); // check is we have already downloaded and matchs hash if (!MD5File(file + ".new", hash)) { if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus((int)((done / (double)count) * 100), Strings.Getting + file + "\n" + done + " of " + count + " of total " + tasklist.Count); } string subdir = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar; subdir = subdir.Replace("" + Path.DirectorySeparatorChar + Path.DirectorySeparatorChar, "" + Path.DirectorySeparatorChar); if (baseurl.ToLower().Contains(".zip")) { GetNewFileZip(frmProgressReporter, baseurl, subdir, Path.GetFileName(file)); } else { GetNewFile(frmProgressReporter, baseurl + subdir.Replace('\\', '/'), subdir, Path.GetFileName(file)); } // check the new downloaded file matchs hash if (!MD5File(file + ".new", hash)) { throw new Exception("File downloaded does not match hash: " + file); } } else { log.Info("already got new File " + file); } } else { log.Info("Same File " + file); if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Checking + file); } } }); } }
public int WizardValidate() { comport = CMB_port.Text; if (comport == "") { CustomMessageBox.Show(Strings.SelectComport, Strings.ERROR); return(0); } // ensure we are using a comport if (!(MainV2.comPort.BaseStream is SerialPort)) { MainV2.comPort.BaseStream = new SerialPort(); } if (!fwdone) { pdr = new ProgressReporterDialogue(); pdr.DoWork += pdr_DoWork; ThemeManager.ApplyThemeTo(pdr); pdr.RunBackgroundOperationAsync(); if (pdr.doWorkArgs.CancelRequested || !string.IsNullOrEmpty(pdr.doWorkArgs.ErrorMessage)) { return(0); } pdr.Dispose(); } if (MainV2.comPort.BaseStream.IsOpen) { MainV2.comPort.BaseStream.Close(); } // setup for over usb MainV2.comPort.BaseStream.BaudRate = 115200; MainV2.comPort.BaseStream.PortName = comport; MainV2.comPort.Open(true); // try again if (!MainV2.comPort.BaseStream.IsOpen) { CustomMessageBox.Show("Error connecting. Please unplug, plug back in, wait 10 seconds, and click OK", "Try Again"); MainV2.comPort.Open(true); } if (!MainV2.comPort.BaseStream.IsOpen) { return(0); } if (string.IsNullOrEmpty(pdr.doWorkArgs.ErrorMessage)) { if (Wizard.config.ContainsKey("fwtype") && Wizard.config.ContainsKey("fwframe")) { if (Wizard.config["fwtype"].ToString() == "copter" && Wizard.config["fwframe"].ToString() == "tri") { // check if its a tri, and skip the frame type screen return(2); } } if (Wizard.config.ContainsKey("fwtype") && Wizard.config["fwtype"].ToString() == "copter") { // check if its a quad, and show the frame type screen return(1); } if (Wizard.config.ContainsKey("fwtype") && Wizard.config["fwtype"].ToString() == "rover") { // check if its a rover, and show the compass cal screen - skip accel return(3); } else { // skip the frame type screen as its not valid for anythine else return(2); } } return(0); }
void pdr_DoWork(IProgressReporterDialogue sender) { // upload fw Utilities.Firmware fw = new Utilities.Firmware(); fw.Progress += fw_Progress; string firmwareurl = ""; if (usebeta) { firmwareurl = "https://raw.github.com/ardupilot/binary/master/dev/firmware2.xml"; } List <Utilities.Firmware.software> swlist = fw.getFWList(firmwareurl); if (swlist.Count == 0) { sender.doWorkArgs.ErrorMessage = "Error getting Firmware list"; return; } switch (Wizard.config["fwtype"].ToString()) { case "copter": // fwframe is already defined for copter break; default: // mirror fwtype to fwframe Wizard.config["fwframe"] = Wizard.config["fwtype"].ToString(); break; } string target = Wizard.config["fwframe"].ToString(); if (sender.doWorkArgs.CancelRequested) { sender.doWorkArgs.CancelAcknowledged = true; return; } foreach (var sw in swlist) { foreach (KeyValuePair <string, string> parturl in fwmap) { if (target.ToLower() == parturl.Key.ToLower() && sw.url2560.ToLower().Contains(parturl.Value.ToString().ToLower())) { try { fwdone = fw.update(comport, sw, ""); //fwdone = true; } catch { } if (fwdone == false) { sender.doWorkArgs.ErrorMessage = "Error uploading Firmware"; return; } break; } } if (fwdone) { break; } } if (sender.doWorkArgs.CancelRequested) { sender.doWorkArgs.CancelAcknowledged = true; return; } if (!fwdone) { sender.doWorkArgs.ErrorMessage = "Error with Firmware"; return; } return; }
static void CheckMD5(IProgressReporterDialogue frmProgressReporter, string md5url, string baseurl) { log.InfoFormat("get checksums {0} - base {1}", md5url, baseurl); string responseFromServer = ""; responseFromServer = client.GetStringAsync(md5url).GetAwaiter().GetResult(); File.WriteAllText(Settings.GetRunningDirectory() + "checksums.txt.new", responseFromServer); Regex regex = new Regex(@"([^\s]+)\s+[^/]+/(.*)", RegexOptions.IgnoreCase); if (regex.IsMatch(responseFromServer)) { if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, "Hashing Files"); } // cleanup dll's with the same exe name var dlls = Directory.GetFiles(Settings.GetRunningDirectory(), "*.dll", SearchOption.AllDirectories); var exes = Directory.GetFiles(Settings.GetRunningDirectory(), "*.exe", SearchOption.AllDirectories); List <string> files = new List <string>(); // hash everything MatchCollection matchs = regex.Matches(responseFromServer); for (int i = 0; i < matchs.Count; i++) { string hash = matchs[i].Groups[1].Value.ToString(); string file = matchs[i].Groups[2].Value.ToString(); files.Add(file); } // cleanup unused dlls and exes dlls.ForEach(dll => { try { var result = files.Any(task => Path.Combine(Settings.GetRunningDirectory(), task).ToLower().Equals(dll.ToLower())); if (result == false) { File.Delete(dll); } } catch { } }); exes.ForEach(exe => { try { var result = files.Any(task => Path.Combine(Settings.GetRunningDirectory(), task).ToLower().Equals(exe.ToLower())); if (result == false) { File.Delete(exe); } } catch { } }); // background md5 List <Tuple <string, string, Task <bool> > > tasklist = new List <Tuple <string, string, Task <bool> > >(); for (int i = 0; i < matchs.Count; i++) { string hash = matchs[i].Groups[1].Value.ToString().Trim(); string file = matchs[i].Groups[2].Value.ToString().Trim(); if (file.ToLower().EndsWith("files.html")) { continue; } Task <bool> ismatch = Task <bool> .Factory.StartNew(() => MD5File(file, hash)); tasklist.Add(new Tuple <string, string, Task <bool> >(file, hash, ismatch)); } // get count and wait for all hashing to be done int count = tasklist.Count(a => { a.Item3.Wait(); return(!a.Item3.GetAwaiter().GetResult()); }); // parallel download ParallelOptions opt = new ParallelOptions() { MaxDegreeOfParallelism = 3 }; tasklist.Sort((a, b) => { if (a == null || b == null) { return(0); } if (a.Item1.ToLower().EndsWith(".exe") && b.Item1.ToLower().EndsWith(".exe")) { return(a.Item1.CompareTo(b.Item1)); } if (a.Item1.ToLower().EndsWith(".exe")) { return(-1); } if (b.Item1.ToLower().EndsWith(".exe")) { return(1); } if (a.Item1.ToLower().EndsWith(".dll") && b.Item1.ToLower().EndsWith(".dll")) { return(a.Item1.CompareTo(b.Item1)); } if (a.Item1.ToLower().EndsWith(".dll")) { return(-1); } if (b.Item1.ToLower().EndsWith(".dll")) { return(1); } return(a.Item1.CompareTo(b.Item1)); }); /* * if (frmProgressReporter != null) * frmProgressReporter.UpdateProgressAndStatus(-1, "Downloading parts"); * * // start download * if (baseurl.ToLower().Contains(".zip")) * { * List<(int, int)> ranges = new List<(int, int)>(); * * using (DownloadStream ds = new DownloadStream(baseurl)) * using (ZipArchive zip = new ZipArchive(ds)) * { * FieldInfo fieldInfo = typeof(ZipArchiveEntry).GetField("_offsetOfLocalHeader", BindingFlags.NonPublic | BindingFlags.Instance); * var extents = zip.Entries.Select(e => * { * var _offsetOfLocalHeader = (long)fieldInfo.GetValue(e); * return (e.FullName, _offsetOfLocalHeader); * }).OrderBy(a => a._offsetOfLocalHeader); * * tasklist.ForEach(task => { * * task.Item3.Wait(); * bool match = task.Item3.GetAwaiter().GetResult(); * * if (!match) * { * extents.ForEach(entry1 => * { * var fn = entry1.FullName; * * var diskfn = task.Item1; * * if (diskfn.EndsWith(fn)) * { * var next = ds.Length; * zip.Entries.ForEach(entry2 => { * var _offsetOfLocalHeader2 = (long)fieldInfo.GetValue(entry2); * if (_offsetOfLocalHeader2 > entry1._offsetOfLocalHeader) * next = Math.Min(_offsetOfLocalHeader2, next); * }); * * ranges.Add(((int)entry1._offsetOfLocalHeader, (int)(next))); * } * }); * } * }); * * ranges = ranges.SimplifyIntervals().ToList(); * ranges.ForEach(range => { * ds.chunksize = range.Item2 - range.Item1; * ds.getAllData(range.Item1, range.Item2); * }); * * } * } */ int done = 0; Parallel.ForEach(tasklist, opt, task => //foreach (var task in tasklist) { string file = task.Item1; string hash = task.Item2; // check if existing matchs hash task.Item3.Wait(); bool match = task.Item3.GetAwaiter().GetResult(); if (!match) { done++; log.Info("Newer File " + file); if (frmProgressReporter != null && frmProgressReporter.doWorkArgs.CancelRequested) { frmProgressReporter.doWorkArgs.CancelAcknowledged = true; throw new Exception("User Request"); } // check is we have already downloaded and matchs hash if (!MD5File(file + ".new", hash)) { if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus((int)((done / (double)count) * 100), Strings.Getting + file + "\n" + done + " of " + count + " of total " + tasklist.Count); } string subdir = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar; subdir = subdir.Replace("" + Path.DirectorySeparatorChar + Path.DirectorySeparatorChar, "" + Path.DirectorySeparatorChar); if (baseurl.ToLower().Contains(".zip")) { GetNewFileZip(frmProgressReporter, baseurl, subdir, Path.GetFileName(file)); } else { GetNewFile(frmProgressReporter, baseurl + subdir.Replace('\\', '/'), subdir, Path.GetFileName(file)); } // check the new downloaded file matchs hash if (!MD5File(file + ".new", hash)) { throw new Exception("File downloaded does not match hash: " + file); } } else { log.Info("already got new File " + file); } } else { log.Info("Same File " + file); if (frmProgressReporter != null) { frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Checking + file); } } }); } }
void ConvertData(IProgressReporterDialogue sender) { string inFilePath = TXT_InData.Text; string[] lines = new string[1]; if (File.Exists(inFilePath)) { if (formProgressReporter != null) { this.formProgressReporter.UpdateProgressAndStatus(1, "Reading input file."); } try { lines = File.ReadAllLines(inFilePath); } catch (Exception e) { if (formProgressReporter != null) { formProgressReporter.doWorkArgs.ErrorMessage = e.Message; } return; } } else { if (formProgressReporter != null) { formProgressReporter.doWorkArgs.ErrorMessage = "Input file don't exist."; } return; } List <Tuple <string, double, double> > timeLatLonList = new List <Tuple <string, double, double> >(); List <double> depthList = new List <double>(); bool dbt_OK = false; bool gga_OK = false; double lat = 0; double lon = 0; string time = ""; double depth = 0; int progressIndex = 0; foreach (string line in lines) { if (progressIndex % 200 == 0) { Thread.Sleep(1); } progressIndex++; //Si el usuario cancela el dialogo if (formProgressReporter != null && formProgressReporter.doWorkArgs.CancelRequested) { formProgressReporter.doWorkArgs.CancelAcknowledged = true; formProgressReporter.doWorkArgs.ErrorMessage = "User Canceled."; return; } //Reportar progreso if (formProgressReporter != null) { this.formProgressReporter.UpdateProgressAndStatus((progressIndex * 70) / lines.Count(), "Extracting NMEA sentences."); } if (!string.IsNullOrEmpty(line)) { if (line.Contains("$GPDBT")) { string[] sp = line.Split(','); depth = double.Parse(sp[3], CultureInfo.InvariantCulture); dbt_OK = true; } if (line.Contains("$GPGGA") || line.Contains("$GNGGA")) { string[] sp = line.Split(','); time = sp[1]; lat = ToDecimalDegrees(sp[2] + sp[3]); lon = ToDecimalDegrees(sp[4] + sp[5]); gga_OK = true; } continue; } //Cuando se llega a este punto, se ha completado un bloque. if (dbt_OK && gga_OK) { timeLatLonList.Add(time, lat, lon); depthList.Add(depth); } dbt_OK = false; gga_OK = false; } //Crear el Filtro - orden 30, determinado experimental MathNet.Filtering.OnlineFilter filter = MathNet.Filtering.OnlineFilter.CreateDenoise(30); //Reportar progreso if (formProgressReporter != null) { this.formProgressReporter.UpdateProgressAndStatus(80, "Applying filtering forward-backward."); } Thread.Sleep(1000); //Filtrar Forward y Backward double[] depthForward = filter.ProcessSamples(depthList.ToArray()); double[] depthBackward = filter.ProcessSamples(depthForward.Reverse().ToArray()); depthBackward = depthBackward.Reverse().ToArray(); //Reportar progreso if (formProgressReporter != null) { this.formProgressReporter.UpdateProgressAndStatus(85, "Preparing text structure."); } Thread.Sleep(1000); //Crear la lista string Lat,Lon,Depth List <string> listOut = new List <string>(); NumberFormatInfo nfi = new NumberFormatInfo(); NumberFormatInfo nfi2 = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; nfi2.NumberDecimalSeparator = "."; nfi2.NumberDecimalDigits = 1; for (int i = 0; i < timeLatLonList.Count(); i++) { DateTime dateTime = DateTime.ParseExact(timeLatLonList[i].Item1, "HHmmss.ff", null); string st = dateTime.TimeOfDay.TotalSeconds.ToString(nfi2); listOut.Add(st + "," + // Time timeLatLonList[i].Item2.ToString(nfi) + "," + // Lat timeLatLonList[i].Item3.ToString(nfi) + "," + // Lon depthList[i].ToString(nfi) + "," + depthBackward[i].ToString(nfi)); // Depth } //Crear la lista string fotmato HYPACK List <string> listOutHYPACK = new List <string>(); listOutHYPACK.Add("FTP NEW 2"); listOutHYPACK.Add("TND 12:00:26 05/01/2019"); listOutHYPACK.Add("DEV 0 32784 \"ECHOSOUNDER\" 0"); listOutHYPACK.Add("DEV 1 32837 \"GPS\" 57348"); listOutHYPACK.Add("USR \"GEOSUPPORT\" \"HYPACK\""); listOutHYPACK.Add("EOH"); for (int i = 0; i < timeLatLonList.Count(); i++) { //EC2 0 1.0 2.8 0.000 //POS 1 1.1 307916.529 6461349.538 double[] east_north = new PointLatLngAlt(timeLatLonList[i].Item2, timeLatLonList[i].Item3).ToUTM(); DateTime dateTime = DateTime.ParseExact(timeLatLonList[i].Item1, "HHmmss.ff", null); string st = dateTime.TimeOfDay.TotalSeconds.ToString(nfi2); listOutHYPACK.Add("EC2 0 " + st + " " + depthBackward[i].ToString(nfi) + " 0.0"); listOutHYPACK.Add("POS 1 " + st + " " + east_north[0].ToString(nfi) + " " + east_north[1].ToString(nfi)); } //Reportar progreso if (formProgressReporter != null) { this.formProgressReporter.UpdateProgressAndStatus(90, "Writing the output file."); } Thread.Sleep(1000); //Escribir el archivo XYZ final try { File.WriteAllLines(TXT_OutData.Text + "\\" + Path.GetFileNameWithoutExtension(TXT_InData.Text) + ".XYZ", listOut.ToArray()); } catch (Exception e) { if (formProgressReporter != null) { formProgressReporter.doWorkArgs.ErrorMessage = e.Message; } return; } //Escribir el archivo RAW final try { File.WriteAllLines(TXT_OutData.Text + "\\" + Path.GetFileNameWithoutExtension(TXT_InData.Text) + ".RAW", listOutHYPACK.ToArray()); } catch (Exception e) { if (formProgressReporter != null) { formProgressReporter.doWorkArgs.ErrorMessage = e.Message; } return; } //Reportar progreso if (formProgressReporter != null) { this.formProgressReporter.UpdateProgressAndStatus(100, "Done."); } Thread.Sleep(500); }