Example #1
0
        public static void updateCheckMain(ProgressReporterDialogue frmProgressReporter)
        {

            var t = Type.GetType("Mono.Runtime");
            MONO = (t != null);

            try
            {
                if (dobeta)
                {
                    CheckMD5(frmProgressReporter, ConfigurationManager.AppSettings["BetaUpdateLocationMD5"].ToString());
                }
                else
                {
                    CheckMD5(frmProgressReporter, ConfigurationManager.AppSettings["UpdateLocationMD5"].ToString());
                }

                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");

                frmProgressReporter.BeginInvoke((Action) delegate {
                Application.Exit();
                });
            }
            catch (Exception ex)
            {
                log.Error("Update Failed", ex);
                CustomMessageBox.Show("Update Failed " + ex.Message);
            }
        }
Example #2
0
        void doUI(string inputfn, string outputfn, bool showui = true)
        {
            this.inputfn = inputfn;
            this.outputfn = outputfn;

            prd = new ProgressReporterDialogue();

            prd.DoWork += prd_DoWork;

            prd.UpdateProgressAndStatus(-1, Strings.Converting_bin_to_log);

            this.convertstatus += BinaryLog_convertstatus;

            ThemeManager.ApplyThemeTo(prd);

            prd.RunBackgroundOperationAsync();

            prd.Dispose();
        }
Example #3
0
        private async Task UploadFile(string ofdFileName)
        {
            toolStripStatusLabel1.Text = "Upload " + Path.GetFileName(ofdFileName);
            var fn = treeView1.SelectedNode.FullPath + "/" + Path.GetFileName(ofdFileName);
            ProgressReporterDialogue prd    = new ProgressReporterDialogue();
            CancellationTokenSource  cancel = new CancellationTokenSource();

            prd.doWorkArgs.CancelRequestChanged += (o, args) =>
            {
                prd.doWorkArgs.ErrorMessage = "User Cancel";
                cancel.Cancel();
                _mavftp.kCmdResetSessions();
            };
            prd.doWorkArgs.ForceExit = true;

            _mavftp.Progress += i => prd.UpdateProgressAndStatus(i, toolStripStatusLabel1.Text);

            prd.DoWork += (iprd) =>
            {
                _mavftp.UploadFile(fn, ofdFileName);
                if (cancel.IsCancellationRequested)
                {
                    iprd.doWorkArgs.CancelAcknowledged = true;
                    iprd.doWorkArgs.CancelRequested    = true;
                    return;
                }
                uint crc = 0;
                _mavftp.kCmdCalcFileCRC32(fn, ref crc);
                var crc32a = MAVFtp.crc_crc32(0, File.ReadAllBytes(ofdFileName));
                if (crc32a != crc)
                {
                    throw new BadCrcException();
                }
            };
            prd.RunBackgroundOperationAsync();
            toolStripStatusLabel1.Text = "Ready";
        }
Example #4
0
        static void CheckMD5(ProgressReporterDialogue frmProgressReporter, string url)
        {
            var baseurl = ConfigurationManager.AppSettings["UpdateLocation"];

            if (dobeta)
            {
                baseurl = ConfigurationManager.AppSettings["BetaUpdateLocation"];
            }

            WebRequest request = WebRequest.Create(url);
            request.Timeout = 10000;
            // Set the Method property of the request to POST.
            request.Method = "GET";
            // Get the request stream.
            Stream dataStream; //= request.GetRequestStream();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            log.Info(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();

            Regex regex = new Regex(@"([^\s]+)\s+upgrade/(.*)", RegexOptions.IgnoreCase);

            if (regex.IsMatch(responseFromServer))
            {
                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();

                    if (file.ToLower().EndsWith(".etag"))
                        continue;

                    if (!MD5File(file, hash))
                    {
                        log.Info("Newer File " + file);

                        if (frmProgressReporter != null)
                            frmProgressReporter.UpdateProgressAndStatus(-1, "Getting " + file);

                        string subdir = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar;

                        GetNewFile(frmProgressReporter, baseurl + subdir.Replace('\\', '/'), subdir, Path.GetFileName(file));
                    }
                    else
                    {
                        log.Info("Same File " + file);

                        if (frmProgressReporter != null)
                            frmProgressReporter.UpdateProgressAndStatus(-1, "Checking " + file);
                    }
                }
            }
        }
