/// <summary> /// Identify if a particular SystemException is one of the exceptions which may be thrown /// by the Lync Model API. /// </summary> /// <param name="ex"></param> /// <returns></returns> private bool IsLyncException(SystemException ex) { return (ex is NotImplementedException || ex is ArgumentException || ex is NullReferenceException || ex is NotSupportedException || ex is ArgumentOutOfRangeException || ex is IndexOutOfRangeException || ex is InvalidOperationException || ex is TypeLoadException || ex is TypeInitializationException || ex is InvalidCastException); }
public void HelperUtils_ShowTrustRelationshipError_ShowTrustRelationshipError_AreEqual_Expect() { //-----------------------Arrange-------------------------- var mockPopupController = new Mock <IPopupController>(); var vv = new SystemException("The trust relationship between this workstation and the primary domain failed"); //-----------------------Act------------------------------ HelperUtils.ShowTrustRelationshipError(mockPopupController.Object, vv); //-----------------------Assert--------------------------- mockPopupController.VerifySet(o => o.Header = "Error connecting to server", Times.Once); mockPopupController.VerifySet(o => o.ImageType = MessageBoxImage.Error, Times.Once); mockPopupController.Verify(o => o.Show(), Times.Once); Assert.AreEqual(MessageBoxButton.OK, mockPopupController.Object.Buttons); }
/// <inheritdoc /> public void Run() { StringBuilder builder = new StringBuilder(); builder.AppendLine("Start Recursion Test.") .AppendLine(); var exception = new SystemException("This is a Message", new InvalidOperationException("Number dont know ths exception", new FieldAccessException("Number Cant Access your Field", new Exception("Number Dont have time to check for obseletes")))); Recursive(builder, exception); Console.WriteLine(builder.ToString()); }
protected void LogException(string query, SystemException nEx) { try { Trace.CorrelationManager.StartLogicalOperation(_type); Trace.TraceError("Sql query failed: {0}", query); Trace.TraceError(nEx.ToString()); } finally { Trace.CorrelationManager.StopLogicalOperation(); } }
public void Failed_Source_must_emit_error_immediately() { var ex = new SystemException(); var p = Source.Failed <int>(ex).RunWith(Sink.AsPublisher <int>(false), Materializer); var c = TestSubscriber.CreateManualProbe <int>(this); p.Subscribe(c); c.ExpectSubscriptionAndError(); //reject additional subscriber var c2 = TestSubscriber.CreateManualProbe <int>(this); p.Subscribe(c2); c2.ExpectSubscriptionAndError(); }
public static void Cozy() { Console.WriteLine("\n-----------------------------------------------"); Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName); Console.WriteLine("-----------------------------------------------"); System.Exception e1 = new Exception(); System.ApplicationException e2 = new ApplicationException(); e2 = null; System.Reflection.TargetInvocationException e3 = new TargetInvocationException(e1); System.SystemException e4 = new SystemException(); e4 = null; System.StackOverflowException e5 = new StackOverflowException(); e5 = null; }
// public bool IsDisposed = false; private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { // if (report == null) return; if (this.CancellationPending) { return; } if (e.UserState != null) { SystemException ex = e.UserState as SystemException; exceptionReport?.Invoke(ex); } int percentage = e.ProgressPercentage; report?.Invoke(percentage); }
public void Stop() { OpenWrite(); if (writable) { try { Writer.Device.ExecuteCommand(CAMSRCLib.DeviceCommands.camStop); acquiring = false; } catch (SystemException ex) { exception = ex; } } CloseWrite(); }
private void validar() { if (this.comboBox1.SelectedIndex == -1) { // MessageBox.Show("Eliga Año"); SystemException ex = new SystemException("Eliga Año"); throw ex; } if (this.comboBox2.SelectedIndex == -1) { // MessageBox.Show("Seleccione el semestre"); SystemException ex = new SystemException("Seleccione el semestre"); throw ex; } }
private void CantidadMayorACero() { if (CantidadOfertas.Text == "") { SystemException ex = new SystemException("Debe ingresar una cantidad Valida"); throw ex; } else { int CantidadAComprar = int.Parse(CantidadOfertas.Text); if (CantidadAComprar.Equals(null) || CantidadAComprar < 1) { SystemException ex = new SystemException("Debe ingresar una cantidad Valida"); throw ex; } } }
public JsonResult Message(SystemException exception) { string message = string.Empty; string messageType = string.Empty; if (exception.Message.Contains(";")) { message = exception.Message.Split(';')[1]; messageType = exception.Message.Split(';')[0]; } else { message = "Ocorreu um erro ao executar a ação."; messageType = MessageError; } return(Message(message, messageType)); }
private void validar() { if (this.comboBox1.SelectedIndex == -1) { SystemException ex = new SystemException("Eliga Tipo Listado"); throw ex; } if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]")) { MessageBox.Show("Año en numeros."); textBox1.Clear(); } if (this.comboBox2.SelectedIndex == -1) { SystemException ex = new SystemException("Seleccione el semestre"); throw ex; } }
private void validar() { if (this.textBoxDesc.TextLength <= 0) { SystemException ex = new SystemException("Debes ponerle una descripcion"); throw ex; } if (this.comboBoxEstado.SelectedIndex == -1) { SystemException ex = new SystemException("Seleccione si el rol esta habilitado"); throw ex; } if (this.comboBoxRegistrable.SelectedIndex == -1) { SystemException ex = new SystemException("Seleccione si el rol es registrable"); throw ex; } }
public void Start() { OpenWrite(); if (writable) { try { Writer.Device.ExecuteCommand(CAMSRCLib.DeviceCommands.camStart); acquiring = true; lastStart = DateTime.Now; } catch (SystemException ex) { exception = ex; } } CloseWrite(); }
//Private Parts //Geçiçi Çözüm - sonradan kişiye özel bir mantık belirle. private string UserNoGenerator() { Random randomNumber = new Random(); for (int i = 0; i < int.MaxValue; i++) { string randomUserNo = LongRandom(10000000000, 99999999999, randomNumber); User tempUser = _userDal.Get(u => u.UserNo == randomUserNo); if (tempUser is null) { return(randomUserNo); } } Exception exception = new SystemException(); throw exception; return("Erorr"); }
public void Log_WithMultipleNestedExceptions_LogsAll() { // Arrange var _innerInnerExceptionMessage = "InnerInnerExceptionMessage: Test ArgumentNullException Message."; _innerException = new InvalidOperationException(_innerExceptionMessage, new ArgumentNullException("TestArgumentException", _innerInnerExceptionMessage)); _exception = new SystemException(_exceptionMessage, _innerException); // Act _exception.Log(_mockLog.Object, _level); var loggedItems = _mockLog.LoggedItems; var logItem = loggedItems.FirstOrDefault(); // Assert Assert.IsTrue(logItem.Message.Contains(_exceptionMessage)); Assert.IsTrue(logItem.Message.Contains(_innerExceptionMessage)); Assert.IsTrue(logItem.Message.Contains(_innerInnerExceptionMessage)); }
/// <summary> /// Adds an SystemException object to the exception handler. /// Will only log if the logger is valid. Will only print the stack /// trace if the print stack trace flag is enabled (true). /// </summary> /// <param name="msg"></param> /// <param name="sysEx"></param> public void AddException(string msg, SystemException sysEx) { if (sysEx == null) { return; } int uniqId = this.systemExceptionList.Count; if (this.logger != null) { if (this.logger.IsLogWarn) { this.logger.logMessage(LogLevel.WARN, sysEx.Source, (string)((msg == null) ? "" : "(" + msg + ")") + "(" + uniqId + ")SystemException Thrown: " + sysEx.TargetSite + ":" + sysEx.Message); } } if (this.printStackTrace) { if (this.logger != null) { if (this.logger.IsLogInfo) { this.logger.logMessage(LogLevel.INFO, sysEx.Source, (string)((msg == null) ? "" : "(" + msg + ")") + "(" + uniqId + ")SystemException Details: " + sysEx.Data + ":" + sysEx.StackTrace); } } } lock (mutexObj) { this.systemExceptionList.Add(sysEx); } lock (mutexObj) { if (this.exceptionCallback != null) { this.exceptionCallback(); } else { //Purge the system exceptions this.systemExceptionList.Clear(); } } }
public static void WriteException(Exception ex, string ipAddress) { try { using (var context = new DataContext()) { SystemException exception = new SystemException(); exception.CreateDate = DateTime.Now; exception.IpAdress = ipAddress; exception.Name = ex.Message ?? ""; ; exception.StackTrace = ex.StackTrace ?? ""; context.SystemExceptions.InsertOnSubmit(exception); context.SubmitChanges(); } } catch { // WriteException should NEVER throw exception } }
public void Execute_5_Dependencies() { _resolverMock.Resolve <string>().Returns("str-dep-1"); _resolverMock.Resolve <long>().Returns(42); _resolverMock.Resolve <int>().Returns(12); var dep4 = new FlagsAttribute(); _resolverMock.Resolve <FlagsAttribute>().Returns(dep4); var dep5 = new SystemException(); _resolverMock.Resolve <SystemException>().Returns(dep5); var queryMock = Substitute.For <IQuery <int, string, long, int, FlagsAttribute, SystemException> >(); _queryExecutor.Execute(queryMock); queryMock.Received().Execute("str-dep-1", 42, 12, dep4, dep5); }
public double?GetDoubleEntry(string key) { bool flag; string stringEntry = this.GetStringEntry(key); double? nullable = null; CultureInfo cultureInfo = CultureInfo.GetCultureInfo("EN-US"); bool flag1 = stringEntry == null; if (!flag1) { try { char[] chrArray = new char[2]; chrArray[0] = ','; chrArray[1] = '.'; int num = stringEntry.LastIndexOfAny(chrArray); if (num < 0) { flag = true; } else { flag = stringEntry[num] != ','; } flag1 = flag; if (!flag1) { cultureInfo = CultureInfo.GetCultureInfo("de-AT"); } nullable = new double?(Convert.ToDouble(stringEntry, cultureInfo)); } catch (SystemException systemException1) { SystemException systemException = systemException1; Console.WriteLine(string.Concat("Converting to int error:", systemException.Message)); } } double?nullable1 = nullable; return(nullable1); }
public void WhenOption0ThenException_OldWay() { var expectedException = new SystemException("I will NOT process that. Eww.");; try { _service.ProcessAction(0); Assert.Fail("An exception was not thrown as expected."); } catch (Exception e) { // If the exception thrown was from the Assert.Fail, then rethrow. if (e.GetType() == typeof(AssertFailedException)) { throw; } Assert.AreEqual(expectedException.GetType(), e.GetType()); Assert.AreEqual(expectedException.Message, e.Message); } }
public void WhenOption0ThenException_OldWay() { var expectedException = new SystemException("I've got a paperclip and bubblegum, we'll fix this.");; try { _service.ProcessFunc(0); Assert.Fail("An exception was not thrown as expected."); } catch (Exception e) { // If the exception thrown was from the Assert.Fail, then rethrow. if (e.GetType() == typeof(AssertFailedException)) { throw; } Assert.AreEqual(expectedException.GetType(), e.GetType()); Assert.AreEqual(expectedException.Message, e.Message); } }
public void TestParentNameNotFound() { // Arrange TagBuilder builder = new TagBuilder("flavors"); // Act SystemException exception = Assert.Throws <SystemException>(() => { for (Int32 i = 0; i < 2; i++) { builder.AddToParent("favors", "flavor"); builder.AddChild("requirements"); builder.AddChild("requirement"); } }); // Assert const String expectedErrorMessage = "missing parent tag: favors"; Assert.AreEqual(expectedErrorMessage, exception.Message); }
private void SetStyle(StyleType type) { switch (type) { case StyleType.Normal: font = new Font("宋体", 9); colorList = SelectColor(0); outLineColor = Color.Gray; break; case StyleType.Light: font = new Font("宋体", 9); colorList = SelectColor(7); outLineColor = Color.Gray; break; default: SystemException exception = new SystemException("No this type chart."); break; } }
public static void UnknownType(var exception) { Random random = new Random(); switch (random.Next(1, 5)) { case 1: exception = new ApplicationException("An application exception."); break; case 2: exception = new SystemException("A system exception"); break; case 3: exception = "This is not an exception"; break; } Console.WriteLine(exception.ToString()); //Console.WriteLine(exception.Message); // Compilation error? }
/// <summary> /// Gets the info inside the Sample Info of the detector /// </summary> public void GetSampleData() { OpenRead(); if (opened) { try { sampleTitle = (string)Reader.get_Parameter(CanberraDataAccessLib.ParamCodes.CAM_T_STITLE); user = (string)Reader.get_Parameter(CanberraDataAccessLib.ParamCodes.CAM_T_SCOLLNAME); description1 = (string)Reader.get_Parameter(CanberraDataAccessLib.ParamCodes.CAM_T_SDESC1); description2 = (string)Reader.get_Parameter(CanberraDataAccessLib.ParamCodes.CAM_T_SDESC2); description3 = (string)Reader.get_Parameter(CanberraDataAccessLib.ParamCodes.CAM_T_SDESC3); description4 = (string)Reader.get_Parameter(CanberraDataAccessLib.ParamCodes.CAM_T_SDESC4); } catch (SystemException ex) { exception = ex; } } CloseRead(); }
public int?GetIntegerEntry(string key) { string stringEntry = this.GetStringEntry(key); int? nullable = null; bool flag = stringEntry == null; if (!flag) { try { nullable = new int?(int.Parse(stringEntry)); } catch (SystemException systemException1) { SystemException systemException = systemException1; Console.WriteLine(string.Concat("Converting to int error:", systemException.Message)); } } int?nullable1 = nullable; return(nullable1); }
private string MyErrorHandler(SystemException e, string statusCode) { Type t = e.GetType(); string status = ""; if (t == typeof(WebException)) { status = ((WebException)e).Status.ToString(); } m_logger.LogIf(TraceLevel.Error, "-- RestError ---------------------"); m_logger.LogIf(TraceLevel.Error, " Resource = " + ResourcePath); m_logger.LogIf(TraceLevel.Error, " StatusCode = " + statusCode); m_logger.LogIf(TraceLevel.Error, " Type = " + t); m_logger.LogIf(TraceLevel.Error, " Message = " + e.Message); m_logger.LogIf(TraceLevel.Error, " Status = " + status); m_logger.LogIf(TraceLevel.Error, "----------------------------------"); return(String.Format(CultureInfo.InvariantCulture, "<*error*>\nResource={0}\nStatusCode={1}\nType={2}\nMessage={3}\nStatus={4}", ResourcePath, statusCode, t, e.Message, status)); }
/// <summary> /// Looks for and processes a new message /// </summary> public async void Handle() { Interlocked.Increment(ref _waitingOnAsyncTasks); try { try { await TryProcessIncomingMessageAsync().ConfigureAwait(false); _seriousExceptionProcessBackOffHelper.Value.Reset(); } catch (MessageException exception) { UserException?.Invoke(this, new MessageErrorEventArgs(exception)); } catch (CommitException exception) { UserException?.Invoke(this, new MessageErrorEventArgs(exception)); } catch (Exception e) { SystemException?.Invoke(this, new MessageErrorEventArgs(e)); //generic exceptions tend to indicate a serious problem - lets start delaying processing //this counter will reset once a message has been processed by this thread _seriousExceptionProcessBackOffHelper.Value.Wait(); } } catch (Exception ex) //not cool - one of the exception events threw an exception { //there is not a lot we can do here - log the exception _log.ErrorException("An error has occurred while trying to handle an exception", ex, null); } finally { Interlocked.Decrement(ref _waitingOnAsyncTasks); } }
public static void Main() { string aString = "hello"; aString = upper("hello"); Console.WriteLine(aString); var reference; if (new Random().NextDouble() < 0.5) { reference = "hello"; } else { reference = new SystemException("A system exception"); } aString = getString(reference); // * Correct! Console.WriteLine(aString); aString = upper(reference); // * Compilation error (reference is static) var dynamicReference; if (new Random().NextDouble() < 1) { dynamicReference = "hello"; } else { dynamicReference = new SystemException("A system exception"); } aString = dynamicReference.ToUpper(); // * Correct! (dynamicReference is dynamic) Console.WriteLine(aString); aString = getString(dynamicReference); // * Correct! (regardles of parameter dynamism) aString = upper(dynamicReference); // * Compilation error (correct if we set parameter to dynamic) Console.WriteLine(aString); }
/// Processes records from the input pipeline. /// For each input file, the command sets its /// security descriptor to the specified /// Access Control List (ACL). protected override void ProcessRecord() { ObjectSecurity aclObjectSecurity = _securityDescriptor as ObjectSecurity; if (_inputObject != null) { PSMethodInfo methodInfo = _inputObject.Methods["SetSecurityDescriptor"]; if (methodInfo != null) { CommonSecurityDescriptor aclCommonSD = _securityDescriptor as CommonSecurityDescriptor; string sddl; if (aclObjectSecurity != null) { sddl = aclObjectSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All); } else if (aclCommonSD != null) { sddl = aclCommonSD.GetSddlForm(AccessControlSections.All); } else { Exception e = new ArgumentException("AclObject"); WriteError(new ErrorRecord( e, "SetAcl_AclObject", ErrorCategory.InvalidArgument, AclObject)); return; } try { methodInfo.Invoke(sddl); } catch (Exception e) { // Calling user code, Catch-all OK CommandProcessorBase.CheckForSevereException(e); ErrorRecord er = SecurityUtils.CreateNotSupportedErrorRecord( UtilsStrings.MethodInvokeFail, "SetAcl_OperationNotSupported" ); WriteError(er); return; } } else { ErrorRecord er = SecurityUtils.CreateNotSupportedErrorRecord( UtilsStrings.SetMethodNotFound, "SetAcl_OperationNotSupported" ); WriteError(er); } } else { if (Path == null) { Exception e = new ArgumentException("Path"); WriteError(new ErrorRecord( e, "SetAcl_Path", ErrorCategory.InvalidArgument, AclObject)); return; } if (aclObjectSecurity == null) { Exception e = new ArgumentException("AclObject"); WriteError(new ErrorRecord( e, "SetAcl_AclObject", ErrorCategory.InvalidArgument, AclObject)); return; } if (CentralAccessPolicy != null || ClearCentralAccessPolicy) { if (!DownLevelHelper.IsWin8AndAbove()) { Exception e = new ParameterBindingException(); WriteError(new ErrorRecord( e, "SetAcl_OperationNotSupported", ErrorCategory.InvalidArgument, null)); return; } } if (CentralAccessPolicy != null && ClearCentralAccessPolicy) { Exception e = new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyParameters); ErrorRecord er = SecurityUtils.CreateInvalidArgumentErrorRecord( e, "SetAcl_OperationNotSupported" ); WriteError(er); return; } IntPtr pSacl = IntPtr.Zero; NativeMethods.TOKEN_PRIVILEGE previousState = new NativeMethods.TOKEN_PRIVILEGE(); try { if (CentralAccessPolicy != null) { pSacl = GetSaclWithCapId(CentralAccessPolicy); if (pSacl == IntPtr.Zero) { SystemException e = new SystemException( UtilsStrings.GetSaclWithCapIdFail); WriteError(new ErrorRecord(e, "SetAcl_CentralAccessPolicy", ErrorCategory.InvalidResult, null)); return; } } else if (ClearCentralAccessPolicy) { pSacl = GetEmptySacl(); if (pSacl == IntPtr.Zero) { SystemException e = new SystemException( UtilsStrings.GetEmptySaclFail); WriteError(new ErrorRecord(e, "SetAcl_ClearCentralAccessPolicy", ErrorCategory.InvalidResult, null)); return; } } foreach (string p in Path) { Collection<PathInfo> pathsToProcess = new Collection<PathInfo>(); CmdletProviderContext context = this.CmdletProviderContext; context.PassThru = Passthru; if (_isLiteralPath) { ProviderInfo Provider = null; PSDriveInfo Drive = null; string pathStr = SessionState.Path.GetUnresolvedProviderPathFromPSPath(p, out Provider, out Drive); pathsToProcess.Add(new PathInfo(Drive, Provider, pathStr, SessionState)); context.SuppressWildcardExpansion = true; } else { pathsToProcess = SessionState.Path.GetResolvedPSPathFromPSPath(p, CmdletProviderContext); } foreach (PathInfo pathInfo in pathsToProcess) { if (ShouldProcess(pathInfo.Path)) { try { InvokeProvider.SecurityDescriptor.Set(pathInfo.Path, aclObjectSecurity, context); if (CentralAccessPolicy != null || ClearCentralAccessPolicy) { if (!pathInfo.Provider.NameEquals(Context.ProviderNames.FileSystem)) { Exception e = new ArgumentException("Path"); WriteError(new ErrorRecord( e, "SetAcl_Path", ErrorCategory.InvalidArgument, AclObject)); continue; } // Enable the security privilege required to set SCOPE_SECURITY_INFORMATION. IntPtr pToken = GetTokenWithEnabledPrivilege("SeSecurityPrivilege", previousState); if (pToken == IntPtr.Zero) { SystemException e = new SystemException( UtilsStrings.GetTokenWithEnabledPrivilegeFail); WriteError(new ErrorRecord(e, "SetAcl_AdjustTokenPrivileges", ErrorCategory.InvalidResult, null)); return; } // Set the file's CAPID. uint rs = NativeMethods.SetNamedSecurityInfo( pathInfo.ProviderPath, NativeMethods.SeObjectType.SE_FILE_OBJECT, NativeMethods.SecurityInformation.SCOPE_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, pSacl); // Restore privileges to the previous state. if (pToken != IntPtr.Zero) { NativeMethods.TOKEN_PRIVILEGE newState = new NativeMethods.TOKEN_PRIVILEGE(); uint newSize = 0; NativeMethods.AdjustTokenPrivileges( pToken, false, ref previousState, (uint)Marshal.SizeOf(newState), ref newState, ref newSize); NativeMethods.CloseHandle(pToken); pToken = IntPtr.Zero; } if (rs != NativeMethods.ERROR_SUCCESS) { Exception e = new Win32Exception( (int)rs, UtilsStrings.SetCentralAccessPolicyFail); WriteError(new ErrorRecord(e, "SetAcl_SetNamedSecurityInfo", ErrorCategory.InvalidResult, null)); } } } catch (NotSupportedException) { ErrorRecord er = SecurityUtils.CreateNotSupportedErrorRecord( UtilsStrings.OperationNotSupportedOnPath, "SetAcl_OperationNotSupported", pathInfo.Path ); WriteError(er); } } } } } finally { Marshal.FreeHGlobal(pSacl); } } }
public CarIsAwesomeException(string message, SystemException inner) : base(message, inner) { }