public void CanReflectOnSecurityExceptionWithoutPermission() { SecurityPermission denyPermission = new SecurityPermission(SecurityPermissionFlag.ControlPolicy | SecurityPermissionFlag.ControlEvidence); PermissionSet permissions = new PermissionSet(PermissionState.None); permissions.AddPermission(denyPermission); permissions.Deny(); SecurityException exception = null; try { DemandException(denyPermission); } catch (SecurityException e) { exception = e; } ExceptionFormatter formatter = new ExceptionFormatter(); String message = formatter.GetMessage(exception); Match demandedMatch = DemandedEntryRegex.Match(message); Assert.IsNotNull(demandedMatch); Assert.AreEqual(Resources.PropertyAccessFailed, demandedMatch.Groups[1].Value); CodeAccessPermission.RevertDeny(); message = formatter.GetMessage(exception); demandedMatch = DemandedEntryRegex.Match(message); Assert.IsNotNull(demandedMatch); Assert.AreNotEqual(Resources.PropertyAccessFailed, demandedMatch.Groups[1].Value); }
public IProvider GetProvider(IContext context) { _ = context ?? throw new ArgumentNullException(nameof(context)); return(this.ProviderCallback == null ? throw new ActivationException(ExceptionFormatter.ProviderCallbackIsNull(context)) : this.ProviderCallback(context)); }
Exception AmbiguousObjectBuilderException(bool hasInfo) { return(hasInfo ? new AmbiguousObjectBuilderException( ExceptionFormatter.Format("More than one ObjectBuilders matches the request for the contract type [{0}] and the injection condition while only one is needed! Please make sure to invoke the IObjectContainer.ResolveAll/IObjectContainer.TryResolveAll methods, instead of IObjectContainer.Resolve/IObjectContainer.TryResolve methods!", _candidates[0].ObjectDescription.ContractType.ToTypeName())) : new AmbiguousObjectBuilderException( ExceptionFormatter.Format("More than one ObjectBuilders matches the request for the contract type [{0}] while only one is needed! Please make sure to invoke the IObjectContainer.ResolveAll/IObjectContainer.TryResolveAll methods, instead of IObjectContainer.Resolve/IObjectContainer.TryResolve methods!", _candidates[0].ObjectDescription.ContractType.ToTypeName()))); }
public override void RuntimeInitialize(MethodBase method) { base.RuntimeInitialize(method); if (Formatter != null) { MessageFormatter = Activator.CreateInstance(Formatter) as ExceptionFormatter; } }
public void Can_add_exceptionLayouts_by_scanning_assemblies() { // Arrange && Assert var formatter = ExceptionFormatter.Create(this.GetType().Assembly); // Assert ((ExceptionFormatter)formatter).ExceptionLayouts.Should().NotBeEmpty(); }
protected string CauseToString(string prefix = "Cause: ") { if (_causedByFailure == null) { return(""); } return(ExceptionFormatter.DebugFormat(_causedByFailure, prefix)); }
private void RegisterExceptionFormatterFor(LoggerName name, ExceptionFormatter formatter) { if (formatter == null) { throw new ArgumentNullException("formatter"); } RegisterValueFor <ExceptionFormatter>(name, nameToExceptionFormatterMapping, formatter); }
public void FormatReturnsEmptyStringForNullException() { var formatter = new ExceptionFormatter(); string result = formatter.Format(null, new Logger()); Assert.AreEqual(string.Empty, result); }
public void RegisterExceptionFormatterFor(string name, ExceptionFormatter formatter) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } RegisterExceptionFormatterFor(new LoggerName(name), formatter); }
public void RegisterExceptionFormatterFor(Type type, ExceptionFormatter formatter) { if (type == null) { throw new ArgumentNullException("type"); } RegisterExceptionFormatterFor(new LoggerName(type), formatter); }
public static void WoxError(this NLog.Logger logger, string message, System.Exception exception, [CallerMemberName] string methodName = "") { Debug.WriteLine($"ERROR|{logger.Name}|{methodName}|{message}"); logger.Error($"{methodName}|{message}|{ExceptionFormatter.FormattedException(exception)}"); #if DEBUG throw exception; #endif }
public IActionResult UpdatePicklistLayout([FromRoute] string name, [FromRoute] Guid id, [FromBody] LayoutModel layout) { try { var stopwatch = StopwatchLogger.Start(_log); _log.Info("Called PicklistController UpdatePicklistLayout with LayoutModel {0}=", JsonConvert.SerializeObject(layout)); _log.Info("Called PicklistController UpdatePicklistLayout with name {0}=", name); _log.Info("Called PicklistController UpdatePicklistLayout with id {0}=", id); #region API validation if (string.IsNullOrEmpty(name)) { return(BadRequest("Picklist name required")); } if (id == Guid.Empty) { return(BadRequest("Picklist id required")); } if (layout == null) { return(BadRequest("Layout required")); } if (!Enum.IsDefined(typeof(LayoutType), layout.LayoutType)) { return(BadRequest("Layout type required")); } #endregion layout.ModifiedBy = UserId; if (layout.LayoutType == LayoutType.List) { layout.Layout = JsonConvert.SerializeObject(layout.ListLayoutDetails, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); } else if (layout.LayoutType == LayoutType.Form) { layout.Layout = JsonConvert.SerializeObject(layout.FormLayoutDetails, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); } else if (layout.LayoutType == LayoutType.View) { layout.Layout = JsonConvert.SerializeObject(layout.ViewLayoutDetails, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); } _iLayoutManager.UpdatePicklistLayout(TenantCode, id, layout); stopwatch.StopAndLog("UpdatePicklistLayout method of PicklistController."); return(Ok(HttpStatusCode.OK)); } catch (Exception ex) { _log.Error(ExceptionFormatter.SerializeToString(ex)); return(StatusCode((int)HttpStatusCode.InternalServerError, ApiConstant.CustomErrorMessage)); } }
public IActionResult CreateMenu([FromBody] MenuItem menuItem) { try { var stopwatch = StopwatchLogger.Start(_log); _log.Info("Called MenuController CreateMenu"); if (menuItem != null && menuItem.ReferenceEntityId != null) { if (menuItem.MenuTypeId == 1) { menuItem.ReferenceEntityId = _iMetadataManager.GetEntityContextByEntityName(menuItem.ReferenceEntityId, false); } else if (menuItem.MenuTypeId == 2) { menuItem.ReferenceEntityId = _iMetadataManager.GetEntityContextByEntityName(menuItem.ReferenceEntityId, true); } } using (TransactionScope ts = new TransactionScope()) { //create menu var retVal = _iMenuManager.CreateMenu(menuItem, UserId, TenantCode); _iMenuManager.ClearMenuCache(TenantCode); //create resource //get language key value string langKey = ""; string langValue = ""; var retLan = _resourceManager.GetDefaultLanguageByTenant(TenantCode); if (retLan != null && retLan.Key != null) { langKey = Convert.ToString(retLan.Key); } if (retLan != null && retLan.Text != null) { langValue = Convert.ToString(retLan.Text); } //check resource by key var retRes = _resourceManager.GetResourcesByKey(TenantCode, menuItem.Menucode); if (retRes.Count == 0) { string msg = ""; _resourceManager.Create(TenantCode, new Entities.EntityCore.Model.Resource.Resource(menuItem.Menucode, menuItem.Name, langKey, langValue, menuItem.ReferenceEntityId, false), UserId, ref msg); } ts.Complete(); stopwatch.StopAndLog("CreateMenu method of MenuController"); return(Ok(retVal)); } } catch (Exception ex) { _log.Error(ExceptionFormatter.SerializeToString(ex)); return(StatusCode((int)HttpStatusCode.InternalServerError, ApiConstant.CustomErrorMessage)); } }
private object ResolveInternal(object scope) { var cachedInstance = this.Cache.TryGet(this); if (cachedInstance != null) { return(cachedInstance); } this.Request.ActiveBindings.Push(this.Binding); var reference = new InstanceReference { Instance = this.GetProvider().Create(this) }; this.Request.ActiveBindings.Pop(); if (reference.Instance == null) { if (!this.Kernel.Settings.AllowNullInjection) { throw new ActivationException(ExceptionFormatter.ProviderReturnedNull(this)); } if (this.Plan == null) { this.Plan = this.Planner.GetPlan(this.Request.Service); } return(null); } if (scope != null) { this.Cache.Remember(this, reference); } if (this.Plan == null) { this.Plan = this.Planner.GetPlan(reference.Instance.GetType()); } try { this.Pipeline.Activate(this, reference); } catch (ActivationException) { if (scope != null) { this.Cache.Release(reference.Instance); } throw; } return(reference.Instance); }
/// <summary> /// Gets the provider for the binding. /// </summary> /// <param name="context">The context.</param> /// <returns>The provider to use.</returns> public IProvider GetProvider(IContext context) { if (this.ProviderCallback == null) { throw new ActivationException(ExceptionFormatter.ProviderCallbackIsNull(context)); } return(this.ProviderCallback(context)); }
internal Log4NetTextFormatterOptions(IFormatProvider?formatProvider, CDataMode cDataMode, XmlQualifiedName?xmlNamespace, XmlWriterSettings xmlWriterSettings, PropertyFilter filterProperty, ExceptionFormatter formatException) { FormatProvider = formatProvider; CDataMode = cDataMode; XmlNamespace = xmlNamespace; XmlWriterSettings = xmlWriterSettings; FilterProperty = filterProperty; FormatException = formatException; }
public void GetString_WithoutCallstack_ShouldSucceed() { Exception testException = GetTestException(); var exceptionFormatter = new ExceptionFormatter(); string text = exceptionFormatter.GetText(testException, false); Assert.Equal("Test outer exception --> Test inner exception", text); }
/// <summary> /// let exception throw as normal is better for Debug /// </summary> // [Conditional("RELEASE")] private static void RegisterAppDomainExceptions() { AppDomain.CurrentDomain.UnhandledException += ErrorReporting.UnhandledExceptionHandle; AppDomain.CurrentDomain.FirstChanceException += (_, e) => { Log.Error("|App.RegisterAppDomainExceptions|First Chance Exception:" + ExceptionFormatter.FormatExcpetion(e.Exception)); // Log.Error("|App.RegisterAppDomainExceptions|First Chance Exception:"+ e); }; }
private static void Report(Exception e, [CallerMemberName] string method = "") { var logger = LogManager.GetLogger(method); logger.Fatal(ExceptionFormatter.ExceptionWithRuntimeInfo(e)); var reportWindow = new ReportWindow(e); reportWindow.Show(); }
/*----------------------------------------------------------------------------------------*/ /// <summary> /// Unloads the module from the kernel. /// </summary> public virtual void Unload() { if (!IsLoaded) { throw new InvalidOperationException(ExceptionFormatter.CannotUnloadModuleThatIsNotLoaded(this)); } Bindings.Each(Kernel.RemoveBinding); }
private static void Report(Exception e) { var logger = LogManager.GetLogger("UnHandledException"); logger.Fatal(ExceptionFormatter.FormatExcpetion(e)); var reportWindow = new ReportWindow(e); reportWindow.Show(); }
public void ShouldGenerateSameFormatAsToStringWhenStripFalse() { var exception = GetRealNestedException(); var expected = exception.ToString(); var actual = ExceptionFormatter.FormatStackTrace(exception, stripErrorMessage: false); Assert.AreEqual(expected, actual); }
public static string ToFormattedString(this Exception exception) { if (exception == null) { throw new ArgumentNullException(nameof(exception)); } return(ExceptionFormatter.GetFormattedException(exception)); }
public ActionResult AcceptRequestBot( [FromBody] _tmp2 requestingTwitchUsername ) { try { string token; var userInfo = this.authenticationProvider.Authenticate(this.HttpContext, out token); if (userInfo.Result != Constants.AuthenticationResult.Success) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"Could not authenticate")); } if (this.appSettings.TwitchClientID != userInfo.GetClientID()) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"{nameof(this.appSettings.TwitchClientID)} does not match")); } if (requestingTwitchUsername == null) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, $"Missing Requested Twitch Username")); } if (string.IsNullOrWhiteSpace(requestingTwitchUsername.requestingTwitchUsername)) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, $"Invalid Requesting Twitch Username")); } var botRequest = this.userHelper.GetBotRequest(userInfo.GetUserID()); if (botRequest == null) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, new { message = $"Your Twitch account has not been requested to act as a bot for another user." })); } if (botRequest.requestingUsername != requestingTwitchUsername.requestingTwitchUsername) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, new { message = $"Your Twitch account has been requested by {botRequest.requestingUsername}. Please re-send the bot request while logged in as {requestingTwitchUsername}" })); } this.userHelper.AcceptBotRequest(botRequest, token); // Restart their bot: var config = this.userHelper.GetConfigurationForUser(botRequest.requestingUserID); if (config != null && config.basicConfiguration.botEnabled) { Startup.chatBotManager.UnregisterConnection(botRequest.requestingUserID); Startup.chatBotManager.RegisterConnection(config); } return(Json(new { })); } catch (Exception exc) { this._logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError)); } }
/*----------------------------------------------------------------------------------------*/ IBindingBehaviorHeuristicComponentOrParameterSyntax IBindingConditionSyntax.WhereTargetHas(Type attribute) { if (!typeof(Attribute).IsAssignableFrom(attribute)) { throw new NotSupportedException(ExceptionFormatter.InvalidAttributeTypeUsedInBindingCondition(Binding, attribute)); } Binding.Condition = new PredicateCondition <IContext>(ctx => ctx.Member.HasAttribute(attribute)); return(this); }
public void SkippedNonReadableProperty() { ExceptionFormatter formatter = new ExceptionFormatter(); Exception nonReadablePropertyException = new ExceptionWithNonReadableProperty("MyException"); string message = formatter.GetMessage(nonReadablePropertyException); Assert.IsTrue(message.Length > 0); }
public void ShouldNotContainInnerExceptionMessageWhenStripTrue() { var exception = GetRealNestedException(); var actual = ExceptionFormatter.FormatStackTrace(exception, stripErrorMessage: true); var hasExceptionMessage = actual.Contains(InnerExceptionMessage); Assert.False(hasExceptionMessage); }
/// <summary> /// Constructs the exception message. /// </summary> /// <param name="msg">The MSG.</param> /// <param name="ex">The ex.</param> /// <param name="args">The arguments.</param> /// <returns></returns> private string ConstructExceptionMessage(string msg, Exception ex, params object[] args) { var sb = new StringBuilder(); sb.AppendFormat(msg, args); sb.AppendLine(); sb.Append(ExceptionFormatter.ConstructMessage(ex)); return(sb.ToString()); }
/*----------------------------------------------------------------------------------------*/ IBindingConditionBehaviorHeuristicComponentOrParameterSyntax IBindingTargetSyntax.ToProvider(Type providerType) { if (!typeof(IProvider).IsAssignableFrom(providerType)) { throw new NotSupportedException(ExceptionFormatter.InvalidProviderType(Binding, providerType)); } Binding.Provider = Binding.Kernel.Get(providerType) as IProvider; return(this); }
public static void Fatal(System.Exception e) { #if DEBUG throw e; #else var type = CallerType(); var logger = LogManager.GetLogger(type); logger.Fatal(ExceptionFormatter.FormatExcpetion(e)); #endif }
public static void WoxError( this NLog.Logger logger, string message, System.Exception exception, bool throwException = true, bool sendException = true, [CallerMemberName] string methodName = "") { Debug.WriteLine($"ERROR|{logger.Name}|{methodName}|{message}"); logger.Error($"{methodName}|{message}|{ExceptionFormatter.FormattedException(exception)}"); if (sendException) { SendException(exception); } }
private string GetMessage(Exception exception) { ExceptionFormatter exFormatter = new ExceptionFormatter(additionalInfo, this.ApplicationName); return exFormatter.GetMessage(exception); }
private string GetMessage(Exception exception) { ExceptionFormatter exFormatter = new ExceptionFormatter(additionalInfo, this.EventSource); return exFormatter.GetMessage(exception); }
/// <summary> /// <para>Logs an exception that occurs during a cryptography operation to the event log.</para> /// </summary> /// <param name="ex"> /// <para>The <see cref="Exception"/> to log.</para> /// </param> public static void LogCryptographyException(Exception ex) { ExceptionFormatter formatter = new ExceptionFormatter(new NameValueCollection(), applicationName); EventLog.WriteEntry(eventLogSource, formatter.GetMessage(ex), EventLogEntryType.Error); }