Example #5
0
        public static void DoUpdate()
        {
            ProgressReporterDialogue frmProgressReporter = new ProgressReporterDialogue()
            {
                Text = "Check for Updates",
                StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
            };

            ThemeManager.ApplyThemeTo(frmProgressReporter);

            frmProgressReporter.DoWork += new ProgressReporterDialogue.DoWorkEventHandler(DoUpdateWorker_DoWork);

            frmProgressReporter.UpdateProgressAndStatus(-1, "Checking for Updates");

            frmProgressReporter.RunBackgroundOperationAsync();
        }
Example #6
0
        private void DownloadBurstToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem listView1SelectedItem in listView1.SelectedItems)
            {
                toolStripStatusLabel1.Text = "Download " + listView1SelectedItem.Text;
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.FileName         = listView1SelectedItem.Text;
                sfd.RestoreDirectory = true;
                sfd.OverwritePrompt  = true;
                var dr = sfd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    var path = treeView1.SelectedNode.FullPath + "/" + listView1SelectedItem.Text;
                    ProgressReporterDialogue prd    = new ProgressReporterDialogue();
                    CancellationTokenSource  cancel = new CancellationTokenSource();
                    prd.doWorkArgs.CancelRequestChanged += (o, args) =>
                    {
                        prd.doWorkArgs.ErrorMessage = "User Cancel";
                        cancel.Cancel();
                        _mavftp.kCmdResetSessions();
                    };
                    prd.doWorkArgs.ForceExit = false;

                    Action <string, int> progress = delegate(string message, int i)
                    {
                        prd.UpdateProgressAndStatus(i, toolStripStatusLabel1.Text);
                    };
                    _mavftp.Progress += progress;

                    prd.DoWork += (iprd) =>
                    {
                        var ms = _mavftp.GetFile(path, cancel);
                        if (cancel.IsCancellationRequested)
                        {
                            iprd.doWorkArgs.CancelAcknowledged = true;
                            iprd.doWorkArgs.CancelRequested    = true;
                            return;
                        }

                        File.WriteAllBytes(sfd.FileName, ms.ToArray());

                        prd.UpdateProgressAndStatus(-1, "Calc CRC");
                        uint crc = 0;
                        _mavftp.kCmdCalcFileCRC32(path, ref crc, cancel);
                        var crc32a = MAVFtp.crc_crc32(0, File.ReadAllBytes(sfd.FileName));
                        if (crc32a != crc)
                        {
                            throw new BadCrcException();
                        }
                    };
                    prd.RunBackgroundOperationAsync();
                    _mavftp.Progress -= progress;
                }
                else if (dr == DialogResult.Cancel)
                {
                    return;
                }
            }

            toolStripStatusLabel1.Text = "Ready";
        }
        /*
        public Bitmap getImage()
        {
            MemoryStream ms = new MemoryStream();

        }
        */
        public void getParamList()
        {
            frmProgressReporter = new ProgressReporterDialogue
            {
                StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen,
                Text = Strings.GettingParams + " " + sysidcurrent
            };

            frmProgressReporter.DoWork += FrmProgressReporterGetParams;
            frmProgressReporter.UpdateProgressAndStatus(-1, Strings.GettingParamsD);
            ThemeManager.ApplyThemeTo(frmProgressReporter);

            frmProgressReporter.RunBackgroundOperationAsync();

            frmProgressReporter.Dispose();

            if (ParamListChanged != null)
            {
                ParamListChanged(this, null);
            }

            // nan check
            foreach (string item in MAV.param.Keys)
            {
                if (float.IsNaN((float)MAV.param[item]))
                    CustomMessageBox.Show("BAD PARAM, " + item + " = NAN \n Fix this NOW!!", Strings.ERROR);
            }
        }
