public async Task <ActivityLogModel> GetActivityByTitle(string title) { const string sql = @" SELECT [Id], [Title], [Title2], [Title3], [Organizers], [Location], [StartDate], [EndDate], [OnCampus], [WebSite], [Notes], [Created], [CreatedBy] FROM [dbo].[ActivityLog] WHERE [Title] = @Title"; ActivityLogModel activity = null; try { IEnumerable <dynamic> rows = await UnitOfWork.Context().QueryAsync <dynamic>(sql, new { Title = title }); activity = ProcessRows(rows).SingleOrDefault(); } catch (Exception e) { e.Data["SQL"] = sql; ErrorStore.LogException(e, HttpContext.Current); activity = null; } return(activity); }
public async Task Save(int studentId, IEnumerable <int> promoIds) { await Delete(studentId); if (promoIds != null && promoIds.Any()) { const string sql = @" INSERT INTO [dbo].[StudentPromoLog] ([PromoId], [StudentId], [Created]) VALUES (@PromoId, @StudentId, @Created)"; try { DateTime created = DateTime.Now.ToUniversalTime(); foreach (int promoId in promoIds) { await UnitOfWork.Context().ExecuteAsync(sql, new { PromoId = promoId, StudentId = studentId, Created = created }); } } catch (Exception e) { e.Data["SQL"] = sql; ErrorStore.LogException(e, HttpContext.Current); } } }
public async Task <int> InsertActivity(ActivityLogModel model, int userId) { const string sql = @" INSERT INTO [dbo].[ActivityLog] ( [Title], [Title2], [Title3], [Organizers], [Location], [StartDate], [EndDate], [OnCampus], [WebSite], [Notes], [Created], [CreatedBy] ) OUTPUT INSERTED.Id VALUES ( @Title, @Title2, @Title3, @Organizers, @Location, @StartDate, @EndDate, @OnCampus, @WebSite, @Notes, @Created, @CreatedBy )"; try { model.StartDate = model.StartDate.ToUniversalTime(); model.EndDate = model.EndDate.ToUniversalTime(); model.Created = DateTime.Now.ToUniversalTime(); model.CreatedBy = userId; return((await UnitOfWork.Context().QueryAsync <int>(sql, model)).Single()); } catch (Exception e) { e.Data["SQL"] = sql; ErrorStore.LogException(e, HttpContext.Current); throw e; } }
static void Main(string[] args) { // init settings new AppSettings().Init(); ErrorStore.Setup(ShareConstants.ExceptionHanlderAppName, new StackExchange.Exceptional.Stores.SQLErrorStore(AppSettings.Base.Connections.SimpleFeedly.ConnectionString)); // setup DatabaseAccess helper new SimpleFeedlyDatabaseAccess().Setup(() => { return(new DatabaseAccessSettings( connectionString: AppSettings.Base.Connections.SimpleFeedly.ConnectionString, timeout: 200 )); }); HostFactory.Run(config => { config.UseNLog(); config.Service <CrawlerService>(s => { s.ConstructUsing(name => new CrawlerService()); s.WhenStarted(service => service.Start()); s.WhenStopped(service => service.Stop()); }); //Setup Account that window service use to run. config.RunAsLocalSystem(); config.SetServiceName("SimpleFeedly.Crawler"); config.SetDisplayName("SimpleFeedly Crawler"); config.SetDescription("SimpleFeedly Crawler"); }); }
public async Task <IEnumerable <ActivityLogModel> > GetAllActivities() { const string sql = @" SELECT [Id], [Title], [Title2], [Title3], [Organizers], [Location], [StartDate], [EndDate], [OnCampus], [WebSite], [Notes], [Created], [CreatedBy] FROM [dbo].[ActivityLog] ORDER BY [CreatedBy] DESC"; List <ActivityLogModel> activities = new List <ActivityLogModel>(); try { IEnumerable <dynamic> rows = await UnitOfWork.Context().QueryAsync <dynamic>(sql); activities = ProcessRows(rows).ToList(); } catch (Exception e) { e.Data["SQL"] = sql; ErrorStore.LogException(e, HttpContext.Current); throw e; } foreach (ActivityLogModel activity in activities) { activity.Types = await GetActivityTypes(activity.Id); } return(activities); }
/// <summary> /// Get all types for a given activity log. /// </summary> /// <param name="activityId">Activity log ID.</param> /// <returns>Types for the activity.</returns> public async Task <ActivityLogTypes[]> GetActivityTypes(int activityId) { const string sql = @" SELECT [TypeId] FROM [dbo].[ActivityLogTypes] WHERE [EventId] = @EventId"; ICollection <ActivityLogTypes> types = new List <ActivityLogTypes>(); try { IEnumerable <dynamic> rows = await UnitOfWork.Context().QueryAsync <dynamic>(sql, new { EventId = activityId }); foreach (IDictionary <string, object> row in rows) { types.Add((ActivityLogTypes)(int)row["TypeId"]); } } catch (Exception e) { e.Data["SQL"] = sql; ErrorStore.LogException(e, HttpContext.Current); throw e; } // TODO: Can we refactor this to return an ICollection or something rather than an array? return(types.ToArray()); }
static void Main() { // Example of code-only setup, alteratively this can be in the App.config // rollupSeconds is 0 so a new file is always generated, for demonstration purposes ErrorStore.Setup("Samples.Console", new JSONErrorStore(path: "Errors", rollupSeconds: 0)); // Optional: for logging all unhandled exceptions AppDomain.CurrentDomain.UnhandledException += ExceptionalHandler; DisplayExceptionStats(); PauseForInput(); try { throw new Exception("Just a try/catch test"); } catch (Exception ex) { // logged, but caught so we don't crash ErrorStore.LogExceptionWithoutContext(ex); } DisplayExceptionStats(); PauseForInput(); System.Console.WriteLine("This next one will crash the program, but will be logged on the way out..."); PauseForInput(); // one not explicitly caught, will be logged by ExceptionHandler throw new Exception("I am an exception thrown on exit"); }
protected override void Write(LogEventInfo logEvent) { var exception = logEvent.Exception; // Only capture log events that include an exception. if (exception == null) { return; } var logMessage = logEvent.FormattedMessage; var logLevel = logEvent.Level.ToString().ToUpperInvariant(); var loggerName = !string.IsNullOrEmpty(logEvent.LoggerName) ? logEvent.LoggerName : "<empty>"; var logData = new Dictionary <string, string> { { "NLog-Level", logLevel }, { "NLog-LoggerName", loggerName } }; if (!string.IsNullOrEmpty(logMessage)) { logData.Add("NLog-Message", logMessage); } ErrorStore.LogExceptionWithoutContext(exception, customData: logData); }
public async Task <IEnumerable <NoteModel> > GetNotes(int studentId) { const string sql = @" SELECT n.Id AS StudentId, u.Id AS Id, u.FirstName AS CreatedByFirstName, u.LastName AS CreatedByLastName, [EntryDate], [Note], u.Id AS CreatedById FROM [dbo].[StudentNotes] n INNER JOIN [dbo].[Users] u ON [CreatedBy] = u.[Id] WHERE n.StudentId = @StudentId ORDER BY [EntryDate] DESC"; List <NoteModel> notes = new List <NoteModel>(); try { notes = (await UnitOfWork.Context().QueryAsync <NoteModel>(sql, new { StudentId = studentId })).ToList(); notes.ForEach(x => x.EntryDate = DateTimeFilter.UtcToLocal(x.EntryDate)); } catch (Exception e) { e.Data["SQL"] = e; ErrorStore.LogException(e, HttpContext.Current); } return(notes); }
public async Task InsertNote(int userId, AddStudentNoteViewModel model) { const string sql = @" INSERT INTO [dbo].[StudentNotes] ([StudentId], [CreatedBy], [EntryDate], [Note]) VALUES (@StudentId, @CreatedBy, @EntryDate, @Note)"; try { await UnitOfWork.Context().ExecuteAsync(sql, new { StudentId = model.StudentId, CreatedBy = userId, EntryDate = DateTime.Now.ToUniversalTime(), Note = model.Note.Trim() }); } catch (Exception e) { e.Data["SQL"] = sql; ErrorStore.LogException(e, HttpContext.Current); throw e; } }
private static void InitializeExceptionLog() { ErrorStore.Setup("eLink", new SqlErrorStore(null, "Default")); ErrorStore.GetCustomData = (exception, context, data) => { foreach (var key in exception.Data.Keys) { var s = key as string; if (s != null && s.StartsWith("log:", StringComparison.OrdinalIgnoreCase)) { string v; var value = exception.Data[key]; if (value == null) v = "[null]"; else v = value.ToString(); data.Add(s.Substring(4), v); } } }; ErrorStore.OnBeforeLog += (sender, args) => { if (args.Error.Exception != null && args.Error is INotLoggedException) args.Abort = true; args.Error.Cookies.Remove(FormsAuthentication.FormsCookieName); ReplaceKey(args.Error.Form, "Password"); ReplaceKey(args.Error.Form, "PasswordConfirm"); }; Dependency.Resolve<IDependencyRegistrar>().RegisterInstance<IExceptionLogger>(new ErrorStoreLogger()); }
public async Task <bool> Delete(int id) { int rowsDeleted; const string sql = @" DELETE FROM [dbo].[StudyAbroad] WHERE [Id] = @Id"; try { rowsDeleted = await UnitOfWork.Context().ExecuteAsync(sql, new { Id = id }); } catch (Exception e) { e.Data["SQL"] = sql; ErrorStore.LogException(e, HttpContext.Current); return(false); } try { await ReplaceProgramTypes(id, null); } catch (Exception) { return(false); } return(rowsDeleted == 1); }
public async Task Save(AddStudyAbroadViewModel model) { const string sql = @" INSERT INTO [dbo].[StudyAbroad] ( StudentId, Year, Semester, CreditBearing, Internship, CountryId, ProgramId, StartDate, EndDate, City ) OUTPUT INSERTED.Id VALUES ( @StudentId, @Year, @Semester, @CreditBearing, @Internship, @CountryId, @ProgramId, @StartDate, @EndDate, @City )"; if (model.StartDate.HasValue) { model.StartDate = model.StartDate.Value.ToUniversalTime(); } if (model.EndDate.HasValue) { model.EndDate = model.EndDate.Value.ToUniversalTime(); } int studyAbroadId; try { studyAbroadId = (await UnitOfWork.Context().QueryAsync <int>(sql, new { StudentId = model.StudentId, Year = model.Year, Semester = model.Semester, CreditBearing = model.CreditBearing, Internship = model.Internship, CountryId = model.CountryId, ProgramId = model.ProgramId, StartDate = model.StartDate, EndDate = model.EndDate, City = model.City })).Single(); } catch (Exception e) { e.Data["SQL"] = sql; ErrorStore.LogException(e, HttpContext.Current); throw e; } try { await ReplaceProgramTypes(studyAbroadId, model.ProgramTypes); } catch (Exception) { // Caught and logged already. } }
public async Task <IEnumerable <PromoViewModel> > GetPromos() { List <PromoViewModel> promos = new List <PromoViewModel>(); const string sql = @" SELECT p.Id AS Id, [Description], p.Created, [PublicToken], p.Active, u.FirstName AS CreatedByFirstName, u.LastName AS CreatedByLastName, (SELECT COUNT(*) FROM [StudentPromoLog] WHERE [PromoId] = p.Id) AS TotalStudents FROM [dbo].[UserPromo] p INNER JOIN [dbo].[Users] u ON [CreatedBy] = u.id ORDER BY [Description]"; try { promos = (await UnitOfWork.Context().QueryAsync <PromoViewModel>(sql)).ToList(); promos.ForEach(x => x.Created = DateTimeFilter.UtcToLocal(x.Created)); } catch (Exception e) { e.Data["SQL"] = sql; ErrorStore.LogException(e, HttpContext.Current); } return(promos); }
public async Task UpdateActivity(ActivityLogModel model) { const string sql = @" UPDATE [dbo].[ActivityLog] SET [Title] = @Title, [Title2] = @Title2, [Title3] = @Title3, [Organizers] = @Organizers, [Location] = @Location, [StartDate] = @StartDate, [EndDate] = @EndDate, [OnCampus] = @OnCampus, [WebSite] = @WebSite, [Notes] = @Notes WHERE [Id] = @Id"; try { model.StartDate = model.StartDate.ToUniversalTime(); model.EndDate = model.EndDate.ToUniversalTime(); await UnitOfWork.Context().ExecuteAsync(sql, model); } catch (Exception e) { e.Data["SQL"] = sql; ErrorStore.LogException(e, HttpContext.Current); throw e; } }
protected TestSettings GetSettings(ErrorStore store) { var settings = new TestSettings(store); settings.Store.ApplicationName = store.Settings.ApplicationName; return(settings); }
public async Task Save(int studentId, Guid promoToken) { const string sql = @" INSERT INTO [dbo].[StudentPromoLog] ([PromoId], [StudentId], [Created]) VALUES ( (SELECT [Id] FROM [dbo].[UserPromo] WHERE [PublicToken] = @PromoToken), @StudentId, @Created )"; try { await UnitOfWork.Context().ExecuteAsync(sql, new { PromoToken = promoToken, StudentId = studentId, Created = DateTime.Now.ToUniversalTime() }); } catch (Exception e) { e.Data["SQL"] = sql; ErrorStore.LogException(e, HttpContext.Current); } }
public async Task AssociatePeopleWithActivity(int activityId, IEnumerable <ActivityLogParticipantModel> people) { const string sql = @" INSERT INTO [dbo].[ActivityLogParticipant] ([EventId], [PersonId], [ParticipantType]) VALUES (@EventId, @PersonId, @Type)"; try { foreach (ActivityLogParticipantModel person in people) { await UnitOfWork.Context().ExecuteAsync(sql, new { EventId = activityId, PersonId = person.Person.Id, Type = person.Type }); } } catch (Exception e) { e.Data["SQL"] = sql; ErrorStore.LogException(e, HttpContext.Current); throw e; } }
protected void Application_Start() { // Instead of any web.config entries, you can setup entirely through code // Setup Exceptional: // memory example: //ErrorStore.Setup("My Error Log Name", new MemoryErrorStore()); // JSON example //ErrorStore.Setup("My Error Log Name", new JSONErrorStore(path: "~/Errors")); // SQL Example //ErrorStore.Setup("My Error Log Name", new SQLErrorStore(connectionString: "Data Source=.;Initial Catalog=Exceptions;Integrated Security=SSPI;")); // Optionally add custom data to any logged exception (visible on the exception detail page): ErrorStore.GetCustomData = (exception, context, data) => { // exception is the exception thrown // context is the HttpContext of the request (could be null, e.g. background thread exception) // data is a Dictionary<string, string> to add custom data too data.Add("Example string", DateTime.UtcNow.ToString()); data.Add("User Id", "You could fetch a user/account Id here, etc."); data.Add("Links get linkified", "http://www.google.com"); }; ErrorStore.AddJSInclude("~/Content/errors.js"); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
public async Task Update(UserModel model) { const string sql = @" UPDATE [dbo].[Users] SET [FirstName] = @FirstName, [LastName] = @LastName, [Email] = @Email, [Password] = @Password, [Admin] = @Admin, [Active] = @Active WHERE [Id] = @Id"; try { await UnitOfWork.Context().ExecuteAsync(sql, new { FirstName = model.FirstName.Trim(), LastName = model.LastName.Trim(), Email = model.Email.Trim(), Password = model.Password, Admin = model.IsAdmin, Active = model.IsActive, Id = model.Id }); } catch (Exception e) { e.Data["SQL"] = sql.ToString(); ErrorStore.LogException(e, HttpContext.Current); throw e; } }
/// <summary> /// Fires on Application Error /// </summary> protected void Application_Error(object sender, EventArgs e) { var environment = ConfigurationManager.AppSettings["Environment"]; if (environment != "dev") { var ex = Server.GetLastError().GetBaseException(); Context.Response.Clear(); Server.ClearError(); var routeData = new RouteData(); routeData.Values.Add("controller", "Error"); routeData.Values.Add("action", "500"); if (ex.GetType() == typeof(HttpException)) { var httpException = (HttpException)ex; var code = httpException.GetHttpCode(); // Is it a 4xx Error if (code % 400 < 100) { routeData.Values["action"] = "404"; } } ErrorStore.LogException(ex, this.Context); routeData.Values.Add("error", ex); IController errorController = new ErrorController(); errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); } }
private async Task SaveStudentLanguages(int studentId, string tableName, IEnumerable <int> languages) { await DeleteLanguages(studentId, tableName); if (languages != null && languages.Any()) { string insertSql = string.Format(@" INSERT INTO [dbo].[{0}] ([StudentId], [LanguageId]) VALUES (@StudentId, @LanguageId)", tableName); try { foreach (int languageId in languages) { await UnitOfWork.Context().ExecuteAsync(insertSql, new { StudentId = studentId, LanguageId = languageId }); } } catch (Exception e) { e.Data["SQL"] = insertSql.ToString(); ErrorStore.LogException(e, HttpContext.Current); throw e; } } }
/// <summary> /// manually write an exception to our standard exception log /// </summary> public static void LogException(Exception ex, bool rollupPerServer = false) { try { ErrorStore.LogException(ex, Context, appendFullStackTrace: true, rollupPerServer: rollupPerServer); } catch { /* Do nothing */ } }
/// <summary> /// Creates a new <see cref="WebPage"/> for rendering. /// </summary> /// <param name="error">The current error (null if not on an error-specific page).</param> /// <param name="store">The store to render.</param> /// <param name="baseURL">The base URL for the current request.</param> /// <param name="pageTitle">The title of the page.</param> protected WebPage(Error error, ErrorStore store, string baseURL, string pageTitle) { Error = error; Store = store; BaseUrl = baseURL.EndsWith("/") ? baseURL : baseURL + "/"; PageTitle = pageTitle; HeaderTitle = "Exceptions Log: " + Settings.ApplicationName.HtmlEncode(); }
public static IMatsTelemetryClient CreateMats(IApplicationConfiguration applicationConfiguration, IPlatformProxy platformProxy, IMatsConfig matsConfig) { string dpti = platformProxy.GetDevicePlatformTelemetryId(); if (!IsDeviceEnabled(matsConfig.AudienceType, dpti)) { return(null); } string deviceNetworkState = platformProxy.GetDeviceNetworkState(); int osPlatformCode = platformProxy.GetMatsOsPlatformCode(); bool enableAggregation = true; IEventFilter eventFilter = new EventFilter(enableAggregation); var errorStore = new ErrorStore(); var scenarioStore = new ScenarioStore(TimeConstants.ScenarioTimeoutMilliseconds, errorStore); var allowedScopes = new HashSet <string>(); if (matsConfig.AllowedScopes != null) { foreach (string s in matsConfig.AllowedScopes) { allowedScopes.Add(s); } } var actionStore = new ActionStore( TimeConstants.ActionTimeoutMilliseconds, TimeConstants.AggregationWindowMilliseconds, errorStore, eventFilter, allowedScopes); var contextStore = ContextStore.CreateContextStore( matsConfig.AudienceType, applicationConfiguration.ClientName, applicationConfiguration.ClientVersion, dpti, deviceNetworkState, matsConfig.SessionId, osPlatformCode); IUploader uploader = new TelemetryUploader(matsConfig.DispatchAction, platformProxy, applicationConfiguration.ClientName); // it's this way in mats c++ bool isScenarioUploadDisabled = true; return(new MatsTelemetryClient( applicationConfiguration, platformProxy, errorStore, uploader, actionStore, scenarioStore, contextStore, isScenarioUploadDisabled)); }
/// <summary> /// manually write an exception to our standard exception log /// </summary> public static void LogException(Exception ex, string key = null, int?reLogDelaySeconds = null) { if (!ShouldLog(key)) { return; } ErrorStore.LogException(ex, Context, appendFullStackTrace: true); RecordLogged(key); }
public async Task <bool> InsertActivityLogDocument(int activityLogId, int userId, HttpPostedFileBase document) { // ContentLength hardcoded into SQL statements because as a // parameter it's always zero. Unsure if it's Dapper or something // else. string sql = string.Format(@" UPDATE [dbo].[Documents] SET [Content] = @Content, [Size] = {0}, [MimeType] = @MimeType, [LastModified] = @LastModified, [LastModifiedBy] = @LastModifiedBy, [Deleted] = NULL, [DeletedBy] = NULL WHERE [ActivityLogId] = @ActivityLogId AND LOWER([Title]) = LOWER(@Title) IF @@ROWCOUNT = 0 INSERT INTO [dbo].[Documents] ( [Id], [Created], [CreatedBy], [ActivityLogId], [Title], [Size], [MimeType], [Content] ) VALUES ( @Id, @Created, @CreatedBy, @ActivityLogId, @Title, {0}, @MimeType, @Content );", document.ContentLength); try { await UnitOfWork.Context().ExecuteAsync(sql, new { Content = GetDocumentFromPostedFileBase(document.InputStream), ActivityLogId = activityLogId, Title = document.FileName, Id = Guid.NewGuid(), Created = DateTime.Now.ToUniversalTime(), CreatedBy = userId, MimeType = document.ContentType, LastModified = DateTime.Now.ToUniversalTime(), LastModifiedBy = userId }); return(true); } catch (Exception e) { e.Data["SQL"] = sql; ErrorStore.LogException(e, HttpContext.Current); } return(false); }
// Optional, for logging all unhanled exceptions on the way out static void ExceptionalHandler(object sender, UnhandledExceptionEventArgs e) { // e.ExceptionObject may not be an exception, refer to http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf // section 10.5, CLS Rule 40 if you're curious on why this check needs to happen var exception = e.ExceptionObject as Exception; if (exception != null) { ErrorStore.LogExceptionWithoutContext(exception); } }
void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs // Get the exception object. Exception exc = Server.GetLastError(); ErrorStore.LogException(exc, null); // Server.ClearError(); }
private static void ErrorHandle(Exception ex, string feedUrl) { // we can send an email for warning right here if needed // or just log error into some error stores, it's up to you ErrorStore.LogExceptionWithoutContext(ex, false, false, new Dictionary <string, string> { { "feedUrl", feedUrl } }); }