public static GetRunningDirectory ( ) : string | ||
return | string |
public static void Reload() { string paramMetaDataXMLFileName = String.Format("{0}{1}", Settings.GetUserDataDirectory(), "ParameterMetaData.xml"); string paramMetaDataXMLFileNameBackup = String.Format("{0}{1}{2}", Settings.GetRunningDirectory(), Path.DirectorySeparatorChar, "ParameterMetaDataBackup.xml"); try { log.Debug(paramMetaDataXMLFileName); if (File.Exists(paramMetaDataXMLFileName)) { _parameterMetaDataXML = XDocument.Load(paramMetaDataXMLFileName); } } catch (Exception ex) { log.Error(ex); } try { log.Debug(paramMetaDataXMLFileNameBackup); // error loading the good file, load the backup if (File.Exists(paramMetaDataXMLFileNameBackup) && _parameterMetaDataXML == null) { _parameterMetaDataXML = XDocument.Load(paramMetaDataXMLFileNameBackup); Console.WriteLine("Using backup param data"); } } catch { } }
public static void Reload() { string paramMetaDataXMLFileName = String.Format("{0}{1}", Settings.GetUserDataDirectory(), ConfigurationManager.AppSettings["ParameterMetaDataXMLFileName"]); string paramMetaDataXMLFileNameBackup = String.Format("{0}{1}{2}", Settings.GetRunningDirectory(), Path.DirectorySeparatorChar, ConfigurationManager.AppSettings["ParameterMetaDataXMLFileNameBackup"]); try { if (File.Exists(paramMetaDataXMLFileName)) { _parameterMetaDataXML = XDocument.Load(paramMetaDataXMLFileName); } } catch { } try { // error loading the good file, load the backup if (File.Exists(paramMetaDataXMLFileNameBackup) && _parameterMetaDataXML == null) { _parameterMetaDataXML = XDocument.Load(paramMetaDataXMLFileNameBackup); Console.WriteLine("Using backup param data"); } } catch { } }
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.Result); }); // 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.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 = ""; 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)) { 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); } } }); } }
protected override void OnCreate(Bundle savedInstanceState) { Current = this; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException; TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; SetSupportActionBar((Toolbar)FindViewById(ToolbarResource)); this.Window.AddFlags(WindowManagerFlags.Fullscreen | WindowManagerFlags.TurnScreenOn | WindowManagerFlags.HardwareAccelerated); base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); Settings.CustomUserDataDirectory = Application.Context.GetExternalFilesDir(null).ToString(); Log.Info("MP", "Settings.CustomUserDataDirectory " + Settings.CustomUserDataDirectory); WinForms.BundledPath = Application.Context.ApplicationInfo.NativeLibraryDir; Log.Info("MP", "WinForms.BundledPath " + WinForms.BundledPath); Test.BlueToothDevice = new BTDevice(); Test.UsbDevices = new USBDevices(); Test.Radio = new Radio(); Test.GPS = new GPS(); //ConfigFirmwareManifest.ExtraDeviceInfo /* * var intent = new global::Android.Content.Intent(Intent.ActionOpenDocumentTree); * * intent.AddFlags(ActivityFlags.GrantWriteUriPermission | ActivityFlags.GrantReadUriPermission); * intent.PutExtra(DocumentsContract.ExtraInitialUri, "Mission Planner"); * * StartActivityForResult(intent, 1); */ UserDialogs.Init(this); AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser; { if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) != (int)Permission.Granted || ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted || ContextCompat.CheckSelfPermission(this, Manifest.Permission.Bluetooth) != (int)Permission.Granted) { ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessFineLocation, Manifest.Permission.LocationHardware, Manifest.Permission.WriteExternalStorage, Manifest.Permission.ReadExternalStorage, Manifest.Permission.Bluetooth }, 1); } while (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted) { Thread.Sleep(1000); var text = "Checking Permissions - " + DateTime.Now.ToString("T"); DoToastMessage(text); } } try { // print some info var pm = this.PackageManager; var name = this.PackageName; var pi = pm.GetPackageInfo(name, PackageInfoFlags.Activities); Console.WriteLine("pi.ApplicationInfo.DataDir " + pi?.ApplicationInfo?.DataDir); Console.WriteLine("pi.ApplicationInfo.NativeLibraryDir " + pi?.ApplicationInfo?.NativeLibraryDir); // api level 24 - android 7 Console.WriteLine("pi.ApplicationInfo.DeviceProtectedDataDir " + pi?.ApplicationInfo?.DeviceProtectedDataDir); } catch {} global::Xamarin.Forms.Forms.Init(this, savedInstanceState); { // clean start, see if it was an intent/usb attach if (savedInstanceState == null) { DoToastMessage("Init Saved State"); proxyIfUsbAttached(this.Intent); } } GC.Collect(); Task.Run(() => { var gdaldir = Settings.GetRunningDirectory() + "gdalimages"; Directory.CreateDirectory(gdaldir); MissionPlanner.Utilities.GDAL.GDALBase = new GDAL.GDAL(); GDAL.GDAL.ScanDirectory(gdaldir); GMap.NET.MapProviders.GMapProviders.List.Add(GDAL.GDALProvider.Instance); }); DoToastMessage("Launch App"); LoadApplication(new App()); }
public static void readmavgraphsxml() { if (readmavgraphsxml_runonce) { return; } readmavgraphsxml_runonce = true; List <graphitem> items = new List <graphitem>(); log.Info("readmavgraphsxml from " + Settings.GetRunningDirectory() + Path.DirectorySeparatorChar + "graphs"); var files = Directory.GetFiles(Settings.GetRunningDirectory() + Path.DirectorySeparatorChar + "graphs", "*.xml"); foreach (var file in files) { try { using ( XmlReader reader = XmlReader.Create(file)) { while (reader.Read()) { if (reader.ReadToFollowing("graph")) { graphitem newGraphitem = new graphitem(); for (int a = 0; a < reader.AttributeCount; a++) { reader.MoveToAttribute(a); if (reader.Name.ToLower() == "name") { newGraphitem.name = reader.Value + " " + Path.GetFileNameWithoutExtension(file); } } reader.MoveToElement(); XmlReader inner = reader.ReadSubtree(); while (inner.Read()) { if (inner.IsStartElement()) { if (inner.Name.ToLower() == "expression") { newGraphitem.expressions.Add(inner.ReadString().Trim()); } else if (inner.Name.ToLower() == "description") { newGraphitem.description = inner.ReadString().Trim(); } } } processGraphItem(newGraphitem); items.Add(newGraphitem); } } } } catch (Exception ex) { log.Error(ex); } } }
public static void Clean() { Process pr = new Process(); pr.StartInfo = new ProcessStartInfo("pnputil", "/enum-drivers") { RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false }; pr.Start(); var so = pr.StandardOutput.ReadToEndAsync(); var se = pr.StandardError.ReadToEndAsync(); /* * Published Name: oem62.inf * Original Name: lpro564s.inf * Provider Name: Logitech * Class Name: Sound, video and game controllers * Class GUID: {4d36e96c-e325-11ce-bfc1-08002be10318} * Driver Version: 10/22/2012 13.80.853.0 * Signer Name: Microsoft Windows Hardware Compatibility Publisher */ var pun = Regex.Matches(so.Result, @"Published Name:\s+(.+)"); var orn = Regex.Matches(so.Result, @"Original Name:\s+(.+)"); var prn = Regex.Matches(so.Result, @"Provider Name:\s+(.+)"); var cln = Regex.Matches(so.Result, @"Class Name:\s+(.+)"); var clg = Regex.Matches(so.Result, @"Class GUID:\s+(.+)"); var drv = Regex.Matches(so.Result, @"Driver Version:\s+(.+)"); var sin = Regex.Matches(so.Result, @"Signer Name:\s+(.+)"); for (int i = 0; i < pun.Count; i++) { Console.WriteLine("{0} {1} {2} {3} {4}", pun[i].Groups[1].Value.Trim(), orn[i].Groups[1].Value.Trim(), prn[i].Groups[1].Value.Trim(), cln[i].Groups[1].Value.Trim(), sin[i].Groups[1].Value.Trim()); ProcessStartInfo si = new ProcessStartInfo("pnputil", "-f -d " + pun[i].Groups[1].Value.Trim()) { Verb = "runas" }; if (sin[i].Groups[1].Value.Trim() == "Michael Oborne") { var pr2 = Process.Start(si); continue; } if (prn[i].Groups[1].Value.Trim() == "3D Robotics" || prn[i].Groups[1].Value.Trim() == "Laser Navigation" || prn[i].Groups[1].Value.Trim() == "Hex Technology Limited") { Process.Start(si); continue; } } var driversdir = Settings.GetRunningDirectory() + Path.DirectorySeparatorChar + "drivers"; var infs = Directory.GetFiles(driversdir, "*.inf"); foreach (var inf in infs) { ProcessStartInfo si = new ProcessStartInfo(driversdir + Path.DirectorySeparatorChar + "DPInstx64.exe", @"/u """ + inf + @"""/d /s") { Verb = "runas" }; } }
void ContinueInit() { var list = Application.Context.GetExternalFilesDirs(null); list.ForEach(a => Log.Info("MP", "External dir option: " + a.AbsolutePath)); var list2 = Application.Context.GetExternalFilesDirs(Environment.DirectoryDownloads); list2.ForEach(a => Log.Info("MP", "External DirectoryDownloads option: " + a.AbsolutePath)); var pref = this.GetSharedPreferences("pref", FileCreationMode.Private); Settings.CustomUserDataDirectory = Application.Context.GetExternalFilesDir(null).ToString(); //pref.GetString("Directory", Application.Context.GetExternalFilesDir(null).ToString()); Log.Info("MP", "Settings.CustomUserDataDirectory " + Settings.CustomUserDataDirectory); try { WinForms.Android = true; WinForms.BundledPath = Application.Context.ApplicationInfo.NativeLibraryDir; GStreamer.BundledPath = Application.Context.ApplicationInfo.NativeLibraryDir; GStreamer.Android = true; } catch { } Log.Info("MP", "WinForms.BundledPath " + WinForms.BundledPath); try { JavaSystem.LoadLibrary("gstreamer_android"); Org.Freedesktop.Gstreamer.GStreamer.Init(this.ApplicationContext); } catch (Exception ex) { Log.Error("MP", ex.ToString()); } Test.BlueToothDevice = new BTDevice(); Test.UsbDevices = new USBDevices(); Test.Radio = new Radio(); Test.GPS = new GPS(); Test.SystemInfo = new SystemInfo(); androidvideo = new AndroidVideo(); //disable //androidvideo.Start(); AndroidVideo.onNewImage += (e, o) => { WinForms.SetHUDbg(o); }; //ConfigFirmwareManifest.ExtraDeviceInfo /* * var intent = new global::Android.Content.Intent(Intent.ActionOpenDocumentTree); * * intent.AddFlags(ActivityFlags.GrantWriteUriPermission | ActivityFlags.GrantReadUriPermission); * intent.PutExtra(DocumentsContract.ExtraInitialUri, "Mission Planner"); * * StartActivityForResult(intent, 1); */ UserDialogs.Init(this); AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser; { if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) != (int)Permission.Granted || ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted || ContextCompat.CheckSelfPermission(this, Manifest.Permission.Bluetooth) != (int)Permission.Granted) { ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessFineLocation, Manifest.Permission.LocationHardware, Manifest.Permission.WriteExternalStorage, Manifest.Permission.ReadExternalStorage, Manifest.Permission.Bluetooth }, 1); } while (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted) { Thread.Sleep(1000); var text = "Checking Permissions - " + DateTime.Now.ToString("T"); DoToastMessage(text); } } try { // print some info var pm = this.PackageManager; var name = this.PackageName; var pi = pm.GetPackageInfo(name, PackageInfoFlags.Activities); Console.WriteLine("pi.ApplicationInfo.DataDir " + pi?.ApplicationInfo?.DataDir); Console.WriteLine("pi.ApplicationInfo.NativeLibraryDir " + pi?.ApplicationInfo?.NativeLibraryDir); // api level 24 - android 7 Console.WriteLine("pi.ApplicationInfo.DeviceProtectedDataDir " + pi?.ApplicationInfo?.DeviceProtectedDataDir); } catch {} { // clean start, see if it was an intent/usb attach //if (savedInstanceState == null) { DoToastMessage("Init Saved State"); proxyIfUsbAttached(this.Intent); Console.WriteLine(this.Intent?.Action); Console.WriteLine(this.Intent?.Categories); Console.WriteLine(this.Intent?.Data); Console.WriteLine(this.Intent?.DataString); Console.WriteLine(this.Intent?.Type); } } GC.Collect(); try { Java.Lang.JavaSystem.LoadLibrary("gdal"); Java.Lang.JavaSystem.LoadLibrary("gdalalljni"); Java.Lang.JavaSystem.LoadLibrary("gdalwrap"); } catch (System.Exception ex) { Log.Error("GDAL", ex.ToString()); } Task.Run(() => { var gdaldir = Settings.GetRunningDirectory() + "gdalimages"; Directory.CreateDirectory(gdaldir); MissionPlanner.Utilities.GDAL.GDALBase = new GDAL.GDAL(); GDAL.GDAL.ScanDirectory(gdaldir); GMap.NET.MapProviders.GMapProviders.List.Add(GDAL.GDALProvider.Instance); }); DoToastMessage("Launch App"); LoadApplication(new App()); }
protected override void OnCreate(Bundle savedInstanceState) { Current = this; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException; TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; SetSupportActionBar((Toolbar)FindViewById(ToolbarResource)); this.Window.AddFlags(WindowManagerFlags.Fullscreen | WindowManagerFlags.TurnScreenOn | WindowManagerFlags.HardwareAccelerated); base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); Settings.CustomUserDataDirectory = Application.Context.GetExternalFilesDir(null).ToString(); Log.Info("MP", "Settings.CustomUserDataDirectory " + Settings.CustomUserDataDirectory); WinForms.BundledPath = Application.Context.ApplicationInfo.NativeLibraryDir; Log.Info("MP", "WinForms.BundledPath " + WinForms.BundledPath); Test.BlueToothDevice = new BTDevice(); Test.UsbDevices = new USBDevices(); Test.Radio = new Radio(); //ConfigFirmwareManifest.ExtraDeviceInfo /* * var intent = new global::Android.Content.Intent(Intent.ActionOpenDocumentTree); * * intent.AddFlags(ActivityFlags.GrantWriteUriPermission | ActivityFlags.GrantReadUriPermission); * intent.PutExtra(DocumentsContract.ExtraInitialUri, "Mission Planner"); * * StartActivityForResult(intent, 1); */ UserDialogs.Init(this); AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser; { if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) != (int)Permission.Granted || ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted || ContextCompat.CheckSelfPermission(this, Manifest.Permission.Bluetooth) != (int)Permission.Granted) { ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessFineLocation, Manifest.Permission.LocationHardware, Manifest.Permission.WriteExternalStorage, Manifest.Permission.ReadExternalStorage, Manifest.Permission.Bluetooth }, 1); } while (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted) { Thread.Sleep(1000); var text = "Checking Permissions - " + DateTime.Now.ToString("T"); DoToastMessage(text); } } try { // print some info var pm = this.PackageManager; var name = this.PackageName; var pi = pm.GetPackageInfo(name, PackageInfoFlags.Activities); Console.WriteLine("pi.ApplicationInfo.DataDir " + pi?.ApplicationInfo?.DataDir); Console.WriteLine("pi.ApplicationInfo.NativeLibraryDir " + pi?.ApplicationInfo?.NativeLibraryDir); // api level 24 - android 7 Console.WriteLine("pi.ApplicationInfo.DeviceProtectedDataDir " + pi?.ApplicationInfo?.DeviceProtectedDataDir); } catch {} { DoToastMessage("Staging Files"); try { // nofly dir Directory.CreateDirectory(Settings.GetUserDataDirectory() + Path.DirectorySeparatorChar + "NoFly"); // restore assets Directory.CreateDirectory(Settings.GetUserDataDirectory()); File.WriteAllText(Settings.GetUserDataDirectory() + Path.DirectorySeparatorChar + "airports.csv", new StreamReader(Resources.OpenRawResource( Xamarin.Droid.Resource.Raw.airports)).ReadToEnd()); File.WriteAllText( Settings.GetUserDataDirectory() + Path.DirectorySeparatorChar + "BurntKermit.mpsystheme", new StreamReader( Resources.OpenRawResource( Droid.Resource.Raw.BurntKermit)).ReadToEnd()); File.WriteAllText( Settings.GetUserDataDirectory() + Path.DirectorySeparatorChar + "ParameterMetaData.xml", new StreamReader( Resources.OpenRawResource( Droid.Resource.Raw.ParameterMetaDataBackup)).ReadToEnd()); File.WriteAllText( Settings.GetUserDataDirectory() + Path.DirectorySeparatorChar + "camerasBuiltin.xml", new StreamReader( Resources.OpenRawResource( Droid.Resource.Raw.camerasBuiltin)).ReadToEnd()); File.WriteAllText( Settings.GetUserDataDirectory() + Path.DirectorySeparatorChar + "checklistDefault.xml", new StreamReader( Resources.OpenRawResource( Droid.Resource.Raw.checklistDefault)).ReadToEnd()); File.WriteAllText( Settings.GetUserDataDirectory() + Path.DirectorySeparatorChar + "mavcmd.xml", new StreamReader( Resources.OpenRawResource( Droid.Resource.Raw.mavcmd)).ReadToEnd()); { var pluginsdir = Settings.GetRunningDirectory() + "plugins"; Directory.CreateDirectory(pluginsdir); string[] files = new[] { "example2menu", "example3fencedist", "example4herelink", "example5latencytracker", "example6mapicondesc", "example7canrtcm", "example8modechange", "example9hudonoff", "examplewatchbutton", "generator", "InitialParamsCalculator" }; foreach (var file in files) { try { var id = (int)typeof(Droid.Resource.Raw) .GetField(file) .GetValue(null); var filename = pluginsdir + Path.DirectorySeparatorChar + file + ".cs"; if (File.Exists(filename)) { File.Delete(filename); } /* * File.WriteAllText(filename * , * new StreamReader( * Resources.OpenRawResource(id)).ReadToEnd()); */ } catch { } } } { var graphsdir = Settings.GetRunningDirectory() + "graphs"; Directory.CreateDirectory(graphsdir); string[] files = new[] { "ekf3Graphs", "ekfGraphs", "mavgraphs", "mavgraphs2", "mavgraphsMP" }; foreach (var file in files) { try { var id = (int)typeof(Droid.Resource.Raw) .GetField(file) .GetValue(null); File.WriteAllText( graphsdir + Path.DirectorySeparatorChar + file + ".xml", new StreamReader( Resources.OpenRawResource(id)).ReadToEnd()); } catch { } } } } catch (Exception ex) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Error"); alert.SetMessage("Failed to save to storage " + ex.ToString()); alert.SetNeutralButton("OK", (senderAlert, args) => { }); Dialog dialog = alert.Create(); dialog.Show(); } } global::Xamarin.Forms.Forms.Init(this, savedInstanceState); { // clean start, see if it was an intent/usb attach if (savedInstanceState == null) { DoToastMessage("Init Saved State"); proxyIfUsbAttached(this.Intent); } } GC.Collect(); Task.Run(() => { var gdaldir = Settings.GetRunningDirectory() + "gdalimages"; Directory.CreateDirectory(gdaldir); MissionPlanner.Utilities.GDAL.GDALBase = new GDAL.GDAL(); GDAL.GDAL.ScanDirectory(gdaldir); GMap.NET.MapProviders.GMapProviders.List.Add(GDAL.GDALProvider.Instance); }); DoToastMessage("Launch App"); LoadApplication(new App()); }
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); } } }); } }