Example #8
0
        private void metroDMButton1_Click(object sender, EventArgs e)
        {
            //if ((altmode)CMB_altmode.SelectedValue == altmode.Absolute)
            //{
            //    if (DialogResult.No == CustomMessageBox.Show("Absolute Alt is selected are you sure?", "Alt Mode", MessageBoxButtons.YesNo))
            //    {
            //        CMB_altmode.SelectedValue = (int)altmode.Relative;
            //    }
            //}

            // check for invalid grid data
            for (int a = 0; a < Commands.Rows.Count - 0; a++)
            {
                for (int b = 0; b < Commands.ColumnCount - 0; b++)
                {
                    double answer;
                    if (b >= 1 && b <= 7)
                    {
                        if (!double.TryParse(Commands[b, a].Value.ToString(), out answer))
                        {
                            CustomMessageBox.Show("There are errors in your mission");
                            return;
                        }
                    }

                    if (TXT_altwarn.Text == "")
                        TXT_altwarn.Text = (0).ToString();

                    if (Commands.Rows[a].Cells[Command.Index].Value.ToString().Contains("UNKNOWN"))
                        continue;

                    byte cmd = (byte)(int)Enum.Parse(typeof(MAVLink.MAV_CMD), Commands.Rows[a].Cells[Command.Index].Value.ToString(), false);

                    if (cmd < (byte)MAVLink.MAV_CMD.LAST && double.Parse(Commands[Alt.Index, a].Value.ToString()) < double.Parse(TXT_altwarn.Text))
                    {
                        if (cmd != (byte)MAVLink.MAV_CMD.TAKEOFF &&
                            cmd != (byte)MAVLink.MAV_CMD.LAND &&
                            cmd != (byte)MAVLink.MAV_CMD.RETURN_TO_LAUNCH)
                        {
                            CustomMessageBox.Show("Low alt on WP#" + (a + 1) + "\nPlease reduce the alt warning, or increase the altitude");
                            return;
                        }
                    }
                }
            }

            ProgressReporterDialogue frmProgressReporter = new ProgressReporterDialogue
            {
                StartPosition = FormStartPosition.CenterScreen,
                Text = "上传航点中"
            };

            frmProgressReporter.DoWork += saveWPs;
            frmProgressReporter.UpdateProgressAndStatus(-1, "上传航点中");

            //ThemeManager.ApplyThemeTo(frmProgressReporter);

            frmProgressReporter.RunBackgroundOperationAsync();

            frmProgressReporter.Dispose();

            gMapControl1.Focus();
        }
        public void Open(bool getparams, bool skipconnectedcheck = false)
        {
            if (BaseStream.IsOpen && !skipconnectedcheck)
                return;

            MAVlist.Clear();

            frmProgressReporter = new ProgressReporterDialogue
            {
                StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen,
                Text = Strings.ConnectingMavlink
            };

            if (getparams)
            {
                frmProgressReporter.DoWork += FrmProgressReporterDoWorkAndParams;
            }
            else
            {
                frmProgressReporter.DoWork += FrmProgressReporterDoWorkNOParams;
            }
            frmProgressReporter.UpdateProgressAndStatus(-1, Strings.MavlinkConnecting);
            ThemeManager.ApplyThemeTo(frmProgressReporter);

            frmProgressReporter.RunBackgroundOperationAsync();

            frmProgressReporter.Dispose();

            if (ParamListChanged != null)
            {
                ParamListChanged(this, null);
            }
        }
