public static Ok ( string title, string instruction, string observation, Icons icon = Icons.Error ) : bool | ||
title | string | The title of the window. |
instruction | string | The main instruction. |
observation | string | A complementar observation. |
icon | Icons | The image of the dialog. |
리턴 | bool |
private void Add_Executed(object sender, ExecutedRoutedEventArgs e) { var ofd = new OpenFileDialog { AddExtension = true, CheckFileExists = true, Title = "Open a Resource Dictionay", Filter = "Resource Dictionay (*.xaml)|*.xaml;" }; var result = ofd.ShowDialog(); if (result.HasValue && result.Value) { #region Validation var subs = ofd.FileName.Substring(ofd.FileName.IndexOf("StringResources")); if (Application.Current.Resources.MergedDictionaries.Any(x => 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 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)) { var resourceDictionary = Application.Current.Resources.MergedDictionaries.LastOrDefault(); var imageItem = new ImageListBoxItem(); imageItem.Tag = resourceDictionary.Source.OriginalString; imageItem.Content = resourceDictionary.Source.OriginalString; imageItem.Image = FindResource("Vector.Translate") as Canvas; imageItem.Author = "Recognized as " + pieces[1]; ResourceListBox.Items.Add(imageItem); } } }
private async Task <IEnumerable <string> > GetProperCulturesAsync() { IEnumerable <string> allCodes = await Task.Factory.StartNew(() => CultureInfo.GetCultures(CultureTypes.AllCultures).Where(x => !string.IsNullOrEmpty(x.Name)).Select(x => x.Name)); try { IEnumerable <string> downloadedCodes = await GetLanguageCodesAsync(); IEnumerable <string> properCodes = await Task.Factory.StartNew(() => allCodes.Where(x => downloadedCodes.Contains(x))); if (properCodes == null) { return(allCodes); } return(properCodes); } catch (Exception ex) { Dispatcher.Invoke(() => Dialog.Ok("Translator", "Translator - Getting Language Codes", ex.Message + Environment.NewLine + "Loading all local language codes.")); } GC.Collect(); return(allCodes); }
private void FeedbackPreview_Loaded(object sender, RoutedEventArgs e) { try { MainBrowser.NavigateToString(Html); } catch (Exception ex) { LogWriter.Log(ex, "Displaying the preview"); Dialog.Ok("Feedback Preview", "It was not possible to display the content", ex.Message); } }
private void WhenBothLoaded() { _playerLoadedCount++; if (_playerLoadedCount > 1) { #region Visibility / IsEnable SelectionSlider.IsEnabled = true; OkButton.IsEnabled = true; Splitter.Visibility = Visibility.Visible; DetailsGrid.Visibility = Visibility.Visible; LoadingLabel.Visibility = Visibility.Collapsed; if (_lowerPlayer.NaturalVideoWidth <= 0 || _upperPlayer.NaturalVideoWidth <= 0) { Dialog.Ok(FindResource("ImportVideo.Title") as string, "Impossible to load video", "Looks like a codec is missing, but it may be anything else."); OkButton.IsEnabled = false; return; } #endregion //Events used to show the actual frames. _lowerPlayer.Changed += LowerPlayer_Changed; _upperPlayer.Changed += UpperPlayer_Changed; SelectionSlider.Maximum = _upperPlayer.NaturalDuration.TimeSpan.TotalMilliseconds; LowerSelectionImage.Source = PreviewFrame(_lowerPlayer); UpperSelectionImage.Source = PreviewFrame(_upperPlayer); SelectionSlider.LowerValue = 0; SelectionSlider.UpperValue = SelectionSlider.Maximum; Dispatcher.InvokeAsync(() => { LowerSelectionImage.Source = PreviewFrame(_lowerPlayer); }); Dispatcher.InvokeAsync(() => { UpperSelectionImage.Source = PreviewFrame(_upperPlayer); }); MinWidth = Width; } }
private async void Save_Executed(object sender, ExecutedRoutedEventArgs e) { StatusBand.Info(LocalizationHelper.Get("S.Localization.Exporting")); if (!(ResourceListBox.SelectedItem is ImageListBoxItem selected)) { return; } var source = selected.Content.ToString(); var subs = source.Substring(source.IndexOf("StringResources", StringComparison.InvariantCulture)); var sfd = new SaveFileDialog { AddExtension = true, Filter = LocalizationHelper.Get("S.Localization.File.Resource") + " (*.xaml)|*.xaml", Title = LocalizationHelper.Get("S.Localization.SaveResource"), FileName = subs }; var result = sfd.ShowDialog(); if (result.HasValue && result.Value) { try { //Pass the UI parameters to the task. var fileName = sfd.FileName; var index = selected.Index; await Task.Factory.StartNew(() => LocalizationHelper.SaveSelected(index, fileName)); } catch (Exception ex) { LogWriter.Log(ex, "Impossible to save the resource"); Dialog.Ok("Impossible to Save", "Impossible to save the Xaml file", ex.Message, Icons.Warning); } } StatusBand.Hide(); CommandManager.InvalidateRequerySuggested(); }
private async void Save_Executed(object sender, ExecutedRoutedEventArgs e) { StatusBand.Info("Exporting resource..."); var sfd = new SaveFileDialog { AddExtension = true, Filter = "Resource Dictionary (*.xaml)|*.xaml", Title = "Save Resource Dictionary" }; var source = ((ImageListBoxItem)ResourceListBox.SelectedItem).Content.ToString(); var subs = source.Substring(source.IndexOf("StringResources")); sfd.FileName = subs; var result = sfd.ShowDialog(); var fileName = sfd.FileName; //We have to access UI components here (can't do that in the task below) var index = ResourceListBox.SelectedIndex; if (result.HasValue && result.Value) { try { await Task.Factory.StartNew(() => LocalizationHelper.SaveSelected(index, fileName)); } catch (Exception ex) { Dialog.Ok("Impossible to Save", "Impossible to save the Xaml file", ex.Message, Dialog.Icons.Warning); } } StatusBand.Hide(); CommandManager.InvalidateRequerySuggested(); }
private async void DownloadButton_Click(object sender, RoutedEventArgs e) { #region Save as var save = new Microsoft.Win32.SaveFileDialog { FileName = "ScreenToGif" + (IsInstaller ? " Setup " + Element.XPathSelectElement("tag_name").Value : ""), DefaultExt = IsInstaller ? ".msi" : ".exe", Filter = IsInstaller ? "ScreenToGif setup (.msi)|*.msi" : "ScreenToGif executable (.exe)|*.exe" }; var result = save.ShowDialog(); if (!result.HasValue || !result.Value) { return; } if (save.FileName == Assembly.GetExecutingAssembly().Location) { Dialog.Ok(Title, this.TextResource("Update.Filename.Warning"), this.TextResource("Update.Filename.Warning2"), Icons.Warning); return; } #endregion 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 ? Element.XPathSelectElement("assets").LastNode : 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 Installer if (IsInstaller) { if (!Dialog.Ask(Title, this.TextResource("Update.Install.Header"), this.TextResource("Update.Install.Description"))) { return; } try { Process.Start(tempFilename); } catch (Exception ex) { LogWriter.Log(ex, "Starting the installer"); Dialog.Ok(Title, "Error while starting the installer", ex.Message); return; } Environment.Exit(25); } #endregion #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 #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(Title, "Error while finishing the update", ex.Message); return; } #endregion GC.Collect(); DialogResult = true; }
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, Text = FindResource("Encoder.Starting").ToString(), FrameCount = listFrames.Count, Id = a, TokenSource = cancellationTokenSource }; 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 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 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").LastNode.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; }
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 bool InsertFrames(bool after) { try { #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(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) { StartProgress(ActualList.Count, FindResource("Editor.UpdatingFrames").ToString()); //Saves the state before resizing the images. ActionStack.SaveState(ActionStack.EditAction.ImageAndProperties, ActualList, Util.Other.CreateIndexList2(0, ActualList.Count)); 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(RightImage)); var leftPoint = Dispatcher.Invoke(() => Canvas.GetLeft(RightImage)); //The image. context.DrawImage(frameInfo.ImageLocation.SourceFrom(), new Rect(leftPoint, topPoint, RightImage.ActualWidth, RightImage.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)(RightCanvas.ActualWidth * scale), (int)(RightCanvas.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 PngBitmapEncoder(); 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(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) { 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(LeftImage)); var leftPoint = Dispatcher.Invoke(() => Canvas.GetLeft(LeftImage)); //The front image. context.DrawImage(frameInfo.ImageLocation.SourceFrom(), new Rect(leftPoint, topPoint, LeftImage.ActualWidth, LeftImage.ActualHeight)); } //Converts the Visual (DrawingVisual) into a BitmapSource. var bmp = new RenderTargetBitmap((int)(LeftCanvas.ActualWidth * scale), (int)(LeftCanvas.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 PngBitmapEncoder(); 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")}.png"); //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++; } //Saves the state before inserting the images. ActionStack.SaveState(ActionStack.EditAction.Add, _insertIndex, NewList.Count); 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 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 bool InsertFrames(bool after) { try { #region Actual List var actualFrame = ActualList[0].ImageLocation.SourceFrom(); double oldWidth = actualFrame.Width; double oldHeight = actualFrame.Height; //If the canvas size changed. if (Math.Abs(LeftCanvas.ActualWidth - oldWidth) > 0 || Math.Abs(LeftCanvas.ActualHeight - oldHeight) > 0 || Math.Abs(LeftImage.ActualWidth - oldWidth) > 0 || Math.Abs(LeftImage.ActualHeight - oldHeight) > 0) { StartProgress(ActualList.Count, "Drawing Current Images"); foreach (var frameInfo in ActualList) { #region Resize Images // Draws the images into a DrawingVisual component DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext context = drawingVisual.RenderOpen()) { //The back canvas. context.DrawRectangle(new SolidColorBrush(Settings.Default.InsertFillColor), null, new Rect(new Point(0, 0), new Point((int)RightCanvas.ActualWidth, (int)RightCanvas.ActualHeight))); double topPoint = Dispatcher.Invoke(() => Canvas.GetTop(LeftImage)); double 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 RenderTargetBitmap bmp = new RenderTargetBitmap((int)LeftCanvas.ActualWidth, (int)LeftCanvas.ActualHeight, 96, 96, 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.Width; oldHeight = newFrame.Height; //If the canvas size changed. if (Math.Abs(RightCanvas.ActualWidth - oldWidth) > 0 || Math.Abs(RightCanvas.ActualHeight - oldHeight) > 0 || Math.Abs(RightImage.ActualWidth - oldWidth) > 0 || Math.Abs(RightImage.ActualHeight - oldHeight) > 0) { StartProgress(ActualList.Count, "Drawing Current Images"); var folder = Path.GetDirectoryName(ActualList[0].ImageLocation); var insertFolder = Path.GetDirectoryName(NewList[0].ImageLocation); foreach (var frameInfo in NewList) { #region Resize Images // Draws the images into a DrawingVisual component DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext context = drawingVisual.RenderOpen()) { //The back canvas. context.DrawRectangle(new SolidColorBrush(Settings.Default.InsertFillColor), null, new Rect(new Point(0, 0), new Point((int)RightCanvas.ActualWidth, (int)RightCanvas.ActualHeight))); double topPoint = Dispatcher.Invoke(() => Canvas.GetTop(RightImage)); double 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 RenderTargetBitmap bmp = new RenderTargetBitmap((int)RightCanvas.ActualWidth, (int)RightCanvas.ActualHeight, 96, 96, PixelFormats.Pbgra32); bmp.Render(drawingVisual); #endregion #region Save // Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); File.Delete(frameInfo.ImageLocation); var fileName = Path.Combine(folder, String.Format("{0}-{1}.bmp", _insertIndex, NewList.IndexOf(frameInfo))); // 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)); } 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 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 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; }