/// <summary> /// Removes an sql dependecy set on a HttpRuntime.Cache key. This method only removes /// the dependency, it does not purge the actual item from cache. /// </summary> /// <param name="key">The cache key.</param> public static void RemoveDependecy(string key) { SqlConnection con = new SqlConnection(_ConnectionString); DataAccessManager dam = new DataAccessManager(ConnectionString); dam.AddInputParameter("@CacheKey", key); dam.AddInputParameter("@ApplicationId", ClusteredCacheController.ApplicationId); try { dam.ExecuteNonQuery(GetFormattedStoredProcedureName(SP_DELETE)); } catch { throw; } finally { switch (ClusteredCacheController.ClusteredCachingMode) { case ClusteredCachingMode.ServiceBroker: #region service broker string dependencyId = GetDependencyIDFromCacheKey(key); if (!string.IsNullOrEmpty(dependencyId)) { _ServiceBrokerDependencies[dependencyId].SqlDependency.OnChange -= OnChange; _ServiceBrokerDependencies.Remove(dependencyId); } #endregion break; case ClusteredCachingMode.CheckAtRequest: CheckAtRequestDependencies.Remove(key); break; } } }
/// <summary> /// Purges a clustered cache item from cache. Calling this method purges the cache record /// associated with the specified key from all machines on the cluster. /// </summary> /// <param name="key">The cache key.</param> public static void PurgeCacheItem(string key) { DataAccessManager dam = new DataAccessManager(ConnectionString); dam.AddInputParameter("@CacheKey", key); dam.AddInputParameter("@LastUpdate", DateTime.UtcNow.Ticks); dam.AddInputParameter("@ApplicationId", ClusteredCacheController.ApplicationId); dam.ExecuteNonQuery(GetFormattedStoredProcedureName(SP_INSERT_UPDATE)); switch (ClusteredCacheController.ClusteredCachingMode) { case ClusteredCachingMode.ServiceBroker: #region service broker if (ClusteredCacheController.MillisecondsToSleepAfterCachePurge > 0) { Thread.Sleep(ClusteredCacheController.MillisecondsToSleepAfterCachePurge); } #endregion break; case ClusteredCachingMode.CheckAtRequest: break; } }
/// <summary> /// Updates the exception handling status. /// </summary> /// <param name="exceptionId">The id of the exception record to update</param> /// <param name="handlingStatus">The new handlig status</param> public static void UpdateExceptionHandlingStatus(long exceptionId, ExceptionHandlingStatus handlingStatus) { DataAccessManager dam = new DataAccessManager(ConnectionString); dam.AddInputParameter("@ExceptionId", exceptionId); dam.AddInputParameter("@HandlingStatus", (byte)handlingStatus); dam.ExecuteNonQuery(GetFormattedStoredProcedureName(SP_EXCEPTIONS_UPDATE)); }
/// <summary> /// Deletes exception records older than a specific amount of days. /// </summary> /// <param name="applicationId">The application id.</param> /// <param name="exceptionId">The ExceptionId of the exception record to delete</param> /// <param name="olderThanInDays">The amount of days.</param> protected static void DeleteExceptionRecords(int?applicationId, long?exceptionId, int?olderThanInDays) { DataAccessManager dam = new DataAccessManager(ConnectionString); dam.AddInputParameter("@ApplicationId", (applicationId.HasValue ? applicationId.Value : -1)); dam.AddInputParameter("@ExceptionId", (exceptionId.HasValue ? exceptionId.Value : -1)); dam.AddInputParameter("@OlderThanInDays", (olderThanInDays.HasValue ? olderThanInDays.Value : -1)); dam.ExecuteNonQuery(GetFormattedStoredProcedureName(SP_EXCEPTIONS_DELETE)); }
/// <summary> /// Deletes the event records. /// </summary> /// <param name="applicationId">The application id.</param> /// <param name="eventId">The EventId of the record to delete.</param> /// <param name="olderThanInDays">The amount of days.</param> /// <param name="eventTypeFilter">The event type filter.</param> protected static void DeleteEventRecords(int?applicationId, long?eventId, int?olderThanInDays, int?eventTypeFilter) { DataAccessManager dam = new DataAccessManager(ConnectionString); dam.AddInputParameter("@ApplicationId", (applicationId.HasValue ? applicationId.Value : -1)); dam.AddInputParameter("@EventId", (eventId.HasValue ? eventId.Value : -1)); dam.AddInputParameter("@OlderThanInDays", (olderThanInDays.HasValue ? olderThanInDays.Value : -1)); dam.AddInputParameter("@EventType", (eventTypeFilter.HasValue ? eventTypeFilter.Value : -1)); dam.ExecuteNonQuery(GetFormattedStoredProcedureName(SP_EVENTLOG_DELETE)); }
/// <summary> /// Gets the event page. /// </summary> /// <param name="applicationId">The application id.</param> /// <param name="pageSize">Size of the page.</param> /// <param name="pageIndex">Index of the page.</param> /// <param name="rowCount">The row count.</param> /// <param name="appLocationFilter">The app location filter.</param> /// <param name="eventTypeFilter">The event type filter.</param> /// <param name="userId">The user id.</param> /// <param name="startDate">The start date.</param> /// <param name="endDate">The end date.</param> /// <returns></returns> public static LogDatasets.EventLogDataTable GetEventPage(int applicationId, int pageSize, int pageIndex, out int?rowCount, int appLocationFilter, int eventTypeFilter , int userId, DateTime startDate, DateTime endDate) { rowCount = 0; DataAccessManager dam = new DataAccessManager(ConnectionString); dam.AddInputParameter("@ApplicationId", applicationId); dam.AddInputParameter("@PageIndex", pageIndex); dam.AddInputParameter("@PageSize", pageSize); dam.AddInputParameter("@AppLocationFilter", appLocationFilter); dam.AddInputParameter("@EventTypeFilter", eventTypeFilter); dam.AddInputParameter("@AuthenticatedUserIdFilter", userId.ToString()); dam.AddInputParameter("@StartDate", startDate); dam.AddInputParameter("@EndDate", endDate); dam.AddOutPutParameter("@RowCount", SqlDbType.Int); Dictionary <string, object> outputParameters = new Dictionary <string, object>(); LogDatasets.EventLogDataTable dt = dam.ExecuteTableQuery <LogDatasets.EventLogDataTable>(GetFormattedStoredProcedureName(SP_EVENTLOG_GETPAGE_WITHFILTERS), out outputParameters); rowCount = (int)outputParameters["@RowCount"]; return(dt); }
/// <summary> /// Removes an sql dependecy set on a HttpRuntime.Cache key. This method only removes /// the dependency, it does not purge the actual item from cache. /// </summary> public static void RemoveAllDependecies() { SqlConnection con = new SqlConnection(_ConnectionString); DataAccessManager dam = new DataAccessManager(ConnectionString); dam.AddInputParameter("@ApplicationId", ClusteredCacheController.ApplicationId); try { dam.ExecuteNonQuery(GetFormattedStoredProcedureName(SP_DELETE_ALL)); } catch { throw; } finally { switch (ClusteredCacheController.ClusteredCachingMode) { case ClusteredCachingMode.ServiceBroker: #region service broker _ServiceBrokerDependencies.Clear(); #endregion break; case ClusteredCachingMode.CheckAtRequest: CheckAtRequestDependencies.Clear(); break; } } }
/// <summary> /// This methods writes all queued events to the database. Implement this method at the global.asax at web projects to ensure /// that all the queued events in memory get written to the database at a system crash. /// </summary> public static void SafeAllPendingEvents() { if (EventLogTable.Count == 0) { return; } // first generate the xml string StringBuilder sb = new StringBuilder("<" + INSERT_NODE + ">"); foreach (LogDatasets.EventLogRow row in EventLogTable.Rows) { sb.Append(string.Format(INSERT_EVENT_TAG , row.AppLocation , row.EventDate.ToString("MM.dd.yyyy HH:mm:ss") , row.EventType , row.Message.Replace(@"""", @""").Replace("<", "<").Replace(">", ">") , row.MachineName , row.AuthenticatedUserId , row.ApplicationId)); } sb.Append("</" + INSERT_NODE + ">"); // now send to the db DataAccessManager dam = new DataAccessManager(ConnectionString); dam.AddInputParameter("@EventXml", sb.ToString()); dam.ExecuteNonQuery(GetFormattedStoredProcedureName(SP_EVENTLOG_INSERTBATCH)); // we are finished, clear the table... EventLogTable.Clear(); }
/// <summary> /// Determines whether [is up to date] [the specified key]. /// </summary> /// <param name="key">The key.</param> /// <param name="synchTicks">The synch ticks.</param> /// <returns></returns> public static ClusteredCachingSynchronizationStatus IsUpToDate(string key, out long synchTicks) { #region check whether we can delay the synchronization check if (ClusteredCacheController.CheckAtRequestIsUpToDateDelayInMilliseconds > 0 && CheckAtRequestDependencies.ContainsKey(key) && CheckAtRequestDependencies[key].LastChecked.HasValue && CheckAtRequestDependencies[key].LastChecked.Value.AddMilliseconds(ClusteredCacheController.CheckAtRequestIsUpToDateDelayInMilliseconds) > DateTime.UtcNow) { synchTicks = CheckAtRequestDependencies[key].Ticks; return(ClusteredCachingSynchronizationStatus.UpToDate); } #endregion DataAccessManager dam = new DataAccessManager(ConnectionString); dam.AddInputParameter("@CacheKey", key); dam.AddInputParameter("@ApplicationId", ClusteredCacheController.ApplicationId); synchTicks = dam.ExecuteScalar <long>(GetFormattedStoredProcedureName(SP_SELECT)); if (synchTicks <= 0) { return(ClusteredCachingSynchronizationStatus.RemovedFromCollection); } else { if (CheckAtRequestDependencies.ContainsKey(key)) { if (CheckAtRequestDependencies[key].Ticks.Equals(synchTicks)) { if (ClusteredCacheController.CheckAtRequestIsUpToDateDelayInMilliseconds > 0) { CheckAtRequestDependencies[key] = GetCheckAtRequestInfo(synchTicks); } return(ClusteredCachingSynchronizationStatus.UpToDate); } else { return(ClusteredCachingSynchronizationStatus.OutOfDate); } } else { return(ClusteredCachingSynchronizationStatus.NotFound); } } }
/// <summary> /// Logs an event. /// </summary> /// <param name="applicationId">The application id.</param> /// <param name="appLocation">The Application location. This parameter should represent where in your application the event occurred, e.g. MyEnum.BusinessLayer or MyEnum.UserCreation</param> /// <param name="eventType">Type of the event. This parameter should represent the type of your event, e.g. MyEnum.Information</param> /// <param name="message">The event message.</param> /// <param name="authenticatedUserId">The authenticated user id.</param> public static void LogEvent(int applicationId, int appLocation, int eventType, string message, string authenticatedUserId) { DataAccessManager dam = new DataAccessManager(ConnectionString); dam.AddInputParameter("@ApplicationId", applicationId); dam.AddInputParameter("@AppLocation", appLocation); dam.AddInputParameter("@EventType", eventType); dam.AddInputParameter("@Message", message); dam.AddInputParameter("@MachineName", System.Environment.MachineName); dam.AddInputParameter("@AuthenticatedUserId", authenticatedUserId); dam.ExecuteNonQuery(GetFormattedStoredProcedureName(SP_EVENTLOG_INSERT)); }
/// <summary> /// Gets the exception page. /// </summary> /// <param name="applicationId">The application id.</param> /// <param name="pageSize">The amount of record rows to retrieve.</param> /// <param name="pageIndex">The index of the page to retrieve.</param> /// <param name="rowCount">The total amount of rows of the exception table.</param> /// <param name="appLocationFilter">The ApplicationLocation to filter. Set this value to -1 if you don't want to filter by application locations.</param> /// <param name="handlingStatus">The handling status of this exception. Set this value to -1 if you don't want to filter by handling status.</param> /// <param name="orderBy">The order by.</param> /// <returns></returns> public static LogDatasets.ExceptionLogDataTable GetExceptionPage(int applicationId, int pageSize, int pageIndex, out int?rowCount, int appLocationFilter, int handlingStatus , ExceptionsOrderBy orderBy) { rowCount = 0; DataAccessManager dam = new DataAccessManager(ConnectionString); dam.AddInputParameter("@ApplicationId", applicationId); dam.AddInputParameter("@PageIndex", pageIndex); dam.AddInputParameter("@PageSize", pageSize); dam.AddInputParameter("@AppLocationFilter", appLocationFilter); dam.AddInputParameter("@HandlingStatus", handlingStatus); dam.AddOutPutParameter("@RowCount", SqlDbType.Int); dam.AddInputParameter("@OrderBy", (int)orderBy); Dictionary <string, object> outputParameters = new Dictionary <string, object>(); LogDatasets.ExceptionLogDataTable dt = dam.ExecuteTableQuery <LogDatasets.ExceptionLogDataTable>(GetFormattedStoredProcedureName(SP_EXCEPTIONS_GETPAGE), out outputParameters); rowCount = (int)outputParameters["@RowCount"]; return(dt); }
/// <summary> /// Adds an object to the HttpRuntime.Cache collection and sets an SQL Dependency on it's /// key. /// </summary> /// <param name="key">The cache key.</param> /// <param name="item">The item to add to the cache.</param> /// <param name="priority">The priority.</param> public static void AddCacheItem(string key, object item, CacheItemPriority priority) { if (ClusteredCacheController.ClusteredCachingMode == ClusteredCachingMode.ServiceBroker) { if (_ServiceBrokerDependencies.ContainsKey(key)) { _ServiceBrokerDependencies.Remove(key); } } #region insert/update at database long utcNow = DateTime.UtcNow.Ticks; DataAccessManager dam = new DataAccessManager(ConnectionString); dam.AddInputParameter("@CacheKey", key); dam.AddInputParameter("@LastUpdate", utcNow); dam.AddInputParameter("@ApplicationId", ClusteredCacheController.ApplicationId); dam.ExecuteNonQuery(GetFormattedStoredProcedureName(SP_INSERT_UPDATE)); #endregion #region add to cache collection HttpRuntime.Cache.Remove(key); HttpRuntime.Cache.Insert(key, item, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, priority, null); #endregion #region add dependency switch (ClusteredCacheController.ClusteredCachingMode) { case ClusteredCachingMode.ServiceBroker: #region service broker SqlConnection con = new SqlConnection(_ConnectionString); SqlCommand cmd = new SqlCommand(GetFormattedStoredProcedureName(SP_SELECT), con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@CacheKey", SqlDbType.NVarChar, 256); cmd.Parameters[0].Value = key; // Clear any existing notifications cmd.Notification = null; // Create the dependency for this command SqlDependency dependency = new SqlDependency(cmd); // Add the event handler dependency.OnChange += new OnChangeEventHandler(OnChange); #region execute reader try { con.Open(); // Execute the command. cmd.ExecuteReader(); // Process the DataReader } catch (SqlException err) { DataAccessManager.ThrowDataAccessManagerException(err, GetFormattedStoredProcedureName(SP_SELECT)); } finally { con.Close(); } #endregion _ServiceBrokerDependencies.Add(dependency.Id, new CacheKeySqlDependency() { CacheKey = key, SqlDependency = dependency }); #endregion break; case ClusteredCachingMode.CheckAtRequest: if (CheckAtRequestDependencies.ContainsKey(key)) { CheckAtRequestDependencies[key] = GetCheckAtRequestInfo(utcNow); } else { CheckAtRequestDependencies.Add(key, GetCheckAtRequestInfo(utcNow)); } break; } #endregion }
/// <summary> /// Logs an exception. /// </summary> /// <param name="applicationId">The application id.</param> /// <param name="appLocation">The Application location. This parameter should represent where in your application the event occurred, e.g. MyEnum.BusinessLayer or MyEnum.UserCreation</param> /// <param name="handlindStatus">The handling status of this exception.</param> /// <param name="e">The exception to log.</param> /// <param name="authenticatedUserId">The authenticated user id.</param> public static void LogException(int applicationId, int appLocation, ExceptionHandlingStatus handlindStatus, Exception e, string authenticatedUserId) { DataAccessManager dam = new DataAccessManager(ConnectionString); string hashCode = string.Empty; HttpContext context = HttpContext.Current; if (context != null) { hashCode = (appLocation.ToString() + context.Request.Url.PathAndQuery + e.ToString()); dam.AddInputParameter("@ApplicationId", applicationId); dam.AddInputParameter("@AppLocation", appLocation); dam.AddInputParameter("@Exception", e.GetType().ToString()); dam.AddInputParameter("@ExceptionMessage", ConversionHelper.GetFormattedException(string.Empty, e, TextFormat.HTML)); dam.AddInputParameter("@Method", e.TargetSite == null ? string.Empty : e.TargetSite.ToString()); dam.AddInputParameter("@IPAddress", context.Request.UserHostAddress); dam.AddInputParameter("@UserAgent", context.Request.UserAgent); dam.AddInputParameter("@HttpReferrer", context.Request.UrlReferrer == null ? null : context.Request.UrlReferrer.ToString()); dam.AddInputParameter("@HttpVerb", context.Request.HttpMethod); dam.AddInputParameter("@Url", context.Request.Url.ToString()); dam.AddInputParameter("@HashCode", hashCode.GetHashCode()); dam.AddInputParameter("@HandlingStatus", (byte)handlindStatus); dam.AddInputParameter("@AuthenticatedUserId", authenticatedUserId); dam.AddInputParameter("@MachineName", System.Environment.MachineName); } else { hashCode = (appLocation.ToString() + e.ToString()); dam.AddInputParameter("@ApplicationId", applicationId); dam.AddInputParameter("@AppLocation", appLocation); dam.AddInputParameter("@Exception", e.GetType().ToString()); dam.AddInputParameter("@ExceptionMessage", ConversionHelper.GetFormattedException(string.Empty, e, TextFormat.HTML)); dam.AddInputParameter("@Method", e.TargetSite == null ? string.Empty : e.TargetSite.ToString()); dam.AddInputParameter("@IPAddress", null); dam.AddInputParameter("@UserAgent", null); dam.AddInputParameter("@HttpReferrer", null); dam.AddInputParameter("@HttpVerb", null); dam.AddInputParameter("@Url", null); dam.AddInputParameter("@HashCode", hashCode.GetHashCode()); dam.AddInputParameter("@HandlingStatus", (byte)handlindStatus); dam.AddInputParameter("@AuthenticatedUserId", authenticatedUserId); dam.AddInputParameter("@MachineName", System.Environment.MachineName); } dam.ExecuteNonQuery(GetFormattedStoredProcedureName(SP_EXCEPTIONS_INSERT)); }