Example #10
0
File: GCS.cs Project: kkouer/PcGcs
        private void button8_Click(object sender, EventArgs e)
        {

            //启用解锁按钮
            if (!comPort.BaseStream.IsOpen)
                return;

            buttonArmed.Enabled = true;
            buttonDisarmed.Enabled = true;

            //航线上传提示
            if (comPort.MAV.cs.alt > 20)
            {
                if (CustomMessageBox.Show("飞机已经在执行任务,是否继续上传并覆盖已有航线?", "覆盖航线", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                    return;
            }

            for (int a = 0; a < Commands.Rows.Count - 0; a++)
            {
                for (int b = 0; b < Commands.ColumnCount - 0; b++)
                {
                    double answer;
                    if (b >= 1 && b <= 7)
                    {
                        if (!double.TryParse(Commands[b, a].Value.ToString(), out answer))
                        {
                            CustomMessageBox.Show("There are errors in your mission");
                            return;
                        }
                    }

                    if (TXT_altwarn.Text == "")
                        TXT_altwarn.Text = (0).ToString();

                    if (Commands.Rows[a].Cells[Command.Index].Value.ToString().Contains("UNKNOWN"))
                        continue;

                    byte cmd = (byte)(int)Enum.Parse(typeof(MAVLink.MAV_CMD), Commands.Rows[a].Cells[Command.Index].Value.ToString(), false);

                    if (cmd < (byte)MAVLink.MAV_CMD.LAST && double.Parse(Commands[Alt.Index, a].Value.ToString()) < double.Parse(TXT_altwarn.Text))
                    {
                        if (cmd != (byte)MAVLink.MAV_CMD.TAKEOFF &&
                            cmd != (byte)MAVLink.MAV_CMD.LAND &&
                            cmd != (byte)MAVLink.MAV_CMD.RETURN_TO_LAUNCH)
                        {
                            CustomMessageBox.Show("Low alt on WP#" + (a + 1) + "\nPlease reduce the alt warning, or increase the altitude");
                            return;
                        }
                    }
                }
            }

            ProgressReporterDialogue frmProgressReporter = new ProgressReporterDialogue
            {
                StartPosition = FormStartPosition.CenterScreen,
                Text = "上传航点中"
            };

            frmProgressReporter.DoWork += saveWPs;
            frmProgressReporter.UpdateProgressAndStatus(-1, "上传航点中");

            //ThemeManager.ApplyThemeTo(frmProgressReporter);

            frmProgressReporter.RunBackgroundOperationAsync();

            frmProgressReporter.Dispose();

            gMapControl1.Focus();
        }
Example #11
0
 void BinaryLog_convertstatus(ProgressReporterDialogue prd, float progress)
 {
     prd.UpdateProgressAndStatus((int) progress, Strings.Converting_bin_to_log);
 }
Example #12
0
        static async void CheckMD5(ProgressReporterDialogue frmProgressReporter, string url)
        {
            var baseurl = ConfigurationManager.AppSettings["UpdateLocation"];

            if (dobeta)
            {
                baseurl = ConfigurationManager.AppSettings["BetaUpdateLocation"];
            }

            L10N.ReplaceMirrorUrl(ref baseurl);

            string responseFromServer = "";

            WebRequest request = WebRequest.Create(url);
            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+upgrade/(.*)", RegexOptions.IgnoreCase);

            if (regex.IsMatch(responseFromServer))
            {
                List<Tuple<string, string, Task<bool>>> tasklist = new List<Tuple<string, string, Task<bool>>>();

                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 = MD5File(file, hash);

                    tasklist.Add(new Tuple<string,string, Task<bool>>(file, hash, ismatch));
                }

                log.Info("MD5File Running");

                foreach (var task in tasklist)
                {
                    string file = task.Item1;
                    string hash = task.Item2;
                    // check if existing matchs hash
                    bool match = await task.Item3;
                    if (!match)
                    {
                        log.Info("Newer File " + file);

                        // check is we have already downloaded and matchs hash
                        if (!MD5File(file + ".new", hash).Result)
                        {
                            if (frmProgressReporter != null)
                                frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Getting + file);

                            string subdir = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar;

                            GetNewFile(frmProgressReporter, baseurl + subdir.Replace('\\', '/'), subdir,
                                Path.GetFileName(file));

                            // check the new downloaded file matchs hash
                            if (!MD5File(file + ".new", hash).Result)
                            {
                                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);
                    }
                }
            }
        }
Example #13
0
        public static void DoUpdate()
        {
            if (Program.WindowsStoreApp)
            {
                CustomMessageBox.Show(Strings.Not_available_when_used_as_a_windows_store_app);
                return;
            }

            ProgressReporterDialogue frmProgressReporter = new ProgressReporterDialogue()
            {
                Text = "Check for Updates",
                StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
            };

            ThemeManager.ApplyThemeTo(frmProgressReporter);

            frmProgressReporter.DoWork += new ProgressReporterDialogue.DoWorkEventHandler(DoUpdateWorker_DoWork);

            frmProgressReporter.UpdateProgressAndStatus(-1, "Checking for Updates");

            frmProgressReporter.RunBackgroundOperationAsync();

            frmProgressReporter.Dispose();
        }
        public void Open()
        {
            if (client.Client.Connected)
            {
                log.Info("udpserial socket already open");
                return;
            }

            client.Close();

            string dest = Port;

            dest = OnSettings("UDP_port", dest);

            if (System.Windows.Forms.DialogResult.Cancel == InputBox.Show("Listern Port", "Enter Local port (ensure remote end is already sending)", ref dest))
            {
                return;
            }
            Port = dest;

            OnSettings("UDP_port", Port, true);

            ProgressReporterDialogue frmProgressReporter = new ProgressReporterDialogue
            {
                StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen,
                Text = "Connecting UDP"
            };

            ApplyThemeTo(frmProgressReporter);           

            frmProgressReporter.DoWork += frmProgressReporter_DoWork;

            frmProgressReporter.UpdateProgressAndStatus(-1, "Connecting UDP");

            frmProgressReporter.RunBackgroundOperationAsync();

            frmProgressReporter.Dispose();
        }
Example #15
0
        static void GetNewFile(ProgressReporterDialogue 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
                {

                    // Create a request using a URL that can receive a post.
                    WebRequest request = WebRequest.Create(baseurl + file);
                    log.Info("get " + baseurl + file + " ");
                    // 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.
                    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();

                    // update status
                    if (frmProgressReporter != null)
                        frmProgressReporter.UpdateProgressAndStatus(-1, "Getting " + file);

                    // 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";

                    if (!File.Exists(path))
                        fn = path;

                    using (FileStream fs = new FileStream(fn, FileMode.Create))
                    {

                        DateTime dt = DateTime.Now;

                        while (dataStream.CanRead)
                        {
                            try
                            {
                                if (dt.Second != DateTime.Now.Second)
                                {
                                    if (frmProgressReporter != null)
                                        frmProgressReporter.UpdateProgressAndStatus((int)(((double)(contlen - bytes) / (double)contlen) * 100), "Getting " + file + ": " + (((double)(contlen - bytes) / (double)contlen) * 100).ToString("0.0") + "%"); //+ Math.Abs(bytes) + " bytes");
                                    dt = DateTime.Now;
                                }
                            }
                            catch { }
                            log.Debug(file + " " + bytes);
                            int len = dataStream.Read(buf1, 0, buf1.Length);
                            if (len == 0)
                                break;
                            bytes -= len;
                            fs.Write(buf1, 0, len);
                        }
                        fs.Close();
                    }

                    response.Close();

                }
                catch (Exception ex) { fail = ex; attempt++; continue; }

                // break if we have no exception
                break;
            }

            if (attempt == 2)
            {
                throw fail;
            }
        }
