/// <summary> /// Generic handler for all CQ calls. /// Except for user logon and admin logon case. /// </summary> /// <param name="cEx"></param> public static void HandleCQException(COMException cEx) { string errMsg = UtilityMethods.Format(CQResource.CQ_COM_ERROR, cEx.Message); if (cEx.Message.Contains("80040154")) { //System.Runtime.InteropServices.COMException (0x80040154) throw new ClearQuestCOMDllNotFoundException(errMsg, cEx); } else { throw new ClearQuestCOMCallException(errMsg, cEx); } }
public MorphicResult <MorphicUnit, WindowsComError> SetMasterMuteState(bool muteState) { // set the master mute state var result = this._audioEndpointVolume.SetMute(muteState ? 1 : 0, IntPtr.Zero); if (result != ExtendedPInvoke.S_OK) { // TODO: consider throwing more granular exceptions here var comException = new COMException("IAudioEndpointVolume.SetMute failed", Marshal.GetExceptionForHR(result)); return(MorphicResult.ErrorResult(WindowsComError.ComException(comException))); } return(MorphicResult.OkResult()); }
internal MethodDataEnumerator(ManagementObject parent) { this.parent = parent; this.methodNames = new ArrayList(); IWbemClassObjectFreeThreaded wbemClassObjectFreeThreaded = null; IWbemClassObjectFreeThreaded wbemClassObjectFreeThreaded1 = null; int num = -2147217407; lock (typeof(MethodDataCollection.enumLock)) { try { num = parent.wbemObject.BeginMethodEnumeration_(0); if (num >= 0) { string str = ""; while (str != null && num >= 0 && num != 0x40005) { str = null; num = parent.wbemObject.NextMethod_(0, out str, out wbemClassObjectFreeThreaded, out wbemClassObjectFreeThreaded1); if (num < 0 || num == 0x40005) { continue; } this.methodNames.Add(str); } parent.wbemObject.EndMethodEnumeration_(); } } catch (COMException cOMException1) { COMException cOMException = cOMException1; ManagementException.ThrowWithExtendedInfo(cOMException); } this.en = this.methodNames.GetEnumerator(); } if (((long)num & (long)-4096) != (long)-2147217408) { if (((long)num & (long)-2147483648) != (long)0) { Marshal.ThrowExceptionForHR(num); } return; } else { ManagementException.ThrowWithExtendedInfo((ManagementStatus)num); return; } }
static bool IsRetry(COMException e) { var errorCode = (uint)e.ErrorCode; switch (errorCode) { case RPC_E_SERVERCALL_RETRYLATER: case VBA_E_IGNORE: return(true); default: return(false); } }
private void HandleCOMException(COMException cex) { if (this.State == BackgroundCopyJobState.Error || this.State == BackgroundCopyJobState.TransientError) { IBackgroundCopyError pErr; m_ijob.GetError(out pErr); OnError(pErr); } else { throw new BackgroundCopyException(cex); } }
private static string GetMessageFromError(COMException e) { switch (e.ErrorCode) { case BusinessOneNotRunningErrorCode: return(FormatConnectionMessage()); case LoginInScreenLock: return(@"Login screen is in lock mode. Please login and run the addon again."); default: return(e.Message); } }
IsEncryptedPackageEnvelope( Stream stream ) { if (stream == null) { throw new ArgumentNullException("stream"); } bool retval = false; StorageRoot root = null; try { // // When StorageRoot.CreateOnStream is called on a stream that is not // a storage object, it throws an IOException whose inner exception is // a COMException whose error code is 0x80030050, STG_E_FILEALREADYEXISTS. // Check for that case and return false because that means that this // stream is not an RM-protected file. // // Any other exception is a real error. // root = StorageRoot.CreateOnStream(stream, FileMode.Open); // // It's a compound file. Does it contain an "EncryptedPackage" stream? // retval = ContainsEncryptedPackageStream(root); } catch (IOException ex) { COMException comException = ex.InnerException as COMException; if (comException != null && comException.ErrorCode == STG_E_FILEALREADYEXISTS) { return(false); } throw; // Any other kind of IOException is a real error. } finally { if (root != null) { root.Close(); } } return(retval); }
public void TestCOMException() { var value = new COMException("Message", 12345); try { ExceptionDispatchInfo.Capture(value).Throw(); } catch (COMException ex) { Assert.That(ex, Is.Not.SameAs(value)); Assert.That(ex.ErrorCode, Is.EqualTo(value.ErrorCode)); } }
public static ReplicationConnection FindByName(DirectoryContext context, string name) { ReplicationConnection replicationConnection; ReplicationConnection.ValidateArgument(context, name); context = new DirectoryContext(context); DirectoryEntry directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { string propertyValue = (string)PropertyManager.GetPropertyValue(context, directoryEntry, PropertyManager.ServerName); string str = string.Concat("CN=NTDS Settings,", propertyValue); directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, str); string[] strArrays = new string[1]; strArrays[0] = "distinguishedName"; ADSearcher aDSearcher = new ADSearcher(directoryEntry, string.Concat("(&(objectClass=nTDSConnection)(objectCategory=NTDSConnection)(name=", Utils.GetEscapedFilterValue(name), "))"), strArrays, SearchScope.OneLevel, false, false); SearchResult searchResult = null; try { searchResult = aDSearcher.FindOne(); } catch (COMException cOMException1) { COMException cOMException = cOMException1; if (cOMException.ErrorCode != -2147016656) { throw ExceptionHelper.GetExceptionFromCOMException(context, cOMException); } else { throw new ActiveDirectoryObjectNotFoundException(Res.GetString("DSNotFound"), typeof(ReplicationConnection), name); } } if (searchResult != null) { DirectoryEntry directoryEntry1 = searchResult.GetDirectoryEntry(); replicationConnection = new ReplicationConnection(context, directoryEntry1, name); } else { Exception activeDirectoryObjectNotFoundException = new ActiveDirectoryObjectNotFoundException(Res.GetString("DSNotFound"), typeof(ReplicationConnection), name); throw activeDirectoryObjectNotFoundException; } } finally { directoryEntry.Dispose(); } return(replicationConnection); }
public static void GetException(COMException exception) { switch ((uint)exception.ErrorCode) { case WIA_ERROR_BUSY: throw new DeviceException("Device is busy. Error code :WIA_ERROR_BUSY", exception, (uint)exception.ErrorCode); case WIA_ERROR_DEVICE_COMMUNICATION: throw new DeviceException("Device communication error. Error code :WIA_ERROR_DEVICE_COMMUNICATION", exception, (uint)exception.ErrorCode); case WIA_ERROR_DEVICE_LOCKED: throw new DeviceException("Device is locked. Error code :WIA_ERROR_DEVICE_LOCKED", exception, (uint)exception.ErrorCode); case WIA_ERROR_EXCEPTION_IN_DRIVER: throw new DeviceException("Exception in driver. Error code :WIA_ERROR_EXCEPTION_IN_DRIVER", exception, (uint)exception.ErrorCode); case WIA_ERROR_GENERAL_ERROR: throw new DeviceException("General error. Error code :WIA_ERROR_GENERAL_ERROR", exception, (uint)exception.ErrorCode); case WIA_ERROR_INCORRECT_HARDWARE_SETTING: throw new DeviceException( "Incorrect hardware error. Error code :WIA_ERROR_INCORRECT_HARDWARE_SETTING", exception, (uint)exception.ErrorCode); case WIA_ERROR_INVALID_COMMAND: throw new DeviceException("Invalid command. Error code :WIA_ERROR_INVALID_COMMAND", exception, (uint)exception.ErrorCode); case WIA_ERROR_INVALID_DRIVER_RESPONSE: throw new DeviceException("Invalid driver response. Error code :WIA_ERROR_INVALID_DRIVER_RESPONSE", exception, (uint)exception.ErrorCode); case WIA_ERROR_OFFLINE: throw new DeviceException("Device is offline. Error code :WIA_ERROR_OFFLINE", exception, WIA_ERROR_OFFLINE, (uint)exception.ErrorCode); case WIA_ERROR_UNABLE_TO_FOCUS: throw new DeviceException("Unable to focus. Error code :WIA_ERROR_UNABLE_TO_FOCUS", exception, WIA_ERROR_UNABLE_TO_FOCUS, (uint)exception.ErrorCode); default: throw new DeviceException("Unknown error. Error code:" + (uint)exception.ErrorCode, exception, (uint)exception.ErrorCode); } }
private string WiaErrorOrMessage(Exception ex) { string error = null; COMException comException = ex as COMException; if (comException != null) { switch ((uint)comException.ErrorCode) { case 0x80210001: { error = "WIA: General error"; break; } case 0x80210002: { error = "WIA: Paper jam"; break; } case 0x80210003: { error = "WIA: Paper empty"; break; } case 0x80210004: { error = "WIA: Paper problem"; break; } case 0x80210005: { error = "WIA: Offline"; break; } case 0x80210006: { error = "WIA: Busy"; break; } case 0x80210007: { error = "WIA: Warming up"; break; } case 0x80210008: { error = "WIA: User intervention required"; break; } case 0x80210009: { error = "WIA: Item deleted"; break; } case 0x8021000A: { error = "WIA: Failed to communicate with device"; break; } case 0x8021000B: { error = "WIA: Invalid command"; break; } case 0x8021000C: { error = "WIA: Incorrect hardware setting"; break; } case 0x8021000D: { error = "WIA: Device locked"; break; } case 0x8021000E: { error = "WIA: Exception in driver"; break; } case 0x8021000F: { error = "WIA: Invalid Driver response"; break; } } } if (error == null) { error = ex.Message; } return(error); }
private void DataLink_Click(object sender, RoutedEventArgs e) { try { // Create data links object as IDataInitialize Type dataLinksType = Type.GetTypeFromCLSID(NativeMethods.CLSID_DataLinks); NativeMethods.IDataInitialize dataInitialize = Activator.CreateInstance(dataLinksType) as NativeMethods.IDataInitialize; // Create data source object from connection string object dataSource = null; dataInitialize.GetDataSource(null, NativeMethods.CLSCTX_INPROC_SERVER, _connectionProperties.ToFullString(), ref NativeMethods.IID_IUnknown, ref dataSource); // Get IDBPromptInitialize interface from data links object NativeMethods.IDBPromptInitialize promptInitialize = (NativeMethods.IDBPromptInitialize)dataInitialize; // Display the data links dialog using this data source promptInitialize.PromptDataSource( null, new WindowInteropHelper(Window.GetWindow(this)).Handle, NativeMethods.DBPROMPTOPTIONS_PROPERTYSHEET | NativeMethods.DBPROMPTOPTIONS_DISABLE_PROVIDER_SELECTION, 0, IntPtr.Zero, null, ref NativeMethods.IID_IUnknown, ref dataSource); // Retrieve the new connection string from the data source dataInitialize.GetInitializationString(dataSource, true, out string newConnectionString); // Parse the new connection string into the connection properties object _connectionProperties.Parse(newConnectionString); // Reload the control with the modified connection properties VisualTreeHelpers.RefreshBindings(this); passwordTextbox.Password = Password; } catch (Exception ex) { COMException comex = ex as COMException; if (comex == null || comex.ErrorCode != NativeMethods.DB_E_CANCELED) { MessageBox.Show(ex.Message, Properties.Resources.Error_Label, MessageBoxButton.OK, MessageBoxImage.Error); } } }
public DiaFile(String pdbFile, String dllFile) { m_dsc = GetDiaSourceClass(); string pdbPath = System.IO.Path.GetDirectoryName(pdbFile); // Open the PDB file, validating it matches the supplied DLL file DiaLoadCallback loadCallback = new DiaLoadCallback(); try { m_dsc.loadDataForExe(dllFile, pdbPath, loadCallback); } catch (System.Exception diaEx) { // Provide additional diagnostics context and rethrow string msg = "ERROR from DIA loading PDB for specified DLL"; COMException comEx = diaEx as COMException; if (comEx != null) { if (Enum.IsDefined(typeof(DiaHResults), comEx.ErrorCode)) { // This is a DIA-specific error code, DiaHResults hr = (DiaHResults)comEx.ErrorCode; msg += ": " + hr.ToString(); // Additional clarification for the common case of the DLL not matching the PDB if (hr == DiaHResults.E_PDB_NOT_FOUND) { msg += " - The specified PDB file does not match the specified DLL file"; } } } throw new ApplicationException(msg, diaEx); } // Save the path of the PDB file actually loaded Debug.Assert(loadCallback.LoadedPdbPath != null, "Didn't get PDB load callback"); m_loadedPdbPath = loadCallback.LoadedPdbPath; // Also use DIA to get the debug directory entry in the DLL referring // to the PDB, and save it's timestamp comparison at runtime. m_debugTimestamp = loadCallback.DebugTimeDateStamp; Debug.Assert(m_debugTimestamp != 0, "Didn't find debug directory entry"); m_dsc.openSession(out m_session); m_global = new DiaSymbol(m_session.globalScope); m_publicsEnum = null; }
public static int GetWIAErrorCode(this COMException cx) { int origErrorMsg = cx.ErrorCode; int errorCode = origErrorMsg & 0xFFFF; int errorFacility = ((origErrorMsg) >> 16) & 0x1fff; if (errorFacility == WIAFacility) { return(errorCode); } return(-1); }
public void SolutionCreateThrows_ReturnsFalse() { var repoDir = @"x:\repo"; var dte = Substitute.For <DTE>(); var log = Substitute.For <ILogger>(); var ex = new COMException(); dte.Solution.When(s => s.Create(Arg.Any <string>(), Arg.Any <string>())).Do(ci => { throw ex; }); var target = CreateVSServices(repoDir, dte: dte, log: log); var success = target.TryOpenRepository(repoDir); Assert.False(success); log.Received(1).Error(ex, "Error opening repository"); }
protected override void OnSetComplete(int index, object oldValue, object newValue) { ActiveDirectorySiteLink activeDirectorySiteLink = (ActiveDirectorySiteLink)newValue; string propertyValue = (string)PropertyManager.GetPropertyValue(activeDirectorySiteLink.context, activeDirectorySiteLink.cachedEntry, PropertyManager.DistinguishedName); try { this.de.Properties["siteLinkList"][index] = propertyValue; } catch (COMException cOMException1) { COMException cOMException = cOMException1; throw ExceptionHelper.GetExceptionFromCOMException(this.context, cOMException); } }
protected override void OnRemoveComplete(int index, object value) { ActiveDirectorySite activeDirectorySite = (ActiveDirectorySite)value; string propertyValue = (string)PropertyManager.GetPropertyValue(activeDirectorySite.context, activeDirectorySite.cachedEntry, PropertyManager.DistinguishedName); try { this.de.Properties["siteList"].Remove(propertyValue); } catch (COMException cOMException1) { COMException cOMException = cOMException1; throw ExceptionHelper.GetExceptionFromCOMException(this.context, cOMException); } }
private Exception WrapCOMException(Exception ex) { Exception returnEx = ex; COMException comEx = ex as COMException; if (comEx != null) { String lastApiError = Api.GetLastError(); returnEx = new EnhancedCOMException(comEx, lastApiError); } return(returnEx); }
private void FillNextResultError(COMException e, Exception f) { #if DEBUG if (AdapterSwitches.DataError.TraceError) { Debug.WriteLine(e.ToString() + " " + ODB.ELookup(e.ErrorCode)); } #endif // i.e. ADODB.Recordset opened with adCmdTableDirect // Current provider does not support returning multiple recordsets from a single execution. if (ODB.ADODB_NextResultError != e.ErrorCode) { throw f; } }
public void CanFormatMessageWithInnerExceptions() { var inner2 = new COMException("inner2", 2000); var inner1 = new COMException("inner1", inner2); var outer = new Exception("outer", inner1); string message = ExceptionUtils.FormatMessage(outer); Console.WriteLine(message); const string expected = "outer\r\n\r\n---> inner1\r\n- Error code: -2147467259\r\n\r\n---> inner2\r\n- Error code: 2000"; Assert.AreEqual(expected, message); }
private static WiaResult ShowWiaErrorCode(COMException ex) { WiaResult error = new WiaResult(); if (Enum.IsDefined(typeof(WiaError), (uint)ex.ErrorCode)) { error.Error = ((WiaError)ex.ErrorCode); } else { error.Error = WiaError.UNKNOWN; } error.Message = ex.Message; return(error); }
private Task <TResult> Start(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { this.tcs.SetCanceled(); return(this.tcs.Task); } NativeCommon.IFabricAsyncOperationContext context = null; try { AppTrace.TraceSource.WriteNoise(this.functionTag, "{0}: begin", this.traceId); // This is where the call to the native API is being made context = this.beginFunc(this); } catch (Exception ex) { COMException comEx = Utility.TryTranslateExceptionToCOM(ex); if (comEx != null) { this.TraceException(ex, "{0}: begin delegate threw an exception", this.traceId); // The begin call failed hence there is nothing further to do throw Utility.TranslateCOMExceptionToManaged(comEx, this.functionTag); } if (ex is ArgumentException) { throw Utility.TranslateArgumentException(ex as ArgumentException); } throw; } // Try to initialize the shared context with the context returned from the begin function // If the shared context was already initialized by the callback then the context will be freed // (Release of COM object) this.InitializeSharedContext(context); // try to acquire the shared native object and using it try to finish the operation if the // operation was completed synchronously this.nativeContext.TryAcquireAndInvoke((inner) => this.Finish(inner, true)); this.RegisterForCancellation(cancellationToken); return(this.tcs.Task); }
protected override void ProcessRecord() { string hostName = Dns.GetHostName(); string str = null; Exception exception = null; if (base.ShouldProcess(hostName)) { try { ManagementObject managementObject = new ManagementObject(string.Concat("Win32_ComputerSystem.Name=\"", hostName, "\"")); if (!(bool)managementObject["PartOfDomain"]) { string resetComputerNotInDomain = ComputerResources.ResetComputerNotInDomain; ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(resetComputerNotInDomain), "ComputerNotInDomain", ErrorCategory.InvalidOperation, hostName); base.ThrowTerminatingError(errorRecord); } str = (string)LanguagePrimitives.ConvertTo(managementObject["Domain"], typeof(string), CultureInfo.InvariantCulture); } catch (ManagementException managementException1) { ManagementException managementException = managementException1; exception = managementException; } catch (COMException cOMException1) { COMException cOMException = cOMException1; exception = cOMException; } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; exception = unauthorizedAccessException; } if (exception != null) { string str1 = StringUtil.Format(ComputerResources.FailToGetDomainInformation, exception.Message); ErrorRecord errorRecord1 = new ErrorRecord(new InvalidOperationException(str1), "FailToGetDomainInformation", ErrorCategory.OperationStopped, hostName); base.ThrowTerminatingError(errorRecord1); } ResetComputerMachinePasswordCommand.ResetMachineAccountPassword(str, hostName, this.Server, this.Credential, this); return; } else { return; } }
private void InstallEncoderQuery(COMException ex) { if ((uint)ex.ErrorCode == 0x80040154) { if (MessageBox.Show("Windows Media Encoder 9 is not installed." + Environment.NewLine + "Do you want to download and install it?", "Error", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { System.Diagnostics.Process.Start("www.softpedia.com/progDownload/Windows-Media-Encoder-Download-1393.html"); } else { //Application.Current.Shutdown(-1); } _parentDlg.FileDlgEnableOkBtn = false; } }
// Test the COMException class. public void TestCOMException() { // Check the three main exception constructors. ExceptionTester.CheckMain (typeof(COMException), unchecked((int)0x80004005)); // Test the fourth constructor. COMException e = new COMException("foobar", 0x0BADBEEF); AssertEquals("COM (1)", "foobar", e.Message); AssertEquals("COM (2)", 0x0BADBEEF, e.ErrorCode); // Test that the error code is zero by default. e = new COMException("foobar"); AssertEquals("COM (3)", "foobar", e.Message); AssertEquals("COM (4)", 0, e.ErrorCode); }
/// <summary> /// Ermittelt für eine (WIA-)COM-Ausnahme die zugehörige Fehlermeldung /// </summary> /// <param name="ex">die (WIA-)COM-Ausnahme</param> /// <returns>die zur (WIA-)COM-Ausnahme gehörende Fehlermeldung</returns> public static string GetMessageFromComException(COMException ex) { WiaError wiaError = (WiaError)ex.ErrorCode; int errorCode; if (!Int32.TryParse(wiaError.ToString(), out errorCode)) { string message = wiaError.ToString(); WiaException.messageMappings.TryGetValue(wiaError, out message); return(message); } else { return(ex.Message); } }
public void GetExceptionForHR_ThrowExceptionForHR_ThrowsSameException() { const int ErrorCode = unchecked ((int)0x80131D0B); COMException getHRException = Marshal.GetExceptionForHR(ErrorCode) as COMException; Assert.Equal(ErrorCode, getHRException.HResult); try { Marshal.ThrowExceptionForHR(ErrorCode); } catch (COMException e) { Assert.Equal(ErrorCode, e.HResult); Assert.Equal(e.HResult, getHRException.HResult); } }
public virtual IMessage SyncProcessMessage(IMessage msg) { IMethodCallMessage reqMsg = (IMethodCallMessage)msg; IMethodReturnMessage methodReturnMessage = RemotingServices.ExecuteMessage(this._comObject, reqMsg); if (methodReturnMessage != null) { COMException comException = methodReturnMessage.Exception as COMException; if (comException != null && (comException._HResult == -2147023174 || comException._HResult == -2147023169)) { this._comObject = (MarshalByRefObject)Activator.CreateInstance(this._serverType, true); methodReturnMessage = RemotingServices.ExecuteMessage(this._comObject, reqMsg); } } return((IMessage)methodReturnMessage); }
private void HandleCOMException(COMException cex) { BackgroundCopyJobState state = BackgroundCopyJob.GetState(m_ijob); if (state == BackgroundCopyJobState.Error || state == BackgroundCopyJobState.TransientError) { Interop.IBackgroundCopyError pErr; m_ijob.GetError(out pErr); throw new BackgroundCopyException(pErr); } else { throw new BackgroundCopyException(cex); } }
const uint NAME_NOT_FOUND = 0x800A03EC; // When called from the main thread, but Excel is busy. static bool IsRetry(COMException e) { uint errorCode = (uint)e.ErrorCode; switch (errorCode) { case RPC_E_SERVERCALL_RETRYLATER: case VBA_E_IGNORE: case NAME_NOT_FOUND: case RPC_E_CALL_REJECTED: return(true); default: return(false); } }
private static bool IsFatalException(Exception ex) { COMException exception = ex as COMException; if (exception != null) { switch (((uint)exception.ErrorCode)) { case 0x80070026: case 0x800703e3: case 0x800704cd: return(false); } } return(true); }
public void SerializationRoundTrip() { var ex = new COMException("E_BAD_PIZZA", -1337); BinaryFormatterHelpers.AssertRoundtrips(ex); }