public void SerializeAsStringMethodSerializesATelemetryCorrectly() { var exceptionTelemetry = new ExceptionTelemetry(); string exceptionAsJson = JsonSerializer.SerializeAsString(exceptionTelemetry); // Expected: {"name":"Microsoft.ApplicationInsights.Exception","time":"0001-01-01T00:00:00.0000000+00:00","data":{"baseType":"ExceptionData","baseData":{"ver":2,"handledAt":"Unhandled","exceptions":[]}}} // Deserialize (Validates a valid JSON string) JObject obj = JsonConvert.DeserializeObject<JObject>(exceptionAsJson); // Validtes 2 random properties Assert.NotNull(exceptionAsJson); Assert.Equal("Microsoft.ApplicationInsights.Exception", obj["name"].ToString()); Assert.Equal("Unhandled", obj["data"]["baseData"]["handledAt"].ToString()); }
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'AccountController.GetSinnerAsAdmin()' public async Task <ActionResult <ResultGroupGetSearchGroups> > GetSinnerAsAdmin() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'AccountController.GetSinnerAsAdmin()' { SINSearchGroupResult ret = new SINSearchGroupResult(); ResultAccountGetSinnersByAuthorization res = new ResultAccountGetSinnersByAuthorization(ret); SINnerGroup sg = new SINnerGroup(); var user = await _signInManager.UserManager.GetUserAsync(User); if (user == null) { var e = new AuthenticationException("User is not authenticated."); res = new ResultAccountGetSinnersByAuthorization(e) { ErrorText = "Unauthorized" }; return(BadRequest(res)); } user.FavoriteGroups = user.FavoriteGroups.GroupBy(a => a.FavoriteGuid).Select(b => b.First()).ToList(); SINnerSearchGroup ssg = new SINnerSearchGroup(sg, user) { MyMembers = new List <SINnerSearchGroupMember>() }; try { var roles = await _userManager.GetRolesAsync(user); ret.Roles = roles.ToList(); ssg.Groupname = user.Email; ssg.Id = Guid.Empty; //get all from visibility List <SINner> mySinners = await _context.SINners.Include(a => a.MyGroup) .Include(a => a.SINnerMetaData.Visibility.UserRights) .OrderByDescending(a => a.UploadDateTime) .Take(200) .ToListAsync(); foreach (var sin in mySinners) { SINnerSearchGroupMember ssgm = new SINnerSearchGroupMember(user, sin); ssg.MyMembers.Add(ssgm); if (sin.MyGroup != null) { SINnerSearchGroup ssgFromSIN = ssg.MySINSearchGroups.FirstOrDefault(a => a.Id == sin.MyGroup.Id); if (ssgFromSIN == null) { ssgFromSIN = new SINnerSearchGroup(sin.MyGroup, user); ssg.MySINSearchGroups.Add(ssgFromSIN); } //add all members of his group var members = await sin.MyGroup.GetGroupMembers(_context, false); foreach (var member in members) { member.MyGroup = sin.MyGroup; member.MyGroup.MyGroups = new List <SINnerGroup>(); SINnerSearchGroupMember sinssgGroupMember = new SINnerSearchGroupMember(user, member); ssgFromSIN.MyMembers.Add(sinssgGroupMember); } sin.MyGroup.PasswordHash = string.Empty; sin.MyGroup.MyGroups = new List <SINnerGroup>(); } } ret.SINGroups.Add(ssg); res = new ResultAccountGetSinnersByAuthorization(ret); return(Ok(res)); } catch (Exception e) { try { await _signInManager.UserManager.GetUserAsync(User); //var tc = new Microsoft.ApplicationInsights.TelemetryClient(); ExceptionTelemetry et = new ExceptionTelemetry(e); et.Properties.Add("user", User.Identity.Name); tc.TrackException(et); } catch (Exception ex) { _logger?.LogError(ex.ToString()); } res = new ResultAccountGetSinnersByAuthorization(e); return(BadRequest(res)); } }
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'AccountController.GetAddSqlDbUser(string, string, string, string)' public async Task <ActionResult <string> > GetAddSqlDbUser(string username, string password, string start_ip_address, string end_ip_address) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'AccountController.GetAddSqlDbUser(string, string, string, string)' { string result = string.Empty; try { if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException(nameof(username)); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException(nameof(password)); } IPAddress startaddress = null; if (!string.IsNullOrEmpty(start_ip_address)) { startaddress = IPAddress.Parse(start_ip_address); } IPAddress endaddress = null; if (!string.IsNullOrEmpty(end_ip_address)) { endaddress = IPAddress.Parse(end_ip_address); } if (string.IsNullOrEmpty(Startup.ConnectionStringToMasterSqlDb)) { throw new ArgumentNullException(nameof(Startup.ConnectionStringToMasterSqlDb)); } try { string cmd = "CREATE LOGIN " + username + " WITH password = '******';"; using (SqlConnection masterConnection = new SqlConnection(Startup.ConnectionStringToMasterSqlDb)) { await masterConnection.OpenAsync(); using (SqlCommand dbcmd = new SqlCommand(cmd, masterConnection)) { dbcmd.ExecuteNonQuery(); } } } catch (SqlException e) { result += e.Message + Environment.NewLine + Environment.NewLine; } //create the user in the master DB try { string cmd = "CREATE USER " + username + " FROM LOGIN " + username + ";"; using (SqlConnection masterConnection = new SqlConnection(Startup.ConnectionStringToMasterSqlDb)) { await masterConnection.OpenAsync(); using (SqlCommand dbcmd = new SqlCommand(cmd, masterConnection)) { dbcmd.ExecuteNonQuery(); } } } catch (SqlException e) { result += e.Message + Environment.NewLine + Environment.NewLine; } //create the user in the sinner_db as well! try { string cmd = "CREATE USER " + username + " FROM LOGIN " + username + ";"; using (SqlConnection masterConnection = new SqlConnection(Startup.ConnectionStringSinnersDb)) { await masterConnection.OpenAsync(); using (SqlCommand dbcmd = new SqlCommand(cmd, masterConnection)) { dbcmd.ExecuteNonQuery(); } } } catch (Exception e) { result += e.Message + Environment.NewLine + Environment.NewLine; } try { string cmd = "ALTER ROLE dbmanager ADD MEMBER " + username + ";"; using (SqlConnection masterConnection = new SqlConnection(Startup.ConnectionStringSinnersDb)) { await masterConnection.OpenAsync(); using (SqlCommand dbcmd = new SqlCommand(cmd, masterConnection)) { dbcmd.ExecuteNonQuery(); } } } catch (Exception e) { bool worked = false; try { string cmd = "EXEC sp_addrolemember 'db_owner', '" + username + "';"; using (SqlConnection masterConnection = new SqlConnection(Startup.ConnectionStringSinnersDb)) { await masterConnection.OpenAsync(); using (SqlCommand dbcmd = new SqlCommand(cmd, masterConnection)) { dbcmd.ExecuteNonQuery(); } } worked = true; } catch (Exception e1) { result += e1 + Environment.NewLine + Environment.NewLine; } if (worked) { result += "User added!" + Environment.NewLine + Environment.NewLine; } else { result += e.Message + Environment.NewLine + Environment.NewLine; } } try { string cmd = "EXEC sp_set_database_firewall_rule N'Allow " + username + "', '" + startaddress + "', '" + endaddress + "';"; using (SqlConnection masterConnection = new SqlConnection(Startup.ConnectionStringSinnersDb)) { await masterConnection.OpenAsync(); using (SqlCommand dbcmd = new SqlCommand(cmd, masterConnection)) { dbcmd.ExecuteNonQuery(); } result += "Firewallrule added: " + startaddress + " - " + endaddress + Environment.NewLine + Environment.NewLine; } } catch (Exception e) { result += e.Message + Environment.NewLine + Environment.NewLine; } return(Ok(result)); } catch (Exception e) { try { var user = await _signInManager.UserManager.GetUserAsync(User); //var tc = new Microsoft.ApplicationInsights.TelemetryClient(); ExceptionTelemetry et = new ExceptionTelemetry(e); et.Properties.Add("user", User.Identity.Name); tc.TrackException(et); } catch (Exception ex) { _logger?.LogError(ex.ToString()); } result += Environment.NewLine + e; if (e is HubException) { return(BadRequest(e)); } HubException hue = new HubException(result, e); return(BadRequest(hue)); } }
public void Execute(MessageContext context, Action next, MiddlewareParameter parameter) { var telemetry = new RequestTelemetry(); var stopwatch = new Stopwatch(); stopwatch.Start(); var name = parameter.Route.Name; if (!string.IsNullOrWhiteSpace(parameter.Saga?.Name)) { name = $"{parameter.Saga?.Name}_{name}"; } try { telemetry.Timestamp = context.DateTimeUtc; telemetry.Id = context.Id; telemetry.Name = name; telemetry.Properties.Add("from", context.Origin.From); telemetry.Properties.Add("version", context.Version); telemetry.Properties.Add("origin", context.Origin.Key); telemetry.Properties.Add("sagaid", context.SagaContext?.Id); telemetry.Properties.Add("replytorequestid", context.ReplyToRequestId); telemetry.Properties.Add("requestid", context.RequestId); telemetry.Context.Operation.Id = $"{context.Id}{context.RetryCount}"; telemetry.Context.Operation.Name = name; telemetry.Context.Operation.ParentId = $"{context.Id}{context.RetryCount}"; telemetry.Source = context.Origin.From; if (!string.IsNullOrWhiteSpace(_configuration.ApplicationName)) { telemetry.Context.Cloud.RoleName = _configuration.ApplicationName; } foreach (var h in context.Headers) { telemetry.Properties.Add(h.Key, h.Value); } telemetry.Metrics.Add("retry", context.RetryCount); next(); telemetry.ResponseCode = "200"; telemetry.Success = true; } catch (Exception exception) { telemetry.ResponseCode = "500"; telemetry.Success = false; var telemetryexception = new ExceptionTelemetry(exception); telemetryexception.Context.Operation.Id = $"{context.Id}{context.RetryCount}"; telemetryexception.Context.Operation.ParentId = $"{context.Id}{context.RetryCount}"; _client.TrackException(telemetryexception); throw; } finally { telemetry.Duration = TimeSpan.FromMilliseconds(stopwatch.ElapsedMilliseconds); _client.TrackRequest(telemetry); } }
private static void RunCustomAIAvailabilityTest(ILogger log) { log.LogInformation($"Entering Run at: {DateTime.Now}"); // [CONFIGURATION_REQUIRED] provide {testName} accordingly for your test function string testName = "AvailabilityTestConsole"; // REGION_NAME is a default environment variable that comes with App Service string location = "Boston, MA"; //"East US"; //Environment.GetEnvironmentVariable("REGION_NAME"); log.LogInformation($"Executing availability test run for {testName} at: {DateTime.Now}"); string operationId = Guid.NewGuid().ToString("N"); Console.WriteLine("Enter: 1 for Github Test, 2 for local Test, other for null Test"); int i = Convert.ToInt32(Console.ReadLine()); var availability = new AvailabilityTelemetry { Id = operationId, Name = testName, RunLocation = location, Success = false }; var stopwatch = new Stopwatch(); stopwatch.Start(); try { switch (i) { case 1: availability.Properties.Add("Test Url", "https://api.github.com/orgs/dotnet/repos"); RunAvailabilityTestGithubDotnet(log); break; case 2: RunAvailabilityTestLocal(log); availability.Properties.Add("Test Url", "http://localhost:5555/"); break; default: RunNotImplemented(log); break; } availability.Success = true; availability.Message = "Availability test from Console"; availability.Properties.Add("Server", "JuanLaptop"); } catch (Exception ex) { availability.Message = ex.Message; availability.Success = false; var exceptionTelemetry = new ExceptionTelemetry(ex); exceptionTelemetry.Context.Operation.Id = operationId; exceptionTelemetry.Properties.Add("TestName", testName); exceptionTelemetry.Properties.Add("TestLocation", location); telemetryClient.TrackException(exceptionTelemetry); } finally { stopwatch.Stop(); availability.Duration = stopwatch.Elapsed; availability.Timestamp = DateTimeOffset.UtcNow; telemetryClient.TrackAvailability(availability); // call flush to ensure telemetry is sent telemetryClient.Flush(); } }
public void TrackException(ExceptionTelemetry telemetry) { client.TrackException(telemetry); }
/// <summary> /// Send an <see cref="ExceptionTelemetry"/> for display in Diagnostic Search. /// </summary> internal void TrackException(ExceptionTelemetry telemetry) { if (telemetry == null) { var exception = new Exception(Utils.PopulateRequiredStringValue(null, "message", typeof(ExceptionTelemetry).FullName)); telemetry = new ExceptionTelemetry(exception) { HandledAt = ExceptionHandledAt.UserCode, }; } this.Track(telemetry); }
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'AccountController.GetDeleteAllSINnersDb()' public async Task <ActionResult <string> > GetDeleteAllSINnersDb() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'AccountController.GetDeleteAllSINnersDb()' { try { var user = await _signInManager.UserManager.GetUserAsync(User); if (user == null) { return(Unauthorized()); } var roles = await _userManager.GetRolesAsync(user); if (!roles.Contains("Administrator")) { return(Unauthorized()); } var count = await _context.SINners.CountAsync(); using (var transaction = _context.Database.BeginTransaction()) { _context.UserRights.RemoveRange(_context.UserRights.ToList()); _context.SINnerComments.RemoveRange(_context.SINnerComments.ToList()); _context.Tags.RemoveRange(_context.Tags.ToList()); _context.SINnerVisibility.RemoveRange(_context.SINnerVisibility.ToList()); _context.SINnerMetaData.RemoveRange(_context.SINnerMetaData.ToList()); _context.SINners.RemoveRange(_context.SINners.ToList()); _context.UploadClients.RemoveRange(_context.UploadClients.ToList()); await _context.SaveChangesAsync(); // Commit transaction if all commands succeed, transaction will auto-rollback // when disposed if either commands fails transaction.Commit(); } return(Ok("Reseted " + count + " SINners")); } catch (Exception e) { try { var user = await _signInManager.UserManager.GetUserAsync(User); //var tc = new Microsoft.ApplicationInsights.TelemetryClient(); ExceptionTelemetry et = new ExceptionTelemetry(e); et.Properties.Add("user", User.Identity.Name); tc.TrackException(et); } catch (Exception ex) { if (_logger != null) { _logger.LogError(ex.ToString()); } } if (e is HubException) { return(BadRequest(e)); } HubException hue = new HubException(e.Message, e); return(BadRequest(hue)); } }
private static async Task TestAvailability(TelemetryClient telemetryClient, HttpClient client, String address, ILogger _logger) { var availability = new AvailabilityTelemetry { Id = Guid.NewGuid().ToString("N"), Name = address, RunLocation = System.Environment.MachineName, Success = false }; string testRunId = availability.Id; availability.Context.Operation.Id = availability.Id; var stopwatch = new Stopwatch(); stopwatch.Start(); DateTimeOffset startTimeTest = DateTimeOffset.UtcNow; try { var request = new HttpRequestMessage() { RequestUri = new Uri(address), Method = HttpMethod.Get }; request.Headers.Add("SyntheticTest-RunId", testRunId); request.Headers.Add("Request-Id", "|" + testRunId); using (var httpResponse = await client.SendAsync(request).ConfigureAwait(false)) { // add test results to availability telemetry property availability.Properties.Add("HttpResponseStatusCode", Convert.ToInt32(httpResponse.StatusCode).ToString()); if (httpResponse.IsSuccessStatusCode) { availability.Success = true; availability.Message = $"Test succeeded with response: {httpResponse.StatusCode}"; _logger.LogTrace($"[Verbose]: {availability.Message}"); } else if (!httpResponse.IsSuccessStatusCode) { availability.Message = $"Test failed with response: {httpResponse.StatusCode}"; _logger.LogWarning($"[Warning]: {availability.Message}"); } } } catch (Exception ex) { // track exception when unable to determine the state of web app availability.Message = ex.Message; var exceptionTelemetry = new ExceptionTelemetry(ex); exceptionTelemetry.Context.Operation.Id = availability.Id; exceptionTelemetry.Properties.Add("TestAddress", address); exceptionTelemetry.Properties.Add("RunLocation", availability.RunLocation); telemetryClient.TrackException(exceptionTelemetry); _logger.LogError($"[Error]: {ex.Message}"); } finally { stopwatch.Stop(); availability.Duration = stopwatch.Elapsed; availability.Timestamp = startTimeTest; telemetryClient.TrackAvailability(availability); _logger.LogInformation($"Availability telemetry for {availability.Name} is sent."); } }
public object Execute(MessageContext context, Func <MessageContext, MiddlewareContext, object> next, MiddlewareContext middlewarecontext) { var stopwatch = new Stopwatch(); stopwatch.Start(); var telemetry = new DependencyTelemetry() { Name = context.EndPoint.Name, Id = context.Identity.Id, Timestamp = context.DateTimeUtc, Target = middlewarecontext.Channel.GetPath(), Data = context.Content, Type = Configuration.ChannelProviderName, }; PopulateContext(telemetry.Context, context); PopulateProperties(telemetry.Properties, context); PopulateMetrics(telemetry.Metrics, context); try { var result = next(context, middlewarecontext); telemetry.Success = true; telemetry.ResultCode = "200"; return(result); } catch (Exception exception) { telemetry.Success = false; telemetry.ResultCode = "500"; var telemetryexception = new ExceptionTelemetry(exception); PopulateContext(telemetryexception.Context, context); PopulateProperties(telemetryexception.Properties, context); PopulateMetrics(telemetryexception.Metrics, context); Client.TrackException(telemetryexception); throw; } finally { telemetry.Duration = TimeSpan.FromMilliseconds(stopwatch.ElapsedMilliseconds); Client.TrackDependency(telemetry); } }
public void ValidateBasicException(InProcessServer server, string requestPath, ExceptionTelemetry expected) { var httpClientHandler = new HttpClientHandler(); httpClientHandler.UseDefaultCredentials = true; Task <HttpResponseMessage> task; using (var httpClient = new HttpClient(httpClientHandler, true)) { task = httpClient.GetAsync(server.BaseHost + requestPath); task.Wait(TestTimeoutMs); } var result = task.Result; server.Dispose(); var actual = server.BackChannel.Buffer.OfType <ExceptionTelemetry>().Single(); Assert.Equal(expected.Exception.GetType(), actual.Exception.GetType()); Assert.NotEmpty(actual.Exception.StackTrace); Assert.NotEmpty(actual.Context.Operation.Name); Assert.NotEmpty(actual.Context.Operation.Id); }
private static void Main() { // Set DPI Stuff before anything else, even the mutex SetProcessDPI(GlobalSettings.DpiScalingMethodSetting); if (IsMainThread) { SetThreadDPI(GlobalSettings.DpiScalingMethodSetting); } using (GlobalChummerMutex = new Mutex(false, @"Global\" + ChummerGuid, out bool blnIsNewInstance)) { try { try { // Chummer instance already exists, so switch to it instead of opening a new instance if (!blnIsNewInstance || !GlobalChummerMutex.WaitOne(TimeSpan.FromSeconds(2), false)) { // Try to get the main chummer process by fetching the Chummer process with the earliest start time Process objMainChummerProcess = MyProcess; foreach (Process objLoopProcess in Process.GetProcessesByName(MyProcess.ProcessName)) { if (objLoopProcess.StartTime.Ticks < objMainChummerProcess.StartTime.Ticks) { objMainChummerProcess = objLoopProcess; } } if (objMainChummerProcess != MyProcess) { NativeMethods.SendMessage(objMainChummerProcess.MainWindowHandle, NativeMethods.WM_SHOWME, 0, IntPtr.Zero); string strCommandLineArgumentsJoined = string.Join("<>", Environment.GetCommandLineArgs()); NativeMethods.CopyDataStruct objData = new NativeMethods.CopyDataStruct(); IntPtr ptrCommandLineArguments = IntPtr.Zero; try { // Allocate memory for the data and copy objData = NativeMethods.CopyDataFromString(CommandLineArgsDataTypeId, strCommandLineArgumentsJoined); ptrCommandLineArguments = Marshal.AllocCoTaskMem(Marshal.SizeOf(objData)); Marshal.StructureToPtr(objData, ptrCommandLineArguments, false); // Send the message NativeMethods.SendMessage(objMainChummerProcess.MainWindowHandle, NativeMethods.WM_COPYDATA, 0, ptrCommandLineArguments); } finally { // Free the allocated memory after the control has been returned if (ptrCommandLineArguments != IntPtr.Zero) { Marshal.FreeCoTaskMem(ptrCommandLineArguments); } if (objData.lpData != IntPtr.Zero) { Marshal.FreeHGlobal(objData.lpData); } } } return; } } catch (AbandonedMutexException e) { Log.Info(e); } //for some fun try out this command line parameter: chummer://plugin:SINners:Load:5ff55b9d-7d1c-4067-a2f5-774127346f4e PageViewTelemetry pvt = null; DateTimeOffset startTime = DateTimeOffset.UtcNow; // Set default cultures based on the currently set language CultureInfo.DefaultThreadCurrentCulture = GlobalSettings.CultureInfo; CultureInfo.DefaultThreadCurrentUICulture = GlobalSettings.CultureInfo; string strPostErrorMessage = string.Empty; string settingsDirectoryPath = Path.Combine(Utils.GetStartupPath, "settings"); if (!Directory.Exists(settingsDirectoryPath)) { try { Directory.CreateDirectory(settingsDirectoryPath); } catch (UnauthorizedAccessException ex) { string strMessage = LanguageManager.GetString("Message_Insufficient_Permissions_Warning", GlobalSettings.Language, false); if (string.IsNullOrEmpty(strMessage)) { strMessage = ex.ToString(); } strPostErrorMessage = strMessage; } catch (Exception ex) { strPostErrorMessage = ex.ToString(); } } IsMono = Type.GetType("Mono.Runtime") != null; // Delete old ProfileOptimization file because we don't want it anymore, instead we restart profiling for each newly generated assembly Utils.SafeDeleteFile(Path.Combine(Utils.GetStartupPath, "chummerprofile")); // We avoid weird issues with ProfileOptimization pointing JIT to the wrong place by checking for and removing all profile optimization files that // were made in an older version (i.e. an older assembly) string strProfileOptimizationName = "chummerprofile_" + Utils.CurrentChummerVersion + ".profile"; foreach (string strProfileFile in Directory.GetFiles(Utils.GetStartupPath, "*.profile", SearchOption.TopDirectoryOnly)) { if (!string.Equals(strProfileFile, strProfileOptimizationName, StringComparison.OrdinalIgnoreCase)) { Utils.SafeDeleteFile(strProfileFile); } } // Mono, non-Windows native stuff, and Win11 don't always play nice with ProfileOptimization, so it's better to just not bother with it when running under them if (!IsMono && Utils.HumanReadableOSVersion.StartsWith("Windows") && !Utils.HumanReadableOSVersion.StartsWith("Windows 11")) { ProfileOptimization.SetProfileRoot(Utils.GetStartupPath); ProfileOptimization.StartProfile(strProfileOptimizationName); } Stopwatch sw = Stopwatch.StartNew(); //If debugging and launched from other place (Bootstrap), launch debugger if (Environment.GetCommandLineArgs().Contains("/debug") && !Debugger.IsAttached) { Debugger.Launch(); } sw.TaskEnd("dbgchk"); //Various init stuff (that mostly "can" be removed as they serve //debugging more than function //Needs to be called before Log is setup, as it moves where log might be. FixCwd(); sw.TaskEnd("fixcwd"); AppDomain.CurrentDomain.FirstChanceException += ExceptionHeatMap.OnException; sw.TaskEnd("appdomain 2"); string strInfo = string.Format(GlobalSettings.InvariantCultureInfo, "Application Chummer5a build {0} started at {1} with command line arguments {2}", Utils.CurrentChummerVersion, DateTime.UtcNow, Environment.CommandLine); sw.TaskEnd("infogen"); sw.TaskEnd("infoprnt"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); sw.TaskEnd("languagefreestartup"); void HandleCrash(object o, UnhandledExceptionEventArgs exa) { if (exa.ExceptionObject is Exception ex) { try { if (GlobalSettings.UseLoggingApplicationInsights >= UseAILogging.Crashes && ChummerTelemetryClient != null && !Utils.IsMilestoneVersion) { ExceptionTelemetry et = new ExceptionTelemetry(ex) { SeverityLevel = SeverityLevel.Critical }; //we have to enable the uploading of THIS message, so it isn't filtered out in the DropUserdataTelemetryProcessos foreach (DictionaryEntry d in ex.Data) { if ((d.Key != null) && (d.Value != null)) { et.Properties.Add(d.Key.ToString(), d.Value.ToString()); } } et.Properties.Add("IsCrash", bool.TrueString); CustomTelemetryInitializer ti = new CustomTelemetryInitializer(); ti.Initialize(et); ChummerTelemetryClient.TrackException(et); ChummerTelemetryClient.Flush(); } } catch (Exception ex1) { Log.Error(ex1); } #if !DEBUG CrashHandler.WebMiniDumpHandler(ex); #endif } } AppDomain.CurrentDomain.UnhandledException += HandleCrash; sw.TaskEnd("Startup"); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); if (!string.IsNullOrEmpty(LanguageManager.ManagerErrorMessage)) { // MainForm is null at the moment, so we have to show error box manually MessageBox.Show(LanguageManager.ManagerErrorMessage, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!string.IsNullOrEmpty(GlobalSettings.ErrorMessage)) { // MainForm is null at the moment, so we have to show error box manually MessageBox.Show(GlobalSettings.ErrorMessage, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!string.IsNullOrEmpty(strPostErrorMessage)) { // MainForm is null at the moment, so we have to show error box manually MessageBox.Show(strPostErrorMessage, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { TelemetryConfiguration.Active.InstrumentationKey = "012fd080-80dc-4c10-97df-4f2cf8c805d5"; LogManager.ThrowExceptions = true; if (IsMono) { //Mono Crashes because of Application Insights. Set Logging to local, when Mono Runtime is detected GlobalSettings.UseLoggingApplicationInsights = UseAILogging.OnlyLocal; } if (GlobalSettings.UseLoggingApplicationInsights > UseAILogging.OnlyMetric) { ConfigurationItemFactory.Default.Targets.RegisterDefinition( "ApplicationInsightsTarget", typeof(ApplicationInsightsTarget) ); } LogManager.ThrowExceptions = false; Log = LogManager.GetCurrentClassLogger(); if (GlobalSettings.UseLogging) { foreach (LoggingRule objRule in LogManager.Configuration.LoggingRules) { #if DEBUG //enable logging to EventLog when Debugging if (objRule.Levels.Count == 0 && objRule.RuleName == "ELChummer") { objRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal); } #endif //only change the loglevel, if it's off - otherwise it has been changed manually if (objRule.Levels.Count == 0) { objRule.EnableLoggingForLevels(LogLevel.Debug, LogLevel.Fatal); } } } if (Settings.Default.UploadClientId == Guid.Empty) { Settings.Default.UploadClientId = Guid.NewGuid(); Settings.Default.Save(); } if (!Utils.IsUnitTest && GlobalSettings.UseLoggingApplicationInsights >= UseAILogging.OnlyMetric) { #if DEBUG //If you set true as DeveloperMode (see above), you can see the sending telemetry in the debugging output window in IDE. TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true; #else TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = false; #endif TelemetryConfiguration.Active.TelemetryInitializers.Add(new CustomTelemetryInitializer()); TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Use(next => new TranslateExceptionTelemetryProcessor(next)); TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Use(next => new DropUserdataTelemetryProcessor(next, Environment.UserName)); TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Build(); //for now lets disable live view.We may make another GlobalOption to enable it at a later stage... //var live = new LiveStreamProvider(ApplicationInsightsConfig); //live.Enable(); //Log an Event with AssemblyVersion and CultureInfo MetricIdentifier objMetricIdentifier = new MetricIdentifier("Chummer", "Program Start", "Version", "Culture", "AISetting", "OSVersion"); string strOSVersion = Utils.HumanReadableOSVersion; Metric objMetric = ChummerTelemetryClient.GetMetric(objMetricIdentifier); objMetric.TrackValue(1, Utils.CurrentChummerVersion.ToString(), CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, GlobalSettings.UseLoggingApplicationInsights.ToString(), strOSVersion); //Log a page view: pvt = new PageViewTelemetry("frmChummerMain()") { Name = "Chummer Startup: " + Utils.CurrentChummerVersion, Id = Settings.Default.UploadClientId.ToString(), Timestamp = startTime }; pvt.Context.Operation.Name = "Operation Program.Main()"; pvt.Properties.Add("parameters", Environment.CommandLine); UploadObjectAsMetric.UploadObject(ChummerTelemetryClient, typeof(GlobalSettings)); } else { TelemetryConfiguration.Active.DisableTelemetry = true; } Log.Info(strInfo); Log.Info("Logging options are set to " + GlobalSettings.UseLogging + " and Upload-Options are set to " + GlobalSettings.UseLoggingApplicationInsights + " (Installation-Id: " + Settings.Default.UploadClientId.ToString("D", GlobalSettings.InvariantCultureInfo) + ")."); //make sure the Settings are upgraded/preserved after an upgrade //see for details: https://stackoverflow.com/questions/534261/how-do-you-keep-user-config-settings-across-different-assembly-versions-in-net/534335#534335 if (Settings.Default.UpgradeRequired) { if (UnblockPath(AppDomain.CurrentDomain.BaseDirectory)) { Settings.Default.Upgrade(); Settings.Default.UpgradeRequired = false; Settings.Default.Save(); } else { Log.Warn("Files could not be unblocked in " + AppDomain.CurrentDomain.BaseDirectory); } } } catch (Exception e) { Console.WriteLine(e); Log.Error(e); #if DEBUG throw; #endif } //load the plugins and maybe work of any command line arguments //arguments come in the form of // /plugin:Name:Parameter:Argument // /plugin:SINners:RegisterUriScheme:0 bool showMainForm = !Utils.IsUnitTest; bool blnRestoreDefaultLanguage; try { // Make sure the default language has been loaded before attempting to open the Main Form. blnRestoreDefaultLanguage = !LanguageManager.LoadLanguage(GlobalSettings.Language); } // This to catch and handle an extremely strange issue where Chummer tries to load a language it shouldn't and ends up // dereferencing a null value that should be impossible by static code analysis. This code here is a failsafe so that // it at least keeps working in English instead of crashing. catch (NullReferenceException) { Utils.BreakIfDebug(); blnRestoreDefaultLanguage = true; } // Restore Chummer's language to en-US if we failed to load the default one. if (blnRestoreDefaultLanguage) { GlobalSettings.Language = GlobalSettings.DefaultLanguage; } MainForm = new ChummerMainForm(); try { PluginLoader.LoadPlugins(); } catch (ApplicationException) { showMainForm = false; } if (!Utils.IsUnitTest) { string[] strArgs = Environment.GetCommandLineArgs(); try { // Process plugin args synchronously because plugin load order can end up mattering foreach (string strArg in strArgs) { if (!strArg.Contains("/plugin")) { continue; } if (!GlobalSettings.PluginsEnabled) { const string strMessage = "Please enable Plugins to use command-line arguments invoking specific plugin-functions!"; Log.Warn(strMessage); MainForm.ShowMessageBox(strMessage, "Plugins not enabled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { string strWhatPlugin = strArg.Substring(strArg.IndexOf("/plugin", StringComparison.Ordinal) + 8); //some external apps choose to add a '/' before a ':' even in the middle of an url... strWhatPlugin = strWhatPlugin.TrimStart(':'); int intEndPlugin = strWhatPlugin.IndexOf(':'); string strParameter = strWhatPlugin.Substring(intEndPlugin + 1); strWhatPlugin = strWhatPlugin.Substring(0, intEndPlugin); IPlugin objActivePlugin = PluginLoader.MyActivePlugins.Find(a => a.ToString() == strWhatPlugin); if (objActivePlugin == null) { if (PluginLoader.MyPlugins.All(a => a.ToString() != strWhatPlugin)) { string strMessage = "Plugin " + strWhatPlugin + " is not enabled in the options!" + Environment.NewLine + "If you want to use command-line arguments, please enable this plugin and restart the program."; Log.Warn(strMessage); MainForm.ShowMessageBox(strMessage, strWhatPlugin + " not enabled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else { showMainForm &= objActivePlugin.ProcessCommandLine(strParameter); } } } } catch (Exception e) { ExceptionTelemetry ex = new ExceptionTelemetry(e) { SeverityLevel = SeverityLevel.Warning }; ChummerTelemetryClient?.TrackException(ex); Log.Warn(e); } } // Delete the old executable if it exists (created by the update process). Utils.SafeClearDirectory(Utils.GetStartupPath, "*.old"); // Purge the temporary directory Utils.SafeClearDirectory(Utils.GetTempPath()); if (showMainForm) { MainForm.MyStartupPvt = pvt; Application.Run(MainForm); } PluginLoader?.Dispose(); Log.Info(ExceptionHeatMap.GenerateInfo()); if (GlobalSettings.UseLoggingApplicationInsights > UseAILogging.OnlyLocal && ChummerTelemetryClient != null) { ChummerTelemetryClient.Flush(); //we have to wait a bit to give it time to upload the data Console.WriteLine("Waiting a bit to flush logging data..."); Utils.SafeSleep(TimeSpan.FromSeconds(2)); } } finally { GlobalChummerMutex.ReleaseMutex(); } } }
public async Task <VacationImportStatusDto> UploadVacationReportFileAsync(Stream fileStream) { var excelReader = ExcelReaderFactory.CreateBinaryReader(fileStream); var sheets = GetWorksheetNames(excelReader); var workSheet = GetWorksheetData(excelReader, sheets.First()); var importStatus = new VacationImportStatusDto { Imported = new List <VacationImportEntryDto>(), Skipped = new List <VacationImportEntryDto>() }; foreach (var row in workSheet) { var acceptableData = row[CodeColIndex] is string && row[FullnameColIndex] is string && row[OperationColIndex] is string && row[OfficeColIndex] is string && row[JobTitleColIndex] is string && (row[VacationTotalTimeColIndex] is double || row[VacationTotalTimeColIndex] is int) && (row[VacationUsedTimeColIndex] is double || row[VacationUsedTimeColIndex] is int) && (row[VacationUnusedTimeColIndex] is double || row[VacationUnusedTimeColIndex] is int); if (!acceptableData) { continue; } var fullName = row[FullnameColIndex].ToString(); var code = row[CodeColIndex].ToString(); var users = _applicationUserDbSet.Where(_vacationDomainService.UsersByNamesFilter(fullName).Compile()).ToList(); var userToUpdate = _vacationDomainService.FindUser(users, fullName); if (userToUpdate != null) { var fullTime = (double)row[VacationTotalTimeColIndex]; var usedTime = (double)row[VacationUsedTimeColIndex]; var unusedTime = (double)row[VacationUnusedTimeColIndex]; userToUpdate.VacationTotalTime = fullTime; userToUpdate.VacationUsedTime = usedTime; userToUpdate.VacationUnusedTime = unusedTime; userToUpdate.VacationLastTimeUpdated = DateTime.UtcNow; importStatus.Imported.Add(new VacationImportEntryDto { Code = code, FullName = fullName }); } else { var exception = new VacationImportException($"User wasn't found during import - entry code: {code}, fullname: {fullName}"); var exceptionTelemetry = new ExceptionTelemetry { Message = exception.Message, Exception = exception }; exceptionTelemetry.Properties.Add("Entry code", code); exceptionTelemetry.Properties.Add("Entry last name, first name", fullName); _telemetryClient.TrackException(exceptionTelemetry); importStatus.Skipped.Add(new VacationImportEntryDto { Code = code, FullName = fullName }); } } await _uow.SaveChangesAsync(); excelReader.Close(); return(importStatus); }
private void AddExceptionProperties(IDictionary <string, object> eventPayload, ExceptionTelemetry exception) { eventPayload.Add(TelemetryTypeProperty, "exception"); eventPayload.Add(nameof(exception.Exception), exception.Exception.ToString()); if (!string.IsNullOrEmpty(exception.Message)) { eventPayload.Add(nameof(exception.Message), exception.Message); } }
private static async Task TestAvailability(TelemetryClient telemetryClient, HttpClient HttpClient, String address, ILogger _logger) { var availability = new AvailabilityTelemetry { Id = Guid.NewGuid().ToString(), Name = address, RunLocation = System.Environment.MachineName, Success = false }; var stopwatch = new Stopwatch(); stopwatch.Start(); bool isMonitoringFailure = false; try { using (var httpResponse = await HttpClient.GetAsync(address)) { // add test results to availability telemetry property availability.Properties.Add("HttpResponseStatusCode", Convert.ToInt32(httpResponse.StatusCode).ToString()); //if HttpStatusCode is in the successful range 200-299 if (httpResponse.IsSuccessStatusCode) { availability.Success = true; availability.Message = $"Test succeeded with response: {httpResponse.StatusCode}"; _logger.LogTrace($"[Verbose]: {availability.Message}"); } else if (!httpResponse.IsSuccessStatusCode) { availability.Message = $"Test failed with response: {httpResponse.StatusCode}"; _logger.LogWarning($"[Warning]: {availability.Message}"); } } } catch (System.Net.Sockets.SocketException se) { availability.Message = $"Test failed with socket exception, response: {se.Message}"; _logger.LogWarning($"[Warning]: {availability.Message}"); } catch (TaskCanceledException e) { availability.Message = $"Test failed due to monitoring interruption: {e.Message}"; _logger.LogWarning($"[Warning]: {availability.Message}"); } catch (System.Net.Http.HttpRequestException hre) { availability.Message = $"Test failed with an HTTP request exception, response: {hre.Message}"; _logger.LogWarning($"[Warning]: {availability.Message}"); } catch (Exception ex) { // track exception when unable to determine the state of web app isMonitoringFailure = true; var exceptionTelemetry = new ExceptionTelemetry(ex); // exceptionTelemetry.Context.Operation.Id = "test"; exceptionTelemetry.Properties.Add("Message", ex.Message); exceptionTelemetry.Properties.Add("Source", ex.Source); exceptionTelemetry.Properties.Add("Test site", address); //exceptionTelemetry.Properties.Add("StackTrace", ex.StackTrace); telemetryClient.TrackException(exceptionTelemetry); _logger.LogError($"[Error]: {ex.Message}"); } finally { stopwatch.Stop(); availability.Duration = stopwatch.Elapsed; availability.Timestamp = DateTimeOffset.UtcNow; if (!isMonitoringFailure) { telemetryClient.TrackAvailability(availability); _logger.LogInformation($"Availability telemetry for {availability.Name} is sent."); Console.WriteLine($"Availability telemetry for {availability.Name} is sent."); } // call flush to ensure all telemetry is sent telemetryClient.Flush(); } }
private static void SerializeExceptionTelemetry(ExceptionTelemetry exceptionTelemetry, JsonWriter writer) { writer.WriteStartObject(); exceptionTelemetry.WriteTelemetryName(writer, ExceptionTelemetry.TelemetryName); exceptionTelemetry.WriteEnvelopeProperties(writer); writer.WritePropertyName("data"); { writer.WriteStartObject(); writer.WriteProperty("baseType", exceptionTelemetry.BaseType); writer.WritePropertyName("baseData"); { writer.WriteStartObject(); writer.WriteProperty("ver", exceptionTelemetry.Data.ver); writer.WriteProperty( "handledAt", Utils.PopulateRequiredStringValue(exceptionTelemetry.Data.handledAt, "handledAt", typeof(ExceptionTelemetry).FullName)); writer.WriteProperty("properties", exceptionTelemetry.Data.properties); writer.WriteProperty("measurements", exceptionTelemetry.Data.measurements); writer.WritePropertyName("exceptions"); { writer.WriteStartArray(); SerializeExceptions(exceptionTelemetry.Exceptions, writer); writer.WriteEndArray(); } if (exceptionTelemetry.Data.severityLevel.HasValue) { writer.WriteProperty("severityLevel", exceptionTelemetry.Data.severityLevel.Value.ToString()); } writer.WriteEndObject(); } writer.WriteEndObject(); } writer.WriteEndObject(); }
/// <summary> /// Initializes a new instance of the <see cref="ExceptionTelemetryTraceMessage" /> class. /// </summary> /// <param name="telemetry">Telemetry item to be converted. </param> public ExceptionTelemetryTraceMessage(ExceptionTelemetry telemetry) { this.Category = telemetry.SeverityLevel == null ? "--" : SeverityToGlimpseCategory.SeverityToCategory((SeverityLevel)telemetry.SeverityLevel); this.Message = "Exception: " + telemetry.Exception.GetType(); this.IndentLevel = 0; }
/// <summary> /// Initializes a new instance of the <see cref="ExceptionTelemetryTimelineMessage"/> class. /// </summary> /// <param name="telemetry">object telemetry</param> public ExceptionTelemetryTimelineMessage(ExceptionTelemetry telemetry) { this.EventName = telemetry.Exception.Message; this.EventCategory = new TimelineCategoryItem("Application Insights", "green", "yellow"); this.EventSubText = "Exception of type: " + telemetry.Exception.Message + "<br> Happened in: " + telemetry.Exception.StackTrace; }
private static void SerializeTelemetryItem(ITelemetry telemetryItem, JsonWriter jsonWriter) { if (telemetryItem is EventTelemetry) { EventTelemetry eventTelemetry = telemetryItem as EventTelemetry; SerializeEventTelemetry(eventTelemetry, jsonWriter); } else if (telemetryItem is ExceptionTelemetry) { ExceptionTelemetry exceptionTelemetry = telemetryItem as ExceptionTelemetry; SerializeExceptionTelemetry(exceptionTelemetry, jsonWriter); } else if (telemetryItem is MetricTelemetry) { MetricTelemetry metricTelemetry = telemetryItem as MetricTelemetry; SerializeMetricTelemetry(metricTelemetry, jsonWriter); } else if (telemetryItem is PageViewTelemetry) { PageViewTelemetry pageViewTelemetry = telemetryItem as PageViewTelemetry; SerializePageViewTelemetry(pageViewTelemetry, jsonWriter); } else if (telemetryItem is DependencyTelemetry) { DependencyTelemetry remoteDependencyTelemetry = telemetryItem as DependencyTelemetry; SerializeDependencyTelemetry(remoteDependencyTelemetry, jsonWriter); } else if (telemetryItem is RequestTelemetry) { RequestTelemetry requestTelemetry = telemetryItem as RequestTelemetry; SerializeRequestTelemetry(requestTelemetry, jsonWriter); } #pragma warning disable 618 else if (telemetryItem is SessionStateTelemetry) { EventTelemetry telemetry = (telemetryItem as SessionStateTelemetry).Data; SerializeEventTelemetry(telemetry, jsonWriter); } #pragma warning restore 618 else if (telemetryItem is TraceTelemetry) { TraceTelemetry traceTelemetry = telemetryItem as TraceTelemetry; SerializeTraceTelemetry(traceTelemetry, jsonWriter); } #pragma warning disable 618 else if (telemetryItem is PerformanceCounterTelemetry) { MetricTelemetry telemetry = (telemetryItem as PerformanceCounterTelemetry).Data; SerializeMetricTelemetry(telemetry, jsonWriter); } else if (telemetryItem is AvailabilityTelemetry) { AvailabilityTelemetry availabilityTelemetry = telemetryItem as AvailabilityTelemetry; SerializeAvailability(availabilityTelemetry, jsonWriter); } else { string msg = string.Format(CultureInfo.InvariantCulture, "Unknown telemtry type: {0}", telemetryItem.GetType()); CoreEventSource.Log.LogVerbose(msg); } }
public static async Task ScheduledAnalyticsRun(string name, string query, ILogger log) { log.LogInformation($"Executing scheduled analytics run for {name} at: {DateTime.Now}"); string requestId = Guid.NewGuid().ToString(); log.LogInformation($"[Verbose]: API request ID is {requestId}"); try { MetricTelemetry metric = new MetricTelemetry { Name = name }; metric.Context.Operation.Id = requestId; metric.Properties.Add("TestAppId", AiAppId); metric.Properties.Add("TestQuery", query); metric.Properties.Add("TestRequestId", requestId); using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add("x-api-key", AiAppKey); httpClient.DefaultRequestHeaders.Add("x-ms-app", "FunctionTemplate"); httpClient.DefaultRequestHeaders.Add("x-ms-client-request-id", requestId); string apiPath = $"{AppInsightsApi}/{AiAppId}/query?clientId={requestId}×pan=P1D&query={query}"; using (var httpResponse = await httpClient.GetAsync(apiPath)) { httpResponse.EnsureSuccessStatusCode(); var resultJson = await httpResponse.Content.ReadAsAsync <JToken>(); double result; if (double.TryParse(resultJson.SelectToken("Tables[0].Rows[0][0]")?.ToString(), out result)) { metric.Sum = result; log.LogInformation($"[Verbose]: Metric result is {metric.Sum}"); } else { log.LogError($"[Error]: {resultJson.ToString()}"); throw new FormatException("Query must result in a single metric number. Try it on Analytics before scheduling."); } } } TelemetryClient.TrackMetric(metric); log.LogInformation($"Metric telemetry for {name} is sent."); } catch (Exception ex) { var exceptionTelemetry = new ExceptionTelemetry(ex); exceptionTelemetry.Context.Operation.Id = requestId; exceptionTelemetry.Properties.Add("TestName", name); exceptionTelemetry.Properties.Add("TestAppId", AiAppId); exceptionTelemetry.Properties.Add("TestQuery", query); exceptionTelemetry.Properties.Add("TestRequestId", requestId); TelemetryClient.TrackException(exceptionTelemetry); log.LogError($"[Error]: Client Request ID {requestId}: {ex.Message}"); throw; } finally { TelemetryClient.Flush(); } }
/// <summary> /// Send an <see cref="ExceptionTelemetry"/> for display in Diagnostic Search. /// </summary> /// <param name="exception">The exception to log.</param> /// <param name="properties">Named string values you can use to classify and search for this exception.</param> public void TrackException(Exception exception, IDictionary<string, string> properties = null) { if (exception == null) { exception = new Exception(Utils.PopulateRequiredStringValue(null, "message", typeof(ExceptionTelemetry).FullName)); } var service = ServiceLocator.GetService<IUnhandledExceptionTelemetryModule>(); // if service is not implemented, use default exception telemetry ITelemetry telemetry = service == null ? telemetry = new ExceptionTelemetry(exception) { HandledAt = ExceptionHandledAt.UserCode } : service.CreateCrashTelemetry(exception, ExceptionHandledAt.UserCode); if (properties != null && properties.Count > 0) { Utils.CopyDictionary(properties, telemetry.Context.Properties); } this.Track(telemetry); }
private async Task <ActionResult <ResultAccountGetSinnersByAuthorization> > GetSINnersByAuthorizationInternal() { Stopwatch sw = new Stopwatch(); sw.Start(); //var tc = new Microsoft.ApplicationInsights.TelemetryClient(); ResultAccountGetSinnersByAuthorization res = null; SINSearchGroupResult ret = new SINSearchGroupResult(); res = new ResultAccountGetSinnersByAuthorization(ret); SINnerGroup sg = new SINnerGroup(); SINnerSearchGroup ssg = new SINnerSearchGroup(sg) { MyMembers = new List <SINnerSearchGroupMember>() }; using (var t = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }, TransactionScopeAsyncFlowOption.Enabled)) { try { var user = await _signInManager.UserManager.GetUserAsync(User); if (user == null) { var e = new AuthenticationException("User is not authenticated."); res = new ResultAccountGetSinnersByAuthorization(e) { ErrorText = "Unauthorized" }; return(BadRequest(res)); } var roles = await _userManager.GetRolesAsync(user); ret.Roles = roles.ToList(); ssg.Groupname = user.UserName; ssg.Id = Guid.Empty; //get all from visibility List <SINner> mySinners = await SINner.GetSINnersFromUser(user, _context, true); MetricTelemetry mt = new MetricTelemetry("GetSINersByAuthorization", "SINners found", mySinners.Count, 0, 0, 0, 0); tc.TrackMetric(mt); foreach (var sin in mySinners) { //check if that char is already added: var foundseq = (from a in ssg.MyMembers where a.MySINner.Id == sin.Id select a); if (foundseq.Any()) { continue; } sin.LastDownload = DateTime.Now; SINnerSearchGroupMember ssgm = new SINnerSearchGroupMember { MySINner = sin, Username = user.UserName }; if (sin.MyGroup?.Id != null) { if (!user.FavoriteGroups.Any(a => a.FavoriteGuid == sin.MyGroup.Id.Value)) { user.FavoriteGroups.Add(new ApplicationUserFavoriteGroup() { FavoriteGuid = sin.MyGroup.Id.Value }); } } else { ssg.MyMembers.Add(ssgm); } } user.FavoriteGroups = user.FavoriteGroups.GroupBy(a => a.FavoriteGuid).Select(b => b.First()).ToList(); foreach (var singroupId in user.FavoriteGroups) { SINnerSearchGroup ssgFromSIN; var singroup = await _context.SINnerGroups.FirstOrDefaultAsync(a => a.Id == singroupId.FavoriteGuid); if (ssg.MySINSearchGroups.Any(a => a.Id == singroupId.FavoriteGuid)) { ssgFromSIN = ssg.MySINSearchGroups.FirstOrDefault(a => a.Id == singroupId.FavoriteGuid); } else { ssgFromSIN = new SINnerSearchGroup(singroup); ssg.MySINSearchGroups.Add(ssgFromSIN); } //add all members of his group var members = await singroup.GetGroupMembers(_context, false); foreach (var member in members) { member.LastDownload = DateTime.Now; member.MyGroup = singroup; member.MyGroup.MyGroups = new List <SINnerGroup>(); SINnerSearchGroupMember sinssgGroupMember = new SINnerSearchGroupMember { MySINner = member }; //check if it is already added: var groupseq = from a in ssgFromSIN.MyMembers where a.MySINner == member select a; if (groupseq.Any()) { continue; } ssgFromSIN.MyMembers.Add(sinssgGroupMember); //} } singroup.PasswordHash = ""; singroup.MyGroups = new List <SINnerGroup>(); } await _context.SaveChangesAsync(); ret.SINGroups.Add(ssg); res = new ResultAccountGetSinnersByAuthorization(ret); return(Ok(res)); } catch (Exception e) { try { var user = await _signInManager.UserManager.GetUserAsync(User); ExceptionTelemetry et = new ExceptionTelemetry(e); et.Properties.Add("user", User.Identity.Name); tc.TrackException(et); } catch (Exception ex) { _logger?.LogError(ex.ToString()); } res = new ResultAccountGetSinnersByAuthorization(e); return(BadRequest(res)); } finally { Microsoft.ApplicationInsights.DataContracts.AvailabilityTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.AvailabilityTelemetry("GetSINnersByAuthorization", DateTimeOffset.Now, sw.Elapsed, "Azure", res?.CallSuccess ?? false, res?.ErrorText); tc.TrackAvailability(telemetry); } #pragma warning disable CS0162 // Unreachable code detected t.Complete(); #pragma warning restore CS0162 // Unreachable code detected } }
public void ValidateBasicException(InProcessServer server, string requestPath, ExceptionTelemetry expected) { this.ExecuteRequest(server.BaseHost + requestPath); var actual = server.Listener.ReceiveItemsOfType <TelemetryItem <ExceptionData> >(1, TestListenerTimeoutInMs); this.DebugTelemetryItems(actual); var item = actual.OfType <TelemetryItem <ExceptionData> >().FirstOrDefault(); Assert.NotNull(item); var data = ((TelemetryItem <ExceptionData>)item).data.baseData; Assert.Equal(expected.Exception.GetType().ToString(), data.exceptions[0].typeName); Assert.NotEmpty(data.exceptions[0].parsedStack); }
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Program.Seed()' public static void Seed(IApplicationBuilder app) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Program.Seed()' { if (app == null) { throw new ArgumentNullException(nameof(app)); } using (var scope = app.ApplicationServices.CreateScope()) { var services = scope.ServiceProvider; var logger = services.GetRequiredService <ILogger <Program> >(); ApplicationDbContext context = services.GetRequiredService <ApplicationDbContext>(); try { context.Database.Migrate(); } catch (SqlException e) { if (!e.Message.Contains("already exists") == true) { throw; } logger.LogWarning(e, e.Message); } catch (Exception e) { try { var tc = new TelemetryClient(); var telemetry = new ExceptionTelemetry(e); tc.TrackException(telemetry); } catch (Exception ex) { logger.LogError(ex.ToString()); } logger.LogError(e.Message, "An error occurred migrating the DB: " + e); context.Database.EnsureDeleted(); context.Database.EnsureCreated(); } // requires using Microsoft.Extensions.Configuration; var config = services.GetRequiredService <IConfiguration>(); // Set password with the Secret Manager tool. // dotnet user-secrets set SeedUserPW <pw> var testUserPw = config["SeedUserPW"]; try { var env = services.GetService <IHostEnvironment>(); SeedData.Initialize(services, testUserPw, env).Wait(); } catch (Exception ex) { try { var tc = new TelemetryClient(); var telemetry = new ExceptionTelemetry(ex); tc.TrackException(telemetry); } catch (Exception e1) { logger.LogError(e1.ToString()); } logger.LogError(ex.Message, "An error occurred seeding the DB: " + ex); } } }
static void Main() { //for some fun try out this command line parameter: chummer://plugin:SINners:Load:5ff55b9d-7d1c-4067-a2f5-774127346f4e PageViewTelemetry pvt = null; var startTime = DateTimeOffset.UtcNow; using (GlobalChummerMutex = new Mutex(false, @"Global\" + strChummerGuid)) { // Set default cultures based on the currently set language CultureInfo.DefaultThreadCurrentCulture = GlobalOptions.CultureInfo; CultureInfo.DefaultThreadCurrentUICulture = GlobalOptions.CultureInfo; string strPostErrorMessage = string.Empty; string settingsDirectoryPath = Path.Combine(Utils.GetStartupPath, "settings"); if (!Directory.Exists(settingsDirectoryPath)) { try { Directory.CreateDirectory(settingsDirectoryPath); } catch (UnauthorizedAccessException ex) { string strMessage = LanguageManager.GetString("Message_Insufficient_Permissions_Warning", GlobalOptions.Language, false); if (string.IsNullOrEmpty(strMessage)) { strMessage = ex.ToString(); } strPostErrorMessage = strMessage; } catch (Exception ex) { strPostErrorMessage = ex.ToString(); } } IsMono = Type.GetType("Mono.Runtime") != null; // Mono doesn't always play nice with ProfileOptimization, so it's better to just not bother with it when running under Mono if (!IsMono) { ProfileOptimization.SetProfileRoot(Utils.GetStartupPath); ProfileOptimization.StartProfile("chummerprofile"); } Stopwatch sw = Stopwatch.StartNew(); //If debugging and launched from other place (Bootstrap), launch debugger if (Environment.GetCommandLineArgs().Contains("/debug") && !Debugger.IsAttached) { Debugger.Launch(); } sw.TaskEnd("dbgchk"); //Various init stuff (that mostly "can" be removed as they serve //debugging more than function //Needs to be called before Log is setup, as it moves where log might be. FixCwd(); sw.TaskEnd("fixcwd"); AppDomain.CurrentDomain.FirstChanceException += ExceptionHeatmap.OnException; sw.TaskEnd("appdomain 2"); string strInfo = string.Format(GlobalOptions.InvariantCultureInfo, "Application Chummer5a build {0} started at {1} with command line arguments {2}", Assembly.GetExecutingAssembly().GetName().Version, DateTime.UtcNow, Environment.CommandLine); sw.TaskEnd("infogen"); sw.TaskEnd("infoprnt"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); sw.TaskEnd("languagefreestartup"); #if !DEBUG AppDomain.CurrentDomain.UnhandledException += (o, e) => { if (e.ExceptionObject is Exception ex) { CrashHandler.WebMiniDumpHandler(ex); } //main.Hide(); //main.ShowInTaskbar = false; }; #else AppDomain.CurrentDomain.UnhandledException += (o, e) => { try { if (e.ExceptionObject is Exception myException) { myException.Data.Add("IsCrash", bool.TrueString); ExceptionTelemetry et = new ExceptionTelemetry(myException) { SeverityLevel = SeverityLevel.Critical }; //we have to enable the uploading of THIS message, so it isn't filtered out in the DropUserdataTelemetryProcessos foreach (DictionaryEntry d in myException.Data) { if (d.Key != null && d.Value != null) { et.Properties.Add(d.Key.ToString(), d.Value.ToString()); } } ChummerTelemetryClient.TrackException(myException); ChummerTelemetryClient.Flush(); } } catch (Exception exception) { Console.WriteLine(exception); } }; #endif sw.TaskEnd("Startup"); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); if (LanguageManager.ManagerErrorMessage.Length > 0) { // MainForm is null at the moment, so we have to show error box manually MessageBox.Show(LanguageManager.ManagerErrorMessage.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (GlobalOptions.ErrorMessage.Length > 0) { // MainForm is null at the moment, so we have to show error box manually MessageBox.Show(GlobalOptions.ErrorMessage.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!string.IsNullOrEmpty(strPostErrorMessage)) { // MainForm is null at the moment, so we have to show error box manually MessageBox.Show(strPostErrorMessage, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { TelemetryConfiguration.Active.InstrumentationKey = "012fd080-80dc-4c10-97df-4f2cf8c805d5"; LogManager.ThrowExceptions = true; if (GlobalOptions.UseLoggingApplicationInsights > UseAILogging.OnlyMetric) { ConfigurationItemFactory.Default.Targets.RegisterDefinition( "ApplicationInsightsTarget", typeof(ApplicationInsightsTarget) ); } LogManager.ThrowExceptions = false; Log = LogManager.GetCurrentClassLogger(); if (GlobalOptions.UseLogging) { foreach (var rule in LogManager.Configuration.LoggingRules.ToList()) { //only change the loglevel, if it's off - otherwise it has been changed manually if (rule.Levels.Count == 0) { rule.EnableLoggingForLevels(LogLevel.Debug, LogLevel.Fatal); } } } if (Properties.Settings.Default.UploadClientId == Guid.Empty) { Properties.Settings.Default.UploadClientId = Guid.NewGuid(); Properties.Settings.Default.Save(); } if (GlobalOptions.UseLoggingApplicationInsights >= UseAILogging.OnlyMetric) { #if DEBUG //If you set true as DeveloperMode (see above), you can see the sending telemetry in the debugging output window in IDE. TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true; #else TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = false; #endif TelemetryConfiguration.Active.TelemetryInitializers.Add(new CustomTelemetryInitializer()); TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Use((next) => new TranslateExceptionTelemetryProcessor(next)); var replacePath = Environment.UserName; TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Use((next) => new DropUserdataTelemetryProcessor(next, replacePath)); TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Build(); //for now lets disable live view.We may make another GlobalOption to enable it at a later stage... //var live = new LiveStreamProvider(ApplicationInsightsConfig); //live.Enable(); //Log an Event with AssemblyVersion and CultureInfo MetricIdentifier mi = new MetricIdentifier("Chummer", "Program Start", "Version", "Culture", dimension3Name: "AISetting"); var metric = ChummerTelemetryClient.GetMetric(mi); metric.TrackValue(1, Assembly.GetExecutingAssembly().GetName().Version.ToString(), CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, GlobalOptions.UseLoggingApplicationInsights.ToString()); //Log a page view: pvt = new PageViewTelemetry("frmChummerMain()") { Name = "Chummer Startup: " + Assembly.GetExecutingAssembly().GetName().Version, Id = Properties.Settings.Default.UploadClientId.ToString() }; pvt.Context.Operation.Name = "Operation Program.Main()"; pvt.Properties.Add("parameters", Environment.CommandLine); pvt.Timestamp = startTime; UploadObjectAsMetric.UploadObject(ChummerTelemetryClient, typeof(GlobalOptions)); } else { TelemetryConfiguration.Active.DisableTelemetry = true; } if (Utils.IsUnitTest) { TelemetryConfiguration.Active.DisableTelemetry = true; } Log.Info(strInfo); Log.Info(new StringBuilder("Logging options are set to ") .Append(GlobalOptions.UseLogging) .Append(" and Upload-Options are set to ") .Append(GlobalOptions.UseLoggingApplicationInsights) .Append(" (Installation-Id: ") .Append(Properties.Settings.Default.UploadClientId.ToString("D", GlobalOptions.InvariantCultureInfo)) .Append(").").ToString()); //make sure the Settings are upgraded/preserved after an upgrade //see for details: https://stackoverflow.com/questions/534261/how-do-you-keep-user-config-settings-across-different-assembly-versions-in-net/534335#534335 if (Properties.Settings.Default.UpgradeRequired) { if (UnblockPath(AppDomain.CurrentDomain.BaseDirectory)) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.UpgradeRequired = false; Properties.Settings.Default.Save(); } else { Log.Warn("Files could not be unblocked in " + AppDomain.CurrentDomain.BaseDirectory); } } } catch (Exception e) { Console.WriteLine(e); Log.Error(e); #if DEBUG throw; #endif } //load the plugins and maybe work of any command line arguments //arguments come in the form of // /plugin:Name:Parameter:Argument // /plugin:SINners:RegisterUriScheme:0 bool showMainForm = true; // Make sure the default language has been loaded before attempting to open the Main Form. LanguageManager.LoadLanguage(GlobalOptions.Language); MainForm = new frmChummerMain(); try { PluginLoader.LoadPlugins(null); } catch (ApplicationException) { showMainForm = false; } if (!Utils.IsUnitTest) { string[] strArgs = Environment.GetCommandLineArgs(); try { // Hacky, but necessary because innards of Parallel.For would end up invoking // a UI function that would wait for Parallel.For to finish, causing the program // to lock up. Task.Run() delegates Parallel.For to a new thread, preventing this. bool blnIsCompleted = Task.Run(() => { var loopResult = Parallel.For(1, strArgs.Length, i => { if (strArgs[i].Contains("/plugin")) { if (!GlobalOptions.PluginsEnabled) { string msg = "Please enable Plugins to use command-line arguments invoking specific plugin-functions!"; Log.Warn(msg); MainForm.ShowMessageBox(msg, "Plugins not enabled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { string whatplugin = strArgs[i].Substring(strArgs[i].IndexOf("/plugin", StringComparison.Ordinal) + 8); //some external apps choose to add a '/' before a ':' even in the middle of an url... whatplugin = whatplugin.TrimStart(':'); int endplugin = whatplugin.IndexOf(':'); string parameter = whatplugin.Substring(endplugin + 1); whatplugin = whatplugin.Substring(0, endplugin); var plugin = PluginLoader.MyActivePlugins.FirstOrDefault(a => a.ToString() == whatplugin); if (plugin == null) { if (PluginLoader.MyPlugins.All(a => a.ToString() != whatplugin)) { string msg = new StringBuilder("Plugin ").Append(whatplugin) .AppendLine(" is not enabled in the options!") .Append("If you want to use command-line arguments, please enable this plugin and restart the program.").ToString(); Log.Warn(msg); MainForm.ShowMessageBox(msg, whatplugin + " not enabled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else { showMainForm &= plugin.ProcessCommandLine(parameter); } } } }); return(loopResult.IsCompleted); }).Result; if (!blnIsCompleted) { Utils.BreakIfDebug(); } } catch (Exception e) { ExceptionTelemetry ex = new ExceptionTelemetry(e) { SeverityLevel = SeverityLevel.Warning }; ChummerTelemetryClient?.TrackException(ex); Log.Warn(e); } } if (showMainForm) { MainForm.MyStartupPVT = pvt; Application.Run(MainForm); } PluginLoader?.Dispose(); Log.Info(ExceptionHeatmap.GenerateInfo()); if (GlobalOptions.UseLoggingApplicationInsights > UseAILogging.OnlyLocal && ChummerTelemetryClient != null) { ChummerTelemetryClient.Flush(); //we have to wait a bit to give it time to upload the data Console.WriteLine("Waiting a bit to flush logging data..."); Thread.Sleep(2000); } } }
private async Task ProcessWebQueueMessageAsync(object sender, BasicDeliverEventArgs @event) { // ExtractActivity creates the Activity setting the parent based on the RabbitMQ "traceparent" header var activity = @event.ExtractActivity("Process single RabbitMQ message"); ISpan span = null; IOperationHolder <DependencyTelemetry> operation = null; var processingSucceeded = false; string source = string.Empty; IDisposable loggingScope = null; try { if (tracer != null) { // OpenTelemetry seems to require the Activity to have started, unlike AI SDK activity.Start(); tracer.StartActiveSpanFromActivity(activity.OperationName, activity, SpanKind.Consumer, out span); span.SetAttribute("queue", Constants.WebQueueName); } using (operation = telemetryClient?.StartOperation <DependencyTelemetry>(activity)) { if (operation != null) { operation.Telemetry.Properties.Add("queue", Constants.WebQueueName); operation.Telemetry.Type = ApplicationInformation.Name; operation.Telemetry.Target = this.rabbitMQHostName; } loggingScope = logger.BeginScope("Starting message processing"); // Get the payload var message = JsonSerializer.Deserialize <EnqueuedMessage>(@event.Body, jsonSerializerOptions); if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation("Processing message from {source}: {message}", message.Source, Encoding.UTF8.GetString(@event.Body)); } source = message.Source; if ("error".Equals(message.EventName, StringComparison.OrdinalIgnoreCase)) { throw new InvalidEventNameException("Invalid event name"); } var apiFullUrl = $"{timeApiURL}/api/time/dbtime"; var time = await httpClientFactory.CreateClient().GetStringAsync(apiFullUrl); if (!string.IsNullOrEmpty(message.EventName)) { span?.AddEvent(message.EventName); telemetryClient?.TrackEvent(message.EventName); } } processingSucceeded = true; } catch (Exception ex) { if (span != null) { span.SetAttribute("error", true); span.Status = Status.Internal.WithDescription(ex.ToString()); } if (operation != null) { operation.Telemetry.Success = false; operation.Telemetry.ResultCode = "500"; // Track exception, adding the connection to the current activity var exOperation = new ExceptionTelemetry(ex); exOperation.Context.Operation.Id = operation.Telemetry.Context.Operation.Id; exOperation.Context.Operation.ParentId = operation.Telemetry.Context.Operation.ParentId; telemetryClient.TrackException(exOperation); } logger.LogError(ex, "Failed to process message from {source}", source); } finally { span?.End(); metrics.TrackItemProcessed(1, source, processingSucceeded); loggingScope?.Dispose(); } }
internal static void UpdateTelemetryExceptionForHTTPCorrelationProtocol(ExceptionTelemetry telemetry, Activity activity) { telemetry.Context.Operation.ParentId = activity.Id; telemetry.Context.Operation.Id = activity.RootId; }
/*************************************************************************/ public async Task WriteTelemetry(Telemetry telemetry) { await Task.Yield(); switch (telemetry.Type) { case Telemetry.TelemetryType.Error: { var tel = new ExceptionTelemetry(telemetry.Exception); tel.MergeProperties(telemetry, _childrenAsJson); tel.Message = telemetry.Exception.Message; tel.SeverityLevel = (SeverityLevel)((int)telemetry.Severity); SetAttributes(telemetry, tel, tel); _client.TrackException(tel); break; } case Telemetry.TelemetryType.Event: { var tel = new EventTelemetry(telemetry.Message); tel.MergeProperties(telemetry, _childrenAsJson); SetAttributes(telemetry, tel, tel); _client.TrackEvent(tel); break; } case Telemetry.TelemetryType.Metric: { var tel = new MetricTelemetry(telemetry.Message, telemetry.Value); tel.MergeProperties(telemetry, _childrenAsJson); SetAttributes(telemetry, tel, tel); _client.TrackMetric(tel); break; } case Telemetry.TelemetryType.Trace: { var tel = new TraceTelemetry(telemetry.Message, (SeverityLevel)((int)telemetry.Severity)); tel.MergeProperties(telemetry, _childrenAsJson); SetAttributes(telemetry, tel, tel); _client.TrackTrace(tel); break; } case Telemetry.TelemetryType.Request: { var tel = new RequestTelemetry(telemetry.Message, telemetry.Request.StartTime, telemetry.Request.Duration, telemetry.Request.ResponseCode, telemetry.Request.Success); tel.MergeProperties(telemetry, _childrenAsJson); SetAttributes(telemetry, tel, tel); _client.TrackRequest(tel); break; } } _client.Flush(); return; }
private async Task <ActionResult <ResultAccountGetSinnersByAuthorization> > GetSINnersByAuthorizationInternal() { Stopwatch sw = new Stopwatch(); sw.Start(); //var tc = new Microsoft.ApplicationInsights.TelemetryClient(); ResultAccountGetSinnersByAuthorization res = null; SINSearchGroupResult ret = new SINSearchGroupResult(); res = new ResultAccountGetSinnersByAuthorization(ret); SINnerGroup sg = new SINnerGroup(); var user = await _signInManager.UserManager.GetUserAsync(User); if (user == null) { var e = new AuthenticationException("User is not authenticated."); res = new ResultAccountGetSinnersByAuthorization(e) { ErrorText = "Unauthorized" }; return(BadRequest(res)); } user.FavoriteGroups = user.FavoriteGroups.GroupBy(a => a.FavoriteGuid).Select(b => b.First()).ToList(); SINnerSearchGroup ssg = new SINnerSearchGroup(sg, user) { MyMembers = new List <SINnerSearchGroupMember>() }; using (var t = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted }, TransactionScopeAsyncFlowOption.Enabled)) { try { var roles = await _userManager.GetRolesAsync(user); ret.Roles = roles.ToList(); ssg.Groupname = user.UserName; ssg.Id = Guid.Empty; var worklist = user.FavoriteGroups.Select(a => a.FavoriteGuid).ToList(); var groupworklist = _context.SINnerGroups .Include(a => a.MyGroups) .ThenInclude(b => b.MyGroups) .ThenInclude(c => c.MyGroups) .ThenInclude(d => d.MyGroups) .Where(a => a.Id != null && worklist.Contains(a.Id.Value)).ToList(); ssg.MySINSearchGroups = await RecursiveBuildGroupMembers(groupworklist, user); var memberworklist = _context.SINners .Include(a => a.MyGroup) .Include(a => a.SINnerMetaData.Visibility) .Where(a => a.Id != null && worklist.Contains(a.Id.Value)); foreach (var member in memberworklist) { if (member.SINnerMetaData?.Visibility?.IsGroupVisible == false) { if (member.SINnerMetaData?.Visibility.UserRights.Any(a => !string.IsNullOrEmpty(a.EMail)) == true) { if (member.SINnerMetaData?.Visibility.UserRights.Any(a => user.NormalizedEmail.Equals(a.EMail, StringComparison.OrdinalIgnoreCase)) == false) { //dont show this guy! continue; } } } member.LastDownload = DateTime.Now; if (member.MyGroup == null) { member.MyGroup = new SINnerGroup(); } if (member.MyGroup.MyGroups == null) { member.MyGroup.MyGroups = new List <SINnerGroup>(); } SINnerSearchGroupMember sinssgGroupMember = new SINnerSearchGroupMember(user, member) { MySINner = member }; ssg.MyMembers.Add(sinssgGroupMember); } await _context.SaveChangesAsync(); ret.SINGroups.Add(ssg); res = new ResultAccountGetSinnersByAuthorization(ret); return(Ok(res)); } catch (Exception e) { try { await _signInManager.UserManager.GetUserAsync(User); ExceptionTelemetry et = new ExceptionTelemetry(e); et.Properties.Add("user", User.Identity.Name); tc.TrackException(et); } catch (Exception ex) { _logger?.LogError(ex.ToString()); } res = new ResultAccountGetSinnersByAuthorization(e); return(BadRequest(res)); } finally { AvailabilityTelemetry telemetry = new AvailabilityTelemetry("GetSINnersByAuthorization", DateTimeOffset.Now, sw.Elapsed, "Azure", res.CallSuccess, res.ErrorText); tc?.TrackAvailability(telemetry); } } }
/// <summary> /// Initializes a new instance of the <see cref="ExceptionTelemetryTraceMessage" /> class. /// </summary> /// <param name="telemetry">Telemetry item to be converted. </param> public ExceptionTelemetryTraceMessage(ExceptionTelemetry telemetry) { this.Category = telemetry.SeverityLevel == null ? "--" : telemetry.SeverityLevel.ToString(); this.Message = "Exception: " + telemetry.Exception.GetType(); this.IndentLevel = 0; }
private void ValidateException(ExceptionTelemetry telemetry, string expectedOperationId, string expectedOperationName, string expectedCategory) { Assert.IsType <FunctionInvocationException>(telemetry.Exception); ValidateTelemetry(telemetry, expectedOperationId, expectedOperationName, expectedCategory, SeverityLevel.Error); }
/// <inheritdoc /> public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { if (IsEnabled(logLevel)) { var stateDictionary = state as IReadOnlyList <KeyValuePair <string, object> >; if (exception != null) { var exceptionTelemetry = new ExceptionTelemetry(exception) { Message = formatter(state, exception), SeverityLevel = GetSeverityLevel(logLevel) }; PopulateTelemetry(exceptionTelemetry, stateDictionary); telemetryClient.TrackException(exceptionTelemetry); return; } var requestState = stateDictionary.FirstOrDefault(x => x.Key == Constants.Request).Value as RequestLog; if (requestState != null) { var telemetry = new RequestTelemetry { Id = requestState.Id, Name = requestState.Name, // Type = requestState.Type, Url = requestState.Uri, Source = requestState.Source, Timestamp = requestState.StartTime, Duration = requestState.Duration, ResponseCode = requestState.ResponseCode, Success = requestState.Success }; telemetry.Context.Operation.Id = requestState.OperationId; telemetry.Context.Operation.Name = requestState.OperationName; telemetry.Context.Operation.ParentId = requestState.OperationParentId; telemetryClient.TrackRequest(telemetry); return; } var dependencyState = stateDictionary.FirstOrDefault(x => x.Key == Constants.Response).Value as DependencyLog; if (dependencyState != null) { var telemetry = new DependencyTelemetry { Id = dependencyState.Id, Name = dependencyState.Name, Type = dependencyState.Type, Data = dependencyState.Uri?.ToString(), Target = dependencyState.Target, Timestamp = dependencyState.StartTime, Duration = dependencyState.Duration, ResultCode = dependencyState.ResponseCode, Success = dependencyState.Success }; telemetry.Context.Operation.Id = dependencyState.OperationId; telemetry.Context.Operation.Name = dependencyState.OperationName; telemetry.Context.Operation.ParentId = dependencyState.OperationParentId; telemetryClient.TrackDependency(telemetry); return; } var traceTelemetry = new TraceTelemetry(formatter(state, exception), GetSeverityLevel(logLevel)); PopulateTelemetry(traceTelemetry, stateDictionary); telemetryClient.TrackTrace(traceTelemetry); } }
private static async Task TestAvailability(TelemetryClient telemetryClient, HttpClient HttpClient, String address, ILogger _logger) { var availability = new AvailabilityTelemetry { Id = Guid.NewGuid().ToString(), Name = $"Availability Test: {address}", RunLocation = System.Environment.MachineName, Success = false }; var stopwatch = new Stopwatch(); stopwatch.Start(); bool isMonitoringFailure = false; try { using (var httpResponse = await HttpClient.GetAsync(address)) { // add test results to availability telemetry property availability.Properties.Add("HttpResponseStatusCode", Convert.ToInt32(httpResponse.StatusCode).ToString()); // check if response content contains specific text string content = httpResponse.Content != null ? await httpResponse.Content.ReadAsStringAsync() : ""; if (httpResponse.IsSuccessStatusCode) { availability.Success = true; availability.Message = $"Test succeeded with response: {httpResponse.StatusCode}"; _logger.LogTrace($"[Verbose]: {availability.Message}"); } else if (!httpResponse.IsSuccessStatusCode) { availability.Message = $"Test failed with response: {httpResponse.StatusCode}"; _logger.LogWarning($"[Warning]: {availability.Message}"); } } } catch (TaskCanceledException e) { availability.Message = $"Test timed out: {e.Message}"; _logger.LogDebug($"[Warning]: {availability.Message}"); } catch (Exception ex) { // track exception when unable to determine the state of web app isMonitoringFailure = true; var exceptionTelemetry = new ExceptionTelemetry(ex); exceptionTelemetry.Context.Operation.Id = "test"; exceptionTelemetry.Properties.Add("TestName", "test"); exceptionTelemetry.Properties.Add("TestLocation", "test"); exceptionTelemetry.Properties.Add("TestUri", "test"); telemetryClient.TrackException(exceptionTelemetry); _logger.LogError($"[Error]: {ex.Message}"); // optional - throw to fail the function throw; } finally { stopwatch.Stop(); availability.Duration = stopwatch.Elapsed; availability.Timestamp = DateTimeOffset.UtcNow; // do not make an assumption as to the state of the web app when monitoring failures occur if (!isMonitoringFailure) { telemetryClient.TrackAvailability(availability); _logger.LogInformation($"Availability telemetry for {availability.Name} is sent."); } // call flush to ensure telemetries are sent telemetryClient.Flush(); } }
static void Main() { PageViewTelemetry pvt = null; var startTime = DateTimeOffset.UtcNow; using (GlobalChummerMutex = new Mutex(false, @"Global\" + strChummerGuid)) { IsMono = Type.GetType("Mono.Runtime") != null; // Mono doesn't always play nice with ProfileOptimization, so it's better to just not bother with it when running under Mono if (!IsMono) { ProfileOptimization.SetProfileRoot(Utils.GetStartupPath); ProfileOptimization.StartProfile("chummerprofile"); } Stopwatch sw = Stopwatch.StartNew(); //If debuging and launched from other place (Bootstrap), launch debugger if (Environment.GetCommandLineArgs().Contains("/debug") && !Debugger.IsAttached) { Debugger.Launch(); } sw.TaskEnd("dbgchk"); //Various init stuff (that mostly "can" be removed as they serve //debugging more than function //Needs to be called before Log is setup, as it moves where log might be. FixCwd(); sw.TaskEnd("fixcwd"); AppDomain.CurrentDomain.FirstChanceException += ExceptionHeatmap.OnException; sw.TaskEnd("appdomain 2"); string strInfo = $"Application Chummer5a build {System.Reflection.Assembly.GetExecutingAssembly().GetName().Version} started at {DateTime.UtcNow} with command line arguments {Environment.CommandLine}"; sw.TaskEnd("infogen"); sw.TaskEnd("infoprnt"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); sw.TaskEnd("languagefreestartup"); #if !DEBUG AppDomain.CurrentDomain.UnhandledException += (o, e) => { if (e.ExceptionObject is Exception ex) { CrashHandler.WebMiniDumpHandler(ex); } //main.Hide(); //main.ShowInTaskbar = false; }; #else AppDomain.CurrentDomain.UnhandledException += (o, e) => { try { if (e.ExceptionObject is Exception myException) { myException.Data.Add("IsCrash", true.ToString()); ExceptionTelemetry et = new ExceptionTelemetry(myException) { SeverityLevel = SeverityLevel.Critical }; //we have to enable the uploading of THIS message, so it isn't filtered out in the DropUserdataTelemetryProcessos foreach (DictionaryEntry d in myException.Data) { if ((d.Key != null) && (d.Value != null)) { et.Properties.Add(d.Key.ToString(), d.Value.ToString()); } } Program.TelemetryClient.TrackException(myException); Program.TelemetryClient.Flush(); } } catch (Exception exception) { Console.WriteLine(exception); } }; #endif sw.TaskEnd("Startup"); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); if (!string.IsNullOrEmpty(LanguageManager.ManagerErrorMessage)) { MessageBox.Show(LanguageManager.ManagerErrorMessage, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!string.IsNullOrEmpty(GlobalOptions.ErrorMessage)) { MessageBox.Show(GlobalOptions.ErrorMessage, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { LogManager.ThrowExceptions = true; if (GlobalOptions.UseLoggingApplicationInsights > UseAILogging.OnlyMetric) { ConfigurationItemFactory.Default.Targets.RegisterDefinition( "ApplicationInsightsTarget", typeof(Microsoft.ApplicationInsights.NLogTarget.ApplicationInsightsTarget) ); } LogManager.ThrowExceptions = false; Log = NLog.LogManager.GetCurrentClassLogger(); if (GlobalOptions.UseLogging) { foreach (var rule in NLog.LogManager.Configuration.LoggingRules.ToList()) { //only change the loglevel, if it's off - otherwise it has been changed manually if (rule.Levels.Count == 0) { rule.EnableLoggingForLevels(LogLevel.Debug, LogLevel.Fatal); } } } Log.Info(strInfo); if (GlobalOptions.UseLoggingApplicationInsights >= UseAILogging.OnlyMetric) { #if DEBUG //If you set true as DeveloperMode (see above), you can see the sending telemetry in the debugging output window in IDE. TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true; #else TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = false; #endif TelemetryConfiguration.Active.TelemetryInitializers.Add(new CustomTelemetryInitializer()); TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Use((next) => new TranslateExceptionTelemetryProcessor(next)); var replacePath = Environment.UserName; TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Use((next) => new DropUserdataTelemetryProcessor(next, replacePath)); TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Build(); //for now lets disable live view.We may make another GlobalOption to enable it at a later stage... //var live = new LiveStreamProvider(ApplicationInsightsConfig); //live.Enable(); //Log an Event with AssemblyVersion and CultureInfo if (Properties.Settings.Default.UploadClientId == Guid.Empty) { Properties.Settings.Default.UploadClientId = Guid.NewGuid(); Properties.Settings.Default.Save(); } MetricIdentifier mi = new MetricIdentifier("Chummer", "Program Start", "Version", "Culture", dimension3Name: "AISetting"); var metric = TelemetryClient.GetMetric(mi); metric.TrackValue(1, Assembly.GetExecutingAssembly().GetName().Version.ToString(), CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, GlobalOptions.UseLoggingApplicationInsights.ToString()); //Log a page view: pvt = new PageViewTelemetry("frmChummerMain()") { Name = "Chummer Startup: " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version }; pvt.Id = Properties.Settings.Default.UploadClientId.ToString(); pvt.Context.Operation.Name = "Operation Program.Main()"; pvt.Properties.Add("parameters", Environment.CommandLine); pvt.Timestamp = startTime; UploadObjectAsMetric.UploadObject(TelemetryClient, typeof(GlobalOptions)); } else { TelemetryConfiguration.Active.DisableTelemetry = true; } if (Utils.IsUnitTest) { TelemetryConfiguration.Active.DisableTelemetry = true; } //make sure the Settings are upgraded/preserved after an upgrade //see for details: https://stackoverflow.com/questions/534261/how-do-you-keep-user-config-settings-across-different-assembly-versions-in-net/534335#534335 if (Properties.Settings.Default.UpgradeRequired) { if (UnblockPath(AppDomain.CurrentDomain.BaseDirectory)) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.UpgradeRequired = false; Properties.Settings.Default.Save(); } else { Log.Warn("Files could not be unblocked in " + AppDomain.CurrentDomain.BaseDirectory); } } } catch (Exception e) { Console.WriteLine(e); Log.Error(e); } // Make sure the default language has been loaded before attempting to open the Main Form. LanguageManager.TranslateWinForm(GlobalOptions.Language, null); MainForm = new frmChummerMain(false, pvt); Application.Run(MainForm); Log.Info(ExceptionHeatmap.GenerateInfo()); if (GlobalOptions.UseLoggingApplicationInsights > UseAILogging.OnlyLocal) { if (TelemetryClient != null) { TelemetryClient.Flush(); //we have to wait a bit to give it time to upload the data Console.WriteLine("Waiting a bit to flush logging data..."); Thread.Sleep(5000); } } } }