/// <summary> /// Shows a Yes/No dialog. /// </summary> /// <param name="title">The title of the window.</param> /// <param name="instruction">The main instruction.</param> /// <param name="observation">A complementar observation.</param> /// <param name="icon">The image of the dialog.</param> /// <returns>True if Yes</returns> public static bool Ask(string title, string instruction, string observation, Icons icon = Icons.Error) { var dialog = new Dialog(); dialog.PrepareAsk(title, instruction, observation, icon); var result = dialog.ShowDialog(); return result.HasValue && result.Value; }
private void InternalAddItem(List <FrameInfo> listFrames, Parameters param) { //Creates the Cancellation Token var cancellationTokenSource = new CancellationTokenSource(); CancellationTokenList.Add(cancellationTokenSource); var context = TaskScheduler.FromCurrentSynchronizationContext(); //Creates Task and send the Task Id. var a = -1; var task = new Task(() => { Encode(listFrames, a, param, cancellationTokenSource); }, CancellationTokenList.Last().Token, TaskCreationOptions.LongRunning); a = task.Id; #region Error Handling task.ContinueWith(t => { var aggregateException = t.Exception; aggregateException?.Handle(exception => true); SetStatus(Status.Error, a, null, false, t.Exception); LogWriter.Log(t.Exception, "Encoding Error"); }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, context); #endregion #region Creates List Item var encoderItem = new EncoderListViewItem { OutputType = param.Type == Export.Gif ? OutputType.Gif : OutputType.Video, Text = FindResource("Encoder.Starting").ToString(), FrameCount = listFrames.Count, Id = a, TokenSource = cancellationTokenSource, WillCopyToClipboard = param is GifParameters && ((GifParameters)param).SaveToClipboard, }; encoderItem.CancelClicked += EncoderItem_CancelClicked; EncodingListView.Items.Add(encoderItem); EncodingListView.ScrollIntoView(encoderItem); #endregion try { TaskList.Add(task); TaskList.Last().Start(); } catch (Exception ex) { Dialog.Ok("Task Error", "Unable to start the encoding task", "A generic error occured while trying to start the encoding task. " + ex.Message); LogWriter.Log(ex, "Errow while starting the task."); } }
private bool InsertFrames(bool after) { try { ActionStack.Did(ActualList); #region Actual List var actualFrame = ActualList[0].ImageLocation.SourceFrom(); double oldWidth = actualFrame.PixelWidth; double oldHeight = actualFrame.PixelHeight; var scale = Math.Round(actualFrame.DpiX, MidpointRounding.AwayFromZero) / 96d; //If the canvas size changed. if (Math.Abs(LeftCanvas.ActualWidth * scale - oldWidth) > 0 || Math.Abs(LeftCanvas.ActualHeight * scale - oldHeight) > 0 || Math.Abs(LeftImage.ActualWidth * scale - oldWidth) > 0 || Math.Abs(LeftImage.ActualHeight * scale - oldHeight) > 0) { StartProgress(ActualList.Count, FindResource("Editor.UpdatingFrames").ToString()); foreach (var frameInfo in ActualList) { #region Resize Images // Draws the images into a DrawingVisual component var drawingVisual = new DrawingVisual(); using (var context = drawingVisual.RenderOpen()) { //The back canvas. context.DrawRectangle(new SolidColorBrush(Settings.Default.InsertFillColor), null, new Rect(new Point(0, 0), new Point(Math.Round(RightCanvas.ActualWidth, MidpointRounding.AwayFromZero), Math.Round(RightCanvas.ActualHeight, MidpointRounding.AwayFromZero)))); var topPoint = Dispatcher.Invoke(() => Canvas.GetTop(LeftImage)); var leftPoint = Dispatcher.Invoke(() => Canvas.GetLeft(LeftImage)); //The image. context.DrawImage(frameInfo.ImageLocation.SourceFrom(), new Rect(leftPoint, topPoint, LeftImage.ActualWidth, LeftImage.ActualHeight)); //context.DrawText(new FormattedText("Hi!", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface("Segoe UI"), 32, Brushes.Black), new Point(0, 0)); } // Converts the Visual (DrawingVisual) into a BitmapSource var bmp = new RenderTargetBitmap((int)(LeftCanvas.ActualWidth * scale), (int)(LeftCanvas.ActualHeight * scale), actualFrame.DpiX, actualFrame.DpiX, PixelFormats.Pbgra32); bmp.Render(drawingVisual); #endregion #region Save // Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); // Saves the image into a file using the encoder using (Stream stream = File.Create(frameInfo.ImageLocation)) encoder.Save(stream); #endregion if (_isCancelled) { return(false); } UpdateProgress(ActualList.IndexOf(frameInfo)); } } #endregion #region New List var newFrame = NewList[0].ImageLocation.SourceFrom(); oldWidth = newFrame.PixelWidth; oldHeight = newFrame.PixelHeight; scale = Math.Round(newFrame.DpiX, MidpointRounding.AwayFromZero) / 96d; StartProgress(ActualList.Count, FindResource("Editor.ImportingFrames").ToString()); var folder = Path.GetDirectoryName(ActualList[0].ImageLocation); var insertFolder = Path.GetDirectoryName(NewList[0].ImageLocation); //If the canvas size changed. if (Math.Abs(RightCanvas.ActualWidth * scale - oldWidth) > 0 || Math.Abs(RightCanvas.ActualHeight * scale - oldHeight) > 0 || Math.Abs(RightImage.ActualWidth * scale - oldWidth) > 0 || Math.Abs(RightImage.ActualHeight * scale - oldHeight) > 0) { foreach (var frameInfo in NewList) { #region Resize Images // Draws the images into a DrawingVisual component var drawingVisual = new DrawingVisual(); using (var context = drawingVisual.RenderOpen()) { //The back canvas. context.DrawRectangle(new SolidColorBrush(Settings.Default.InsertFillColor), null, new Rect(new Point(0, 0), new Point(Math.Round(RightCanvas.ActualWidth, MidpointRounding.AwayFromZero), Math.Round(RightCanvas.ActualHeight, MidpointRounding.AwayFromZero)))); var topPoint = Dispatcher.Invoke(() => Canvas.GetTop(RightImage)); var leftPoint = Dispatcher.Invoke(() => Canvas.GetLeft(RightImage)); //The front image. context.DrawImage(frameInfo.ImageLocation.SourceFrom(), new Rect(leftPoint, topPoint, RightImage.ActualWidth, RightImage.ActualHeight)); } // Converts the Visual (DrawingVisual) into a BitmapSource var bmp = new RenderTargetBitmap((int)(RightCanvas.ActualWidth * scale), (int)(RightCanvas.ActualHeight * scale), newFrame.DpiX, newFrame.DpiX, PixelFormats.Pbgra32); bmp.Render(drawingVisual); #endregion #region Save // Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); File.Delete(frameInfo.ImageLocation); var fileName = Path.Combine(folder, $"{_insertIndex}-{NewList.IndexOf(frameInfo)} {DateTime.Now.ToString("hh-mm-ss")}.bmp"); // Saves the image into a file using the encoder using (Stream stream = File.Create(fileName)) encoder.Save(stream); frameInfo.ImageLocation = fileName; #endregion if (_isCancelled) { return(false); } UpdateProgress(NewList.IndexOf(frameInfo)); } } else { foreach (var frameInfo in NewList) { #region Move var fileName = Path.Combine(folder, $"{_insertIndex}-{NewList.IndexOf(frameInfo)} {DateTime.Now.ToString("hh-mm-ss")}.png"); File.Move(frameInfo.ImageLocation, fileName); frameInfo.ImageLocation = fileName; #endregion if (_isCancelled) { return(false); } UpdateProgress(NewList.IndexOf(frameInfo)); } } Directory.Delete(insertFolder, true); #endregion if (_isCancelled) { return(false); } #region Merge the Lists if (after) { _insertIndex++; } ActualList.InsertRange(_insertIndex, NewList); #endregion return(true); } catch (Exception ex) { LogWriter.Log(ex, "Insert Error"); Dispatcher.Invoke(() => Dialog.Ok("Insert Error", "Something Wrong Happened", ex.Message)); return(false); } }
private async void Persist() { try { var path = Path.Combine(UserSettings.All.TemporaryFolderResolved, "ScreenToGif", "Feedback"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var name = Path.Combine(path, DateTime.Now.ToString("yy_MM_dd HH-mm-ss")); var title = TitleTextBox.Text; var message = MessageTextBox.Text; var email = EmailTextBox.Text; var issue = IssueCheckBox.IsChecked == true; var suggestion = SuggestionCheckBox.IsChecked == true; await Task.Factory.StartNew(() => File.WriteAllText(name + ".html", BuildBody(title, message, email, issue, suggestion))); if (AttachmentListBox.Items.Count <= 0) { DialogResult = true; return; } if (Directory.Exists(name)) { Directory.Delete(name); } Directory.CreateDirectory(name); foreach (var item in AttachmentListBox.Items.OfType <AttachmentListBoxItem>()) { var sourceName = Path.GetFileName(item.Attachment); var destName = Path.Combine(name, sourceName); if (item.Attachment.StartsWith(UserSettings.All.LogsFolder)) { File.Move(item.Attachment, destName); } else { File.Copy(item.Attachment, destName, true); } } ZipFile.CreateFromDirectory(name, name + ".zip"); Directory.Delete(name, true); DialogResult = true; } catch (Exception ex) { LogWriter.Log(ex, "Persist feedback"); Dialog.Ok("Feedback", "Error while creating the feedback", ex.Message); } }
private async void Add_Executed(object sender, ExecutedRoutedEventArgs e) { var ofd = new OpenFileDialog { AddExtension = true, CheckFileExists = true, Title = LocalizationHelper.Get("S.Localization.OpenResource"), Filter = LocalizationHelper.Get("S.Localization.File.Resource") + " (*.xaml)|*.xaml;" }; var result = ofd.ShowDialog(); if (!result.HasValue || !result.Value) { return; } #region Validations var position = ofd.FileName.IndexOf("StringResources", StringComparison.InvariantCulture); var subs = position > -1 ? ofd.FileName.Substring(position) : ""; var pieces = subs.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); //Wrong filename format. if (position < 0 || pieces.Length != 3) { Dialog.Ok(Title, LocalizationHelper.Get("S.Localization.Warning.Name"), LocalizationHelper.Get("S.Localization.Warning.Name.Info")); StatusBand.Hide(); return; } //Repeated language code. if (Application.Current.Resources.MergedDictionaries.Any(x => x.Source != null && x.Source.OriginalString.Contains(subs))) { Dialog.Ok(Title, LocalizationHelper.Get("S.Localization.Warning.Repeated"), LocalizationHelper.Get("S.Localization.Warning.Repeated.Info")); StatusBand.Hide(); return; } try { var properCulture = await Task.Factory.StartNew(() => CheckSupportedCulture(pieces[1])); if (properCulture != pieces[1]) { Dialog.Ok(Title, LocalizationHelper.Get("S.Localization.Warning.Redundant"), LocalizationHelper.GetWithFormat("S.Localization.Warning.Redundant.Info", "The \"{0}\" code is redundant. Try using \"{1}\" instead.", pieces[1], properCulture)); StatusBand.Hide(); return; } } catch (CultureNotFoundException cn) { LogWriter.Log(cn, "Impossible to validade the resource name, culture not found"); Dialog.Ok(Title, LocalizationHelper.Get("S.Localization.Warning.Unknown"), LocalizationHelper.GetWithFormat("S.Localization.Warning.Unknown.Info", "The \"{0}\" and its family were not recognized as valid language codes.", pieces[1])); StatusBand.Hide(); return; } catch (Exception ex) { LogWriter.Log(ex, "Impossible to validade the resource name"); Dialog.Ok(Title, LocalizationHelper.Get("S.Localization.Warning.NotPossible"), ex.Message); StatusBand.Hide(); return; } #endregion StatusBand.Info(LocalizationHelper.Get("S.Localization.Importing")); try { var fileName = ofd.FileName; await Task.Factory.StartNew(() => LocalizationHelper.ImportStringResource(fileName)); } catch (Exception ex) { LogWriter.Log(ex, "Impossible to import the resource"); Dialog.Ok(Title, LocalizationHelper.Get("S.Localization.Warning.NotPossible"), ex.Message); StatusBand.Hide(); return; } var resourceDictionary = Application.Current.Resources.MergedDictionaries.LastOrDefault(); var imageItem = new ImageListBoxItem { Content = resourceDictionary?.Source.OriginalString ?? "...", Image = FindResource("Vector.Translate") as Canvas, Author = LocalizationHelper.GetWithFormat("S.Localization.Recognized", "Recognized as {0}", pieces[1]), Index = Application.Current.Resources.MergedDictionaries.Count - 1, ShowMarkOnSelection = false }; StatusBand.Hide(); ResourceListBox.Items.Add(imageItem); ResourceListBox.ScrollIntoView(imageItem); UpdateIndexes(); CommandManager.InvalidateRequerySuggested(); }
private void SendButton_Click(object sender, RoutedEventArgs e) { StatusBand.Hide(); #region Validation if (TitleTextBox.Text.Length == 0) { StatusBand.Warning(FindResource("S.Feedback.Warning.Title") as string); TitleTextBox.Focus(); return; } if (MessageTextBox.Text.Length == 0) { StatusBand.Warning(FindResource("S.Feedback.Warning.Message") as string); MessageTextBox.Focus(); return; } if (string.IsNullOrWhiteSpace(Secret.Password)) { Dialog.Ok("Feedback", "You are probably running from the source code", "Please, don't try to log into the account of the e-mail sender. " + "Everytime someone does that, the e-mail gets locked and this feature (the feedback) stops working.", Dialog.Icons.Warning); return; } #endregion #region UI StatusBand.Info(FindResource("S.Feedback.Sending").ToString()); Cursor = Cursors.AppStarting; MainGrid.IsEnabled = false; MainGrid.UpdateLayout(); #endregion //Please, don't try to log with this e-mail and password. :/ //Everytime someone does this, I have to change the password and the Feedback feature stops working until I update the app. var passList = Secret.Password.Split('|'); var smtp = new SmtpClient { Timeout = 5 * 60 * 1000, //Minutes, seconds, miliseconds Port = Secret.Port, Host = Secret.Host, EnableSsl = true, UseDefaultCredentials = true, Credentials = new NetworkCredential(Secret.Email, passList[_current]) }; //Please, don't try to log with this e-mail and password. :/ //Everytime someone does this, I have to change the password and the Feedback feature stops working until I update the app. var mail = new MailMessage { From = new MailAddress("*****@*****.**"), Subject = "ScreenToGif - Feedback", IsBodyHtml = true }; mail.To.Add("*****@*****.**"); #region Text var sb = new StringBuilder(); sb.Append("<html xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\">"); sb.Append("<head><meta content=\"en-us\" http-equiv=\"Content-Language\" />" + "<meta content=\"text/html; charset=utf-16\" http-equiv=\"Content-Type\" />" + "<title>Screen To Gif - Feedback</title>" + "</head>"); sb.AppendFormat("<style>{0}</style>", Util.Other.GetTextResource("ScreenToGif.Resources.Style.css")); sb.Append("<body>"); sb.AppendFormat("<h1>{0}</h1>", TitleTextBox.Text); sb.Append("<div id=\"content\"><div>"); sb.Append("<h2>Overview</h2>"); sb.Append("<div id=\"overview\"><table><tr>"); sb.Append("<th _locid=\"UserTableHeader\">User</th>"); if (MailTextBox.Text.Length > 0) { sb.Append("<th _locid=\"FromTableHeader\">Mail</th>"); } sb.Append("<th _locid=\"VersionTableHeader\">Version</th>"); sb.Append("<th _locid=\"WindowsTableHeader\">Windows</th>"); sb.Append("<th _locid=\"BitsTableHeader\">Instruction Size</th>"); sb.Append("<th _locid=\"MemoryTableHeader\">Working Memory</th>"); sb.Append("<th _locid=\"IssueTableHeader\">Issue?</th>"); sb.Append("<th _locid=\"SuggestionTableHeader\">Suggestion?</th></tr>"); sb.AppendFormat("<tr><td class=\"textcentered\">{0}</td>", Environment.UserName); if (MailTextBox.Text.Length > 0) { sb.AppendFormat("<td class=\"textcentered\">{0}</td>", MailTextBox.Text); } sb.AppendFormat("<td class=\"textcentered\">{0}</td>", Assembly.GetExecutingAssembly().GetName().Version.ToString(4)); sb.AppendFormat("<td class=\"textcentered\">{0}</td>", Environment.OSVersion.Version); sb.AppendFormat("<td class=\"textcentered\">{0}</td>", Environment.Is64BitOperatingSystem ? "64 bits" : "32 Bits"); sb.AppendFormat("<td class=\"textcentered\">{0}</td>", Humanizer.BytesToString(Environment.WorkingSet)); sb.AppendFormat("<td class=\"textcentered\">{0}</td>", IssueCheckBox.IsChecked.Value ? "Yes" : "No"); sb.AppendFormat("<td class=\"textcentered\">{0}</td></tr></table></div></div>", SuggestionCheckBox.IsChecked.Value ? "Yes" : "No"); sb.Append("<h2>Details</h2><div><div><table>"); sb.Append("<tr id=\"ProjectNameHeaderRow\"><th class=\"messageCell\" _locid=\"MessageTableHeader\">Message</th></tr>"); sb.Append("<tr name=\"MessageRowClassProjectName\">"); sb.AppendFormat("<td class=\"messageCell\">{0}</td></tr></table>", MessageTextBox.Text); sb.Append("</div></div></div></body></html>"); #endregion mail.Body = sb.ToString(); foreach (AttachmentListBoxItem attachment in AttachmentListBox.Items) { mail.Attachments.Add(new Attachment(attachment.Attachment)); } smtp.SendCompleted += Smtp_OnSendCompleted; smtp.SendMailAsync(mail); }
private void Add_Executed(object sender, ExecutedRoutedEventArgs e) { var ofd = new OpenFileDialog { AddExtension = true, CheckFileExists = true, Title = "Open a Resource Dictionary", Filter = "Resource Dictionay (*.xaml)|*.xaml;" }; var result = ofd.ShowDialog(); if (!result.HasValue || !result.Value) { return; } #region Validation if (!ofd.FileName.Contains("StringResources")) { Dialog.Ok("Action Denied", "The name of file does not follow a valid pattern.", "Try renaming like (without the []): StringResources.[Language Code].xaml"); return; } var subs = ofd.FileName.Substring(ofd.FileName.IndexOf("StringResources")); if (Application.Current.Resources.MergedDictionaries.Any(x => x.Source != null && x.Source.OriginalString.Contains(subs))) { Dialog.Ok("Action Denied", "You can't add a resource with the same name.", "Try renaming like: StringResources.[Language Code].xaml"); return; } var pieces = subs.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (pieces.Length != 3) { Dialog.Ok("Action Denied", "Filename with wrong format.", "Try renaming like: StringResources.[Language Code].xaml"); return; } var culture = new CultureInfo(pieces[1]); if (culture.EnglishName.Contains("Unknown")) { Dialog.Ok("Action Denied", "Unknown Language.", $"The \"{pieces[1]}\" was not recognized as a valid language code."); return; } #endregion if (!LocalizationHelper.ImportStringResource(ofd.FileName)) { return; } var resourceDictionary = Application.Current.Resources.MergedDictionaries.LastOrDefault(); var imageItem = new ImageListBoxItem { Tag = resourceDictionary?.Source.OriginalString ?? "Unknown", Content = resourceDictionary?.Source.OriginalString ?? "Unknown", Image = FindResource("Vector.Translate") as Canvas, Author = "Recognized as " + pieces[1] }; ResourceListBox.Items.Add(imageItem); ResourceListBox.ScrollIntoView(imageItem); CommandManager.InvalidateRequerySuggested(); }
private async void Add_Executed(object sender, ExecutedRoutedEventArgs e) { var ofd = new OpenFileDialog { AddExtension = true, CheckFileExists = true, Title = "Open a Resource Dictionary", Filter = "Resource Dictionay (*.xaml)|*.xaml;" }; var result = ofd.ShowDialog(); if (!result.HasValue || !result.Value) { return; } StatusBand.Info("Validating resource name..."); #region Validation if (!ofd.FileName.Contains("StringResources")) { Dialog.Ok("Action Denied", "The name of file does not follow a valid pattern.", "Try renaming like (without the []): StringResources.[Language Code].xaml"); StatusBand.Hide(); return; } var subs = ofd.FileName.Substring(ofd.FileName.IndexOf("StringResources")); if (Application.Current.Resources.MergedDictionaries.Any(x => x.Source != null && x.Source.OriginalString.Contains(subs))) { Dialog.Ok("Action Denied", "You can't add a resource with the same name.", "Try renaming like: StringResources.[Language Code].xaml"); StatusBand.Hide(); return; } var pieces = subs.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (pieces.Length != 3) { Dialog.Ok("Action Denied", "Filename with wrong format.", "Try renaming like: StringResources.[Language Code].xaml"); StatusBand.Hide(); return; } var cultureName = pieces[1]; string properCulture; try { properCulture = await Task.Factory.StartNew(() => CheckSupportedCulture(cultureName)); } catch (CultureNotFoundException) { Dialog.Ok("Action Denied", "Unknown Language.", $"The \"{cultureName}\" and its family were not recognized as a valid language codes."); StatusBand.Hide(); return; } catch (Exception ex) { Dialog.Ok("Action Denied", "Error checking culture.", ex.Message); StatusBand.Hide(); return; } if (properCulture != cultureName) { Dialog.Ok("Action Denied", "Redundant Language Code.", $"The \"{cultureName}\" code is redundant. Try using \'{properCulture}\" instead"); StatusBand.Hide(); return; } #endregion StatusBand.Info("Importing resource..."); var fileName = ofd.FileName; try { await Task.Factory.StartNew(() => LocalizationHelper.ImportStringResource(fileName)); } catch (Exception ex) { Dialog.Ok("Localization", "Localization - Importing Xaml Resource", ex.Message); StatusBand.Hide(); await Task.Factory.StartNew(GC.Collect); return; } var resourceDictionary = Application.Current.Resources.MergedDictionaries.LastOrDefault(); var imageItem = new ImageListBoxItem { Tag = resourceDictionary?.Source.OriginalString ?? "Unknown", Content = resourceDictionary?.Source.OriginalString ?? "Unknown", Image = FindResource("Vector.Translate") as Canvas, Author = "Recognized as " + pieces[1] }; StatusBand.Hide(); ResourceListBox.Items.Add(imageItem); ResourceListBox.ScrollIntoView(imageItem); CommandManager.InvalidateRequerySuggested(); }
private async void DownloadButton_Click(object sender, RoutedEventArgs e) { #region Save as var save = new Microsoft.Win32.SaveFileDialog { FileName = "ScreenToGif " + Global.UpdateModel.Version + (IsInstaller ? " Setup" : ""), DefaultExt = IsInstaller ? ".msi" : ".exe", Filter = IsInstaller ? "ScreenToGif setup|*.msi" : "ScreenToGif executable|*.exe" }; var result = save.ShowDialog(); if (!result.HasValue || !result.Value) { return; } if (save.FileName == Assembly.GetExecutingAssembly().Location) { Dialog.Ok(Title, LocalizationHelper.Get("Update.Filename.Warning"), LocalizationHelper.Get("Update.Filename.Warning2"), Icons.Warning); return; } #endregion //After downloading, remove the notification and set the global variable to null; DownloadButton.IsEnabled = false; StatusBand.Info("Downloading..."); DownloadProgressBar.Visibility = Visibility.Visible; var tempFilename = !IsInstaller?save.FileName.Replace(".exe", DateTime.Now.ToString(" hh-mm-ss fff") + ".zip") : save.FileName; #region Download try { using (var webClient = new WebClient()) { webClient.Credentials = CredentialCache.DefaultNetworkCredentials; webClient.Proxy = WebHelper.GetProxy(); await webClient.DownloadFileTaskAsync(new Uri(IsInstaller ? Global.UpdateModel.InstallerDownloadUrl : Global.UpdateModel.PortableDownloadUrl), tempFilename); } } catch (Exception ex) { LogWriter.Log(ex, "Download updates"); DownloadButton.IsEnabled = true; DownloadProgressBar.Visibility = Visibility.Hidden; StatusBand.Hide(); Dialog.Ok("Update", "Error while downloading", ex.Message); return; } #endregion //If cancelled. if (!IsLoaded) { StatusBand.Hide(); return; } #region Installer if (IsInstaller) { if (!Dialog.Ask(Title, LocalizationHelper.Get("Update.Install.Header"), LocalizationHelper.Get("Update.Install.Description"))) { return; } try { Process.Start(tempFilename); } catch (Exception ex) { LogWriter.Log(ex, "Starting the installer"); StatusBand.Hide(); Dialog.Ok(Title, "Error while starting the installer", ex.Message); return; } Global.UpdateModel = null; Environment.Exit(25); } #endregion #region Unzip try { //Unzips the only file. using (var zipArchive = ZipFile.Open(tempFilename, ZipArchiveMode.Read)) zipArchive.Entries.First(x => x.Name.EndsWith(".exe")).ExtractToFile(save.FileName, true); } catch (Exception ex) { LogWriter.Log(ex, "Unziping update"); DownloadButton.IsEnabled = true; DownloadProgressBar.Visibility = Visibility.Hidden; StatusBand.Hide(); Dialog.Ok("Update", "Error while unzipping", ex.Message); return; } #endregion Global.UpdateModel = null; #region Delete temporary zip and run try { File.Delete(tempFilename); Process.Start(save.FileName); } catch (Exception ex) { LogWriter.Log(ex, "Finishing update"); DownloadButton.IsEnabled = true; DownloadProgressBar.Visibility = Visibility.Hidden; StatusBand.Hide(); Dialog.Ok(Title, "Error while finishing the update", ex.Message); return; } #endregion GC.Collect(); DialogResult = true; }
/// <summary> /// Shows a Ok dialog. /// </summary> /// <param name="title">The title of the window.</param> /// <param name="instruction">The main instruction.</param> /// <param name="observation">A complementar observation.</param> /// <param name="icon">The image of the dialog.</param> /// <returns>True if Ok</returns> public static bool Ok(string title, string instruction, string observation, Icons icon = Icons.Error) { var dialog = new Dialog(); dialog.PrepareOk(title, instruction, observation.Replace(@"\n", Environment.NewLine).Replace(@"\r", ""), icon); var result = dialog.ShowDialog(); return result.HasValue && result.Value; }
private async void DownloadButton_Click(object sender, RoutedEventArgs e) { #region Save as var save = new Microsoft.Win32.SaveFileDialog { FileName = "ScreenToGif", // + Element.XPathSelectElement("tag_name").Value, DefaultExt = ".exe", Filter = "ScreenToGif executable (.exe)|*.exe" }; var result = save.ShowDialog(); if (!result.HasValue || !result.Value) { return; } #endregion DownloadButton.IsEnabled = false; StatusBand.Info("Downloading..."); DownloadProgressBar.Visibility = Visibility.Visible; var tempFilename = save.FileName.Replace(".exe", DateTime.Now.ToString(" hh-mm-ss fff") + ".zip"); #region Download try { using (var webClient = new WebClient()) { webClient.Credentials = CredentialCache.DefaultNetworkCredentials; await webClient.DownloadFileTaskAsync(new Uri(Element.XPathSelectElement("assets").FirstNode.XPathSelectElement("browser_download_url").Value), tempFilename); } } catch (Exception ex) { LogWriter.Log(ex, "Download updates"); DownloadButton.IsEnabled = true; DownloadProgressBar.Visibility = Visibility.Hidden; Dialog.Ok("Update", "Error while downloading", ex.Message); return; } #endregion //If cancelled. if (!IsLoaded) { return; } #region Unzip try { //Deletes if already exists. if (File.Exists(save.FileName)) { File.Delete(save.FileName); } //Unzips the only file. using (var zipArchive = ZipFile.Open(tempFilename, ZipArchiveMode.Read)) { zipArchive.Entries.First(x => x.Name.EndsWith(".exe")).ExtractToFile(save.FileName); } } catch (Exception ex) { LogWriter.Log(ex, "Unziping update"); DownloadButton.IsEnabled = true; DownloadProgressBar.Visibility = Visibility.Hidden; Dialog.Ok("Update", "Error while unzipping", ex.Message); return; } #endregion //If cancelled. if (!IsLoaded) { return; } #region Delete temporary zip and run try { File.Delete(tempFilename); Process.Start(save.FileName); } catch (Exception ex) { LogWriter.Log(ex, "Finishing update"); DownloadButton.IsEnabled = true; DownloadProgressBar.Visibility = Visibility.Hidden; Dialog.Ok("Update", "Error while finishing the update", ex.Message); return; } #endregion DialogResult = true; }