/// <summary> /// Called when the <see cref="ResetToDefaultsCommand" /> is executed. /// </summary> /// <param name="parameter">The command parameter.</param> private void OnResetToDefaultsCommandExecuted(object parameter) { var activeSettingsName = ActiveSettingsName; var result = MessageBox.Show(Resources.AreYouSureYouWantAll + activeSettingsName + Resources.OptionsViewModel_OnResetToDefaultsCommandExecuted_ToBeResetToTheirDefaults + Environment.NewLine + Environment.NewLine + Resources.ThisActionCannotBeUndone, Resources.CodeMaidConfirmationForReset + activeSettingsName, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No); if (result == MessageBoxResult.Yes) { try { File.Delete(ActiveSettingsPath); RefreshPackageSettings(); ActiveSettings.Reload(); ReloadPagesFromSettings(); MessageBox.Show(string.Format(Resources.CodeMaidHasSuccessfullyReset + activeSettingsName + "."), Resources.CodeMaidReset + activeSettingsName + Resources.Successful, MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine(Resources.UnableToReset + ActiveSettingsName, ex); MessageBox.Show(Resources.CodeMaidWasUnableToReset + activeSettingsName + Resources.SeeOutputWindowForMoreDetails, Resources.CodeMaidReset + activeSettingsName + Resources.Unsuccessful, MessageBoxButton.OK, MessageBoxImage.Error); } } }
/// <summary> /// Called when the <see cref="ExportCommand" /> is executed. /// </summary> /// <param name="parameter">The command parameter.</param> private void OnExportCommandExecuted(object parameter) { if (CheckToSavePendingChangesShouldCancelOperation()) { return; } var activeSettingsName = ActiveSettingsName; var dialog = new Microsoft.Win32.SaveFileDialog { Title = Resources.CodeMaidExport + activeSettingsName, FileName = "CodeMaid", DefaultExt = ".config", Filter = Resources.ConfigFilesConfigConfigAllFiles }; if (dialog.ShowDialog() == true) { try { File.Copy(ActiveSettingsPath, dialog.FileName, true); MessageBox.Show(string.Format(Resources.CodeMaidHasSuccessfullyExported + activeSettingsName + Resources.To0, dialog.FileName), Resources.CodeMaidExport + activeSettingsName + Resources.Successful, MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine(Resources.UnableToExport + activeSettingsName, ex); MessageBox.Show(Resources.CodeMaidWasUnableToExport + activeSettingsName + Resources.SeeOutputWindowForMoreDetails, Resources.CodeMaidExport + activeSettingsName + Resources.Unsuccessful, MessageBoxButton.OK, MessageBoxImage.Error); } } }
/// <summary> /// Called when the <see cref="ExportCommand" /> is executed. /// </summary> /// <param name="parameter">The command parameter.</param> private void OnExportCommandExecuted(object parameter) { if (CheckToSavePendingChangesShouldCancelOperation()) { return; } var activeSettingsName = ActiveSettingsName; var dialog = new Microsoft.Win32.SaveFileDialog { Title = "CodeMaid: Export " + activeSettingsName, FileName = "CodeMaid", DefaultExt = ".config", Filter = "Config files (*.config)|*.config|All Files (*.*)|*.*" }; if (dialog.ShowDialog() == true) { try { File.Copy(ActiveSettingsPath, dialog.FileName, true); MessageBox.Show(string.Format("CodeMaid has successfully exported " + activeSettingsName + " to '{0}'.", dialog.FileName), "CodeMaid: Export " + activeSettingsName + " Successful", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine("Unable to export " + activeSettingsName, ex); MessageBox.Show("CodeMaid was unable to export " + activeSettingsName + ". See output window for more details.", "CodeMaid: Export " + activeSettingsName + " Unsuccessful", MessageBoxButton.OK, MessageBoxImage.Error); } } }
public async Task <CreateResult> CreateProjectAsync(string name, string description, bool isPrivate) { var user = await _storage.GetUserAsync(); if (user == null) { throw new UnauthorizedAccessException(Strings.NotLoginYet); } var result = new CreateResult(); try { var repo = await user.Session.CreateRepoAsync(name, description, isPrivate); result.Project = new Project() { Repo = repo }; return(result); } catch (WebException ex) { OutputWindowHelper.ExceptionWriteLine($"LoginAsync:{ex.Message}", ex); var res = (HttpWebResponse)ex.Response; var statusCode = (int)res.StatusCode; throw new Exception($"错误代码: {statusCode}"); } }
/// <summary> /// Called when the <see cref="ResetToDefaultsCommand" /> is executed. /// </summary> /// <param name="parameter">The command parameter.</param> private void OnResetToDefaultsCommandExecuted(object parameter) { var activeSettingsName = ActiveSettingsName; var result = MessageBox.Show(@"Are you sure you want all " + activeSettingsName + " to be reset to their defaults?" + Environment.NewLine + Environment.NewLine + @"This action cannot be undone.", @"CodeMaid: Confirmation for Reset " + activeSettingsName, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No); if (result == MessageBoxResult.Yes) { try { File.Delete(ActiveSettingsPath); RefreshPackageSettings(); ActiveSettings.Reload(); ReloadPagesFromSettings(); MessageBox.Show(string.Format("CodeMaid has successfully reset " + activeSettingsName + "."), "CodeMaid: Reset " + activeSettingsName + " Successful", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine("Unable to reset " + ActiveSettingsName, ex); MessageBox.Show("CodeMaid was unable to reset " + activeSettingsName + ". See output window for more details.", "CodeMaid: Reset " + activeSettingsName + " Unsuccessful", MessageBoxButton.OK, MessageBoxImage.Error); } } }
public async Task <User> LoginAsync(string username, string password) { try { var ses = await Gitee.Api.SDK.LoginAsync(username, password); var userdetail = await ses.GetUserAsync(); var user = new Shared.User() { Detail = userdetail, Session = ses, Username = username }; return(user); } catch (WebException we) { OutputWindowHelper.ExceptionWriteLine($"LoginAsync:{we.Message}", we); throw we; } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine($"LoginAsync:{ex.Message}", ex); throw ex; } }
/// <summary> /// Builds a <see cref="SetCodeItems" /> of CodeItems based on the specified code model. If /// the document gets marked as stale during execution this process will recursively call /// itself to start over in order to guarantee a valid code model is returned. /// </summary> /// <param name="codeModel">The code model.</param> private void BuildCodeItems(CodeModel codeModel) { try { OutputWindowHelper.DiagnosticWriteLine( string.Format("CodeModelManager.BuildCodeItems started for '{0}'", codeModel.Document.FullName)); codeModel.IsBuilding = true; codeModel.IsStale = false; var codeItems = _codeModelBuilder.RetrieveAllCodeItems(codeModel.Document); if (codeModel.IsStale) { BuildCodeItems(codeModel); return; } codeModel.CodeItems = codeItems; codeModel.IsBuilding = false; OutputWindowHelper.DiagnosticWriteLine( string.Format("CodeModelManager.BuildCodeItems completed for '{0}'", codeModel.Document.FullName)); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine( string.Format("Unable to build code model for '{0}'", codeModel.Document.FullName), ex); codeModel.CodeItems = new SetCodeItems(); codeModel.IsBuilding = false; } }
/// <summary> /// Called when the <see cref="ExportCommand" /> is executed. /// </summary> /// <param name="parameter">The command parameter.</param> private void OnExportCommandExecuted(object parameter) { // Always save first, forcing the configuration file to be created if it does not exist yet. Save(); // Prompt the user for the settings file name and location. var dialog = new Microsoft.Win32.SaveFileDialog { Title = "CodeMaid: Export Settings", FileName = "CodeMaid", DefaultExt = ".settings", Filter = "Settings files (*.settings)|*.settings|All Files (*.*)|*.*" }; if (dialog.ShowDialog() == true) { try { var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); config.SaveAs(dialog.FileName, ConfigurationSaveMode.Full, true); MessageBox.Show(string.Format("CodeMaid has successfully exported settings to '{0}'.", dialog.FileName), "CodeMaid: Export Settings Successful", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine("Unable to export settings", ex); MessageBox.Show("CodeMaid was unable to export settings. See output window for more details.", "CodeMaid: Export Settings Unsuccessful", MessageBoxButton.OK, MessageBoxImage.Error); } } }
/// <summary> /// Loads all lazy initialized values for items within the code model. /// </summary> /// <param name="codeModel">The code model.</param> private void LoadLazyInitializedValues(CodeModel codeModel) { try { OutputWindowHelper.DiagnosticWriteLine( string.Format("CodeModelManager.LoadLazyInitializedValues for '{0}'", codeModel.Document.FullName)); if (Settings.Default.General_Multithread) { Parallel.ForEach(codeModel.CodeItems, x => x.LoadLazyInitializedValues()); } else { foreach (var codeItem in codeModel.CodeItems) { codeItem.LoadLazyInitializedValues(); } } } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine( string.Format("Unable to load lazy initialized values for '{0}'", codeModel.Document.FullName), ex); } }
/// <summary> /// Called when a DispatcherUnhandledException is raised by Visual Studio. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e"> /// The <see cref="DispatcherUnhandledExceptionEventArgs" /> instance containing the event data. /// </param> private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { if (!Settings.Default.General_DiagnosticsMode) { return; } OutputWindowHelper.ExceptionWriteLine("Diagnostics mode caught and marked as handled the following DispatcherUnhandledException raised in Visual Studio", e.Exception); e.Handled = true; }
/// <summary> /// Tries to execute the specified function on a background thread, returning the default of /// the type on error or timeout. /// </summary> /// <typeparam name="T">The result type.</typeparam> /// <param name="func">The function to execute.</param> /// <returns>The result of the function, otherwise the default for the result type.</returns> protected static T TryDefault <T>(Func <T> func) { try { return(func()); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine($"TryDefault caught an exception on '{func}'", ex); return(default);
private void MenuItem_BeforeQueryStatus(object sender, EventArgs e) { var command = (OleMenuCommand)sender; Debug.WriteLine($"MenuItem_BeforeQueryStatus {command.Text} {command.CommandID.ID} "); try { switch ((uint)command.CommandID.ID) { case PackageIds.OpenCreateSnippet: command.Text = Strings.OpenOnGitLabPackage_CreateSnippet; var selectionLineRange = GetSelectionLineRange(); command.Enabled = selectionLineRange.Item1 < selectionLineRange.Item2; break; case PackageIds.IssuesToolWindowCommandId: command.Enabled = true; break; case PackageIds.OpenFromUrl: command.Enabled = Clipboard.ContainsText(TextDataFormat.Text) && Regex.IsMatch(Clipboard.GetText(TextDataFormat.Text), "[a-zA-z]+://[^\\s]*"); command.Text = Strings.OpenFormURL; break; default: // TODO:is should avoid create GitAnalysis every call? var git = GitAnalysis.GetBy(GetActiveFilePath()); if (!git.IsDiscoveredGitRepository) { command.Enabled = false; return; } var type = ToGitLabUrlType(command.CommandID.ID); var targetPath = git.GetGitLabTargetPath(type); if (type == GitLabUrlType.CurrentBranch && targetPath == "master") { command.Visible = false; } else { command.Text = git.GetGitLabTargetDescription(type); command.Enabled = true; } break; } } catch (Exception ex) { var exstr = ex.ToString(); OutputWindowHelper.ExceptionWriteLine(exstr, ex); command.Text = "error:" + ex.GetType().Name; command.Enabled = false; } }
private void SaveHostVersion() { try { var filename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "hostinfo.json"); System.IO.File.WriteAllText(filename, JsonConvert.SerializeObject(HostVersionInfo)); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine("SaveHostVersion", ex); } }
/// <summary> /// Attempts to run code cleanup on the specified document. /// </summary> /// <param name="document">The document for cleanup.</param> /// <param name="isAutoSave">A flag indicating if occurring due to auto-save.</param> internal void Cleanup(Document document, bool isAutoSave = false) { if (!_codeCleanupAvailabilityLogic.ShouldCleanup(document, true)) { return; } // Make sure the document to be cleaned up is active, required for some commands like // format document. document.Activate(); if (_package.ActiveDocument != document) { OutputWindowHelper.WarningWriteLine( string.Format("Activation was not completed before cleaning began for '{0}'", document.Name)); } // Conditionally start cleanup with reorganization. if (Settings.Default.Reorganizing_RunAtStartOfCleanup) { _codeReorderManager.Reorganize(document, isAutoSave); } _undoTransactionHelper.Run( () => !(isAutoSave && Settings.Default.General_SkipUndoTransactionsDuringAutoCleanupOnSave), delegate { var cleanupMethod = FindCodeCleanupMethod(document); if (cleanupMethod != null) { OutputWindowHelper.DiagnosticWriteLine( string.Format("CodeCleanupManager.Cleanup started for '{0}'", document.FullName)); _package.IDE.StatusBar.Text = string.Format("CodeMaid is cleaning '{0}'...", document.Name); // Perform the set of configured cleanups based on the language. cleanupMethod(document, isAutoSave); _package.IDE.StatusBar.Text = string.Format("CodeMaid cleaned '{0}'.", document.Name); OutputWindowHelper.DiagnosticWriteLine( string.Format("CodeCleanupManager.Cleanup completed for '{0}'", document.FullName)); } }, delegate(Exception ex) { OutputWindowHelper.ExceptionWriteLine( string.Format("Stopped cleaning '{0}'", document.Name), ex); _package.IDE.StatusBar.Text = string.Format("CodeMaid stopped cleaning '{0}'. See output window for more details.", document.Name); }); }
/// <summary> /// Tries to execute the specified function on a background thread, returning the default of /// the type on error or timeout. /// </summary> /// <typeparam name="T">The result type.</typeparam> /// <param name="func">The function to execute.</param> /// <returns>The result of the function, otherwise the default for the result type.</returns> protected static T TryDefault <T>(Func <T> func) { try { return(func()); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine( string.Format("TryDefault caught an exception on '{0}'", func), ex); return(default(T)); } }
/// <summary> /// Attempts to load a resource dictionary for the specified theme URI. /// </summary> /// <param name="themeUri">The theme URI.</param> /// <returns>The loaded resource dictionary, otherwise null.</returns> private ResourceDictionary LoadResourceDictionary(Uri themeUri) { try { var dictionary = (ResourceDictionary)Application.LoadComponent(themeUri); dictionary.Source = themeUri; return(dictionary); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine($"Unable to load theme '{themeUri}'", ex); _package.IDE.StatusBar.Text = $"CodeMaid failed to load theme '{themeUri}'. See output window for more details."; return(null); } }
/// <summary> /// Attempts to load a resource dictionary for the specified theme URI. /// </summary> /// <param name="themeUri">The theme URI.</param> /// <returns>The loaded resource dictionary, otherwise null.</returns> private ResourceDictionary LoadResourceDictionary(Uri themeUri) { try { var dictionary = (ResourceDictionary)Application.LoadComponent(themeUri); dictionary.Source = themeUri; return(dictionary); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine($"Unable to load theme '{themeUri}'", ex); _package.IDE.StatusBar.Text = string.Format(Resources.CodeMaidFailedToLoadTheme0SeeOutputWindowForMoreDetails, themeUri); return(null); } }
/// <summary> /// Attempts to get the outlining manager associated with the specified document. /// </summary> /// <param name="document">The document.</param> /// <returns>The associated outlining manager, otherwise null.</returns> private IOutliningManager GetOutliningManager(Document document) { try { _wpfTextView = GetWpfTextView(document); if (_wpfTextView != null && _outliningManagerService != null) { return(_outliningManagerService.GetOutliningManager(_wpfTextView)); } } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine($"Unable to retrieve an outlining manager for '{document.FullName}'", ex); } return(null); }
/// <summary> /// Called when the <see cref="ImportCommand" /> is executed. /// </summary> /// <param name="parameter">The command parameter.</param> private void OnImportCommandExecuted(object parameter) { // Prompt the user for the settings file to import. var dialog = new Microsoft.Win32.OpenFileDialog { Title = "CodeMaid: Import Settings", DefaultExt = ".settings", Filter = "Settings files (*.settings)|*.settings|All Files (*.*)|*.*", CheckFileExists = true }; if (dialog.ShowDialog() == true) { try { // Always save first, forcing the configuration file to be created if it does // not exist yet. Save(); var sectionName = Settings.Default.Context["GroupName"].ToString(); var xDocument = XDocument.Load(dialog.FileName); var settings = xDocument.XPathSelectElements("//" + sectionName); var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); config.GetSectionGroup("userSettings") .Sections[sectionName] .SectionInformation .SetRawXml(settings.Single().ToString()); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("userSettings"); Settings.Default.Reload(); ReloadPagesFromSettings(); MessageBox.Show(string.Format("CodeMaid has successfully imported settings from '{0}'.", dialog.FileName), "CodeMaid: Import Settings Successful", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine("Unable to import settings", ex); MessageBox.Show("CodeMaid was unable to import settings. See output window for more details.", "CodeMaid: Import Settings Unsuccessful", MessageBoxButton.OK, MessageBoxImage.Error); } } }
public void AddHostVersionInfo(string host, ApiVersion apiVersion) { try { if (Uri.TryCreate(host, UriKind.RelativeOrAbsolute, out var uri)) { if (!HostVersionInfo.ContainsKey(uri.Host)) { HostVersionInfo.Add(uri.Host, apiVersion); } } SaveHostVersion(); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine("AddHostVersionInfo", ex); } }
/// <summary> /// Loads all lazy initialized values for items within the code model. /// </summary> /// <param name="codeModel">The code model.</param> private void LoadLazyInitializedValues(CodeModel codeModel) { try { OutputWindowHelper.DiagnosticWriteLine( $"CodeModelManager.LoadLazyInitializedValues for '{codeModel.Document.FullName}'"); foreach (var codeItem in codeModel.CodeItems) { codeItem.LoadLazyInitializedValues(); } } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine( $"Unable to load lazy initialized values for '{codeModel.Document.FullName}'", ex); } }
/// <summary> /// Prompts the user about cleaning up external files. /// </summary> /// <param name="document">The document.</param> /// <returns>True if external files should be cleaned, otherwise false.</returns> private static bool PromptUserAboutCleaningExternalFiles(Document document) { try { var viewModel = new YesNoPromptViewModel { Title = Resources.CodeMaidCleanupExternalFile, Message = document.Name + Resources.IsNotInTheSolutionSoSomeCleanupActionsMayBeUnavailable + Environment.NewLine + Environment.NewLine + Resources.DoYouWantToPerformAPartialCleanup, CanRemember = true }; var response = UIThread.Run(() => { var window = new YesNoPromptWindow { DataContext = viewModel }; return(window.ShowDialog()); }); if (!response.HasValue) { return(false); } if (viewModel.Remember) { var preference = (int)(response.Value ? AskYesNo.Yes : AskYesNo.No); Settings.Default.Cleaning_PerformPartialCleanupOnExternal = preference; Settings.Default.Save(); } return(response.Value); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine("Unable to prompt user about cleaning external files", ex); return(false); } }
/// <summary> /// Called to execute the command. /// </summary> protected override void OnExecute() { base.OnExecute(); Document document = Package.ActiveDocument; if (document != null) { try { FileAttributes originalAttributes = File.GetAttributes(document.FullName); FileAttributes newAttributes = originalAttributes ^ FileAttributes.ReadOnly; File.SetAttributes(document.FullName, newAttributes); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine($"{ Resources.UnableToToggleReadOnlyStateOn}'{document.FullName}'", ex); } } }
/// <summary> /// Prompts the user about reorganizing files with preprocessor conditionals. /// </summary> /// <param name="document">The document.</param> /// <returns>True if files with preprocessor conditionals should be reorganized, otherwise false.</returns> private static bool PromptUserAboutReorganizingPreprocessorConditionals(Document document) { try { var viewModel = new YesNoPromptViewModel { Title = @Resources.CodeMaidReorganizePreprocessorConditionals, Message = string.Format(Resources.ContainsPreprocessorConditionalsEGIfPragmaWhichReorganizationDoesNotCurrentlySupportDoYouWantToReorganizeAnywaysDANGEROUS, document.Name), CanRemember = true }; var response = UIThread.Run(() => { var window = new YesNoPromptWindow { DataContext = viewModel }; return(window.ShowDialog()); }); if (!response.HasValue) { return(false); } if (viewModel.Remember) { var preference = (int)(response.Value ? AskYesNo.Yes : AskYesNo.No); Settings.Default.Reorganizing_PerformWhenPreprocessorConditionals = preference; Settings.Default.Save(); } return(response.Value); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine("Unable to prompt user about reorganizing preprocessor conditionals", ex); return(false); } }
/// <summary> /// Prompts the user about reorganizing files with preprocessor conditionals. /// </summary> /// <param name="document">The document.</param> /// <returns>True if files with preprocessor conditionals should be reorganized, otherwise false.</returns> private static bool PromptUserAboutReorganizingPreprocessorConditionals(Document document) { try { var viewModel = new YesNoPromptViewModel { Title = @"CodeMaid: Reorganize Preprocessor Conditionals", Message = document.Name + " contains preprocessor conditionals (e.g. #if, #pragma) which reorganization does not currently support." + Environment.NewLine + Environment.NewLine + "Do you want to reorganize anyways (DANGEROUS)?", CanRemember = true }; var window = new YesNoPromptWindow { DataContext = viewModel }; var response = window.ShowModal(); if (!response.HasValue) { return(false); } if (viewModel.Remember) { var preference = (int)(response.Value ? AskYesNo.Yes : AskYesNo.No); Settings.Default.Reorganizing_PerformWhenPreprocessorConditionals = preference; Settings.Default.Save(); } return(response.Value); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine("Unable to prompt user about reorganizing preprocessor conditionals", ex); return(false); } }
/// <summary> /// Called when the <see cref="ImportCommand" /> is executed. /// </summary> /// <param name="parameter">The command parameter.</param> private void OnImportCommandExecuted(object parameter) { if (CheckToSavePendingChangesShouldCancelOperation()) { return; } var activeSettingsName = ActiveSettingsName; var dialog = new Microsoft.Win32.OpenFileDialog { Title = Resources.CodeMaidImport + activeSettingsName, DefaultExt = ".config", Filter = Resources.ConfigFilesConfigConfigAllFiles, CheckFileExists = true }; if (dialog.ShowDialog() == true) { try { File.Copy(dialog.FileName, ActiveSettingsPath, true); File.SetAttributes(ActiveSettingsPath, File.GetAttributes(ActiveSettingsPath) & ~FileAttributes.ReadOnly); RefreshPackageSettings(); ActiveSettings.Reload(); ReloadPagesFromSettings(); MessageBox.Show(string.Format(Resources.CodeMaidHasSuccessfullyImported1From0, dialog.FileName, activeSettingsName), Resources.CodeMaidImport + activeSettingsName + Resources.Successful, MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine(Resources._UnableToImport + activeSettingsName, ex); MessageBox.Show(Resources.CodeMaidWasUnableToImport + activeSettingsName + Resources.SeeOutputWindowForMoreDetails, Resources.CodeMaidImport + activeSettingsName + Resources.Unsuccessful, MessageBoxButton.OK, MessageBoxImage.Error); } } }
/// <summary> /// Called to execute the command. /// </summary> protected override void OnExecute() { base.OnExecute(); Document document = Package.ActiveDocument; if (document != null) { try { FileAttributes originalAttributes = File.GetAttributes(document.FullName); FileAttributes newAttributes = originalAttributes ^ FileAttributes.ReadOnly; File.SetAttributes(document.FullName, newAttributes); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine( string.Format("Unable to toggle read only state on '{0}'", document.FullName), ex); } } }
/// <summary> /// Prompts the user about cleaning up external files. /// </summary> /// <param name="document">The document.</param> /// <returns>True if external files should be cleaned, otherwise false.</returns> private static bool PromptUserAboutCleaningExternalFiles(Document document) { try { var viewModel = new YesNoPromptViewModel { Title = @"CodeMaid: Cleanup External File", Message = document.Name + " is not in the solution so some cleanup actions may be unavailable." + Environment.NewLine + Environment.NewLine + "Do you want to perform a partial cleanup?", CanRemember = true }; var window = new YesNoPromptWindow { DataContext = viewModel }; var response = window.ShowModal(); if (!response.HasValue) { return(false); } if (viewModel.Remember) { var preference = (int)(response.Value ? AskYesNo.Yes : AskYesNo.No); Settings.Default.Cleaning_PerformPartialCleanupOnExternal = preference; Settings.Default.Save(); } return(response.Value); } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine("Unable to prompt user about cleaning external files", ex); return(false); } }
public async Task <CreateSnippetResult> CreateSnippetAsync(string title, string fileName, string desc, string code, bool visibility) { CreateSnippetResult result = null; var user = await _storage.GetUserAsync(); if (user == null) { result = new CreateSnippetResult { Success = false, Message = Strings.NotLoginYet }; } else { try { var gists = await user.Session.CreateGists(fileName, code, desc, visibility); result = new CreateSnippetResult { WebUrl = gists.html_url, Success = gists != null, Message = Strings.GistsCreated }; } catch (Exception ex) { OutputWindowHelper.ExceptionWriteLine($"LoginAsync:{ex.Message}", ex); result = new CreateSnippetResult() { Success = false, Message = ex.Message }; } } return(result); }
/// <summary> /// Reorganizes the specified document. /// </summary> /// <param name="document">The document for reorganizing.</param> /// <param name="isAutoSave">A flag indicating if occurring due to auto-save.</param> internal void Reorganize(Document document, bool isAutoSave) { if (!CanReorganize(document)) { return; } _undoTransactionHelper.Run( () => !(isAutoSave && Settings.Default.General_SkipUndoTransactionsDuringAutoCleanupOnSave), delegate { OutputWindowHelper.DiagnosticWriteLine( string.Format("CodeReorderManager.Reorganize started for '{0}'", document.FullName)); _package.IDE.StatusBar.Text = string.Format("CodeMaid is reorganizing '{0}'...", document.Name); // Retrieve all relevant code items (excluding using statements). var rawCodeItems = _codeModelManager.RetrieveAllCodeItems(document).Where(x => !(x is CodeItemUsingStatement)); // Build the code tree based on the current file layout. var codeItems = new SetCodeItems(rawCodeItems); var codeTree = CodeTreeBuilder.RetrieveCodeTree(new CodeTreeRequest(document, codeItems, TreeLayoutMode.FileLayout)); // Recursively reorganize the code tree. RecursivelyReorganize(codeTree); _package.IDE.StatusBar.Text = string.Format("CodeMaid reorganized '{0}'.", document.Name); OutputWindowHelper.DiagnosticWriteLine( string.Format("CodeReorderManager.Reorganize completed for '{0}'", document.FullName)); }, delegate(Exception ex) { OutputWindowHelper.ExceptionWriteLine( string.Format("Stopped reorganizing '{0}'", document.Name), ex); _package.IDE.StatusBar.Text = string.Format("CodeMaid stopped reorganizing '{0}'. See output window for more details.", document.Name); }); }