Code:
/ 4.0 / 4.0 / untmp / DEVDIV_TFS / Dev10 / Releases / RTMRel / ndp / fx / src / Wmi / managed / System / Management / ManagementException.cs / 1305376 / ManagementException.cs
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using WbemClient_v1;
using System.Security.Permissions;
namespace System.Management
{
///
/// Represents the enumeration of all WMI error codes that are currently defined.
///
public enum ManagementStatus
{
///
/// The operation was successful.
///
NoError = 0,
///
/// This value is returned when no more objects
/// are available, the number of objects returned is less than the number requested,
/// or at the end of an enumeration. It is also returned when the method is called
/// with a value of 0 for the parameter.
///
False = 1,
///
/// An overridden property was deleted. This value is
/// returned to signal that the original, non-overridden value has been restored as a
/// result of the deletion.
///
ResetToDefault = 0x40002,
///
/// The compared items (such as objects and classes)
/// are not identical.
///
Different = 0x40003,
///
/// A call timed out. This is not an
/// error condition; therefore, some results may have been returned.
///
Timedout = 0x40004,
///
/// No more data is available from the enumeration; the
/// user should terminate the enumeration.
///
NoMoreData = 0x40005,
///
/// The operation was
/// canceled.
///
OperationCanceled = 0x40006,
///
/// A request is still in progress; however, the results are not
/// yet available.
///
Pending = 0x40007,
///
/// More than one copy of the same object was detected in
/// the result set of an enumeration.
///
DuplicateObjects = 0x40008,
///
/// The user did not receive all of the requested objects
/// because of inaccessible resources (other than security violations).
///
PartialResults = 0x40010,
///
/// The call failed.
///
Failed = unchecked((int)0x80041001),
///
/// The object could not be found.
///
NotFound = unchecked((int)0x80041002),
///
/// The current user does not have permission to perform the
/// action.
///
AccessDenied = unchecked((int)0x80041003),
///
/// The provider failed after
/// initialization.
///
ProviderFailure = unchecked((int)0x80041004),
///
/// A type mismatch occurred.
///
TypeMismatch = unchecked((int)0x80041005),
///
/// There was not enough memory for the operation.
///
OutOfMemory = unchecked((int)0x80041006),
///
/// The context object is not valid.
///
InvalidContext = unchecked((int)0x80041007),
///
/// One of the parameters to the call is not correct.
///
///
InvalidParameter = unchecked((int)0x80041008),
///
/// The resource, typically a remote server, is not
/// currently available.
///
NotAvailable = unchecked((int)0x80041009),
///
/// An internal, critical, and unexpected error occurred.
/// Report this error to Microsoft Product Support Services.
///
CriticalError = unchecked((int)0x8004100A),
///
/// One or more network packets were corrupted during a remote session.
///
InvalidStream = unchecked((int)0x8004100B),
///
/// The feature or operation is not supported.
///
NotSupported = unchecked((int)0x8004100C),
///
/// The specified base class is not valid.
///
InvalidSuperclass = unchecked((int)0x8004100D),
///
/// The specified namespace could not be found.
///
InvalidNamespace = unchecked((int)0x8004100E),
///
/// The specified instance is not valid.
///
InvalidObject = unchecked((int)0x8004100F),
///
/// The specified class is not valid.
///
InvalidClass = unchecked((int)0x80041010),
///
/// A provider referenced in the schema does not have a
/// corresponding registration.
///
ProviderNotFound = unchecked((int)0x80041011),
///
/// A provider referenced in the schema has an incorrect or
/// incomplete registration.
///
InvalidProviderRegistration = unchecked((int)0x80041012),
///
/// COM cannot locate a provider referenced in the schema.
///
ProviderLoadFailure = unchecked((int)0x80041013),
///
/// A component, such as a provider, failed to initialize for internal reasons.
///
InitializationFailure = unchecked((int)0x80041014),
///
/// A networking error that prevents normal operation has
/// occurred.
///
TransportFailure = unchecked((int)0x80041015),
///
/// The requested operation is not valid. This error usually
/// applies to invalid attempts to delete classes or properties.
///
InvalidOperation = unchecked((int)0x80041016),
///
/// The query was not syntactically valid.
///
InvalidQuery = unchecked((int)0x80041017),
///
/// The requested query language is not supported.
///
InvalidQueryType = unchecked((int)0x80041018),
///
/// In a put operation, the
/// flag was specified, but the instance already exists.
///
AlreadyExists = unchecked((int)0x80041019),
///
/// The add operation cannot be performed on the qualifier
/// because the owning object does not permit overrides.
///
OverrideNotAllowed = unchecked((int)0x8004101A),
///
/// The user attempted to delete a qualifier that was not
/// owned. The qualifier was inherited from a parent class.
///
PropagatedQualifier = unchecked((int)0x8004101B),
///
/// The user attempted to delete a property that was not
/// owned. The property was inherited from a parent class.
///
PropagatedProperty = unchecked((int)0x8004101C),
///
/// The client made an unexpected and illegal sequence of
/// calls.
///
Unexpected = unchecked((int)0x8004101D),
///
/// The user requested an illegal operation, such as
/// spawning a class from an instance.
///
IllegalOperation = unchecked((int)0x8004101E),
///
/// There was an illegal attempt to specify a key qualifier
/// on a property that cannot be a key. The keys are specified in the class
/// definition for an object and cannot be altered on a per-instance basis.
///
CannotBeKey = unchecked((int)0x8004101F),
///
/// The current object is not a valid class definition.
/// Either it is incomplete, or it has not been registered with WMI using
/// ().
///
IncompleteClass = unchecked((int)0x80041020),
///
/// Reserved for future use.
///
InvalidSyntax = unchecked((int)0x80041021),
///
/// Reserved for future use.
///
NondecoratedObject = unchecked((int)0x80041022),
///
/// The property that you are attempting to modify is read-only.
///
ReadOnly = unchecked((int)0x80041023),
///
/// The provider cannot perform the requested operation, such
/// as requesting a query that is too complex, retrieving an instance, creating or
/// updating a class, deleting a class, or enumerating a class.
///
ProviderNotCapable = unchecked((int)0x80041024),
///
/// An attempt was made to make a change that would
/// invalidate a derived class.
///
ClassHasChildren = unchecked((int)0x80041025),
///
/// An attempt has been made to delete or modify a class that
/// has instances.
///
ClassHasInstances = unchecked((int)0x80041026),
///
/// Reserved for future use.
///
QueryNotImplemented = unchecked((int)0x80041027),
///
/// A value of null was specified for a property that may
/// not be null, such as one that is marked by a , , or
/// qualifier.
///
IllegalNull = unchecked((int)0x80041028),
///
/// The value provided for a qualifier was not a
/// legal qualifier type.
///
InvalidQualifierType = unchecked((int)0x80041029),
///
/// The CIM type specified for a property is not valid.
///
InvalidPropertyType = unchecked((int)0x8004102A),
///
/// The request was made with an out-of-range value, or is
/// incompatible with the type.
///
ValueOutOfRange = unchecked((int)0x8004102B),
///
/// An illegal attempt was made to make a class singleton,
/// such as when the class is derived from a non-singleton class.
///
CannotBeSingleton = unchecked((int)0x8004102C),
///
/// The CIM type specified is not valid.
///
InvalidCimType = unchecked((int)0x8004102D),
///
/// The requested method is not available.
///
InvalidMethod = unchecked((int)0x8004102E),
///
/// The parameters provided for the method are not valid.
///
///
InvalidMethodParameters = unchecked((int)0x8004102F),
///
/// There was an attempt to get qualifiers on a system
/// property.
///
SystemProperty = unchecked((int)0x80041030),
///
/// The property type is not recognized.
///
InvalidProperty = unchecked((int)0x80041031),
///
/// An asynchronous process has been canceled internally or
/// by the user. Note that because of the timing and nature of the asynchronous
/// operation, the operation may not have been truly canceled.
///
CallCanceled = unchecked((int)0x80041032),
///
/// The user has requested an operation while WMI is in the
/// process of quitting.
///
ShuttingDown = unchecked((int)0x80041033),
///
/// An attempt was made to reuse an existing method name from
/// a base class, and the signatures did not match.
///
PropagatedMethod = unchecked((int)0x80041034),
///
/// One or more parameter values, such as a query text, is
/// too complex or unsupported. WMI is requested to retry the operation
/// with simpler parameters.
///
UnsupportedParameter = unchecked((int)0x80041035),
///
/// A parameter was missing from the method call.
///
MissingParameterID = unchecked((int)0x80041036),
///
/// A method parameter has an invalid qualifier.
///
InvalidParameterID = unchecked((int)0x80041037),
///
/// One or more of the method parameters have
/// qualifiers that are out of sequence.
///
NonconsecutiveParameterIDs = unchecked((int)0x80041038),
///
/// The return value for a method has an qualifier.
///
///
ParameterIDOnRetval = unchecked((int)0x80041039),
///
/// The specified object path was invalid.
///
InvalidObjectPath = unchecked((int)0x8004103A),
///
/// There is not enough free disk space to continue the
/// operation.
///
OutOfDiskSpace = unchecked((int)0x8004103B),
///
/// The supplied buffer was too small to hold all the objects
/// in the enumerator or to read a string property.
///
BufferTooSmall = unchecked((int)0x8004103C),
///
/// The provider does not support the requested put
/// operation.
///
UnsupportedPutExtension = unchecked((int)0x8004103D),
///
/// An object with an incorrect type or version was
/// encountered during marshaling.
///
UnknownObjectType = unchecked((int)0x8004103E),
///
/// A packet with an incorrect type or version was
/// encountered during marshaling.
///
UnknownPacketType = unchecked((int)0x8004103F),
///
/// The packet has an unsupported version.
///
MarshalVersionMismatch = unchecked((int)0x80041040),
///
/// The packet is corrupted.
///
MarshalInvalidSignature = unchecked((int)0x80041041),
///
/// An attempt has been made to mismatch qualifiers, such as
/// putting [key] on an object instead of a property.
///
InvalidQualifier = unchecked((int)0x80041042),
///
/// A duplicate parameter has been declared in a CIM method.
///
InvalidDuplicateParameter = unchecked((int)0x80041043),
///
/// Reserved for future use.
///
TooMuchData = unchecked((int)0x80041044),
///
/// The delivery of an event has failed. The provider may
/// choose to re-raise the event.
///
ServerTooBusy = unchecked((int)0x80041045),
///
/// The specified flavor was invalid.
///
InvalidFlavor = unchecked((int)0x80041046),
///
/// An attempt has been made to create a reference that is
/// circular (for example, deriving a class from itself).
///
CircularReference = unchecked((int)0x80041047),
///
/// The specified class is not supported.
///
UnsupportedClassUpdate = unchecked((int)0x80041048),
///
/// An attempt was made to change a key when instances or derived
/// classes are already using the key.
///
CannotChangeKeyInheritance = unchecked((int)0x80041049),
///
/// An attempt was made to change an index when instances or derived
/// classes are already using the index.
///
CannotChangeIndexInheritance = unchecked((int)0x80041050),
///
/// An attempt was made to create more properties than the
/// current version of the class supports.
///
TooManyProperties = unchecked((int)0x80041051),
///
/// A property was redefined with a conflicting type in a
/// derived class.
///
UpdateTypeMismatch = unchecked((int)0x80041052),
///
/// An attempt was made in a derived class to override a
/// non-overrideable qualifier.
///
UpdateOverrideNotAllowed = unchecked((int)0x80041053),
///
/// A method was redeclared with a conflicting signature in a
/// derived class.
///
UpdatePropagatedMethod = unchecked((int)0x80041054),
///
/// An attempt was made to execute a method not marked with
/// [implemented] in any relevant class.
///
MethodNotImplemented = unchecked((int)0x80041055),
///
/// An attempt was made to execute a method marked with
/// [disabled].
///
MethodDisabled = unchecked((int)0x80041056),
///
/// The refresher is busy with another operation.
///
RefresherBusy = unchecked((int)0x80041057),
///
/// The filtering query is syntactically invalid.
///
UnparsableQuery = unchecked((int)0x80041058),
///
/// The FROM clause of a filtering query references a class
/// that is not an event class.
///
NotEventClass = unchecked((int)0x80041059),
///
/// A GROUP BY clause was used without the corresponding
/// GROUP WITHIN clause.
///
MissingGroupWithin = unchecked((int)0x8004105A),
///
/// A GROUP BY clause was used. Aggregation on all properties
/// is not supported.
///
MissingAggregationList = unchecked((int)0x8004105B),
///
/// Dot notation was used on a property that is not an
/// embedded object.
///
PropertyNotAnObject = unchecked((int)0x8004105C),
///
/// A GROUP BY clause references a property that is an
/// embedded object without using dot notation.
///
AggregatingByObject = unchecked((int)0x8004105D),
///
/// An event provider registration query
/// ( ) did not specify the classes for which
/// events were provided.
///
UninterpretableProviderQuery = unchecked((int)0x8004105F),
///
/// An request was made to back up or restore the repository
/// while WinMgmt.exe was using it.
///
BackupRestoreWinmgmtRunning = unchecked((int)0x80041060),
///
/// The asynchronous delivery queue overflowed from the
/// event consumer being too slow.
///
QueueOverflow = unchecked((int)0x80041061),
///
/// The operation failed because the client did not have the
/// necessary security privilege.
///
PrivilegeNotHeld = unchecked((int)0x80041062),
///
/// The operator is not valid for this property type.
///
InvalidOperator = unchecked((int)0x80041063),
///
/// The user specified a username, password, or authority on a
/// local connection. The user must use an empty user name and password and rely on
/// default security.
///
LocalCredentials = unchecked((int)0x80041064),
///
/// The class was made abstract when its base class is not
/// abstract.
///
CannotBeAbstract = unchecked((int)0x80041065),
///
/// An amended object was used in a put operation without the
/// WBEM_FLAG_USE_AMENDED_QUALIFIERS flag being specified.
///
AmendedObject = unchecked((int)0x80041066),
///
/// The client was not retrieving objects quickly enough from
/// an enumeration.
///
ClientTooSlow = unchecked((int)0x80041067),
///
/// The provider registration overlaps with the system event
/// domain.
///
RegistrationTooBroad = unchecked((int)0x80042001),
///
/// A WITHIN clause was not used in this query.
///
RegistrationTooPrecise = unchecked((int)0x80042002)
}
///
/// Represents management exceptions.
///
///
/// using System;
/// using System.Management;
///
/// // This sample demonstrates how to display error
/// // information stored in a ManagementException object.
/// class Sample_ManagementException
/// {
/// public static int Main(string[] args)
/// {
/// try
/// {
/// ManagementObject disk =
/// new ManagementObject("Win32_LogicalDisk.DeviceID='BAD:'");
/// disk.Get(); // throws ManagementException
/// Console.WriteLine("This shouldn't be displayed.");
/// }
/// catch (ManagementException e)
/// {
/// Console.WriteLine("ErrorCode " + e.ErrorCode);
/// Console.WriteLine("Message " + e.Message);
/// Console.WriteLine("Source " + e.Source);
/// if (e.ErrorInformation) //extended error object
/// Console.WriteLine("Extended Description : " + e.ErrorInformation["Description"]);
/// }
/// return 0;
/// }
/// }
///
/// Imports System
/// Imports System.Management
///
/// ' This sample demonstrates how to display error
/// ' information stored in a ManagementException object.
/// Class Sample_ManagementException
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Try
/// Dim disk As New ManagementObject("Win32_LogicalDisk.DeviceID='BAD:'")
/// disk.Get() ' throws ManagementException
/// Console.WriteLine("This shouldn't be displayed.")
/// Catch e As ManagementException
/// Console.WriteLine("ErrorCode " & e.ErrorCode)
/// Console.WriteLine("Message " & e.Message)
/// Console.WriteLine("Source " & e.Source)
/// If e.ErrorInformation != Nothing Then 'extended error object
/// Console.WriteLine("Extended Description : " & e.ErrorInformation("Description"))
/// End If
/// End Try
/// Return 0
/// End Function
/// End Class
///
///
[Serializable]
public class ManagementException : SystemException
{
private ManagementBaseObject errorObject = null;
private ManagementStatus errorCode = 0;
internal static void ThrowWithExtendedInfo(ManagementStatus errorCode)
{
ManagementBaseObject errObj = null;
string msg = null;
//Try to get extended error info first, and save in errorObject member
IWbemClassObjectFreeThreaded obj = WbemErrorInfo.GetErrorInfo();
if (obj != null)
errObj = new ManagementBaseObject(obj);
//If the error code is not a WMI one and there's an extended error object available, stick the message
//from the extended error object in.
if (((msg = GetMessage(errorCode)) == null) && (errObj != null))
try
{
msg = (string)errObj["Description"];
}
catch {}
throw new ManagementException(errorCode, msg, errObj);
}
internal static void ThrowWithExtendedInfo(Exception e)
{
ManagementBaseObject errObj = null;
string msg = null;
//Try to get extended error info first, and save in errorObject member
IWbemClassObjectFreeThreaded obj = WbemErrorInfo.GetErrorInfo();
if (obj != null)
errObj = new ManagementBaseObject(obj);
//If the error code is not a WMI one and there's an extended error object available, stick the message
//from the extended error object in.
if (((msg = GetMessage(e)) == null) && (errObj != null))
try
{
msg = (string)errObj["Description"];
}
catch {}
throw new ManagementException(e, msg, errObj);
}
internal ManagementException(ManagementStatus errorCode, string msg, ManagementBaseObject errObj) : base (msg)
{
this.errorCode = errorCode;
this.errorObject = errObj;
}
internal ManagementException(Exception e, string msg, ManagementBaseObject errObj) : base (msg, e)
{
try
{
if (e is ManagementException)
{
errorCode = ((ManagementException)e).ErrorCode;
// May/may not have extended error info.
//
if (errorObject != null)
errorObject = (ManagementBaseObject)((ManagementException)e).errorObject.Clone();
else
errorObject = null;
}
else if (e is COMException)
errorCode = (ManagementStatus)((COMException)e).ErrorCode;
else
errorCode = (ManagementStatus)this.HResult;
}
catch {}
}
///
/// Initializes a new instance of the class that is serializable.
///
/// The to populate with data.
/// The destination (see ) for this serialization.
protected ManagementException(SerializationInfo info, StreamingContext context) : base(info, context)
{
errorCode = (ManagementStatus)info.GetValue("errorCode", typeof(ManagementStatus));
errorObject = info.GetValue("errorObject", typeof(ManagementBaseObject)) as ManagementBaseObject;
}
///
/// Initializes a new instance of the class
///
public ManagementException():this(ManagementStatus.Failed, "", null)
{
}
///
/// Initializes a new instance of the
/// class with a specified error message.
/// The message that describes the error.
///
public ManagementException(string message):this(ManagementStatus.Failed, message, null)
{
}
///
/// Initializes a empty new instance of the class
/// The message that describes the error.
/// The exception that is the cause of the current exception. If the innerException
/// parameter is not a null reference (Nothing in Visual Basic), the current exception is raised in a catch
/// block that handles the inner exception.
///
public ManagementException(string message,Exception innerException):this(innerException, message, null)
{
// if the exception passed is not a ManagementException, then initialize the ErrorCode to Failed
if (!(innerException is ManagementException))
errorCode = ManagementStatus.Failed;
}
///
/// Populates the object with the data needed to
/// serialize the
/// object.
///
/// The to populate with data.
/// The destination (see ) for this serialization.
//FXCop requests explicit demand of the SerializationFormatter permission
[SecurityPermission(SecurityAction.Demand, SerializationFormatter=true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("errorCode", errorCode);
info.AddValue("errorObject", errorObject);
}
private static string GetMessage(Exception e)
{
string msg = null;
if (e is COMException)
{
// Try and get WMI error message. If not use the one in
// the exception
msg = GetMessage ((ManagementStatus)((COMException)e).ErrorCode);
}
if (null == msg)
msg = e.Message;
return msg;
}
private static string GetMessage(ManagementStatus errorCode)
{
string msg = null;
IWbemStatusCodeText statusCode = null;
int hr;
statusCode = (IWbemStatusCodeText) new WbemStatusCodeText();
if (statusCode != null)
{
try {
hr = statusCode.GetErrorCodeText_((int)errorCode, 0, 1, out msg);
// Just in case it didn't like the flag=1, try it again
// with flag=0.
if (hr != 0)
hr = statusCode.GetErrorCodeText_((int)errorCode, 0, 0, out msg);
}
catch {}
}
return msg;
}
///
/// Gets the extended error object provided by WMI.
///
///
/// A representing the
/// extended error object provided by WMI, if available;
/// otherwise.
///
public ManagementBaseObject ErrorInformation
{
get
{ return errorObject; }
}
///
/// Gets the error code reported by WMI, which caused this exception.
///
///
/// A value representing the error code returned by
/// the WMI operation.
///
public ManagementStatus ErrorCode
{
get
{ return errorCode; }
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
// Copyright (c) Microsoft Corporation. All rights reserved.
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- DataServiceQueryProvider.cs
- AppSettings.cs
- ControlSerializer.cs
- CultureNotFoundException.cs
- EncoderFallback.cs
- StylusPointPropertyUnit.cs
- ExecutorLocksHeldException.cs
- ToolStripOverflowButton.cs
- AssemblyAttributesGoHere.cs
- XmlQueryStaticData.cs
- WebPartDescriptionCollection.cs
- ApplicationTrust.cs
- UrlMappingsModule.cs
- HttpHandlerActionCollection.cs
- IpcServerChannel.cs
- DoubleCollectionConverter.cs
- SlipBehavior.cs
- Viewport2DVisual3D.cs
- EndpointInfoCollection.cs
- DesignTimeTemplateParser.cs
- XmlSchemas.cs
- Marshal.cs
- DescendentsWalkerBase.cs
- ScrollChrome.cs
- _FixedSizeReader.cs
- Stack.cs
- BinaryParser.cs
- RootBrowserWindowProxy.cs
- RegistryDataKey.cs
- VisualProxy.cs
- DataControlFieldCollection.cs
- DataGridViewRowConverter.cs
- ObfuscationAttribute.cs
- StylusDevice.cs
- AbstractExpressions.cs
- entitydatasourceentitysetnameconverter.cs
- BooleanAnimationUsingKeyFrames.cs
- SamlAttributeStatement.cs
- CodeBlockBuilder.cs
- TableStyle.cs
- HandledMouseEvent.cs
- HtmlTableRowCollection.cs
- MediaTimeline.cs
- HostedElements.cs
- TypedReference.cs
- DesignerOptionService.cs
- GetImportFileNameRequest.cs
- CustomErrorsSectionWrapper.cs
- DataGridColumnFloatingHeader.cs
- Animatable.cs
- DocumentViewerConstants.cs
- XmlEncodedRawTextWriter.cs
- Assert.cs
- XhtmlBasicPageAdapter.cs
- FontDifferentiator.cs
- FilterableData.cs
- ComplexLine.cs
- WebHostScriptMappingsInstallComponent.cs
- BinaryObjectWriter.cs
- SingleSelectRootGridEntry.cs
- TdsParserSafeHandles.cs
- ReaderWriterLock.cs
- NoClickablePointException.cs
- ScrollData.cs
- CompilerScopeManager.cs
- Membership.cs
- XamlFigureLengthSerializer.cs
- SigningCredentials.cs
- CriticalFinalizerObject.cs
- SmtpNegotiateAuthenticationModule.cs
- TypeElement.cs
- InputProcessorProfiles.cs
- XmlComment.cs
- XmlWriter.cs
- IDictionary.cs
- HtmlInputReset.cs
- StickyNote.cs
- RemoteX509AsymmetricSecurityKey.cs
- XmlSerializer.cs
- LinqDataSourceDisposeEventArgs.cs
- PropertyGridEditorPart.cs
- StateMachineSubscriptionManager.cs
- NetworkInterface.cs
- DataGridViewRowsRemovedEventArgs.cs
- PagedDataSource.cs
- ServiceContractDetailViewControl.cs
- BamlResourceContent.cs
- EnumMember.cs
- sitestring.cs
- RadioButton.cs
- HttpWriter.cs
- ObjectDataSourceMethodEventArgs.cs
- ObjectCloneHelper.cs
- ScrollBarRenderer.cs
- JumpList.cs
- RequestSecurityToken.cs
- WebBrowserEvent.cs
- PathFigureCollection.cs
- SapiRecoInterop.cs
- LightweightEntityWrapper.cs