/// <summary> /// Метод, которое сплитит строку и возвращает результат выражения. /// </summary> /// <param name="expr"> Строка с ппримером. </param> /// <returns></returns> public double Calculate(string expr) { try { string[] problem = expr.Split(' '); double a = double.Parse(problem[0].ToString()); double b = double.Parse(problem[2].ToString()); if (double.IsNaN(Math.Round(operations[problem[1]](a, b), 3))) { throw new Exception("Результат не является числом."); } else if (problem[1] == "/" && b == 0) { throw new Exception("Деление на 0."); } else if (!operations.ContainsKey(problem[1])) { throw new Exception("Некорректно введенная операция."); } return(operations[problem[1]](a, b)); } catch (Exception ex) { // Вызов события. Можно вызвать без точки, но так безопаснее. ErrorNotification?.Invoke(ex.Message); throw ex; } }
static void AddPathFromProjectItem(List <string> basePaths, Project projectItem) { if (projectItem == null) { return; } try { // Project var projectFileName = projectItem.FileName; if (!string.IsNullOrWhiteSpace(projectFileName)) { if (projectItem.Properties.Item("FullPath").Value is string fullPath) { basePaths.Add(fullPath); } } else { // Folder for (var i = 1; i <= projectItem.ProjectItems.Count; i++) { AddPathFromProjectItem(basePaths, projectItem.ProjectItems.Item(i).Object as Project); } } } catch (Exception err) { ErrorNotification.EmailError(err); } }
public static void Invoke(TargetAction action, CleanupOptions cleanupOptions) { try { var projects = SolutionActions.FindProjects(DteServiceProvider.Instance); for (var i = 0; i < projects.Count; i++) { var currentProject = projects[i]; if (currentProject.ProjectItems == null) { continue; } if (currentProject.FullName.ToLower().EndsWith(".shproj")) { continue; } for (var j = 1; j < currentProject.ProjectItems.Count; j++) { ActionCSharpOnProjectItem.Action(currentProject.ProjectItems.Item(j), action, cleanupOptions); } } } catch (Exception e) { ErrorNotification.EmailError(e); ProcessActions.GeeksProductivityToolsProcess(); } }
async void MenuItemCallback(object sender, EventArgs e) { try { var fileName = GetSelectedItem().Get(f => f.ToLower()); if (fileName == null) { return; } var workingDirectory = Path.GetDirectoryName(fileName); var projectFolder = FindProjectFolder(workingDirectory); if (projectFolder != null) { workingDirectory = projectFolder; } await System.Threading.Tasks.Task.Run(() => Process.Start(new ProcessStartInfo { WorkingDirectory = workingDirectory, UseShellExecute = false, FileName = "cmd.exe", Arguments = "/c \"\"" + fileName + "\"\"" })); } catch (Exception err) { ErrorNotification.EmailError(err); } }
void KillSelected() { foreach (ProcHolder holder in listBoxProcess.SelectedItems) { if (holder.Process != null) { try { var prc = System.Diagnostics.Process.GetProcessById(holder.Process.ProcessID); if (prc != null) { prc.Kill(); } else { MessageBox.Show("Cannot find process with id " + holder.Process.ProcessID, "Error (on FormAttacher.cs line 191)", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception err) { ErrorNotification.EmailError(err); } } } System.Threading.Thread.Sleep(100); RefreshList(); }
protected virtual async Task RunAsync(ProjectItem item) { ProjectItemDetails = new ProjectItemDetailsType(item); if (IsReportOnlyMode) { await RefreshResultAsync(item.ToSyntaxNode()); } UNModifiedProjectItemDetails = ProjectItemDetails; var initialSourceNode = CleanUpAsync(ProjectItemDetails.InitialSourceNode); if (!IsReportOnlyMode) { try { var result = await initialSourceNode; await SaveResultAsync(result); } catch (Exception ex) { ErrorNotification.WriteErrorToFile(ex); } } }
public static void Invoke(TargetAction action, Definition.CodeCleanerType[] type) { try { var projects = DteServiceProvider.Instance.ActiveSolutionProjects as Array; var currentProject = projects.GetValue(0) as Project; if (currentProject.ProjectItems == null) { return; } if (currentProject.FullName.ToLower().EndsWith(".shproj")) { MessageBox.Show("Clean up can't be called direlctly on Shared Project", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } for (var i = 1; i <= currentProject.ProjectItems.Count; i++) { ActionCSharpOnProjectItem.Action(currentProject.ProjectItems.Item(i), action, type); } } catch (Exception e) { ErrorNotification.EmailError(e); ProcessActions.GeeksProductivityToolsProcess(); } }
private async void ShowErrorMessage(FireErrorMessage message) { try { string errorMessage = null; if (message == null || string.IsNullOrEmpty(message.ErrorMessage)) { errorMessage = AppResources.Values.GetString("MessageError"); ErrorNotification.Show(errorMessage); } else { errorMessage = message.ErrorMessage; } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ErrorNotification.Show(errorMessage); }); } catch (Exception ex) { _logger.LogError(ex, "Show error message failed."); } }
/// <summary> /// Gathers information for the last error (if any error is available) /// and reports it to BugSnag using information from the application /// configuration file and other defaults /// </summary> /// <param name="extraData">Any extra data to pass when reporting this error</param> public void Notify(object extraData) { // If we're a web application, we can report errors automagically if (HttpContext.Current != null) { // If we have errors... if (HttpContext.Current.AllErrors != null && HttpContext.Current.AllErrors.Any()) { // ... go through all of the errors and report them List <Event> events = new List <Event>(); events.Add(ProcessExceptions( HttpContext.Current.AllErrors.ToList(), HttpContext.Current.Request.Path, GetDefaultUserId(), extraData) ); // Send the notification: ErrorNotification notification = new ErrorNotification() { Api_Key = this.apiKey, Events = events }; SendNotification(notification, this.useSSL); } } // If we're not a web application, we're SOL ATM (call another method) }
public override void Run(DTE2 app) { try { var basePaths = Utils.FindSolutionDirectories(app); if (basePaths == null || basePaths.Count() == 0) { return; } var repository = new Repository(/*basePath*/); var loader = GetLoaderAgent(basePaths, repository); var filterer = new Filterer(basePaths, repository); var form = new FinderForm(GetTitle(), GetColor(), loader, filterer, defaultSearchTerm: app.GetSelectedText()); if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK) { var foundItem = form.GetSelectedItem(); FoundItemsBank.Items = filterer.FoundItems; GotoItem(app, basePaths, foundItem); } else { app.StatusBar.Text = "Ready"; } } catch (Exception e) { ErrorNotification.EmailError(e); } }
/// <summary> /// Sends current set of events to BugSnag via a JSON post /// </summary> /// <param name="notification">The notification to send</param> /// <param name="useSSL">Indicates the post should use SSL when sending JSON data</param> private void SendNotification(ErrorNotification notification, bool useSSL) { string serializedJSON = notification.SerializeToString(); // Create a byte array: byte[] byteArray = Encoding.UTF8.GetBytes(serializedJSON); // Post JSON to server: WebRequest request; if (useSSL) { request = WebRequest.Create(httpsUrl); } else { request = WebRequest.Create(httpUrl); } request.Method = WebRequestMethods.Http.Post; request.ContentType = "application/json"; request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); // Get the response. See https://bugsnag.com/docs/notifier-api for response codes var response = request.GetResponse(); }
public static void Invoke(TargetAction action, CleanupOptions cleanupOptions) { try { var projects = SolutionActions.FindProjects(DteServiceProvider.Instance); for (var i = 0; i < projects.Count; i++) { var currentProject = projects[i]; if (currentProject.ProjectItems == null) { continue; } if (currentProject.FullName.EndsWith(".shproj", StringComparison.OrdinalIgnoreCase)) { continue; } for (var j = 1; j < currentProject.ProjectItems.Count; j++) { ActionCSharpOnProjectItem.Action(currentProject.ProjectItems.Item(j), action, cleanupOptions); } } } catch (Exception e) { ErrorNotification.WriteErrorToFile(e); ErrorNotification.WriteErrorToOutputWindow(e); ProcessActions.GeeksProductivityToolsProcess(); } }
public override void Run(DTE2 app) { try { if (app.ActiveDocument == null) { app.StatusBar.Text = "No Active Document"; return; } var sisterFile = app.ActiveDocument.FullName.FindSisterFile(); if (sisterFile.HasValue() && File.Exists(sisterFile)) { sisterFile = sisterFile.WrapInQuatation(); // handle white spaces in the path app.ExecuteCommand("File.OpenFile", sisterFile); app.StatusBar.Text = "Ready"; } else { app.StatusBar.Text = "File Not found: " + sisterFile; } } catch (Exception err) { ErrorNotification.EmailError(err); } }
public static void DoCleanup(ProjectItem item, CodeCleanerType[] actionType, bool fileWindowMustBeOpend = false) { if (!item.IsCsharpFile() || item.IsCSharpDesignerFile()) { return; } try { var path = item.Properties.Item("FullPath").Value.ToString(); if (path.EndsWithAny(new[] { "AssemblyInfo.cs", "TheApplication.cs" })) { return; } var window = item.Open(Constants.vsViewKindCode); window.Activate(); foreach (var actionTypeItem in actionType) { CodeCleanerHost.Run(item, actionTypeItem); } if (fileWindowMustBeOpend == false) { window.Close(vsSaveChanges.vsSaveChangesYes); } } catch (Exception e) { ErrorNotification.EmailError(e); ProcessActions.GeeksProductivityToolsProcess(); } }
public static void GotoItem(DTE2 app, string[] basePaths, Item item) { if (item != null) { try { if (!item.FileName.HasValue()) { return; } app.ItemOperations.OpenFile(item.FullPath, EnvDTE.Constants.vsViewKindAny); var selection = app.ActiveDocument.Selection as TextSelection; selection?.MoveTo(item.LineNumber, item.Column, Extend: false); if (Settings.Default.TrackItemInSolutionExplorer) { TrackInSolutionExplorer(app, item); } } catch (Exception err) { ErrorNotification.EmailError(err); } } }
public static void Invoke(TargetAction action, CleanupOptions cleanupOptions) { try { var projects = DteServiceProvider.Instance.ActiveSolutionProjects as Array; var currentProject = projects.GetValue(0) as Project; if (currentProject.ProjectItems == null) { return; } if (currentProject.FullName.EndsWith(".shproj", StringComparison.OrdinalIgnoreCase)) { System.Windows.MessageBox .Show("Clean up can't be called direlctly on Shared Project", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } for (var i = 1; i <= currentProject.ProjectItems.Count; i++) { ActionCSharpOnProjectItem.Action(currentProject.ProjectItems.Item(i), action, cleanupOptions); } } catch (Exception e) { ErrorNotification.WriteErrorToOutputWindow(e); ErrorNotification.WriteErrorToFile(e); ProcessActions.GeeksProductivityToolsProcess(); } }
void Awake() { errorNotification = addMovieScreen.errorNotification; errorNotification.MessageSet.AddListener(ShowErrorMessage); editDoneButton.OnClick.AddListener(addMovieScreen.SaveMovie); returnButton.OnClick.AddListener(Return); }
public void ShowError(Exception exception, IErrorContainer errorContainer) { if (exception == null) { return; } ErrorContainer errorGrid = (ErrorContainer)errorContainer; if (!_dispatcher.CheckAccess()) { _dispatcher.BeginInvoke(() => ShowError(exception, errorGrid)); return; } ErrorNotification errorNotification = new ErrorNotification(); errorGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); errorNotification.SetValue(Grid.RowProperty, errorGrid.RowDefinitions.Count - 1); errorGrid.Children.Add(errorNotification); errorGrid.UpdateLayout(); // Force OnApplyTemplate for ErrorNotification errorNotification.Show(exception); }
public Task Handle(ErrorNotification notification, CancellationToken cancellationToken) { return(Task.Run(() => { Console.WriteLine($"ERRO: '{notification.Error} \n {notification.StackTraceError}'"); })); }
/// <inheritdoc/> protected override void OnNavigatedFrom(NavigationEventArgs e) { Messenger.Default.Unregister <FireErrorMessage>(this, msg => ShowErrorMessage(msg)); Messenger.Default.Unregister <FireInfoMessage>(this, msg => ShowInfoMessage(msg)); ErrorNotification.Dismiss(); InfoNotification.Dismiss(); }
public UserLogins() { Error = new ErrorNotification(); Successful = new SuccessfulNotification(); EmployeeManagementDBContext context = new EmployeeManagementDBContext(); AccountService = new Accounts(context); }
/// <summary> /// This handler is called, whenever a message on the subscribed topic is received. /// </summary> /// <param name="message"> is the received message.</param> protected override void ReceiveMessage(ErrorNotification message) { Debug.Log("Message reveived at subscriber. Send message to Log Text Manager"); //LogText.Instance.SendOperatorLogMessage(message.msg, LogText.LogLevel.error); lastMessage = message.msg; newMessage = true; Debug.Log("after sending to log"); }
/// <summary> /// This handler is called, whenever a message on the subscribed topic is received. /// </summary> /// <param name="message"> is the received message.</param> protected override void ReceiveMessage(ErrorNotification message) { // Split operator and roboy log with code 0 for operator log, 1 for roboy log if (message.code == 0) { LogSubscriber.Instance.EnqueueOperatorMessage(message); } }
/// <summary> /// Method to add exercises to user tracker /// </summary> /// <param name="user">User to which you want to add exercise</param> /// <param name="exercise">Exercise you want to add</param> /// <param name="exerciseStart">Date when you have done exercise</param> /// <param name="exerciseEnd">Date when you have finished exercise</param> /// <param name="units">Specific unit of exercise (distance\times etc.)</param> public void AddNewExercise(User user, Exercises exercise, DateTime exerciseStart, DateTime exerciseEnd, double units) { var statisticService = new StatisticService(); statisticService.StatusNotification += NotificationManager.SendStatusNotification; statisticService.ErrorNotification += NotificationManager.SendErrorNotification; switch (exercise) { case Exercises.PushUps: var newPushUps = new PushUpSeries { Name = $"PushUps #{user.PushUps.Count + 1}", ExerciseStart = exerciseStart, ExerciseEnd = exerciseEnd, ExerciseTimeSpan = exerciseEnd - exerciseStart, Count = (int)units, }; user.PushUps.Add(newPushUps); StatusNotification?.Invoke($"Push Ups #{user.PushUps.Count} for user {user.Name} successfully added!"); user.AvaragePushUps = statisticService.GetAverageStatistic(user, exercise); break; case Exercises.Run: var newRun = new Run { Name = $"Run #{user.Runs.Count + 1}", ExerciseStart = exerciseStart, ExerciseEnd = exerciseEnd, ExerciseTimeSpan = exerciseEnd - exerciseStart, Distance = units, }; user.Runs.Add(newRun); StatusNotification?.Invoke($"Run #{user.Runs.Count} for user {user.Name} successfully added!"); user.AvarageRunDistance = statisticService.GetAverageStatistic(user, exercise); break; case Exercises.Squats: var newSquats = new SquatSeries { Name = $"Squats #{user.Squats.Count + 1}", ExerciseStart = exerciseStart, ExerciseEnd = exerciseEnd, ExerciseTimeSpan = exerciseEnd - exerciseStart, Count = (int)units, }; user.Squats.Add(newSquats); StatusNotification?.Invoke($"Squats #{user.Squats.Count} for user {user.Name} successfully added!"); user.AvarageSquats = statisticService.GetAverageStatistic(user, exercise); break; default: ErrorNotification?.Invoke("No such Exercise!"); break; } user.AvarageExercisePulse = statisticService.GetPulsePerMinute(user, exercise); }
public async Task <ErrorNotification> CreateAsync(ErrorNotification errorNotification) { await Task.Run(() => { var json = JsonSerializer.Serialize(errorNotification); _logger.LogError("{Error}", json); }); return(errorNotification); }
private void ShowErrorMessage(string title, string content) { ErrorNotification.Raise( new Notification { Content = content, Title = title }); }
public override async Task <SyntaxNode> CleanUpAsync(SyntaxNode initialSourceNode) { var item = ProjectItemDetails.ProjectItem; try { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); item.Open(Constants.vsViewKindCode); var document = item.Document; document.Activate(); try { document.DTE.ExecuteCommand(UsingsCommands.RemoveAndSortCommandName); } catch (Exception ex) { if (ex.Message != "Command \"Edit.RemoveAndSort\" is not available.") { throw; } document.Activate(); document.DTE.ExecuteCommand(UsingsCommands.RemoveAndSortCommandName); } var doc = (EnvDTE.TextDocument)(document.Object("TextDocument")); var p = doc.StartPoint.CreateEditPoint(); var s = p.GetText(doc.EndPoint); var modified = SyntaxFactory.ParseSyntaxTree(s); if (IsReportOnlyMode && !IsEquivalentToUNModified(await modified.GetRootAsync())) { CollectMessages(new ChangesReport(initialSourceNode) { LineNumber = 1, Column = 1, Message = "Your Using usage is not good", Generator = nameof(UsingDirectiveOrganizer) }); document.Undo(); return(initialSourceNode); } document.Save(); } catch (Exception e) { ErrorNotification.WriteErrorToFile(e, initialSourceNode.GetFilePath()); ErrorNotification.WriteErrorToOutputWindow(e, initialSourceNode.GetFilePath()); ProcessActions.GeeksProductivityToolsProcess(); } return(item.ToSyntaxNode()); }
public async Task Publish_RequiredHandlerReturnsError_ReturnsError() { var session = CreateSession(); var notification = new ErrorNotification(); var response = await session.PublishNotification(notification); Assert.True(response.HasErrors); Assert.Equal(ErrorCodes.Test, response.Error.Code); }
protected override void Write(LogEventInfo logEvent) { var logMessage = Layout.Render(logEvent); var source = logEvent.LoggerName?.Split('.').Last() ?? ""; var notification = new ErrorNotification(logMessage) { Source = source }; ErrorOccured?.Invoke(this, new ErrorNotificationEventArgs(notification)); }
private void ReportError(string titleId, string message) { DispatchOnUiThread(() => { var notification = new ErrorNotification(message); notification.TitleTextId = titleId; Notifications.ShowNotifications(new List <INotification> { notification }); }); }