Example #16
0
File: GCS.cs Project: kkouer/PcGcs
        private void button9_Click(object sender, EventArgs e)
        {
            if (Commands.Rows.Count > 0)
            {
                if (CustomMessageBox.Show("将覆盖本地航点,是否继续?", "确定", MessageBoxButtons.OKCancel) != DialogResult.OK)
                {
                    return;
                }
            }

            ProgressReporterDialogue frmProgressReporter = new ProgressReporterDialogue
            {
                StartPosition = FormStartPosition.CenterScreen,
                Text = "下载航点"
            };

            frmProgressReporter.DoWork += getWPs;
            frmProgressReporter.UpdateProgressAndStatus(-1, "下载航点");


            frmProgressReporter.RunBackgroundOperationAsync();

            frmProgressReporter.Dispose();
        }
Example #17
0
        private static bool updateCheck(ProgressReporterDialogue frmProgressReporter, string baseurl, string subdir)
        {
            bool update = false;
            List<string> files = new List<string>();

            // Create a request using a URL that can receive a post.
            log.Info(baseurl);
            WebRequest request = WebRequest.Create(baseurl);
            request.Timeout = 10000;
            // Set the Method property of the request to POST.
            request.Method = "GET";
            // Get the request stream.
            Stream dataStream; //= request.GetRequestStream();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            log.Info(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Regex regex = new Regex("href=\"([^\"]+)\"", RegexOptions.IgnoreCase);

            Uri baseuri = new Uri(baseurl, UriKind.Absolute);

            if (regex.IsMatch(responseFromServer))
            {
                MatchCollection matchs = regex.Matches(responseFromServer);
                for (int i = 0; i < matchs.Count; i++)
                {
                    if (matchs[i].Groups[1].Value.ToString().Contains(".."))
                        continue;
                    if (matchs[i].Groups[1].Value.ToString().Contains("http"))
                        continue;
                    if (matchs[i].Groups[1].Value.ToString().StartsWith("?"))
                        continue;
                    if (matchs[i].Groups[1].Value.ToString().ToLower().Contains(".etag"))
                        continue;

                    //
                    {
                        string url = System.Web.HttpUtility.UrlDecode(matchs[i].Groups[1].Value.ToString());
                        Uri newuri = new Uri(baseuri, url);
                        files.Add(baseuri.MakeRelativeUri(newuri).ToString());
                    }

                    // dirs
                    if (matchs[i].Groups[1].Value.ToString().Contains("tree/master/"))
                    {
                        string url = System.Web.HttpUtility.UrlDecode(matchs[i].Groups[1].Value.ToString()) + "/";
                        Uri newuri = new Uri(baseuri, url);
                        files.Add(baseuri.MakeRelativeUri(newuri).ToString());

                    }
                    // files
                    if (matchs[i].Groups[1].Value.ToString().Contains("blob/master/"))
                    {
                        string url = System.Web.HttpUtility.UrlDecode(matchs[i].Groups[1].Value.ToString());
                        Uri newuri = new Uri(baseuri, url);
                        files.Add(System.Web.HttpUtility.UrlDecode(newuri.Segments[newuri.Segments.Length - 1]));
                    }
                }
            }

            //Console.WriteLine(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();

            string dir = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir;
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            foreach (string file in files)
            {
                if (frmProgressReporter.doWorkArgs.CancelRequested)
                {
                    frmProgressReporter.doWorkArgs.CancelAcknowledged = true;
                    throw new Exception("Cancel");
                }

                if (file.Equals("/") || file.Equals("") || file.StartsWith("../"))
                {
                    continue;
                }
                if (file.EndsWith("/"))
                {
                    update = updateCheck(frmProgressReporter, baseurl + file, subdir.Replace('/', Path.DirectorySeparatorChar) + file) && update;
                    continue;
                }
                if (frmProgressReporter != null)
                    frmProgressReporter.UpdateProgressAndStatus(-1, "Checking " + file);

                string path = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir + file;

                //   baseurl = baseurl.Replace("//github.com", "//raw.github.com");
                //   baseurl = baseurl.Replace("/tree/", "/");

                Exception fail = null;
                int attempt = 0;

                while (attempt < 2)
                {

                    try
                    {

                        // Create a request using a URL that can receive a post.
                        request = WebRequest.Create(baseurl + file);
                        log.Info(baseurl + file + " ");
                        // Set the Method property of the request to POST.
                        request.Method = "GET";

                        ((HttpWebRequest)request).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                        request.Headers.Add("Accept-Encoding", "gzip,deflate");

                        // Get the response.
                        response = request.GetResponse();
                        // Display the status.
                        log.Info(((HttpWebResponse)response).StatusDescription);
                        // Get the stream containing content returned by the server.
                        dataStream = response.GetResponseStream();
                        // Open the stream using a StreamReader for easy access.

                        bool updateThisFile = false;

                        if (File.Exists(path))
                        {
                            FileInfo fi = new FileInfo(path);

                            //log.Info(response.Headers[HttpResponseHeader.ETag]);
                            string CurrentEtag = "";

                            if (File.Exists(path + ".etag"))
                            {
                                using (Stream fs = File.OpenRead(path + ".etag"))
                                {
                                    using (StreamReader sr = new StreamReader(fs))
                                    {
                                        CurrentEtag = sr.ReadLine();
                                        sr.Close();
                                    }
                                    fs.Close();
                                }
                            }

                            log.Debug("New file Check: " + fi.Length + " vs " + response.ContentLength + " " + response.Headers[HttpResponseHeader.ETag] + " vs " + CurrentEtag);

                            if (fi.Length != response.ContentLength || response.Headers[HttpResponseHeader.ETag] != CurrentEtag)
                            {
                                using (StreamWriter sw = new StreamWriter(path + ".etag.new"))
                                {
                                    sw.WriteLine(response.Headers[HttpResponseHeader.ETag]);
                                    sw.Close();
                                }
                                updateThisFile = true;
                                log.Info("NEW FILE " + file);
                            }
                        }
                        else
                        {
                            updateThisFile = true;
                            log.Info("NEW FILE " + file);
                            using (StreamWriter sw = new StreamWriter(path + ".etag.new"))
                            {
                                sw.WriteLine(response.Headers[HttpResponseHeader.ETag]);
                                sw.Close();
                            }
                            // get it
                        }

                        if (updateThisFile)
                        {
                            if (!update)
                            {
                                //DialogResult dr = MessageBox.Show("Update Found\n\nDo you wish to update now?", "Update Now", MessageBoxButtons.YesNo);
                                //if (dr == DialogResult.Yes)
                                {
                                    update = true;
                                }
                                //else
                                {
                                    //    return;
                                }
                            }
                            if (frmProgressReporter != null)
                                frmProgressReporter.UpdateProgressAndStatus(-1, "Getting " + file);

                            // from head
                            long bytes = response.ContentLength;

                            long contlen = bytes;

                            byte[] buf1 = new byte[4096];

                            using (FileStream fs = new FileStream(path + ".new", FileMode.Create))
                            {

                                DateTime dt = DateTime.Now;

                                //dataStream.ReadTimeout = 30000;

                                while (dataStream.CanRead)
                                {
                                    try
                                    {
                                        if (dt.Second != DateTime.Now.Second)
                                        {
                                            if (frmProgressReporter != null)
                                                frmProgressReporter.UpdateProgressAndStatus((int)(((double)(contlen - bytes) / (double)contlen) * 100), "Getting " + file + ": " + (((double)(contlen - bytes) / (double)contlen) * 100).ToString("0.0") + "%"); //+ Math.Abs(bytes) + " bytes");
                                            dt = DateTime.Now;
                                        }
                                    }
                                    catch { }
                                    log.Debug(file + " " + bytes);
                                    int len = dataStream.Read(buf1, 0, buf1.Length);
                                    if (len == 0)
                                        break;
                                    bytes -= len;
                                    fs.Write(buf1, 0, len);
                                }
                                fs.Close();
                            }
                        }

                        reader.Close();
                        //dataStream.Close();
                        response.Close();

                    }
                    catch (Exception ex) { fail = ex; attempt++; update = false; continue; }

                    // break if we have no exception
                    break;
                }

                if (attempt == 2)
                {
                    throw fail;
                }
            }

            //P.StartInfo.CreateNoWindow = true;
            //P.StartInfo.RedirectStandardOutput = true;
            return update;
        }
Example #18
0
        public void Open(bool getparams)
        {
            if (BaseStream.IsOpen)
                return;

            frmProgressReporter = new ProgressReporterDialogue
                                      {
                                          StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen,
                                          Text = "Connecting Mavlink"
                                      };

            if (getparams)
            {
                frmProgressReporter.DoWork += FrmProgressReporterDoWorkAndParams;
            }
            else
            {
                frmProgressReporter.DoWork += FrmProgressReporterDoWorkNOParams;
            }
            frmProgressReporter.UpdateProgressAndStatus(-1, "Mavlink Connecting...");
            ThemeManager.ApplyThemeTo(frmProgressReporter);

            frmProgressReporter.RunBackgroundOperationAsync();

            if (ParamListChanged != null)
            {
                ParamListChanged(this, null);
            }
        }
        /*
        public Bitmap getImage()
        {
            MemoryStream ms = new MemoryStream();

        }
        */

        public void getParamList()
        {
            frmProgressReporter = new ProgressReporterDialogue
            {
                StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen,
                Text = Strings.GettingParams + " " + sysidcurrent
            };

            frmProgressReporter.DoWork += FrmProgressReporterGetParams;
            frmProgressReporter.UpdateProgressAndStatus(-1, Strings.GettingParamsD);
            ThemeManager.ApplyThemeTo(frmProgressReporter);

            frmProgressReporter.RunBackgroundOperationAsync();

            frmProgressReporter.Dispose();

            if (ParamListChanged != null)
            {
                ParamListChanged(this, null);
            }
        }
        public void Open()
        {
            if (client.Client.Connected)
            {
                log.Info("udpserial socket already open");
                return;
            }

            ProgressReporterDialogue frmProgressReporter = new ProgressReporterDialogue
            {
                StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen,
                Text = "Connecting Mavlink UDP"
            };

            frmProgressReporter.DoWork += frmProgressReporter_DoWork;

            frmProgressReporter.UpdateProgressAndStatus(-1, "Connecting Mavlink UDP");

            frmProgressReporter.RunBackgroundOperationAsync();
        }