[DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLExecDirectW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
- /*SQLCHAR* */string StatementText,
+ /*SQLCHAR* */string StatementText,
/*SQLINTEGER*/int TextLength);
[DllImport(Interop.Libraries.Odbc32)]
[DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLPrepareW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
- /*SQLCHAR* */string StatementText,
+ /*SQLCHAR* */string StatementText,
/*SQLINTEGER*/int TextLength);
[DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)]
internal static partial class Advapi32
{
[DllImport(Interop.Libraries.Advapi32, SetLastError = true)]
- internal static extern
- bool DuplicateTokenEx(SafeTokenHandle ExistingTokenHandle,
+ internal static extern bool DuplicateTokenEx(SafeTokenHandle ExistingTokenHandle,
TokenAccessLevels DesiredAccess,
IntPtr TokenAttributes,
SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
internal const int ERROR_INVALID_PARAMETER = 0x57;
internal const int ERROR_BROKEN_PIPE = 0x6D;
internal const int ERROR_SEM_TIMEOUT = 0x79;
- internal const int ERROR_CALL_NOT_IMPLEMENTED = 0x78;
+ internal const int ERROR_CALL_NOT_IMPLEMENTED = 0x78;
internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A;
internal const int ERROR_INVALID_NAME = 0x7B;
internal const int ERROR_NEGATIVE_SEEK = 0x83;
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363189.aspx
internal struct COMMPROP
{
- public ushort wPacketLength;
- public ushort wPacketVersion;
+ public ushort wPacketLength;
+ public ushort wPacketVersion;
public int dwServiceMask;
public int dwReserved1;
public int dwMaxTxQueue;
public int dwSettableParams;
public int dwSettableBaud;
public ushort wSettableData;
- public ushort wSettableStopParity;
+ public ushort wSettableStopParity;
public int dwCurrentTxQueue;
public int dwCurrentRxQueue;
public int dwProvSpec1;
{
internal partial class Kernel32
{
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool ClearCommBreak(
SafeFileHandle hFile);
}
{
internal partial class Kernel32
{
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool ClearCommError(
SafeFileHandle hFile,
ref int lpErrors,
internal const int CLRDTR = 6;
}
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool EscapeCommFunction(
SafeFileHandle hFile,
int dwFunc);
if (GetCPInfoExW((uint)codePage, 0, &cpInfo) != BOOL.FALSE)
{
// we don't care about the last 2 bytes as those are nulls
- for (int i=0; i<10 && leadByteRanges[i] != 0; i+=2)
+ for (int i = 0; i < 10 && leadByteRanges[i] != 0; i += 2)
{
leadByteRanges[i] = cpInfo.LeadByte[i];
- leadByteRanges[i+1] = cpInfo.LeadByte[i+1];
+ leadByteRanges[i + 1] = cpInfo.LeadByte[i + 1];
count++;
}
}
internal const int MS_RLSD_ON = 0x80;
}
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool GetCommModemStatus(
SafeFileHandle hFile,
ref int lpModemStat);
{
internal partial class Kernel32
{
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool GetCommProperties(
SafeFileHandle hFile,
ref COMMPROP lpCommProp);
{
internal partial class Kernel32
{
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool GetCommState(
SafeFileHandle hFile,
ref DCB lpDCB);
{
internal partial class Kernel32
{
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern unsafe bool GetOverlappedResult(
SafeFileHandle hFile,
NativeOverlapped* lpOverlapped,
{
internal partial class Kernel32
{
- [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Unicode, EntryPoint ="PeekConsoleInputW")]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "PeekConsoleInputW")]
internal static extern bool PeekConsoleInput(IntPtr hConsoleInput, out InputRecord buffer, int numInputRecords_UseOne, out int numEventsRead);
}
}
internal const uint PURGE_RXCLEAR = 0x0008; // Kill the typeahead buffer if there.
}
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool PurgeComm(
SafeFileHandle hFile,
uint dwFlags);
{
internal partial class Kernel32
{
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool SetCommBreak(
SafeFileHandle hFile);
}
internal const int ALL_EVENTS = 0x1fb;
}
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool SetCommMask(
SafeFileHandle hFile,
int dwEvtMask
{
internal partial class Kernel32
{
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool SetCommState(
SafeFileHandle hFile,
ref DCB lpDCB);
{
internal const int MAXDWORD = -1; // This is 0xfffffff, or UInt32.MaxValue, here used as an int
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool SetCommTimeouts(
SafeFileHandle hFile,
ref COMMTIMEOUTS lpCommTimeouts);
{
internal partial class Kernel32
{
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool SetupComm(
SafeFileHandle hFile,
int dwInQueue,
{
internal partial class Kernel32
{
- [DllImport(Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto)]
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern unsafe bool WaitCommEvent(
SafeFileHandle hFile,
int* lpEvtMask,
{
internal partial class Kernel32
{
- [DllImport(Libraries.Kernel32, ExactSpelling=true, SetLastError=true)]
+ [DllImport(Libraries.Kernel32, ExactSpelling = true, SetLastError = true)]
internal static extern int WaitForSingleObject(SafeWaitHandle handle, int timeout);
}
}
{
internal partial class NtDll
{
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal unsafe struct RTL_OSVERSIONINFOEX
{
internal uint dwOSVersionInfoSize;
{
internal partial class NtDll
{
- [DllImport(Libraries.NtDll, ExactSpelling=true)]
+ [DllImport(Libraries.NtDll, ExactSpelling = true)]
private static extern int RtlGetVersion(ref RTL_OSVERSIONINFOEX lpVersionInformation);
internal static unsafe int RtlGetVersionEx(out RTL_OSVERSIONINFOEX osvi)
//
private static unsafe int MustRunInitializeSecurityContext(
ref SafeFreeCredentials inCredentials,
- bool isContextAbsent,
+ bool isContextAbsent,
byte* targetName,
Interop.SspiCli.ContextFlags inFlags,
Interop.SspiCli.Endianness endianness,
{
internal partial class User32
{
- [DllImport(Libraries.User32, CharSet=CharSet.Unicode, SetLastError=true, ExactSpelling = true)]
+ [DllImport(Libraries.User32, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr CreateWindowExW(
int exStyle,
string lpszClassName,
{
internal partial class User32
{
- [DllImport(Libraries.User32, CharSet=CharSet.Unicode, ExactSpelling = true)]
+ [DllImport(Libraries.User32, CharSet = CharSet.Unicode, ExactSpelling = true)]
public static extern bool GetClassInfoW(IntPtr hInst, string lpszClass, ref WNDCLASS wc);
}
}
{
internal partial class User32
{
- [DllImport(Libraries.User32, ExactSpelling=true)]
+ [DllImport(Libraries.User32, ExactSpelling = true)]
internal static extern IntPtr GetProcessWindowStation();
}
}
{
internal partial class User32
{
- [DllImport(Libraries.User32, SetLastError=true, CharSet = CharSet.Unicode, ExactSpelling = true)]
+ [DllImport(Libraries.User32, SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
public static extern bool GetUserObjectInformationW(IntPtr hObj, int nIndex, ref USEROBJECTFLAGS pvBuffer, int nLength, ref int lpnLengthNeeded);
}
}
internal partial class User32
{
[StructLayout(LayoutKind.Sequential)]
- public struct MSG {
- public IntPtr hwnd;
- public int message;
- public IntPtr wParam;
- public IntPtr lParam;
- public int time;
- public int pt_x;
- public int pt_y;
+ public struct MSG
+ {
+ public IntPtr hwnd;
+ public int message;
+ public IntPtr wParam;
+ public IntPtr lParam;
+ public int time;
+ public int pt_x;
+ public int pt_y;
}
}
}
{
internal partial class User32
{
- internal struct USEROBJECTFLAGS {
+ internal struct USEROBJECTFLAGS
+ {
public int fInherit;
public int fReserved;
public int dwFlags;
{
internal partial class User32
{
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal unsafe struct WNDCLASS
{
public int style;
+ "))"
+ "[\\s;]*"
;*/
- private const string ConnectionStringPattern = // may not contain embedded null except trailing last value
+ private const string ConnectionStringPattern = // may not contain embedded null except trailing last value
"([\\s;]*" // leading whitespace and extra semicolons
+ "(?![\\s;])" // key does not start with space or semicolon
+ "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)" // allow any visible character for keyname except '=' which must quoted as '=='
+ "\\s*=(?!=)\\s*" // the equal sign divides the key and value parts
+ "(?<value>"
- + "(\"([^\"\u0000]|\"\")*\")" // double quoted string, " must be quoted as ""
+ + "(\"([^\"\u0000]|\"\")*\")" // double quoted string, " must be quoted as ""
+ "|"
- + "('([^'\u0000]|'')*')" // single quoted string, ' must be quoted as ''
+ + "('([^'\u0000]|'')*')" // single quoted string, ' must be quoted as ''
+ "|"
- + "((?![\"'\\s])" // unquoted value must not start with " or ' or space, would also like = but too late to change
- + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
+ + "((?![\"'\\s])" // unquoted value must not start with " or ' or space, would also like = but too late to change
+ + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
+ "(?<![\"']))" // unquoted value must not stop with " or '
- + ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
- + ")*" // repeat the key-value pair
- + "[\\s;]*[\u0000\\s]*" // trailing whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
+ + ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
+ + ")*" // repeat the key-value pair
+ + "[\\s;]*[\u0000\\s]*" // trailing whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
;
- private const string ConnectionStringPatternOdbc = // may not contain embedded null except trailing last value
- "([\\s;]*" // leading whitespace and extra semicolons
- + "(?![\\s;])" // key does not start with space or semicolon
- + "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}])+)" // allow any visible character for keyname except '='
- + "\\s*=\\s*" // the equal sign divides the key and value parts
+ private const string ConnectionStringPatternOdbc = // may not contain embedded null except trailing last value
+ "([\\s;]*" // leading whitespace and extra semicolons
+ + "(?![\\s;])" // key does not start with space or semicolon
+ + "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}])+)" // allow any visible character for keyname except '='
+ + "\\s*=\\s*" // the equal sign divides the key and value parts
+ "(?<value>"
+ "(\\{([^\\}\u0000]|\\}\\})*\\})" // quoted string, starts with { and ends with }
+ "|"
+ "((?![\\{\\s])" // unquoted value must not start with { or space, would also like = but too late to change
- + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
+ + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
- + ")" // although the spec does not allow {}
- // embedded within a value, the retail code does.
+ + ")" // although the spec does not allow {} embedded within a value, the retail code does.
+ ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
- + ")*" // repeat the key-value pair
- + "[\\s;]*[\u0000\\s]*" // traling whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
+ + ")*" // repeat the key-value pair
+ + "[\\s;]*[\u0000\\s]*" // traling whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
;
private static readonly Regex s_connectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
try
{
#endif
- int nextStartPosition = 0;
- int endPosition = connectionString.Length;
- while (nextStartPosition < endPosition)
- {
- int startPosition = nextStartPosition;
-
- string keyname, keyvalue;
- nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue);
- if (string.IsNullOrEmpty(keyname))
+ int nextStartPosition = 0;
+ int endPosition = connectionString.Length;
+ while (nextStartPosition < endPosition)
{
- // if (nextStartPosition != endPosition) { throw; }
- break;
- }
+ int startPosition = nextStartPosition;
+
+ string keyname, keyvalue;
+ nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue);
+ if (string.IsNullOrEmpty(keyname))
+ {
+ break;
+ }
#if DEBUG
DebugTraceKeyValuePair(keyname, keyvalue, synonyms);
Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname");
Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue");
#endif
- string synonym;
- string realkeyname = null != synonyms ?
- (synonyms.TryGetValue(keyname, out synonym) ? synonym : null) :
- keyname;
- if (!IsKeyNameValid(realkeyname))
- {
- throw ADP.KeywordNotSupported(keyname);
- }
- if (!firstKey || !parsetable.ContainsKey(realkeyname))
- {
- parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
- }
+ string synonym;
+ string realkeyname = null != synonyms ?
+ (synonyms.TryGetValue(keyname, out synonym) ? synonym : null) :
+ keyname;
- if (null != localKeychain)
- {
- localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
- }
- else if (buildChain)
- { // first time only - don't contain modified chain from UDL file
- keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
+ if (!IsKeyNameValid(realkeyname))
+ {
+ throw ADP.KeywordNotSupported(keyname);
+ }
+ if (!firstKey || !parsetable.ContainsKey(realkeyname))
+ {
+ parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
+ }
+
+ if (null != localKeychain)
+ {
+ localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
+ }
+ else if (buildChain)
+ {
+ // first time only - don't contain modified chain from UDL file
+ keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
+ }
}
- }
#if DEBUG
}
catch (ArgumentException e)
#else
internal
#endif
- sealed class ExcludeFromCodeCoverageAttribute: Attribute
+ sealed class ExcludeFromCodeCoverageAttribute : Attribute
{
public ExcludeFromCodeCoverageAttribute()
{ }
// Handles E0, which should format the same as E-0
i++;
}
- else if (src+1 < format.Length && pFormat[src] == '+' && pFormat[src + 1] == '0')
+ else if (src + 1 < format.Length && pFormat[src] == '+' && pFormat[src + 1] == '0')
{
// Handles E+0
positiveSign = true;
}
- else if (src+1 < format.Length && pFormat[src] == '-' && pFormat[src + 1] == '0')
+ else if (src + 1 < format.Length && pFormat[src] == '-' && pFormat[src + 1] == '0')
{
// Handles E-0
// Do nothing, this is just a place holder s.t. we don't break out of the loop.
public static new bool IsEnabled =>
Log.IsEnabled();
- //true; // uncomment for debugging only
[NonEvent]
public static string IdOf(object value) => value != null ? value.GetType().Name + "#" + GetHashCode(value) : NullInstance;
// This is a user type, or a precanned resource. Find type
// table index. If not there, add new element.
string typeName;
- if (type == typeof(PrecannedResource)) {
+ if (type == typeof(PrecannedResource))
+ {
typeName = ((PrecannedResource)value).TypeName;
- if (typeName.StartsWith("ResourceTypeCode.", StringComparison.Ordinal)) {
+ if (typeName.StartsWith("ResourceTypeCode.", StringComparison.Ordinal))
+ {
typeName = typeName.Substring(17); // Remove through '.'
ResourceTypeCode typeCode = (ResourceTypeCode)Enum.Parse(typeof(ResourceTypeCode), typeName);
return typeCode;
}
int typeIndex = types.IndexOf(typeName);
- if (typeIndex == -1) {
+ if (typeIndex == -1)
+ {
typeIndex = types.Count;
types.Add(typeName);
}
WriteLength(-1);
}
- private void PopTag(Asn1Tag tag, UniversalTagNumber tagType, bool sortContents=false)
+ private void PopTag(Asn1Tag tag, UniversalTagNumber tagType, bool sortContents = false)
{
CheckDisposed();
}
public override string SignatureAlgorithm => "DSA";
- public override string KeyExchangeAlgorithm => null;
+ public override string KeyExchangeAlgorithm => null;
// Need to override since base methods throw a "override me" exception: makes SignData/VerifyData function.
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) =>
out key);
}
- internal static ReadOnlyMemory<byte> ReadSubjectPublicKeyInfo(
- ReadOnlyMemory<byte> source,
- out int bytesRead)
+ internal static ReadOnlyMemory<byte> ReadSubjectPublicKeyInfo(
+ ReadOnlyMemory<byte> source,
+ out int bytesRead)
{
return KeyFormatHelper.ReadSubjectPublicKeyInfo(
s_validOids,
out key);
}
- internal static ReadOnlyMemory<byte> ReadSubjectPublicKeyInfo(
- ReadOnlyMemory<byte> source,
- out int bytesRead)
+ internal static ReadOnlyMemory<byte> ReadSubjectPublicKeyInfo(
+ ReadOnlyMemory<byte> source,
+ out int bytesRead)
{
return KeyFormatHelper.ReadSubjectPublicKeyInfo(
s_validOids,
out key);
}
- internal static ReadOnlyMemory<byte> ReadSubjectPublicKeyInfo(
- ReadOnlyMemory<byte> source,
- out int bytesRead)
+ internal static ReadOnlyMemory<byte> ReadSubjectPublicKeyInfo(
+ ReadOnlyMemory<byte> source,
+ out int bytesRead)
{
return KeyFormatHelper.ReadSubjectPublicKeyInfo(
s_validOids,
index++;
}
- int result = OSEncoding.MultiByteToWideChar(_encoding.CodePage, pTempBuffer, index+1, chars, charCount);
+ int result = OSEncoding.MultiByteToWideChar(_encoding.CodePage, pTempBuffer, index + 1, chars, charCount);
if (count - index > 0)
result += OSEncoding.MultiByteToWideChar(
if (charCount == 0)
return 0;
- byte lastByte = byteCount > 0 && !flush && IsLastByteALeadByte(bytes, byteCount) ? bytes[byteCount - 1] : (byte) 0;
+ byte lastByte = byteCount > 0 && !flush && IsLastByteALeadByte(bytes, byteCount) ? bytes[byteCount - 1] : (byte)0;
if (lastByte != 0)
byteCount--;
return 0;
}
- int result = OSEncoding.MultiByteToWideChar(_encoding.CodePage, bytes, byteCount, chars, charCount);
+ int result = OSEncoding.MultiByteToWideChar(_encoding.CodePage, bytes, byteCount, chars, charCount);
_leftOverLeadByte = lastByte;
return result;
}
index++;
}
- int result = OSEncoding.WideCharToMultiByte(_encoding.CodePage, pTempBuffer, index+1, bytes, byteCount);
+ int result = OSEncoding.WideCharToMultiByte(_encoding.CodePage, pTempBuffer, index + 1, bytes, byteCount);
if (count - index > 0)
result += OSEncoding.WideCharToMultiByte(
return 0;
}
- int result = OSEncoding.WideCharToMultiByte(_encoding.CodePage, chars, charCount, bytes, byteCount);
+ int result = OSEncoding.WideCharToMultiByte(_encoding.CodePage, chars, charCount, bytes, byteCount);
_charLeftOver = lastChar;
return result;
}
fixed (char* pChar = chars)
{
- return WideCharToMultiByte(_codePage, pChar+index, count, null, 0);
+ return WideCharToMultiByte(_codePage, pChar + index, count, null, 0);
}
}
}
fixed (char* pChars = s)
- fixed (byte *pBytes = &bytes[0])
+ fixed (byte* pBytes = &bytes[0])
{
- return WideCharToMultiByte(_codePage, pChars+charIndex, charCount, pBytes+byteIndex, bytes.Length - byteIndex);
+ return WideCharToMultiByte(_codePage, pChars + charIndex, charCount, pBytes + byteIndex, bytes.Length - byteIndex);
}
}
}
fixed (char* pChars = chars)
- fixed (byte *pBytes = &bytes[0])
+ fixed (byte* pBytes = &bytes[0])
{
- return WideCharToMultiByte(_codePage, pChars+charIndex, charCount, pBytes+byteIndex, bytes.Length - byteIndex);
+ return WideCharToMultiByte(_codePage, pChars + charIndex, charCount, pBytes + byteIndex, bytes.Length - byteIndex);
}
}
fixed (byte* pBytes = bytes)
{
- return MultiByteToWideChar(_codePage, pBytes+index, count, null, 0);
+ return MultiByteToWideChar(_codePage, pBytes + index, count, null, 0);
}
}
fixed (byte* pBytes = bytes)
fixed (char* pChars = &chars[0])
{
- return MultiByteToWideChar(_codePage, pBytes+byteIndex, byteCount, pChars+charIndex, chars.Length - charIndex);
+ return MultiByteToWideChar(_codePage, pBytes + byteIndex, byteCount, pChars + charIndex, chars.Length - charIndex);
}
}
// creating binders is not a very frequent operation.
// typically a dynamic operation in the source will create just one binder lazily when first executed.
private static readonly ConcurrentDictionary<ICSharpBinder, ICSharpBinder> binderEquivalenceCache =
- new ConcurrentDictionary<ICSharpBinder, ICSharpBinder>(concurrencyLevel:2, capacity: 32, new BinderEqualityComparer());
+ new ConcurrentDictionary<ICSharpBinder, ICSharpBinder>(concurrencyLevel: 2, capacity: 32, new BinderEqualityComparer());
internal static T TryGetExisting<T>(this T binder)
- where T: ICSharpBinder
+ where T : ICSharpBinder
{
var fromCache = binderEquivalenceCache.GetOrAdd(binder, binder);
if (fromCache == (object)binder)
DynamicMetaObject arg0 = args[0];
expression = Expression.Block(
- new[] {tempForIncrement},
+ new[] { tempForIncrement },
Expression.Assign(tempForIncrement, Expression.Convert(arg0.Expression, arg0.Value.GetType())),
expression,
Expression.Assign(arg0.Expression, Expression.Convert(tempForIncrement, arg0.Expression.Type)));
return array;
}
- return new[] {sourceHead, sourceLast};
+ return new[] { sourceHead, sourceLast };
}
/////////////////////////////////////////////////////////////////////////////////
{
BinderHelper.ValidateBindArgument(target, nameof(target));
BinderHelper.ValidateBindArgument(arg, nameof(arg));
- return BinderHelper.Bind(this, _binder, new[] {target, arg}, _argumentInfo, errorSuggestion);
+ return BinderHelper.Bind(this, _binder, new[] { target, arg }, _argumentInfo, errorSuggestion);
}
}
}
/// </summary>
internal sealed class CSharpGetIndexBinder : GetIndexBinder, ICSharpBinder
{
- public string Name => SpecialNames.Indexer;
+ public string Name => SpecialNames.Indexer;
public BindingFlag BindingFlags => BindingFlag.BIND_RVALUEREQUIRED;
public override DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
BinderHelper.ValidateBindArgument(target, nameof(target));
- return BinderHelper.Bind(this, _binder, new[] {target}, _argumentInfo, errorSuggestion);
+ return BinderHelper.Bind(this, _binder, new[] { target }, _argumentInfo, errorSuggestion);
}
}
}
return GenerateConvert(call);
case PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT:
- {
ExprList list = (ExprList)call.OptionalArguments;
return
Expression.NewArrayInit(
((ExprTypeOf)list.OptionalElement).SourceType.AssociatedSystemType,
GetArgumentsFromArrayInit((ExprArrayInit)list.OptionalNextListNode));
- }
case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX:
case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2:
pexprDest = ExprFactory.CreateConstant(typeDest, cv);
return ConstCastResult.Success;
}
- valueInt = (long)(constSrc.UInt64Value& 0xFFFFFFFFFFFFFFFF);
+ valueInt = (long)(constSrc.UInt64Value & 0xFFFFFFFFFFFFFFFF);
}
else
{
// invocation.
private GroupToArgsBinderResult BindMethodGroupToArgumentsCore(BindingFlag bindFlags, ExprMemberGroup grp, Expr args, int carg, NamedArgumentsKind namedArgumentsKind)
{
- ArgInfos pargInfo = new ArgInfos {carg = carg};
+ ArgInfos pargInfo = new ArgInfos { carg = carg };
FillInArgInfoFromArgList(pargInfo, args);
- ArgInfos pOriginalArgInfo = new ArgInfos {carg = carg};
+ ArgInfos pOriginalArgInfo = new ArgInfos { carg = carg };
FillInArgInfoFromArgList(pOriginalArgInfo, args);
GroupToArgsBinder binder = new GroupToArgsBinder(this, bindFlags, grp, pargInfo, pOriginalArgInfo, namedArgumentsKind);
[Conditional("DEBUG")]
private static void AssertObjectIsLvalue(Expr pObject)
{
- Debug.Assert (
+ Debug.Assert(
pObject == null || // statics are always lvalues
(((pObject.Flags & EXPRFLAG.EXF_LVALUE) != 0) && (pObject.Kind != ExpressionKind.Property)) ||
// things marked as lvalues have props/fields which are lvalues, with one exception: props of structs
return type;
- NEXTI:
+ NEXTI:
;
}
}
protected ExprOperator(ExpressionKind kind, CType type, Expr call, MethPropWithInst userDefinedMethod)
- : this (kind, type)
+ : this(kind, type)
{
OptionalUserDefinedCall = call;
UserDefinedCallMethod = userDefinedMethod;
Expr lhs;
if (assignment.LHS is ExprProperty prop)
{
- if (prop.OptionalArguments== null)
+ if (prop.OptionalArguments == null)
{
// Regular property.
lhs = Visit(prop);
{
Debug.Assert(expr != null);
Expr pObject;
- if (expr.OptionalObject== null)
+ if (expr.OptionalObject == null)
{
pObject = ExprFactory.CreateNull();
}
}
Expr pObject;
- if (expr.MethWithInst.Meth().isStatic || expr.MemberGroup.OptionalObject== null)
+ if (expr.MethWithInst.Meth().isStatic || expr.MemberGroup.OptionalObject == null)
{
pObject = ExprFactory.CreateNull();
}
{
Debug.Assert(expr != null);
Expr pObject;
- if (expr.PropWithTypeSlot.Prop().isStatic || expr.MemberGroup.OptionalObject== null)
+ if (expr.PropWithTypeSlot.Prop().isStatic || expr.MemberGroup.OptionalObject == null)
{
pObject = ExprFactory.CreateNull();
}
}
// The SymWithType is considered NULL iff the Symbol is NULL.
- public static implicit operator bool (SymWithType swt)
+ public static implicit operator bool(SymWithType swt)
{
return swt != null;
}
public override bool Equals(object obj)
{
Debug.Fail("Sub-optimal overload called. Check if this can be avoided.");
- return obj is NameHashKey key && Equals(key);
+ return obj is NameHashKey key && Equals(key);
}
public override int GetHashCode() => Type.GetHashCode() ^ Name.GetHashCode();
{
// We use "IsEquivalentTo" so that unified local types match.
if (sym is AggregateSymbol agg)
- if (agg.AssociatedSystemType.IsEquivalentTo(t.IsGenericType ? t.GetGenericTypeDefinition() : t))
- {
- return agg;
- }
+ if (agg.AssociatedSystemType.IsEquivalentTo(t.IsGenericType ? t.GetGenericTypeDefinition() : t))
+ {
+ return agg;
+ }
sym = sym.nextSameName;
}
else if (ArgumentMatch(arg, "out") || ShortNameArgumentMatch(arg, "o"))
{
i++;
- if (i >= args.Length || codePath != null )
+ if (i >= args.Length || codePath != null)
{
errs.Add(SR.Format(SR.ErrInvalidArgument, arg));
}
private bool ArgumentMatch(string arg, string formal)
{
// Full name format, eg: --assembly
- if (arg.Length < 3 || arg[0] != '-' || arg[1] != '-' )
+ if (arg.Length < 3 || arg[0] != '-' || arg[1] != '-')
{
return false;
}
}
}
- // replace + with . for nested classes.
- //
- var sb = new StringBuilder(s.Length + 10);
- if ((typeRef.Options & CodeTypeReferenceOptions.GlobalReference) != 0)
- {
- sb.Append("global::");
- }
+ // replace + with . for nested classes.
+ //
+ var sb = new StringBuilder(s.Length + 10);
+ if ((typeRef.Options & CodeTypeReferenceOptions.GlobalReference) != 0)
+ {
+ sb.Append("global::");
+ }
- string baseType = typeRef.BaseType;
+ string baseType = typeRef.BaseType;
- int lastIndex = 0;
- int currentTypeArgStart = 0;
- for (int i = 0; i < baseType.Length; i++)
- {
- switch (baseType[i])
+ int lastIndex = 0;
+ int currentTypeArgStart = 0;
+ for (int i = 0; i < baseType.Length; i++)
+ {
+ switch (baseType[i])
+ {
+ case '+':
+ case '.':
+ sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
+ sb.Append('.');
+ i++;
+ lastIndex = i;
+ break;
+
+ case '`':
+ sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
+ i++; // skip the '
+ int numTypeArgs = 0;
+ while (i < baseType.Length && baseType[i] >= '0' && baseType[i] <= '9')
{
- case '+':
- case '.':
- sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
- sb.Append('.');
- i++;
- lastIndex = i;
- break;
-
- case '`':
- sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
- i++; // skip the '
- int numTypeArgs = 0;
- while (i < baseType.Length && baseType[i] >= '0' && baseType[i] <= '9')
- {
- numTypeArgs = numTypeArgs * 10 + (baseType[i] - '0');
- i++;
- }
-
- GetTypeArgumentsOutput(typeRef.TypeArguments, currentTypeArgStart, numTypeArgs, sb);
- currentTypeArgStart += numTypeArgs;
-
- // Arity can be in the middle of a nested type name, so we might have a . or + after it.
- // Skip it if so.
- if (i < baseType.Length && (baseType[i] == '+' || baseType[i] == '.'))
- {
- sb.Append('.');
- i++;
- }
-
- lastIndex = i;
- break;
+ numTypeArgs = numTypeArgs * 10 + (baseType[i] - '0');
+ i++;
+ }
+
+ GetTypeArgumentsOutput(typeRef.TypeArguments, currentTypeArgStart, numTypeArgs, sb);
+ currentTypeArgStart += numTypeArgs;
+
+ // Arity can be in the middle of a nested type name, so we might have a . or + after it.
+ // Skip it if so.
+ if (i < baseType.Length && (baseType[i] == '+' || baseType[i] == '.'))
+ {
+ sb.Append('.');
+ i++;
}
- }
- if (lastIndex < baseType.Length)
- sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex)));
+ lastIndex = i;
+ break;
+ }
+ }
- return sb.ToString();
+ if (lastIndex < baseType.Length)
+ sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex)));
+
+ return sb.ToString();
}
private string GetTypeArgumentsOutput(CodeTypeReferenceCollection typeArguments)
}
}
- var sb = new StringBuilder(baseType.Length + 10);
- if ((typeRef.Options & CodeTypeReferenceOptions.GlobalReference) != 0)
- {
- sb.Append("Global.");
- }
+ var sb = new StringBuilder(baseType.Length + 10);
+ if ((typeRef.Options & CodeTypeReferenceOptions.GlobalReference) != 0)
+ {
+ sb.Append("Global.");
+ }
- int lastIndex = 0;
- int currentTypeArgStart = 0;
- for (int i = 0; i < baseType.Length; i++)
+ int lastIndex = 0;
+ int currentTypeArgStart = 0;
+ for (int i = 0; i < baseType.Length; i++)
+ {
+ switch (baseType[i])
{
- switch (baseType[i])
- {
- case '+':
- case '.':
- sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
- sb.Append('.');
- i++;
- lastIndex = i;
- break;
+ case '+':
+ case '.':
+ sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
+ sb.Append('.');
+ i++;
+ lastIndex = i;
+ break;
- case '`':
- sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
- i++; // skip the '
- int numTypeArgs = 0;
- while (i < baseType.Length && baseType[i] >= '0' && baseType[i] <= '9')
- {
- numTypeArgs = numTypeArgs * 10 + (baseType[i] - '0');
- i++;
- }
+ case '`':
+ sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
+ i++; // skip the '
+ int numTypeArgs = 0;
+ while (i < baseType.Length && baseType[i] >= '0' && baseType[i] <= '9')
+ {
+ numTypeArgs = numTypeArgs * 10 + (baseType[i] - '0');
+ i++;
+ }
- GetTypeArgumentsOutput(typeRef.TypeArguments, currentTypeArgStart, numTypeArgs, sb);
- currentTypeArgStart += numTypeArgs;
+ GetTypeArgumentsOutput(typeRef.TypeArguments, currentTypeArgStart, numTypeArgs, sb);
+ currentTypeArgStart += numTypeArgs;
- // Arity can be in the middle of a nested type name, so we might have a . or + after it.
- // Skip it if so.
- if (i < baseType.Length && (baseType[i] == '+' || baseType[i] == '.'))
- {
- sb.Append('.');
- i++;
- }
+ // Arity can be in the middle of a nested type name, so we might have a . or + after it.
+ // Skip it if so.
+ if (i < baseType.Length && (baseType[i] == '+' || baseType[i] == '.'))
+ {
+ sb.Append('.');
+ i++;
+ }
- lastIndex = i;
- break;
- }
+ lastIndex = i;
+ break;
}
+ }
- if (lastIndex < baseType.Length)
- {
- sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex)));
- }
+ if (lastIndex < baseType.Length)
+ {
+ sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex)));
+ }
- return sb.ToString();
+ return sb.ToString();
}
private string GetTypeOutputWithoutArrayPostFix(CodeTypeReference typeRef)
private readonly IEnumerator<TSource> _sharedReader;
private readonly SharedLong _sharedIndex; //initial value -1
- private volatile KeyValuePair<long, TSource>[]? _fillBuffer; // intermediate buffer to reduce locking
- private volatile int _fillBufferSize; // actual number of elements in _FillBuffer. Will start
- // at _FillBuffer.Length, and might be reduced during the last refill
- private volatile int _fillBufferCurrentPosition; //shared value to be accessed by Interlock.Increment only
- private volatile int _activeCopiers; //number of active copiers
+ private volatile KeyValuePair<long, TSource>[]? _fillBuffer; // intermediate buffer to reduce locking
+ private volatile int _fillBufferSize; // actual number of elements in _FillBuffer. Will start
+ // at _FillBuffer.Length, and might be reduced during the last refill
+ private volatile int _fillBufferCurrentPosition; //shared value to be accessed by Interlock.Increment only
+ private volatile int _activeCopiers; //number of active copiers
//fields shared by all partitions that this Enumerable owns, their allocation is deferred
private readonly SharedBool _hasNoElementsLeft; // no elements left at all.
{
return ref this.Root.ItemRef(index);
}
- #endif
+#endif
#endregion
}
[Obsolete("Please use NameObjectCollectionBase(IEqualityComparer) instead.")]
- protected NameObjectCollectionBase(IHashCodeProvider hashProvider, IComparer comparer) {
+ protected NameObjectCollectionBase(IHashCodeProvider hashProvider, IComparer comparer)
+ {
_keyComparer = new CompatibleComparer(hashProvider, comparer);
Reset();
}
[Obsolete("Please use NameObjectCollectionBase(Int32, IEqualityComparer) instead.")]
- protected NameObjectCollectionBase(int capacity, IHashCodeProvider hashProvider, IComparer comparer) {
+ protected NameObjectCollectionBase(int capacity, IHashCodeProvider hashProvider, IComparer comparer)
+ {
_keyComparer = new CompatibleComparer(hashProvider, comparer);
Reset(capacity);
}
[Obsolete("Please use NameValueCollection(IEqualityComparer) instead.")]
public NameValueCollection(IHashCodeProvider hashProvider, IComparer comparer)
- : base(hashProvider, comparer) {
+ : base(hashProvider, comparer)
+ {
}
/// <devdoc>
[Obsolete("Please use NameValueCollection(Int32, IEqualityComparer) instead.")]
public NameValueCollection(int capacity, IHashCodeProvider hashProvider, IComparer comparer)
- : base(capacity, hashProvider, comparer) {
+ : base(capacity, hashProvider, comparer)
+ {
}
protected NameValueCollection(SerializationInfo info, StreamingContext context) : base(info, context)
#endregion
#region IDeserializationCallback implementation
- void IDeserializationCallback.OnDeserialization(object sender) {
+ void IDeserializationCallback.OnDeserialization(object sender)
+ {
OnDeserialization(sender);
}
}
return result;
- }
+ }
}
internal override bool InOrderTreeWalk(TreeWalkPredicate<T> action)
public void Add(object item)
{
- _collectionOfT.Add((T) item);
+ _collectionOfT.Add((T)item);
}
public void Clear()
// CreationPolicy.Any.Equals(definition.Metadata[CompositionConstants.PartCreationPolicyMetadataName]) ||
// policy.Equals(definition.Metadata[CompositionConstants.PartCreationPolicyMetadataName]);
- return Expression.MakeBinary(ExpressionType.OrElse,
+ return Expression.MakeBinary(ExpressionType.OrElse,
Expression.MakeBinary(ExpressionType.OrElse,
Expression.Not(CreateMetadataContainsKeyExpression(parameter, CompositionConstants.PartCreationPolicyMetadataName)),
CreateMetadataValueEqualsExpression(parameter, CreationPolicy.Any, CompositionConstants.PartCreationPolicyMetadataName)),
// definition.Metadata.ContainsKey(CompositionServices.ExportTypeIdentity) &&
// requiredTypeIdentity.Equals(definition.Metadata[CompositionConstants.ExportTypeIdentityMetadataName]);
- return Expression.MakeBinary(ExpressionType.AndAlso,
+ return Expression.MakeBinary(ExpressionType.AndAlso,
CreateMetadataContainsKeyExpression(parameter, CompositionConstants.ExportTypeIdentityMetadataName),
CreateMetadataValueEqualsExpression(parameter, requiredTypeIdentity, CompositionConstants.ExportTypeIdentityMetadataName));
}
}
// definition.Metadata.ContainsKey(constantKey)
- return Expression.Call(
+ return Expression.Call(
Expression.Property(parameter, ConstraintServices._exportDefinitionMetadataProperty),
ConstraintServices._metadataContainsKeyMethod,
Expression.Constant(constantKey));
}
// constantValue.Equals(definition.Metadata[CompositionServices.PartCreationPolicyMetadataName])
- return Expression.Call(
+ return Expression.Call(
Expression.Constant(constantValue),
ConstraintServices._metadataEqualsMethod,
Expression.Call(
/// </para>
/// </remarks>
public AggregateExportProvider(IEnumerable<ExportProvider> providers)
- : this((providers!= null) ? providers.AsArray() : null)
+ : this((providers != null) ? providers.AsArray() : null)
{
}
private readonly ICompositionElement _definitionOrigin = null;
private readonly ReflectionContext _reflectionContext = null;
- public ApplicationCatalog() {}
+ public ApplicationCatalog() { }
public ApplicationCatalog(ICompositionElement definitionOrigin)
{
: new DirectoryCatalog(location, pattern);
}
-// Note:
-// Creating a catalog does not cause change notifications to propagate, For some reason the DeploymentCatalog did, but that is a bug.
-// InnerCatalog is delay evaluated, from data supplied at construction time and so does not propagate change notifications
+ // Note:
+ // Creating a catalog does not cause change notifications to propagate, For some reason the DeploymentCatalog did, but that is a bug.
+ // InnerCatalog is delay evaluated, from data supplied at construction time and so does not propagate change notifications
private AggregateCatalog InnerCatalog
{
get
string relativeSearchPath = AppDomain.CurrentDomain.RelativeSearchPath;
if (!string.IsNullOrEmpty(relativeSearchPath))
{
- string[] probingPaths = relativeSearchPath.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);
+ string[] probingPaths = relativeSearchPath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var probingPath in probingPaths)
{
var path = Path.Combine(location, probingPath);
}
public ComposablePartExportProvider(bool isThreadSafe)
- :this(isThreadSafe ? CompositionOptions.IsThreadSafe : CompositionOptions.Default)
+ : this(isThreadSafe ? CompositionOptions.IsThreadSafe : CompositionOptions.Default)
{
}
}
}
-/// <summary>
+ /// <summary>
/// Returns all exports that match the conditions of the specified import.
/// </summary>
/// <param name="definition">The <see cref="ImportDefinition"/> that defines the conditions of the
/// <exception cref="ArgumentException">
/// <paramref name="providers"/> contains an element that is <see langword="null"/>.
/// </exception>
- public CompositionContainer(ComposablePartCatalog catalog, params ExportProvider[] providers):
+ public CompositionContainer(ComposablePartCatalog catalog, params ExportProvider[] providers) :
this(catalog, false, providers)
{
}
_disposableRootProvider = _rootProvider as IDisposable;
}
-//Insert Composition Service
+ //Insert Composition Service
if (compositionOptions.HasFlag(CompositionOptions.ExportCompositionService))
{
this.ComposeExportedValue<ICompositionService>(new CompositionServiceShim(this));
[Flags]
public enum CompositionOptions
{
- Default = 0x0000,
- DisableSilentRejection = 0x0001,
- IsThreadSafe = 0x0002,
+ Default = 0x0000,
+ DisableSilentRejection = 0x0001,
+ IsThreadSafe = 0x0002,
ExportCompositionService = 0x0004
}
}
InitializeCompositionScopeDefinition(catalog, children, null);
}
-/// <summary>
+ /// <summary>
/// Initializes a new instance of the <see cref="CompositionScopeDefinition"/> class.
/// </summary>
/// <param name="catalog">The catalog.</param>
InitializeCompositionScopeDefinition(catalog, children, publicSurface);
}
-/// <summary>
+ /// <summary>
/// Initializes a new instance of the <see cref="CompositionScopeDefinition"/> class.
/// </summary>
/// <param name="catalog">The catalog.</param>
ThrowIfDisposed();
if (_publicSurface == null)
{
- return this.SelectMany( (p) => p.ExportDefinitions );
+ return this.SelectMany((p) => p.ExportDefinitions);
}
return _publicSurface;
return _compositionScopeDefinition.Children.ToReadOnlyCollection();
}
}
-
-}
+ }
}
}
}
-internal static string GetTypeIdentityFromExport(this MemberInfo member, Type typeIdentityType)
+ internal static string GetTypeIdentityFromExport(this MemberInfo member, Type typeIdentityType)
{
if (typeIdentityType != null)
{
return string.IsNullOrEmpty(export.ContractName);
}
-internal static Type GetContractTypeFromImport(this IAttributedImport import, ImportType importType)
+ internal static Type GetContractTypeFromImport(this IAttributedImport import, ImportType importType)
{
if (import.ContractType != null)
{
bool hasConstraints = false;
object[] genericParameterConstraints = new object[genericArguments.Length];
GenericParameterAttributes[] genericParameterAttributes = new GenericParameterAttributes[genericArguments.Length];
- for (int i=0; i< genericArguments.Length; i++)
+ for (int i = 0; i < genericArguments.Length; i++)
{
Type genericArgument = genericArguments[i];
}
}
-/// <summary>
+ /// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
/// </summary>
public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
-/// <summary>
+ /// <summary>
/// Notify when the contents of the Catalog is changing.
/// </summary>
public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
-/// <summary>
+ /// <summary>
/// Raises the <see cref="Changed"/> event.
/// </summary>
/// <param name="e">The <see cref="System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs"/> instance containing the event data.</param>
var reply = _metadata;
if (reply == null)
{
- reply = new Dictionary<string, object> (_sourceDefinition.Metadata);
+ reply = new Dictionary<string, object>(_sourceDefinition.Metadata);
reply.Remove(CompositionConstants.ImportSourceMetadataName);
_metadata = reply;
}
return false;
}
-/// <summary>
+ /// <summary>
/// Determines whether the part contains a metadata entry with the specified key.
/// </summary>
/// <param name="part">The part.</param>
/// Specifies that an attribute can be used to provide metadata for a type, property, field,
/// or method marked with the <see cref="ExportAttribute"/>.
/// </summary>
- [AttributeUsage(AttributeTargets.Class,
- AllowMultiple=false, Inherited=true)]
+ [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class MetadataAttributeAttribute : Attribute
{
/// <summary>
{
public delegate object MetadataViewFactory(IDictionary<string, object> metadata);
- public const string MetadataViewType = "MetadataViewType";
- public const string MetadataItemKey = "MetadataItemKey";
- public const string MetadataItemTargetType = "MetadataItemTargetType";
- public const string MetadataItemSourceType = "MetadataItemSourceType";
- public const string MetadataItemValue = "MetadataItemValue";
- public const string MetadataViewFactoryName= "Create";
+ public const string MetadataViewType = "MetadataViewType";
+ public const string MetadataItemKey = "MetadataItemKey";
+ public const string MetadataItemTargetType = "MetadataItemTargetType";
+ public const string MetadataItemSourceType = "MetadataItemSourceType";
+ public const string MetadataItemValue = "MetadataItemValue";
+ public const string MetadataViewFactoryName = "Create";
private static readonly Lock _lock = new Lock();
private static readonly Dictionary<Type, MetadataViewFactory> _metadataViewFactories = new Dictionary<Type, MetadataViewFactory>();
private static readonly AssemblyName ProxyAssemblyName = new AssemblyName(string.Format(CultureInfo.InvariantCulture, "MetadataViewProxies_{0}", Guid.NewGuid()));
- private static ModuleBuilder transparentProxyModuleBuilder;
+ private static ModuleBuilder transparentProxyModuleBuilder;
private static readonly Type[] CtorArgumentTypes = new Type[] { typeof(IDictionary<string, object>) };
private static readonly MethodInfo _mdvDictionaryTryGet = CtorArgumentTypes[0].GetMethod("TryGetValue");
}
// If the Metadata dictionary is cast compatible with the passed in type
- if (ExportServices.IsDefaultMetadataViewType(metadataViewType)
- || metadataViewType.IsInterface
- || ExportServices.IsDictionaryConstructorViewType(metadataViewType))
+ if (ExportServices.IsDefaultMetadataViewType(metadataViewType) ||
+ metadataViewType.IsInterface ||
+ ExportServices.IsDictionaryConstructorViewType(metadataViewType))
{
return true;
}
/// <see cref="ComposablePartDefinition"/>.
/// </value>
/// <remarks>
- /// <note type="inheritinfo">
+ /// <note type="inheritinfo">
/// Overrides of this property should never return <see langword="null"/>.
/// If the <see cref="ComposablePart"/> objects created by the
/// <see cref="ComposablePartDefinition"/> do not provide exported values, return
// This array should contains a lit of all argument types, and the last one is the return type (could be void)
Type[] parameterTypes = new Type[parameters.Length + 1];
parameterTypes[parameters.Length] = _method.ReturnType;
- for (int i = 0; i < parameters.Length; i++ )
+ for (int i = 0; i < parameters.Length; i++)
{
parameterTypes[i] = parameters[i].ParameterType;
}
}
}
-internal static bool IsImportDependentOnPart(this ImportDefinition import, ComposablePartDefinition part, ExportDefinition export, bool expandGenerics)
+ internal static bool IsImportDependentOnPart(this ImportDefinition import, ComposablePartDefinition part, ExportDefinition export, bool expandGenerics)
{
import = import.GetProductImportDefinition();
if (expandGenerics)
private static readonly MethodInfo _createStronglyTypedExportFactoryOfT = typeof(ExportFactoryCreator).GetMethod("CreateStronglyTypedExportFactoryOfT", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
private static readonly MethodInfo _createStronglyTypedExportFactoryOfTM = typeof(ExportFactoryCreator).GetMethod("CreateStronglyTypedExportFactoryOfTM", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
- private readonly Type _exportFactoryType;
+ private readonly Type _exportFactoryType;
public ExportFactoryCreator(Type exportFactoryType)
{
MethodInfo genericMethod = null;
if (metadataViewType == null)
{
- genericMethod = _createStronglyTypedExportFactoryOfT.MakeGenericMethod(exportType);
+ genericMethod = _createStronglyTypedExportFactoryOfT.MakeGenericMethod(exportType);
}
else
{
var metadataView = AttributedModelServices.GetMetadataView<M>(export.Metadata);
object[] args = { exportLifetimeContextCreator, metadataView };
- var instance = Activator.CreateInstance(constructed, args);
+ var instance = Activator.CreateInstance(constructed, args);
return instance;
}
{
RequiresRunning();
Requires.NotNull(definition, nameof(definition));
- Requires.NotNull(exports, nameof(exports));;
+ Requires.NotNull(exports, nameof(exports));
ImportingItem item = GetImportingItemFromDefinition(definition);
if (item == null)
}
}
-internal class ReflectionPartCreationInfo : IReflectionPartCreationInfo
+ internal class ReflectionPartCreationInfo : IReflectionPartCreationInfo
{
private readonly Lazy<Type> _partType;
private readonly Lazy<IEnumerable<ImportDefinition>> _imports;
public ReflectionParameter(ParameterInfo parameter)
{
- if (parameter == null)
- {
+ if (parameter == null)
+ {
throw new ArgumentNullException(nameof(parameter));
}
/// </summary>
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
- return s_values ?? (s_values = new StandardValuesCollection(new object[] {true, false}));
+ return s_values ?? (s_values = new StandardValuesCollection(new object[] { true, false }));
}
/// <summary>
public abstract class DesignerOptionService : IDesignerOptionService
{
private DesignerOptionCollection _options;
- private static readonly char[] s_slash = {'\\'};
+ private static readonly char[] s_slash = { '\\' };
/// <summary>
/// Returns the options collection for this service. There is
}
}
- protected string[] TabClassNames => (string[]) _tabClassNames?.Clone();
+ protected string[] TabClassNames => (string[])_tabClassNames?.Clone();
/// <summary>
/// Gets the scopes of tabs for this System.ComponentModel.Design.PropertyTabAttribute, from System.ComponentModel.Design.PropertyTabScope.
private static LicenseProvider GetCachedProviderInstance(Type providerType)
{
Debug.Assert(providerType != null, "Type cannot ever be null");
- return (LicenseProvider) s_providerInstances?[providerType];
+ return (LicenseProvider)s_providerInstances?[providerType];
}
/// <summary>
lock (this)
{
_site?.Container?.Remove(this);
- ((EventHandler) _events?[s_eventDisposed])?.Invoke(this, EventArgs.Empty);
+ ((EventHandler)_events?[s_eventDisposed])?.Invoke(this, EventArgs.Empty);
}
}
}
/// Gets the name of the category that the member belongs to, as specified
/// in the <see cref='System.ComponentModel.CategoryAttribute'/>.
/// </summary>
- public virtual string Category => _category ?? (_category = ((CategoryAttribute) Attributes[typeof(CategoryAttribute)]).Category);
+ public virtual string Category => _category ?? (_category = ((CategoryAttribute)Attributes[typeof(CategoryAttribute)]).Category);
/// <summary>
/// Gets the description of the member as specified in the <see cref='System.ComponentModel.DescriptionAttribute'/>.
/// </summary>
public virtual string Description => _description ??
- (_description = ((DescriptionAttribute) Attributes[typeof(DescriptionAttribute)]).Description);
+ (_description = ((DescriptionAttribute)Attributes[typeof(DescriptionAttribute)]).Description);
/// <summary>
/// Gets a value indicating whether the member is browsable as specified in the
protected static ISite GetSite(object component) => (component as IComponent)?.Site;
[Obsolete("This method has been deprecated. Use GetInvocationTarget instead. https://go.microsoft.com/fwlink/?linkid=14202")]
- protected static object GetInvokee(Type componentClass, object component) {
+ protected static object GetInvokee(Type componentClass, object component)
+ {
if (componentClass == null)
{
}
else if (destinationType == typeof(InstanceDescriptor))
{
- ConstructorInfo ci = NullableType.GetConstructor(new Type[] {UnderlyingType});
+ ConstructorInfo ci = NullableType.GetConstructor(new Type[] { UnderlyingType });
Debug.Assert(ci != null, "Couldn't find constructor");
- return new InstanceDescriptor(ci, new object[] {value}, true);
+ return new InstanceDescriptor(ci, new object[] { value }, true);
}
else if (value == null)
{
{
if (component != null)
{
- ((EventHandler) _valueChangedHandlers?[component])?.Invoke(component, e);
+ ((EventHandler)_valueChangedHandlers?[component])?.Invoke(component, e);
}
}
if (value != null)
{
// Try the reference service first.
- IReferenceService refSvc = (IReferenceService) context?.GetService(typeof(IReferenceService));
+ IReferenceService refSvc = (IReferenceService)context?.GetService(typeof(IReferenceService));
if (refSvc != null)
{
string name = refSvc.GetName(value);
if (changeService != null)
{
- try {
+ try
+ {
changeService.OnComponentChanging(component, this);
}
- catch (CheckoutException coEx) {
- if (coEx == CheckoutException.Canceled) {
+ catch (CheckoutException coEx)
+ {
+ if (coEx == CheckoutException.Canceled)
+ {
return;
}
throw;
if (changeService != null)
{
- try {
+ try
+ {
changeService.OnComponentChanging(component, this);
}
- catch (CheckoutException coEx) {
- if (coEx == CheckoutException.Canceled) {
+ catch (CheckoutException coEx)
+ {
+ if (coEx == CheckoutException.Canceled)
+ {
return;
}
throw;
{
// Check our association table for a match.
Hashtable assocTable = AssociationTable;
- IList associations = (IList) assocTable?[primary];
+ IList associations = (IList)assocTable?[primary];
if (associations != null)
{
lock (associations)
}
Hashtable assocTable = AssociationTable;
- IList associations = (IList) assocTable?[primary];
+ IList associations = (IList)assocTable?[primary];
if (associations != null)
{
lock (associations)
/// A <see cref="string"/> containing the contract name to export the type or member
/// marked with this attribute, under. The default value is an empty string ("").
/// </value>
- public string ContractName { get; }
+ public string ContractName { get; }
/// <summary>
/// Get the contract type that is exported by the member that this attribute is attached to.
public int GetHashCode(ParameterInfo obj)
{
- return HashHelpers.Combine(obj.Position.GetHashCode(), obj.Member.GetHashCode());
+ return HashHelpers.Combine(obj.Position.GetHashCode(), obj.Member.GetHashCode());
}
public bool Equals(ParameterInfo x, ParameterInfo y)
protected const string ConfigSectionsTag = "configSections";
protected const string SectionTag = "section";
- protected const string SectionNameAttribute = "name";
- protected const string SectionTypeAttribute = "type";
- protected const string SectionAllowLocationAttribute = "allowLocation";
- protected const string SectionAllowDefinitionAttribute = "allowDefinition";
- protected const string AllowDefinitionEverywhere = "Everywhere";
- protected const string AllowDefinitionMachineOnly = "MachineOnly";
- protected const string AllowDefinitionMachineToApplication = "MachineToApplication";
- protected const string AllowDefinitionMachineToWebRoot = "MachineToWebRoot";
- protected const string SectionAllowExeDefinitionAttribute = "allowExeDefinition";
- protected const string AllowExeDefinitionMachineToRoaming = "MachineToRoamingUser";
- protected const string AllowExeDefinitionMachineToLocal = "MachineToLocalUser";
- protected const string SectionRestartonExternalChangesAttribute = "restartOnExternalChanges";
- protected const string SectionRequirePermissionAttribute = "requirePermission";
- internal const string SectionOverrideModeDefaultAttribute = "overrideModeDefault";
+ protected const string SectionNameAttribute = "name";
+ protected const string SectionTypeAttribute = "type";
+ protected const string SectionAllowLocationAttribute = "allowLocation";
+ protected const string SectionAllowDefinitionAttribute = "allowDefinition";
+ protected const string AllowDefinitionEverywhere = "Everywhere";
+ protected const string AllowDefinitionMachineOnly = "MachineOnly";
+ protected const string AllowDefinitionMachineToApplication = "MachineToApplication";
+ protected const string AllowDefinitionMachineToWebRoot = "MachineToWebRoot";
+ protected const string SectionAllowExeDefinitionAttribute = "allowExeDefinition";
+ protected const string AllowExeDefinitionMachineToRoaming = "MachineToRoamingUser";
+ protected const string AllowExeDefinitionMachineToLocal = "MachineToLocalUser";
+ protected const string SectionRestartonExternalChangesAttribute = "restartOnExternalChanges";
+ protected const string SectionRequirePermissionAttribute = "requirePermission";
+ internal const string SectionOverrideModeDefaultAttribute = "overrideModeDefault";
internal const string OverrideModeInherit = "Inherit";
internal const string OverrideModeAllow = "Allow";
internal const string OverrideModeDeny = "Deny";
protected const string SectionGroupTag = "sectionGroup";
- protected const string SectionGroupNameAttribute = "name";
- protected const string SectionGroupTypeAttribute = "type";
+ protected const string SectionGroupNameAttribute = "name";
+ protected const string SectionGroupTypeAttribute = "type";
protected const string RemoveTag = "remove";
protected const string ClearTag = "clear";
protected const string LocationTag = "location";
- protected const string LocationPathAttribute = "path";
- internal const string LocationAllowOverrideAttribute = "allowOverride";
- internal const string LocationOverrideModeAttribute = "overrideMode";
- protected const string LocationInheritInChildApplicationsAttribute = "inheritInChildApplications";
+ protected const string LocationPathAttribute = "path";
+ internal const string LocationAllowOverrideAttribute = "allowOverride";
+ internal const string LocationOverrideModeAttribute = "overrideMode";
+ protected const string LocationInheritInChildApplicationsAttribute = "inheritInChildApplications";
protected const string ConfigSourceAttribute = "configSource";
internal const string ProtectionProviderAttibute = "configProtectionProvider";
}
else
{
- ApplicationUri = Uri.EscapeDataString(configBasePath);
+ ApplicationUri = Uri.EscapeDataString(configBasePath);
}
}
childRecord = _isDesignTime
? MgmtConfigurationRecord.Create(this, currentRecord, currentConfigPath, null)
- : (BaseConfigurationRecord) RuntimeConfigurationRecord.Create(this, currentRecord, currentConfigPath);
+ : (BaseConfigurationRecord)RuntimeConfigurationRecord.Create(this, currentRecord, currentConfigPath);
currentRecord.HlAddChild(configName, childRecord);
private static readonly ConfigurationPropertyCollection s_properties = new ConfigurationPropertyCollection { s_propProviders, s_propDefaultProvider };
- public ProtectedConfigurationSection(){}
+ public ProtectedConfigurationSection() { }
protected internal override ConfigurationPropertyCollection Properties => s_properties;
stream: outputStream,
encoding: OutputEncoding.RemovePreamble(), // This ensures no prefix is written to the stream.
bufferSize: WriteBufferSize,
- leaveOpen: true) { AutoFlush = true });
+ leaveOpen: true)
+ {
+ AutoFlush = true
+ });
}
private static StrongBox<bool> _isStdInRedirected;
}
// Try to give a better error message here
- Interop.Kernel32.COORD bounds = Interop.Kernel32.GetLargestConsoleWindowSize(OutputHandle);
+ Interop.Kernel32.COORD bounds = Interop.Kernel32.GetLargestConsoleWindowSize(OutputHandle);
if (width > bounds.X)
throw new ArgumentOutOfRangeException(nameof(width), width, SR.Format(SR.ArgumentOutOfRange_ConsoleWindowSize_Size, bounds.X));
if (height > bounds.Y)
internal string _name = string.Empty;
internal PropertyCollection _extendedProperties = null;
- internal Constraint() {}
+ internal Constraint() { }
/// <summary>
/// The name of this constraint within the <see cref='System.Data.ConstraintCollection'/>.
}
DataRow dataRow = LoadRow(values, loadOption, indextoUse); // if indextoUse == null, it means we dont have PK,
- // so LoadRow will take care of just adding the row to end
+ // so LoadRow will take care of just adding the row to end
return dataRow;
}
}
/// <summary>This method exists for LinqDataView to keep a level of abstraction away from the RBTree</summary>
- internal Range FindRecords<TKey, TRow>(Index.ComparisonBySelector<TKey, TRow> comparison, TKey key) where TRow:DataRow
+ internal Range FindRecords<TKey, TRow>(Index.ComparisonBySelector<TKey, TRow> comparison, TKey key) where TRow : DataRow
{
return _index.FindRecords(comparison, key);
}
}
else // find for expression based sort
{
- if (sortExpressionBuilder.Count !=1)
+ if (sortExpressionBuilder.Count != 1)
throw DataSetUtil.InvalidOperation(SR.Format(SR.LDV_InvalidNumOfKeys, sortExpressionBuilder.Count));
Index.ComparisonBySelector<object, DataRow> compareDelg =
internal override void SetIndex(string newSort, DataViewRowState newRowStates, IFilter newRowFilter)
{
// Throw only if expressions (filter or sort) are used and rowstate is not current rows
- if ( (base.SortComparison != null || base.RowPredicate != null)
- && newRowStates != DataViewRowState.CurrentRows)
+ if ((base.SortComparison != null || base.RowPredicate != null) && newRowStates != DataViewRowState.CurrentRows)
{
throw DataSetUtil.Argument(SR.LDVRowStateError);
}
/// <summary>
/// Converts a <see cref='SqlBinary'/> to a binary object.
/// </summary>
- public static explicit operator byte[] (SqlBinary x) => x.Value;
+ public static explicit operator byte[](SqlBinary x) => x.Value;
/// <summary>
/// Returns a string describing a <see cref='SqlBinary'/> object.
/// <summary>
/// Converts a <see cref='SqlBoolean'/> to a boolean.
/// </summary>
- public static explicit operator bool (SqlBoolean x)
+ public static explicit operator bool(SqlBoolean x)
{
return x.Value;
}
}
// Explicit conversion from SqlByte to byte. Throw exception if x is Null.
- public static explicit operator byte (SqlByte x)
+ public static explicit operator byte(SqlByte x)
{
return x.Value;
}
}
// Explicit conversion from SqlDecimal to Decimal. Throw exception if x is Null.
- public static explicit operator decimal (SqlDecimal x)
+ public static explicit operator decimal(SqlDecimal x)
{
return x.Value;
}
}
// Explicit conversion from SqlDouble to double. Throw exception if x is Null.
- public static explicit operator double (SqlDouble x)
+ public static explicit operator double(SqlDouble x)
{
return x.Value;
}
}
// Explicit conversion from SqlInt16 to short. Throw exception if x is Null.
- public static explicit operator short (SqlInt16 x)
+ public static explicit operator short(SqlInt16 x)
{
return x.Value;
}
}
// Explicit conversion from SqlInt32 to int. Throw exception if x is Null.
- public static explicit operator int (SqlInt32 x)
+ public static explicit operator int(SqlInt32 x)
{
return x.Value;
}
}
// Explicit conversion from SqlInt64 to long. Throw exception if x is Null.
- public static explicit operator long (SqlInt64 x)
+ public static explicit operator long(SqlInt64 x)
{
return x.Value;
}
}
// Explicit conversion from SqlMoney to Decimal. Throw exception if x is Null.
- public static explicit operator decimal (SqlMoney x)
+ public static explicit operator decimal(SqlMoney x)
{
return x.Value;
}
}
// Explicit conversion from SqlSingle to float. Throw exception if x is Null.
- public static explicit operator float (SqlSingle x)
+ public static explicit operator float(SqlSingle x)
{
return x.Value;
}
}
// Explicit conversion from SqlString to String. Throw exception if x is Null.
- public static explicit operator string (SqlString x)
+ public static explicit operator string(SqlString x)
{
return x.Value;
}
return x;
}
- internal delegate int ComparisonBySelector<TKey, TRow>(TKey key, TRow row) where TRow:DataRow;
+ internal delegate int ComparisonBySelector<TKey, TRow>(TKey key, TRow row) where TRow : DataRow;
/// <summary>This method exists for LinqDataView to keep a level of abstraction away from the RBTree</summary>
- internal Range FindRecords<TKey, TRow>(ComparisonBySelector<TKey, TRow> comparison, TKey key) where TRow:DataRow
+ internal Range FindRecords<TKey, TRow>(ComparisonBySelector<TKey, TRow> comparison, TKey key) where TRow : DataRow
{
int x = _records.root;
while (IndexTree.NIL != x)
// Column set for SQLPrimaryKeys
internal enum SQL_PRIMARYKEYS : short
{
-/*
- CATALOGNAME = 1, // TABLE_CAT
- SCHEMANAME = 2, // TABLE_SCHEM
- TABLENAME = 3, // TABLE_NAME
-*/
+ // CATALOGNAME = 1, // TABLE_CAT
+ // SCHEMANAME = 2, // TABLE_SCHEM
+ // TABLENAME = 3, // TABLE_NAME
COLUMNNAME = 4, // COLUMN_NAME
-/*
- KEY_SEQ = 5, // KEY_SEQ
- PKNAME = 6, // PK_NAME
-*/
+ // KEY_SEQ = 5, // KEY_SEQ
+ // PKNAME = 6, // PK_NAME
}
// Column set for SQLStatistics
internal enum SQL_STATISTICS : short
{
-/*
- CATALOGNAME = 1, // TABLE_CAT
- SCHEMANAME = 2, // TABLE_SCHEM
- TABLENAME = 3, // TABLE_NAME
- NONUNIQUE = 4, // NON_UNIQUE
- INDEXQUALIFIER = 5, // INDEX_QUALIFIER
-*/
+ // CATALOGNAME = 1, // TABLE_CAT
+ // SCHEMANAME = 2, // TABLE_SCHEM
+ // TABLENAME = 3, // TABLE_NAME
+ // NONUNIQUE = 4, // NON_UNIQUE
+ // INDEXQUALIFIER = 5, // INDEX_QUALIFIER
INDEXNAME = 6, // INDEX_NAME
-/*
- TYPE = 7, // TYPE
-*/
- ORDINAL_POSITION = 8, // ORDINAL_POSITION
- COLUMN_NAME = 9, // COLUMN_NAME
-/*
- ASC_OR_DESC = 10, // ASC_OR_DESC
- CARDINALITY = 11, // CARDINALITY
- PAGES = 12, // PAGES
- FILTER_CONDITION = 13, // FILTER_CONDITION
-*/
+ // TYPE = 7, // TYPE
+ ORDINAL_POSITION = 8, // ORDINAL_POSITION
+ COLUMN_NAME = 9, // COLUMN_NAME
+ // ASC_OR_DESC = 10, // ASC_OR_DESC
+ // CARDINALITY = 11, // CARDINALITY
+ // PAGES = 12, // PAGES
+ // FILTER_CONDITION = 13, // FILTER_CONDITION
}
// Column set for SQLSpecialColumns
internal enum SQL_SPECIALCOLUMNSET : short
{
-/*
- SCOPE = 1, // SCOPE
-*/
+ // SCOPE = 1, // SCOPE
COLUMN_NAME = 2, // COLUMN_NAME
-/*
- DATA_TYPE = 3, // DATA_TYPE
- TYPE_NAME = 4, // TYPE_NAME
- COLUMN_SIZE = 5, // COLUMN_SIZE
- BUFFER_LENGTH = 6, // BUFFER_LENGTH
- DECIMAL_DIGITS = 7, // DECIMAL_DIGITS
- PSEUDO_COLUMN = 8, // PSEUDO_COLUMN
-*/
+ // DATA_TYPE = 3, // DATA_TYPE
+ // TYPE_NAME = 4, // TYPE_NAME
+ // COLUMN_SIZE = 5, // COLUMN_SIZE
+ // BUFFER_LENGTH = 6, // BUFFER_LENGTH
+ // DECIMAL_DIGITS = 7, // DECIMAL_DIGITS
+ // PSEUDO_COLUMN = 8, // PSEUDO_COLUMN
}
internal const short SQL_DIAG_SQLSTATE = 4;
private object _coercedValue;
- private OdbcParameter(OdbcParameter source) : this() { // V1.2.3300, Clone
+ private OdbcParameter(OdbcParameter source) : this() // V1.2.3300, Clone
+ {
ADP.CheckArgumentNull(source, nameof(source));
source.CloneHelper(this);
return new SQLLEN(value);
}
- public static unsafe implicit operator int (SQLLEN value)
- { //
+ public static unsafe implicit operator int(SQLLEN value)
+ {
#if WIN32
return (int)value._value.ToInt32();
#else
#endif
}
- public static unsafe explicit operator long (SQLLEN value)
+ public static unsafe explicit operator long(SQLLEN value)
{
return value._value.ToInt64();
}
}
}
- public override bool IsFixedSize {
- get {
+ public override bool IsFixedSize
+ {
+ get
+ {
return ((System.Collections.IList)InnerList).IsFixedSize;
}
}
- public override bool IsReadOnly {
- get {
+ public override bool IsReadOnly
+ {
+ get
+ {
return ((System.Collections.IList)InnerList).IsReadOnly;
}
}
- public override bool IsSynchronized {
- get {
+ public override bool IsSynchronized
+ {
+ get
+ {
return ((System.Collections.ICollection)InnerList).IsSynchronized;
}
}
internal static ArgumentOutOfRangeException InvalidCommandType(CommandType value)
{
#if DEBUG
- switch (value) {
- case CommandType.Text:
- case CommandType.StoredProcedure:
- case CommandType.TableDirect:
- Debug.Assert(false, "valid CommandType " + value.ToString());
- break;
+ switch (value)
+ {
+ case CommandType.Text:
+ case CommandType.StoredProcedure:
+ case CommandType.TableDirect:
+ Debug.Assert(false, "valid CommandType " + value.ToString());
+ break;
}
#endif
return InvalidEnumerationValue(typeof(CommandType), (int)value);
internal static ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value)
{
#if DEBUG
- switch (value) {
- case DataRowVersion.Default:
- case DataRowVersion.Current:
- case DataRowVersion.Original:
- case DataRowVersion.Proposed:
- Debug.Assert(false, "valid DataRowVersion " + value.ToString());
- break;
+ switch (value)
+ {
+ case DataRowVersion.Default:
+ case DataRowVersion.Current:
+ case DataRowVersion.Original:
+ case DataRowVersion.Proposed:
+ Debug.Assert(false, "valid DataRowVersion " + value.ToString());
+ break;
}
#endif
return InvalidEnumerationValue(typeof(DataRowVersion), (int)value);
internal static ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value)
{
#if DEBUG
- switch (value) {
- case IsolationLevel.Unspecified:
- case IsolationLevel.Chaos:
- case IsolationLevel.ReadUncommitted:
- case IsolationLevel.ReadCommitted:
- case IsolationLevel.RepeatableRead:
- case IsolationLevel.Serializable:
- case IsolationLevel.Snapshot:
- Debug.Assert(false, "valid IsolationLevel " + value.ToString());
- break;
+ switch (value)
+ {
+ case IsolationLevel.Unspecified:
+ case IsolationLevel.Chaos:
+ case IsolationLevel.ReadUncommitted:
+ case IsolationLevel.ReadCommitted:
+ case IsolationLevel.RepeatableRead:
+ case IsolationLevel.Serializable:
+ case IsolationLevel.Snapshot:
+ Debug.Assert(false, "valid IsolationLevel " + value.ToString());
+ break;
}
#endif
return InvalidEnumerationValue(typeof(IsolationLevel), (int)value);
internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value)
{
#if DEBUG
- switch (value) {
- case ParameterDirection.Input:
- case ParameterDirection.Output:
- case ParameterDirection.InputOutput:
- case ParameterDirection.ReturnValue:
- Debug.Assert(false, "valid ParameterDirection " + value.ToString());
- break;
+ switch (value)
+ {
+ case ParameterDirection.Input:
+ case ParameterDirection.Output:
+ case ParameterDirection.InputOutput:
+ case ParameterDirection.ReturnValue:
+ Debug.Assert(false, "valid ParameterDirection " + value.ToString());
+ break;
}
#endif
return InvalidEnumerationValue(typeof(ParameterDirection), (int)value);
internal static ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value)
{
#if DEBUG
- switch (value) {
- case UpdateRowSource.None:
- case UpdateRowSource.OutputParameters:
- case UpdateRowSource.FirstReturnedRecord:
- case UpdateRowSource.Both:
- Debug.Assert(false, "valid UpdateRowSource " + value.ToString());
- break;
+ switch (value)
+ {
+ case UpdateRowSource.None:
+ case UpdateRowSource.OutputParameters:
+ case UpdateRowSource.FirstReturnedRecord:
+ case UpdateRowSource.Both:
+ Debug.Assert(false, "valid UpdateRowSource " + value.ToString());
+ break;
}
#endif
return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value);
return (condition == (condition & value.Direction));
}
#if DEBUG
- private static void IsDirectionValid(ParameterDirection value) {
- switch (value) { // @perfnote: Enum.IsDefined
- case ParameterDirection.Input:
- case ParameterDirection.Output:
- case ParameterDirection.InputOutput:
- case ParameterDirection.ReturnValue:
- break;
- default:
- throw ADP.InvalidParameterDirection(value);
+ private static void IsDirectionValid(ParameterDirection value)
+ {
+ switch (value)
+ { // @perfnote: Enum.IsDefined
+ case ParameterDirection.Input:
+ case ParameterDirection.Output:
+ case ParameterDirection.InputOutput:
+ case ParameterDirection.ReturnValue:
+ break;
+ default:
+ throw ADP.InvalidParameterDirection(value);
}
}
#endif
lock (this)
{
- if (_sqlUserInstanceLibraryHandle !=null)
+ if (_sqlUserInstanceLibraryHandle != null)
{
return true;
}
private int _dataCapacity; // the total capacity requested, if the array is rented this may be less than the _data.Length, does not include smux header length
private int _dataOffset; // the start point of the data in the data segment, advanced by Take-ing data
private int _headerLength; // the amount of space at the start of the array reserved for the smux header, this is zeroed in SetHeader
- // _headerOffset is not needed because it is always 0
+ // _headerOffset is not needed because it is always 0
private byte[] _data;
private SNIAsyncCallback _completionCallback;
{
AsyncHelper.ContinueTaskWithState(execNQ, completion,
state: Tuple.Create(this, completion),
- onSuccess: state => {
+ onSuccess: state =>
+ {
var parameters = (Tuple<SqlCommand, TaskCompletionSource<object>>)state;
parameters.Item1.BeginExecuteNonQueryInternalReadStage(parameters.Item2);
}
{
AsyncHelper.ContinueTaskWithState(writeTask, completion,
state: Tuple.Create(this, completion),
- onSuccess: state => {
+ onSuccess: state =>
+ {
var parameters = (Tuple<SqlCommand, TaskCompletionSource<object>>)state;
parameters.Item1.BeginExecuteXmlReaderInternalReadStage(parameters.Item2);
}
{
AsyncHelper.ContinueTaskWithState(writeTask, completion,
state: Tuple.Create(this, completion),
- onSuccess: state => {
+ onSuccess: state =>
+ {
var parameters = (Tuple<SqlCommand, TaskCompletionSource<object>>)state;
parameters.Item1.BeginExecuteReaderInternalReadStage(parameters.Item2);
}
Debug.Assert(!IsPrepared, "Batch RPC should not be prepared!");
Debug.Assert(!IsDirty, "Batch RPC should not be marked as dirty!");
Debug.Assert(_SqlRPCBatchArray != null, "RunExecuteReader rpc array not provided");
- writeTask = _stateObj.Parser.TdsExecuteRPC( _SqlRPCBatchArray, timeout, inSchema, this.Notification, _stateObj, CommandType.StoredProcedure == CommandType, sync: !asyncWrite);
+ writeTask = _stateObj.Parser.TdsExecuteRPC(_SqlRPCBatchArray, timeout, inSchema, this.Notification, _stateObj, CommandType.StoredProcedure == CommandType, sync: !asyncWrite);
}
else if ((System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters)))
{
if (parameter.IsDerivedParameterTypeName)
{
string[] parts = MultipartIdentifier.ParseMultipartIdentifier(parameter.TypeName, "[\"", "]\"", SR.SQL_TDSParserTableName, false);
- if (parts != null && parts.Length==4) // will always return int[4] right justified
+ if (parts != null && parts.Length == 4) // will always return int[4] right justified
{
if (
parts[3] != null && // name must not be null
string appDomainKey,
out bool appDomainStop)
{
- Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
- server = null; // Reset out param.
- identity = null;
- user = null;
- database = null;
- appDomainStop = false;
+ Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
+ server = null; // Reset out param.
+ identity = null;
+ user = null;
+ database = null;
+ appDomainStop = false;
SqlConnectionContainerHashHelper hashHelper = GetHashHelper(connectionString,
out SqlConnectionStringBuilder connectionStringBuilder,
bool stopped = false;
- lock (_connectionContainers)
- {
- if (_connectionContainers.ContainsKey(hashHelper))
- {
- SqlConnectionContainer container = _connectionContainers[hashHelper];
- server = container.Server; // Return server, database, and queue info for use by calling SqlDependency.
- database = container.Database;
- queueService = container.Queue;
-
- if (container.Stop(appDomainKey, out appDomainStop))
- { // Stop can be blocking if refCount == 0 on container.
- stopped = true;
- _connectionContainers.Remove(hashHelper); // Remove from collection.
- }
- }
- }
-
- return stopped;
+ lock (_connectionContainers)
+ {
+ if (_connectionContainers.ContainsKey(hashHelper))
+ {
+ SqlConnectionContainer container = _connectionContainers[hashHelper];
+ server = container.Server; // Return server, database, and queue info for use by calling SqlDependency.
+ database = container.Database;
+ queueService = container.Queue;
+
+ if (container.Stop(appDomainKey, out appDomainStop))
+ {
+ // Stop can be blocking if refCount == 0 on container.
+ stopped = true;
+ _connectionContainers.Remove(hashHelper); // Remove from collection.
+ }
+ }
+ }
+
+ return stopped;
}
}
}
switch (retval)
- {
- case 0:
- break;
+ {
+ case 0:
+ break;
- case Interop.Errors.ERROR_SHARING_VIOLATION:
- throw ADP.InvalidOperation(SR.GetString(SR.SqlFileStream_FileAlreadyInTransaction));
+ case Interop.Errors.ERROR_SHARING_VIOLATION:
+ throw ADP.InvalidOperation(SR.GetString(SR.SqlFileStream_FileAlreadyInTransaction));
- case Interop.Errors.ERROR_INVALID_PARAMETER:
- throw ADP.Argument(SR.GetString(SR.SqlFileStream_InvalidParameter));
+ case Interop.Errors.ERROR_INVALID_PARAMETER:
+ throw ADP.Argument(SR.GetString(SR.SqlFileStream_InvalidParameter));
- case Interop.Errors.ERROR_FILE_NOT_FOUND:
- {
- System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException();
- ADP.TraceExceptionAsReturnValue(e);
- throw e;
- }
- default:
+ case Interop.Errors.ERROR_FILE_NOT_FOUND:
+ {
+ System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException();
+ ADP.TraceExceptionAsReturnValue(e);
+ throw e;
+ }
+ default:
+ {
+ uint error = Interop.NtDll.RtlNtStatusToDosError(retval);
+ if (error == ERROR_MR_MID_NOT_FOUND)
{
- uint error = Interop.NtDll.RtlNtStatusToDosError(retval);
- if (error == ERROR_MR_MID_NOT_FOUND)
- {
- // status code could not be mapped to a Win32 error code
- error = (uint)retval;
- }
-
- System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked((int)error));
- ADP.TraceExceptionAsReturnValue(e);
- throw e;
+ // status code could not be mapped to a Win32 error code
+ error = (uint)retval;
}
- }
-
- if (hFile.IsInvalid)
- {
- System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Interop.Errors.ERROR_INVALID_HANDLE);
- ADP.TraceExceptionAsReturnValue(e);
- throw e;
- }
-
- if (Interop.Kernel32.GetFileType(hFile) != Interop.Kernel32.FileTypes.FILE_TYPE_DISK)
- {
- hFile.Dispose();
- throw ADP.Argument(SR.GetString(SR.SqlFileStream_PathNotValidDiskResource));
- }
- // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan
- // through current data and then append new data to the end, so we need to tell SQL Server to preserve
- // the existing file contents.
- if (access == System.IO.FileAccess.ReadWrite)
- {
- uint ioControlCode = Interop.Kernel32.CTL_CODE(FILE_DEVICE_FILE_SYSTEM,
- IoControlCodeFunctionCode, (byte)Interop.Kernel32.IoControlTransferType.METHOD_BUFFERED,
- (byte)Interop.Kernel32.IoControlCodeAccess.FILE_ANY_ACCESS);
-
- if (!Interop.Kernel32.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out uint cbBytesReturned, IntPtr.Zero))
- {
- System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
+ System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked((int)error));
ADP.TraceExceptionAsReturnValue(e);
throw e;
}
+ }
+
+ if (hFile.IsInvalid)
+ {
+ System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Interop.Errors.ERROR_INVALID_HANDLE);
+ ADP.TraceExceptionAsReturnValue(e);
+ throw e;
+ }
+
+ if (Interop.Kernel32.GetFileType(hFile) != Interop.Kernel32.FileTypes.FILE_TYPE_DISK)
+ {
+ hFile.Dispose();
+ throw ADP.Argument(SR.GetString(SR.SqlFileStream_PathNotValidDiskResource));
+ }
+
+ // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan
+ // through current data and then append new data to the end, so we need to tell SQL Server to preserve
+ // the existing file contents.
+ if (access == System.IO.FileAccess.ReadWrite)
+ {
+ uint ioControlCode = Interop.Kernel32.CTL_CODE(FILE_DEVICE_FILE_SYSTEM,
+ IoControlCodeFunctionCode, (byte)Interop.Kernel32.IoControlTransferType.METHOD_BUFFERED,
+ (byte)Interop.Kernel32.IoControlCodeAccess.FILE_ANY_ACCESS);
+
+ if (!Interop.Kernel32.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out uint cbBytesReturned, IntPtr.Zero))
+ {
+ System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
+ ADP.TraceExceptionAsReturnValue(e);
+ throw e;
}
+ }
- // now that we've successfully opened a handle on the path and verified that it is a file,
- // use the SafeFileHandle to initialize our internal System.IO.FileStream instance
- System.Diagnostics.Debug.Assert(_m_fs == null);
- _m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0));
+ // now that we've successfully opened a handle on the path and verified that it is a file,
+ // use the SafeFileHandle to initialize our internal System.IO.FileStream instance
+ System.Diagnostics.Debug.Assert(_m_fs == null);
+ _m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0));
}
catch
{
// NOTE: Udts can change their value any time
if (_internalMetaType.SqlDbType == Data.SqlDbType.Udt)
{
- Set(SqlParameterFlags.IsNull, ((_value == null) || (_value == DBNull.Value) || (( _flags.HasFlag(SqlParameterFlags.IsSqlParameterSqlType)) && (_valueAsINullable.IsNull))));
+ Set(SqlParameterFlags.IsNull, ((_value == null) || (_value == DBNull.Value) || ((_flags.HasFlag(SqlParameterFlags.IsSqlParameterSqlType)) && (_valueAsINullable.IsNull))));
}
return _flags.HasFlag(SqlParameterFlags.IsNull);
}
TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
ContinueTaskWithState(task, completion,
state: Tuple.Create(onSuccess, onFailure, completion),
- onSuccess: (state) => {
+ onSuccess: (state) =>
+ {
var parameters = (Tuple<Action, Action<Exception>, TaskCompletionSource<object>>)state;
Action success = parameters.Item1;
TaskCompletionSource<object> taskCompletionSource = parameters.Item3;
{
var completion = new TaskCompletionSource<object>();
ContinueTaskWithState(task, completion, state,
- onSuccess: (continueState) => {
+ onSuccess: (continueState) =>
+ {
onSuccess(continueState);
completion.SetResult(null);
},
internal override bool IsValidPacket(PacketHandle packetPointer)
{
- Debug.Assert(packetPointer.Type == PacketHandle.NativePointerType || packetPointer.Type==PacketHandle.NativePacketType, "unexpected packet type when requiring NativePointer");
+ Debug.Assert(packetPointer.Type == PacketHandle.NativePointerType || packetPointer.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePointer");
return (
(packetPointer.Type == PacketHandle.NativePointerType && packetPointer.NativePointer != IntPtr.Zero)
||
{
if (!s_isAppContainerProcessInitalized)
{
- if (Environment.OSVersion.Version.Major < 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor <= 1))
- {
- // Windows 7 or older.
- s_isAppContainerProcess = false;
- }
- else
- {
- s_isAppContainerProcess = HasAppContainerToken();
- }
+ if (Environment.OSVersion.Version.Major < 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor <= 1))
+ {
+ // Windows 7 or older.
+ s_isAppContainerProcess = false;
+ }
+ else
+ {
+ s_isAppContainerProcess = HasAppContainerToken();
+ }
s_isAppContainerProcessInitalized = true;
}
return true;
}
- private bool EnumWindowsCallback(IntPtr handle, IntPtr extraParameter) {
+ private bool EnumWindowsCallback(IntPtr handle, IntPtr extraParameter)
+ {
int processId;
Interop.User32.GetWindowThreadProcessId(handle, out processId);
- if (processId == _processId) {
- if (IsMainWindow(handle)) {
+ if (processId == _processId)
+ {
+ if (IsMainWindow(handle))
+ {
_bestHandle = handle;
return false;
}
{
public class SymLanguageType
{
- public static readonly Guid C = new Guid(0x63a08714, unchecked((short) 0xfc37), 0x11d2, 0x90, 0x4c, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
+ public static readonly Guid C = new Guid(0x63a08714, unchecked((short)0xfc37), 0x11d2, 0x90, 0x4c, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
public static readonly Guid CPlusPlus = new Guid(0x3a12d0b7, unchecked((short)0xc26c), 0x11d0, 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2);
public static readonly Guid CSharp = new Guid(0x3f5162f8, unchecked((short)0x07c6), 0x11d3, 0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
public static readonly Guid Cobol = new Guid(unchecked((int)0xaf046cd1), unchecked((short)0xd0e1), 0x11d2, 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc);
- public static readonly Guid Pascal = new Guid(unchecked((int)0xaf046cd2), unchecked((short) 0xd0e1), 0x11d2, 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc);
+ public static readonly Guid Pascal = new Guid(unchecked((int)0xaf046cd2), unchecked((short)0xd0e1), 0x11d2, 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc);
public static readonly Guid ILAssembly = new Guid(unchecked((int)0xaf046cd3), unchecked((short)0xd0e1), 0x11d2, 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc);
{
public class SymLanguageVendor
{
- public static readonly Guid Microsoft = new Guid(unchecked((int)0x994b45c4), unchecked((short) 0xe6e9), 0x11d2, 0x90, 0x3f, 0x00, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
+ public static readonly Guid Microsoft = new Guid(unchecked((int)0x994b45c4), unchecked((short)0xe6e9), 0x11d2, 0x90, 0x3f, 0x00, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
}
}
namespace System.Diagnostics
{
- public class ConsoleTraceListener : TextWriterTraceListener {
+ public class ConsoleTraceListener : TextWriterTraceListener
+ {
public ConsoleTraceListener()
- : base (Console.Out)
+ : base(Console.Out)
{
}
public ConsoleTraceListener(bool useErrorStream)
- : base (useErrorStream ? Console.Error : Console.Out)
+ : base(useErrorStream ? Console.Error : Console.Out)
{
}
string stackTrace;
try
{
- stackTrace = new StackTrace(fNeedFileInfo:true).ToString();
+ stackTrace = new StackTrace(fNeedFileInfo: true).ToString();
}
catch
{
public static void Indent()
{
- Debug.IndentLevel++;
+ Debug.IndentLevel++;
}
public static void Unindent()
public StringDictionary Attributes
{
- get {
+ get
+ {
if (_attributes == null)
_attributes = new StringDictionary();
return _attributes;
}
}
- public StringDictionary Attributes {
- get {
+ public StringDictionary Attributes
+ {
+ get
+ {
// Ensure that config is loaded
Initialize();
}
private bool _disposed = false; // keeps track of whether this object was disposed or not.
- private readonly bool _disposeDirEntry = false; // If set to true then the RangeRetriever object will own the directory entry
+ private readonly bool _disposeDirEntry = false; // If set to true then the RangeRetriever object will own the directory entry
// supplied to it in the constructor and will be responsible for disposing this entry
// when Dispose() is called on this object.
private bool _cacheValues = false; // If set to true then the attribute values will be cached in the InnerList
// By default caching is turned off.
- private readonly DirectoryEntry _de; // the DirectoryEntry whose property we're retrieving the values of
- private readonly string _propertyName; // the property we're retrieving the values of
+ private readonly DirectoryEntry _de; // the DirectoryEntry whose property we're retrieving the values of
+ private readonly string _propertyName; // the property we're retrieving the values of
private bool _endReached = false; // if true, all property values (from all chunks) have been retrieved
static GlobalDebug()
{
GlobalDebug.s_debugLevel = GlobalConfig.DebugLevel;
-//#if DEBUG
#if SUPPORTDEBUGLOGFILE // not defined
string debugLogFile = GlobalConfig.DebugLogFile;
{
private readonly DirectoryControl[] _resultControls = null;
- internal SearchResultEntry(string dn) : this(dn, new SearchResultAttributeCollection()) {}
+ internal SearchResultEntry(string dn) : this(dn, new SearchResultAttributeCollection()) { }
internal SearchResultEntry(string dn, SearchResultAttributeCollection attrs)
{
set;
}
- object Values { get; set; }
+ object Values { get; set; }
}
[ComImport, Guid("C6F602B6-8F69-11D0-8528-00C04FD8D503")]
_searcher.ServerPageTimeLimit = s_defaultTimeSpan;
}
- _searcher.CacheResults = cacheResults;
+ _searcher.CacheResults = cacheResults;
}
public SearchResult FindOne() => _searcher.FindOne();
/// </devdoc>
[
DefaultValue(""),
- // CoreFXPort - Remove design support
- // TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign)
+ // CoreFXPort - Remove design support
+ // TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign)
]
public string AttributeScopeQuery
{
internal Bitmap(IntPtr ptr) => SetNativeImage(ptr);
- public Bitmap(string filename) : this (filename, useIcm: false) { }
+ public Bitmap(string filename) : this(filename, useIcm: false) { }
public Bitmap(string filename, bool useIcm)
{
public static Brush MediumOrchid => GetBrush(s_mediumOrchidKey, Color.MediumOrchid);
public static Brush MediumPurple => GetBrush(s_mediumPurpleKey, Color.MediumPurple);
public static Brush MediumSeaGreen => GetBrush(s_mediumSeaGreenKey, Color.MediumSeaGreen);
- public static Brush MediumSlateBlue => GetBrush(s_mediumSlateBlueKey, Color.MediumSlateBlue);
+ public static Brush MediumSlateBlue => GetBrush(s_mediumSlateBlueKey, Color.MediumSlateBlue);
public static Brush MediumSpringGreen => GetBrush(s_mediumSpringGreenKey, Color.MediumSpringGreen);
public static Brush MediumTurquoise => GetBrush(s_mediumTurquoiseKey, Color.MediumTurquoise);
public static Brush MediumVioletRed => GetBrush(s_mediumVioletRedKey, Color.MediumVioletRed);
if (count == 0 || value.Positions.Length == 0)
throw new ArgumentException(SR.BlendObjectMustHaveTwoElements);
- if (count >=2 && count != value.Positions.Length)
+ if (count >= 2 && count != value.Positions.Length)
throw new ArgumentOutOfRangeException();
if (count >= 2 && value.Positions[0] != 0.0F)
throw new ArgumentException(SR.BlendObjectFirstElementInvalid);
public void ScaleTransform(float sx, float sy, MatrixOrder order)
{
- Gdip.CheckStatus( Gdip.GdipScaleLineTransform(
+ Gdip.CheckStatus(Gdip.GdipScaleLineTransform(
new HandleRef(this, NativeBrush), sx, sy, order));
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
- using System.Runtime.InteropServices;
+using System.Runtime.InteropServices;
namespace System.Drawing.Imaging
{
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
- public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type) :
+ public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type) :
this(fileName, referenceHdc, frameRect, frameUnit, type, null)
{
}
/// </summary>
private Pen(IntPtr nativePen) => SetNativePen(nativePen);
- internal Pen(Color color, bool immutable) : this(color) => _immutable = immutable;
+ internal Pen(Color color, bool immutable) : this(color) => _immutable = immutable;
/// <summary>
/// Initializes a new instance of the Pen class with the specified <see cref='Color'/>.
int status = Gdip.GdipSetPenLineCap197819(new HandleRef(this, NativePen),
unchecked((int)startCap), unchecked((int)endCap), unchecked((int)dashCap));
- Gdip.CheckStatus(status);
+ Gdip.CheckStatus(status);
}
/// <summary>
{
IntPtr nativeBrush = IntPtr.Zero;
int status = Gdip.GdipGetPenBrushFill(new HandleRef(this, NativePen), out nativeBrush);
- Gdip.CheckStatus(status);
+ Gdip.CheckStatus(status);
return nativeBrush;
}
return (value) ? True : False;
}
- public static explicit operator bool (TriState value)
+ public static explicit operator bool(TriState value)
{
if (value.IsDefault)
throw new InvalidCastException(SR.TriStateCompareError);
Gdip.CheckStatus(Gdip.GdipIsVisibleRegionPointI(
new HandleRef(this, NativeRegion),
point.X, point.Y,
- new HandleRef(g, g?.NativeGraphics ?? IntPtr.Zero),
+ new HandleRef(g, g?.NativeGraphics ?? IntPtr.Zero),
out int isVisible));
return isVisible != 0;
}
public Stream BaseStream => _stream;
- public override bool CanRead => _mode == CompressionMode.Decompress && _stream != null && _stream.CanRead;
- public override bool CanWrite => _mode == CompressionMode.Compress && _stream != null && _stream.CanWrite;
+ public override bool CanRead => _mode == CompressionMode.Decompress && _stream != null && _stream.CanRead;
+ public override bool CanWrite => _mode == CompressionMode.Compress && _stream != null && _stream.CanWrite;
public override bool CanSeek => false;
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override long Length => throw new NotSupportedException();
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
- return FinishReadAsyncMemory(buffer, cancellationToken);
+ return FinishReadAsyncMemory(buffer, cancellationToken);
}
private async ValueTask<int> FinishReadAsyncMemory(Memory<byte> buffer, CancellationToken cancellationToken)
foreach (ZipArchiveEntry entry in source.Entries)
{
- entry.ExtractRelativeToDirectory(destinationDirectoryName, overwriteFiles);
+ entry.ExtractRelativeToDirectory(destinationDirectoryName, overwriteFiles);
}
}
}
throw new InvalidDataException(SR.GenericInvalidData);
}
- _inflater.SetInput(_buffer, 0, bytes);
+ _inflater.SetInput(_buffer, 0, bytes);
}
}
{
private DeflateStream _deflateStream;
- public GZipStream(Stream stream, CompressionMode mode): this(stream, mode, leaveOpen: false)
+ public GZipStream(Stream stream, CompressionMode mode) : this(stream, mode, leaveOpen: false)
{
}
public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen)
{
- _deflateStream = new DeflateStream(stream, mode, leaveOpen, ZLibNative.GZip_DefaultWindowBits);
+ _deflateStream = new DeflateStream(stream, mode, leaveOpen, ZLibNative.GZip_DefaultWindowBits);
}
// Implies mode = Compress
- public GZipStream(Stream stream, CompressionLevel compressionLevel): this(stream, compressionLevel, leaveOpen: false)
+ public GZipStream(Stream stream, CompressionLevel compressionLevel) : this(stream, compressionLevel, leaveOpen: false)
{
}
compressedSize = reader.ReadInt32();
uncompressedSize = reader.ReadInt32();
}
- reader.BaseStream.Seek( -seekSize - entry.CompressedLength - 4, SeekOrigin.Current); // Seek back to the beginning of compressed stream
+ reader.BaseStream.Seek(-seekSize - entry.CompressedLength - 4, SeekOrigin.Current); // Seek back to the beginning of compressed stream
}
if (entry.CompressedLength != compressedSize)
=> EnumerateFileSystemEntries(path, searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions)
- => InternalEnumeratePaths(path, searchPattern, SearchTarget.Both, enumerationOptions);
+ => InternalEnumeratePaths(path, searchPattern, SearchTarget.Both, enumerationOptions);
public static string GetDirectoryRoot(string path)
{
EnumerationOptions options,
bool isNormalized)
{
- return new FileSystemEnumerable<FileInfo>(
- directory,
- (ref FileSystemEntry entry) => (FileInfo)entry.ToFileSystemInfo(),
- options,
- isNormalized)
- {
- ShouldIncludePredicate = (ref FileSystemEntry entry) =>
- !entry.IsDirectory && MatchesPattern(expression, entry.FileName, options)
- };
+ return new FileSystemEnumerable<FileInfo>(
+ directory,
+ (ref FileSystemEntry entry) => (FileInfo)entry.ToFileSystemInfo(),
+ options,
+ isNormalized)
+ {
+ ShouldIncludePredicate = (ref FileSystemEntry entry) =>
+ !entry.IsDirectory && MatchesPattern(expression, entry.FileName, options)
+ };
}
internal static IEnumerable<DirectoryInfo> DirectoryInfos(
/// For internal use. These are the options we want to use if calling the existing Directory/File APIs where you don't
/// explicitly specify EnumerationOptions.
/// </summary>
- internal static EnumerationOptions Compatible { get; } = new EnumerationOptions
- { MatchType = MatchType.Win32, AttributesToSkip = 0, IgnoreInaccessible = false };
+ internal static EnumerationOptions Compatible { get; } =
+ new EnumerationOptions { MatchType = MatchType.Win32, AttributesToSkip = 0, IgnoreInaccessible = false };
- private static EnumerationOptions CompatibleRecursive { get; } = new EnumerationOptions
- { RecurseSubdirectories = true, MatchType = MatchType.Win32, AttributesToSkip = 0, IgnoreInaccessible = false };
+ private static EnumerationOptions CompatibleRecursive { get; } =
+ new EnumerationOptions { RecurseSubdirectories = true, MatchType = MatchType.Win32, AttributesToSkip = 0, IgnoreInaccessible = false };
/// <summary>
/// Internal singleton for default options.
internal static unsafe FileSystemInfo Create(string fullPath, ref FileSystemEntry findData)
{
FileSystemInfo info = findData.IsDirectory
- ? (FileSystemInfo) new DirectoryInfo(fullPath, fileName: findData.FileName.ToString(), isNormalized: true)
+ ? (FileSystemInfo)new DirectoryInfo(fullPath, fileName: findData.FileName.ToString(), isNormalized: true)
: new FileInfo(fullPath, fileName: findData.FileName.ToString(), isNormalized: true);
Debug.Assert(!PathInternal.IsPartiallyQualified(fullPath.AsSpan()), $"'{fullPath}' should be fully qualified when constructed from directory enumeration");
// .NET Framework will parse this as relative. This will break internal relationships
// in packaging. For more information, see
// http://www.mono-project.com/docs/faq/known-issues/urikind-relativeorabsolute/
- private static readonly UriKind DotNetRelativeOrAbsolute = Type.GetType ("Mono.Runtime") == null ? UriKind.RelativeOrAbsolute : (UriKind)300;
+ private static readonly UriKind DotNetRelativeOrAbsolute = Type.GetType("Mono.Runtime") == null ? UriKind.RelativeOrAbsolute : (UriKind)300;
#region IEnumerable
/// <summary>
/// This parameter can be null in which case we will create a valid pack uri
/// that references the entire package</param>
/// <returns>A Uri with the "pack://" scheme</returns>
- /// <exception cref="ArgumentNullException">If packageUri parameter is null</exception>
+ /// <exception cref="ArgumentNullException">If packageUri parameter is null</exception>
/// <exception cref="ArgumentException">If packageUri parameter is not an absolute Uri</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
public static Uri Create(Uri packageUri, Uri partUri)
//has been closed.
private bool IsStreamClosed(Stream s)
{
- return !s.CanRead && !s.CanSeek && !s.CanWrite;
+ return !s.CanRead && !s.CanSeek && !s.CanWrite;
}
#endregion Private Methods
{
ProcessDefaultTagAttributes(reader);
}
+ else if (reader.NodeType == XmlNodeType.Element
+ && reader.Depth == 1
+ && (string.CompareOrdinal(reader.NamespaceURI, TypesNamespaceUri) == 0)
+ && (string.CompareOrdinal(reader.Name, OverrideTagName) == 0))
+ {
+ ProcessOverrideTagAttributes(reader);
+ }
+ else if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == 0 && string.CompareOrdinal(reader.Name, TypesTagName) == 0)
+ {
+ continue;
+ }
else
- if (reader.NodeType == XmlNodeType.Element
- && reader.Depth == 1
- && (string.CompareOrdinal(reader.NamespaceURI, TypesNamespaceUri) == 0)
- && (string.CompareOrdinal(reader.Name, OverrideTagName) == 0))
- {
- ProcessOverrideTagAttributes(reader);
- }
- else
- if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == 0 && string.CompareOrdinal(reader.Name, TypesTagName) == 0)
- continue;
- else
- {
- throw new XmlException(SR.TypesXmlDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
- }
+ {
+ throw new XmlException(SR.TypesXmlDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
+ }
}
}
else
public override long Length
{
- get {
+ get
+ {
// ZipArchiveEntry's read stream doesn't provide a length since it's a raw DeflateStream
// Return length from the archive entry.
if (_packageFileAccess == FileAccess.Read)
//
// Constructor for creating access rules for pipe objects
//
- public PipeAccessRule( string identity, PipeAccessRights rights, AccessControlType type)
- : this( new NTAccount(identity), AccessMaskFromRights(rights, type), false, type)
+ public PipeAccessRule(string identity, PipeAccessRights rights, AccessControlType type)
+ : this(new NTAccount(identity), AccessMaskFromRights(rights, type), false, type)
{
}
- public PipeAccessRule( IdentityReference identity, PipeAccessRights rights, AccessControlType type)
+ public PipeAccessRule(IdentityReference identity, PipeAccessRights rights, AccessControlType type)
: this(identity, AccessMaskFromRights(rights, type), false, type)
{
}
// Internal constructor to be called by public constructors
// and the access rights factory methods
//
- internal PipeAccessRule( IdentityReference identity, int accessMask, bool isInherited, AccessControlType type)
- : base( identity, accessMask, isInherited, InheritanceFlags.None, PropagationFlags.None, type)
+ internal PipeAccessRule(IdentityReference identity, int accessMask, bool isInherited, AccessControlType type)
+ : base(identity, accessMask, isInherited, InheritanceFlags.None, PropagationFlags.None, type)
{
}
{
if (portName == null)
{
- throw new ArgumentNullException(nameof(portName));
+ throw new ArgumentNullException(nameof(portName));
}
if (!portName.StartsWith("COM", StringComparison.OrdinalIgnoreCase) ||
// JsonValue -> CLI
- public static implicit operator bool (JsonValue value)
+ public static implicit operator bool(JsonValue value)
{
if (value == null)
{
return Convert.ToBoolean(((JsonPrimitive)value).Value, CultureInfo.InvariantCulture);
}
- public static implicit operator byte (JsonValue value)
+ public static implicit operator byte(JsonValue value)
{
if (value == null)
{
return Convert.ToByte(((JsonPrimitive)value).Value, CultureInfo.InvariantCulture);
}
- public static implicit operator char (JsonValue value)
+ public static implicit operator char(JsonValue value)
{
if (value == null)
{
return Convert.ToChar(((JsonPrimitive)value).Value, CultureInfo.InvariantCulture);
}
- public static implicit operator decimal (JsonValue value)
+ public static implicit operator decimal(JsonValue value)
{
if (value == null)
{
return Convert.ToDecimal(((JsonPrimitive)value).Value, CultureInfo.InvariantCulture);
}
- public static implicit operator double (JsonValue value)
+ public static implicit operator double(JsonValue value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
return Convert.ToDouble(((JsonPrimitive)value).Value, CultureInfo.InvariantCulture);
}
- public static implicit operator float (JsonValue value)
+ public static implicit operator float(JsonValue value)
{
if (value == null)
{
return Convert.ToSingle(((JsonPrimitive)value).Value, CultureInfo.InvariantCulture);
}
- public static implicit operator int (JsonValue value)
+ public static implicit operator int(JsonValue value)
{
if (value == null)
{
return Convert.ToInt32(((JsonPrimitive)value).Value, CultureInfo.InvariantCulture);
}
- public static implicit operator long (JsonValue value)
+ public static implicit operator long(JsonValue value)
{
if (value == null)
{
}
[CLSCompliant(false)]
- public static implicit operator sbyte (JsonValue value)
+ public static implicit operator sbyte(JsonValue value)
{
if (value == null)
{
return Convert.ToSByte(((JsonPrimitive)value).Value, CultureInfo.InvariantCulture);
}
- public static implicit operator short (JsonValue value)
+ public static implicit operator short(JsonValue value)
{
if (value == null)
{
return Convert.ToInt16(((JsonPrimitive)value).Value, CultureInfo.InvariantCulture);
}
- public static implicit operator string (JsonValue value)
+ public static implicit operator string(JsonValue value)
{
return value != null ?
(string)((JsonPrimitive)value).Value :
}
[CLSCompliant(false)]
- public static implicit operator uint (JsonValue value)
+ public static implicit operator uint(JsonValue value)
{
if (value == null)
{
}
[CLSCompliant(false)]
- public static implicit operator ulong (JsonValue value)
+ public static implicit operator ulong(JsonValue value)
{
if (value == null)
{
}
[CLSCompliant(false)]
- public static implicit operator ushort (JsonValue value)
+ public static implicit operator ushort(JsonValue value)
{
if (value == null)
{
}
else
{
- _instructions.EmitByRefCall(method, parameters, new[] {updater});
+ _instructions.EmitByRefCall(method, parameters, new[] { updater });
updater.UndefineTemps(_instructions, _locals);
}
internal abstract Expression Expression { get; }
internal abstract IEnumerable Enumerable { get; }
- internal EnumerableQuery() {}
+ internal EnumerableQuery() { }
internal static IQueryable Create(Type elementType, IEnumerable sequence)
{
var interfacesWithInfo = pubType.GetInterfaces().Select(IntrospectionExtensions.GetTypeInfo).ToArray();
var singleTypeGenInterfacesWithGetType = interfacesWithInfo
.Where(i => i.IsGenericType && i.GenericTypeArguments.Length == 1)
- .Select(i => new {Info = i, GenType = i.GetGenericTypeDefinition() })
+ .Select(i => new { Info = i, GenType = i.GetGenericTypeDefinition() })
.ToArray();
Type typeArg = singleTypeGenInterfacesWithGetType
.Where(i => i.GenType == typeof(IOrderedQueryable<>) || i.GenType == typeof(IOrderedEnumerable<>))
using System.Runtime.Versioning;
using System.Text;
-namespace WbemClient_v1 {}
-namespace WbemUtilities_v1 {}
+namespace WbemClient_v1 { }
+namespace WbemUtilities_v1 { }
namespace System.Management
{
Dispose_(false);
}
- private void Dispose_ ( bool finalization )
+ private void Dispose_(bool finalization)
{
if (pWbemClassObject != IntPtr.Zero)
{
Dispose_(true);
}
- private void DeserializeFromBlob(byte [] rg)
+ private void DeserializeFromBlob(byte[] rg)
{
IntPtr hGlobal = IntPtr.Zero;
System.Runtime.InteropServices.ComTypes.IStream stream = null;
private byte[] SerializeToBlob()
{
- byte [] rg = null;
+ byte[] rg = null;
System.Runtime.InteropServices.ComTypes.IStream stream = null;
IntPtr pData = IntPtr.Zero;
try
{
if (pWbemClassObject == IntPtr.Zero)
throw new ObjectDisposedException(name);
- int res = WmiNetUtilsHelper.BeginMethodEnumeration_f(22, pWbemClassObject, lEnumFlags);
+ int res = WmiNetUtilsHelper.BeginMethodEnumeration_f(22, pWbemClassObject, lEnumFlags);
GC.KeepAlive(this);
return res;
}
private enum STATFLAG
{
- STATFLAG_DEFAULT = 0,
- STATFLAG_NONAME = 1
+ STATFLAG_DEFAULT = 0,
+ STATFLAG_NONAME = 1
}
private enum MSHCTX
{
- MSHCTX_LOCAL = 0,
- MSHCTX_NOSHAREDMEM = 1,
- MSHCTX_DIFFERENTMACHINE = 2,
- MSHCTX_INPROC = 3
+ MSHCTX_LOCAL = 0,
+ MSHCTX_NOSHAREDMEM = 1,
+ MSHCTX_DIFFERENTMACHINE = 2,
+ MSHCTX_INPROC = 3
}
private enum MSHLFLAGS
{
- MSHLFLAGS_NORMAL = 0,
- MSHLFLAGS_TABLESTRONG = 1,
- MSHLFLAGS_TABLEWEAK = 2,
- MSHLFLAGS_NOPING = 3
+ MSHLFLAGS_NORMAL = 0,
+ MSHLFLAGS_TABLESTRONG = 1,
+ MSHLFLAGS_TABLEWEAK = 2,
+ MSHLFLAGS_NOPING = 3
}
}
Dispose_(false);
}
- private void Dispose_( bool finalization )
+ private void Dispose_(bool finalization)
{
if (pWbemQualifierSet != IntPtr.Zero)
{
Marshal.Release(pWbemQualifierSet);
pWbemQualifierSet = IntPtr.Zero;
}
- if ( finalization == false )
+ if (finalization == false)
{
GC.KeepAlive(this);
}
{
if (pWbemQualifierSet == IntPtr.Zero)
throw new ObjectDisposedException(name);
- int res = WmiNetUtilsHelper.QualifierPut_f(4, pWbemQualifierSet, wszName, ref pVal, lFlavor);
+ int res = WmiNetUtilsHelper.QualifierPut_f(4, pWbemQualifierSet, wszName, ref pVal, lFlavor);
GC.KeepAlive(this);
return res;
}
[ComImport]
internal interface IWbemClassObject_DoNotMarshal
{
- [PreserveSig] int GetQualifierSet_([Out][MarshalAs(UnmanagedType.Interface)] out IWbemQualifierSet_DoNotMarshal ppQualSet);
- [PreserveSig] int Get_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][Out] ref object pVal, [In][Out] ref int pType, [In][Out] ref int plFlavor);
- [PreserveSig] int Put_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In] ref object pVal, [In] int Type);
- [PreserveSig] int Delete_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
- [PreserveSig] int GetNames_([In][MarshalAs(UnmanagedType.LPWStr)] string wszQualifierName, [In] int lFlags, [In] ref object pQualifierVal, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)] out string[] pNames);
+ [PreserveSig] int GetQualifierSet_([Out][MarshalAs(UnmanagedType.Interface)] out IWbemQualifierSet_DoNotMarshal ppQualSet);
+ [PreserveSig] int Get_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][Out] ref object pVal, [In][Out] ref int pType, [In][Out] ref int plFlavor);
+ [PreserveSig] int Put_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In] ref object pVal, [In] int Type);
+ [PreserveSig] int Delete_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
+ [PreserveSig] int GetNames_([In][MarshalAs(UnmanagedType.LPWStr)] string wszQualifierName, [In] int lFlags, [In] ref object pQualifierVal, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] out string[] pNames);
[PreserveSig] int BeginEnumeration_([In] int lEnumFlags);
- [PreserveSig] int Next_([In] int lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string strName, [In][Out] ref object pVal, [In][Out] ref int pType, [In][Out] ref int plFlavor);
+ [PreserveSig] int Next_([In] int lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string strName, [In][Out] ref object pVal, [In][Out] ref int pType, [In][Out] ref int plFlavor);
[PreserveSig] int EndEnumeration_();
- [PreserveSig] int GetPropertyQualifierSet_([In][MarshalAs(UnmanagedType.LPWStr)] string wszProperty, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemQualifierSet_DoNotMarshal ppQualSet);
- [PreserveSig] int Clone_([Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppCopy);
- [PreserveSig] int GetObjectText_([In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrObjectText);
- [PreserveSig] int SpawnDerivedClass_([In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppNewClass);
- [PreserveSig] int SpawnInstance_([In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppNewInstance);
- [PreserveSig] int CompareTo_([In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pCompareTo);
- [PreserveSig] int GetPropertyOrigin_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName);
- [PreserveSig] int InheritsFrom_([In][MarshalAs(UnmanagedType.LPWStr)] string strAncestor);
- [PreserveSig] int GetMethod_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppInSignature, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppOutSignature);
- [PreserveSig] int PutMethod_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pInSignature, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pOutSignature);
- [PreserveSig] int DeleteMethod_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
+ [PreserveSig] int GetPropertyQualifierSet_([In][MarshalAs(UnmanagedType.LPWStr)] string wszProperty, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemQualifierSet_DoNotMarshal ppQualSet);
+ [PreserveSig] int Clone_([Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppCopy);
+ [PreserveSig] int GetObjectText_([In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrObjectText);
+ [PreserveSig] int SpawnDerivedClass_([In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppNewClass);
+ [PreserveSig] int SpawnInstance_([In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppNewInstance);
+ [PreserveSig] int CompareTo_([In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pCompareTo);
+ [PreserveSig] int GetPropertyOrigin_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName);
+ [PreserveSig] int InheritsFrom_([In][MarshalAs(UnmanagedType.LPWStr)] string strAncestor);
+ [PreserveSig] int GetMethod_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppInSignature, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppOutSignature);
+ [PreserveSig] int PutMethod_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pInSignature, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pOutSignature);
+ [PreserveSig] int DeleteMethod_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
[PreserveSig] int BeginMethodEnumeration_([In] int lEnumFlags);
- [PreserveSig] int NextMethod_([In] int lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string pstrName, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal ppInSignature, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal ppOutSignature);
+ [PreserveSig] int NextMethod_([In] int lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string pstrName, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal ppInSignature, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal ppOutSignature);
[PreserveSig] int EndMethodEnumeration_();
- [PreserveSig] int GetMethodQualifierSet_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMethod, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemQualifierSet_DoNotMarshal ppQualSet);
- [PreserveSig] int GetMethodOrigin_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMethodName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName);
+ [PreserveSig] int GetMethodQualifierSet_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMethod, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemQualifierSet_DoNotMarshal ppQualSet);
+ [PreserveSig] int GetMethodOrigin_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMethodName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName);
}
[InterfaceTypeAttribute(0x0001)]
[ComImport]
internal interface IWbemQualifierSet_DoNotMarshal
{
- [PreserveSig] int Get_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][Out] ref object pVal, [In][Out] ref int plFlavor);
- [PreserveSig] int Put_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] ref object pVal, [In] int lFlavor);
- [PreserveSig] int Delete_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
- [PreserveSig] int GetNames_([In] int lFlags, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)] out string[] pNames);
+ [PreserveSig] int Get_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][Out] ref object pVal, [In][Out] ref int plFlavor);
+ [PreserveSig] int Put_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] ref object pVal, [In] int lFlavor);
+ [PreserveSig] int Delete_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
+ [PreserveSig] int GetNames_([In] int lFlags, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] out string[] pNames);
[PreserveSig] int BeginEnumeration_([In] int lFlags);
- [PreserveSig] int Next_([In] int lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string pstrName, [In][Out] ref object pVal, [In][Out] ref int plFlavor);
+ [PreserveSig] int Next_([In] int lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string pstrName, [In][Out] ref object pVal, [In][Out] ref int plFlavor);
[PreserveSig] int EndEnumeration_();
}
[ComImport]
internal interface IWbemLocator
{
- [PreserveSig] int ConnectServer_([In][MarshalAs(UnmanagedType.BStr)] string strNetworkResource, [In][MarshalAs(UnmanagedType.BStr)] string strUser, [In]IntPtr strPassword, [In][MarshalAs(UnmanagedType.BStr)] string strLocale, [In] int lSecurityFlags, [In][MarshalAs(UnmanagedType.BStr)] string strAuthority, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemServices ppNamespace);
+ [PreserveSig] int ConnectServer_([In][MarshalAs(UnmanagedType.BStr)] string strNetworkResource, [In][MarshalAs(UnmanagedType.BStr)] string strUser, [In]IntPtr strPassword, [In][MarshalAs(UnmanagedType.BStr)] string strLocale, [In] int lSecurityFlags, [In][MarshalAs(UnmanagedType.BStr)] string strAuthority, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemServices ppNamespace);
}
[GuidAttribute("44ACA674-E8FC-11D0-A07C-00C04FB68820")]
[ComImport]
internal interface IWbemContext
{
- [PreserveSig] int Clone_([Out][MarshalAs(UnmanagedType.Interface)] out IWbemContext ppNewCopy);
- [PreserveSig] int GetNames_([In] int lFlags, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)] out string[] pNames);
+ [PreserveSig] int Clone_([Out][MarshalAs(UnmanagedType.Interface)] out IWbemContext ppNewCopy);
+ [PreserveSig] int GetNames_([In] int lFlags, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] out string[] pNames);
[PreserveSig] int BeginEnumeration_([In] int lFlags);
- [PreserveSig] int Next_([In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrName, [Out] out object pValue);
+ [PreserveSig] int Next_([In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrName, [Out] out object pValue);
[PreserveSig] int EndEnumeration_();
- [PreserveSig] int SetValue_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In] ref object pValue);
- [PreserveSig] int GetValue_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [Out] out object pValue);
- [PreserveSig] int DeleteValue_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags);
+ [PreserveSig] int SetValue_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In] ref object pValue);
+ [PreserveSig] int GetValue_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [Out] out object pValue);
+ [PreserveSig] int DeleteValue_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags);
[PreserveSig] int DeleteAll_();
}
[ComImport]
internal interface IWbemServices
{
- [PreserveSig] int OpenNamespace_([In][MarshalAs(UnmanagedType.BStr)] string strNamespace, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemServices ppWorkingNamespace, [In] IntPtr ppCallResult);
- [PreserveSig] int CancelAsyncCall_([In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pSink);
- [PreserveSig] int QueryObjectSink_([In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemObjectSink ppResponseHandler);
- [PreserveSig] int GetObject_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(MarshalWbemObject))] out IWbemClassObjectFreeThreaded ppObject, [In] IntPtr ppCallResult);
- [PreserveSig] int GetObjectAsync_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int PutClass_([In] IntPtr pObject, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
- [PreserveSig] int PutClassAsync_([In] IntPtr pObject, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int DeleteClass_([In][MarshalAs(UnmanagedType.BStr)] string strClass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
- [PreserveSig] int DeleteClassAsync_([In][MarshalAs(UnmanagedType.BStr)] string strClass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int CreateClassEnum_([In][MarshalAs(UnmanagedType.BStr)] string strSuperclass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
- [PreserveSig] int CreateClassEnumAsync_([In][MarshalAs(UnmanagedType.BStr)] string strSuperclass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int PutInstance_([In] IntPtr pInst, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
- [PreserveSig] int PutInstanceAsync_([In] IntPtr pInst, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int DeleteInstance_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
- [PreserveSig] int DeleteInstanceAsync_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int CreateInstanceEnum_([In][MarshalAs(UnmanagedType.BStr)] string strFilter, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
- [PreserveSig] int CreateInstanceEnumAsync_([In][MarshalAs(UnmanagedType.BStr)] string strFilter, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int ExecQuery_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
- [PreserveSig] int ExecQueryAsync_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int ExecNotificationQuery_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
- [PreserveSig] int ExecNotificationQueryAsync_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int ExecMethod_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In][MarshalAs(UnmanagedType.BStr)] string strMethodName, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr pInParams, [Out][MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(MarshalWbemObject))] out IWbemClassObjectFreeThreaded ppOutParams, [In] IntPtr ppCallResult);
- [PreserveSig] int ExecMethodAsync_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In][MarshalAs(UnmanagedType.BStr)] string strMethodName, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr pInParams, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int OpenNamespace_([In][MarshalAs(UnmanagedType.BStr)] string strNamespace, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemServices ppWorkingNamespace, [In] IntPtr ppCallResult);
+ [PreserveSig] int CancelAsyncCall_([In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pSink);
+ [PreserveSig] int QueryObjectSink_([In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemObjectSink ppResponseHandler);
+ [PreserveSig] int GetObject_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MarshalWbemObject))] out IWbemClassObjectFreeThreaded ppObject, [In] IntPtr ppCallResult);
+ [PreserveSig] int GetObjectAsync_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int PutClass_([In] IntPtr pObject, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
+ [PreserveSig] int PutClassAsync_([In] IntPtr pObject, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int DeleteClass_([In][MarshalAs(UnmanagedType.BStr)] string strClass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
+ [PreserveSig] int DeleteClassAsync_([In][MarshalAs(UnmanagedType.BStr)] string strClass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int CreateClassEnum_([In][MarshalAs(UnmanagedType.BStr)] string strSuperclass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
+ [PreserveSig] int CreateClassEnumAsync_([In][MarshalAs(UnmanagedType.BStr)] string strSuperclass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int PutInstance_([In] IntPtr pInst, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
+ [PreserveSig] int PutInstanceAsync_([In] IntPtr pInst, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int DeleteInstance_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
+ [PreserveSig] int DeleteInstanceAsync_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int CreateInstanceEnum_([In][MarshalAs(UnmanagedType.BStr)] string strFilter, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
+ [PreserveSig] int CreateInstanceEnumAsync_([In][MarshalAs(UnmanagedType.BStr)] string strFilter, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int ExecQuery_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
+ [PreserveSig] int ExecQueryAsync_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int ExecNotificationQuery_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
+ [PreserveSig] int ExecNotificationQueryAsync_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int ExecMethod_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In][MarshalAs(UnmanagedType.BStr)] string strMethodName, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr pInParams, [Out][MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MarshalWbemObject))] out IWbemClassObjectFreeThreaded ppOutParams, [In] IntPtr ppCallResult);
+ [PreserveSig] int ExecMethodAsync_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In][MarshalAs(UnmanagedType.BStr)] string strMethodName, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr pInParams, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
}
[InterfaceTypeAttribute(0x0001)]
[ComImport]
internal interface IWbemServices_Old
{
- [PreserveSig] int OpenNamespace_([In][MarshalAs(UnmanagedType.BStr)] string strNamespace, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemServices ppWorkingNamespace, [In] IntPtr ppCallResult);
- [PreserveSig] int CancelAsyncCall_([In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pSink);
- [PreserveSig] int QueryObjectSink_([In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemObjectSink ppResponseHandler);
- [PreserveSig] int GetObject_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal ppObject, [In] IntPtr ppCallResult);
- [PreserveSig] int GetObjectAsync_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int PutClass_([In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pObject, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
- [PreserveSig] int PutClassAsync_([In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pObject, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int DeleteClass_([In][MarshalAs(UnmanagedType.BStr)] string strClass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
- [PreserveSig] int DeleteClassAsync_([In][MarshalAs(UnmanagedType.BStr)] string strClass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int CreateClassEnum_([In][MarshalAs(UnmanagedType.BStr)] string strSuperclass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
- [PreserveSig] int CreateClassEnumAsync_([In][MarshalAs(UnmanagedType.BStr)] string strSuperclass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int PutInstance_([In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pInst, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
- [PreserveSig] int PutInstanceAsync_([In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pInst, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int DeleteInstance_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
- [PreserveSig] int DeleteInstanceAsync_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int CreateInstanceEnum_([In][MarshalAs(UnmanagedType.BStr)] string strFilter, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
- [PreserveSig] int CreateInstanceEnumAsync_([In][MarshalAs(UnmanagedType.BStr)] string strFilter, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int ExecQuery_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
- [PreserveSig] int ExecQueryAsync_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int ExecNotificationQuery_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
- [PreserveSig] int ExecNotificationQueryAsync_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
- [PreserveSig] int ExecMethod_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In][MarshalAs(UnmanagedType.BStr)] string strMethodName, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pInParams, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal ppOutParams, [In] IntPtr ppCallResult);
- [PreserveSig] int ExecMethodAsync_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In][MarshalAs(UnmanagedType.BStr)] string strMethodName, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pInParams, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int OpenNamespace_([In][MarshalAs(UnmanagedType.BStr)] string strNamespace, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemServices ppWorkingNamespace, [In] IntPtr ppCallResult);
+ [PreserveSig] int CancelAsyncCall_([In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pSink);
+ [PreserveSig] int QueryObjectSink_([In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemObjectSink ppResponseHandler);
+ [PreserveSig] int GetObject_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal ppObject, [In] IntPtr ppCallResult);
+ [PreserveSig] int GetObjectAsync_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int PutClass_([In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pObject, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
+ [PreserveSig] int PutClassAsync_([In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pObject, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int DeleteClass_([In][MarshalAs(UnmanagedType.BStr)] string strClass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
+ [PreserveSig] int DeleteClassAsync_([In][MarshalAs(UnmanagedType.BStr)] string strClass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int CreateClassEnum_([In][MarshalAs(UnmanagedType.BStr)] string strSuperclass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
+ [PreserveSig] int CreateClassEnumAsync_([In][MarshalAs(UnmanagedType.BStr)] string strSuperclass, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int PutInstance_([In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pInst, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
+ [PreserveSig] int PutInstanceAsync_([In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pInst, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int DeleteInstance_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult);
+ [PreserveSig] int DeleteInstanceAsync_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int CreateInstanceEnum_([In][MarshalAs(UnmanagedType.BStr)] string strFilter, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
+ [PreserveSig] int CreateInstanceEnumAsync_([In][MarshalAs(UnmanagedType.BStr)] string strFilter, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int ExecQuery_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
+ [PreserveSig] int ExecQueryAsync_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int ExecNotificationQuery_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
+ [PreserveSig] int ExecNotificationQueryAsync_([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
+ [PreserveSig] int ExecMethod_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In][MarshalAs(UnmanagedType.BStr)] string strMethodName, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pInParams, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal ppOutParams, [In] IntPtr ppCallResult);
+ [PreserveSig] int ExecMethodAsync_([In][MarshalAs(UnmanagedType.BStr)] string strObjectPath, [In][MarshalAs(UnmanagedType.BStr)] string strMethodName, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pInParams, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pResponseHandler);
}
[GuidAttribute("44ACA675-E8FC-11D0-A07C-00C04FB68820")]
[ComImport]
internal interface IWbemCallResult
{
- [PreserveSig] int GetResultObject_([In] int lTimeout, [Out][MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(MarshalWbemObject))] out IWbemClassObjectFreeThreaded ppResultObject);
- [PreserveSig] int GetResultString_([In] int lTimeout, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrResultString);
- [PreserveSig] int GetResultServices_([In] int lTimeout, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemServices ppServices);
+ [PreserveSig] int GetResultObject_([In] int lTimeout, [Out][MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MarshalWbemObject))] out IWbemClassObjectFreeThreaded ppResultObject);
+ [PreserveSig] int GetResultString_([In] int lTimeout, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrResultString);
+ [PreserveSig] int GetResultServices_([In] int lTimeout, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemServices ppServices);
[PreserveSig] int GetCallStatus_([In] int lTimeout, [Out] out int plStatus);
}
internal interface IWbemObjectSink
{
[PreserveSig] int Indicate_([In] int lObjectCount, [In][MarshalAs(UnmanagedType.LPArray)] IntPtr[] apObjArray);
- [PreserveSig] int SetStatus_([In] int lFlags, [In][MarshalAs(UnmanagedType.Error)] int hResult, [In][MarshalAs(UnmanagedType.BStr)] string strParam, [In] IntPtr pObjParam);
+ [PreserveSig] int SetStatus_([In] int lFlags, [In][MarshalAs(UnmanagedType.Error)] int hResult, [In][MarshalAs(UnmanagedType.BStr)] string strParam, [In] IntPtr pObjParam);
}
[InterfaceTypeAttribute(0x0001)]
{
[PreserveSig] int Reset_();
[PreserveSig] int Next_([In] int lTimeout, [In] uint uCount, [In][Out][MarshalAs(UnmanagedType.LPArray)] IWbemClassObject_DoNotMarshal[] apObjects, [Out] out uint puReturned);
- [PreserveSig] int NextAsync_([In] uint uCount, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pSink);
- [PreserveSig] int Clone_([Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
+ [PreserveSig] int NextAsync_([In] uint uCount, [In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pSink);
+ [PreserveSig] int Clone_([Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum);
[PreserveSig] int Skip_([In] int lTimeout, [In] uint nCount);
}
[ComImport]
internal interface IWbemShutdown
{
- [PreserveSig] int Shutdown_([In] int uReason, [In] uint uMaxMilliseconds, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx);
+ [PreserveSig] int Shutdown_([In] int uReason, [In] uint uMaxMilliseconds, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx);
}
[InterfaceTypeAttribute(0x0001)]
[ComImport]
internal interface IWbemObjectTextSrc
{
- [PreserveSig] int GetText_([In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pObj, [In] uint uObjTextFormat, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.BStr)] out string strText);
- [PreserveSig] int CreateFromText_([In] int lFlags, [In][MarshalAs(UnmanagedType.BStr)] string strText, [In] uint uObjTextFormat, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal pNewObj);
+ [PreserveSig] int GetText_([In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pObj, [In] uint uObjTextFormat, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.BStr)] out string strText);
+ [PreserveSig] int CreateFromText_([In] int lFlags, [In][MarshalAs(UnmanagedType.BStr)] string strText, [In] uint uObjTextFormat, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal pNewObj);
}
[GuidAttribute("49353C9A-516B-11D1-AEA6-00C04FB68820")]
[ComImport]
internal interface IWbemObjectAccess
{
- [PreserveSig] int GetQualifierSet_([Out][MarshalAs(UnmanagedType.Interface)] out IWbemQualifierSet_DoNotMarshal ppQualSet);
- [PreserveSig] int Get_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][Out] ref object pVal, [In][Out] ref int pType, [In][Out] ref int plFlavor);
- [PreserveSig] int Put_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In] ref object pVal, [In] int Type);
- [PreserveSig] int Delete_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
- [PreserveSig] int GetNames_([In][MarshalAs(UnmanagedType.LPWStr)] string wszQualifierName, [In] int lFlags, [In] ref object pQualifierVal, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)] out string[] pNames);
+ [PreserveSig] int GetQualifierSet_([Out][MarshalAs(UnmanagedType.Interface)] out IWbemQualifierSet_DoNotMarshal ppQualSet);
+ [PreserveSig] int Get_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][Out] ref object pVal, [In][Out] ref int pType, [In][Out] ref int plFlavor);
+ [PreserveSig] int Put_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In] ref object pVal, [In] int Type);
+ [PreserveSig] int Delete_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
+ [PreserveSig] int GetNames_([In][MarshalAs(UnmanagedType.LPWStr)] string wszQualifierName, [In] int lFlags, [In] ref object pQualifierVal, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] out string[] pNames);
[PreserveSig] int BeginEnumeration_([In] int lEnumFlags);
- [PreserveSig] int Next_([In] int lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string strName, [In][Out] ref object pVal, [In][Out] ref int pType, [In][Out] ref int plFlavor);
+ [PreserveSig] int Next_([In] int lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string strName, [In][Out] ref object pVal, [In][Out] ref int pType, [In][Out] ref int plFlavor);
[PreserveSig] int EndEnumeration_();
- [PreserveSig] int GetPropertyQualifierSet_([In][MarshalAs(UnmanagedType.LPWStr)] string wszProperty, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemQualifierSet_DoNotMarshal ppQualSet);
- [PreserveSig] int Clone_([Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppCopy);
- [PreserveSig] int GetObjectText_([In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrObjectText);
- [PreserveSig] int SpawnDerivedClass_([In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppNewClass);
- [PreserveSig] int SpawnInstance_([In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppNewInstance);
- [PreserveSig] int CompareTo_([In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pCompareTo);
- [PreserveSig] int GetPropertyOrigin_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName);
- [PreserveSig] int InheritsFrom_([In][MarshalAs(UnmanagedType.LPWStr)] string strAncestor);
- [PreserveSig] int GetMethod_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppInSignature, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppOutSignature);
- [PreserveSig] int PutMethod_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pInSignature, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pOutSignature);
- [PreserveSig] int DeleteMethod_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
+ [PreserveSig] int GetPropertyQualifierSet_([In][MarshalAs(UnmanagedType.LPWStr)] string wszProperty, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemQualifierSet_DoNotMarshal ppQualSet);
+ [PreserveSig] int Clone_([Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppCopy);
+ [PreserveSig] int GetObjectText_([In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrObjectText);
+ [PreserveSig] int SpawnDerivedClass_([In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppNewClass);
+ [PreserveSig] int SpawnInstance_([In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppNewInstance);
+ [PreserveSig] int CompareTo_([In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pCompareTo);
+ [PreserveSig] int GetPropertyOrigin_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName);
+ [PreserveSig] int InheritsFrom_([In][MarshalAs(UnmanagedType.LPWStr)] string strAncestor);
+ [PreserveSig] int GetMethod_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppInSignature, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemClassObject_DoNotMarshal ppOutSignature);
+ [PreserveSig] int PutMethod_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pInSignature, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pOutSignature);
+ [PreserveSig] int DeleteMethod_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
[PreserveSig] int BeginMethodEnumeration_([In] int lEnumFlags);
- [PreserveSig] int NextMethod_([In] int lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string pstrName, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal ppInSignature, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal ppOutSignature);
+ [PreserveSig] int NextMethod_([In] int lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string pstrName, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal ppInSignature, [In][Out][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal ppOutSignature);
[PreserveSig] int EndMethodEnumeration_();
- [PreserveSig] int GetMethodQualifierSet_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMethod, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemQualifierSet_DoNotMarshal ppQualSet);
- [PreserveSig] int GetMethodOrigin_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMethodName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName);
- [PreserveSig] int GetPropertyHandle_([In][MarshalAs(UnmanagedType.LPWStr)] string wszPropertyName, [Out] out int pType, [Out] out int plHandle);
+ [PreserveSig] int GetMethodQualifierSet_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMethod, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemQualifierSet_DoNotMarshal ppQualSet);
+ [PreserveSig] int GetMethodOrigin_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMethodName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName);
+ [PreserveSig] int GetPropertyHandle_([In][MarshalAs(UnmanagedType.LPWStr)] string wszPropertyName, [Out] out int pType, [Out] out int plHandle);
[PreserveSig] int WritePropertyValue_([In] int lHandle, [In] int lNumBytes, [In] ref byte aData);
[PreserveSig] int ReadPropertyValue_([In] int lHandle, [In] int lBufferSize, [Out] out int plNumBytes, [Out] out byte aData);
[PreserveSig] int ReadDWORD_([In] int lHandle, [Out] out uint pdw);
[PreserveSig] int WriteDWORD_([In] int lHandle, [In] uint dw);
[PreserveSig] int ReadQWORD_([In] int lHandle, [Out] out ulong pqw);
[PreserveSig] int WriteQWORD_([In] int lHandle, [In] ulong pw);
- [PreserveSig] int GetPropertyInfoByHandle_([In] int lHandle, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrName, [Out] out int pType);
+ [PreserveSig] int GetPropertyInfoByHandle_([In] int lHandle, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrName, [Out] out int pType);
[PreserveSig] int Lock_([In] int lFlags);
[PreserveSig] int Unlock_([In] int lFlags);
}
[ComImport]
internal interface IUnsecuredApartment
{
- [PreserveSig] int CreateObjectStub_([In][MarshalAs(UnmanagedType.IUnknown)] object pObject, [Out][MarshalAs(UnmanagedType.IUnknown)] out object ppStub);
+ [PreserveSig] int CreateObjectStub_([In][MarshalAs(UnmanagedType.IUnknown)] object pObject, [Out][MarshalAs(UnmanagedType.IUnknown)] out object ppStub);
}
[GuidAttribute("EB87E1BC-3233-11D2-AEC9-00C04FB68820")]
[ComImport]
internal interface IWbemStatusCodeText
{
- [PreserveSig] int GetErrorCodeText_([In][MarshalAs(UnmanagedType.Error)] int hRes, [In] uint LocaleId, [In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string MessageText);
- [PreserveSig] int GetFacilityCodeText_([In][MarshalAs(UnmanagedType.Error)] int hRes, [In] uint LocaleId, [In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string MessageText);
+ [PreserveSig] int GetErrorCodeText_([In][MarshalAs(UnmanagedType.Error)] int hRes, [In] uint LocaleId, [In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string MessageText);
+ [PreserveSig] int GetFacilityCodeText_([In][MarshalAs(UnmanagedType.Error)] int hRes, [In] uint LocaleId, [In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string MessageText);
}
[InterfaceTypeAttribute(0x0001)]
[ComImport]
internal interface IWbemUnboundObjectSink
{
- [PreserveSig] int IndicateToConsumer_([In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pLogicalConsumer, [In] int lNumObjects, [In][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal apObjects);
+ [PreserveSig] int IndicateToConsumer_([In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pLogicalConsumer, [In] int lNumObjects, [In][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal apObjects);
}
[InterfaceTypeAttribute(0x0001)]
[ComImport]
internal interface IWbemPropertyProvider
{
- [PreserveSig] int GetProperty_([In] int lFlags, [In][MarshalAs(UnmanagedType.BStr)] string strLocale, [In][MarshalAs(UnmanagedType.BStr)] string strClassMapping, [In][MarshalAs(UnmanagedType.BStr)] string strInstMapping, [In][MarshalAs(UnmanagedType.BStr)] string strPropMapping, [Out] out object pvValue);
- [PreserveSig] int PutProperty_([In] int lFlags, [In][MarshalAs(UnmanagedType.BStr)] string strLocale, [In][MarshalAs(UnmanagedType.BStr)] string strClassMapping, [In][MarshalAs(UnmanagedType.BStr)] string strInstMapping, [In][MarshalAs(UnmanagedType.BStr)] string strPropMapping, [In] ref object pvValue);
+ [PreserveSig] int GetProperty_([In] int lFlags, [In][MarshalAs(UnmanagedType.BStr)] string strLocale, [In][MarshalAs(UnmanagedType.BStr)] string strClassMapping, [In][MarshalAs(UnmanagedType.BStr)] string strInstMapping, [In][MarshalAs(UnmanagedType.BStr)] string strPropMapping, [Out] out object pvValue);
+ [PreserveSig] int PutProperty_([In] int lFlags, [In][MarshalAs(UnmanagedType.BStr)] string strLocale, [In][MarshalAs(UnmanagedType.BStr)] string strClassMapping, [In][MarshalAs(UnmanagedType.BStr)] string strInstMapping, [In][MarshalAs(UnmanagedType.BStr)] string strPropMapping, [In] ref object pvValue);
}
[InterfaceTypeAttribute(0x0001)]
[ComImport]
internal interface IWbemEventProvider
{
- [PreserveSig] int ProvideEvents_([In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pSink, [In] int lFlags);
+ [PreserveSig] int ProvideEvents_([In][MarshalAs(UnmanagedType.Interface)] IWbemObjectSink pSink, [In] int lFlags);
}
[GuidAttribute("580ACAF8-FA1C-11D0-AD72-00C04FD8FDFF")]
[ComImport]
internal interface IWbemEventProviderQuerySink
{
- [PreserveSig] int NewQuery_([In] uint dwId, [In][MarshalAs(UnmanagedType.LPWStr)] string wszQueryLanguage, [In][MarshalAs(UnmanagedType.LPWStr)] string wszQuery);
+ [PreserveSig] int NewQuery_([In] uint dwId, [In][MarshalAs(UnmanagedType.LPWStr)] string wszQueryLanguage, [In][MarshalAs(UnmanagedType.LPWStr)] string wszQuery);
[PreserveSig] int CancelQuery_([In] uint dwId);
}
[ComImport]
internal interface IWbemEventProviderSecurity
{
- [PreserveSig] int AccessCheck_([In][MarshalAs(UnmanagedType.LPWStr)] string wszQueryLanguage, [In][MarshalAs(UnmanagedType.LPWStr)] string wszQuery, [In] int lSidLength, [In] ref byte pSid);
+ [PreserveSig] int AccessCheck_([In][MarshalAs(UnmanagedType.LPWStr)] string wszQueryLanguage, [In][MarshalAs(UnmanagedType.LPWStr)] string wszQuery, [In] int lSidLength, [In] ref byte pSid);
}
[GuidAttribute("631F7D97-D993-11D2-B339-00105A1F4AAF")]
[ComImport]
internal interface IWbemProviderIdentity
{
- [PreserveSig] int SetRegistrationObject_([In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pProvReg);
+ [PreserveSig] int SetRegistrationObject_([In] int lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pProvReg);
}
[InterfaceTypeAttribute(0x0001)]
[ComImport]
internal interface IWbemEventConsumerProvider
{
- [PreserveSig] int FindConsumer_([In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pLogicalConsumer, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemUnboundObjectSink ppConsumer);
+ [PreserveSig] int FindConsumer_([In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pLogicalConsumer, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemUnboundObjectSink ppConsumer);
}
[GuidAttribute("1BE41571-91DD-11D1-AEB2-00C04FB68820")]
[ComImport]
internal interface IWbemProviderInit
{
- [PreserveSig] int Initialize_([In][MarshalAs(UnmanagedType.LPWStr)] string wszUser, [In] int lFlags, [In][MarshalAs(UnmanagedType.LPWStr)] string wszNamespace, [In][MarshalAs(UnmanagedType.LPWStr)] string wszLocale, [In][MarshalAs(UnmanagedType.Interface)] IWbemServices pNamespace, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemProviderInitSink pInitSink);
+ [PreserveSig] int Initialize_([In][MarshalAs(UnmanagedType.LPWStr)] string wszUser, [In] int lFlags, [In][MarshalAs(UnmanagedType.LPWStr)] string wszNamespace, [In][MarshalAs(UnmanagedType.LPWStr)] string wszLocale, [In][MarshalAs(UnmanagedType.Interface)] IWbemServices pNamespace, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In][MarshalAs(UnmanagedType.Interface)] IWbemProviderInitSink pInitSink);
}
[InterfaceTypeAttribute(0x0001)]
[ComImport]
internal interface IWbemDecoupledRegistrar
{
- [PreserveSig] int Register_([In] int flags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext context, [In][MarshalAs(UnmanagedType.LPWStr)] string user, [In][MarshalAs(UnmanagedType.LPWStr)] string locale, [In][MarshalAs(UnmanagedType.LPWStr)] string scope, [In][MarshalAs(UnmanagedType.LPWStr)] string registration, [In][MarshalAs(UnmanagedType.IUnknown)] object unknown);
+ [PreserveSig] int Register_([In] int flags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext context, [In][MarshalAs(UnmanagedType.LPWStr)] string user, [In][MarshalAs(UnmanagedType.LPWStr)] string locale, [In][MarshalAs(UnmanagedType.LPWStr)] string scope, [In][MarshalAs(UnmanagedType.LPWStr)] string registration, [In][MarshalAs(UnmanagedType.IUnknown)] object unknown);
[PreserveSig] int UnRegister_();
}
[ComImport]
internal interface IWbemEventSink
{
- [PreserveSig] int Indicate_([In] int lObjectCount, [In][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal apObjArray);
- [PreserveSig] int SetStatus_([In] int lFlags, [In][MarshalAs(UnmanagedType.Error)] int hResult, [In][MarshalAs(UnmanagedType.BStr)] string strParam, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pObjParam);
- [PreserveSig] int IndicateWithSD_([In] int lNumObjects, [In][MarshalAs(UnmanagedType.IUnknown)] ref object apObjects, [In] int lSDLength, [In] ref byte pSD);
+ [PreserveSig] int Indicate_([In] int lObjectCount, [In][MarshalAs(UnmanagedType.Interface)] ref IWbemClassObject_DoNotMarshal apObjArray);
+ [PreserveSig] int SetStatus_([In] int lFlags, [In][MarshalAs(UnmanagedType.Error)] int hResult, [In][MarshalAs(UnmanagedType.BStr)] string strParam, [In][MarshalAs(UnmanagedType.Interface)] IWbemClassObject_DoNotMarshal pObjParam);
+ [PreserveSig] int IndicateWithSD_([In] int lNumObjects, [In][MarshalAs(UnmanagedType.IUnknown)] ref object apObjects, [In] int lSDLength, [In] ref byte pSD);
[PreserveSig] int SetSinkSecurity_([In] int lSDLength, [In] ref byte pSD);
[PreserveSig] int IsActive_();
- [PreserveSig] int GetRestrictedSink_([In] int lNumQueries, [In][MarshalAs(UnmanagedType.LPWStr)] ref string awszQueries, [In][MarshalAs(UnmanagedType.IUnknown)] object pCallback, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemEventSink ppSink);
+ [PreserveSig] int GetRestrictedSink_([In] int lNumQueries, [In][MarshalAs(UnmanagedType.LPWStr)] ref string awszQueries, [In][MarshalAs(UnmanagedType.IUnknown)] object pCallback, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemEventSink ppSink);
[PreserveSig] int SetBatchingParameters_([In] int lFlags, [In] uint dwMaxBufferSize, [In] uint dwMaxSendLatency);
}
internal interface IWbemPathKeyList
{
[PreserveSig] int GetCount_([Out] out uint puKeyCount);
- [PreserveSig] int SetKey_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] uint uFlags, [In] uint uCimType, [In] IntPtr pKeyVal);
- [PreserveSig] int SetKey2_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] uint uFlags, [In] uint uCimType, [In] ref object pKeyVal);
- [PreserveSig] int GetKey_([In] uint uKeyIx, [In] uint uFlags, [In][Out] ref uint puNameBufSize, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 2)] char[] pszKeyName, [In][Out] ref uint puKeyValBufSize, [In][Out] IntPtr pKeyVal, [Out] out uint puApparentCimType);
- [PreserveSig] int GetKey2_([In] uint uKeyIx, [In] uint uFlags, [In][Out] ref uint puNameBufSize, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 2)] char[] pszKeyName, [In][Out] ref object pKeyValue, [Out] out uint puApparentCimType);
- [PreserveSig] int RemoveKey_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] uint uFlags);
+ [PreserveSig] int SetKey_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] uint uFlags, [In] uint uCimType, [In] IntPtr pKeyVal);
+ [PreserveSig] int SetKey2_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] uint uFlags, [In] uint uCimType, [In] ref object pKeyVal);
+ [PreserveSig] int GetKey_([In] uint uKeyIx, [In] uint uFlags, [In][Out] ref uint puNameBufSize, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 2)] char[] pszKeyName, [In][Out] ref uint puKeyValBufSize, [In][Out] IntPtr pKeyVal, [Out] out uint puApparentCimType);
+ [PreserveSig] int GetKey2_([In] uint uKeyIx, [In] uint uFlags, [In][Out] ref uint puNameBufSize, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 2)] char[] pszKeyName, [In][Out] ref object pKeyValue, [Out] out uint puApparentCimType);
+ [PreserveSig] int RemoveKey_([In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] uint uFlags);
[PreserveSig] int RemoveAllKeys_([In] uint uFlags);
[PreserveSig] int MakeSingleton_([In] sbyte bSet);
[PreserveSig] int GetInfo_([In] uint uRequestedInfo, [Out] out ulong puResponse);
- [PreserveSig] int GetText_([In] int lFlags, [In][Out] ref uint puBuffLength, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 1)] char[] pszText);
+ [PreserveSig] int GetText_([In] int lFlags, [In][Out] ref uint puBuffLength, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 1)] char[] pszText);
}
[GuidAttribute("3BC15AF2-736C-477E-9E51-238AF8667DCC")]
[ComImport]
internal interface IWbemPath
{
- [PreserveSig] int SetText_([In] uint uMode, [In][MarshalAs(UnmanagedType.LPWStr)] string pszPath);
- [PreserveSig] int GetText_([In] int lFlags, [In][Out] ref uint puBuffLength, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 1)] char[] pszText);
+ [PreserveSig] int SetText_([In] uint uMode, [In][MarshalAs(UnmanagedType.LPWStr)] string pszPath);
+ [PreserveSig] int GetText_([In] int lFlags, [In][Out] ref uint puBuffLength, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 1)] char[] pszText);
[PreserveSig] int GetInfo_([In] uint uRequestedInfo, [Out] out ulong puResponse);
- [PreserveSig] int SetServer_([In][MarshalAs(UnmanagedType.LPWStr)] string Name);
- [PreserveSig] int GetServer_([In][Out] ref uint puNameBufLength, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 0)] char[] pName);
+ [PreserveSig] int SetServer_([In][MarshalAs(UnmanagedType.LPWStr)] string Name);
+ [PreserveSig] int GetServer_([In][Out] ref uint puNameBufLength, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 0)] char[] pName);
[PreserveSig] int GetNamespaceCount_([Out] out uint puCount);
- [PreserveSig] int SetNamespaceAt_([In] uint uIndex, [In][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 0)] char[] pszName);
- [PreserveSig] int GetNamespaceAt_([In] uint uIndex, [In][Out] ref uint puNameBufLength, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 1)] char[] pName);
+ [PreserveSig] int SetNamespaceAt_([In] uint uIndex, [In][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 0)] char[] pszName);
+ [PreserveSig] int GetNamespaceAt_([In] uint uIndex, [In][Out] ref uint puNameBufLength, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 1)] char[] pName);
[PreserveSig] int RemoveNamespaceAt_([In] uint uIndex);
[PreserveSig] int RemoveAllNamespaces_();
[PreserveSig] int GetScopeCount_([Out] out uint puCount);
- [PreserveSig] int SetScope_([In] uint uIndex, [In][MarshalAs(UnmanagedType.LPWStr)] string pszClass);
- [PreserveSig] int SetScopeFromText_([In] uint uIndex, [In][MarshalAs(UnmanagedType.LPWStr)] string pszText);
- [PreserveSig] int GetScope_([In] uint uIndex, [In][Out] ref uint puClassNameBufSize, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 1)] char[] pszClass, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemPathKeyList pKeyList);
- [PreserveSig] int GetScopeAsText_([In] uint uIndex, [In][Out] ref uint puTextBufSize, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 1)] char[] pszText);
+ [PreserveSig] int SetScope_([In] uint uIndex, [In][MarshalAs(UnmanagedType.LPWStr)] string pszClass);
+ [PreserveSig] int SetScopeFromText_([In] uint uIndex, [In][MarshalAs(UnmanagedType.LPWStr)] string pszText);
+ [PreserveSig] int GetScope_([In] uint uIndex, [In][Out] ref uint puClassNameBufSize, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 1)] char[] pszClass, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemPathKeyList pKeyList);
+ [PreserveSig] int GetScopeAsText_([In] uint uIndex, [In][Out] ref uint puTextBufSize, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 1)] char[] pszText);
[PreserveSig] int RemoveScope_([In] uint uIndex);
[PreserveSig] int RemoveAllScopes_();
- [PreserveSig] int SetClassName_([In][MarshalAs(UnmanagedType.LPWStr)] string Name);
- [PreserveSig] int GetClassName_([In][Out] ref uint puBuffLength, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 0)] char[] pszName);
- [PreserveSig] int GetKeyList_([Out][MarshalAs(UnmanagedType.Interface)] out IWbemPathKeyList pOut);
- [PreserveSig] int CreateClassPart_([In] int lFlags, [In][MarshalAs(UnmanagedType.LPWStr)] string Name);
+ [PreserveSig] int SetClassName_([In][MarshalAs(UnmanagedType.LPWStr)] string Name);
+ [PreserveSig] int GetClassName_([In][Out] ref uint puBuffLength, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 0)] char[] pszName);
+ [PreserveSig] int GetKeyList_([Out][MarshalAs(UnmanagedType.Interface)] out IWbemPathKeyList pOut);
+ [PreserveSig] int CreateClassPart_([In] int lFlags, [In][MarshalAs(UnmanagedType.LPWStr)] string Name);
[PreserveSig] int DeleteClassPart_([In] int lFlags);
- [PreserveSig] int IsRelative_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMachine, [In][MarshalAs(UnmanagedType.LPWStr)] string wszNamespace);
- [PreserveSig] int IsRelativeOrChild_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMachine, [In][MarshalAs(UnmanagedType.LPWStr)] string wszNamespace, [In] int lFlags);
- [PreserveSig] int IsLocal_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMachine);
- [PreserveSig] int IsSameClassName_([In][MarshalAs(UnmanagedType.LPWStr)] string wszClass);
+ [PreserveSig] int IsRelative_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMachine, [In][MarshalAs(UnmanagedType.LPWStr)] string wszNamespace);
+ [PreserveSig] int IsRelativeOrChild_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMachine, [In][MarshalAs(UnmanagedType.LPWStr)] string wszNamespace, [In] int lFlags);
+ [PreserveSig] int IsLocal_([In][MarshalAs(UnmanagedType.LPWStr)] string wszMachine);
+ [PreserveSig] int IsSameClassName_([In][MarshalAs(UnmanagedType.LPWStr)] string wszClass);
}
#endregion
ndx = reqList.Add(myReq);
- if ( evtGo.Set() == false )
+ if (evtGo.Set() == false)
{
reqList.RemoveAt(ndx);
throw new ManagementException(SR.WorkerThreadWakeupFailed);
public static bool IsNoContextMTA()
{
// If the runtime says we are not an MTA thread, we'll trust it and return false
- if (Thread.CurrentThread.GetApartmentState() != ApartmentState.MTA)
+ if (Thread.CurrentThread.GetApartmentState() != ApartmentState.MTA)
return false;
// We know that 'ApartmentState' says we are MTA
// If we are on Win2k or above, we are OK
// - Platform == Win32NT and OS version >= 5.0.0.0
OperatingSystem os = Environment.OSVersion;
- if (os.Platform==PlatformID.Win32NT && os.Version >= new Version(5, 0))
+ if (os.Platform == PlatformID.Win32NT && os.Version >= new Version(5, 0))
return true;
return false;
}
internal class ThreadDispatch
{
#region Private fields
- private Thread thread;
- private Exception exception; // Exception thrown from worker method (if any). Exposed as property.
- private ThreadWorkerMethodWithReturn threadWorkerMethodWithReturn; // Delegate to be called for worker method with return value
- private ThreadWorkerMethodWithReturnAndParam threadWorkerMethodWithReturnAndParam; // Delegate to be called for worker method with return value and parameter
- private ThreadWorkerMethod threadWorkerMethod; // Delegate to be called for worker method
- private ThreadWorkerMethodWithParam threadWorkerMethodWithParam; // Delegate to be called for worker method with parameter
- private object threadReturn; // Return data from worker method.
- private object threadParams; // Parameters to be passed to worker method
- private bool backgroundThread; // Is this a background thread?
- private ApartmentState apartmentType; // Apartment type of thread
+ private Thread thread;
+ private Exception exception; // Exception thrown from worker method (if any). Exposed as property.
+ private ThreadWorkerMethodWithReturn threadWorkerMethodWithReturn; // Delegate to be called for worker method with return value
+ private ThreadWorkerMethodWithReturnAndParam threadWorkerMethodWithReturnAndParam; // Delegate to be called for worker method with return value and parameter
+ private ThreadWorkerMethod threadWorkerMethod; // Delegate to be called for worker method
+ private ThreadWorkerMethodWithParam threadWorkerMethodWithParam; // Delegate to be called for worker method with parameter
+ private object threadReturn; // Return data from worker method.
+ private object threadParams; // Parameters to be passed to worker method
+ private bool backgroundThread; // Is this a background thread?
+ private ApartmentState apartmentType; // Apartment type of thread
#endregion
#region Properties
/// <summary>
/// Delegate declaration representing signature of worker method with return value.
/// </summary>
- public delegate object ThreadWorkerMethodWithReturn ( );
+ public delegate object ThreadWorkerMethodWithReturn();
/// <summary>
/// Delegate declaration representing signature of worker method with return value and parameter.
/// </summary>
- public delegate object ThreadWorkerMethodWithReturnAndParam ( object param );
+ public delegate object ThreadWorkerMethodWithReturnAndParam(object param);
/// <summary>
/// Delegate declaration representing signature of worker method with no return value and no parameter
/// </summary>
- public delegate void ThreadWorkerMethod ( );
+ public delegate void ThreadWorkerMethod();
/// <summary>
/// Delegate declaration representing signature of worker method with parameter.
/// </summary>
- public delegate void ThreadWorkerMethodWithParam ( object param );
+ public delegate void ThreadWorkerMethodWithParam(object param);
#endregion
#region Public methods
/// 3. Background thread status will be false
/// </summary>
/// <param name="workerMethod">Delegate to be called to perform the work</param>
- public ThreadDispatch ( ThreadWorkerMethodWithReturn workerMethod ) : this ( )
+ public ThreadDispatch(ThreadWorkerMethodWithReturn workerMethod) : this()
{
- InitializeThreadState ( null, workerMethod, ApartmentState.MTA, false );
+ InitializeThreadState(null, workerMethod, ApartmentState.MTA, false);
}
/// <summary>
/// 3. Background thread status will be false
/// </summary>
/// <param name="workerMethod">Delegate to be called to perform the work</param>
- public ThreadDispatch ( ThreadWorkerMethodWithReturnAndParam workerMethod ) : this ( )
+ public ThreadDispatch(ThreadWorkerMethodWithReturnAndParam workerMethod) : this()
{
- InitializeThreadState ( null, workerMethod, ApartmentState.MTA, false );
+ InitializeThreadState(null, workerMethod, ApartmentState.MTA, false);
}
/// <summary>
/// 3. Background thread status will be false
/// </summary>
/// <param name="workerMethod">Delegate to be called to perform the work</param>
- public ThreadDispatch ( ThreadWorkerMethodWithParam workerMethod ) : this ( )
+ public ThreadDispatch(ThreadWorkerMethodWithParam workerMethod) : this()
{
- InitializeThreadState ( null, workerMethod, ApartmentState.MTA, false );
+ InitializeThreadState(null, workerMethod, ApartmentState.MTA, false);
}
/// <summary>
/// 3. Background thread status will be false
/// </summary>
/// <param name="workerMethod">Delegate to be called to perform the work</param>
- public ThreadDispatch ( ThreadWorkerMethod workerMethod ) : this ( )
+ public ThreadDispatch(ThreadWorkerMethod workerMethod) : this()
{
- InitializeThreadState ( null, workerMethod, ApartmentState.MTA, false );
+ InitializeThreadState(null, workerMethod, ApartmentState.MTA, false);
}
/// <summary>
/// Starts the thread execution and waits for thread to finish. If an exception occurs in the worker method
/// this method rethrows the exception.
/// </summary>
- public void Start ( )
+ public void Start()
{
this.exception = null;
DispatchThread();
- if ( this.Exception != null )
+ if (this.Exception != null)
{
throw this.Exception;
}
/// Initializes the ThreadDispatch instance with initial values. Note that this constructor is private to avoid
/// declaring instances without specifying at least a worker delegate instance.
/// </summary>
- private ThreadDispatch ( )
+ private ThreadDispatch()
{
- this.thread = null;
- this.exception = null;
- this.threadParams = null;
- this.threadWorkerMethodWithReturn = null;
+ this.thread = null;
+ this.exception = null;
+ this.threadParams = null;
+ this.threadWorkerMethodWithReturn = null;
this.threadWorkerMethodWithReturnAndParam = null;
- this.threadWorkerMethod = null;
- this.threadWorkerMethodWithParam = null;
- this.threadReturn = null;
- this.backgroundThread = false;
- this.apartmentType = ApartmentState.MTA;
+ this.threadWorkerMethod = null;
+ this.threadWorkerMethodWithParam = null;
+ this.threadReturn = null;
+ this.backgroundThread = false;
+ this.apartmentType = ApartmentState.MTA;
}
/// <summary>
/// <param name="workerMethod">The delegate to be called from thread</param>
/// <param name="aptState">The apartment of the thread created</param>
/// <param name="background">Thread is created as a background or not</param>
- private void InitializeThreadState ( object threadParams, ThreadWorkerMethodWithReturn workerMethod, ApartmentState aptState, bool background )
+ private void InitializeThreadState(object threadParams, ThreadWorkerMethodWithReturn workerMethod, ApartmentState aptState, bool background)
{
this.threadParams = threadParams;
- this.threadWorkerMethodWithReturn = workerMethod;
- this.thread = new Thread ( new ThreadStart ( ThreadEntryPointMethodWithReturn ) );
+ this.threadWorkerMethodWithReturn = workerMethod;
+ this.thread = new Thread(new ThreadStart(ThreadEntryPointMethodWithReturn));
this.thread.SetApartmentState(aptState);
this.backgroundThread = background;
}
/// <param name="workerMethod">The delegate to be called from thread</param>
/// <param name="aptState">The apartment of the thread created</param>
/// <param name="background">Thread is created as a background or not</param>
- private void InitializeThreadState ( object threadParams, ThreadWorkerMethodWithReturnAndParam workerMethod, ApartmentState aptState, bool background )
+ private void InitializeThreadState(object threadParams, ThreadWorkerMethodWithReturnAndParam workerMethod, ApartmentState aptState, bool background)
{
this.threadParams = threadParams;
this.threadWorkerMethodWithReturnAndParam = workerMethod;
- this.thread = new Thread ( new ThreadStart ( ThreadEntryPointMethodWithReturnAndParam ) );
+ this.thread = new Thread(new ThreadStart(ThreadEntryPointMethodWithReturnAndParam));
this.thread.SetApartmentState(aptState);
this.backgroundThread = background;
}
/// <param name="workerMethod">The delegate to be called from thread</param>
/// <param name="aptState">The apartment of the thread created</param>
/// <param name="background">Thread is created as a background or not</param>
- private void InitializeThreadState ( object threadParams, ThreadWorkerMethod workerMethod, ApartmentState aptState, bool background )
+ private void InitializeThreadState(object threadParams, ThreadWorkerMethod workerMethod, ApartmentState aptState, bool background)
{
this.threadParams = threadParams;
- this.threadWorkerMethod = workerMethod;
- this.thread = new Thread ( new ThreadStart ( ThreadEntryPoint ) );
- this.thread.SetApartmentState(aptState );
+ this.threadWorkerMethod = workerMethod;
+ this.thread = new Thread(new ThreadStart(ThreadEntryPoint));
+ this.thread.SetApartmentState(aptState);
this.backgroundThread = background;
}
/// <param name="workerMethod">The delegate to be called from thread</param>
/// <param name="aptState">The apartment of the thread created</param>
/// <param name="background">Thread is created as a background or not</param>
- private void InitializeThreadState ( object threadParams, ThreadWorkerMethodWithParam workerMethod, ApartmentState aptState, bool background )
+ private void InitializeThreadState(object threadParams, ThreadWorkerMethodWithParam workerMethod, ApartmentState aptState, bool background)
{
this.threadParams = threadParams;
this.threadWorkerMethodWithParam = workerMethod;
- this.thread = new Thread ( new ThreadStart ( ThreadEntryPointMethodWithParam ) );
- this.thread.SetApartmentState( aptState );
+ this.thread = new Thread(new ThreadStart(ThreadEntryPointMethodWithParam));
+ this.thread.SetApartmentState(aptState);
this.backgroundThread = background;
}
/// <summary>
/// Starts the execution of the thread and waits until the threadFinished event is signaled before continuing
/// </summary>
- private void DispatchThread ( )
+ private void DispatchThread()
{
this.thread.Start();
this.thread.Join();
/// exceptions thrown from the worker method and re-throws the exception.
/// The worker method for this thread entry point has no parameter and no return value.
/// </summary>
- private void ThreadEntryPoint ( )
+ private void ThreadEntryPoint()
{
try
{
/// The worker method for this thread entry point takes a parameter and no return value.
/// </summary>
- private void ThreadEntryPointMethodWithParam ( )
+ private void ThreadEntryPointMethodWithParam()
{
try
{
- this.threadWorkerMethodWithParam ( this.threadParams );
+ this.threadWorkerMethodWithParam(this.threadParams);
}
catch (Exception e)
{
/// The worker method for this thread entry point has no parameter but does return a value.
/// </summary>
- private void ThreadEntryPointMethodWithReturn ( )
+ private void ThreadEntryPointMethodWithReturn()
{
try
{
/// The worker method for this thread entry point has a parameter and return value.
/// </summary>
- private void ThreadEntryPointMethodWithReturnAndParam ( )
+ private void ThreadEntryPointMethodWithReturnAndParam()
{
try
{
return new ManagementBaseObject(theClone);
}
- internal virtual void Initialize ( bool getObject ) {}
+ internal virtual void Initialize(bool getObject) { }
//
//Properties
{
get
{
- Initialize ( true );
+ Initialize(true);
if (properties == null)
properties = new PropertyDataCollection(this, false);
{
get
{
- Initialize ( false );
+ Initialize(false);
if (systemProperties == null)
systemProperties = new PropertyDataCollection(this, true);
{
get
{
- Initialize ( true );
+ Initialize(true);
if (qualifiers == null)
qualifiers = new QualifierDataCollection(this);
get { return GetPropertyValue(propertyName); }
set
{
- Initialize ( true );
+ Initialize(true);
try
{
- SetPropertyValue (propertyName, value);
+ SetPropertyValue(propertyName, value);
}
catch (COMException e)
{
public object GetPropertyValue(string propertyName)
{
if (null == propertyName)
- throw new ArgumentNullException (nameof(propertyName));
+ throw new ArgumentNullException(nameof(propertyName));
// Check for system properties
- if (propertyName.StartsWith ("__", StringComparison.Ordinal))
+ if (propertyName.StartsWith("__", StringComparison.Ordinal))
return SystemProperties[propertyName].Value;
else
return Properties[propertyName].Value;
/// </returns>
public object GetQualifierValue(string qualifierName)
{
- return Qualifiers [qualifierName].Value;
+ return Qualifiers[qualifierName].Value;
}
//******************************************************
/// <param name='qualifierValue'>The value to set.</param>
public void SetQualifierValue(string qualifierName, object qualifierValue)
{
- Qualifiers [qualifierName].Value = qualifierValue;
+ Qualifiers[qualifierName].Value = qualifierValue;
}
//
switch (format)
{
- case TextFormat.Mof :
+ case TextFormat.Mof:
status = wbemObject.GetObjectText_(0, out objText);
return objText;
- case TextFormat.CimDtd20 :
- case TextFormat.WmiDtd20 :
+ case TextFormat.CimDtd20:
+ case TextFormat.WmiDtd20:
//This may throw on non-XP platforms... - should we catch ?
IWbemObjectTextSrc wbemTextSrc = (IWbemObjectTextSrc)new WbemObjectTextSrc();
{
if (obj is ManagementBaseObject)
{
- result = CompareTo ((ManagementBaseObject)obj, ComparisonSettings.IncludeAll);
+ result = CompareTo((ManagementBaseObject)obj, ComparisonSettings.IncludeAll);
}
else
{
public bool CompareTo(ManagementBaseObject otherObject, ComparisonSettings settings)
{
if (null == otherObject)
- throw new ArgumentNullException (nameof(otherObject));
+ throw new ArgumentNullException(nameof(otherObject));
bool result = false;
if (null != wbemObject)
{
- int status = (int) ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
- status = wbemObject.CompareTo_((int) settings, otherObject.wbemObject);
+ status = wbemObject.CompareTo_((int)settings, otherObject.wbemObject);
if ((int)ManagementStatus.Different == status)
result = false;
int dummy1 = 0, dummy2 = 0;
int status = (int)ManagementStatus.NoError;
- status = wbemObject.Get_ ("__CLASS", 0, ref val, ref dummy1, ref dummy2);
+ status = wbemObject.Get_("__CLASS", 0, ref val, ref dummy1, ref dummy2);
if (status < 0)
{
if (val is System.DBNull)
return string.Empty;
else
- return ((string) val);
+ return ((string)val);
}
}
/// </summary>
/// <param name='propertyName'>The name of the property to be changed.</param>
/// <param name='propertyValue'>The new value for this property.</param>
- public void SetPropertyValue (
+ public void SetPropertyValue(
string propertyName,
object propertyValue)
{
if (null == propertyName)
- throw new ArgumentNullException (nameof(propertyName));
+ throw new ArgumentNullException(nameof(propertyName));
// Check for system properties
- if (propertyName.StartsWith ("__", StringComparison.Ordinal))
+ if (propertyName.StartsWith("__", StringComparison.Ordinal))
SystemProperties[propertyName].Value = propertyValue;
else
Properties[propertyName].Value = propertyValue;
/// <code lang='VB'>Dim c As New ManagementClass()
/// </code>
/// </example>
- public ManagementClass() : this ((ManagementScope)null, (ManagementPath)null, null) {}
+ public ManagementClass() : this((ManagementScope)null, (ManagementPath)null, null) { }
//parameterized constructors
/// <summary>
/// New ManagementPath("Win32_LogicalDisk"))
/// </code>
/// </example>
- public ManagementClass(ManagementPath path) : this(null, path, null) {}
+ public ManagementClass(ManagementPath path) : this(null, path, null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class initialized to the given path.</para>
/// <code lang='VB'>Dim c As New ManagementClass("Win32_LogicalDisk")
/// </code>
/// </example>
- public ManagementClass(string path) : this(null, new ManagementPath(path), null) {}
+ public ManagementClass(string path) : this(null, new ManagementPath(path), null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class initialized to the
/// Dim c As New ManagementClass(p,o)
/// </code>
/// </example>
- public ManagementClass(ManagementPath path, ObjectGetOptions options) : this(null, path, options) {}
+ public ManagementClass(ManagementPath path, ObjectGetOptions options) : this(null, path, options) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class initialized to the given WMI class path
/// </code>
/// </example>
public ManagementClass(string path, ObjectGetOptions options)
- : this(null, new ManagementPath(path), options) {}
+ : this(null, new ManagementPath(path), options) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class for the specified
/// </code>
/// </example>
public ManagementClass(ManagementScope scope, ManagementPath path, ObjectGetOptions options)
- : base (scope, path, options) {}
+ : base(scope, path, options) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class for the specified WMI class, in the
/// </code>
/// </example>
public ManagementClass(string scope, string path, ObjectGetOptions options)
- : base (new ManagementScope(scope), new ManagementPath(path), options) {}
+ : base(new ManagementScope(scope), new ManagementPath(path), options) { }
protected ManagementClass(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
if (null != val)
- result.AddRange((string [])val);
+ result.AddRange((string[])val);
return result;
}
{
get
{
- Initialize ( true );
+ Initialize(true);
if (methods == null)
methods = new MethodDataCollection(this);
if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length))
throw new InvalidOperationException();
- Initialize ( false );
+ Initialize(false);
IEnumWbemClassObject enumWbem = null;
EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone();
o.EnsureLocatable = false; o.PrototypeOnly = false;
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
try
{
securityHandler = Scope.GetSecurityHandler();
- status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices() ).CreateInstanceEnum_(ClassName,
- o.Flags,
- o.GetContext(),
- ref enumWbem
- );
+ status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).CreateInstanceEnum_(
+ ClassName, o.Flags, o.GetContext(), ref enumWbem);
}
finally
{
if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length))
throw new InvalidOperationException();
- Initialize ( false );
+ Initialize(false);
EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone();
WmiEventSink sink = watcher.GetNewSink(Scope, o.Context);
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
securityHandler = Scope.GetSecurityHandler();
- status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices() ).CreateInstanceEnumAsync_(
- ClassName,
- o.Flags,
- o.GetContext(),
- sink.Stub );
+ status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).CreateInstanceEnumAsync_(
+ ClassName, o.Flags, o.GetContext(), sink.Stub);
if (securityHandler != null)
- securityHandler.Reset();
+ securityHandler.Reset();
if (status < 0)
{
if (null == Path)
throw new InvalidOperationException();
- Initialize ( false );
+ Initialize(false);
IEnumWbemClassObject enumWbem = null;
EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone();
o.EnsureLocatable = false; o.PrototypeOnly = false;
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
try
{
securityHandler = Scope.GetSecurityHandler();
- status = scope.GetSecuredIWbemServicesHandler( Scope.GetIWbemServices() ).CreateClassEnum_(ClassName,
- o.Flags,
- o.GetContext(),
- ref enumWbem);
+ status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).CreateClassEnum_(
+ ClassName, o.Flags, o.GetContext(), ref enumWbem);
}
finally
{
if (null == Path)
throw new InvalidOperationException();
- Initialize ( false );
+ Initialize(false);
EnumerationOptions o = (null == options) ? new EnumerationOptions() :
(EnumerationOptions)options.Clone();
WmiEventSink sink = watcher.GetNewSink(Scope, o.Context);
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
securityHandler = Scope.GetSecurityHandler();
- status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices() ).CreateClassEnumAsync_(ClassName,
- o.Flags,
- o.GetContext(),
- sink.Stub);
+ status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).CreateClassEnumAsync_(
+ ClassName, o.Flags, o.GetContext(), sink.Stub);
if (securityHandler != null)
if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length))
throw new InvalidOperationException();
- Initialize ( false );
+ Initialize(false);
IEnumWbemClassObject enumWbem = null;
//Ensure EnumerateDeep flag bit is turned off as it's invalid for queries
o.EnumerateDeep = true;
- RelatedObjectQuery q = new RelatedObjectQuery(true, Path.Path,
+ RelatedObjectQuery q = new RelatedObjectQuery(true, Path.Path,
relatedClass,
relationshipClass,
relatedQualifier,
relatedRole, thisRole);
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
try
{
securityHandler = Scope.GetSecurityHandler();
- status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices() ).ExecQuery_(
+ status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecQuery_(
q.QueryLanguage,
q.QueryString,
o.Flags,
if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length))
throw new InvalidOperationException();
- Initialize ( true );
+ Initialize(true);
if (null == watcher)
throw new ArgumentNullException(nameof(watcher));
relatedRole, thisRole);
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
securityHandler = Scope.GetSecurityHandler();
- status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices() ).ExecQueryAsync_(
- q.QueryLanguage,
- q.QueryString,
- o.Flags,
- o.GetContext(),
- sink.Stub);
+ status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecQueryAsync_(
+ q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), sink.Stub);
if (securityHandler != null)
if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length))
throw new InvalidOperationException();
- Initialize ( false );
+ Initialize(false);
IEnumWbemClassObject enumWbem = null;
relationshipQualifier, thisRole);
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
//Execute WMI query
try
{
securityHandler = Scope.GetSecurityHandler();
- status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices() ).ExecQuery_(
- q.QueryLanguage,
- q.QueryString,
- o.Flags,
- o.GetContext(),
- ref enumWbem);
+ status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecQuery_(
+ q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), ref enumWbem);
}
finally
throw new ArgumentNullException(nameof(watcher));
else
{
- Initialize ( true );
+ Initialize(true);
EnumerationOptions o =
(null != options) ? (EnumerationOptions)options.Clone() : new EnumerationOptions();
relationshipQualifier, thisRole);
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
securityHandler = Scope.GetSecurityHandler();
- status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecQueryAsync_(
- q.QueryLanguage,
- q.QueryString,
- o.Flags,
- o.GetContext(),
- sink.Stub);
+ status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecQueryAsync_(
+ q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), sink.Stub);
if (securityHandler != null)
tempString = dmtf.Substring(15, 6);
if (("******" != tempString))
{
- ticks = (long.Parse(tempString, (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long)))) * (TimeSpan.TicksPerMillisecond/1000);
+ ticks = (long.Parse(tempString, (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long)))) * (TimeSpan.TicksPerMillisecond / 1000);
}
tempString = dmtf.Substring(22, 3);
if (("***" != tempString))
utcOffset = int.Parse(tempString, frmInt32);
}
- if ( year < 0 || month < 0 || day < 0 || hour < 0 || minute < 0 || second < 0 || ticks < 0)
+ if (year < 0 || month < 0 || day < 0 || hour < 0 || minute < 0 || second < 0 || ticks < 0)
{
throw new ArgumentOutOfRangeException(nameof(dmtfDate));
}
else
{
string strTemp = OffsetMins.ToString(frmInt32);
- UtcString = "-" + strTemp.Substring(1, strTemp.Length-1).PadLeft(3, '0');
+ UtcString = "-" + strTemp.Substring(1, strTemp.Length - 1).PadLeft(3, '0');
}
string dmtfDateTime = date.Year.ToString(frmInt32).PadLeft(4, '0');
// Construct a DateTime with the precision to Second as same as the passed DateTime and so get
// the ticks difference so that the microseconds can be calculated
DateTime dtTemp = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0);
- long microsec = ((date.Ticks-dtTemp.Ticks) * 1000) / System.TimeSpan.TicksPerMillisecond;
+ long microsec = ((date.Ticks - dtTemp.Ticks) * 1000) / System.TimeSpan.TicksPerMillisecond;
// fill the microseconds field
string strMicrosec = microsec.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long)));
seconds = int.Parse(tempString, frmInt32);
tempString = dmtfts.Substring(15, 6);
- ticks = (long.Parse(tempString, (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long)))) * (System.TimeSpan.TicksPerMillisecond/1000);
+ ticks = (long.Parse(tempString, (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long)))) * (System.TimeSpan.TicksPerMillisecond / 1000);
}
catch
throw new System.ArgumentOutOfRangeException(nameof(dmtfTimespan));
}
- if ( days < 0 || hours < 0 || minutes < 0 || seconds < 0 || ticks < 0 )
+ if (days < 0 || hours < 0 || minutes < 0 || seconds < 0 || ticks < 0)
{
throw new System.ArgumentOutOfRangeException(nameof(dmtfTimespan));
}
// Construct a DateTime with the precision to Second as same as the passed DateTime and so get
// the ticks difference so that the microseconds can be calculated
TimeSpan tsTemp = new TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0);
- long microsec = ((timespan.Ticks-tsTemp.Ticks) * 1000) / System.TimeSpan.TicksPerMillisecond;
+ long microsec = ((timespan.Ticks - tsTemp.Ticks) * 1000) / System.TimeSpan.TicksPerMillisecond;
// fill the microseconds field
string strMicrosec = microsec.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(long)));
namespace System.Management
{
-internal class IdentifierChangedEventArgs : EventArgs
-{
- internal IdentifierChangedEventArgs () {}
-}
-
-internal class InternalObjectPutEventArgs : EventArgs
-{
- private readonly ManagementPath path;
-
- internal InternalObjectPutEventArgs (ManagementPath path)
+ internal class IdentifierChangedEventArgs : EventArgs
{
- this.path = path.Clone();
+ internal IdentifierChangedEventArgs() { }
}
- internal ManagementPath Path {
- get { return path; }
- }
-}
-
-
- /// <summary>
- /// <para>Represents the virtual base class to hold event data for WMI events.</para>
- /// </summary>
-public abstract class ManagementEventArgs : EventArgs
-{
- private readonly object context;
+ internal class InternalObjectPutEventArgs : EventArgs
+ {
+ private readonly ManagementPath path;
- /// <summary>
- /// Constructor. This is not callable directly by applications.
- /// </summary>
- /// <param name="context">The operation context which is echoed back
- /// from the operation which trigerred the event.</param>
- internal ManagementEventArgs (object context) {
- this.context = context;
- }
+ internal InternalObjectPutEventArgs(ManagementPath path)
+ {
+ this.path = path.Clone();
+ }
- /// <summary>
- /// <para> Gets the operation context echoed back
- /// from the operation that triggered the event.</para>
- /// </summary>
- /// <value>
- /// A WMI context object containing
- /// context information provided by the operation that triggered the event.
- /// </value>
- public object Context { get { return context; }
+ internal ManagementPath Path
+ {
+ get { return path; }
+ }
}
-}
-/// <summary>
-/// <para>Holds event data for the <see cref='System.Management.ManagementOperationObserver.ObjectReady'/> event.</para>
-/// </summary>
-public class ObjectReadyEventArgs : ManagementEventArgs
-{
- private readonly ManagementBaseObject wmiObject;
/// <summary>
- /// Constructor.
+ /// <para>Represents the virtual base class to hold event data for WMI events.</para>
/// </summary>
- /// <param name="context">The operation context which is echoed back
- /// from the operation which triggerred the event.</param>
- /// <param name="wmiObject">The newly arrived WmiObject.</param>
- internal ObjectReadyEventArgs (
- object context,
- ManagementBaseObject wmiObject
- ) : base (context)
+ public abstract class ManagementEventArgs : EventArgs
{
- this.wmiObject = wmiObject;
- }
+ private readonly object context;
- /// <summary>
- /// <para> Gets the newly-returned object.</para>
- /// </summary>
- /// <value>
- /// <para>A <see cref='System.Management.ManagementBaseObject'/> representing the
- /// newly-returned object.</para>
- /// </value>
- public ManagementBaseObject NewObject
- {
- get {
- return wmiObject;
+ /// <summary>
+ /// Constructor. This is not callable directly by applications.
+ /// </summary>
+ /// <param name="context">The operation context which is echoed back
+ /// from the operation which trigerred the event.</param>
+ internal ManagementEventArgs(object context)
+ {
+ this.context = context;
}
- }
-}
-/// <summary>
-/// <para> Holds event data for the <see cref='System.Management.ManagementOperationObserver.Completed'/> event.</para>
-/// </summary>
-public class CompletedEventArgs : ManagementEventArgs
-{
- private readonly int status;
- private readonly ManagementBaseObject wmiObject;
-
- /// <summary>
- /// Constructor.
- /// </summary>
- /// <param name="context">The operation context which is echoed back
- /// from the operation which trigerred the event.</param>
- /// <param name="status">The completion status of the operation.</param>
- /// <param name="wmiStatusObject">Additional status information
- /// encapsulated within a WmiObject. This may be null.</param>
- internal CompletedEventArgs (
- object context,
- int status,
- ManagementBaseObject wmiStatusObject
- ) : base (context)
- {
- wmiObject = wmiStatusObject;
- this.status = status;
+ /// <summary>
+ /// <para> Gets the operation context echoed back
+ /// from the operation that triggered the event.</para>
+ /// </summary>
+ /// <value>
+ /// A WMI context object containing
+ /// context information provided by the operation that triggered the event.
+ /// </value>
+ public object Context
+ {
+ get { return context; }
+ }
}
/// <summary>
- /// <para>Gets or sets additional status information
- /// within a WMI object. This may be null.</para>
+ /// <para>Holds event data for the <see cref='System.Management.ManagementOperationObserver.ObjectReady'/> event.</para>
/// </summary>
- /// <value>
- /// <para><see langword='null '/> if an error did not occur. Otherwise, may be non-null if the provider
- /// supports extended error information.</para>
- /// </value>
- public ManagementBaseObject StatusObject
+ public class ObjectReadyEventArgs : ManagementEventArgs
{
- get {
- return wmiObject;
+ private readonly ManagementBaseObject wmiObject;
+
+ /// <summary>
+ /// Constructor.
+ /// </summary>
+ /// <param name="context">The operation context which is echoed back
+ /// from the operation which triggerred the event.</param>
+ /// <param name="wmiObject">The newly arrived WmiObject.</param>
+ internal ObjectReadyEventArgs(object context, ManagementBaseObject wmiObject) : base(context)
+ {
+ this.wmiObject = wmiObject;
}
- }
- /// <summary>
- /// <para>Gets the completion status of the operation.</para>
- /// </summary>
- /// <value>
- /// <para>A <see cref='System.Management.ManagementStatus'/> value
- /// indicating the return code of the operation.</para>
- /// </value>
- public ManagementStatus Status
- {
- get {
- return (ManagementStatus) status;
+ /// <summary>
+ /// <para> Gets the newly-returned object.</para>
+ /// </summary>
+ /// <value>
+ /// <para>A <see cref='System.Management.ManagementBaseObject'/> representing the
+ /// newly-returned object.</para>
+ /// </value>
+ public ManagementBaseObject NewObject
+ {
+ get
+ {
+ return wmiObject;
+ }
}
}
-}
-
-/// <summary>
-/// <para>Holds event data for the <see cref='System.Management.ManagementOperationObserver.ObjectPut'/> event.</para>
-/// </summary>
-public class ObjectPutEventArgs : ManagementEventArgs
-{
- private readonly ManagementPath wmiPath;
/// <summary>
- /// Constructor
+ /// <para> Holds event data for the <see cref='System.Management.ManagementOperationObserver.Completed'/> event.</para>
/// </summary>
- /// <param name="context">The operation context which is echoed back
- /// from the operation which trigerred the event.</param>
- /// <param name="path">The WmiPath representing the identity of the
- /// object that has been put.</param>
- internal ObjectPutEventArgs (
- object context,
- ManagementPath path
- ) : base (context)
+ public class CompletedEventArgs : ManagementEventArgs
{
- wmiPath = path;
- }
+ private readonly int status;
+ private readonly ManagementBaseObject wmiObject;
- /// <summary>
- /// <para> Gets the identity of the
- /// object that has been put.</para>
- /// </summary>
- /// <value>
- /// <para>A <see cref='System.Management.ManagementPath'/> containing the path of the object that has
- /// been put.</para>
- /// </value>
- public ManagementPath Path
- {
- get {
- return wmiPath;
+ /// <summary>
+ /// Constructor.
+ /// </summary>
+ /// <param name="context">The operation context which is echoed back
+ /// from the operation which trigerred the event.</param>
+ /// <param name="status">The completion status of the operation.</param>
+ /// <param name="wmiStatusObject">Additional status information
+ /// encapsulated within a WmiObject. This may be null.</param>
+ internal CompletedEventArgs(object context, int status, ManagementBaseObject wmiStatusObject) : base(context)
+ {
+ wmiObject = wmiStatusObject;
+ this.status = status;
}
- }
-}
-/// <summary>
-/// <para>Holds event data for the <see cref='System.Management.ManagementOperationObserver.Progress'/> event.</para>
-/// </summary>
-public class ProgressEventArgs : ManagementEventArgs
-{
- private readonly int upperBound;
- private readonly int current;
- private readonly string message;
+ /// <summary>
+ /// <para>Gets or sets additional status information
+ /// within a WMI object. This may be null.</para>
+ /// </summary>
+ /// <value>
+ /// <para><see langword='null '/> if an error did not occur. Otherwise, may be non-null if the provider
+ /// supports extended error information.</para>
+ /// </value>
+ public ManagementBaseObject StatusObject
+ {
+ get
+ {
+ return wmiObject;
+ }
+ }
- /// <summary>
- /// Constructor
- /// </summary>
- /// <param name="context">The operation context which is echoed back
- /// from the operation which trigerred the event.</param>
- /// <param name="upperBound">A quantity representing the total
- /// amount of work required to be done by the operation.</param>
- /// <param name="current">A quantity representing the current
- /// amount of work required to be done by the operation. This is
- /// always less than or equal to upperBound.</param>
- /// <param name="message">Optional additional information regarding
- /// operation progress.</param>
- internal ProgressEventArgs (
- object context,
- int upperBound,
- int current,
- string message
- ) : base (context)
- {
- this.upperBound = upperBound;
- this.current = current;
- this.message = message;
+ /// <summary>
+ /// <para>Gets the completion status of the operation.</para>
+ /// </summary>
+ /// <value>
+ /// <para>A <see cref='System.Management.ManagementStatus'/> value
+ /// indicating the return code of the operation.</para>
+ /// </value>
+ public ManagementStatus Status
+ {
+ get
+ {
+ return (ManagementStatus)status;
+ }
+ }
}
/// <summary>
- /// <para> Gets the total
- /// amount of work required to be done by the operation.</para>
+ /// <para>Holds event data for the <see cref='System.Management.ManagementOperationObserver.ObjectPut'/> event.</para>
/// </summary>
- /// <value>
- /// An integer representing the total
- /// amount of work for the operation.
- /// </value>
- public int UpperBound
+ public class ObjectPutEventArgs : ManagementEventArgs
{
- get {
- return upperBound;
+ private readonly ManagementPath wmiPath;
+
+ /// <summary>
+ /// Constructor
+ /// </summary>
+ /// <param name="context">The operation context which is echoed back
+ /// from the operation which trigerred the event.</param>
+ /// <param name="path">The WmiPath representing the identity of the
+ /// object that has been put.</param>
+ internal ObjectPutEventArgs(object context, ManagementPath path) : base(context)
+ {
+ wmiPath = path;
}
- }
- /// <summary>
- /// <para> Gets the current amount of work
- /// done by the operation. This is always less than or equal to <see cref='System.Management.ProgressEventArgs.UpperBound'/>.</para>
- /// </summary>
- /// <value>
- /// <para>An integer representing the current amount of work
- /// already completed by the operation.</para>
- /// </value>
- public int Current
- {
- get {
- return current;
+ /// <summary>
+ /// <para> Gets the identity of the
+ /// object that has been put.</para>
+ /// </summary>
+ /// <value>
+ /// <para>A <see cref='System.Management.ManagementPath'/> containing the path of the object that has
+ /// been put.</para>
+ /// </value>
+ public ManagementPath Path
+ {
+ get
+ {
+ return wmiPath;
+ }
}
}
/// <summary>
- /// <para>Gets or sets optional additional information regarding the operation's progress.</para>
+ /// <para>Holds event data for the <see cref='System.Management.ManagementOperationObserver.Progress'/> event.</para>
/// </summary>
- /// <value>
- /// A string containing additional
- /// information regarding the operation's progress.
- /// </value>
- public string Message
+ public class ProgressEventArgs : ManagementEventArgs
{
- get {
- return (null != message) ? message : string.Empty;
+ private readonly int upperBound;
+ private readonly int current;
+ private readonly string message;
+
+ /// <summary>
+ /// Constructor
+ /// </summary>
+ /// <param name="context">The operation context which is echoed back
+ /// from the operation which trigerred the event.</param>
+ /// <param name="upperBound">A quantity representing the total
+ /// amount of work required to be done by the operation.</param>
+ /// <param name="current">A quantity representing the current
+ /// amount of work required to be done by the operation. This is
+ /// always less than or equal to upperBound.</param>
+ /// <param name="message">Optional additional information regarding
+ /// operation progress.</param>
+ internal ProgressEventArgs(object context, int upperBound, int current, string message) : base(context)
+ {
+ this.upperBound = upperBound;
+ this.current = current;
+ this.message = message;
}
- }
-}
-/// <summary>
-/// <para>Holds event data for the <see cref='System.Management.ManagementEventWatcher.EventArrived'/> event.</para>
-/// </summary>
-public class EventArrivedEventArgs : ManagementEventArgs
-{
- private readonly ManagementBaseObject eventObject;
+ /// <summary>
+ /// <para> Gets the total
+ /// amount of work required to be done by the operation.</para>
+ /// </summary>
+ /// <value>
+ /// An integer representing the total
+ /// amount of work for the operation.
+ /// </value>
+ public int UpperBound
+ {
+ get
+ {
+ return upperBound;
+ }
+ }
- internal EventArrivedEventArgs (
- object context,
- ManagementBaseObject eventObject) : base (context)
- {
- this.eventObject = eventObject;
+ /// <summary>
+ /// <para> Gets the current amount of work
+ /// done by the operation. This is always less than or equal to <see cref='System.Management.ProgressEventArgs.UpperBound'/>.</para>
+ /// </summary>
+ /// <value>
+ /// <para>An integer representing the current amount of work
+ /// already completed by the operation.</para>
+ /// </value>
+ public int Current
+ {
+ get
+ {
+ return current;
+ }
+ }
+
+ /// <summary>
+ /// <para>Gets or sets optional additional information regarding the operation's progress.</para>
+ /// </summary>
+ /// <value>
+ /// A string containing additional
+ /// information regarding the operation's progress.
+ /// </value>
+ public string Message
+ {
+ get
+ {
+ return (null != message) ? message : string.Empty;
+ }
+ }
}
/// <summary>
- /// <para> Gets the WMI event that was delivered.</para>
+ /// <para>Holds event data for the <see cref='System.Management.ManagementEventWatcher.EventArrived'/> event.</para>
/// </summary>
- /// <value>
- /// The object representing the WMI event.
- /// </value>
- public ManagementBaseObject NewEvent
+ public class EventArrivedEventArgs : ManagementEventArgs
{
- get { return this.eventObject; }
- }
-}
+ private readonly ManagementBaseObject eventObject;
-/// <summary>
-/// <para>Holds event data for the <see cref='System.Management.ManagementEventWatcher.Stopped'/> event.</para>
-/// </summary>
-public class StoppedEventArgs : ManagementEventArgs
-{
- private readonly int status;
+ internal EventArrivedEventArgs(object context, ManagementBaseObject eventObject) : base(context)
+ {
+ this.eventObject = eventObject;
+ }
- internal StoppedEventArgs (
- object context,
- int status) : base (context)
- {
- this.status = status;
+ /// <summary>
+ /// <para> Gets the WMI event that was delivered.</para>
+ /// </summary>
+ /// <value>
+ /// The object representing the WMI event.
+ /// </value>
+ public ManagementBaseObject NewEvent
+ {
+ get { return this.eventObject; }
+ }
}
/// <summary>
- /// <para> Gets the completion status of the operation.</para>
+ /// <para>Holds event data for the <see cref='System.Management.ManagementEventWatcher.Stopped'/> event.</para>
/// </summary>
- /// <value>
- /// <para>A <see cref='System.Management.ManagementStatus'/> value representing the status of the
- /// operation.</para>
- /// </value>
- public ManagementStatus Status
+ public class StoppedEventArgs : ManagementEventArgs
{
- get {
- return (ManagementStatus) status;
+ private readonly int status;
+
+ internal StoppedEventArgs(object context, int status) : base(context)
+ {
+ this.status = status;
+ }
+
+ /// <summary>
+ /// <para> Gets the completion status of the operation.</para>
+ /// </summary>
+ /// <value>
+ /// <para>A <see cref='System.Management.ManagementStatus'/> value representing the status of the
+ /// operation.</para>
+ /// </value>
+ public ManagementStatus Status
+ {
+ get
+ {
+ return (ManagementStatus)status;
+ }
}
}
-}
}
/// <summary>
/// <para>Represents the method that will handle the <see cref='System.Management.ManagementEventWatcher.Stopped'/> event.</para>
/// </summary>
- public delegate void StoppedEventHandler (object sender, StoppedEventArgs e);
+ public delegate void StoppedEventHandler(object sender, StoppedEventArgs e);
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
public class ManagementEventWatcher : Component
{
//fields
- private ManagementScope scope;
- private EventQuery query;
- private EventWatcherOptions options;
- private IEnumWbemClassObject enumWbem;
- private IWbemClassObjectFreeThreaded[] cachedObjects; //points to objects currently available in cache
- private uint cachedCount; //says how many objects are in the cache (when using BlockSize option)
- private uint cacheIndex; //used to walk the cache
- private SinkForEventQuery sink; // the sink implementation for event queries
- private readonly WmiDelegateInvoker delegateInvoker;
+ private ManagementScope scope;
+ private EventQuery query;
+ private EventWatcherOptions options;
+ private IEnumWbemClassObject enumWbem;
+ private IWbemClassObjectFreeThreaded[] cachedObjects; //points to objects currently available in cache
+ private uint cachedCount; //says how many objects are in the cache (when using BlockSize option)
+ private uint cacheIndex; //used to walk the cache
+ private SinkForEventQuery sink; // the sink implementation for event queries
+ private readonly WmiDelegateInvoker delegateInvoker;
//Called when IdentifierChanged() event fires
private void HandleIdentifierChange(object sender,
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class. For further
/// initialization, set the properties on the object. This is the default constructor.</para>
/// </summary>
- public ManagementEventWatcher() : this((ManagementScope)null, null, null) {}
+ public ManagementEventWatcher() : this((ManagementScope)null, null, null) { }
//parameterized constructors
/// <summary>
/// <para>The namespace in which the watcher will be listening for
/// events is the default namespace that is currently set.</para>
/// </remarks>
- public ManagementEventWatcher (
- EventQuery query) : this(null, query, null) {}
+ public ManagementEventWatcher(
+ EventQuery query) : this(null, query, null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class when given a WMI event query in the
/// <para>The namespace in which the watcher will be listening for
/// events is the default namespace that is currently set.</para>
/// </remarks>
- public ManagementEventWatcher (
- string query) : this(null, new EventQuery(query), null) {}
+ public ManagementEventWatcher(
+ string query) : this(null, new EventQuery(query), null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/>
/// <param name=' query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param>
public ManagementEventWatcher(
ManagementScope scope,
- EventQuery query) : this(scope, query, null) {}
+ EventQuery query) : this(scope, query, null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/>
/// <param name=' query'> The query that defines the events for which the watcher will listen.</param>
public ManagementEventWatcher(
string scope,
- string query) : this(new ManagementScope(scope), new EventQuery(query), null) {}
+ string query) : this(new ManagementScope(scope), new EventQuery(query), null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class that listens for
public ManagementEventWatcher(
string scope,
string query,
- EventWatcherOptions options) : this(new ManagementScope(scope), new EventQuery(query), options) {}
+ EventWatcherOptions options) : this(new ManagementScope(scope), new EventQuery(query), options) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class
cachedCount = 0;
cacheIndex = 0;
sink = null;
- delegateInvoker = new WmiDelegateInvoker (this);
+ delegateInvoker = new WmiDelegateInvoker(this);
}
/// <summary>
/// <para>Ensures that outstanding calls are cleared. This is the destructor for the object.</para>
/// </summary>
- ~ManagementEventWatcher ()
+ ~ManagementEventWatcher()
{
// Ensure any outstanding calls are cleared
- Stop ();
+ Stop();
if (null != scope)
- scope.IdentifierChanged -= new IdentifierChangedEventHandler (HandleIdentifierChange);
+ scope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
if (null != options)
- options.IdentifierChanged -= new IdentifierChangedEventHandler (HandleIdentifierChange);
+ options.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
if (null != query)
- query.IdentifierChanged -= new IdentifierChangedEventHandler (HandleIdentifierChange);
+ query.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
}
//
/// <summary>
/// <para> Occurs when a new event arrives.</para>
/// </summary>
- public event EventArrivedEventHandler EventArrived;
+ public event EventArrivedEventHandler EventArrived;
/// <summary>
/// <para> Occurs when a subscription is canceled.</para>
/// </summary>
- public event StoppedEventHandler Stopped;
+ public event StoppedEventHandler Stopped;
//
//Public Properties
if (null != value)
{
ManagementScope oldScope = scope;
- scope = (ManagementScope)value.Clone ();
+ scope = (ManagementScope)value.Clone();
// Unregister ourselves from the previous scope object
if (null != oldScope)
if (null != value)
{
ManagementQuery oldQuery = query;
- query = (EventQuery)value.Clone ();
+ query = (EventQuery)value.Clone();
// Unregister ourselves from the previous query object
if (null != oldQuery)
if (null != value)
{
EventWatcherOptions oldOptions = options;
- options = (EventWatcherOptions)value.Clone ();
+ options = (EventWatcherOptions)value.Clone();
// Unregister ourselves from the previous scope object
if (null != oldOptions)
{
ManagementBaseObject obj = null;
- Initialize ();
+ Initialize();
#pragma warning disable CA2002
lock (this)
if (null == enumWbem) //don't have an enumerator yet - get it
{
//Execute the query
- status = scope.GetSecuredIWbemServicesHandler( Scope.GetIWbemServices() ).ExecNotificationQuery_(
+ status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecNotificationQuery_(
query.QueryLanguage,
query.QueryString,
options.Flags,
- options.GetContext (),
+ options.GetContext(),
ref enumWbem);
}
IWbemClassObject_DoNotMarshal[] tempArray = new IWbemClassObject_DoNotMarshal[options.BlockSize];
int timeout = (ManagementOptions.InfiniteTimeout == options.Timeout)
- ? (int) tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE :
- (int) options.Timeout.TotalMilliseconds;
+ ? (int)tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE :
+ (int)options.Timeout.TotalMilliseconds;
status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Next_(timeout, (uint)options.BlockSize, tempArray, ref cachedCount);
cacheIndex = 0;
/// </summary>
public void Start()
{
- Initialize ();
+ Initialize();
// Cancel any current event query
- Stop ();
+ Stop();
// Submit a new query
SecurityHandler securityHandler = Scope.GetSecurityHandler();
{
Marshal.ReleaseComObject(enumWbem);
enumWbem = null;
- FireStopped (new StoppedEventArgs (options.Context, (int)ManagementStatus.OperationCanceled));
+ FireStopped(new StoppedEventArgs(options.Context, (int)ManagementStatus.OperationCanceled));
}
// In async mode cancel the call to the sink - this will
// unwind the operation and cause a Stopped message
if (null != sink)
{
- sink.Cancel ();
+ sink.Cancel();
sink = null;
}
}
- private void Initialize ()
+ private void Initialize()
{
//If the query is not set yet we can't do it
if (null == query)
throw new InvalidOperationException();
if (null == options)
- Options = new EventWatcherOptions ();
+ Options = new EventWatcherOptions();
//If we're not connected yet, this is the time to do it...
#pragma warning disable CA2002
#pragma warning restore CA2002
{
if (null == scope)
- Scope = new ManagementScope ();
+ Scope = new ManagementScope();
if (null == cachedObjects)
cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize];
lock (scope)
{
- scope.Initialize ();
+ scope.Initialize();
}
}
- internal void FireStopped (StoppedEventArgs args)
+ internal void FireStopped(StoppedEventArgs args)
{
try
{
- delegateInvoker.FireEventToDelegates (Stopped, args);
+ delegateInvoker.FireEventToDelegates(Stopped, args);
}
catch
{
}
}
- internal void FireEventArrived (EventArrivedEventArgs args)
+ internal void FireEventArrived(EventArrivedEventArgs args)
{
try
{
- delegateInvoker.FireEventToDelegates (EventArrived, args);
+ delegateInvoker.FireEventToDelegates(EventArrived, args);
}
catch
{
internal class SinkForEventQuery : IWmiEventSource
{
- private readonly ManagementEventWatcher eventWatcher;
- private readonly object context;
- private readonly IWbemServices services;
+ private readonly ManagementEventWatcher eventWatcher;
+ private readonly object context;
+ private readonly IWbemServices services;
private IWbemObjectSink stub; // The secured IWbemObjectSink
private int status;
private readonly bool isLocal;
- public int Status {get {return status; } set {status=value; }}
+ public int Status { get { return status; } set { status = value; } }
- public SinkForEventQuery (ManagementEventWatcher eventWatcher,
+ public SinkForEventQuery(ManagementEventWatcher eventWatcher,
object context,
IWbemServices services)
{
this.isLocal = false;
// determine if the server is local, and if so don't create a real stub using unsecap
- if ((0==string.Compare(eventWatcher.Scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
- (0==string.Compare(eventWatcher.Scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
+ if ((0 == string.Compare(eventWatcher.Scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
+ (0 == string.Compare(eventWatcher.Scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
{
this.isLocal = true;
}
//
// Ensure we are able to trap exceptions from worker thread.
//
- ThreadDispatch disp = new ThreadDispatch ( new ThreadDispatch.ThreadWorkerMethodWithParam ( HackToCreateStubInMTA ) );
+ ThreadDispatch disp = new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethodWithParam(HackToCreateStubInMTA));
disp.Parameter = this;
- disp.Start ( );
+ disp.Start();
}
}
private void HackToCreateStubInMTA(object param)
{
- SinkForEventQuery obj = (SinkForEventQuery) param;
+ SinkForEventQuery obj = (SinkForEventQuery)param;
object dmuxStub = null;
- obj.Status = WmiNetUtilsHelper.GetDemultiplexedStub_f (obj, obj.isLocal, out dmuxStub);
- obj.stub = (IWbemObjectSink) dmuxStub;
+ obj.Status = WmiNetUtilsHelper.GetDemultiplexedStub_f(obj, obj.isLocal, out dmuxStub);
+ obj.stub = (IWbemObjectSink)dmuxStub;
}
internal IWbemObjectSink Stub
}
}
- public void SetStatus (
+ public void SetStatus(
int flags,
int hResult,
string message,
}
}
- internal void Cancel ()
+ internal void Cancel()
{
if (null != stub)
{
}
}
- internal void ReleaseStub ()
+ internal void ReleaseStub()
{
if (null != stub)
{
/// and <see cref='System.Runtime.Serialization.StreamingContext'/>.</para>
/// </summary>
/// <param name='info'>The <see cref='System.Runtime.Serialization.SerializationInfo'/> to populate with data.</param>
- /// <param name='context'>The destination (see <see cref='System.Runtime.Serialization.StreamingContext'/> ) for this serialization.</param>
+ /// <param name='context'>The destination (see <see cref='System.Runtime.Serialization.StreamingContext'/> ) for this serialization.</param>
protected ManagementNamedValueCollection(SerializationInfo info, StreamingContext context) : base(info, context)
{
throw new PlatformNotSupportedException();
{
int status = (int)ManagementStatus.NoError;
- try {
- wbemContext = (IWbemContext) new WbemContext ();
+ try
+ {
+ wbemContext = (IWbemContext)new WbemContext();
foreach (string name in this)
{
object val = base.BaseGet(name);
- status = wbemContext.SetValue_ (name, 0, ref val);
+ status = wbemContext.SetValue_(name, 0, ref val);
if ((status & 0x80000000) != 0)
{
break;
}
}
- } catch {}
+ }
+ catch { }
}
return wbemContext;
/// </summary>
/// <param name=' name'>The name of the new value.</param>
/// <param name=' value'>The value to be associated with the name.</param>
- public void Add (string name, object value)
+ public void Add(string name, object value)
{
// Remove any old entry
try
{
- base.BaseRemove (name);
- } catch {}
+ base.BaseRemove(name);
+ }
+ catch { }
- base.BaseAdd (name, value);
- FireIdentifierChanged ();
+ base.BaseAdd(name, value);
+ FireIdentifierChanged();
}
/// <summary>
/// exception is thrown.</para>
/// </summary>
/// <param name=' name'>The name of the value to be removed.</param>
- public void Remove (string name)
+ public void Remove(string name)
{
- base.BaseRemove (name);
- FireIdentifierChanged ();
+ base.BaseRemove(name);
+ FireIdentifierChanged();
}
/// <summary>
/// <para>Removes all entries from the collection.</para>
/// </summary>
- public void RemoveAll ()
+ public void RemoveAll()
{
- base.BaseClear ();
- FireIdentifierChanged ();
+ base.BaseClear();
+ FireIdentifierChanged();
}
/// <summary>
/// <returns>
/// The new copy of the collection.
/// </returns>
- public ManagementNamedValueCollection Clone ()
+ public ManagementNamedValueCollection Clone()
{
ManagementNamedValueCollection nvc = new ManagementNamedValueCollection();
foreach (string name in this)
{
// If we can clone the value, do so. Otherwise throw.
- object val = base.BaseGet (name);
+ object val = base.BaseGet(name);
if (null != val)
{
- Type valueType = val.GetType ();
+ Type valueType = val.GetType();
if (valueType.IsByRef)
{
try
{
- object clonedValue = ((ICloneable)val).Clone ();
- nvc.Add (name, clonedValue);
+ object clonedValue = ((ICloneable)val).Clone();
+ nvc.Add(name, clonedValue);
}
catch
{
- throw new NotSupportedException ();
+ throw new NotSupportedException();
}
}
else
{
- nvc.Add (name, val);
+ nvc.Add(name, val);
}
}
else
- nvc.Add (name, null);
+ {
+ nvc.Add(name, null);
+ }
}
return nvc;
/// </value>
public object this[string name]
{
- get {
+ get
+ {
return base.BaseGet(name);
}
}
//Fields
- private IWbemClassObjectFreeThreaded wmiClass;
- internal ManagementScope scope;
- internal ManagementPath path;
- internal ObjectGetOptions options;
+ private IWbemClassObjectFreeThreaded wmiClass;
+ internal ManagementScope scope;
+ internal ManagementPath path;
+ internal ObjectGetOptions options;
//Used to represent whether this managementObject is currently bound to a wbemObject
//or not - whenever an "identifying" property is changed (Path, Scope...) the object
/// Console.WriteLine(o("FreeSpace"))
/// </code>
/// </example>
- public ManagementObject() : this ((ManagementScope)null, null, null) {}
+ public ManagementObject() : this((ManagementScope)null, null, null) { }
//parameterized constructors
/// <summary>
/// Dim o As New ManagementObject(p)
/// </code>
/// </example>
- public ManagementObject(ManagementPath path) : this(null, path, null) {}
+ public ManagementObject(ManagementPath path) : this(null, path, null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObject'/> class for the specified WMI object path. The path
/// Dim o As New ManagementObject("\\\\MyServer\\root\\MyApp:MyClass.Key=""abc""");
/// </code>
/// </example>
- public ManagementObject(string path) : this(null, new ManagementPath(path), null) {}
+ public ManagementObject(string path) : this(null, new ManagementPath(path), null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObject'/> class bound to the specified
/// Console.WriteLine(o.GetQualifierValue("Description"));
/// </code>
/// </example>
- public ManagementObject(ManagementPath path, ObjectGetOptions options) : this(null, path, options) {}
+ public ManagementObject(ManagementPath path, ObjectGetOptions options) : this(null, path, options) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObject'/> class bound to the specified WMI path, including the
/// </code>
/// </example>
public ManagementObject(string path, ObjectGetOptions options) :
- this(new ManagementPath(path), options) {}
+ this(new ManagementPath(path), options)
+ { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementObject'/>
/// </code>
/// </example>
public ManagementObject(ManagementScope scope, ManagementPath path, ObjectGetOptions options)
- : base (null)
+ : base(null)
{
ManagementObjectCTOR(scope, path, options);
}
// we don't have a scope
nsPath = path.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY);
- if ((null != scope) && (scope.Path.NamespacePath.Length>0))
+ if ((null != scope) && (scope.Path.NamespacePath.Length > 0))
{
// If the scope has a path too, the namespace portion of
// scope.path takes precedence over what is specified in path
else
{
// Use the path if possible, otherwise let it default
- if (nsPath.Length>0)
+ if (nsPath.Length > 0)
{
this.scope = new ManagementScope(nsPath);
this.scope.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
/// </code>
/// </example>
public ManagementObject(string scopeString, string pathString, ObjectGetOptions options)
- : this(new ManagementScope(scopeString), new ManagementPath(pathString), options) {}
+ : this(new ManagementScope(scopeString), new ManagementPath(pathString), options) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObject'/> class that is serializable.</para>
/// </summary>
/// <param name='info'>The <see cref='System.Runtime.Serialization.SerializationInfo'/> to populate with data.</param>
- /// <param name='context'>The destination (see <see cref='System.Runtime.Serialization.StreamingContext'/> ) for this serialization.</param>
+ /// <param name='context'>The destination (see <see cref='System.Runtime.Serialization.StreamingContext'/> ) for this serialization.</param>
protected ManagementObject(SerializationInfo info, StreamingContext context) : base(info, context)
{
ManagementObjectCTOR(null, null, null);
newPath.IsEmpty)
{
if (null != path)
- path.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
+ path.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
path = ManagementPath._Clone((ManagementPath)value, new IdentifierChangedEventHandler(HandleIdentifierChange));
{
IWbemClassObjectFreeThreaded tempObj = null;
- Initialize ( false ); // this may throw
+ Initialize(false); // this may throw
- if ((null == path) || (path.Path.Length==0))
+ if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
else
{
(null == options) ? new ObjectGetOptions() : options;
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
try
{
securityHandler = scope.GetSecurityHandler();
- status = scope.GetSecuredIWbemServicesHandler( scope.GetIWbemServices() ).GetObject_(path.RelativePath,
+ status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).GetObject_(path.RelativePath,
gOptions.Flags,
gOptions.GetContext(),
ref tempObj,
- IntPtr.Zero );
+ IntPtr.Zero);
if (status < 0)
{
/// </example>
public void Get(ManagementOperationObserver watcher)
{
- Initialize ( false );
+ Initialize(false);
- if ((null == path) || (path.Path.Length==0))
+ if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
else if (null == watcher)
throw new ArgumentNullException(nameof(watcher));
o.SendStatus = true;
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
securityHandler = scope.GetSecurityHandler();
bool classDefinitionsOnly,
EnumerationOptions options)
{
- if ((null == path) || (path.Path.Length==0))
+ if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
- Initialize ( false );
+ Initialize(false);
IEnumWbemClassObject enumWbem = null;
EnumerationOptions o = (null != options) ? options : new EnumerationOptions();
o.EnumerateDeep = true; //note this turns the FLAG to 0 !!
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
try
{
securityHandler = scope.GetSecurityHandler();
- status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices() ).ExecQuery_(
+ status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).ExecQuery_(
q.QueryLanguage,
q.QueryString,
o.Flags,
bool classDefinitionsOnly,
EnumerationOptions options)
{
- if ((null == path) || (path.Path.Length==0))
+ if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
- Initialize ( true );
+ Initialize(true);
if (null == watcher)
throw new ArgumentNullException(nameof(watcher));
//Make sure the EnumerateDeep flag bit is turned off because it's invalid for queries
o.EnumerateDeep = true; //note this turns the FLAG to 0 !!
- SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ SecurityHandler securityHandler = null;
+ int status = (int)ManagementStatus.NoError;
securityHandler = scope.GetSecurityHandler();
- status = scope.GetSecuredIWbemServicesHandler( scope.GetIWbemServices() ).ExecQueryAsync_(
+ status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).ExecQueryAsync_(
q.QueryLanguage,
q.QueryString,
o.Flags,
bool classDefinitionsOnly,
EnumerationOptions options)
{
- if ((null == path) || (path.Path.Length==0))
+ if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
- Initialize ( false );
+ Initialize(false);
IEnumWbemClassObject enumWbem = null;
EnumerationOptions o =
o.EnumerateDeep = true; //note this turns the FLAG to 0 !!
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
try
{
q.QueryString,
o.Flags,
o.GetContext(),
- ref enumWbem );
+ ref enumWbem);
if (status < 0)
bool classDefinitionsOnly,
EnumerationOptions options)
{
- if ((null == path) || (path.Path.Length==0))
+ if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
if (null == watcher)
throw new ArgumentNullException(nameof(watcher));
else
{
- Initialize ( false );
+ Initialize(false);
// Ensure we switch off ReturnImmediately as this is invalid for async calls
EnumerationOptions o =
o.EnumerateDeep = true; //note this turns the FLAG to 0 !!
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
securityHandler = scope.GetSecurityHandler();
- status = scope.GetSecuredIWbemServicesHandler( scope.GetIWbemServices() ).ExecQueryAsync_(
+ status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).ExecQueryAsync_(
q.QueryLanguage,
q.QueryString,
o.Flags,
o.GetContext(),
- sink.Stub );
+ sink.Stub);
if (securityHandler != null)
/// </returns>
public ManagementPath Put()
{
- return Put((PutOptions) null);
+ return Put((PutOptions)null);
}
public ManagementPath Put(PutOptions options)
{
ManagementPath newPath = null;
- Initialize ( true );
+ Initialize(true);
PutOptions o = (null != options) ? options : new PutOptions();
IWbemServices wbemServices = scope.GetIWbemServices();
// has been redefined to be an IntPtr. Due to the fact that it wasn't possible to
// pass NULL for the optional argument.
//
- IntPtr ppwbemCallResult = IntPtr.Zero;
- IntPtr pwbemCallResult = IntPtr.Zero;
- IWbemCallResult wbemCallResult = null;
- SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ IntPtr ppwbemCallResult = IntPtr.Zero;
+ IntPtr pwbemCallResult = IntPtr.Zero;
+ IWbemCallResult wbemCallResult = null;
+ SecurityHandler securityHandler = null;
+ int status = (int)ManagementStatus.NoError;
try
{
if (IsClass)
{
- status = scope.GetSecuredIWbemServicesHandler(wbemServices).PutClass_( wbemObject,
+ status = scope.GetSecuredIWbemServicesHandler(wbemServices).PutClass_(wbemObject,
o.Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY,
o.GetContext(),
- ppwbemCallResult );
+ ppwbemCallResult);
}
else
{
}
catch
- {
- }
+ {
+ }
if (newPath == null)
newPath = new ManagementPath();
throw new ArgumentNullException(nameof(watcher));
else
{
- Initialize ( false );
+ Initialize(false);
PutOptions o = (null == options) ?
new PutOptions() : (PutOptions)options.Clone();
sink.InternalObjectPut +=
new InternalObjectPutEventHandler(this.HandleObjectPut);
- SecurityHandler securityHandler = null;
+ SecurityHandler securityHandler = null;
// Assign to error initially to insure internal event handler cleanup
// on non-management exception.
- int status = (int)ManagementStatus.Failed;
+ int status = (int)ManagementStatus.Failed;
securityHandler = scope.GetSecurityHandler();
if (IsClass)
{
- status = scope.GetSecuredIWbemServicesHandler( wbemServices ).PutClassAsync_(
+ status = scope.GetSecuredIWbemServicesHandler(wbemServices).PutClassAsync_(
wbemObject,
o.Flags,
o.GetContext(),
}
else
{
- status = scope.GetSecuredIWbemServicesHandler( wbemServices ).PutInstanceAsync_(
+ status = scope.GetSecuredIWbemServicesHandler(wbemServices).PutInstanceAsync_(
wbemObject,
o.Flags,
o.GetContext(),
/// </returns>
public ManagementPath CopyTo(ManagementPath path, PutOptions options)
{
- Initialize ( false );
+ Initialize(false);
ManagementScope destinationScope = null;
// has been redefined to be an IntPtr. Due to the fact that it wasn't possible to
// pass NULL for the optional argument.
//
- IntPtr ppwbemCallResult = IntPtr.Zero;
- IntPtr pwbemCallResult = IntPtr.Zero;
- IWbemCallResult wbemCallResult = null;
- SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ IntPtr ppwbemCallResult = IntPtr.Zero;
+ IntPtr pwbemCallResult = IntPtr.Zero;
+ IWbemCallResult wbemCallResult = null;
+ SecurityHandler securityHandler = null;
+ int status = (int)ManagementStatus.NoError;
try
{
if (IsClass)
{
- status = scope.GetSecuredIWbemServicesHandler( wbemServices ).PutClass_(
+ status = scope.GetSecuredIWbemServicesHandler(wbemServices).PutClass_(
wbemObject,
o.Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY,
o.GetContext(),
}
else
{
- status = scope.GetSecuredIWbemServicesHandler( wbemServices ).PutInstance_(
+ status = scope.GetSecuredIWbemServicesHandler(wbemServices).PutInstance_(
wbemObject,
o.Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY,
o.GetContext(),
throw new ArgumentNullException(nameof(watcher));
else
{
- Initialize ( false );
+ Initialize(false);
ManagementScope destinationScope = null;
destinationScope = new ManagementScope(path, scope);
destinationScope.Initialize();
- PutOptions o = (null != options) ? (PutOptions) options.Clone() : new PutOptions();
+ PutOptions o = (null != options) ? (PutOptions)options.Clone() : new PutOptions();
// If someone has registered for progress, make sure we flag it
if (watcher.HaveListenersForProgress)
IWbemServices destWbemServices = destinationScope.GetIWbemServices();
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
securityHandler = destinationScope.GetSecurityHandler();
if (IsClass)
{
- status = destinationScope.GetSecuredIWbemServicesHandler( destWbemServices ).PutClassAsync_(
+ status = destinationScope.GetSecuredIWbemServicesHandler(destWbemServices).PutClassAsync_(
wbemObject,
o.Flags,
o.GetContext(),
}
else
{
- status = destinationScope.GetSecuredIWbemServicesHandler( destWbemServices ).PutInstanceAsync_(
+ status = destinationScope.GetSecuredIWbemServicesHandler(destWbemServices).PutInstanceAsync_(
wbemObject,
o.Flags,
o.GetContext(),
/// </summary>
public void Delete()
{
- Delete((DeleteOptions) null);
+ Delete((DeleteOptions)null);
}
/// <summary>
/// <param name='options'>The options for how to delete the object. </param>
public void Delete(DeleteOptions options)
{
- if ((null == path) || (path.Path.Length==0))
+ if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
- Initialize ( false );
+ Initialize(false);
DeleteOptions o = (null != options) ? options : new DeleteOptions();
IWbemServices wbemServices = scope.GetIWbemServices();
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
try
{
if (IsClass)
{
- status = scope.GetSecuredIWbemServicesHandler( wbemServices ).DeleteClass_(
+ status = scope.GetSecuredIWbemServicesHandler(wbemServices).DeleteClass_(
path.RelativePath,
o.Flags,
o.GetContext(),
}
else
{
- status = scope.GetSecuredIWbemServicesHandler( wbemServices ).DeleteInstance_(
+ status = scope.GetSecuredIWbemServicesHandler(wbemServices).DeleteInstance_(
path.RelativePath,
o.Flags,
o.GetContext(),
/// <param name='options'>The options for how to delete the object.</param>
public void Delete(ManagementOperationObserver watcher, DeleteOptions options)
{
- if ((null == path) || (path.Path.Length==0))
+ if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
else if (null == watcher)
throw new ArgumentNullException(nameof(watcher));
else
{
- Initialize ( false );
- DeleteOptions o = (null != options) ? (DeleteOptions) options.Clone() : new DeleteOptions();
+ Initialize(false);
+ DeleteOptions o = (null != options) ? (DeleteOptions)options.Clone() : new DeleteOptions();
// If someone has registered for progress, make sure we flag it
if (watcher.HaveListenersForProgress)
WmiEventSink sink = watcher.GetNewSink(scope, o.Context);
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
securityHandler = scope.GetSecurityHandler();
if (IsClass)
{
- status = scope.GetSecuredIWbemServicesHandler( wbemServices ).DeleteClassAsync_(path.RelativePath,
+ status = scope.GetSecuredIWbemServicesHandler(wbemServices).DeleteClassAsync_(path.RelativePath,
o.Flags,
o.GetContext(),
sink.Stub);
}
else
{
- status = scope.GetSecuredIWbemServicesHandler( wbemServices ).DeleteInstanceAsync_(path.RelativePath,
+ status = scope.GetSecuredIWbemServicesHandler(wbemServices).DeleteInstanceAsync_(path.RelativePath,
o.Flags,
o.GetContext(),
sink.Stub);
{
object result = null;
- if ((null == path) || (path.Path.Length==0))
+ if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
else if (null == methodName)
throw new ArgumentNullException(nameof(methodName));
else
{
- Initialize ( false );
+ Initialize(false);
// Map args into a inparams structure
ManagementBaseObject inParameters;
string methodName,
object[] args)
{
- if ((null == path) || (path.Path.Length==0))
+ if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
else if (null == watcher)
throw new ArgumentNullException(nameof(watcher));
throw new ArgumentNullException(nameof(methodName));
else
{
- Initialize ( false );
+ Initialize(false);
// Map args into a inparams structure
ManagementBaseObject inParameters;
IWbemClassObjectFreeThreaded inParametersClass, outParametersClass;
GetMethodParameters(methodName, out inParameters,
- out inParametersClass, out outParametersClass);
+ out inParametersClass, out outParametersClass);
MapInParameters(args, inParameters, inParametersClass);
{
ManagementBaseObject outParameters = null;
- if ((null == path) || (path.Path.Length==0))
+ if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
else if (null == methodName)
throw new ArgumentNullException(nameof(methodName));
else
{
- Initialize ( false );
+ Initialize(false);
InvokeMethodOptions o = (null != options) ? options : new InvokeMethodOptions();
IWbemServices wbemServices = scope.GetIWbemServices();
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
try
{
IWbemClassObjectFreeThreaded inParams = (null == inParameters) ? null : inParameters.wbemObject;
IWbemClassObjectFreeThreaded outParams = null;
- status = scope.GetSecuredIWbemServicesHandler( scope.GetIWbemServices() ).ExecMethod_(
+ status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).ExecMethod_(
path.RelativePath,
methodName,
o.Flags,
ManagementBaseObject inParameters,
InvokeMethodOptions options)
{
- if ((null == path) || (path.Path.Length==0))
+ if ((null == path) || (path.Path.Length == 0))
throw new InvalidOperationException();
else if (null == watcher)
throw new ArgumentNullException(nameof(watcher));
throw new ArgumentNullException(nameof(methodName));
else
{
- Initialize ( false );
+ Initialize(false);
InvokeMethodOptions o = (null != options) ?
- (InvokeMethodOptions) options.Clone() : new InvokeMethodOptions();
+ (InvokeMethodOptions)options.Clone() : new InvokeMethodOptions();
// If someone has registered for progress, make sure we flag it
if (watcher.HaveListenersForProgress)
WmiEventSink sink = watcher.GetNewSink(scope, o.Context);
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
securityHandler = scope.GetSecurityHandler();
if (null != inParameters)
inParams = inParameters.wbemObject;
- status = scope.GetSecuredIWbemServicesHandler( scope.GetIWbemServices() ).ExecMethodAsync_(
+ status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).ExecMethodAsync_(
path.RelativePath,
methodName,
o.Flags,
o.GetContext(),
inParams,
- sink.Stub );
+ sink.Stub);
if (securityHandler != null)
securityHandler.Reset();
throw new ArgumentNullException(nameof(methodName));
else
{
- Initialize ( false );
+ Initialize(false);
// Do we have the class?
if (null == wmiClass)
// The prototype of Initialize has been changed to accept a bool, indicating whether or not
// the caller wants to bind to the underlying WMI object in the Initialize call or not.
//
- internal override void Initialize( bool getObject )
+ internal override void Initialize(bool getObject)
{
bool needToGetObject = false;
}
//Have we already got this object
- if (!IsBound && ( getObject == true ) )
+ if (!IsBound && (getObject == true))
needToGetObject = true;
if (null == scope)
scope.Initialize();
// If we have just connected, make sure we get the object
- if ( getObject == true )
+ if (getObject == true)
{
needToGetObject = true;
}
IWbemServices wbemServices = scope.GetIWbemServices();
SecurityHandler securityHandler = null;
- int status = (int)ManagementStatus.NoError;
+ int status = (int)ManagementStatus.NoError;
try
{
string objectPath = null;
string curPath = path.RelativePath;
- if (curPath.Length>0)
+ if (curPath.Length > 0)
objectPath = curPath;
- status = scope.GetSecuredIWbemServicesHandler( wbemServices ).GetObject_(objectPath, options.Flags, options.GetContext(), ref tempObj, IntPtr.Zero);
+ status = scope.GetSecuredIWbemServicesHandler(wbemServices).GetObject_(objectPath, options.Flags, options.GetContext(), ref tempObj, IntPtr.Zero);
if (status >= 0)
{
if (status >= 0)
{
- path = (System.DBNull.Value != val) ? (new ManagementPath((string)val)) : (new ManagementPath ());
+ path = (System.DBNull.Value != val) ? (new ManagementPath((string)val)) : (new ManagementPath());
path.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
}
}
private static void MapInParameters(
- object [] args,
+ object[] args,
ManagementBaseObject inParams,
IWbemClassObjectFreeThreaded inParamsClass)
{
{
while (true)
{
- object val = null;
- int dummy = 0;
- string propertyName = null;
+ object val = null;
+ int dummy = 0;
+ string propertyName = null;
IWbemQualifierSetFreeThreaded qualifierSet = null;
status = inParamsClass.Next_(0, ref propertyName, ref val, ref dummy, ref dummy);
// If the id is in range, map the value into the args array
int idIndex = (int)id;
if ((0 <= idIndex) && (topId >= idIndex))
- inParams[propertyName] = args [minIndex + idIndex];
+ inParams[propertyName] = args[minIndex + idIndex];
}
finally
{
}
private static object MapOutParameters(
- object [] args,
+ object[] args,
ManagementBaseObject outParams,
IWbemClassObjectFreeThreaded outParamsClass)
{
{
while (true)
{
- object val = null;
- int dummy = 0;
- string propertyName = null;
+ object val = null;
+ int dummy = 0;
+ string propertyName = null;
IWbemQualifierSetFreeThreaded qualifierSet = null;
status = outParamsClass.Next_(0, ref propertyName, ref val, ref dummy, ref dummy);
// If the id is in range, map the value into the args array
int idIndex = (int)id;
if ((0 <= idIndex) && (topId >= idIndex))
- args [minIndex + idIndex] = outParams[propertyName];
+ args[minIndex + idIndex] = outParams[propertyName];
}
finally
{
IEnumWbemClassObject enumWbem)
{
if (null != options)
- this.options = (EnumerationOptions) options.Clone();
+ this.options = (EnumerationOptions)options.Clone();
else
- this.options = new EnumerationOptions ();
+ this.options = new EnumerationOptions();
if (null != scope)
- this.scope = (ManagementScope)scope.Clone ();
+ this.scope = (ManagementScope)scope.Clone();
else
this.scope = ManagementScope._Clone(null);
/// <summary>
/// <para>Disposes of resources the object is holding. This is the destructor for the object.</para>
/// </summary>
- ~ManagementObjectCollection ()
+ ~ManagementObjectCollection()
{
- Dispose ( false );
+ Dispose(false);
}
/// <summary>
/// method has been called, an attempt to use this object will
/// result in an ObjectDisposedException being thrown.
/// </summary>
- public void Dispose ()
+ public void Dispose()
{
if (!isDisposed)
{
- Dispose ( true );
+ Dispose(true);
}
}
- private void Dispose ( bool disposing )
+ private void Dispose(bool disposing)
{
- if ( disposing )
+ if (disposing)
{
- GC.SuppressFinalize (this);
+ GC.SuppressFinalize(this);
isDisposed = true;
}
- Marshal.ReleaseComObject (enumWbem);
+ Marshal.ReleaseComObject(enumWbem);
}
//
int count = 0;
- IEnumerator enumCol = this.GetEnumerator ( );
- while ( enumCol.MoveNext() == true )
+ IEnumerator enumCol = this.GetEnumerator();
+ while (enumCol.MoveNext() == true)
{
count++;
}
/// </summary>
/// <param name='array'>An array to copy to. </param>
/// <param name='index'>The index to start from. </param>
- public void CopyTo (Array array, int index)
+ public void CopyTo(Array array, int index)
{
if (isDisposed)
throw new ObjectDisposedException(name);
if (null == array)
- throw new ArgumentNullException (nameof(array));
+ throw new ArgumentNullException(nameof(array));
- if ((index < array.GetLowerBound (0)) || (index > array.GetUpperBound(0)))
- throw new ArgumentOutOfRangeException (nameof(index));
+ if ((index < array.GetLowerBound(0)) || (index > array.GetUpperBound(0)))
+ throw new ArgumentOutOfRangeException(nameof(index));
// Since we don't know the size until we've enumerated
// we'll have to dump the objects in a list first then
int capacity = array.Length - index;
int numObjects = 0;
- ArrayList arrList = new ArrayList ();
+ ArrayList arrList = new ArrayList();
ManagementObjectEnumerator en = this.GetEnumerator();
ManagementBaseObject obj;
numObjects++;
if (numObjects > capacity)
- throw new ArgumentException (null, nameof(index));
+ throw new ArgumentException(null, nameof(index));
}
// If we get here we are OK. Now copy the list to the array
- arrList.CopyTo (array, index);
+ arrList.CopyTo(array, index);
return;
}
/// </summary>
/// <param name='objectCollection'>The target array.</param>
/// <param name=' index'>The index to start from.</param>
- public void CopyTo (ManagementBaseObject[] objectCollection, int index)
+ public void CopyTo(ManagementBaseObject[] objectCollection, int index)
{
- CopyTo ((Array)objectCollection, index);
+ CopyTo((Array)objectCollection, index);
}
//
// Unless this is the first enumerator, we have
// to clone. This may throw if we are non-rewindable.
- if ( this.options.Rewindable == true )
+ if (this.options.Rewindable == true)
{
IEnumWbemClassObject enumWbemClone = null;
int status = (int)ManagementStatus.NoError;
try
{
- status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem ).Clone_( ref enumWbemClone);
+ status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Clone_(ref enumWbemClone);
if ((status & 0x80000000) == 0)
{
//since the original enumerator might not be reset, we need
//to reset the new one.
- status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbemClone ).Reset_( );
+ status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbemClone).Reset_();
}
}
catch (COMException e)
{
- ManagementException.ThrowWithExtendedInfo (e);
+ ManagementException.ThrowWithExtendedInfo(e);
}
if ((status & 0xfffff000) == 0x80041000)
{
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
- return new ManagementObjectEnumerator (this, enumWbemClone);
+ return new ManagementObjectEnumerator(this, enumWbemClone);
}
else
{
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
- return GetEnumerator ();
+ return GetEnumerator();
}
/// <summary>
/// <para>Disposes of resources the object is holding. This is the destructor for the object.</para>
/// </summary>
- ~ManagementObjectEnumerator ()
+ ~ManagementObjectEnumerator()
{
- Dispose ();
+ Dispose();
}
/// method has been called, an attempt to use this object will
/// result in an ObjectDisposedException being thrown.
/// </summary>
- public void Dispose ()
+ public void Dispose()
{
if (!isDisposed)
{
if (null != enumWbem)
{
- Marshal.ReleaseComObject (enumWbem);
+ Marshal.ReleaseComObject(enumWbem);
enumWbem = null;
}
isDisposed = true;
- GC.SuppressFinalize (this);
+ GC.SuppressFinalize(this);
}
}
if (cacheIndex < 0)
throw new InvalidOperationException();
- return ManagementBaseObject.GetBaseObject (cachedObjects[cacheIndex],
+ return ManagementBaseObject.GetBaseObject(cachedObjects[cacheIndex],
collectionObject.scope);
}
}
/// successfully advanced to the next element; <see langword='false'/> if the enumerator has
/// passed the end of the collection.</para>
/// </returns>
- public bool MoveNext ()
+ public bool MoveNext()
{
if (isDisposed)
throw new ObjectDisposedException(name);
//counterparts afterwards.
IWbemClassObject_DoNotMarshal[] tempArray = new IWbemClassObject_DoNotMarshal[collectionObject.options.BlockSize];
- int status = collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem ).Next_(timeout, (uint)collectionObject.options.BlockSize, tempArray, ref cachedCount);
+ int status = collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Next_(timeout, (uint)collectionObject.options.BlockSize, tempArray, ref cachedCount);
securityHandler.Reset();
/// <summary>
/// <para>Resets the enumerator to the beginning of the collection.</para>
/// </summary>
- public void Reset ()
+ public void Reset()
{
if (isDisposed)
throw new ObjectDisposedException(name);
}
catch (COMException e)
{
- ManagementException.ThrowWithExtendedInfo (e);
+ ManagementException.ThrowWithExtendedInfo(e);
}
finally
{
- securityHandler.Reset ();
+ securityHandler.Reset();
}
if ((status & 0xfffff000) == 0x80041000)
}
//Flush the current enumeration cache
- for (int i=(cacheIndex >= 0 ? cacheIndex : 0); i<cachedCount; i++)
+ for (int i = (cacheIndex >= 0 ? cacheIndex : 0); i < cachedCount; i++)
Marshal.ReleaseComObject((IWbemClassObject_DoNotMarshal)(Marshal.GetObjectForIUnknown(cachedObjects[i])));
cachedCount = 0;
/// <code lang='VB'>Dim s As New ManagementObjectSearcher()
/// </code>
/// </example>
- public ManagementObjectSearcher() : this((ManagementScope)null, null, null) {}
+ public ManagementObjectSearcher() : this((ManagementScope)null, null, null) { }
//parameterized constructors
/// <summary>
/// <code lang='VB'>Dim s As New ManagementObjectSearcher("SELECT * FROM Win32_Service")
/// </code>
/// </example>
- public ManagementObjectSearcher(string queryString) : this(null, new ObjectQuery(queryString), null) {}
+ public ManagementObjectSearcher(string queryString) : this(null, new ObjectQuery(queryString), null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObjectSearcher'/> class used to invoke the
/// Dim s As New ManagementObjectSearcher(q)
/// </code>
/// </example>
- public ManagementObjectSearcher(ObjectQuery query) : this (null, query, null) {}
+ public ManagementObjectSearcher(ObjectQuery query) : this(null, query, null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObjectSearcher'/> class used to invoke the
/// </code>
/// </example>
public ManagementObjectSearcher(string scope, string queryString) :
- this(new ManagementScope(scope), new ObjectQuery(queryString), null) {}
+ this(new ManagementScope(scope), new ObjectQuery(queryString), null)
+ { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObjectSearcher'/> class used to invoke the
/// Dim s As New ManagementObjectSearcher(myScope,q)
/// </code>
/// </example>
- public ManagementObjectSearcher(ManagementScope scope, ObjectQuery query) : this(scope, query, null) {}
+ public ManagementObjectSearcher(ManagementScope scope, ObjectQuery query) : this(scope, query, null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObjectSearcher'/> class used to invoke the specified
/// </code>
/// </example>
public ManagementObjectSearcher(string scope, string queryString, EnumerationOptions options) :
- this(new ManagementScope(scope), new ObjectQuery(queryString), options) {}
+ this(new ManagementScope(scope), new ObjectQuery(queryString), options)
+ { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementObjectSearcher'/> class to be
/// used to invoke the specified query in the specified scope, with the specified
set
{
if (null != value)
- scope = (ManagementScope) value.Clone ();
+ scope = (ManagementScope)value.Clone();
else
- throw new ArgumentNullException (nameof(value));
+ throw new ArgumentNullException(nameof(value));
}
}
set
{
if (null != value)
- query = (ObjectQuery)value.Clone ();
+ query = (ObjectQuery)value.Clone();
else
- throw new ArgumentNullException (nameof(value));
+ throw new ArgumentNullException(nameof(value));
}
}
set
{
if (null != value)
- options = (EnumerationOptions) value.Clone ();
+ options = (EnumerationOptions)value.Clone();
else
throw new ArgumentNullException(nameof(value));
}
/// </returns>
public ManagementObjectCollection Get()
{
- Initialize ();
+ Initialize();
IEnumWbemClassObject ew = null;
SecurityHandler securityHandler = scope.GetSecurityHandler();
EnumerationOptions enumOptions = (EnumerationOptions)options.Clone();
if (((SelectQuery)query).IsSchemaQuery == false) //deep instance enumeration
{
- status = scope.GetSecuredIWbemServicesHandler( scope.GetIWbemServices() ).CreateInstanceEnum_(
+ status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).CreateInstanceEnum_(
((SelectQuery)query).ClassName,
enumOptions.Flags,
enumOptions.GetContext(),
}
else //deep class enumeration
{
- status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices() ).CreateClassEnum_(((SelectQuery)query).ClassName,
+ status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).CreateClassEnum_(((SelectQuery)query).ClassName,
enumOptions.Flags,
enumOptions.GetContext(),
- ref ew );
+ ref ew);
}
}
else //we can use ExecQuery
{
//Make sure the EnumerateDeep flag bit is turned off because it's invalid for queries
enumOptions.EnumerateDeep = true;
- status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices() ).ExecQuery_(
+ status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).ExecQuery_(
query.QueryLanguage,
query.QueryString,
enumOptions.Flags,
enumOptions.GetContext(),
- ref ew );
+ ref ew);
}
}
catch (COMException e)
public void Get(ManagementOperationObserver watcher)
{
if (null == watcher)
- throw new ArgumentNullException (nameof(watcher));
+ throw new ArgumentNullException(nameof(watcher));
- Initialize ();
- IWbemServices wbemServices = scope.GetIWbemServices ();
+ Initialize();
+ IWbemServices wbemServices = scope.GetIWbemServices();
EnumerationOptions enumOptions = (EnumerationOptions)options.Clone();
// Ensure we switch off ReturnImmediately as this is invalid for async calls
if (watcher.HaveListenersForProgress)
enumOptions.SendStatus = true;
- WmiEventSink sink = watcher.GetNewSink (scope, enumOptions.Context);
+ WmiEventSink sink = watcher.GetNewSink(scope, enumOptions.Context);
SecurityHandler securityHandler = scope.GetSecurityHandler();
int status = (int)ManagementStatus.NoError;
if (((SelectQuery)query).IsSchemaQuery == false) //deep instance enumeration
{
- status = scope.GetSecuredIWbemServicesHandler( wbemServices ).CreateInstanceEnumAsync_(((SelectQuery)query).ClassName,
+ status = scope.GetSecuredIWbemServicesHandler(wbemServices).CreateInstanceEnumAsync_(((SelectQuery)query).ClassName,
enumOptions.Flags,
enumOptions.GetContext(),
sink.Stub);
}
else
{
- status = scope.GetSecuredIWbemServicesHandler( wbemServices ).CreateClassEnumAsync_(((SelectQuery)query).ClassName,
+ status = scope.GetSecuredIWbemServicesHandler(wbemServices).CreateClassEnumAsync_(((SelectQuery)query).ClassName,
enumOptions.Flags,
enumOptions.GetContext(),
sink.Stub);
{
//Make sure the EnumerateDeep flag bit is turned off because it's invalid for queries
enumOptions.EnumerateDeep = true;
- status = scope.GetSecuredIWbemServicesHandler( wbemServices ).ExecQueryAsync_(
+ status = scope.GetSecuredIWbemServicesHandler(wbemServices).ExecQueryAsync_(
query.QueryLanguage,
query.QueryString,
enumOptions.Flags,
}
catch (COMException e)
{
- watcher.RemoveSink (sink);
- ManagementException.ThrowWithExtendedInfo (e);
+ watcher.RemoveSink(sink);
+ ManagementException.ThrowWithExtendedInfo(e);
}
finally
{
/// <summary>
/// <para>Represents the method that will handle the <see cref='System.Management.ManagementOperationObserver.Completed'/> event.</para>
/// </summary>
- public delegate void CompletedEventHandler (object sender, CompletedEventArgs e);
+ public delegate void CompletedEventHandler(object sender, CompletedEventArgs e);
/// <summary>
/// <para>Represents the method that will handle the <see cref='System.Management.ManagementOperationObserver.Progress'/> event.</para>
/// </summary>
- public delegate void ProgressEventHandler (object sender, ProgressEventArgs e);
+ public delegate void ProgressEventHandler(object sender, ProgressEventArgs e);
/// <summary>
/// <para>Represents the method that will handle the <see cref='System.Management.ManagementOperationObserver.ObjectPut'/> event.</para>
/// <summary>
/// <para> Occurs when a new object is available.</para>
/// </summary>
- public event ObjectReadyEventHandler ObjectReady;
+ public event ObjectReadyEventHandler ObjectReady;
/// <summary>
/// <para> Occurs when an operation has completed.</para>
/// </summary>
- public event CompletedEventHandler Completed;
+ public event CompletedEventHandler Completed;
/// <summary>
/// <para> Occurs to indicate the progress of an ongoing operation.</para>
/// </summary>
- public event ProgressEventHandler Progress;
+ public event ProgressEventHandler Progress;
/// <summary>
/// <para> Occurs when an object has been successfully committed.</para>
/// </summary>
- public event ObjectPutEventHandler ObjectPut;
+ public event ObjectPutEventHandler ObjectPut;
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementOperationObserver'/> class. This is the default constructor.</para>
/// </summary>
- public ManagementOperationObserver ()
+ public ManagementOperationObserver()
{
// We make our sink collection synchronized
- m_sinkCollection = new Hashtable ();
- delegateInvoker = new WmiDelegateInvoker (this);
+ m_sinkCollection = new Hashtable();
+ delegateInvoker = new WmiDelegateInvoker(this);
}
/// <summary>
/// <para> Cancels all outstanding operations.</para>
/// </summary>
- public void Cancel ()
+ public void Cancel()
{
// Cancel all the sinks we have - make a copy to avoid things
// changing under our feet
- Hashtable copiedSinkTable = new Hashtable ();
+ Hashtable copiedSinkTable = new Hashtable();
lock (m_sinkCollection)
{
try
{
- sinkEnum.Reset ();
+ sinkEnum.Reset();
- while (sinkEnum.MoveNext ())
+ while (sinkEnum.MoveNext())
{
- DictionaryEntry entry = (DictionaryEntry) sinkEnum.Current;
- copiedSinkTable.Add (entry.Key, entry.Value);
+ DictionaryEntry entry = (DictionaryEntry)sinkEnum.Current;
+ copiedSinkTable.Add(entry.Key, entry.Value);
}
}
catch
try
{
IDictionaryEnumerator copiedSinkEnum = copiedSinkTable.GetEnumerator();
- copiedSinkEnum.Reset ();
+ copiedSinkEnum.Reset();
- while (copiedSinkEnum.MoveNext ())
+ while (copiedSinkEnum.MoveNext())
{
- DictionaryEntry entry = (DictionaryEntry) copiedSinkEnum.Current;
- WmiEventSink eventSink = (WmiEventSink) entry.Value;
+ DictionaryEntry entry = (DictionaryEntry)copiedSinkEnum.Current;
+ WmiEventSink eventSink = (WmiEventSink)entry.Value;
try
{
- eventSink.Cancel ();
+ eventSink.Cancel();
}
catch
{
}
}
- internal WmiEventSink GetNewSink (
+ internal WmiEventSink GetNewSink(
ManagementScope scope,
object context)
{
// Add it to our collection
lock (m_sinkCollection)
{
- m_sinkCollection.Add (eventSink.GetHashCode(), eventSink);
+ m_sinkCollection.Add(eventSink.GetHashCode(), eventSink);
}
return eventSink;
try
{
if (Progress != null)
- result = ((Progress.GetInvocationList ()).Length > 0);
+ result = ((Progress.GetInvocationList()).Length > 0);
}
catch
{
return result;
}
}
- internal WmiEventSink GetNewPutSink (
+ internal WmiEventSink GetNewPutSink(
ManagementScope scope,
object context,
string path,
// Add it to our collection
lock (m_sinkCollection)
{
- m_sinkCollection.Add (eventSink.GetHashCode(), eventSink);
+ m_sinkCollection.Add(eventSink.GetHashCode(), eventSink);
}
return eventSink;
}
}
- internal WmiGetEventSink GetNewGetSink (
+ internal WmiGetEventSink GetNewGetSink(
ManagementScope scope,
object context,
ManagementObject managementObject)
// Add it to our collection
lock (m_sinkCollection)
{
- m_sinkCollection.Add (eventSink.GetHashCode(), eventSink);
+ m_sinkCollection.Add(eventSink.GetHashCode(), eventSink);
}
return eventSink;
}
}
- internal void RemoveSink (WmiEventSink eventSink)
+ internal void RemoveSink(WmiEventSink eventSink)
{
try
{
lock (m_sinkCollection)
{
- m_sinkCollection.Remove (eventSink.GetHashCode ());
+ m_sinkCollection.Remove(eventSink.GetHashCode());
}
// Release the stub as we are now disconnected
- eventSink.ReleaseStub ();
+ eventSink.ReleaseStub();
}
catch
{
/// Fires the ObjectReady event to whomsoever is listening
/// </summary>
/// <param name="args"> </param>
- internal void FireObjectReady (ObjectReadyEventArgs args)
+ internal void FireObjectReady(ObjectReadyEventArgs args)
{
try
{
- delegateInvoker.FireEventToDelegates (ObjectReady, args);
+ delegateInvoker.FireEventToDelegates(ObjectReady, args);
}
catch
{
}
}
- internal void FireCompleted (CompletedEventArgs args)
+ internal void FireCompleted(CompletedEventArgs args)
{
try
{
- delegateInvoker.FireEventToDelegates (Completed, args);
+ delegateInvoker.FireEventToDelegates(Completed, args);
}
catch
{
}
}
- internal void FireProgress (ProgressEventArgs args)
+ internal void FireProgress(ProgressEventArgs args)
{
try
{
- delegateInvoker.FireEventToDelegates (Progress, args);
+ delegateInvoker.FireEventToDelegates(Progress, args);
}
catch
{
}
}
- internal void FireObjectPut (ObjectPutEventArgs args)
+ internal void FireObjectPut(ObjectPutEventArgs args)
{
try
{
- delegateInvoker.FireEventToDelegates (ObjectPut, args);
+ delegateInvoker.FireEventToDelegates(ObjectPut, args);
}
catch
{
private readonly ManagementEventArgs args;
private readonly AutoResetEvent h;
- internal WmiEventState (Delegate d, ManagementEventArgs args, AutoResetEvent h)
+ internal WmiEventState(Delegate d, ManagementEventArgs args, AutoResetEvent h)
{
this.d = d;
this.args = args;
{
internal object sender;
- internal WmiDelegateInvoker (object sender)
+ internal WmiDelegateInvoker(object sender)
{
this.sender = sender;
}
/// <param name="md">The MulticastDelegate representing the collection
/// of targets for the event</param>
/// <param name="args">The accompanying event arguments</param>
- internal void FireEventToDelegates (MulticastDelegate md, ManagementEventArgs args)
+ internal void FireEventToDelegates(MulticastDelegate md, ManagementEventArgs args)
{
try
{
{
try
{
- d.DynamicInvoke (new object [] {this.sender, args});
+ d.DynamicInvoke(new object[] { this.sender, args });
}
catch
{
/// <summary>
/// <para>The default COM authentication level. WMI uses the default Windows Authentication setting.</para>
/// </summary>
- Default=0,
+ Default = 0,
/// <summary>
/// <para> No COM authentication.</para>
/// </summary>
- None=1,
+ None = 1,
/// <summary>
/// <para> Connect-level COM authentication.</para>
/// </summary>
- Connect=2,
+ Connect = 2,
/// <summary>
/// <para> Call-level COM authentication.</para>
/// </summary>
- Call=3,
+ Call = 3,
/// <summary>
/// <para> Packet-level COM authentication.</para>
/// </summary>
- Packet=4,
+ Packet = 4,
/// <summary>
/// <para>Packet Integrity-level COM authentication.</para>
/// </summary>
- PacketIntegrity=5,
+ PacketIntegrity = 5,
/// <summary>
/// <para>Packet Privacy-level COM authentication.</para>
/// </summary>
- PacketPrivacy=6,
+ PacketPrivacy = 6,
/// <summary>
/// <para>The default COM authentication level. WMI uses the default Windows Authentication setting.</para>
/// </summary>
- Unchanged=-1
+ Unchanged = -1
}
/// <summary>
/// <summary>
/// <para>Default impersonation.</para>
/// </summary>
- Default=0,
+ Default = 0,
/// <summary>
/// <para> Anonymous COM impersonation level that hides the
/// identity of the caller. Calls to WMI may fail
/// with this impersonation level.</para>
/// </summary>
- Anonymous=1,
+ Anonymous = 1,
/// <summary>
/// <para> Identify-level COM impersonation level that allows objects
/// to query the credentials of the caller. Calls to
/// WMI may fail with this impersonation level.</para>
/// </summary>
- Identify=2,
+ Identify = 2,
/// <summary>
/// <para> Impersonate-level COM impersonation level that allows
/// objects to use the credentials of the caller. This is the recommended impersonation level for WMI calls.</para>
/// </summary>
- Impersonate=3,
+ Impersonate = 3,
/// <summary>
/// <para> Delegate-level COM impersonation level that allows objects
/// to permit other objects to use the credentials of the caller. This
/// level, which will work with WMI calls but may constitute an unnecessary
/// security risk, is supported only under Windows 2000.</para>
/// </summary>
- Delegate=4
+ Delegate = 4
}
/// <summary>
/// <para> Updates an existing object
/// only; does not create a new object.</para>
/// </summary>
- UpdateOnly=1,
+ UpdateOnly = 1,
/// <summary>
/// <para> Creates an object only;
/// does not update an existing object.</para>
/// </summary>
- CreateOnly=2,
+ CreateOnly = 2,
/// <summary>
/// <para> Saves the object, whether
/// updating an existing object or creating a new object.</para>
/// </summary>
- UpdateOrCreate=3
+ UpdateOrCreate = 3
}
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
FireIdentifierChanged();
}
- internal int Flags {
+ internal int Flags
+ {
get { return flags; }
set { flags = value; }
}
ManagementNamedValueCollection oldContext = context;
if (null != value)
- context = (ManagementNamedValueCollection) value.Clone();
+ context = (ManagementNamedValueCollection)value.Clone();
else
- context = new ManagementNamedValueCollection ();
+ context = new ManagementNamedValueCollection();
if (null != oldContext)
oldContext.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
}
- internal ManagementOptions() : this(null, InfiniteTimeout) {}
- internal ManagementOptions(ManagementNamedValueCollection context, TimeSpan timeout) : this(context, timeout, 0) {}
+ internal ManagementOptions() : this(null, InfiniteTimeout) { }
+ internal ManagementOptions(ManagementNamedValueCollection context, TimeSpan timeout) : this(context, timeout, 0) { }
internal ManagementOptions(ManagementNamedValueCollection context, TimeSpan timeout, int flags)
{
this.flags = flags;
}
- internal IWbemContext GetContext () {
+ internal IWbemContext GetContext()
+ {
if (context != null)
return context.GetContext();
else
public bool ReturnImmediately
{
get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY) != 0) ? true : false); }
- set {
+ set
+ {
Flags = (value == false) ? (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY) :
(Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY);
}
public int BlockSize
{
get { return blockSize; }
- set {
+ set
+ {
//Unfortunately BlockSize was defined as int, but valid values are only > 0
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(value));
public bool Rewindable
{
get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_FORWARD_ONLY) != 0) ? false : true); }
- set {
+ set
+ {
Flags = (value == true) ? (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_FORWARD_ONLY) :
(Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_FORWARD_ONLY);
}
public bool UseAmendedQualifiers
{
get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) != 0) ? true : false); }
- set {
+ set
+ {
Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) :
(Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS);
}
get
{ return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_ENSURE_LOCATABLE) != 0) ? true : false); }
set
- { Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_ENSURE_LOCATABLE) :
- (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_ENSURE_LOCATABLE); }
+ {
+ Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_ENSURE_LOCATABLE) :
+ (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_ENSURE_LOCATABLE);
+ }
}
get
{ return (((Flags & (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_PROTOTYPE) != 0) ? true : false); }
set
- { Flags = (value == true) ? (Flags | (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_PROTOTYPE) :
- (Flags & (int)~tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_PROTOTYPE); }
+ {
+ Flags = (value == true) ? (Flags | (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_PROTOTYPE) :
+ (Flags & (int)~tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_PROTOTYPE);
+ }
}
/// <summary>
get
{ return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_DIRECT_READ) != 0) ? true : false); }
set
- { Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_DIRECT_READ) :
- (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_DIRECT_READ); }
+ {
+ Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_DIRECT_READ) :
+ (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_DIRECT_READ);
+ }
}
get
{ return (((Flags & (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_SHALLOW) != 0) ? false : true); }
set
- { Flags = (value == false) ? (Flags | (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_SHALLOW) :
- (Flags & (int)~tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_SHALLOW); }
+ {
+ Flags = (value == false) ? (Flags | (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_SHALLOW) :
+ (Flags & (int)~tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_SHALLOW);
+ }
}
/// class with default values (see the individual property descriptions
/// for what the default values are). This is the default constructor. </para>
/// </summary>
- public EnumerationOptions() : this (null, InfiniteTimeout, 1, true, true, false, false, false, false, false) {}
+ public EnumerationOptions() : this(null, InfiniteTimeout, 1, true, true, false, false, false, false, false) { }
/// <returns>
/// <para>The cloned object.</para>
/// </returns>
- public override object Clone ()
+ public override object Clone()
{
ManagementNamedValueCollection newContext = null;
if (null != Context)
newContext = (ManagementNamedValueCollection)Context.Clone();
- return new EnumerationOptions (newContext, Timeout, blockSize, Rewindable,
+ return new EnumerationOptions(newContext, Timeout, blockSize, Rewindable,
ReturnImmediately, UseAmendedQualifiers, EnsureLocatable, PrototypeOnly, DirectRead, EnumerateDeep);
}
set
{
blockSize = value;
- FireIdentifierChanged ();
+ FireIdentifierChanged();
}
}
/// This is the default constructor.</para>
/// </summary>
public EventWatcherOptions()
- : this (null, InfiniteTimeout, 1) {}
+ : this(null, InfiniteTimeout, 1) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.EventWatcherOptions'/> class with the given
public EventWatcherOptions(ManagementNamedValueCollection context, TimeSpan timeout, int blockSize)
: base(context, timeout)
{
- Flags = (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY|(int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_FORWARD_ONLY;
+ Flags = (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_FORWARD_ONLY;
BlockSize = blockSize;
}
/// <returns>
/// The cloned object.
/// </returns>
- public override object Clone ()
+ public override object Clone()
{
ManagementNamedValueCollection newContext = null;
if (null != Context)
newContext = (ManagementNamedValueCollection)Context.Clone();
- return new EventWatcherOptions (newContext, Timeout, blockSize);
+ return new EventWatcherOptions(newContext, Timeout, blockSize);
}
}//EventWatcherOptions
public bool UseAmendedQualifiers
{
get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) != 0) ? true : false); }
- set {
+ set
+ {
Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) :
(Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS);
FireIdentifierChanged();
/// <para>Initializes a new instance of the <see cref='System.Management.ObjectGetOptions'/> class for getting a WMI object, using
/// default values. This is the default constructor.</para>
/// </summary>
- public ObjectGetOptions() : this(null, InfiniteTimeout, false) {}
+ public ObjectGetOptions() : this(null, InfiniteTimeout, false) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ObjectGetOptions'/> class for getting a WMI object, using the
/// specified provider-specific context.</para>
/// </summary>
/// <param name='context'>A provider-specific, named-value pairs context object to be passed through to the provider.</param>
- public ObjectGetOptions(ManagementNamedValueCollection context) : this(context, InfiniteTimeout, false) {}
+ public ObjectGetOptions(ManagementNamedValueCollection context) : this(context, InfiniteTimeout, false) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ObjectGetOptions'/> class for getting a WMI object,
/// <returns>
/// <para>The cloned object.</para>
/// </returns>
- public override object Clone ()
+ public override object Clone()
{
ManagementNamedValueCollection newContext = null;
if (null != Context)
newContext = (ManagementNamedValueCollection)Context.Clone();
- return new ObjectGetOptions (newContext, Timeout, UseAmendedQualifiers);
+ return new ObjectGetOptions(newContext, Timeout, UseAmendedQualifiers);
}
}
public bool UseAmendedQualifiers
{
get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) != 0) ? true : false); }
- set { Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) :
- (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS); }
+ set
+ {
+ Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) :
+ (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS);
+ }
}
/// <summary>
/// </value>
public PutType Type
{
- get { return (((Flags & (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_UPDATE_ONLY) != 0) ? PutType.UpdateOnly :
- ((Flags & (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_CREATE_ONLY) != 0) ? PutType.CreateOnly :
- PutType.UpdateOrCreate);
+ get
+ {
+ return (((Flags & (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_UPDATE_ONLY) != 0) ? PutType.UpdateOnly :
+ ((Flags & (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_CREATE_ONLY) != 0) ? PutType.CreateOnly :
+ PutType.UpdateOrCreate);
}
- set {
+ set
+ {
Flags |= value switch
{
PutType.UpdateOnly => (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_UPDATE_ONLY,
/// <para>Initializes a new instance of the <see cref='System.Management.PutOptions'/> class for put operations, using default values.
/// This is the default constructor.</para>
/// </summary>
- public PutOptions() : this(null, InfiniteTimeout, false, PutType.UpdateOrCreate) {}
+ public PutOptions() : this(null, InfiniteTimeout, false, PutType.UpdateOrCreate) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.PutOptions'/> class for committing a WMI object, using the
/// specified provider-specific context.</para>
/// </summary>
/// <param name='context'>A provider-specific, named-value pairs context object to be passed through to the provider.</param>
- public PutOptions(ManagementNamedValueCollection context) : this(context, InfiniteTimeout, false, PutType.UpdateOrCreate) {}
+ public PutOptions(ManagementNamedValueCollection context) : this(context, InfiniteTimeout, false, PutType.UpdateOrCreate) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.PutOptions'/> class for committing a WMI object, using
/// <returns>
/// <para>The cloned object.</para>
/// </returns>
- public override object Clone ()
+ public override object Clone()
{
ManagementNamedValueCollection newContext = null;
if (null != Context)
newContext = (ManagementNamedValueCollection)Context.Clone();
- return new PutOptions (newContext, Timeout, UseAmendedQualifiers, Type);
+ return new PutOptions(newContext, Timeout, UseAmendedQualifiers, Type);
}
}
/// <para>Initializes a new instance of the <see cref='System.Management.DeleteOptions'/> class for the delete operation, using default values.
/// This is the default constructor.</para>
/// </summary>
- public DeleteOptions() : base () {}
+ public DeleteOptions() : base() { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.DeleteOptions'/> class for a delete operation, using
/// </summary>
/// <param name='context'>A provider-specific, named-value pairs object to be passed through to the provider. </param>
/// <param name='timeout'>The length of time to let the operation perform before it times out. The default value is <see cref='System.Management.ManagementOptions.InfiniteTimeout'/> . Setting this parameter will invoke the operation semisynchronously.</param>
- public DeleteOptions(ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) {}
+ public DeleteOptions(ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { }
/// <summary>
/// <para> Returns a copy of the object.</para>
/// <returns>
/// <para>A cloned object.</para>
/// </returns>
- public override object Clone ()
+ public override object Clone()
{
ManagementNamedValueCollection newContext = null;
if (null != Context)
newContext = (ManagementNamedValueCollection)Context.Clone();
- return new DeleteOptions (newContext, Timeout);
+ return new DeleteOptions(newContext, Timeout);
}
}
/// <para>Initializes a new instance of the <see cref='System.Management.InvokeMethodOptions'/> class for the <see cref='System.Management.ManagementObject.InvokeMethod(string, ManagementBaseObject, InvokeMethodOptions) '/> operation, using default values.
/// This is the default constructor.</para>
/// </summary>
- public InvokeMethodOptions() : base () {}
+ public InvokeMethodOptions() : base() { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.InvokeMethodOptions'/> class for an invoke operation using
/// </summary>
/// <param name=' context'>A provider-specific, named-value pairs object to be passed through to the provider. </param>
/// <param name='timeout'>The length of time to let the operation perform before it times out. The default value is <see cref='System.Management.ManagementOptions.InfiniteTimeout'/> . Setting this parameter will invoke the operation semisynchronously.</param>
- public InvokeMethodOptions(ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) {}
+ public InvokeMethodOptions(ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { }
/// <summary>
/// <para> Returns a copy of the object.</para>
/// <returns>
/// <para>The cloned object.</para>
/// </returns>
- public override object Clone ()
+ public override object Clone()
{
ManagementNamedValueCollection newContext = null;
if (null != Context)
newContext = (ManagementNamedValueCollection)Context.Clone();
- return new InvokeMethodOptions (newContext, Timeout);
+ return new InvokeMethodOptions(newContext, Timeout);
}
}
public string Locale
{
get { return (null != locale) ? locale : string.Empty; }
- set {
+ set
+ {
if (locale != value)
{
locale = value;
public string Username
{
get { return username; }
- set {
+ set
+ {
if (username != value)
{
username = value;
/// </remarks>
public string Password
{
- set {
- if ( value != null)
+ set
+ {
+ if (value != null)
{
if (securePassword == null)
{
securePassword = new SecureString();
- for ( int i=0; i <value.Length; i++)
+ for (int i = 0; i < value.Length; i++)
{
securePassword.AppendChar(value[i]);
}
else
{
SecureString tempStr = new SecureString();
- for ( int i=0; i <value.Length; i++)
+ for (int i = 0; i < value.Length; i++)
{
tempStr.AppendChar(value[i]);
}
securePassword.Clear();
securePassword = tempStr.Copy();
FireIdentifierChanged();
- tempStr.Dispose();
+ tempStr.Dispose();
}
}
else
/// </remarks>
public SecureString SecurePassword
{
- set{
- if ( value != null)
+ set
+ {
+ if (value != null)
{
- if ( securePassword == null)
+ if (securePassword == null)
{
securePassword = value.Copy();
}
public string Authority
{
get { return (null != authority) ? authority : string.Empty; }
- set {
+ set
+ {
if (authority != value)
{
authority = value;
public ImpersonationLevel Impersonation
{
get { return impersonation; }
- set {
+ set
+ {
if (impersonation != value)
{
impersonation = value;
public AuthenticationLevel Authentication
{
get { return authentication; }
- set {
+ set
+ {
if (authentication != value)
{
authentication = value;
public bool EnablePrivileges
{
get { return enablePrivileges; }
- set {
+ set
+ {
if (enablePrivileges != value)
{
enablePrivileges = value;
/// <para>Initializes a new instance of the <see cref='System.Management.ConnectionOptions'/> class for the connection operation, using default values. This is the
/// default constructor.</para>
/// </summary>
- public ConnectionOptions () :
- this (DEFAULTLOCALE, null, (string)null, DEFAULTAUTHORITY,
+ public ConnectionOptions() :
+ this(DEFAULTLOCALE, null, (string)null, DEFAULTAUTHORITY,
DEFAULTIMPERSONATION, DEFAULTAUTHENTICATION,
- DEFAULTENABLEPRIVILEGES, null, InfiniteTimeout) {}
+ DEFAULTENABLEPRIVILEGES, null, InfiniteTimeout)
+ { }
//parameterized
/// <param name=' enablePrivileges'><see langword='true'/>to enable special user privileges; otherwise, <see langword='false'/> . This parameter should only be used when performing an operation that requires special Windows NT user privileges.</param>
/// <param name=' context'>A provider-specific, named value pairs object to be passed through to the provider.</param>
/// <param name=' timeout'>Reserved for future use.</param>
- public ConnectionOptions (string locale,
+ public ConnectionOptions(string locale,
string username, string password, string authority,
ImpersonationLevel impersonation, AuthenticationLevel authentication,
bool enablePrivileges,
- ManagementNamedValueCollection context, TimeSpan timeout) : base (context, timeout)
+ ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout)
{
if (locale != null)
this.locale = locale;
if (password != null)
{
this.securePassword = new SecureString();
- for ( int i=0; i <password.Length; i++)
+ for (int i = 0; i < password.Length; i++)
{
securePassword.AppendChar(password[i]);
}
/// <param name='enablePrivileges'><see langword='true'/>to enable special user privileges; otherwise, <see langword='false'/> . This parameter should only be used when performing an operation that requires special Windows NT user privileges.</param>
/// <param name='context'>A provider-specific, named value pairs object to be passed through to the provider.</param>
/// <param name='timeout'>Reserved for future use.</param>
- public ConnectionOptions (string locale,
+ public ConnectionOptions(string locale,
string username, SecureString password, string authority,
ImpersonationLevel impersonation, AuthenticationLevel authentication,
bool enablePrivileges,
- ManagementNamedValueCollection context, TimeSpan timeout) : base (context, timeout)
+ ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout)
{
if (locale != null)
this.locale = locale;
/// <returns>
/// <para>The cloned object.</para>
/// </returns>
- public override object Clone ()
+ public override object Clone()
{
ManagementNamedValueCollection newContext = null;
if (null != Context)
newContext = (ManagementNamedValueCollection)Context.Clone();
- return new ConnectionOptions (locale, username, GetSecurePassword (),
+ return new ConnectionOptions(locale, username, GetSecurePassword(),
authority, impersonation, authentication, enablePrivileges, newContext, Timeout);
}
{
if (securePassword != null)
{
- try{
+ try
+ {
return System.Runtime.InteropServices.Marshal.SecureStringToBSTR(securePassword);
}
catch (OutOfMemoryException)
else
return IntPtr.Zero;
}
- internal SecureString GetSecurePassword()
+ internal SecureString GetSecurePassword()
{
if (securePassword != null)
return securePassword.Copy();
return null;
}
- internal ConnectionOptions(ManagementNamedValueCollection context, TimeSpan timeout, int flags) : base(context, timeout, flags) {}
+ internal ConnectionOptions(ManagementNamedValueCollection context, TimeSpan timeout, int flags) : base(context, timeout, flags) { }
- internal ConnectionOptions(ManagementNamedValueCollection context) : base(context, InfiniteTimeout) {}
+ internal ConnectionOptions(ManagementNamedValueCollection context) : base(context, InfiniteTimeout) { }
internal static ConnectionOptions _Clone(ConnectionOptions options)
{
/// End Class
/// </code>
/// </example>
- [TypeConverter(typeof(ManagementPathConverter ))]
+ [TypeConverter(typeof(ManagementPathConverter))]
public class ManagementPath : ICloneable
{
private static ManagementPath defaultPath = new ManagementPath("//./root/cimv2");
//Used to minimize the cases in which new wbemPath (WMI object path parser) objects need to be constructed
//This is done for performance reasons.
- private bool isWbemPathShared = false;
+ private bool isWbemPathShared = false;
internal event IdentifierChangedEventHandler IdentifierChanged;
/// </summary>
/// <param name="wbemObject">The WMI object whose __PATH property will
/// be used to supply the returned object</param>
- internal static string GetManagementPath (
+ internal static string GetManagementPath(
IWbemClassObjectFreeThreaded wbemObject)
{
string path = null;
- int status = (int)ManagementStatus.Failed;
+ int status = (int)ManagementStatus.Failed;
if (null != wbemObject)
{
int dummy1 = 0, dummy2 = 0;
object val = null;
- status = wbemObject.Get_ ("__PATH", 0, ref val, ref dummy1, ref dummy2);
+ status = wbemObject.Get_("__PATH", 0, ref val, ref dummy1, ref dummy2);
if ((status < 0) || (val == System.DBNull.Value))
{
//try to get the relpath instead
- status = wbemObject.Get_ ("__RELPATH", 0, ref val, ref dummy1, ref dummy2);
+ status = wbemObject.Get_("__RELPATH", 0, ref val, ref dummy1, ref dummy2);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementPath'/> class that is empty. This is the default constructor.</para>
/// </summary>
- public ManagementPath () : this ((string) null) {}
+ public ManagementPath() : this((string)null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementPath'/> class for the given path.</para>
/// path represented by this object. This value is equivalent to the value of the
/// <see cref='System.Management.ManagementPath.Path'/> property.
/// </returns>
- public override string ToString ()
+ public override string ToString()
{
return this.Path;
}
/// <returns>
/// The cloned object.
/// </returns>
- public ManagementPath Clone ()
+ public ManagementPath Clone()
{
- return new ManagementPath (Path);
+ return new ManagementPath(Path);
}
/// <summary>
/// <returns>
/// The cloned object.
/// </returns>
- object ICloneable.Clone ()
+ object ICloneable.Clone()
{
- return Clone ();
+ return Clone();
}
/// <summary>
}
//private members
- private IWbemPath wmiPath;
+ private IWbemPath wmiPath;
private IWbemPath CreateWbemPath(string path)
{
{
if (null != wbemPath)
{
- uint flags = (uint) tag_WBEM_PATH_CREATE_FLAG.WBEMPATH_CREATE_ACCEPT_ALL;
+ uint flags = (uint)tag_WBEM_PATH_CREATE_FLAG.WBEMPATH_CREATE_ACCEPT_ALL;
//For now we have to special-case the "root" namespace -
// this is because in the case of "root", the path parser cannot tell whether
// this is a namespace name or a class name
if (string.Equals(path, "root", StringComparison.OrdinalIgnoreCase))
- flags = flags | (uint) tag_WBEM_PATH_CREATE_FLAG.WBEMPATH_TREAT_SINGLE_IDENT_AS_NS;
+ flags = flags | (uint)tag_WBEM_PATH_CREATE_FLAG.WBEMPATH_TREAT_SINGLE_IDENT_AS_NS;
int status = wbemPath.SetText_(flags, path);
return pathStr;
}
- private void ClearKeys (bool setAsSingleton)
+ private void ClearKeys(bool setAsSingleton)
{
// Test/utilize isWbemPathShared *only* on public + internal members!
int status = (int)ManagementStatus.NoError;
{
sbyte bSingleton = (setAsSingleton) ? (sbyte)(-1) : (sbyte)0;
status = keyList.MakeSingleton_(bSingleton);
- FireIdentifierChanged ();
+ FireIdentifierChanged();
}
}
}
{
get
{
- return (Path.Length == 0 );
+ return (Path.Length == 0);
}
}
/// <para> Sets the path as a new class path. This means that the path must have
/// a class name but not key values.</para>
/// </summary>
- public void SetAsClass ()
+ public void SetAsClass()
{
if (IsClass || IsInstance)
{
isWbemPathShared = false;
}
- ClearKeys (false);
+ ClearKeys(false);
}
else
- throw new ManagementException (ManagementStatus.InvalidOperation, null, null);
+ throw new ManagementException(ManagementStatus.InvalidOperation, null, null);
}
/// <summary>
/// <para> Sets the path as a new singleton object path. This means that it is a path to an instance but
/// there are no key values.</para>
/// </summary>
- public void SetAsSingleton ()
+ public void SetAsSingleton()
{
if (IsClass || IsInstance)
{
isWbemPathShared = false;
}
- ClearKeys (true);
+ ClearKeys(true);
}
else
- throw new ManagementException (ManagementStatus.InvalidOperation, null, null);
+ throw new ManagementException(ManagementStatus.InvalidOperation, null, null);
}
//
}
catch
{
- throw new ArgumentOutOfRangeException (nameof(value));
+ throw new ArgumentOutOfRangeException(nameof(value));
}
FireIdentifierChanged();
}
// Get the space we need to reserve
uint bufLen = 0;
int status = wmiPath.GetText_(
- (int) tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_RELATIVE_ONLY,
+ (int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_RELATIVE_ONLY,
ref bufLen,
null);
{
char[] pathChars = new char[(int)bufLen];
status = wmiPath.GetText_(
- (int) tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_RELATIVE_ONLY,
+ (int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_RELATIVE_ONLY,
ref bufLen,
pathChars);
pathStr = new string(pathChars, 0, Array.IndexOf(pathChars, '\0'));
{
// No need for isWbemPathShared here since internal SetRelativePath
// always creates a new copy.
- SetRelativePath (value);
+ SetRelativePath(value);
}
catch (COMException)
{
- throw new ArgumentOutOfRangeException (nameof(value));
+ throw new ArgumentOutOfRangeException(nameof(value));
}
FireIdentifierChanged();
}
}
- internal void SetRelativePath (string relPath)
+ internal void SetRelativePath(string relPath)
{
// No need for isWbemPathShared here since internal SetRelativePath
// always creates a new copy.
- ManagementPath newPath = new ManagementPath (relPath);
+ ManagementPath newPath = new ManagementPath(relPath);
newPath.NamespacePath = this.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY);
newPath.Server = this.Server;
wmiPath = newPath.wmiPath;
string newPath = string.Empty;
string nsPath = this.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY);
- if (nsPath.Length>0 )
+ if (nsPath.Length > 0)
newPath = string.Concat(nsPath, ":", relPath);
else
newPath = relPath;
internal string SetNamespacePath(string nsPath, out bool bChange)
{
- int status = (int)ManagementStatus.NoError;
- string nsOrg = null;
- string nsNew = null;
- IWbemPath wmiPathTmp = null;
+ int status = (int)ManagementStatus.NoError;
+ string nsOrg = null;
+ string nsNew = null;
+ IWbemPath wmiPathTmp = null;
bChange = false;
Debug.Assert(nsPath != null);
//
if (status >= 0 && nsPath.Length > 1 &&
(nsPath[0] == '\\' && nsPath[1] == '\\' ||
- nsPath[0] == '/' && nsPath[1] == '/'))
+ nsPath[0] == '/' && nsPath[1] == '/'))
{
uint uLen = 0;
status = wmiPathTmp.GetServer_(ref uLen, null);
}
catch (COMException)
{
- throw new ArgumentOutOfRangeException (nameof(value));
+ throw new ArgumentOutOfRangeException(nameof(value));
}
if (bChange)
}
catch (COMException)
{
- throw new ArgumentOutOfRangeException (nameof(value));
+ throw new ArgumentOutOfRangeException(nameof(value));
}
if (status < 0)
if (value is ManagementPath && destinationType == typeof(InstanceDescriptor))
{
ManagementPath obj = ((ManagementPath)(value));
- ConstructorInfo ctor = typeof(ManagementPath).GetConstructor(new Type[] {typeof(string)});
+ ConstructorInfo ctor = typeof(ManagementPath).GetConstructor(new Type[] { typeof(string) });
if (ctor != null)
{
- return new InstanceDescriptor(ctor, new object[] {obj.Path});
+ return new InstanceDescriptor(ctor, new object[] { obj.Path });
}
}
return base.ConvertTo(context, culture, value, destinationType);
/// derivatives of it are actually used in the API.</para>
/// </remarks>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
- [TypeConverter(typeof(ManagementQueryConverter ))]
+ [TypeConverter(typeof(ManagementQueryConverter))]
public abstract class ManagementQuery : ICloneable
{
internal const string DEFAULTQUERYLANGUAGE = "WQL";
private string queryLanguage;
private string queryString;
- internal void SetQueryString (string qString)
+ internal void SetQueryString(string qString)
{
queryString = qString;
}
//default constructor
- internal ManagementQuery() : this(DEFAULTQUERYLANGUAGE, null) {}
+ internal ManagementQuery() : this(DEFAULTQUERYLANGUAGE, null) { }
//parameterized constructors
- internal ManagementQuery(string query) : this(DEFAULTQUERYLANGUAGE, query) {}
+ internal ManagementQuery(string query) : this(DEFAULTQUERYLANGUAGE, query) { }
internal ManagementQuery(string language, string query)
{
QueryLanguage = language;
/// Parses the query string and sets the property values accordingly.
/// </summary>
/// <param name="query">The query string to be parsed.</param>
- protected internal virtual void ParseQuery (string query) {}
+ protected internal virtual void ParseQuery(string query) { }
//
//properties
/// </value>
public virtual string QueryString
{
- get {return (null != queryString) ? queryString : string.Empty; }
- set {
- if (queryString != value) {
- ParseQuery (value); // this may throw
+ get { return (null != queryString) ? queryString : string.Empty; }
+ set
+ {
+ if (queryString != value)
+ {
+ ParseQuery(value); // this may throw
queryString = value;
- FireIdentifierChanged ();
+ FireIdentifierChanged();
}
}
}
/// </value>
public virtual string QueryLanguage
{
- get {return (null != queryLanguage) ? queryLanguage : string.Empty; }
- set {
- if (queryLanguage != value) {
+ get { return (null != queryLanguage) ? queryLanguage : string.Empty; }
+ set
+ {
+ if (queryLanguage != value)
+ {
queryLanguage = value;
- FireIdentifierChanged ();
+ FireIdentifierChanged();
}
}
}
/// </returns>
public abstract object Clone();
- internal static void ParseToken (ref string q, string token, string op, ref bool bTokenFound, ref string tokenValue)
+ internal static void ParseToken(ref string q, string token, string op, ref bool bTokenFound, ref string tokenValue)
{
if (bTokenFound)
- throw new ArgumentException (SR.InvalidQueryDuplicatedToken); // Invalid query - duplicate token
+ throw new ArgumentException(SR.InvalidQueryDuplicatedToken); // Invalid query - duplicate token
bTokenFound = true;
- q = q.Remove (0, token.Length).TrimStart (null);
+ q = q.Remove(0, token.Length).TrimStart(null);
// Next character should be the operator if any
if (op != null)
}
if (0 == q.Length)
- throw new ArgumentException (SR.InvalidQueryNullToken); // Invalid query - token has no value
+ throw new ArgumentException(SR.InvalidQueryNullToken); // Invalid query - token has no value
// Next token should be the token value - look for terminating WS
// or end of string
int i;
- if (-1 == (i = q.IndexOf (' ')))
+ if (-1 == (i = q.IndexOf(' ')))
i = q.Length; // No WS => consume entire string
- tokenValue = q.Substring (0, i);
- q = q.Remove (0, tokenValue.Length).TrimStart(null);
+ tokenValue = q.Substring(0, i);
+ q = q.Remove(0, tokenValue.Length).TrimStart(null);
}
- internal static void ParseToken (ref string q, string token, ref bool bTokenFound)
+ internal static void ParseToken(ref string q, string token, ref bool bTokenFound)
{
if (bTokenFound)
- throw new ArgumentException (SR.InvalidQueryDuplicatedToken); // Invalid query - duplicate token
+ throw new ArgumentException(SR.InvalidQueryDuplicatedToken); // Invalid query - duplicate token
bTokenFound = true;
- q = q.Remove (0, token.Length).TrimStart (null);
+ q = q.Remove(0, token.Length).TrimStart(null);
}
}//ManagementQuery
/// class with no initialized values. This
/// is the default constructor.</para>
/// </summary>
- public ObjectQuery() : base() {}
+ public ObjectQuery() : base() { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ObjectQuery'/>
/// class
/// for a specific query string.</para>
/// </summary>
/// <param name='query'>The string representation of the query.</param>
- public ObjectQuery(string query) : base(query) {}
+ public ObjectQuery(string query) : base(query) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ObjectQuery'/>
/// class for a specific
/// </summary>
/// <param name='language'>The query language in which this query is specified.</param>
/// <param name=' query'>The string representation of the query.</param>
- public ObjectQuery(string language, string query) : base(language, query) {}
+ public ObjectQuery(string language, string query) : base(language, query) { }
//ICloneable
/// <summary>
/// <returns>
/// The cloned object.
/// </returns>
- public override object Clone ()
+ public override object Clone()
{
return new ObjectQuery(QueryLanguage, QueryString);
}
/// class. This is the
/// default constructor.</para>
/// </summary>
- public EventQuery() : base() {}
+ public EventQuery() : base() { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.EventQuery'/>
/// class for the specified query.</para>
/// </summary>
/// <param name='query'>A textual representation of the event query.</param>
- public EventQuery(string query) : base(query) {}
+ public EventQuery(string query) : base(query) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.EventQuery'/>
/// class for the specified
/// </summary>
/// <param name='language'>The language in which the query string is specified. </param>
/// <param name=' query'>The string representation of the query.</param>
- public EventQuery(string language, string query) : base(language, query) {}
+ public EventQuery(string language, string query) : base(language, query) { }
//ICloneable
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.WqlObjectQuery'/> class. This is the
/// default constructor.</para>
/// </summary>
- public WqlObjectQuery() : base(null) {}
+ public WqlObjectQuery() : base(null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.WqlObjectQuery'/> class initialized to the
/// specified query.</para>
/// </summary>
/// <param name='query'><para> The representation of the data query.</para></param>
- public WqlObjectQuery(string query) : base(query) {}
+ public WqlObjectQuery(string query) : base(query) { }
//QueryLanguage property is read-only in this class (does this work ??)
/// <summary>
public override string QueryLanguage
{
get
- {return base.QueryLanguage; }
+ { return base.QueryLanguage; }
}
//ICloneable
/// class. This is the
/// default constructor.</para>
/// </summary>
- public SelectQuery() :this(null) {}
+ public SelectQuery() : this(null) { }
//parameterized constructors
//ISSUE : We have 2 possible constructors that take a single string :
/// </example>
public SelectQuery(string queryOrClassName)
{
- selectedProperties = new StringCollection ();
+ selectedProperties = new StringCollection();
if (null != queryOrClassName)
{
// Do some basic sanity checking on whether it's a class name
//
- ManagementPath p = new ManagementPath (queryOrClassName);
+ ManagementPath p = new ManagementPath(queryOrClassName);
- if (p.IsClass && (p.NamespacePath.Length==0))
+ if (p.IsClass && (p.NamespacePath.Length == 0))
ClassName = queryOrClassName;
else
- throw new ArgumentException (SR.InvalidQuery, nameof(queryOrClassName));
+ throw new ArgumentException(SR.InvalidQuery, nameof(queryOrClassName));
}
}
/// <code lang='VB'>Dim s As New SelectQuery("Win32_Process", "HandleID=1234")
/// </code>
/// </example>
- public SelectQuery(string className, string condition) : this(className, condition, null) {}
+ public SelectQuery(string className, string condition) : this(className, condition, null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.SelectQuery'/>
/// properties)
/// </code>
/// </example>
- public SelectQuery(string className, string condition, string[] selectedProperties) : base ()
+ public SelectQuery(string className, string condition, string[] selectedProperties) : base()
{
this.isSchemaQuery = false;
this.className = className;
this.condition = condition;
- this.selectedProperties = new StringCollection ();
+ this.selectedProperties = new StringCollection();
if (null != selectedProperties)
- this.selectedProperties.AddRange (selectedProperties);
+ this.selectedProperties.AddRange(selectedProperties);
BuildQuery();
}
/// <code lang='VB'>Dim s As New SelectQuery(true, "__CLASS = ""Win32_Service""")
/// </code>
/// </example>
- public SelectQuery(bool isSchemaQuery, string condition) : base ()
+ public SelectQuery(bool isSchemaQuery, string condition) : base()
{
if (isSchemaQuery == false)
throw new ArgumentException(SR.InvalidQuery, nameof(isSchemaQuery));
/// </example>
public override string QueryString
{
- get {
+ get
+ {
// We need to force a rebuild as we may not have detected
// a change to selected properties
- BuildQuery ();
- return base.QueryString; }
- set {
+ BuildQuery();
+ return base.QueryString;
+ }
+ set
+ {
base.QueryString = value;
}
}
public StringCollection SelectedProperties
{
get { return selectedProperties; }
- set {
+ set
+ {
if (null != value)
{
// A tad painful since StringCollection doesn't support ICloneable
StringCollection src = (StringCollection)value;
- StringCollection dst = new StringCollection ();
+ StringCollection dst = new StringCollection();
foreach (string s in src)
- dst.Add (s);
+ dst.Add(s);
selectedProperties = dst;
}
else
- selectedProperties = new StringCollection ();
+ selectedProperties = new StringCollection();
BuildQuery();
FireIdentifierChanged();
//If the class name is not set we can't build a query
//Shouldn't throw here because the user may be in the process of filling in the properties...
if (className == null)
- SetQueryString (string.Empty);
+ SetQueryString(string.Empty);
- if ((className == null) || (className.Length==0))
+ if ((className == null) || (className.Length == 0))
return;
//Select clause
//Set the queryString member to the built query (NB: note we set
//by accessing the internal helper function rather than the property,
//since we do not want to force a parse of a query we just built).
- SetQueryString (s);
+ SetQueryString(s);
}
string keyword = TokenSelect;
if ((q.Length >= keyword.Length) && (string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase) == 0)) //select clause found
{
- ParseToken (ref q, keyword, ref bFound);
+ ParseToken(ref q, keyword, ref bFound);
if (q[0] != '*') //we have properties
{
if (null != selectedProperties)
- selectedProperties.Clear ();
+ selectedProperties.Clear();
else
- selectedProperties = new StringCollection ();
+ selectedProperties = new StringCollection();
//get the property list
while (true)
if ((i = q.IndexOf(',')) > 0)
{
tempProp = q.Substring(0, i);
- q = q.Remove(0, i+1).TrimStart(null);
+ q = q.Remove(0, i + 1).TrimStart(null);
tempProp = tempProp.Trim();
- if (tempProp.Length>0)
+ if (tempProp.Length > 0)
selectedProperties.Add(tempProp);
}
else
// Should start with "select"
if ((q.Length < keyword.Length) ||
- (0 != string.Compare (q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
- throw new ArgumentException (SR.InvalidQuery, "select");
+ (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
+ throw new ArgumentException(SR.InvalidQuery, "select");
- q = q.Remove (0, keyword.Length).TrimStart (null);
+ q = q.Remove(0, keyword.Length).TrimStart(null);
// Next should be a '*'
- if (0 != q.IndexOf ('*', 0))
- throw new ArgumentException (SR.InvalidQuery, "*");
+ if (0 != q.IndexOf('*', 0))
+ throw new ArgumentException(SR.InvalidQuery, "*");
- q = q.Remove (0, 1).TrimStart (null);
+ q = q.Remove(0, 1).TrimStart(null);
// Next should be "from"
keyword = "from";
if ((q.Length < keyword.Length) ||
- (0 != string.Compare (q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
- throw new ArgumentException (SR.InvalidQuery, "from");
+ (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
+ throw new ArgumentException(SR.InvalidQuery, "from");
- q = q.Remove (0, keyword.Length).TrimStart (null);
+ q = q.Remove(0, keyword.Length).TrimStart(null);
// Next should be "meta_class"
keyword = "meta_class";
if ((q.Length < keyword.Length) ||
- (0 != string.Compare (q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
- throw new ArgumentException (SR.InvalidQuery, "meta_class");
+ (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
+ throw new ArgumentException(SR.InvalidQuery, "meta_class");
- q = q.Remove (0, keyword.Length).TrimStart (null);
+ q = q.Remove(0, keyword.Length).TrimStart(null);
// There may be a where clause
if (0 < q.Length)
keyword = "where";
if ((q.Length < keyword.Length) ||
- (0 != string.Compare (q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
- throw new ArgumentException (SR.InvalidQuery, "where");
+ (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
+ throw new ArgumentException(SR.InvalidQuery, "where");
- q = q.Remove (0, keyword.Length);
+ q = q.Remove(0, keyword.Length);
// Must be some white space next
- if ((0 == q.Length) || !char.IsWhiteSpace (q[0]))
+ if ((0 == q.Length) || !char.IsWhiteSpace(q[0]))
throw new ArgumentException(SR.InvalidQuery); // Invalid query
q = q.TrimStart(null); // Remove the leading whitespace
/// <returns>
/// The copied object.
/// </returns>
- public override object Clone ()
+ public override object Clone()
{
string[] strArray = null;
if (0 < count)
{
- strArray = new string [count];
- selectedProperties.CopyTo (strArray, 0);
+ strArray = new string[count];
+ selectedProperties.CopyTo(strArray, 0);
}
}
/// <para>Initializes a new instance of the <see cref='System.Management.RelatedObjectQuery'/> class. This is the
/// default constructor.</para>
/// </summary>
- public RelatedObjectQuery() :this(null) {}
+ public RelatedObjectQuery() : this(null) { }
//parameterized constructor
//ISSUE : We have 2 possible constructors that take a single string :
// Do some basic sanity checking on whether it's a class/instance name
//
- ManagementPath p = new ManagementPath (queryOrSourceObject);
+ ManagementPath p = new ManagementPath(queryOrSourceObject);
- if ((p.IsClass || p.IsInstance) && (p.NamespacePath.Length==0))
+ if ((p.IsClass || p.IsInstance) && (p.NamespacePath.Length == 0))
{
SourceObject = queryOrSourceObject;
isSchemaQuery = false;
}
else
- throw new ArgumentException (SR.InvalidQuery, nameof(queryOrSourceObject));
+ throw new ArgumentException(SR.InvalidQuery, nameof(queryOrSourceObject));
}
}
}
/// <param name='sourceObject'>The path of the source object for this query.</param>
/// <param name='relatedClass'>The related objects class.</param>
public RelatedObjectQuery(string sourceObject, string relatedClass) : this(sourceObject, relatedClass,
- null, null, null, null, null, false) {}
+ null, null, null, null, null, false)
+ { }
//Do we need additional variants of constructors here ??
/// <summary>
//If the source object is not set we can't build a query
//Shouldn't throw here because the user may be in the process of filling in the properties...
if (sourceObject == null)
- SetQueryString (string.Empty);
+ SetQueryString(string.Empty);
- if ((sourceObject == null) || (sourceObject.Length==0))
+ if ((sourceObject == null) || (sourceObject.Length == 0))
return;
//"associators" clause
string s = TokenAssociators + " " + TokenOf + " {" + sourceObject + "}";
//If any of the other parameters are set we need a "where" clause
- if (!(RelatedClass.Length==0) ||
- !(RelationshipClass.Length==0) ||
- !(RelatedQualifier.Length==0) ||
- !(RelationshipQualifier.Length==0) ||
- !(RelatedRole.Length==0) ||
- !(ThisRole.Length==0) ||
+ if (!(RelatedClass.Length == 0) ||
+ !(RelationshipClass.Length == 0) ||
+ !(RelatedQualifier.Length == 0) ||
+ !(RelationshipQualifier.Length == 0) ||
+ !(RelatedRole.Length == 0) ||
+ !(ThisRole.Length == 0) ||
classDefinitionsOnly ||
isSchemaQuery)
{
s = s + " " + TokenWhere;
//"ResultClass"
- if (!(RelatedClass.Length==0))
+ if (!(RelatedClass.Length == 0))
s = s + " " + TokenResultClass + " = " + relatedClass;
//"AssocClass"
- if (!(RelationshipClass.Length==0))
+ if (!(RelationshipClass.Length == 0))
s = s + " " + TokenAssocClass + " = " + relationshipClass;
//"ResultRole"
- if (!(RelatedRole.Length==0))
+ if (!(RelatedRole.Length == 0))
s = s + " " + TokenResultRole + " = " + relatedRole;
//"Role"
- if (!(ThisRole.Length==0))
+ if (!(ThisRole.Length == 0))
s = s + " " + TokenRole + " = " + thisRole;
//"RequiredQualifier"
- if (!(RelatedQualifier.Length==0))
+ if (!(RelatedQualifier.Length == 0))
s = s + " " + TokenRequiredQualifier + " = " + relatedQualifier;
//"RequiredAssocQualifier"
- if (!(RelationshipQualifier.Length==0))
+ if (!(RelationshipQualifier.Length == 0))
s = s + " " + TokenRequiredAssocQualifier + " = " + relationshipQualifier;
//"SchemaOnly" and "ClassDefsOnly"
//Set the queryString member to the built query (NB: note we set
//by accessing the internal helper function rather than the property,
//since we do not want to force a parse of a query we just built).
- SetQueryString (s);
+ SetQueryString(s);
}//BuildQuery()
string tempThisRole = null;
string tempRelatedQualifier = null;
string tempRelationshipQualifier = null;
- bool tempClassDefsOnly = false;
- bool tempIsSchemaQuery = false;
+ bool tempClassDefsOnly = false;
+ bool tempIsSchemaQuery = false;
//Trim whitespaces
string q = query.Trim();
q = q.Remove(0, TokenAssociators.Length);
// Must be some white space next
- if ((0 == q.Length) || !char.IsWhiteSpace (q[0]))
+ if ((0 == q.Length) || !char.IsWhiteSpace(q[0]))
throw new ArgumentException(SR.InvalidQuery); // Invalid query
q = q.TrimStart(null); // Remove the leading whitespace
throw new ArgumentException(SR.InvalidQuery, "of"); // Invalid query
// Strip off the clause and leading WS
- q = q.Remove(0, TokenOf.Length).TrimStart (null);
+ q = q.Remove(0, TokenOf.Length).TrimStart(null);
// Next character should be "{"
if (0 != q.IndexOf('{'))
throw new ArgumentException(SR.InvalidQuery); // Invalid query
tempSourceObject = q.Substring(0, i).TrimEnd(null);
- q = q.Remove(0, i+1).TrimStart(null);
+ q = q.Remove(0, i + 1).TrimStart(null);
// At this point we may or may not have a "where" clause
if (0 < q.Length)
{
// Next should be the "where" clause
- if (0 != string.Compare (q, 0, TokenWhere, 0, TokenWhere.Length, StringComparison.OrdinalIgnoreCase))
+ if (0 != string.Compare(q, 0, TokenWhere, 0, TokenWhere.Length, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(SR.InvalidQuery, "where"); // Invalid query
- q = q.Remove (0, TokenWhere.Length);
+ q = q.Remove(0, TokenWhere.Length);
// Must be some white space next
- if ((0 == q.Length) || !char.IsWhiteSpace (q[0]))
+ if ((0 == q.Length) || !char.IsWhiteSpace(q[0]))
throw new ArgumentException(SR.InvalidQuery); // Invalid query
q = q.TrimStart(null); // Remove the leading whitespace
// Keep looking for tokens until we are done
while (true)
{
- if ((q.Length >= TokenResultClass.Length) && (0 == string.Compare (q, 0, TokenResultClass, 0, TokenResultClass.Length, StringComparison.OrdinalIgnoreCase)))
- ParseToken (ref q, TokenResultClass, "=", ref bResultClassFound, ref tempRelatedClass);
- else if ((q.Length >= TokenAssocClass.Length) && (0 == string.Compare (q, 0, TokenAssocClass, 0, TokenAssocClass.Length, StringComparison.OrdinalIgnoreCase)))
- ParseToken (ref q, TokenAssocClass, "=", ref bAssocClassFound, ref tempRelationshipClass);
- else if ((q.Length >= TokenResultRole.Length) && (0 == string.Compare (q, 0, TokenResultRole, 0, TokenResultRole.Length, StringComparison.OrdinalIgnoreCase)))
- ParseToken (ref q, TokenResultRole, "=", ref bResultRoleFound, ref tempRelatedRole);
- else if ((q.Length >= TokenRole.Length) && (0 == string.Compare (q, 0, TokenRole, 0, TokenRole.Length, StringComparison.OrdinalIgnoreCase)))
- ParseToken (ref q, TokenRole, "=", ref bRoleFound, ref tempThisRole);
- else if ((q.Length >= TokenRequiredQualifier.Length) && (0 == string.Compare (q, 0, TokenRequiredQualifier, 0, TokenRequiredQualifier.Length, StringComparison.OrdinalIgnoreCase)))
- ParseToken (ref q, TokenRequiredQualifier, "=", ref bRequiredQualifierFound, ref tempRelatedQualifier);
- else if ((q.Length >= TokenRequiredAssocQualifier.Length) && (0 == string.Compare (q, 0, TokenRequiredAssocQualifier, 0, TokenRequiredAssocQualifier.Length, StringComparison.OrdinalIgnoreCase)))
- ParseToken (ref q, TokenRequiredAssocQualifier, "=", ref bRequiredAssocQualifierFound, ref tempRelationshipQualifier);
- else if ((q.Length >= TokenSchemaOnly.Length) && (0 == string.Compare (q, 0, TokenSchemaOnly, 0, TokenSchemaOnly.Length, StringComparison.OrdinalIgnoreCase)))
+ if ((q.Length >= TokenResultClass.Length) && (0 == string.Compare(q, 0, TokenResultClass, 0, TokenResultClass.Length, StringComparison.OrdinalIgnoreCase)))
+ ParseToken(ref q, TokenResultClass, "=", ref bResultClassFound, ref tempRelatedClass);
+ else if ((q.Length >= TokenAssocClass.Length) && (0 == string.Compare(q, 0, TokenAssocClass, 0, TokenAssocClass.Length, StringComparison.OrdinalIgnoreCase)))
+ ParseToken(ref q, TokenAssocClass, "=", ref bAssocClassFound, ref tempRelationshipClass);
+ else if ((q.Length >= TokenResultRole.Length) && (0 == string.Compare(q, 0, TokenResultRole, 0, TokenResultRole.Length, StringComparison.OrdinalIgnoreCase)))
+ ParseToken(ref q, TokenResultRole, "=", ref bResultRoleFound, ref tempRelatedRole);
+ else if ((q.Length >= TokenRole.Length) && (0 == string.Compare(q, 0, TokenRole, 0, TokenRole.Length, StringComparison.OrdinalIgnoreCase)))
+ ParseToken(ref q, TokenRole, "=", ref bRoleFound, ref tempThisRole);
+ else if ((q.Length >= TokenRequiredQualifier.Length) && (0 == string.Compare(q, 0, TokenRequiredQualifier, 0, TokenRequiredQualifier.Length, StringComparison.OrdinalIgnoreCase)))
+ ParseToken(ref q, TokenRequiredQualifier, "=", ref bRequiredQualifierFound, ref tempRelatedQualifier);
+ else if ((q.Length >= TokenRequiredAssocQualifier.Length) && (0 == string.Compare(q, 0, TokenRequiredAssocQualifier, 0, TokenRequiredAssocQualifier.Length, StringComparison.OrdinalIgnoreCase)))
+ ParseToken(ref q, TokenRequiredAssocQualifier, "=", ref bRequiredAssocQualifierFound, ref tempRelationshipQualifier);
+ else if ((q.Length >= TokenSchemaOnly.Length) && (0 == string.Compare(q, 0, TokenSchemaOnly, 0, TokenSchemaOnly.Length, StringComparison.OrdinalIgnoreCase)))
{
- ParseToken (ref q, TokenSchemaOnly, ref bSchemaOnlyFound);
+ ParseToken(ref q, TokenSchemaOnly, ref bSchemaOnlyFound);
tempIsSchemaQuery = true;
}
- else if ((q.Length >= TokenClassDefsOnly.Length) && (0 == string.Compare (q, 0, TokenClassDefsOnly, 0, TokenClassDefsOnly.Length, StringComparison.OrdinalIgnoreCase)))
+ else if ((q.Length >= TokenClassDefsOnly.Length) && (0 == string.Compare(q, 0, TokenClassDefsOnly, 0, TokenClassDefsOnly.Length, StringComparison.OrdinalIgnoreCase)))
{
- ParseToken (ref q, TokenClassDefsOnly, ref bClassDefsOnlyFound);
+ ParseToken(ref q, TokenClassDefsOnly, ref bClassDefsOnlyFound);
tempClassDefsOnly = true;
}
else if (0 == q.Length)
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.RelationshipQuery'/> class. This is the default constructor.</para>
/// </summary>
- public RelationshipQuery() :this(null) {}
+ public RelationshipQuery() : this(null) { }
//parameterized constructor
//ISSUE : We have 2 possible constructors that take a single string :
// Do some basic sanity checking on whether it's a class/instance name
//
- ManagementPath p = new ManagementPath (queryOrSourceObject);
+ ManagementPath p = new ManagementPath(queryOrSourceObject);
- if ((p.IsClass || p.IsInstance) && (p.NamespacePath.Length==0))
+ if ((p.IsClass || p.IsInstance) && (p.NamespacePath.Length == 0))
{
SourceObject = queryOrSourceObject;
isSchemaQuery = false;
}
else
- throw new ArgumentException (SR.InvalidQuery, nameof(queryOrSourceObject));
+ throw new ArgumentException(SR.InvalidQuery, nameof(queryOrSourceObject));
}
}
/// <param name='sourceObject'> The path of the source object for this query.</param>
/// <param name='relationshipClass'> The type of relationship for which to query.</param>
public RelationshipQuery(string sourceObject, string relationshipClass) : this(sourceObject, relationshipClass,
- null, null, false) {}
+ null, null, false)
+ { }
+
//Do we need additional variants of constructors here ??
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.RelationshipQuery'/> class for the given set of parameters.
if (sourceObject == null)
SetQueryString(string.Empty);
- if ((sourceObject == null) || (sourceObject.Length==0))
+ if ((sourceObject == null) || (sourceObject.Length == 0))
return;
//"references" clause
string s = TokenReferences + " " + TokenOf + " {" + sourceObject + "}";
//If any of the other parameters are set we need a "where" clause
- if (!(RelationshipClass.Length==0) ||
- !(RelationshipQualifier.Length==0) ||
- !(ThisRole.Length==0) ||
+ if (!(RelationshipClass.Length == 0) ||
+ !(RelationshipQualifier.Length == 0) ||
+ !(ThisRole.Length == 0) ||
classDefinitionsOnly ||
isSchemaQuery)
{
s = s + " " + TokenWhere;
//"ResultClass"
- if (!(RelationshipClass.Length==0))
+ if (!(RelationshipClass.Length == 0))
s = s + " " + TokenResultClass + " = " + relationshipClass;
//"Role"
- if (!(ThisRole.Length==0))
+ if (!(ThisRole.Length == 0))
s = s + " " + TokenRole + " = " + thisRole;
//"RequiredQualifier"
- if (!(RelationshipQualifier.Length==0))
+ if (!(RelationshipQualifier.Length == 0))
s = s + " " + TokenRequiredQualifier + " = " + relationshipQualifier;
//"SchemaOnly" and "ClassDefsOnly"
//Set the queryString member to the built query (NB: note we set
//by accessing the internal helper function rather than the property,
//since we do not want to force a parse of a query we just built).
- SetQueryString (s);
+ SetQueryString(s);
} //BuildQuery()
string tempRelationshipClass = null;
string tempThisRole = null;
string tempRelationshipQualifier = null;
- bool tempClassDefsOnly = false;
- bool tempSchemaOnly = false;
+ bool tempClassDefsOnly = false;
+ bool tempSchemaOnly = false;
//Trim whitespaces
string q = query.Trim();
q = q.Remove(0, TokenReferences.Length);
// Must be some white space next
- if ((0 == q.Length) || !char.IsWhiteSpace (q[0]))
+ if ((0 == q.Length) || !char.IsWhiteSpace(q[0]))
throw new ArgumentException(SR.InvalidQuery); // Invalid query
q = q.TrimStart(null); // Remove the leading whitespace
throw new ArgumentException(SR.InvalidQuery, "of"); // Invalid query
// Strip off the clause and leading WS
- q = q.Remove(0, TokenOf.Length).TrimStart (null);
+ q = q.Remove(0, TokenOf.Length).TrimStart(null);
// Next character should be "{"
if (0 != q.IndexOf('{'))
throw new ArgumentException(SR.InvalidQuery); // Invalid query
tempSourceObject = q.Substring(0, i).TrimEnd(null);
- q = q.Remove(0, i+1).TrimStart(null);
+ q = q.Remove(0, i + 1).TrimStart(null);
// At this point we may or may not have a "where" clause
if (0 < q.Length)
{
// Next should be the "where" clause
- if (0 != string.Compare (q, 0, TokenWhere, 0, TokenWhere.Length, StringComparison.OrdinalIgnoreCase))
+ if (0 != string.Compare(q, 0, TokenWhere, 0, TokenWhere.Length, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(SR.InvalidQuery, "where"); // Invalid query
- q = q.Remove (0, TokenWhere.Length);
+ q = q.Remove(0, TokenWhere.Length);
// Must be some white space next
- if ((0 == q.Length) || !char.IsWhiteSpace (q[0]))
+ if ((0 == q.Length) || !char.IsWhiteSpace(q[0]))
throw new ArgumentException(SR.InvalidQuery); // Invalid query
q = q.TrimStart(null); // Remove the leading whitespace
// Keep looking for tokens until we are done
while (true)
{
- if ((q.Length >= TokenResultClass.Length) && (0 == string.Compare (q, 0, TokenResultClass, 0, TokenResultClass.Length, StringComparison.OrdinalIgnoreCase)))
- ParseToken (ref q, TokenResultClass, "=", ref bResultClassFound, ref tempRelationshipClass);
- else if ((q.Length >= TokenRole.Length) && (0 == string.Compare (q, 0, TokenRole, 0, TokenRole.Length, StringComparison.OrdinalIgnoreCase)))
- ParseToken (ref q, TokenRole, "=", ref bRoleFound, ref tempThisRole);
- else if ((q.Length >= TokenRequiredQualifier.Length) && (0 == string.Compare (q, 0, TokenRequiredQualifier, 0, TokenRequiredQualifier.Length, StringComparison.OrdinalIgnoreCase)))
- ParseToken (ref q, TokenRequiredQualifier, "=", ref bRequiredQualifierFound, ref tempRelationshipQualifier);
- else if ((q.Length >= TokenClassDefsOnly.Length) && (0 == string.Compare (q, 0, TokenClassDefsOnly, 0, TokenClassDefsOnly.Length, StringComparison.OrdinalIgnoreCase)))
+ if ((q.Length >= TokenResultClass.Length) && (0 == string.Compare(q, 0, TokenResultClass, 0, TokenResultClass.Length, StringComparison.OrdinalIgnoreCase)))
+ ParseToken(ref q, TokenResultClass, "=", ref bResultClassFound, ref tempRelationshipClass);
+ else if ((q.Length >= TokenRole.Length) && (0 == string.Compare(q, 0, TokenRole, 0, TokenRole.Length, StringComparison.OrdinalIgnoreCase)))
+ ParseToken(ref q, TokenRole, "=", ref bRoleFound, ref tempThisRole);
+ else if ((q.Length >= TokenRequiredQualifier.Length) && (0 == string.Compare(q, 0, TokenRequiredQualifier, 0, TokenRequiredQualifier.Length, StringComparison.OrdinalIgnoreCase)))
+ ParseToken(ref q, TokenRequiredQualifier, "=", ref bRequiredQualifierFound, ref tempRelationshipQualifier);
+ else if ((q.Length >= TokenClassDefsOnly.Length) && (0 == string.Compare(q, 0, TokenClassDefsOnly, 0, TokenClassDefsOnly.Length, StringComparison.OrdinalIgnoreCase)))
{
- ParseToken (ref q, TokenClassDefsOnly, ref bClassDefsOnlyFound);
+ ParseToken(ref q, TokenClassDefsOnly, ref bClassDefsOnlyFound);
tempClassDefsOnly = true;
}
- else if ((q.Length >= TokenSchemaOnly.Length) && (0 == string.Compare (q, 0, TokenSchemaOnly, 0, TokenSchemaOnly.Length, StringComparison.OrdinalIgnoreCase)))
+ else if ((q.Length >= TokenSchemaOnly.Length) && (0 == string.Compare(q, 0, TokenSchemaOnly, 0, TokenSchemaOnly.Length, StringComparison.OrdinalIgnoreCase)))
{
- ParseToken (ref q, TokenSchemaOnly, ref bSchemaOnlyFound);
+ ParseToken(ref q, TokenSchemaOnly, ref bSchemaOnlyFound);
tempSchemaOnly = true;
}
else if (0 == q.Length)
/// class. This is the default
/// constructor.</para>
/// </summary>
- public WqlEventQuery() : this(null, TimeSpan.Zero, null, TimeSpan.Zero, null, null) {}
+ public WqlEventQuery() : this(null, TimeSpan.Zero, null, TimeSpan.Zero, null, null) { }
//parameterized constructors
//ISSUE : We have 2 possible constructors that take a single string :
{
// Do some basic sanity checking on whether it's a class name
//
- ManagementPath p = new ManagementPath (queryOrEventClassName);
+ ManagementPath p = new ManagementPath(queryOrEventClassName);
- if (p.IsClass && (p.NamespacePath.Length==0))
+ if (p.IsClass && (p.NamespacePath.Length == 0))
{
EventClassName = queryOrEventClassName;
}
else
- throw new ArgumentException (SR.InvalidQuery, nameof(queryOrEventClassName));
+ throw new ArgumentException(SR.InvalidQuery, nameof(queryOrEventClassName));
}
}
}
/// Dim q As New WqlEventQuery("MyEvent", "FirstProp < 20 and SecondProp = 'red'")
/// </code>
/// </example>
- public WqlEventQuery(string eventClassName, string condition) : this(eventClassName, TimeSpan.Zero, condition, TimeSpan.Zero, null, null) {}
+ public WqlEventQuery(string eventClassName, string condition) : this(eventClassName, TimeSpan.Zero, condition, TimeSpan.Zero, null, null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.WqlEventQuery'/>
/// Dim q As New WqlEventQuery("__InstanceCreationEvent", t)
/// </code>
/// </example>
- public WqlEventQuery(string eventClassName, TimeSpan withinInterval):
- this(eventClassName, withinInterval, null, TimeSpan.Zero, null, null) {}
+ public WqlEventQuery(string eventClassName, TimeSpan withinInterval) :
+ this(eventClassName, withinInterval, null, TimeSpan.Zero, null, null)
+ { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.WqlEventQuery'/>
/// class with the specified
/// </code>
/// </example>
public WqlEventQuery(string eventClassName, TimeSpan withinInterval, string condition) :
- this(eventClassName, withinInterval, condition, TimeSpan.Zero, null, null) {}
+ this(eventClassName, withinInterval, condition, TimeSpan.Zero, null, null)
+ { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.WqlEventQuery'/>
/// </code>
/// </example>
public WqlEventQuery(string eventClassName, string condition, TimeSpan groupWithinInterval) :
- this(eventClassName, TimeSpan.Zero, condition, groupWithinInterval, null, null) {}
+ this(eventClassName, TimeSpan.Zero, condition, groupWithinInterval, null, null)
+ { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.WqlEventQuery'/>
/// </code>
/// </example>
public WqlEventQuery(string eventClassName, string condition, TimeSpan groupWithinInterval, string[] groupByPropertyList) :
- this(eventClassName, TimeSpan.Zero, condition, groupWithinInterval, groupByPropertyList, null) {}
+ this(eventClassName, TimeSpan.Zero, condition, groupWithinInterval, groupByPropertyList, null)
+ { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.WqlEventQuery'/>
this.withinInterval = withinInterval;
this.condition = condition;
this.groupWithinInterval = groupWithinInterval;
- this.groupByPropertyList = new StringCollection ();
+ this.groupByPropertyList = new StringCollection();
if (null != groupByPropertyList)
- this.groupByPropertyList.AddRange (groupByPropertyList);
+ this.groupByPropertyList.AddRange(groupByPropertyList);
this.havingCondition = havingCondition;
BuildQuery();
public override string QueryLanguage
{
get
- {return base.QueryLanguage; }
+ { return base.QueryLanguage; }
}
/// <summary>
{
// We need to force a rebuild as we may not have detected
// a change to selected properties
- BuildQuery ();
+ BuildQuery();
return base.QueryString;
}
set
public StringCollection GroupByPropertyList
{
get { return groupByPropertyList; }
- set {
+ set
+ {
// A tad painful since StringCollection doesn't support ICloneable
StringCollection src = (StringCollection)value;
- StringCollection dst = new StringCollection ();
+ StringCollection dst = new StringCollection();
foreach (string s in src)
- dst.Add (s);
+ dst.Add(s);
groupByPropertyList = dst;
BuildQuery();
{
//If the event class name is not set we can't build a query
//This shouldn't throw because the user may be in the process of setting properties...
- if ((eventClassName == null) || (eventClassName.Length==0))
+ if ((eventClassName == null) || (eventClassName.Length == 0))
{
- SetQueryString (string.Empty);
+ SetQueryString(string.Empty);
return;
}
s = s + " within " + withinInterval.TotalSeconds.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(double)));
//Where clause
- if (!(Condition.Length==0))
+ if (!(Condition.Length == 0))
s = s + " where " + condition;
//Group within clause
int count = groupByPropertyList.Count;
s = s + " by ";
- for (int i=0; i<count; i++)
+ for (int i = 0; i < count; i++)
s = s + groupByPropertyList[i] + (i == (count - 1) ? "" : ",");
}
//Having clause
- if (!(HavingCondition.Length==0))
+ if (!(HavingCondition.Length == 0))
{
s = s + " having " + havingCondition;
}
//Set the queryString member to the built query (NB: note we set
//by accessing the internal helper function rather than the property,
//since we do not want to force a parse of a query we just built).
- SetQueryString (s);
+ SetQueryString(s);
}//BuildQuery
//Find "select" clause and make sure it's a select *
string keyword = TokenSelect;
- if ((q.Length < keyword.Length) || (0 != string.Compare (q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
+ if ((q.Length < keyword.Length) || (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
throw new ArgumentException(SR.InvalidQuery);
- q = q.Remove(0, keyword.Length).TrimStart(null);
+ q = q.Remove(0, keyword.Length).TrimStart(null);
if (!q.StartsWith("*", StringComparison.Ordinal))
- throw new ArgumentException(SR.InvalidQuery, "*");
+ throw new ArgumentException(SR.InvalidQuery, "*");
q = q.Remove(0, 1).TrimStart(null);
//Find "from" clause
keyword = "from ";
- if ((q.Length < keyword.Length) || (0 != string.Compare (q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
+ if ((q.Length < keyword.Length) || (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
throw new ArgumentException(SR.InvalidQuery, "from");
ParseToken(ref q, keyword, null, ref bFound, ref eventClassName);
//Find "within" clause
keyword = "within ";
- if ((q.Length >= keyword.Length) && (0 == string.Compare (q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
+ if ((q.Length >= keyword.Length) && (0 == string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
{
string intervalString = null; bFound = false;
ParseToken(ref q, keyword, null, ref bFound, ref intervalString);
w = q.Substring(0, i).Trim();
q = q.Remove(0, i);
- string intervalString = null; bFound=false;
+ string intervalString = null; bFound = false;
ParseToken(ref q, keyword, null, ref bFound, ref intervalString);
groupWithinInterval = TimeSpan.FromSeconds(((IConvertible)intervalString).ToDouble(null));
//Find "By" subclause
keyword = "by ";
- if ((q.Length >= keyword.Length) && (0 == string.Compare (q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
+ if ((q.Length >= keyword.Length) && (0 == string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
{
q = q.Remove(0, keyword.Length);
if (null != groupByPropertyList)
- groupByPropertyList.Clear ();
+ groupByPropertyList.Clear();
else
- groupByPropertyList = new StringCollection ();
+ groupByPropertyList = new StringCollection();
//get the property list
while (true)
if ((i = q.IndexOf(',')) > 0)
{
tempProp = q.Substring(0, i);
- q = q.Remove(0, i+1).TrimStart(null);
+ q = q.Remove(0, i + 1).TrimStart(null);
tempProp = tempProp.Trim();
- if (tempProp.Length>0)
+ if (tempProp.Length > 0)
groupByPropertyList.Add(tempProp);
}
else
//Find "Having" subclause
keyword = "having "; bFound = false;
- if ((q.Length >= keyword.Length) && (0 == string.Compare (q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
+ if ((q.Length >= keyword.Length) && (0 == string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
{ //the rest until the end is assumed to be the having condition
q = q.Remove(0, keyword.Length);
//Find "where" clause
keyword = "where ";
- if ((w.Length >= keyword.Length) && (0 == string.Compare (w, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase))) //where clause exists
+ if ((w.Length >= keyword.Length) && (0 == string.Compare(w, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase))) //where clause exists
{
condition = w.Substring(keyword.Length);
}
if (0 < count)
{
- strArray = new string [count];
- groupByPropertyList.CopyTo (strArray, 0);
+ strArray = new string[count];
+ groupByPropertyList.CopyTo(strArray, 0);
}
}
if (value is EventQuery && destinationType == typeof(InstanceDescriptor))
{
EventQuery obj = ((EventQuery)(value));
- ConstructorInfo ctor = typeof(EventQuery).GetConstructor(new Type[] {typeof(string)});
+ ConstructorInfo ctor = typeof(EventQuery).GetConstructor(new Type[] { typeof(string) });
if (ctor != null)
{
- return new InstanceDescriptor(ctor, new object[] {obj.QueryString});
+ return new InstanceDescriptor(ctor, new object[] { obj.QueryString });
}
}
if (value is ObjectQuery && destinationType == typeof(InstanceDescriptor))
{
ObjectQuery obj = ((ObjectQuery)(value));
- ConstructorInfo ctor = typeof(ObjectQuery).GetConstructor(new Type[] {typeof(string)});
+ ConstructorInfo ctor = typeof(ObjectQuery).GetConstructor(new Type[] { typeof(string) });
if (ctor != null)
{
- return new InstanceDescriptor(ctor, new object[] {obj.QueryString});
+ return new InstanceDescriptor(ctor, new object[] { obj.QueryString });
}
}
return base.ConvertTo(context, culture, value, destinationType);
internal static class CompatSwitches
{
internal const string DotNetVersion = "v4.0.30319";
- private const string RegKeyLocation =@"SOFTWARE\Microsoft\.NETFramework\" + DotNetVersion;
+ private const string RegKeyLocation = @"SOFTWARE\Microsoft\.NETFramework\" + DotNetVersion;
private static readonly object s_syncLock = new object();
private static int s_allowManagementObjectQI;
private static bool GetSwitchValueFromRegistry()
{
- RegistryKey s_switchesRegKey = null;
- try
- {
- s_switchesRegKey = Registry.LocalMachine.OpenSubKey(RegKeyLocation);
-
- if (s_switchesRegKey == null)
- {
- return false;
- }
-
- return ((int)s_switchesRegKey.GetValue(c_WMIDisableCOMSecurity, -1 /* default */) == 1);
- }
-
- // ignore exceptions so that we don't crash the process if we can't read the switch value
- catch (Exception e)
- {
- if (e is StackOverflowException ||
- e is OutOfMemoryException ||
- e is System.Threading.ThreadAbortException ||
- e is AccessViolationException)
- throw;
- }
- finally
- {
- // dispose of the key
- if (s_switchesRegKey != null)
- {
- s_switchesRegKey.Dispose();
- }
- }
-
- // if for any reason we cannot retrieve the value of the switch from the Registry,
- // fallback to 'false' which is the secure behavior
- return false;
+ RegistryKey s_switchesRegKey = null;
+ try
+ {
+ s_switchesRegKey = Registry.LocalMachine.OpenSubKey(RegKeyLocation);
+
+ if (s_switchesRegKey == null)
+ {
+ return false;
+ }
+
+ return ((int)s_switchesRegKey.GetValue(c_WMIDisableCOMSecurity, -1 /* default */) == 1);
+ }
+
+ // ignore exceptions so that we don't crash the process if we can't read the switch value
+ catch (Exception e)
+ {
+ if (e is StackOverflowException ||
+ e is OutOfMemoryException ||
+ e is System.Threading.ThreadAbortException ||
+ e is AccessViolationException)
+ throw;
+ }
+ finally
+ {
+ // dispose of the key
+ if (s_switchesRegKey != null)
+ {
+ s_switchesRegKey.Dispose();
+ }
+ }
+
+ // if for any reason we cannot retrieve the value of the switch from the Registry,
+ // fallback to 'false' which is the secure behavior
+ return false;
}
}
internal delegate int ResetSecurity(IntPtr hToken);
internal delegate int SetSecurity([In][Out] ref bool pNeedtoReset, [In][Out] ref IntPtr pHandle);
internal delegate int BlessIWbemServices([MarshalAs(UnmanagedType.Interface)] IWbemServices pIUnknown,
- [In][MarshalAs(UnmanagedType.BStr)] string strUser,
+ [In][MarshalAs(UnmanagedType.BStr)] string strUser,
IntPtr password,
- [In][MarshalAs(UnmanagedType.BStr)] string strAuthority,
+ [In][MarshalAs(UnmanagedType.BStr)] string strAuthority,
int impersonationLevel,
int authenticationLevel);
internal delegate int BlessIWbemServicesObject([MarshalAs(UnmanagedType.IUnknown)] object pIUnknown,
- [In][MarshalAs(UnmanagedType.BStr)] string strUser,
+ [In][MarshalAs(UnmanagedType.BStr)] string strUser,
IntPtr password,
- [In][MarshalAs(UnmanagedType.BStr)] string strAuthority,
+ [In][MarshalAs(UnmanagedType.BStr)] string strAuthority,
int impersonationLevel,
int authenticationLevel);
- internal delegate int GetPropertyHandle(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszPropertyName, [Out] out int pType, [Out] out int plHandle);
- internal delegate int WritePropertyValue(int vFunc, IntPtr pWbemClassObject, [In] int lHandle, [In] int lNumBytes, [In][MarshalAs(UnmanagedType.LPWStr)] string str);
- internal delegate int GetQualifierSet(int vFunc, IntPtr pWbemClassObject, [Out] out IntPtr ppQualSet);
- internal delegate int Get(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][Out] ref object pVal, [In][Out] ref int pType, [In][Out] ref int plFlavor);
- internal delegate int Put(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In] ref object pVal, [In] int Type);
- internal delegate int Delete(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
- internal delegate int GetNames(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszQualifierName, [In] int lFlags, [In] ref object pQualifierVal, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)] out string[] pNames);
- internal delegate int BeginEnumeration(int vFunc, IntPtr pWbemClassObject, [In] int lEnumFlags);
- internal delegate int Next(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string strName, [In][Out] ref object pVal, [In][Out] ref int pType, [In][Out] ref int plFlavor);
- internal delegate int EndEnumeration(int vFunc, IntPtr pWbemClassObject);
- internal delegate int GetPropertyQualifierSet(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszProperty, [Out] out IntPtr ppQualSet);
- internal delegate int Clone(int vFunc, IntPtr pWbemClassObject, [Out] out IntPtr ppCopy);
- internal delegate int GetObjectText(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrObjectText);
- internal delegate int SpawnDerivedClass(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [Out] out IntPtr ppNewClass);
- internal delegate int SpawnInstance(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [Out] out IntPtr ppNewInstance);
- internal delegate int CompareTo(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [In] IntPtr pCompareTo);
- internal delegate int GetPropertyOrigin(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName);
- internal delegate int InheritsFrom(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string strAncestor);
- internal delegate int GetMethod(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [Out]out IntPtr ppInSignature, [Out] out IntPtr ppOutSignature);
- internal delegate int PutMethod(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In] IntPtr pInSignature, [In] IntPtr pOutSignature);
- internal delegate int DeleteMethod(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
- internal delegate int BeginMethodEnumeration(int vFunc, IntPtr pWbemClassObject, [In] int lEnumFlags);
- internal delegate int NextMethod(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrName, [Out] out IntPtr ppInSignature, [Out] out IntPtr ppOutSignature);
- internal delegate int EndMethodEnumeration(int vFunc, IntPtr pWbemClassObject);
- internal delegate int GetMethodQualifierSet(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszMethod, [Out] out IntPtr ppQualSet);
- internal delegate int GetMethodOrigin(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszMethodName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName);
- internal delegate int QualifierSet_Get(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][Out] ref object pVal, [In][Out] ref int plFlavor);
- internal delegate int QualifierSet_Put(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] ref object pVal, [In] int lFlavor);
- internal delegate int QualifierSet_Delete(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
- internal delegate int QualifierSet_GetNames(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)] out string[] pNames);
- internal delegate int QualifierSet_BeginEnumeration(int vFunc, IntPtr pWbemClassObject, [In] int lFlags);
- internal delegate int QualifierSet_Next(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrName, [Out] out object pVal, [Out] out int plFlavor);
- internal delegate int QualifierSet_EndEnumeration(int vFunc, IntPtr pWbemClassObject);
- internal delegate int GetCurrentApartmentType(int vFunc, IntPtr pComThreadingInfo, [Out] out APTTYPE aptType);
- internal delegate void VerifyClientKey();
- internal delegate int GetDemultiplexedStub([In, MarshalAs(UnmanagedType.IUnknown)]object pIUnknown, [In]bool isLocal, [Out, MarshalAs(UnmanagedType.IUnknown)]out object ppIUnknown);
- internal delegate int CreateInstanceEnumWmi([In][MarshalAs(UnmanagedType.BStr)] string strFilter,
- [In] int lFlags,
- [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
- [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum,
- [In] int impLevel,
- [In] int authnLevel,
- [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace,
- [In][MarshalAs(UnmanagedType.BStr)] string strUser,
- [In]IntPtr strPassword,
- [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
- );
- internal delegate int CreateClassEnumWmi([In][MarshalAs(UnmanagedType.BStr)] string strSuperclass,
- [In] int lFlags,
- [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
- [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum,
- [In] int impLevel,
- [In] int authnLevel,
- [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace,
- [In][MarshalAs(UnmanagedType.BStr)] string strUser,
- [In]IntPtr strPassword,
- [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
- );
- internal delegate int ExecQueryWmi([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage,
- [In][MarshalAs(UnmanagedType.BStr)] string strQuery,
- [In] int lFlags,
- [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
- [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum,
- [In] int impLevel,
- [In] int authnLevel,
- [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace,
- [In][MarshalAs(UnmanagedType.BStr)] string strUser,
- [In]IntPtr strPassword,
- [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
- );
- internal delegate int ExecNotificationQueryWmi( [In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage,
- [In][MarshalAs(UnmanagedType.BStr)] string strQuery,
+ internal delegate int GetPropertyHandle(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszPropertyName, [Out] out int pType, [Out] out int plHandle);
+ internal delegate int WritePropertyValue(int vFunc, IntPtr pWbemClassObject, [In] int lHandle, [In] int lNumBytes, [In][MarshalAs(UnmanagedType.LPWStr)] string str);
+ internal delegate int GetQualifierSet(int vFunc, IntPtr pWbemClassObject, [Out] out IntPtr ppQualSet);
+ internal delegate int Get(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][Out] ref object pVal, [In][Out] ref int pType, [In][Out] ref int plFlavor);
+ internal delegate int Put(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In] ref object pVal, [In] int Type);
+ internal delegate int Delete(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
+ internal delegate int GetNames(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszQualifierName, [In] int lFlags, [In] ref object pQualifierVal, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] out string[] pNames);
+ internal delegate int BeginEnumeration(int vFunc, IntPtr pWbemClassObject, [In] int lEnumFlags);
+ internal delegate int Next(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string strName, [In][Out] ref object pVal, [In][Out] ref int pType, [In][Out] ref int plFlavor);
+ internal delegate int EndEnumeration(int vFunc, IntPtr pWbemClassObject);
+ internal delegate int GetPropertyQualifierSet(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszProperty, [Out] out IntPtr ppQualSet);
+ internal delegate int Clone(int vFunc, IntPtr pWbemClassObject, [Out] out IntPtr ppCopy);
+ internal delegate int GetObjectText(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrObjectText);
+ internal delegate int SpawnDerivedClass(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [Out] out IntPtr ppNewClass);
+ internal delegate int SpawnInstance(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [Out] out IntPtr ppNewInstance);
+ internal delegate int CompareTo(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [In] IntPtr pCompareTo);
+ internal delegate int GetPropertyOrigin(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName);
+ internal delegate int InheritsFrom(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string strAncestor);
+ internal delegate int GetMethod(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [Out]out IntPtr ppInSignature, [Out] out IntPtr ppOutSignature);
+ internal delegate int PutMethod(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In] IntPtr pInSignature, [In] IntPtr pOutSignature);
+ internal delegate int DeleteMethod(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
+ internal delegate int BeginMethodEnumeration(int vFunc, IntPtr pWbemClassObject, [In] int lEnumFlags);
+ internal delegate int NextMethod(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrName, [Out] out IntPtr ppInSignature, [Out] out IntPtr ppOutSignature);
+ internal delegate int EndMethodEnumeration(int vFunc, IntPtr pWbemClassObject);
+ internal delegate int GetMethodQualifierSet(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszMethod, [Out] out IntPtr ppQualSet);
+ internal delegate int GetMethodOrigin(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszMethodName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName);
+ internal delegate int QualifierSet_Get(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] int lFlags, [In][Out] ref object pVal, [In][Out] ref int plFlavor);
+ internal delegate int QualifierSet_Put(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] ref object pVal, [In] int lFlavor);
+ internal delegate int QualifierSet_Delete(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName);
+ internal delegate int QualifierSet_GetNames(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] out string[] pNames);
+ internal delegate int QualifierSet_BeginEnumeration(int vFunc, IntPtr pWbemClassObject, [In] int lFlags);
+ internal delegate int QualifierSet_Next(int vFunc, IntPtr pWbemClassObject, [In] int lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrName, [Out] out object pVal, [Out] out int plFlavor);
+ internal delegate int QualifierSet_EndEnumeration(int vFunc, IntPtr pWbemClassObject);
+ internal delegate int GetCurrentApartmentType(int vFunc, IntPtr pComThreadingInfo, [Out] out APTTYPE aptType);
+ internal delegate void VerifyClientKey();
+ internal delegate int GetDemultiplexedStub([In, MarshalAs(UnmanagedType.IUnknown)]object pIUnknown, [In]bool isLocal, [Out, MarshalAs(UnmanagedType.IUnknown)]out object ppIUnknown);
+ internal delegate int CreateInstanceEnumWmi([In][MarshalAs(UnmanagedType.BStr)] string strFilter,
+ [In] int lFlags,
+ [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
+ [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum,
+ [In] int impLevel,
+ [In] int authnLevel,
+ [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace,
+ [In][MarshalAs(UnmanagedType.BStr)] string strUser,
+ [In]IntPtr strPassword,
+ [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
+ );
+ internal delegate int CreateClassEnumWmi([In][MarshalAs(UnmanagedType.BStr)] string strSuperclass,
+ [In] int lFlags,
+ [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
+ [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum,
+ [In] int impLevel,
+ [In] int authnLevel,
+ [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace,
+ [In][MarshalAs(UnmanagedType.BStr)] string strUser,
+ [In]IntPtr strPassword,
+ [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
+ );
+ internal delegate int ExecQueryWmi([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage,
+ [In][MarshalAs(UnmanagedType.BStr)] string strQuery,
+ [In] int lFlags,
+ [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
+ [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum,
+ [In] int impLevel,
+ [In] int authnLevel,
+ [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace,
+ [In][MarshalAs(UnmanagedType.BStr)] string strUser,
+ [In]IntPtr strPassword,
+ [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
+ );
+ internal delegate int ExecNotificationQueryWmi([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage,
+ [In][MarshalAs(UnmanagedType.BStr)] string strQuery,
[In] int lFlags,
- [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
- [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum,
+ [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
+ [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum,
[In] int impLevel,
[In] int authnLevel,
[In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace,
- [In][MarshalAs(UnmanagedType.BStr)] string strUser,
- [In]IntPtr strPassword,
- [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
+ [In][MarshalAs(UnmanagedType.BStr)] string strUser,
+ [In]IntPtr strPassword,
+ [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
);
internal delegate int PutInstanceWmi([In] IntPtr pInst,
[In] int lFlags,
- [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
+ [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
[In] IntPtr ppCallResult,
[In] int impLevel,
[In] int authnLevel,
[In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace,
- [In][MarshalAs(UnmanagedType.BStr)] string strUser,
- [In]IntPtr strPassword,
- [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
+ [In][MarshalAs(UnmanagedType.BStr)] string strUser,
+ [In]IntPtr strPassword,
+ [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
);
internal delegate int PutClassWmi([In] IntPtr pObject,
[In] int lFlags,
- [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
+ [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
[In] IntPtr ppCallResult,
[In] int impLevel,
[In] int authnLevel,
[In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace,
- [In][MarshalAs(UnmanagedType.BStr)] string strUser,
- [In]IntPtr strPassword,
- [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
+ [In][MarshalAs(UnmanagedType.BStr)] string strUser,
+ [In]IntPtr strPassword,
+ [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
);
internal delegate int CloneEnumWbemClassObject(
- [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum,
+ [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum,
[In] int impLevel,
[In] int authnLevel,
[In] [MarshalAs(UnmanagedType.Interface)] IEnumWbemClassObject pCurrentEnumWbemClassObject,
- [In][MarshalAs(UnmanagedType.BStr)] string strUser,
- [In]IntPtr strPassword,
- [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
+ [In][MarshalAs(UnmanagedType.BStr)] string strUser,
+ [In]IntPtr strPassword,
+ [In][MarshalAs(UnmanagedType.BStr)] string strAuthority
);
internal delegate int ConnectServerWmi(
- [In][MarshalAs(UnmanagedType.BStr)] string strNetworkResource,
- [In][MarshalAs(UnmanagedType.BStr)] string strUser,
+ [In][MarshalAs(UnmanagedType.BStr)] string strNetworkResource,
+ [In][MarshalAs(UnmanagedType.BStr)] string strUser,
[In] IntPtr strPassword,
- [In][MarshalAs(UnmanagedType.BStr)] string strLocale,
+ [In][MarshalAs(UnmanagedType.BStr)] string strLocale,
[In] int lSecurityFlags,
- [In][MarshalAs(UnmanagedType.BStr)] string strAuthority,
- [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
- [Out][MarshalAs(UnmanagedType.Interface)] out IWbemServices ppNamespace,
+ [In][MarshalAs(UnmanagedType.BStr)] string strAuthority,
+ [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx,
+ [Out][MarshalAs(UnmanagedType.Interface)] out IWbemServices ppNamespace,
int impersonationLevel,
int authenticationLevel);
// 'Apartment Type' returned by IComThreadingInfo::GetCurrentApartmentType()
- internal enum APTTYPE
+ internal enum APTTYPE
{
APTTYPE_CURRENT = -1,
APTTYPE_STA = 0,
APTTYPE_MTA = 1,
- APTTYPE_NA = 2,
+ APTTYPE_NA = 2,
APTTYPE_MAINSTA = 3
}
internal static ResetSecurity ResetSecurity_f;
internal static BlessIWbemServices BlessIWbemServices_f;
internal static BlessIWbemServicesObject BlessIWbemServicesObject_f;
internal static GetPropertyHandle GetPropertyHandle_f27;
- internal static WritePropertyValue WritePropertyValue_f28;
+ internal static WritePropertyValue WritePropertyValue_f28;
internal static GetQualifierSet GetQualifierSet_f;
internal static Get Get_f;
internal static Put Put_f;
internal static GetDemultiplexedStub GetDemultiplexedStub_f;
internal static CreateInstanceEnumWmi CreateInstanceEnumWmi_f;
internal static CreateClassEnumWmi CreateClassEnumWmi_f;
- internal static ExecQueryWmi ExecQueryWmi_f;
+ internal static ExecQueryWmi ExecQueryWmi_f;
internal static ExecNotificationQueryWmi ExecNotificationQueryWmi_f;
internal static PutInstanceWmi PutInstanceWmi_f;
internal static PutClassWmi PutClassWmi_f;
CompatSwitches.DotNetVersion, // The same value is hard coded on Environment.Version and quirks for WMI
"wminet_utils.dll");
- IntPtr hModule = Interop.Kernel32.LoadLibrary(wminet_utilsPath);
+ IntPtr hModule = Interop.Kernel32.LoadLibrary(wminet_utilsPath);
if (hModule == IntPtr.Zero)
{
// This is unlikely, so having the TypeInitializationException wrapping it is fine.
[TypeConverter(typeof(ManagementScopeConverter))]
public class ManagementScope : ICloneable
{
- private ManagementPath validatedPath;
- private IWbemServices wbemServices;
- private ConnectionOptions options;
+ private ManagementPath validatedPath;
+ private IWbemServices wbemServices;
+ private ConnectionOptions options;
internal event IdentifierChangedEventHandler IdentifierChanged;
internal bool IsDefaulted; //used to tell whether the current scope has been created from the default
//scope or not - this information is used to tell whether it can be overridden
}
}
- internal IWbemServices GetIWbemServices ()
+ internal IWbemServices GetIWbemServices()
{
IWbemServices localCopy = wbemServices;
//IWbemServices is always created in MTA context. Only if call is made through non MTA context we need to use IWbemServices in right context.
// fail if we are running under a local user account. The QI has to be done by
// someone who is a member of the 'Everyone' group on the target machine, or DCOM
// won't let the call through.
- SecurityHandler securityHandler = GetSecurityHandler ();
+ SecurityHandler securityHandler = GetSecurityHandler();
securityHandler.SecureIUnknown(unknown);
// Now, we can QI and secure the IWbemServices
}
//Internal constructor
- internal ManagementScope (ManagementPath path, IWbemServices wbemServices,
+ internal ManagementScope(ManagementPath path, IWbemServices wbemServices,
ConnectionOptions options)
{
if (null != path)
this.Path = path;
- if (null != options) {
+ if (null != options)
+ {
this.Options = options;
}
this.wbemServices = wbemServices;
}
- internal ManagementScope (ManagementPath path, ManagementScope scope)
- : this (path, (null != scope) ? scope.options : null) {}
+ internal ManagementScope(ManagementPath path, ManagementScope scope)
+ : this(path, (null != scope) ? scope.options : null) { }
internal static ManagementScope _Clone(ManagementScope scope)
{
/// <code lang='VB'>Dim s As New ManagementScope()
/// </code>
/// </example>
- public ManagementScope () :
- this (new ManagementPath (ManagementPath.DefaultPath.Path))
+ public ManagementScope() :
+ this(new ManagementPath(ManagementPath.DefaultPath.Path))
{
//Flag that this scope uses the default path
IsDefaulted = true;
/// Dim s As New ManagementScope(p)
/// </code>
/// </example>
- public ManagementScope (ManagementPath path) : this(path, (ConnectionOptions)null) {}
+ public ManagementScope(ManagementPath path) : this(path, (ConnectionOptions)null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementScope'/> class representing the specified scope
/// <code lang='VB'>Dim s As New ManagementScope("\\MyServer\root\default")
/// </code>
/// </example>
- public ManagementScope (string path) : this(new ManagementPath(path), (ConnectionOptions)null) {}
+ public ManagementScope(string path) : this(new ManagementPath(path), (ConnectionOptions)null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementScope'/> class representing the specified scope path,
/// with the specified options.</para>
/// Dim s As New ManagementScope("\\MyServer\root\default", opt);
/// </code>
/// </example>
- public ManagementScope (string path, ConnectionOptions options) : this (new ManagementPath(path), options) {}
+ public ManagementScope(string path, ConnectionOptions options) : this(new ManagementPath(path), options) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementScope'/> class representing the specified scope path,
/// Dim s As New ManagementScope(p, opt)
/// </code>
/// </example>
- public ManagementScope (ManagementPath path, ConnectionOptions options)
+ public ManagementScope(ManagementPath path, ConnectionOptions options)
{
if (null != path)
this.prvpath = ManagementPath._Clone(path, new IdentifierChangedEventHandler(HandleIdentifierChange));
HandleIdentifierChange(this, null);
}
else
- throw new ArgumentNullException (nameof(value));
+ throw new ArgumentNullException(nameof(value));
}
}
HandleIdentifierChange(this, null);
}
else
- throw new ArgumentNullException (nameof(value));
+ throw new ArgumentNullException(nameof(value));
}
}
/// Dim o As New ManagementObject(s, "Win32_LogicalDisk=""C:""", null)
/// </code>
/// </example>
- public void Connect ()
+ public void Connect()
{
- Initialize ();
+ Initialize();
}
- internal void Initialize ()
+ internal void Initialize()
{
//If the path is not set yet we can't do it
if (null == prvpath)
//
// Ensure we are able to trap exceptions from worker thread.
//
- ThreadDispatch disp = new ThreadDispatch ( new ThreadDispatch.ThreadWorkerMethodWithParam ( InitializeGuts ) );
+ ThreadDispatch disp = new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethodWithParam(InitializeGuts));
disp.Parameter = this;
- disp.Start ( );
+ disp.Start();
}
else
InitializeGuts(this);
private void InitializeGuts(object o)
{
- ManagementScope threadParam = (ManagementScope) o;
- IWbemLocator loc = (IWbemLocator) new WbemLocator();
+ ManagementScope threadParam = (ManagementScope)o;
+ IWbemLocator loc = (IWbemLocator)new WbemLocator();
IntPtr punk = IntPtr.Zero;
if (null == threadParam.options)
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
- if ( ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor >= 1)) || (Environment.OSVersion.Version.Major >= 6) )
+ if (((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor >= 1)) || (Environment.OSVersion.Version.Major >= 6))
{
threadParam.options.Flags |= (int)tag_WBEM_CONNECT_OPTIONS.WBEM_FLAG_CONNECT_USE_MAX_WAIT;
}
try
{
- status = GetSecuredConnectHandler().ConnectNSecureIWbemServices(nsPath, ref threadParam.wbemServices);
+ status = GetSecuredConnectHandler().ConnectNSecureIWbemServices(nsPath, ref threadParam.wbemServices);
}
catch (COMException e)
{
- ManagementException.ThrowWithExtendedInfo (e);
+ ManagementException.ThrowWithExtendedInfo(e);
}
if ((status & 0xfffff000) == 0x80041000)
}
}
- internal SecurityHandler GetSecurityHandler ()
+ internal SecurityHandler GetSecurityHandler()
{
return new SecurityHandler(this);
}
- internal SecuredConnectHandler GetSecuredConnectHandler ()
+ internal SecuredConnectHandler GetSecuredConnectHandler()
{
return new SecuredConnectHandler(this);
}
- internal SecuredIEnumWbemClassObjectHandler GetSecuredIEnumWbemClassObjectHandler (IEnumWbemClassObject pEnumWbemClassObject)
+ internal SecuredIEnumWbemClassObjectHandler GetSecuredIEnumWbemClassObjectHandler(IEnumWbemClassObject pEnumWbemClassObject)
{
- return new SecuredIEnumWbemClassObjectHandler (this, pEnumWbemClassObject);
+ return new SecuredIEnumWbemClassObjectHandler(this, pEnumWbemClassObject);
}
- internal SecuredIWbemServicesHandler GetSecuredIWbemServicesHandler( IWbemServices pWbemServiecs)
+ internal SecuredIWbemServicesHandler GetSecuredIWbemServicesHandler(IWbemServices pWbemServiecs)
{
return new SecuredIWbemServicesHandler(this, pWbemServiecs);
}
{
private readonly IEnumWbemClassObject pEnumWbemClassObjectsecurityHelper;
private readonly ManagementScope scope;
- internal SecuredIEnumWbemClassObjectHandler (ManagementScope theScope, IEnumWbemClassObject pEnumWbemClassObject)
+ internal SecuredIEnumWbemClassObjectHandler(ManagementScope theScope, IEnumWbemClassObject pEnumWbemClassObject)
{
this.scope = theScope;
pEnumWbemClassObjectsecurityHelper = pEnumWbemClassObject;
status = pEnumWbemClassObjectsecurityHelper.Reset_();
return status;
}
- internal int Next_( int lTimeout, uint uCount, IWbemClassObject_DoNotMarshal[] ppOutParams, ref uint puReturned)
+ internal int Next_(int lTimeout, uint uCount, IWbemClassObject_DoNotMarshal[] ppOutParams, ref uint puReturned)
{
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pEnumWbemClassObjectsecurityHelper.Next_( lTimeout, uCount, ppOutParams, out puReturned);
+ status = pEnumWbemClassObjectsecurityHelper.Next_(lTimeout, uCount, ppOutParams, out puReturned);
return status;
}
- internal int NextAsync_( uint uCount, IWbemObjectSink pSink)
+ internal int NextAsync_(uint uCount, IWbemObjectSink pSink)
{
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pEnumWbemClassObjectsecurityHelper.NextAsync_(uCount, pSink);
+ status = pEnumWbemClassObjectsecurityHelper.NextAsync_(uCount, pSink);
return status;
}
- internal int Clone_(ref IEnumWbemClassObject ppEnum)
+ internal int Clone_(ref IEnumWbemClassObject ppEnum)
{
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- if ( null != scope)
+ if (null != scope)
{
IntPtr password = scope.Options.GetPassword();
status = WmiNetUtilsHelper.CloneEnumWbemClassObject_f(
}
return status;
}
- internal int Skip_( int lTimeout, uint nCount)
+ internal int Skip_(int lTimeout, uint nCount)
{
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pEnumWbemClassObjectsecurityHelper.Skip_(lTimeout, nCount);
+ status = pEnumWbemClassObjectsecurityHelper.Skip_(lTimeout, nCount);
return status;
}
}
{
private readonly ManagementScope scope;
- internal SecuredConnectHandler (ManagementScope theScope)
+ internal SecuredConnectHandler(ManagementScope theScope)
{
this.scope = theScope;
}
- internal int ConnectNSecureIWbemServices(string path, ref IWbemServices pServices)
+ internal int ConnectNSecureIWbemServices(string path, ref IWbemServices pServices)
{
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- if ( null != scope )
+ if (null != scope)
{
bool needToReset = false;
IntPtr handle = IntPtr.Zero;
{
private readonly IWbemServices pWbemServiecsSecurityHelper;
private readonly ManagementScope scope;
- internal SecuredIWbemServicesHandler (ManagementScope theScope, IWbemServices pWbemServiecs)
+ internal SecuredIWbemServicesHandler(ManagementScope theScope, IWbemServices pWbemServiecs)
{
this.scope = theScope;
pWbemServiecsSecurityHelper = pWbemServiecs;
return status;
}
- internal int CancelAsyncCall_( IWbemObjectSink pSink)
+ internal int CancelAsyncCall_(IWbemObjectSink pSink)
{
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
status = pWbemServiecsSecurityHelper.CancelAsyncCall_(pSink);
return status;
}
- internal int QueryObjectSink_( int lFlags, ref IWbemObjectSink ppResponseHandler)
+ internal int QueryObjectSink_(int lFlags, ref IWbemObjectSink ppResponseHandler)
{
- int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pWbemServiecsSecurityHelper.QueryObjectSink_(lFlags, out ppResponseHandler);
+ int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
+ status = pWbemServiecsSecurityHelper.QueryObjectSink_(lFlags, out ppResponseHandler);
return status;
}
- internal int GetObject_(string strObjectPath, int lFlags, IWbemContext pCtx, ref IWbemClassObjectFreeThreaded ppObject, IntPtr ppCallResult)
+ internal int GetObject_(string strObjectPath, int lFlags, IWbemContext pCtx, ref IWbemClassObjectFreeThreaded ppObject, IntPtr ppCallResult)
{
- //It is assumed that caller always passes ppCallResult as IntPtr.Zero.
+ //It is assumed that caller always passes ppCallResult as IntPtr.Zero.
//If it changes let this call go through wminet_utils.dll. Check implementation of CreateInstanceEnum_ for more information.
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- if ( !object.ReferenceEquals(ppCallResult, IntPtr.Zero) )
+ if (!object.ReferenceEquals(ppCallResult, IntPtr.Zero))
status = pWbemServiecsSecurityHelper.GetObject_(strObjectPath, lFlags, pCtx, out ppObject, ppCallResult);
return status;
}
internal int GetObjectAsync_(string strObjectPath, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
{
- int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pWbemServiecsSecurityHelper.GetObjectAsync_(strObjectPath, lFlags, pCtx, pResponseHandler);
+ int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
+ status = pWbemServiecsSecurityHelper.GetObjectAsync_(strObjectPath, lFlags, pCtx, pResponseHandler);
return status;
}
- internal int PutClass_(IWbemClassObjectFreeThreaded pObject, int lFlags, IWbemContext pCtx, IntPtr ppCallResult)
+ internal int PutClass_(IWbemClassObjectFreeThreaded pObject, int lFlags, IWbemContext pCtx, IntPtr ppCallResult)
{
- int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- if ( null != scope)
+ int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
+ if (null != scope)
{
IntPtr password = scope.Options.GetPassword();
status = WmiNetUtilsHelper.PutClassWmi_f(pObject,
}
return status;
}
- internal int PutClassAsync_(IWbemClassObjectFreeThreaded pObject, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
+ internal int PutClassAsync_(IWbemClassObjectFreeThreaded pObject, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
{
- int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pWbemServiecsSecurityHelper.PutClassAsync_(pObject, lFlags, pCtx, pResponseHandler);
+ int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
+ status = pWbemServiecsSecurityHelper.PutClassAsync_(pObject, lFlags, pCtx, pResponseHandler);
return status;
}
- internal int DeleteClass_( string strClass, int lFlags, IWbemContext pCtx, IntPtr ppCallResult)
- {
- //It is assumed that caller always passes ppCallResult as IntPtr.Zero.
+ internal int DeleteClass_(string strClass, int lFlags, IWbemContext pCtx, IntPtr ppCallResult)
+ {
+ //It is assumed that caller always passes ppCallResult as IntPtr.Zero.
//If it changes let this call go through wminet_utils.dll. Check implementation of CreateInstanceEnum_ for more information.
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- if ( !object.ReferenceEquals(ppCallResult, IntPtr.Zero) )
+ if (!object.ReferenceEquals(ppCallResult, IntPtr.Zero))
status = pWbemServiecsSecurityHelper.DeleteClass_(strClass, lFlags, pCtx, ppCallResult);
return status;
- }
- internal int DeleteClassAsync_(string strClass, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
+ }
+ internal int DeleteClassAsync_(string strClass, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
{
- int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pWbemServiecsSecurityHelper.DeleteClassAsync_(strClass, lFlags, pCtx, pResponseHandler);
+ int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
+ status = pWbemServiecsSecurityHelper.DeleteClassAsync_(strClass, lFlags, pCtx, pResponseHandler);
return status;
}
- internal int CreateClassEnum_(string strSuperClass, int lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum)
- {
+ internal int CreateClassEnum_(string strSuperClass, int lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum)
+ {
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- if ( null != scope )
+ if (null != scope)
{
IntPtr password = scope.Options.GetPassword();
status = WmiNetUtilsHelper.CreateClassEnumWmi_f(strSuperClass,
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password);
}
return status;
- }
- internal int CreateClassEnumAsync_(string strSuperClass, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
+ }
+ internal int CreateClassEnumAsync_(string strSuperClass, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
{
- int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pWbemServiecsSecurityHelper.CreateClassEnumAsync_(strSuperClass, lFlags, pCtx, pResponseHandler);
+ int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
+ status = pWbemServiecsSecurityHelper.CreateClassEnumAsync_(strSuperClass, lFlags, pCtx, pResponseHandler);
return status;
}
- internal int PutInstance_( IWbemClassObjectFreeThreaded pInst, int lFlags, IWbemContext pCtx, IntPtr ppCallResult)
- {
+ internal int PutInstance_(IWbemClassObjectFreeThreaded pInst, int lFlags, IWbemContext pCtx, IntPtr ppCallResult)
+ {
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- if ( null != scope)
+ if (null != scope)
{
IntPtr password = scope.Options.GetPassword();
status = WmiNetUtilsHelper.PutInstanceWmi_f(pInst,
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password);
}
return status;
- }
- internal int PutInstanceAsync_(IWbemClassObjectFreeThreaded pInst, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
+ }
+ internal int PutInstanceAsync_(IWbemClassObjectFreeThreaded pInst, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
{
- int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pWbemServiecsSecurityHelper.PutInstanceAsync_(pInst, lFlags, pCtx, pResponseHandler);
+ int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
+ status = pWbemServiecsSecurityHelper.PutInstanceAsync_(pInst, lFlags, pCtx, pResponseHandler);
return status;
}
- internal int DeleteInstance_(string strObjectPath, int lFlags, IWbemContext pCtx, IntPtr ppCallResult)
- {
- //It is assumed that caller always passes ppCallResult as IntPtr.Zero.
+ internal int DeleteInstance_(string strObjectPath, int lFlags, IWbemContext pCtx, IntPtr ppCallResult)
+ {
+ //It is assumed that caller always passes ppCallResult as IntPtr.Zero.
//If it changes let this call go through wminet_utils.dll. Check implementation of CreateInstanceEnum_ for more information.
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- if ( !object.ReferenceEquals(ppCallResult, IntPtr.Zero) )
+ if (!object.ReferenceEquals(ppCallResult, IntPtr.Zero))
status = pWbemServiecsSecurityHelper.DeleteInstance_(strObjectPath, lFlags, pCtx, ppCallResult);
return status;
- }
- internal int DeleteInstanceAsync_(string strObjectPath, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
+ }
+ internal int DeleteInstanceAsync_(string strObjectPath, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
{
- int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pWbemServiecsSecurityHelper.DeleteInstanceAsync_(strObjectPath, lFlags, pCtx, pResponseHandler);
+ int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
+ status = pWbemServiecsSecurityHelper.DeleteInstanceAsync_(strObjectPath, lFlags, pCtx, pResponseHandler);
return status;
}
- internal int CreateInstanceEnum_(string strFilter, int lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum)
- {
+ internal int CreateInstanceEnum_(string strFilter, int lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum)
+ {
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- if ( null != scope)
+ if (null != scope)
{
IntPtr password = scope.Options.GetPassword();
status = WmiNetUtilsHelper.CreateInstanceEnumWmi_f(strFilter,
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password);
}
return status;
- }
- internal int CreateInstanceEnumAsync_(string strFilter, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
+ }
+ internal int CreateInstanceEnumAsync_(string strFilter, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
{
- int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pWbemServiecsSecurityHelper.CreateInstanceEnumAsync_(strFilter, lFlags, pCtx, pResponseHandler);
+ int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
+ status = pWbemServiecsSecurityHelper.CreateInstanceEnumAsync_(strFilter, lFlags, pCtx, pResponseHandler);
return status;
}
- internal int ExecQuery_(string strQueryLanguage, string strQuery, int lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum)
- {
+ internal int ExecQuery_(string strQueryLanguage, string strQuery, int lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum)
+ {
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- if ( null != scope)
+ if (null != scope)
{
IntPtr password = scope.Options.GetPassword();
status = WmiNetUtilsHelper.ExecQueryWmi_f(strQueryLanguage,
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password);
}
return status;
- }
- internal int ExecQueryAsync_(string strQueryLanguage, string strQuery, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
+ }
+ internal int ExecQueryAsync_(string strQueryLanguage, string strQuery, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
{
- int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pWbemServiecsSecurityHelper.ExecQueryAsync_(strQueryLanguage, strQuery, lFlags, pCtx, pResponseHandler);
+ int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
+ status = pWbemServiecsSecurityHelper.ExecQueryAsync_(strQueryLanguage, strQuery, lFlags, pCtx, pResponseHandler);
return status;
}
- internal int ExecNotificationQuery_(string strQueryLanguage, string strQuery, int lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum)
+ internal int ExecNotificationQuery_(string strQueryLanguage, string strQuery, int lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum)
{
- int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- if ( null != scope)
+ int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
+ if (null != scope)
{
IntPtr password = scope.Options.GetPassword();
status = WmiNetUtilsHelper.ExecNotificationQueryWmi_f(strQueryLanguage,
}
return status;
}
- internal int ExecNotificationQueryAsync_(string strQueryLanguage, string strQuery, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
+ internal int ExecNotificationQueryAsync_(string strQueryLanguage, string strQuery, int lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)
{
- int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pWbemServiecsSecurityHelper.ExecNotificationQueryAsync_(strQueryLanguage, strQuery, lFlags, pCtx, pResponseHandler);
+ int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
+ status = pWbemServiecsSecurityHelper.ExecNotificationQueryAsync_(strQueryLanguage, strQuery, lFlags, pCtx, pResponseHandler);
return status;
}
- internal int ExecMethod_( string strObjectPath, string strMethodName, int lFlags, IWbemContext pCtx, IWbemClassObjectFreeThreaded pInParams, ref IWbemClassObjectFreeThreaded ppOutParams, IntPtr ppCallResult)
- {
+ internal int ExecMethod_(string strObjectPath, string strMethodName, int lFlags, IWbemContext pCtx, IWbemClassObjectFreeThreaded pInParams, ref IWbemClassObjectFreeThreaded ppOutParams, IntPtr ppCallResult)
+ {
//It is assumed that caller always passes ppCallResult as IntPtr.Zero.
//If it changes let this call go through wminet_utils.dll. Check implementation of CreateInstanceEnum_ for more information.
int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- if ( !object.ReferenceEquals(ppCallResult, IntPtr.Zero) )
+ if (!object.ReferenceEquals(ppCallResult, IntPtr.Zero))
status = pWbemServiecsSecurityHelper.ExecMethod_(strObjectPath, strMethodName, lFlags, pCtx, pInParams, out ppOutParams, ppCallResult);
return status;
- }
- internal int ExecMethodAsync_(string strObjectPath, string strMethodName, int lFlags, IWbemContext pCtx, IWbemClassObjectFreeThreaded pInParams, IWbemObjectSink pResponseHandler)
+ }
+ internal int ExecMethodAsync_(string strObjectPath, string strMethodName, int lFlags, IWbemContext pCtx, IWbemClassObjectFreeThreaded pInParams, IWbemObjectSink pResponseHandler)
{
- int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
- status = pWbemServiecsSecurityHelper.ExecMethodAsync_(strObjectPath, strMethodName, lFlags, pCtx, pInParams, pResponseHandler);
+ int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
+ status = pWbemServiecsSecurityHelper.ExecMethodAsync_(strObjectPath, strMethodName, lFlags, pCtx, pInParams, pResponseHandler);
return status;
}
}
private readonly IntPtr handle;
private readonly ManagementScope scope;
- internal SecurityHandler (ManagementScope theScope)
+ internal SecurityHandler(ManagementScope theScope)
{
this.scope = theScope;
if (null != scope)
}
}
- internal void Reset ()
+ internal void Reset()
{
if (needToReset)
{
if (null != scope)
{
- WmiNetUtilsHelper.ResetSecurity_f ( handle);
+ WmiNetUtilsHelper.ResetSecurity_f(handle);
}
}
}
- internal void Secure (IWbemServices services)
+ internal void Secure(IWbemServices services)
{
if (null != scope)
{
if (value is ManagementScope && destinationType == typeof(InstanceDescriptor))
{
ManagementScope obj = ((ManagementScope)(value));
- ConstructorInfo ctor = typeof(ManagementScope).GetConstructor(new Type[] {typeof(string)});
+ ConstructorInfo ctor = typeof(ManagementScope).GetConstructor(new Type[] { typeof(string) });
if (ctor != null)
{
- return new InstanceDescriptor(ctor, new object[] {obj.Path.Path});
+ return new InstanceDescriptor(ctor, new object[] { obj.Path.Path });
}
}
return base.ConvertTo(context, culture, value, destinationType);
get
{
RefreshMethodInfo();
- return (null == wmiInParams) ? null : new ManagementBaseObject(wmiInParams); }
+ return (null == wmiInParams) ? null : new ManagementBaseObject(wmiInParams);
+ }
}
/// <summary>
get
{
RefreshMethodInfo();
- return (null == wmiOutParams) ? null : new ManagementBaseObject(wmiOutParams); }
+ return (null == wmiOutParams) ? null : new ManagementBaseObject(wmiOutParams);
+ }
}
/// <summary>
/// <para><see langword='true'/> if the object is synchronized;
/// otherwise, <see langword='false'/>.</para>
/// </value>
- public bool IsSynchronized { get { return false; }
+ public bool IsSynchronized
+ {
+ get { return false; }
}
/// <summary>
/// <value>
/// <para>The object to be used for synchronization.</para>
/// </value>
- public object SyncRoot { get { return this; }
+ public object SyncRoot
+ {
+ get { return this; }
}
/// <overload>
{
get
{
- return new MethodData(parent, (string)en.Current);
+ return new MethodData(parent, (string)en.Current);
}
}
/// <para>Moves to the next element in the <see cref='System.Management.MethodDataCollection'/> enumeration.</para>
/// </summary>
/// <returns><see langword='true'/> if the enumerator was successfully advanced to the next method; <see langword='false'/> if the enumerator has passed the end of the collection.</returns>
- public bool MoveNext ()
+ public bool MoveNext()
{
return en.MoveNext();
}
get
{
if (null == methodName)
- throw new ArgumentNullException (nameof(methodName));
+ throw new ArgumentNullException(nameof(methodName));
return new MethodData(parent, methodName);
}
public class PropertyData
{
private readonly ManagementBaseObject parent; //need access to IWbemClassObject pointer to be able to refresh property info
- //and get property qualifiers
+ //and get property qualifiers
private readonly string propertyName;
private object propertyValue;
/// </value>
public object Value
{
- get {
+ get
+ {
RefreshPropertyInfo();
return ValueTypeSafety.GetSafeObject(MapWmiValueToValue(propertyValue,
(CimType)(propertyType & ~(int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY),
(0 != (propertyType & (int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY))));
}
- set {
+ set
+ {
RefreshPropertyInfo();
object newValue = MapValueToWmiValue(value,
// whether this property is a key or not, we just do it for any property
else
if (parent.GetType() == typeof(ManagementObject))
- ((ManagementObject)parent).Path.UpdateRelativePath((string)parent["__RELPATH"]);
+ ((ManagementObject)parent).Path.UpdateRelativePath((string)parent["__RELPATH"]);
}
}
/// <para>A <see cref='System.Management.CimType'/> value
/// representing the CIM type of the property.</para>
/// </value>
- public CimType Type {
- get {
+ public CimType Type
+ {
+ get
+ {
RefreshPropertyInfo();
return (CimType)(propertyType & ~(int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY);
}
/// </value>
public bool IsLocal
{
- get {
+ get
+ {
RefreshPropertyInfo();
- return ((propertyFlavor & (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_ORIGIN_PROPAGATED) != 0) ? false : true; }
+ return ((propertyFlavor & (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_ORIGIN_PROPAGATED) != 0) ? false : true;
+ }
}
/// <summary>
/// </value>
public bool IsArray
{
- get {
+ get
+ {
RefreshPropertyInfo();
- return ((propertyType & (int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY) != 0); }
+ return ((propertyType & (int)tag_CIMTYPE_ENUMERATION.CIM_FLAG_ARRAY) != 0);
+ }
}
/// <summary>
/// </value>
public string Origin
{
- get {
+ get
+ {
string className = null;
int status = parent.wbemObject.GetPropertyOrigin_(propertyName, out className);
/// </value>
public QualifierDataCollection Qualifiers
{
- get {
+ get
+ {
if (qualifiers == null)
qualifiers = new QualifierDataCollection(parent, propertyName, QualifierType.PropertyQualifier);
return qualifiers;
}
}
- internal long NullEnumValue
- {
- get {
- return propertyNullEnumValue;
- }
+ internal long NullEnumValue
+ {
+ get
+ {
+ return propertyNullEnumValue;
+ }
- set {
- propertyNullEnumValue = value;
- }
- }
+ set
+ {
+ propertyNullEnumValue = value;
+ }
+ }
/// <summary>
/// Takes a property value returned from WMI and maps it to an
switch (type)
{
case CimType.UInt16:
- val = new ushort [length];
+ val = new ushort[length];
for (int i = 0; i < length; i++)
- ((ushort[])val) [i] = (ushort)((int)(wmiValueArray.GetValue(i)));
+ ((ushort[])val)[i] = (ushort)((int)(wmiValueArray.GetValue(i)));
break;
case CimType.UInt32:
- val = new uint [length];
+ val = new uint[length];
for (int i = 0; i < length; i++)
((uint[])val)[i] = (uint)((int)(wmiValueArray.GetValue(i)));
break;
case CimType.UInt64:
- val = new ulong [length];
+ val = new ulong[length];
for (int i = 0; i < length; i++)
- ((ulong[])val) [i] = Convert.ToUInt64((string)(wmiValueArray.GetValue(i)), (IFormatProvider)CultureInfo.CurrentCulture.GetFormat(typeof(ulong)));
+ ((ulong[])val)[i] = Convert.ToUInt64((string)(wmiValueArray.GetValue(i)), (IFormatProvider)CultureInfo.CurrentCulture.GetFormat(typeof(ulong)));
break;
case CimType.SInt8:
- val = new sbyte [length];
+ val = new sbyte[length];
for (int i = 0; i < length; i++)
- ((sbyte[])val) [i] = (sbyte)((short)(wmiValueArray.GetValue(i)));
+ ((sbyte[])val)[i] = (sbyte)((short)(wmiValueArray.GetValue(i)));
break;
case CimType.SInt64:
- val = new long [length];
+ val = new long[length];
for (int i = 0; i < length; i++)
- ((long[])val) [i] = Convert.ToInt64((string)(wmiValueArray.GetValue(i)), (IFormatProvider)CultureInfo.CurrentCulture.GetFormat(typeof(long)));
+ ((long[])val)[i] = Convert.ToInt64((string)(wmiValueArray.GetValue(i)), (IFormatProvider)CultureInfo.CurrentCulture.GetFormat(typeof(long)));
break;
case CimType.Char16:
- val = new char [length];
+ val = new char[length];
for (int i = 0; i < length; i++)
- ((char[])val) [i] = (char)((short)(wmiValueArray.GetValue(i)));
+ ((char[])val)[i] = (char)((short)(wmiValueArray.GetValue(i)));
break;
case CimType.Object:
- val = new ManagementBaseObject [length];
+ val = new ManagementBaseObject[length];
for (int i = 0; i < length; i++)
- ((ManagementBaseObject[])val) [i] = new ManagementBaseObject(new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(wmiValueArray.GetValue(i))));
+ ((ManagementBaseObject[])val)[i] = new ManagementBaseObject(new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(wmiValueArray.GetValue(i))));
break;
default:
switch (type)
{
case CimType.SInt8:
- wmiValue = new short [length];
+ wmiValue = new short[length];
for (int i = 0; i < length; i++)
((short[])(wmiValue))[i] = (short)Convert.ToSByte(valArray.GetValue(i), (IFormatProvider)culInfo.GetFormat(typeof(sbyte)));
break;
wmiValue = val;
else
{
- wmiValue = new byte [length];
+ wmiValue = new byte[length];
for (int i = 0; i < length; i++)
((byte[])wmiValue)[i] = Convert.ToByte(valArray.GetValue(i), (IFormatProvider)culInfo.GetFormat(typeof(byte)));
}
wmiValue = val;
else
{
- wmiValue = new short [length];
+ wmiValue = new short[length];
for (int i = 0; i < length; i++)
((short[])(wmiValue))[i] = Convert.ToInt16(valArray.GetValue(i), (IFormatProvider)culInfo.GetFormat(typeof(short)));
}
break;
case CimType.UInt16:
- wmiValue = new int [length];
+ wmiValue = new int[length];
for (int i = 0; i < length; i++)
((int[])(wmiValue))[i] = (int)(Convert.ToUInt16(valArray.GetValue(i), (IFormatProvider)culInfo.GetFormat(typeof(ushort))));
break;
wmiValue = val;
else
{
- wmiValue = new int [length];
+ wmiValue = new int[length];
for (int i = 0; i < length; i++)
((int[])(wmiValue))[i] = Convert.ToInt32(valArray.GetValue(i), (IFormatProvider)culInfo.GetFormat(typeof(int)));
}
break;
case CimType.UInt32:
- wmiValue = new int [length];
+ wmiValue = new int[length];
for (int i = 0; i < length; i++)
((int[])(wmiValue))[i] = (int)(Convert.ToUInt32(valArray.GetValue(i), (IFormatProvider)culInfo.GetFormat(typeof(uint))));
break;
case CimType.SInt64:
- wmiValue = new string [length];
+ wmiValue = new string[length];
for (int i = 0; i < length; i++)
((string[])(wmiValue))[i] = (Convert.ToInt64(valArray.GetValue(i), (IFormatProvider)culInfo.GetFormat(typeof(long)))).ToString((IFormatProvider)culInfo.GetFormat(typeof(long)));
break;
case CimType.UInt64:
- wmiValue = new string [length];
+ wmiValue = new string[length];
for (int i = 0; i < length; i++)
((string[])(wmiValue))[i] = (Convert.ToUInt64(valArray.GetValue(i), (IFormatProvider)culInfo.GetFormat(typeof(ulong)))).ToString((IFormatProvider)culInfo.GetFormat(typeof(ulong)));
break;
wmiValue = val;
else
{
- wmiValue = new float [length];
+ wmiValue = new float[length];
for (int i = 0; i < length; i++)
((float[])(wmiValue))[i] = Convert.ToSingle(valArray.GetValue(i), (IFormatProvider)culInfo.GetFormat(typeof(float)));
}
wmiValue = val;
else
{
- wmiValue = new double [length];
+ wmiValue = new double[length];
for (int i = 0; i < length; i++)
((double[])(wmiValue))[i] = Convert.ToDouble(valArray.GetValue(i), (IFormatProvider)culInfo.GetFormat(typeof(double)));
}
break;
case CimType.Char16:
- wmiValue = new short [length];
+ wmiValue = new short[length];
for (int i = 0; i < length; i++)
((short[])(wmiValue))[i] = (short)Convert.ToChar(valArray.GetValue(i), (IFormatProvider)culInfo.GetFormat(typeof(char)));
break;
wmiValue = val;
else
{
- wmiValue = new string [length];
+ wmiValue = new string[length];
for (int i = 0; i < length; i++)
((string[])(wmiValue))[i] = (valArray.GetValue(i)).ToString();
}
wmiValue = val;
else
{
- wmiValue = new bool [length];
+ wmiValue = new bool[length];
for (int i = 0; i < length; i++)
((bool[])(wmiValue))[i] = Convert.ToBoolean(valArray.GetValue(i), (IFormatProvider)culInfo.GetFormat(typeof(bool)));
}
case CimType.Object:
if (val is ManagementBaseObject)
{
- wmiValue = Marshal.GetObjectForIUnknown(((ManagementBaseObject) val).wbemObject);
+ wmiValue = Marshal.GetObjectForIUnknown(((ManagementBaseObject)val).wbemObject);
}
else
{
wmiValue = new short[length];
for (int i = 0; i < length; i++)
- ((short[])wmiValue) [i] = ((IConvertible)((byte)(arrayValue[i]))).ToInt16(null);
+ ((short[])wmiValue)[i] = ((IConvertible)((byte)(arrayValue[i]))).ToInt16(null);
}
else if (elementType == typeof(sbyte))
{
wmiValue = new short[length];
for (int i = 0; i < length; i++)
- ((short[])wmiValue) [i] = ((IConvertible)((sbyte)(arrayValue[i]))).ToInt16(null);
+ ((short[])wmiValue)[i] = ((IConvertible)((sbyte)(arrayValue[i]))).ToInt16(null);
}
else if (elementType == typeof(bool))
{
wmiValue = new int[length];
for (int i = 0; i < length; i++)
- ((int[])wmiValue) [i] = ((IConvertible)((ushort)(arrayValue[i]))).ToInt32(null);
+ ((int[])wmiValue)[i] = ((IConvertible)((ushort)(arrayValue[i]))).ToInt32(null);
}
else if (elementType == typeof(short))
{
wmiValue = new string[length];
for (int i = 0; i < length; i++)
- ((string[])wmiValue) [i] = ((uint)(arrayValue[i])).ToString((IFormatProvider)culInfo.GetFormat(typeof(uint)));
+ ((string[])wmiValue)[i] = ((uint)(arrayValue[i])).ToString((IFormatProvider)culInfo.GetFormat(typeof(uint)));
}
else if (elementType == typeof(ulong))
{
wmiValue = new string[length];
for (int i = 0; i < length; i++)
- ((string[])wmiValue) [i] = ((ulong)(arrayValue[i])).ToString((IFormatProvider)culInfo.GetFormat(typeof(ulong)));
+ ((string[])wmiValue)[i] = ((ulong)(arrayValue[i])).ToString((IFormatProvider)culInfo.GetFormat(typeof(ulong)));
}
else if (elementType == typeof(long))
{
wmiValue = new string[length];
for (int i = 0; i < length; i++)
- ((string[])wmiValue) [i] = ((long)(arrayValue[i])).ToString((IFormatProvider)culInfo.GetFormat(typeof(long)));
+ ((string[])wmiValue)[i] = ((long)(arrayValue[i])).ToString((IFormatProvider)culInfo.GetFormat(typeof(long)));
}
else if (elementType == typeof(float))
{
wmiValue = new short[length];
for (int i = 0; i < length; i++)
- ((short[])wmiValue) [i] = ((IConvertible)((char)(arrayValue[i]))).ToInt16(null);
+ ((short[])wmiValue)[i] = ((IConvertible)((char)(arrayValue[i]))).ToInt16(null);
}
}
else
if (val is ManagementBaseObject)
{
type = CimType.Object;
- wmiValue = Marshal.GetObjectForIUnknown(((ManagementBaseObject) val).wbemObject);
+ wmiValue = Marshal.GetObjectForIUnknown(((ManagementBaseObject)val).wbemObject);
}
}
}
/// </value>
public int Count
{
- get {
+ get
+ {
string[] propertyNames = null; object qualVal = null;
int flag;
if (isSystem)
/// <para><see langword='true'/> if the object is synchronized;
/// otherwise, <see langword='false'/>.</para>
/// </value>
- public bool IsSynchronized { get { return false; }
+ public bool IsSynchronized
+ {
+ get { return false; }
}
/// <summary>
/// <value>
/// <para>The object to be used for synchronization.</para>
/// </value>
- public object SyncRoot { get { return this; }
+ public object SyncRoot
+ {
+ get { return this; }
}
/// <overload>
/// </value>
public PropertyData Current
{
- get {
+ get
+ {
if ((index == -1) || (index == propertyNames.Length))
throw new InvalidOperationException();
else
/// </example>
public virtual PropertyData this[string propertyName]
{
- get {
+ get
+ {
if (null == propertyName)
throw new ArgumentNullException(nameof(propertyName));
if (elementType == typeof(int))
{
- wmiValue = new int [length];
+ wmiValue = new int[length];
for (int i = 0; i < length; i++)
((int[])(wmiValue))[i] = Convert.ToInt32(valArray.GetValue(i), (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int)));
}
else if (elementType == typeof(double))
{
- wmiValue = new double [length];
+ wmiValue = new double[length];
for (int i = 0; i < length; i++)
((double[])(wmiValue))[i] = Convert.ToDouble(valArray.GetValue(i), (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(double)));
}
else if (elementType == typeof(string))
{
- wmiValue = new string [length];
+ wmiValue = new string[length];
for (int i = 0; i < length; i++)
((string[])(wmiValue))[i] = (valArray.GetValue(i)).ToString();
}
else if (elementType == typeof(bool))
{
- wmiValue = new bool [length];
+ wmiValue = new bool[length];
for (int i = 0; i < length; i++)
((bool[])(wmiValue))[i] = Convert.ToBoolean(valArray.GetValue(i), (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(bool)));
}
/// </remarks>
public object Value
{
- get {
+ get
+ {
RefreshQualifierInfo();
return ValueTypeSafety.GetSafeObject(qualifierValue);
}
- set {
+ set
+ {
int status = (int)ManagementStatus.NoError;
RefreshQualifierInfo();
/// </remarks>
public bool IsAmended
{
- get {
+ get
+ {
RefreshQualifierInfo();
return ((int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_AMENDED ==
(qualifierFlavor & (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_AMENDED));
{
int status = (int)ManagementStatus.NoError;
- RefreshQualifierInfo ();
+ RefreshQualifierInfo();
// Mask out origin bits
int flavor = qualifierFlavor & ~(int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_ORIGIN;
/// </value>
public bool IsLocal
{
- get {
+ get
+ {
RefreshQualifierInfo();
return ((int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_ORIGIN_LOCAL ==
(qualifierFlavor & (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_ORIGIN));
/// </value>
public bool PropagatesToInstance
{
- get {
+ get
+ {
RefreshQualifierInfo();
return ((int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE ==
(qualifierFlavor & (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE));
}
- set {
+ set
+ {
int status = (int)ManagementStatus.NoError;
- RefreshQualifierInfo ();
+ RefreshQualifierInfo();
// Mask out origin bits
int flavor = qualifierFlavor & ~(int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_ORIGIN;
/// </value>
public bool PropagatesToSubclass
{
- get {
+ get
+ {
RefreshQualifierInfo();
return ((int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_DERIVED_CLASS ==
(qualifierFlavor & (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_DERIVED_CLASS));
}
- set {
+ set
+ {
int status = (int)ManagementStatus.NoError;
- RefreshQualifierInfo ();
+ RefreshQualifierInfo();
// Mask out origin bits
int flavor = qualifierFlavor & ~(int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_ORIGIN;
/// </value>
public bool IsOverridable
{
- get {
+ get
+ {
RefreshQualifierInfo();
return ((int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_OVERRIDABLE ==
(qualifierFlavor & (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_PERMISSIONS));
}
- set {
+ set
+ {
int status = (int)ManagementStatus.NoError;
- RefreshQualifierInfo ();
+ RefreshQualifierInfo();
// Mask out origin bits
int flavor = qualifierFlavor & ~(int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_MASK_ORIGIN;
/// </summary>
private IWbemQualifierSetFreeThreaded GetTypeQualifierSet(QualifierType qualifierSetType)
{
- IWbemQualifierSetFreeThreaded qualifierSet = null;
+ IWbemQualifierSetFreeThreaded qualifierSet = null;
int status = qualifierSetType switch
{
/// </value>
public int Count
{
- get {
+ get
+ {
string[] qualifierNames = null;
IWbemQualifierSetFreeThreaded quals;
try
/// <para><see langword='true'/> if the object is synchronized;
/// otherwise, <see langword='false'/>.</para>
/// </value>
- public bool IsSynchronized { get { return false; }
+ public bool IsSynchronized
+ {
+ get { return false; }
}
/// <summary>
/// <value>
/// <para>The object to be used for synchronization.</para>
/// </value>
- public object SyncRoot { get { return this; }
+ public object SyncRoot
+ {
+ get { return this; }
}
/// <overload>
internal QualifierDataEnumerator(ManagementBaseObject parent, string propertyOrMethodName,
QualifierType qualifierType)
{
- this.parent = parent;
+ this.parent = parent;
this.propertyOrMethodName = propertyOrMethodName;
- this.qualifierType = qualifierType;
- this.qualifierNames = null;
+ this.qualifierType = qualifierType;
+ this.qualifierNames = null;
IWbemQualifierSetFreeThreaded qualifierSet = null;
int status = (int)ManagementStatus.NoError;
/// </value>
public QualifierData Current
{
- get {
+ get
+ {
if ((index == -1) || (index == qualifierNames.Length))
throw new InvalidOperationException();
else
/// </value>
public virtual QualifierData this[string qualifierName]
{
- get {
+ get
+ {
if (null == qualifierName)
throw new ArgumentNullException(nameof(qualifierName));
private CodeTypeDeclaration ecc;
private CodeTypeDeclaration EnumObj;
private CodeNamespace cn;
- private CodeMemberProperty cmp;
+ private CodeMemberProperty cmp;
private CodeConstructor cctor;
private CodeMemberField cf;
private CodeObjectCreateExpression coce;
private CodeAttributeDeclaration cad;
- private readonly ArrayList arrKeyType = new ArrayList(5);
- private readonly ArrayList arrKeys = new ArrayList(5);
- private readonly ArrayList BitMap = new ArrayList(5);
- private ArrayList BitValues = new ArrayList(5);
- private readonly ArrayList ValueMap = new ArrayList(5);
- private ArrayList Values = new ArrayList(5);
+ private readonly ArrayList arrKeyType = new ArrayList(5);
+ private readonly ArrayList arrKeys = new ArrayList(5);
+ private readonly ArrayList BitMap = new ArrayList(5);
+ private ArrayList BitValues = new ArrayList(5);
+ private readonly ArrayList ValueMap = new ArrayList(5);
+ private ArrayList Values = new ArrayList(5);
private SortedList PublicProperties = new SortedList(StringComparer.OrdinalIgnoreCase);
- private SortedList PublicMethods = new SortedList (StringComparer.OrdinalIgnoreCase);
- private SortedList PublicNamesUsed = new SortedList(StringComparer.OrdinalIgnoreCase);
+ private SortedList PublicMethods = new SortedList(StringComparer.OrdinalIgnoreCase);
+ private SortedList PublicNamesUsed = new SortedList(StringComparer.OrdinalIgnoreCase);
private SortedList PrivateNamesUsed = new SortedList(StringComparer.OrdinalIgnoreCase);
- private bool bHasEmbeddedProperties = false;
+ private bool bHasEmbeddedProperties = false;
/// <summary>
public bool GenerateCode(CodeLanguage lang, string filePath, string netNamespace)
{
// check for proper arguments
- if (filePath == null )
+ if (filePath == null)
{
- throw new ArgumentOutOfRangeException (SR.NullFilePathException);
+ throw new ArgumentOutOfRangeException(SR.NullFilePathException);
}
if (filePath.Length == 0)
{
- throw new ArgumentOutOfRangeException (SR.EmptyFilePathException);
+ throw new ArgumentOutOfRangeException(SR.EmptyFilePathException);
}
NETNamespace = netNamespace;
InitializeCodeGeneration();
//Now create the filestream (output file)
- tw = new StreamWriter(new FileStream (filePath, FileMode.Create), System.Text.Encoding.UTF8);
+ tw = new StreamWriter(new FileStream(filePath, FileMode.Create), System.Text.Encoding.UTF8);
return GenerateAndWriteCode(lang);
{
if (classobj == null)
{
- if (OriginalNamespace == null || ( OriginalNamespace != null && OriginalNamespace.Length == 0))
+ if (OriginalNamespace == null || (OriginalNamespace != null && OriginalNamespace.Length == 0))
{
- throw new ArgumentOutOfRangeException (SR.NamespaceNotInitializedException);
+ throw new ArgumentOutOfRangeException(SR.NamespaceNotInitializedException);
}
- if (OriginalClassName == null || ( OriginalClassName != null && OriginalClassName.Length == 0))
+ if (OriginalClassName == null || (OriginalClassName != null && OriginalClassName.Length == 0))
{
- throw new ArgumentOutOfRangeException (SR.ClassNameNotInitializedException);
+ throw new ArgumentOutOfRangeException(SR.ClassNameNotInitializedException);
}
}
}
private CodeTypeDeclaration GetCodeTypeDeclarationForClass(bool bIncludeSystemClassinClassDef)
{
//Create type defination for the class
- cc = new CodeTypeDeclaration (PrivateNamesUsed["GeneratedClassName"].ToString());
+ cc = new CodeTypeDeclaration(PrivateNamesUsed["GeneratedClassName"].ToString());
// Adding Component as base class so as to enable drag and drop
cc.BaseTypes.Add(new CodeTypeReference(PrivateNamesUsed["ComponentClass"].ToString()));
// Generate a property "StaticScope" to set and get the static ManagementScope for the class
GeneratePublicProperty(PrivateNamesUsed["staticScope"].ToString(), PublicNamesUsed["ScopeClass"].ToString(),
- new CodeVariableReferenceExpression(PrivateNamesUsed["statMgmtScope"].ToString()), true, SR.CommentStaticScopeProperty, true);
+ new CodeVariableReferenceExpression(PrivateNamesUsed["statMgmtScope"].ToString()), true, SR.CommentStaticScopeProperty, true);
// Generate a function to check if a given class can be represented
// by the generated class
cc.Name = cp.CreateValidIdentifier(cc.Name);
//As we have finished the class definition, generate the class code NOW!!!!!
- cn.Types.Add (cc);
+ cn.Types.Add(cc);
try
{
- cp.GenerateCodeFromNamespace (cn, tw, new CodeGeneratorOptions());
+ cp.GenerateCodeFromNamespace(cn, tw, new CodeGeneratorOptions());
}
finally
{
" results in " + thePath.Path);
*/
}
- classobj = new ManagementClass (thePath);
+ classobj = new ManagementClass(thePath);
}
else
{
foreach (string s in PublicNamesUsed.Values)
{
nIndex = IsContainedIn(s, ref PublicProperties);
- if ( nIndex != -1)
+ if (nIndex != -1)
{
//We had found a collision with a public property
//So we will resolve the collision by changing the property name
//Now we will create the CollectionClass and Enumerator Class names as they are dependent on the
//generated class name and the generated class name might have changed due to collision
- string strTemp = PrivateNamesUsed["GeneratedClassName"].ToString()+"Collection";
+ string strTemp = PrivateNamesUsed["GeneratedClassName"].ToString() + "Collection";
PrivateNamesUsed.Add("CollectionClass", ResolveCollision(strTemp, true));
- strTemp = PrivateNamesUsed["GeneratedClassName"].ToString()+"Enumerator";
+ strTemp = PrivateNamesUsed["GeneratedClassName"].ToString() + "Enumerator";
PrivateNamesUsed.Add("EnumeratorClass", ResolveCollision(strTemp, true));
}
if (bCheckthisFirst == false)
{
k++;
- strTemp = strTemp + strToAdd +k.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int)));
+ strTemp = strTemp + strToAdd + k.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int)));
}
while (bCollision == true)
strToAdd = strToAdd + "_";
k = 0;
}
- strTemp = inString + strToAdd +k.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int)));
+ strTemp = inString + strToAdd + k.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int)));
}
if (strTemp.Length > 0)
{
string strFirstChar = strTemp.Substring(0, 1).ToUpper(CultureInfo.InvariantCulture);
- strTemp = strFirstChar + strTemp.Substring(1, strTemp.Length -1);
+ strTemp = strFirstChar + strTemp.Substring(1, strTemp.Length - 1);
}
return strTemp;
if (NETNamespace.Length == 0)
{
strNs = OriginalNamespace;
- strNs = strNs.Replace ('\\', '.');
+ strNs = strNs.Replace('\\', '.');
strNs = strNs.ToUpper(CultureInfo.InvariantCulture);
}
else
strNs += strClass;
}
//Now trim the class name without the first '_'
- strClass = OriginalClassName.Substring(OriginalClassName.IndexOf('_')+1);
+ strClass = OriginalClassName.Substring(OriginalClassName.IndexOf('_') + 1);
}
else
{
strClass = "C" + strClass;
}
- strClass = ResolveCollision (strClass, true);
+ strClass = ResolveCollision(strClass, true);
// Try to get a type from any of the namespace which are used in the generated code and see if
// it collides with any of the standard classes.
- if (Type.GetType("System." + strClass) != null ||
- Type.GetType("System.ComponentModel." + strClass) != null ||
- Type.GetType("System.Management." + strClass) != null ||
- Type.GetType("System.Collections." + strClass) != null ||
- Type.GetType("System.Globalization." + strClass) != null )
+ if (Type.GetType("System." + strClass) != null ||
+ Type.GetType("System.ComponentModel." + strClass) != null ||
+ Type.GetType("System.Management." + strClass) != null ||
+ Type.GetType("System.Collections." + strClass) != null ||
+ Type.GetType("System.Globalization." + strClass) != null)
{
PublicNamesUsed.Add(strClass, strClass);
strClass = ResolveCollision(strClass, true);
}
- PrivateNamesUsed.Add ("GeneratedClassName", strClass);
+ PrivateNamesUsed.Add("GeneratedClassName", strClass);
PrivateNamesUsed.Add("GeneratedNamespace", strNs);
}
{
//Now add the import statements
cn = new CodeNamespace(PrivateNamesUsed["GeneratedNamespace"].ToString());
- cn.Imports.Add (new CodeNamespaceImport("System"));
- cn.Imports.Add (new CodeNamespaceImport("System.ComponentModel"));
- cn.Imports.Add (new CodeNamespaceImport("System.Management"));
+ cn.Imports.Add(new CodeNamespaceImport("System"));
+ cn.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
+ cn.Imports.Add(new CodeNamespaceImport("System.Management"));
cn.Imports.Add(new CodeNamespaceImport("System.Collections"));
cn.Imports.Add(new CodeNamespaceImport("System.Globalization"));
/// <param name="Comment"></param>
private void GeneratePublicReadOnlyProperty(string propName, string propType, object propValue, bool isLiteral, bool isBrowsable, string Comment)
{
- cmp = new CodeMemberProperty ();
+ cmp = new CodeMemberProperty();
cmp.Name = propName;
cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final;
cmp.Type = new CodeTypeReference(propType);
if (isLiteral == true)
{
- cmp.GetStatements.Add (new CodeMethodReturnStatement (new CodeSnippetExpression(propValue.ToString())));
+ cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression(propValue.ToString())));
}
else
{
- cmp.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression(propValue)));
+ cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(propValue)));
}
- cc.Members.Add (cmp);
- if (Comment != null && Comment.Length != 0 )
+ cc.Members.Add(cmp);
+ if (Comment != null && Comment.Length != 0)
{
cmp.Comments.Add(new CodeCommentStatement(Comment));
}
private CodeTypeDeclaration GenerateSystemPropertiesClass()
{
CodeTypeDeclaration SysPropsClass = new CodeTypeDeclaration(PublicNamesUsed["SystemPropertiesClass"].ToString());
- SysPropsClass.TypeAttributes =TypeAttributes.NestedPublic;
+ SysPropsClass.TypeAttributes = TypeAttributes.NestedPublic;
//First create the constructor
// public ManagementSystemProperties(ManagementObject obj)
SysPropsClass.Members.Add(cctor);
caa = new CodeAttributeArgument();
- caa.Value = new CodeTypeOfExpression (typeof(System.ComponentModel.ExpandableObjectConverter));
+ caa.Value = new CodeTypeOfExpression(typeof(System.ComponentModel.ExpandableObjectConverter));
cad = new CodeAttributeDeclaration();
cad.Name = PublicNamesUsed["TypeConverter"].ToString();
cad.Arguments.Add(caa);
SysPropsClass.CustomAttributes.Add(cad);
- char [] strPropTemp;
- char [] strPropName;
+ char[] strPropTemp;
+ char[] strPropName;
int i = 0;
foreach (PropertyData prop in classobj.SystemProperties)
{
- cmp = new CodeMemberProperty ();
+ cmp = new CodeMemberProperty();
//All properties are browsable by default.
caa = new CodeAttributeArgument();
caa.Value = new CodePrimitiveExpression(true);
//Now we will have to find the occurrence of the first character and trim all the characters before that
strPropTemp = prop.Name.ToCharArray();
- for (i=0; i < strPropTemp.Length; i++)
+ for (i = 0; i < strPropTemp.Length; i++)
{
if (char.IsLetterOrDigit(strPropTemp[i]) == true)
{
i = 0;
}
strPropName = new char[strPropTemp.Length - i];
- for (int j=i; j < strPropTemp.Length; j++)
+ for (int j = i; j < strPropTemp.Length; j++)
{
strPropName[j - i] = strPropTemp[j];
}
cie = new CodeIndexerExpression(
new CodeVariableReferenceExpression(PrivateNamesUsed["LateBoundObject"].ToString()),
- new CodeExpression[] {new CodePrimitiveExpression(prop.Name)});
+ new CodeExpression[] { new CodePrimitiveExpression(prop.Name) });
- cmp.GetStatements.Add (new CodeMethodReturnStatement (new CodeCastExpression(cmp.Type, cie)));
+ cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(cmp.Type, cie)));
SysPropsClass.Members.Add(cmp);
}
//private WmiObject _privObject
string IsValidPropName = string.Empty;
bool bDateIsTimeInterval = false;
- for (int i=0; i< PublicProperties.Count; i++)
+ for (int i = 0; i < PublicProperties.Count; i++)
{
bDateIsTimeInterval = false;
PropertyData prop = classobj.Properties[PublicProperties.GetKey(i).ToString()];
bWrite = true; //All properties are writeable by default
bStatic = false; //By default all properties are non static
- cmp = new CodeMemberProperty ();
+ cmp = new CodeMemberProperty();
cmp.Name = PublicProperties[prop.Name].ToString();
cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final;
cmp.Type = ConvertCIMType(prop.Type, prop.IsArray);
// Method for Is<PropertyName>Null property
IsValidPropName = "Is" + PublicProperties[prop.Name].ToString() + "Null";
- cmp2 = new CodeMemberProperty ();
+ cmp2 = new CodeMemberProperty();
cmp2.Name = IsValidPropName;
cmp2.Attributes = MemberAttributes.Public | MemberAttributes.Final;
cmp2.Type = new CodeTypeReference("System.Boolean");
cie = new CodeIndexerExpression(
new CodeVariableReferenceExpression(PrivateNamesUsed["CurrentObject"].ToString()),
- new CodeExpression[] {new CodePrimitiveExpression(prop.Name)});
+ new CodeExpression[] { new CodePrimitiveExpression(prop.Name) });
bool bNullable = false;
if (bRead == true)
{
- if (IsPropertyValueType(prop.Type) && prop.IsArray == false)
+ if (IsPropertyValueType(prop.Type) && prop.IsArray == false)
{
/*
new CodePrimitiveExpression(null));
- cis.TrueStatements.Add(new CodeMethodReturnStatement (new CodePrimitiveExpression(true) ));
- cis.FalseStatements.Add(new CodeMethodReturnStatement (new CodePrimitiveExpression(false) ));
- cmp2.GetStatements.Add (cis);
- cc.Members.Add (cmp2);
+ cis.TrueStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(true)));
+ cis.FalseStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(false)));
+ cmp2.GetStatements.Add(cis);
+ cc.Members.Add(cmp2);
// Adding TypeConverter Attribute
caa = new CodeAttributeArgument();
- caa.Value = new CodeTypeOfExpression (PrivateNamesUsed["ConverterClass"].ToString());
+ caa.Value = new CodeTypeOfExpression(PrivateNamesUsed["ConverterClass"].ToString());
cad = new CodeAttributeDeclaration();
cad.Name = PublicNamesUsed["TypeConverter"].ToString();
cad.Arguments.Add(caa);
{
if (prop.IsArray)
{
- cis.TrueStatements.Add(new CodeMethodReturnStatement (new CodePrimitiveExpression(null)));
+ cis.TrueStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
}
else
{
cmie.Method.TargetObject = new CodeTypeReferenceExpression("System.Convert");
cmie.Parameters.Add(new CodePrimitiveExpression(prop.NullEnumValue));
cmie.Method.MethodName = arrConvFuncName;
- cis.TrueStatements.Add(new CodeMethodReturnStatement (new CodeCastExpression(cmp.Type, cmie )));
+ cis.TrueStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(cmp.Type, cmie)));
}
}
else
cmie.Method.TargetObject = new CodeTypeReferenceExpression("System.Convert");
if (prop.IsArray)
{
- CodeExpression [] cInit = {cmie };
+ CodeExpression[] cInit = { cmie };
cis.TrueStatements.Add(new CodeMethodReturnStatement(
new CodeArrayCreateExpression(cmp.Type, cInit)));
else
{
// return (<EnumName>)System.Convert.<ConvertFuncName>(0);
- cis.TrueStatements.Add(new CodeMethodReturnStatement (cmie));
+ cis.TrueStatements.Add(new CodeMethodReturnStatement(cmie));
}
}
- cmp.GetStatements.Add (cis);
+ cmp.GetStatements.Add(cis);
}
/*
*/
cmm = new CodeMemberMethod();
cmm.Name = "ShouldSerialize" + PublicProperties[prop.Name].ToString();
- cmm.Attributes = MemberAttributes.Private | MemberAttributes.Final;
+ cmm.Attributes = MemberAttributes.Private | MemberAttributes.Final;
cmm.ReturnType = new CodeTypeReference("System.Boolean");
CodeConditionStatement cis2 = new CodeConditionStatement();
cmm.Statements.Add(cis2);
cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(false)));
- cc.Members.Add (cmm);
+ cc.Members.Add(cmm);
}
if (prop.Type == CimType.Reference)
cmie.Method.TargetObject = new CodeTypeReferenceExpression("System.Convert");
cmie.Parameters.Add(cie);
cmie.Method.MethodName = arrConvFuncName;
- cmp.GetStatements.Add (new CodeMethodReturnStatement (new CodeCastExpression(cmp.Type, cmie )));
+ cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(cmp.Type, cmie)));
}
}
else
{
- cmp.GetStatements.Add (new CodeMethodReturnStatement (new CodeCastExpression(cmp.Type, cie)));
+ cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(cmp.Type, cie)));
}
}
{
if (bNullable)
{
- cmm2 = new CodeMemberMethod ();
+ cmm2 = new CodeMemberMethod();
cmm2.Name = "Reset" + PublicProperties[prop.Name].ToString();
- cmm2.Attributes = MemberAttributes.Private | MemberAttributes.Final;
+ cmm2.Attributes = MemberAttributes.Private | MemberAttributes.Final;
cmm2.Statements.Add(new CodeAssignStatement(cie, new CodePrimitiveExpression(null)));
}
CodeBinaryOperatorType.ValueEquality,
new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("value"),
new CodePrimitiveExpression(0)));
- }
- else
- {
+ }
+ else
+ {
ccs.Condition = new CodeBinaryOperatorExpression(
new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(new CodeTypeReference(PublicProperties[prop.Name].ToString() + "Values")), "NULL_ENUM_VALUE"),
CodeBinaryOperatorType.ValueEquality,
new CodeSnippetExpression("value"));
- }
+ }
ccs.TrueStatements.Add(new CodeAssignStatement(cie, new CodePrimitiveExpression(null)));
ccs.FalseStatements.Add(new CodeAssignStatement(cie, new CodeSnippetExpression("value")));
cmp.SetStatements.Add(ccs);
writeValue = false;
}
}
- // check for ValueMap/Values and BitMap/BitValues pair and create
- // Enum Accordingly
+ // check for ValueMap/Values and BitMap/BitValues pair and create
+ // Enum Accordingly
else if (string.Equals(q.Name, "ValueMap", StringComparison.OrdinalIgnoreCase) && bMapsFailed == false)
{
try
{
if (q.Value != null)
{
- string [] strArray = (string [])q.Value;
- for (int i=0; i < strArray.Length; i++)
+ string[] strArray = (string[])q.Value;
+ for (int i = 0; i < strArray.Length; i++)
{
try
{
}
}
}
- // if the value is not a numerical, then we cannot construct a enum
+ // if the value is not a numerical, then we cannot construct a enum
catch (System.FormatException)
{
bMapsFailed = true;
ValueMap.Clear();
}
- catch (System.InvalidCastException )
+ catch (System.InvalidCastException)
{
// This exception may occur if the qualifier value is not an array as expected
ValueMap.Clear();
if (q.Value != null)
{
ArrayList arTemp = new ArrayList(5);
- string [] strArray = (string[])q.Value;
- for (int i=0; i < strArray.Length; i++)
+ string[] strArray = (string[])q.Value;
+ for (int i = 0; i < strArray.Length; i++)
{
if (strArray[i].Length == 0)
{
}
}
}
- catch (System.InvalidCastException )
+ catch (System.InvalidCastException)
{
// This exception may occur if the qualifier value is not an array as expected
Values.Clear();
{
if (q.Value != null)
{
- string [] strArray = (string [])q.Value;
- for (int i=0; i < strArray.Length; i++)
+ string[] strArray = (string[])q.Value;
+ for (int i = 0; i < strArray.Length; i++)
{
BitMap.Add(ConvertBitMapValueToInt32(strArray[i]));
}
}
}
}
- // if the value is not a numerical, then we cannot construct a enum
+ // if the value is not a numerical, then we cannot construct a enum
catch (System.FormatException)
{
BitMap.Clear();
bMapsFailed = true;
}
- catch (System.InvalidCastException )
+ catch (System.InvalidCastException)
{
// This exception may occur if the qualifier value is not an array as expected
BitMap.Clear();
if (q.Value != null)
{
ArrayList arTemp = new ArrayList(5);
- string [] strArray = (string [])q.Value;
- for (int i=0; i < strArray.Length; i++)
+ string[] strArray = (string[])q.Value;
+ for (int i = 0; i < strArray.Length; i++)
{
if (strArray[i].Length == 0)
{
}
}
}
- catch (System.InvalidCastException )
+ catch (System.InvalidCastException)
{
// This exception may occur if the qualifier value is not an array as expected
BitValues.Clear();
// Property is not writeable only if "read" qualifier is present and its value is "true"
// Also, for dynamic classes, absence of "write" qualifier means that the property is read-only.
- if ((!bDynamicClass && !hasWrite )||
- (!bDynamicClass && hasWrite && writeValue)||
- (bDynamicClass && hasWrite && writeValue) )
+ if ((!bDynamicClass && !hasWrite) ||
+ (!bDynamicClass && hasWrite && writeValue) ||
+ (bDynamicClass && hasWrite && writeValue))
{
bWrite = true;
}
{
cmf.InitExpression = new CodePrimitiveExpression(ValueMap[i]);
long test = System.Convert.ToInt64(ValueMap[i], (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(ulong)));
- if (test > maxValue) maxValue=test;
+ if (test > maxValue) maxValue = test;
if (bZeroFieldInEnum == false)
{
else
{
cmf.InitExpression = new CodePrimitiveExpression(i);
- if (i > maxValue) maxValue=i;
+ if (i > maxValue) maxValue = i;
}
EnumObj.Members.Add(cmf);
}
// If there is no 0 valued field in enum, just add a invalid for enum
// This is just to show in property browser
- if ((bNullable == true) && (bZeroFieldInEnum == false))
+ if ((bNullable == true) && (bZeroFieldInEnum == false))
{
// use the 0 enum position for NULL
cmf = new CodeMemberField();
EnumObj.Members.Add(cmf);
prop.NullEnumValue = 0;
}
- else if ((bNullable == true) && (bZeroFieldInEnum == true))
+ else if ((bNullable == true) && (bZeroFieldInEnum == true))
{
// must create an entry for NULL that is not zero and is not used
// use the another unused enum position for NULL
- cmf = new CodeMemberField ();
+ cmf = new CodeMemberField();
cmf.Name = "NULL_ENUM_VALUE";
- cmf.InitExpression = new CodePrimitiveExpression((int)(maxValue+1));
+ cmf.InitExpression = new CodePrimitiveExpression((int)(maxValue + 1));
EnumObj.Members.Add(cmf);
- prop.NullEnumValue = (int)(maxValue+1);
+ prop.NullEnumValue = (int)(maxValue + 1);
}
else if ((bNullable == false) && (bZeroFieldInEnum == false))
{
// add an entry for 0 valued enum
- cmf = new CodeMemberField ();
+ cmf = new CodeMemberField();
cmf.Name = "INVALID_ENUM_VALUE";
cmf.InitExpression = new CodePrimitiveExpression(0);
EnumObj.Members.Add(cmf);
{
cmf.InitExpression = new CodePrimitiveExpression(BitMap[i]);
long test = System.Convert.ToInt64(BitMap[i], (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(ulong)));
- if (test > maxBitValue) maxBitValue=test;
+ if (test > maxBitValue) maxBitValue = test;
}
else
{
cmf.InitExpression = new CodePrimitiveExpression(bitValue);
- if (bitValue > maxBitValue) maxBitValue=bitValue;
+ if (bitValue > maxBitValue) maxBitValue = bitValue;
// Now shift 1 more bit so that we can put it for the
// next element in the enum
if (bZeroFieldInEnum == false)
{
- if ( (System.Convert.ToInt64(BitMap[i], (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(ulong))) == 0) )
+ if ((System.Convert.ToInt64(BitMap[i], (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(ulong))) == 0))
{
bZeroFieldInEnum = true;
}
// If there is no 0 valued field in enum, just add a invalid for enum
// This is just to show in property browser
- if ((bNullable == true) && (bZeroFieldInEnum == false))
+ if ((bNullable == true) && (bZeroFieldInEnum == false))
{
// use the 0 enum position for NULL
- cmf = new CodeMemberField ();
+ cmf = new CodeMemberField();
cmf.Name = "NULL_ENUM_VALUE";
cmf.InitExpression = new CodePrimitiveExpression(0);
EnumObj.Members.Add(cmf);
prop.NullEnumValue = 0;
}
- else if ((bNullable == true) && (bZeroFieldInEnum == true))
+ else if ((bNullable == true) && (bZeroFieldInEnum == true))
{
// must create an entry for NULL that is not zero and is not used
// use the another unused enum position for NULL
- cmf = new CodeMemberField ();
+ cmf = new CodeMemberField();
cmf.Name = "NULL_ENUM_VALUE";
if (BitValues.Count > 30)
{
- maxBitValue = maxBitValue + 1;
+ maxBitValue = maxBitValue + 1;
}
else
{
}
cmf.InitExpression = new CodePrimitiveExpression((int)(maxBitValue));
EnumObj.Members.Add(cmf);
- // just add one - we won't preserve the bit shifting but this won't be used in CIM anyway.
- prop.NullEnumValue = (int)(maxBitValue);
+ // just add one - we won't preserve the bit shifting but this won't be used in CIM anyway.
+ prop.NullEnumValue = (int)(maxBitValue);
}
else if ((bNullable == false) && (bZeroFieldInEnum == false))
{
// add an entry for 0 valued enum
- cmf = new CodeMemberField ();
+ cmf = new CodeMemberField();
cmf.Name = "INVALID_ENUM_VALUE";
cmf.InitExpression = new CodePrimitiveExpression(0);
EnumObj.Members.Add(cmf);
cmm.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final;
cmm.ReturnType = new CodeTypeReference("System.String");
- for (int i=0; i < arrKeys.Count; i++)
+ for (int i = 0; i < arrKeys.Count; i++)
{
strType = ((CodeTypeReference)arrKeyType[i]).BaseType;
cmm.Parameters.Add(new CodeParameterDeclarationExpression(strType,
- "key"+arrKeys[i].ToString()));
+ "key" + arrKeys[i].ToString()));
}
string strPath = OriginalNamespace + ":" + OriginalClassName;
cmm.Statements.Add(new CodeVariableDeclarationStatement("System.String", strPathObject, new CodePrimitiveExpression(strPath)));
CodeMethodInvokeExpression cmietoAdd;
- for (int i=0; i < arrKeys.Count; i++)
+ for (int i = 0; i < arrKeys.Count; i++)
{
if (((CodeTypeReference)arrKeyType[i]).BaseType == "System.String")
{
- CodeMethodInvokeExpression cmie1 = GenerateConcatStrings(new CodeVariableReferenceExpression("key"+arrKeys[i]), new CodePrimitiveExpression("\""));
+ CodeMethodInvokeExpression cmie1 = GenerateConcatStrings(new CodeVariableReferenceExpression("key" + arrKeys[i]), new CodePrimitiveExpression("\""));
CodeMethodInvokeExpression cmie2 = GenerateConcatStrings(new CodePrimitiveExpression("\""), cmie1);
- CodeMethodInvokeExpression cmie3 = GenerateConcatStrings(new CodePrimitiveExpression(((i==0)?("."+arrKeys[i]+"="):(","+arrKeys[i]+"="))), cmie2);
+ CodeMethodInvokeExpression cmie3 = GenerateConcatStrings(new CodePrimitiveExpression(((i == 0) ? ("." + arrKeys[i] + "=") : ("," + arrKeys[i] + "="))), cmie2);
cmietoAdd = GenerateConcatStrings(new CodeVariableReferenceExpression(strPathObject), cmie3);
else
{
cmie = new CodeMethodInvokeExpression();
- cmie.Method.TargetObject = new CodeCastExpression(new CodeTypeReference(((CodeTypeReference)arrKeyType[i]).BaseType + " "), new CodeVariableReferenceExpression("key"+arrKeys[i]));
+ cmie.Method.TargetObject = new CodeCastExpression(new CodeTypeReference(((CodeTypeReference)arrKeyType[i]).BaseType + " "), new CodeVariableReferenceExpression("key" + arrKeys[i]));
cmie.Method.MethodName = "ToString";
- CodeMethodInvokeExpression cmie1 = GenerateConcatStrings(new CodePrimitiveExpression(((i==0)?("."+arrKeys[i]+"="):(","+arrKeys[i]+"="))), cmie);
+ CodeMethodInvokeExpression cmie1 = GenerateConcatStrings(new CodePrimitiveExpression(((i == 0) ? ("." + arrKeys[i] + "=") : ("," + arrKeys[i] + "="))), cmie);
cmietoAdd = GenerateConcatStrings(new CodeVariableReferenceExpression(strPathObject), cmie1);
cmieInit.Method.MethodName = PrivateNamesUsed["InitialObjectFunc"].ToString();
cmieInit.Method.TargetObject = new CodeThisReferenceExpression();
- for (int i=0; i < arrKeys.Count; i++)
+ for (int i = 0; i < arrKeys.Count; i++)
{
cpde = new CodeParameterDeclarationExpression();
cpde.Type = new CodeTypeReference(((CodeTypeReference)arrKeyType[i]).BaseType);
- cpde.Name = "key"+arrKeys[i].ToString();
+ cpde.Name = "key" + arrKeys[i].ToString();
cctor.Parameters.Add(cpde);
}
cmie.Method.TargetObject = new CodeTypeReferenceExpression(PrivateNamesUsed["GeneratedClassName"].ToString());
cmie.Method.MethodName = PublicNamesUsed["ConstructPathFunction"].ToString();
- for (int i=0; i < arrKeys.Count; i++)
+ for (int i = 0; i < arrKeys.Count; i++)
{
- cmie.Parameters.Add(new CodeVariableReferenceExpression("key"+arrKeys[i]));
+ cmie.Parameters.Add(new CodeVariableReferenceExpression("key" + arrKeys[i]));
}
coce = new CodeObjectCreateExpression();
if (arrKeyType.Count > 0)
{
- for (int i=0; i < arrKeys.Count; i++)
+ for (int i = 0; i < arrKeys.Count; i++)
{
cpde = new CodeParameterDeclarationExpression();
cpde.Type = new CodeTypeReference(((CodeTypeReference)arrKeyType[i]).BaseType);
- cpde.Name = "key"+arrKeys[i].ToString();
+ cpde.Name = "key" + arrKeys[i].ToString();
cctor.Parameters.Add(cpde);
}
cmie.Method.TargetObject = new CodeTypeReferenceExpression(PrivateNamesUsed["GeneratedClassName"].ToString());
cmie.Method.MethodName = PublicNamesUsed["ConstructPathFunction"].ToString();
- for (int i=0; i < arrKeys.Count; i++)
+ for (int i = 0; i < arrKeys.Count; i++)
{
- cmie.Parameters.Add(new CodeVariableReferenceExpression("key"+arrKeys[i]));
+ cmie.Parameters.Add(new CodeVariableReferenceExpression("key" + arrKeys[i]));
}
coce = new CodeObjectCreateExpression();
cmieInit.Parameters.Add(new CodeVariableReferenceExpression(PrivateNamesUsed["ScopeParam"].ToString()));
cmie = new CodeMethodInvokeExpression();
- cmie.Method.TargetObject =new CodeTypeReferenceExpression(PrivateNamesUsed["GeneratedClassName"].ToString());
+ cmie.Method.TargetObject = new CodeTypeReferenceExpression(PrivateNamesUsed["GeneratedClassName"].ToString());
cmie.Method.MethodName = PublicNamesUsed["ConstructPathFunction"].ToString();
coce = new CodeObjectCreateExpression();
{
string strInParams = "inParams";
string strOutParams = "outParams";
- string strClassObj = "classObj";
- bool bStatic = false;
- bool bPrivileges = false;
+ string strClassObj = "classObj";
+ bool bStatic = false;
+ bool bPrivileges = false;
CodePropertyReferenceExpression cprePriveleges = null;
CimType cimRetType = CimType.SInt8; // Initialized to remove warnings
CodeTypeReference retRefType = null;
ArrayList outParamsName = new ArrayList(5);
ArrayList inoutParams = new ArrayList(5);
ArrayList inoutParamsType = new ArrayList(5);
- for (int k=0; k< PublicMethods.Count; k++)
+ for (int k = 0; k < PublicMethods.Count; k++)
{
bStatic = false;
cpde.Direction = FieldDirection.In;
- if ( prop.Type == CimType.DateTime)
+ if (prop.Type == CimType.DateTime)
{
CodeTypeReference dateType = cpde.Type;
// Check if it is Time interval and if so change the type to Time Interval
}
//Find out whether it is a in/out Parameter
- for (int i=0; i < outParamsName.Count; i++)
+ for (int i = 0; i < outParamsName.Count; i++)
{
if (string.Equals(prop.Name, outParamsName[i].ToString(), StringComparison.OrdinalIgnoreCase))
{
}
bInOut = false;
- for (int i=0; i < inoutParams.Count; i++)
+ for (int i = 0; i < inoutParams.Count; i++)
{
if (string.Equals(prop.Name, inoutParams[i].ToString(), StringComparison.OrdinalIgnoreCase))
{
bRetVal = true;
cimRetType = prop.Type;
- if ( prop.Type == CimType.DateTime)
+ if (prop.Type == CimType.DateTime)
{
CodeTypeReference dateType = cmm.ReturnType;
// Check if it is Time interval and if so change the type to Time Interval
cpde.Direction = FieldDirection.Out;
cmm.Parameters.Add(cpde);
- if ( prop.Type == CimType.DateTime)
+ if (prop.Type == CimType.DateTime)
{
CodeTypeReference dateType = cpde.Type;
// Check if it is Time interval and if so change the type to Time Interval
//Now for each in/out params generate the statement
// <inoutParam> = outParams.Properties["<inoutParam>"];
- for (int i=0; i < inoutParams.Count; i++)
+ for (int i = 0; i < inoutParams.Count; i++)
{
cpre = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(strOutParams), "Properties");
cie = new CodeIndexerExpression(cpre, new CodePrimitiveExpression(inoutParams[i].ToString()));
cis.FalseStatements.Add(new CodeMethodReturnStatement(cmie));
}
- // if the return type is array, then just do type casting before returning
+ // if the return type is array, then just do type casting before returning
else
{
cis.TrueStatements.Add(new CodeMethodReturnStatement(
string contextObject = "context";
string TypeDstObject = "destinationType";
string ValueVar = "value";
- string CultureInfoClass = "System.Globalization.CultureInfo";
+ string CultureInfoClass = "System.Globalization.CultureInfo";
string CultureInfoVar = "culture";
- string IDictionary = "System.Collections.IDictionary";
- string DictVar = "dictionary";
- string propColl = "PropertyDescriptorCollection";
- string AttributeVar = "attributeVar";
+ string IDictionary = "System.Collections.IDictionary";
+ string DictVar = "dictionary";
+ string propColl = "PropertyDescriptorCollection";
+ string AttributeVar = "attributeVar";
string baseTypeParam = "inBaseType";
string baseTypeMemberVariable = "baseConverter";
string typeMemberVariable = "baseType";
string TypeDescriptorClass = "TypeDescriptor";
- string srcType = "srcType";
+ string srcType = "srcType";
/*
*/
cmm = new CodeMemberMethod();
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
cmm.Name = "CanConvertFrom";
cmm.ReturnType = new CodeTypeReference("System.Boolean");
*/
cmm = new CodeMemberMethod();
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
cmm.Name = "CanConvertTo";
cmm.ReturnType = new CodeTypeReference("System.Boolean");
*/
cmm = new CodeMemberMethod();
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
cmm.Name = "ConvertFrom";
cmm.ReturnType = new CodeTypeReference("System.Object");
*/
cmm = new CodeMemberMethod();
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
cmm.ReturnType = new CodeTypeReference("System.Object");
cmm.Name = "CreateInstance";
*/
cmm = new CodeMemberMethod();
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
cmm.Name = "GetCreateInstanceSupported";
cmm.ReturnType = new CodeTypeReference("System.Boolean");
*/
cmm = new CodeMemberMethod();
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
cmm.Name = "GetProperties";
cmm.Parameters.Add(new CodeParameterDeclarationExpression(TypeDescriptorContextClass, contextObject));
cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), ValueVar));
*/
cmm = new CodeMemberMethod();
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
cmm.Name = "GetPropertiesSupported";
cmm.Parameters.Add(new CodeParameterDeclarationExpression(TypeDescriptorContextClass, contextObject));
cmm.ReturnType = new CodeTypeReference("System.Boolean");
*/
cmm = new CodeMemberMethod();
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
cmm.Name = "GetStandardValues";
cmm.Parameters.Add(new CodeParameterDeclarationExpression(TypeDescriptorContextClass, contextObject));
cmm.ReturnType = new CodeTypeReference("System.ComponentModel.TypeConverter.StandardValuesCollection");
*/
cmm = new CodeMemberMethod();
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
cmm.Name = "GetStandardValuesExclusive";
cmm.Parameters.Add(new CodeParameterDeclarationExpression(TypeDescriptorContextClass, contextObject));
cmm.ReturnType = new CodeTypeReference("System.Boolean");
*/
cmm = new CodeMemberMethod();
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
cmm.Name = "GetStandardValuesSupported";
cmm.Parameters.Add(new CodeParameterDeclarationExpression(TypeDescriptorContextClass, contextObject));
cmm.ReturnType = new CodeTypeReference("System.Boolean");
// make the member method
cmm = new CodeMemberMethod();
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override | MemberAttributes.Overloaded;
cmm.Name = "ConvertTo";
// add the 3 parameters
cmm.Parameters.Add(new CodeParameterDeclarationExpression(TypeDescriptorContextClass, contextObject));
*/
CodeBinaryOperatorExpression cboe2 = new CodeBinaryOperatorExpression();
- cboe2.Left = new CodeMethodInvokeExpression(
+ cboe2.Left = new CodeMethodInvokeExpression(
new CodeVariableReferenceExpression("value"), "GetType");
cboe2.Right = new CodeVariableReferenceExpression("destinationType");
cboe2.Operator = CodeBinaryOperatorType.IdentityEquality;
// if ( (baseType == typeof(System.Boolean)) && (baseType.BaseType == typeof(System.ValueType)) )
cis = new CodeConditionStatement();
cboe1 = new CodeBinaryOperatorExpression();
- cboe1.Left = new CodeVariableReferenceExpression(typeMemberVariable);
- cboe1.Right = new CodeTypeOfExpression (PublicNamesUsed["Boolean"].ToString());
+ cboe1.Left = new CodeVariableReferenceExpression(typeMemberVariable);
+ cboe1.Right = new CodeTypeOfExpression(PublicNamesUsed["Boolean"].ToString());
cboe1.Operator = CodeBinaryOperatorType.IdentityEquality;
cboe2 = new CodeBinaryOperatorExpression();
new CodeVariableReferenceExpression(typeMemberVariable),
"BaseType");
- cboe2.Right = new CodeTypeOfExpression (PublicNamesUsed["ValueType"].ToString());
+ cboe2.Right = new CodeTypeOfExpression(PublicNamesUsed["ValueType"].ToString());
cboe2.Operator = CodeBinaryOperatorType.IdentityEquality;
cboe3 = new CodeBinaryOperatorExpression();
ccc.BaseTypes.Add("System.Object");
ccc.BaseTypes.Add("ICollection");
- ccc.TypeAttributes =TypeAttributes.NestedPublic;
+ ccc.TypeAttributes = TypeAttributes.NestedPublic;
cf = new CodeMemberField();
cf.Name = strObjectCollection;
//public class ServiceEnumerator : IEnumerator
ecc = new CodeTypeDeclaration(PrivateNamesUsed["EnumeratorClass"].ToString());
- ecc.TypeAttributes =TypeAttributes.NestedPublic;
+ ecc.TypeAttributes = TypeAttributes.NestedPublic;
ecc.BaseTypes.Add("System.Object");
ecc.BaseTypes.Add("System.Collections.IEnumerator");
cf = new CodeMemberField();
cf.Name = strObjectEnumerator;
cf.Attributes = MemberAttributes.Private | MemberAttributes.Final;
- cf.Type = new CodeTypeReference(strManagementObjectCollectionType+"."+
+ cf.Type = new CodeTypeReference(strManagementObjectCollectionType + "." +
strManagementObjectEnumeratorType);
ecc.Members.Add(cf);
new CodeVariableReferenceExpression(strObjectEnumerator),
"Reset"
);
- cmm.Statements.Add(new CodeExpressionStatement (cmie));
+ cmm.Statements.Add(new CodeExpressionStatement(cmie));
ecc.Members.Add(cmm);
ccc.Members.Add(ecc);
private int IsContainedIn(string strToFind, ref SortedList sortedList)
{
int nIndex = -1;
- for (int i=0; i < sortedList.Count; i++)
+ for (int i = 0; i < sortedList.Count; i++)
{
if (string.Equals(sortedList.GetByIndex(i).ToString(), strToFind, StringComparison.OrdinalIgnoreCase))
{
switch (cType)
{
case CimType.SInt8:
- {
- strType = "System.SByte";
- break;
- }
+ {
+ strType = "System.SByte";
+ break;
+ }
case CimType.UInt8:
- {
- strType = "System.Byte";
- break;
- }
+ {
+ strType = "System.Byte";
+ break;
+ }
case CimType.SInt16:
- {
- strType = "System.Int16";
- break;
- }
- case CimType.UInt16:
- {
- if (bUnsignedSupported == false)
{
strType = "System.Int16";
+ break;
}
- else
+ case CimType.UInt16:
{
- strType = "System.UInt16";
+ if (bUnsignedSupported == false)
+ {
+ strType = "System.Int16";
+ }
+ else
+ {
+ strType = "System.UInt16";
+ }
+ break;
}
- break;
- }
case CimType.SInt32:
- {
- strType = "System.Int32";
- break;
- }
- case CimType.UInt32:
- {
- if (bUnsignedSupported == false)
{
strType = "System.Int32";
+ break;
}
- else
+ case CimType.UInt32:
{
- strType = "System.UInt32";
+ if (bUnsignedSupported == false)
+ {
+ strType = "System.Int32";
+ }
+ else
+ {
+ strType = "System.UInt32";
+ }
+ break;
}
- break;
- }
case CimType.SInt64:
- {
- strType = "System.Int64";
- break;
- }
- case CimType.UInt64:
- {
- if (bUnsignedSupported == false)
{
strType = "System.Int64";
+ break;
}
- else
+ case CimType.UInt64:
{
- strType = "System.UInt64";
+ if (bUnsignedSupported == false)
+ {
+ strType = "System.Int64";
+ }
+ else
+ {
+ strType = "System.UInt64";
+ }
+ break;
}
- break;
- }
case CimType.Real32:
- {
- strType = "System.Single";
- break;
- }
+ {
+ strType = "System.Single";
+ break;
+ }
case CimType.Real64:
- {
- strType = "System.Double";
- break;
- }
+ {
+ strType = "System.Double";
+ break;
+ }
case CimType.Boolean:
- {
- strType = "System.Boolean";
- break;
- }
+ {
+ strType = "System.Boolean";
+ break;
+ }
case CimType.String:
- {
- strType = "System.String";
- break;
- }
+ {
+ strType = "System.String";
+ break;
+ }
case CimType.DateTime:
- {
- strType = "System.DateTime";
- break;
- }
+ {
+ strType = "System.DateTime";
+ break;
+ }
case CimType.Reference:
- {
- strType = PublicNamesUsed["PathClass"].ToString();
- break;
- }
+ {
+ strType = PublicNamesUsed["PathClass"].ToString();
+ break;
+ }
case CimType.Char16:
- {
- strType = "System.Char";
- break;
- }
+ {
+ strType = "System.Char";
+ break;
+ }
case CimType.Object:
default:
strType = PublicNamesUsed["BaseObjClass"].ToString();
break;
}
- if (isArray )
+ if (isArray)
{
return new CodeTypeReference(strType, 1);
}
case CimType.SInt8:
case CimType.SInt16:
case CimType.SInt32:
- {
- retVal = true;
- break;
- }
+ {
+ retVal = true;
+ break;
+ }
case CimType.SInt64:
case CimType.UInt64:
case CimType.Real32:
string strRet = string.Empty;
string strToReplace = "_";
string strToAdd = string.Empty;
- bool bAdd = true;
+ bool bAdd = true;
if (str.Length == 0)
{
return string.Copy("");
strToAdd = "l";
}
- for (int i=0; i < str.Length; i++)
+ for (int i = 0; i < str.Length; i++)
{
bAdd = true;
if (char.IsLetterOrDigit(arrString[i]) == false)
private void ResolveEnumNameValues(ArrayList arrIn, ref ArrayList arrayOut)
{
arrayOut.Clear();
- int nCurIndex = 0;
+ int nCurIndex = 0;
string strToAdd = string.Empty;
IFormatProvider formatProv = (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int));
- for ( int i = 0; i < arrIn.Count; i++)
+ for (int i = 0; i < arrIn.Count; i++)
{
strToAdd = arrIn[i].ToString();
strToAdd = ResolveCollision(strToAdd, true);
/// </summary>
private static bool IsContainedInArray(string strToFind, ArrayList arrToSearch)
{
- for (int i=0; i < arrToSearch.Count; i++)
+ for (int i = 0; i < arrToSearch.Count; i++)
{
if (string.Equals(arrToSearch[i].ToString(), strToFind, StringComparison.OrdinalIgnoreCase))
{
case CodeLanguage.CSharp:
strProvider = "C#.";
- cp= new CSharpCodeProvider();
+ cp = new CSharpCodeProvider();
break;
case CodeLanguage.VJSharp:
if (asm != null)
{
codeProvType = asm.GetType("Microsoft.VJSharp.VJSharpCodeProvider");
- if ( codeProvType != null)
+ if (codeProvType != null)
{
cp = (System.CodeDom.Compiler.CodeDomProvider)Activator.CreateInstance(codeProvType);
bSucceeded = true;
if (asm != null)
{
codeProvType = asm.GetType("Microsoft.VisualC.CppCodeProvider");
- if ( codeProvType != null)
+ if (codeProvType != null)
{
cp = (System.CodeDom.Compiler.CodeDomProvider)Activator.CreateInstance(codeProvType);
bSucceeded = true;
}
catch
{
- throw new ArgumentOutOfRangeException(SR.Format(SR.UnableToCreateCodeGeneratorException, strProvider ));
+ throw new ArgumentOutOfRangeException(SR.Format(SR.UnableToCreateCodeGeneratorException, strProvider));
}
if (bSucceeded == true)
break;
case CimType.UInt32:
- {
- if (bUnsignedSupported == false)
{
- retFunctionName = "ToInt32";
- }
- else
- {
- retFunctionName = "ToUInt32";
+ if (bUnsignedSupported == false)
+ {
+ retFunctionName = "ToInt32";
+ }
+ else
+ {
+ retFunctionName = "ToUInt32";
+ }
+ break;
}
- break;
- }
case CimType.SInt64:
- {
- retFunctionName = "ToInt64";
- break;
- }
- case CimType.UInt64:
- {
- if (bUnsignedSupported == false)
{
retFunctionName = "ToInt64";
+ break;
}
- else
+ case CimType.UInt64:
{
- retFunctionName = "ToUInt64";
+ if (bUnsignedSupported == false)
+ {
+ retFunctionName = "ToInt64";
+ }
+ else
+ {
+ retFunctionName = "ToUInt64";
+ }
+ break;
}
- break;
- }
case CimType.Real32:
- {
- retFunctionName = "ToSingle";
- break;
- }
+ {
+ retFunctionName = "ToSingle";
+ break;
+ }
case CimType.Real64:
- {
- retFunctionName = "ToDouble";
- break;
- }
+ {
+ retFunctionName = "ToDouble";
+ break;
+ }
case CimType.Boolean:
- {
- retFunctionName = "ToBoolean";
- break;
- }
+ {
+ retFunctionName = "ToBoolean";
+ break;
+ }
case CimType.Char16:
- {
- retFunctionName = "ToChar";
- break;
- }
+ {
+ retFunctionName = "ToChar";
+ break;
+ }
case CimType.String:
- {
- retFunctionName = "ToString";
- break;
- }
+ {
+ retFunctionName = "ToString";
+ break;
+ }
}
return retFunctionName;
/// Gets the dynamic qualifier on the class to find if the
/// class is a dynamic class
/// </summary>
- private bool IsDynamicClass()
+ private bool IsDynamicClass()
{
bool ret = false;
try
private void GenerateClassNameProperty()
{
string strRetVar = "strRet";
- cmp = new CodeMemberProperty ();
+ cmp = new CodeMemberProperty();
cmp.Name = PublicNamesUsed["ClassNameProperty"].ToString();
cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final;
cmp.Type = new CodeTypeReference("System.String");
cad.Arguments.Add(caa);
cmp.CustomAttributes.Add(cad);
- cmp.GetStatements.Add (new CodeVariableDeclarationStatement("System.String", strRetVar,
+ cmp.GetStatements.Add(new CodeVariableDeclarationStatement("System.String", strRetVar,
new CodeVariableReferenceExpression(PrivateNamesUsed["CreationClassName"].ToString())));
cmp.GetStatements.Add(cis);
- cmp.GetStatements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression(strRetVar)));
- cc.Members.Add (cmp);
+ cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(strRetVar)));
+ cc.Members.Add(cmp);
}
/// <summary>
string strPathParam = "path";
string strGetOptions = "OptionsParam";
- cmm = new CodeMemberMethod ();
+ cmm = new CodeMemberMethod();
cmm.Name = PrivateNamesUsed["ClassNameCheckFunc"].ToString();
cmm.Attributes = MemberAttributes.Private | MemberAttributes.Final;
cmm.ReturnType = new CodeTypeReference("System.Boolean");
// Call this function to generate the first overload of this function
GenerateIfClassvalidFuncWithAllParams();
- string strTempObj = "theObj";
- string strnCtr = "count";
+ string strTempObj = "theObj";
+ string strnCtr = "count";
string strDerivation = "parentClasses";
- cmm = new CodeMemberMethod ();
+ cmm = new CodeMemberMethod();
cmm.Name = PrivateNamesUsed["ClassNameCheckFunc"].ToString();
cmm.Attributes = MemberAttributes.Private | MemberAttributes.Final;
cmm.ReturnType = new CodeTypeReference("System.Boolean");
if (varToAssign == null)
{
- cis1.TrueStatements.Add (new CodeMethodReturnStatement(CreateObjectForProperty(strType, cmie)));
+ cis1.TrueStatements.Add(new CodeMethodReturnStatement(CreateObjectForProperty(strType, cmie)));
statColl.Add(cis1);
- statColl.Add (new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
+ statColl.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
}
else
{
// Assign null to variable
statColl.Add(new CodeAssignStatement(varToAssign, new CodePrimitiveExpression(null)));
- cis1.TrueStatements.Add (new CodeAssignStatement(varToAssign, CreateObjectForProperty(strType, cmie)));
+ cis1.TrueStatements.Add(new CodeAssignStatement(varToAssign, CreateObjectForProperty(strType, cmie)));
statColl.Add(cis1);
}
}
cmie2.Method.MethodName = "ToString";
cmie2.Method.TargetObject = cmie1;
- cfls.Statements.Add( new CodeAssignStatement(new CodeIndexerExpression(new CodeVariableReferenceExpression(strArray),
+ cfls.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeVariableReferenceExpression(strArray),
new CodeVariableReferenceExpression(strnCtr)), CreateObjectForProperty(strType, cmie2)));
cis1.TrueStatements.Add(cfls);
if (varToAssign == null)
{
cis1.TrueStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(strArray)));
- statColl.Add (cis1);
+ statColl.Add(cis1);
statColl.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
}
else
// Assign null to variable
statColl.Add(new CodeAssignStatement(varToAssign, new CodePrimitiveExpression(null)));
cis1.TrueStatements.Add(new CodeAssignStatement(varToAssign, new CodeVariableReferenceExpression(strArray)));
- statColl.Add (cis1);
+ statColl.Add(cis1);
}
}
cmie1.Parameters.Add(new CodeVariableReferenceExpression(strnCtr));
- cfls.Statements.Add( new CodeAssignStatement(new CodeIndexerExpression(new CodeVariableReferenceExpression(strArray),
+ cfls.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeVariableReferenceExpression(strArray),
new CodeVariableReferenceExpression(strnCtr)), ConvertPropertyToString(strType, cmie1)));
cis1.TrueStatements.Add(cfls);
cis1.TrueStatements.Add(new CodeAssignStatement(prop, new CodeVariableReferenceExpression(strArray)));
cis1.FalseStatements.Add(new CodeAssignStatement(prop, new CodePrimitiveExpression(null)));
- statColl.Add (cis1);
+ statColl.Add(cis1);
}
}
{
switch (strType)
{
- case "System.DateTime" :
+ case "System.DateTime":
if (param == null)
{
return new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.DateTime"), "MinValue");
return cmie;
}
- case "System.TimeSpan" :
+ case "System.TimeSpan":
if (param == null)
{
coce = new CodeObjectCreateExpression();
{
switch (strType)
{
- case "System.DateTime" :
+ case "System.DateTime":
CodeMethodInvokeExpression cmie1 = new CodeMethodInvokeExpression();
cmie1.Parameters.Add(new CodeCastExpression(new CodeTypeReference("System.DateTime"), beginingExpression));
cmie1.Method.MethodName = PrivateNamesUsed["ToDMTFDateTimeMethod"].ToString();
return cmie1;
- case "System.TimeSpan" :
+ case "System.TimeSpan":
CodeMethodInvokeExpression cmie2 = new CodeMethodInvokeExpression();
cmie2.Parameters.Add(new CodeCastExpression(new CodeTypeReference("System.TimeSpan"), beginingExpression));
return cmie2;
case "System.Management.ManagementPath":
- return new CodePropertyReferenceExpression(new CodeCastExpression(
+ return new CodePropertyReferenceExpression(new CodeCastExpression(
new CodeTypeReference(PublicNamesUsed["PathClass"].ToString()),
beginingExpression), PublicNamesUsed["PathProperty"].ToString());
cmie2.Method.MethodName = arrConvFuncName;
cfls.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeVariableReferenceExpression(ArrToRet),
new CodeVariableReferenceExpression(strnCtr)),
- new CodeCastExpression(new CodeTypeReference(strEnumName), cmie2 )));
+ new CodeCastExpression(new CodeTypeReference(strEnumName), cmie2)));
cmProp.GetStatements.Add(cfls);
// is "interval" then the returned CodeTypeReference is of type System.TimeSpan
// otherwise the returned type will be System.DateTime.
// This functions is called only for cimtype.DateTime type properties
- private bool GetDateTimeType(PropertyData prop, ref CodeTypeReference codeType )
+ private bool GetDateTimeType(PropertyData prop, ref CodeTypeReference codeType)
{
bool isTimeInterval = false;
codeType = null;
}
else
{
- codeType = new CodeTypeReference("System.DateTime");
+ codeType = new CodeTypeReference("System.DateTime");
}
try
}
else
{
- codeType = new CodeTypeReference("System.TimeSpan");
+ codeType = new CodeTypeReference("System.TimeSpan");
}
}
private void AddToDateTimeFunction()
{
string dmtfParam = "dmtfDate";
- string year = "year";
+ string year = "year";
string month = "month";
string day = "day";
string hour = "hour";
cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"), year, new CodePropertyReferenceExpression(cvreInitializer, "Year")));
//Int32 month = initializer.Month;
- cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"), month, new CodePropertyReferenceExpression(cvreInitializer, "Month")));
+ cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"), month, new CodePropertyReferenceExpression(cvreInitializer, "Month")));
//Int32 day = initializer.Day;
cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"), day, new CodePropertyReferenceExpression(cvreInitializer, "Day")));
}
*/
- CodeMethodReferenceExpression cmre = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(dmtf), "Substring");
+ CodeMethodReferenceExpression cmre = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(dmtf), "Substring");
CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression();
cmie.Method = cmre;
cmie.Parameters.Add(new CodePrimitiveExpression(15));
cis = new CodeConditionStatement();
cis.Condition = cboe;
- CodeMethodReferenceExpression cmre1 = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression("System.Int64"), "Parse");
+ CodeMethodReferenceExpression cmre1 = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression("System.Int64"), "Parse");
CodeMethodInvokeExpression cmie1 = new CodeMethodInvokeExpression();
cmie1.Method = cmre1;
cmie1.Parameters.Add(new CodeVariableReferenceExpression(tempStr));
/*
datetime = datetime.AddTicks(ticks);
*/
- CodeMethodReferenceExpression cmre2 = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(datetimeVariable), "AddTicks");
+ CodeMethodReferenceExpression cmre2 = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(datetimeVariable), "AddTicks");
CodeMethodInvokeExpression cmie2 = new CodeMethodInvokeExpression();
cmie2.Method = cmre2;
cmie2.Parameters.Add(new CodeVariableReferenceExpression(ticks));
int SubStringParam1,
int SubStringParam2)
{
- CodeMethodReferenceExpression cmre = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(dmtfVarName), "Substring");
+ CodeMethodReferenceExpression cmre = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(dmtfVarName), "Substring");
CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression();
cmie.Method = cmre;
cmie.Parameters.Add(new CodePrimitiveExpression(SubStringParam1));
cmie.Method = cmre;
cmie.Parameters.Add(new CodeVariableReferenceExpression(tempVarName));
- cis.TrueStatements.Add( new CodeAssignStatement(new CodeVariableReferenceExpression(toAssign), cmie));
+ cis.TrueStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(toAssign), cmie));
cmmdt.Add(cis);
}
private void AddToDMTFTimeIntervalFunction()
{
string dmtfTimeSpan = "dmtftimespan";
- string timespan = "timespan";
+ string timespan = "timespan";
string tsTemp = "tsTemp";
string microsec = "microsec";
string strmicrosec = "strMicroSec";
private void AddToDMTFDateTimeFunction()
{
string strUtc = "utcString";
- string dateParam = "date";
+ string dateParam = "date";
CodeCastExpression cast = null;
private void AddToTimeSpanFunction()
{
- string tsParam = "dmtfTimespan";
+ string tsParam = "dmtfTimespan";
string days = "days";
string hours = "hours";
string minutes = "minutes";
private static void ToTimeSpanHelper(int start, int numOfCharacters, string strVarToAssign, CodeStatementCollection statCol)
{
string strTemp = "tempString";
- string tsParam = "dmtfTimespan";
+ string tsParam = "dmtfTimespan";
CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression();
cmie.Method = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(tsParam), "Substring");
private void GenerateMethodToInitializeVariables()
{
- CodeMemberMethod cmmInit = new CodeMemberMethod ();
+ CodeMemberMethod cmmInit = new CodeMemberMethod();
cmmInit.Name = PrivateNamesUsed["initVariable"].ToString();
cmmInit.Attributes = MemberAttributes.Private | MemberAttributes.Final;
//
private static CodeMethodInvokeExpression GenerateConcatStrings(CodeExpression ce1, CodeExpression ce2)
{
- CodeExpression []cmieParams = {ce1, ce2 };
+ CodeExpression[] cmieParams = { ce1, ce2 };
CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.String"),
"Concat",
namespace System.Management
{
-internal class WmiEventSink : IWmiEventSource
-{
- private static int s_hash = 0;
- private readonly int hash;
- private readonly ManagementOperationObserver watcher;
- private readonly object context;
- private readonly ManagementScope scope;
- private object stub; // The secured IWbemObjectSink
-
- // Used for Put's only
- internal event InternalObjectPutEventHandler InternalObjectPut;
- private readonly ManagementPath path;
- private readonly string className;
- private readonly bool isLocal;
-
-
- private static ManagementOperationObserver watcherParameter;
- private static object contextParameter;
- private static ManagementScope scopeParameter;
- private static string pathParameter;
- private static string classNameParameter;
- private static WmiEventSink wmiEventSinkNew;
-
- internal static WmiEventSink GetWmiEventSink(
- ManagementOperationObserver watcher,
- object context,
- ManagementScope scope,
- string path,
- string className)
- {
- if (MTAHelper.IsNoContextMTA())
- return new WmiEventSink(watcher, context, scope, path, className);
-
- watcherParameter = watcher;
- contextParameter = context;
- scopeParameter = scope;
- pathParameter = path;
- classNameParameter = className;
-
- //
- // Ensure we are able to trap exceptions from worker thread.
- //
- ThreadDispatch disp = new ThreadDispatch ( new ThreadDispatch.ThreadWorkerMethod ( HackToCreateWmiEventSink ) );
- disp.Start ( );
-
- return wmiEventSinkNew;
- }
-
- private static void HackToCreateWmiEventSink()
+ internal class WmiEventSink : IWmiEventSource
{
- wmiEventSinkNew = new WmiEventSink(watcherParameter, contextParameter, scopeParameter, pathParameter, classNameParameter);
- }
+ private static int s_hash = 0;
+ private readonly int hash;
+ private readonly ManagementOperationObserver watcher;
+ private readonly object context;
+ private readonly ManagementScope scope;
+ private object stub; // The secured IWbemObjectSink
+
+ // Used for Put's only
+ internal event InternalObjectPutEventHandler InternalObjectPut;
+ private readonly ManagementPath path;
+ private readonly string className;
+ private readonly bool isLocal;
+
+
+ private static ManagementOperationObserver watcherParameter;
+ private static object contextParameter;
+ private static ManagementScope scopeParameter;
+ private static string pathParameter;
+ private static string classNameParameter;
+ private static WmiEventSink wmiEventSinkNew;
+
+ internal static WmiEventSink GetWmiEventSink(
+ ManagementOperationObserver watcher,
+ object context,
+ ManagementScope scope,
+ string path,
+ string className)
+ {
+ if (MTAHelper.IsNoContextMTA())
+ return new WmiEventSink(watcher, context, scope, path, className);
+
+ watcherParameter = watcher;
+ contextParameter = context;
+ scopeParameter = scope;
+ pathParameter = path;
+ classNameParameter = className;
+
+ //
+ // Ensure we are able to trap exceptions from worker thread.
+ //
+ ThreadDispatch disp = new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethod(HackToCreateWmiEventSink));
+ disp.Start();
+
+ return wmiEventSinkNew;
+ }
- protected WmiEventSink (ManagementOperationObserver watcher,
- object context,
- ManagementScope scope,
- string path,
- string className)
- {
- try {
- this.context = context;
- this.watcher = watcher;
- this.className = className;
- this.isLocal = false;
+ private static void HackToCreateWmiEventSink()
+ {
+ wmiEventSinkNew = new WmiEventSink(watcherParameter, contextParameter, scopeParameter, pathParameter, classNameParameter);
+ }
- if (null != path)
+ protected WmiEventSink(ManagementOperationObserver watcher,
+ object context,
+ ManagementScope scope,
+ string path,
+ string className)
+ {
+ try
{
- this.path = new ManagementPath (path);
- if ((0==string.Compare(this.path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
- (0==string.Compare(this.path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
+ this.context = context;
+ this.watcher = watcher;
+ this.className = className;
+ this.isLocal = false;
+
+ if (null != path)
{
- this.isLocal = true;
+ this.path = new ManagementPath(path);
+ if ((0 == string.Compare(this.path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
+ (0 == string.Compare(this.path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
+ {
+ this.isLocal = true;
+ }
}
- }
- if (null != scope)
- {
- this.scope = (ManagementScope) scope.Clone ();
- if (null == path) // use scope to see if sink is local
+ if (null != scope)
{
- if ((0==string.Compare(this.scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
- (0==string.Compare(this.scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
+ this.scope = (ManagementScope)scope.Clone();
+ if (null == path) // use scope to see if sink is local
{
- this.isLocal = true;
+ if ((0 == string.Compare(this.scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
+ (0 == string.Compare(this.scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
+ {
+ this.isLocal = true;
+ }
}
}
- }
- WmiNetUtilsHelper.GetDemultiplexedStub_f (this, this.isLocal, out stub);
- hash = Threading.Interlocked.Increment(ref s_hash);
- } catch {}
- }
+ WmiNetUtilsHelper.GetDemultiplexedStub_f(this, this.isLocal, out stub);
+ hash = Threading.Interlocked.Increment(ref s_hash);
+ }
+ catch { }
+ }
- public override int GetHashCode () {
- return hash;
- }
+ public override int GetHashCode()
+ {
+ return hash;
+ }
- public IWbemObjectSink Stub {
- get {
- try {
- return (null != stub) ? (IWbemObjectSink) stub : null;
- } catch {
- return null;
+ public IWbemObjectSink Stub
+ {
+ get
+ {
+ try
+ {
+ return (null != stub) ? (IWbemObjectSink)stub : null;
+ }
+ catch
+ {
+ return null;
+ }
}
}
- }
-
- public virtual void Indicate (IntPtr pIWbemClassObject)
- {
- Marshal.AddRef(pIWbemClassObject);
- IWbemClassObjectFreeThreaded obj = new IWbemClassObjectFreeThreaded(pIWbemClassObject);
- try {
- ObjectReadyEventArgs args = new ObjectReadyEventArgs (context,
- ManagementBaseObject.GetBaseObject (obj, scope));
- watcher.FireObjectReady (args);
- } catch {}
- }
- public void SetStatus (
- int flags,
- int hResult,
- string message,
- IntPtr pErrorObj)
- {
- IWbemClassObjectFreeThreaded errObj = null;
- if (pErrorObj != IntPtr.Zero)
+ public virtual void Indicate(IntPtr pIWbemClassObject)
{
- Marshal.AddRef(pErrorObj);
- errObj = new IWbemClassObjectFreeThreaded(pErrorObj);
+ Marshal.AddRef(pIWbemClassObject);
+ IWbemClassObjectFreeThreaded obj = new IWbemClassObjectFreeThreaded(pIWbemClassObject);
+ try
+ {
+ ObjectReadyEventArgs args = new ObjectReadyEventArgs(context,
+ ManagementBaseObject.GetBaseObject(obj, scope));
+ watcher.FireObjectReady(args);
+ }
+ catch { }
}
- try {
- if (flags == (int) tag_WBEM_STATUS_TYPE.WBEM_STATUS_COMPLETE)
+ public void SetStatus(
+ int flags,
+ int hResult,
+ string message,
+ IntPtr pErrorObj)
+ {
+ IWbemClassObjectFreeThreaded errObj = null;
+ if (pErrorObj != IntPtr.Zero)
{
- // Is this a Put? If so fire the ObjectPut event
- if (null != path)
- {
- if (null == className)
- path.RelativePath = message;
- else
- path.RelativePath = className;
+ Marshal.AddRef(pErrorObj);
+ errObj = new IWbemClassObjectFreeThreaded(pErrorObj);
+ }
- // Fire the internal event (if anyone is interested)
- if (null != InternalObjectPut)
+ try
+ {
+ if (flags == (int)tag_WBEM_STATUS_TYPE.WBEM_STATUS_COMPLETE)
+ {
+ // Is this a Put? If so fire the ObjectPut event
+ if (null != path)
{
- try {
- InternalObjectPutEventArgs iargs = new InternalObjectPutEventArgs (path);
- InternalObjectPut (this, iargs);
- } catch {}
+ if (null == className)
+ path.RelativePath = message;
+ else
+ path.RelativePath = className;
+
+ // Fire the internal event (if anyone is interested)
+ if (null != InternalObjectPut)
+ {
+ try
+ {
+ InternalObjectPutEventArgs iargs = new InternalObjectPutEventArgs(path);
+ InternalObjectPut(this, iargs);
+ }
+ catch { }
+ }
+
+ ObjectPutEventArgs args = new ObjectPutEventArgs(context, path);
+ watcher.FireObjectPut(args);
}
- ObjectPutEventArgs args = new ObjectPutEventArgs (context, path);
- watcher.FireObjectPut(args);
- }
-
- // Fire Completed event
- CompletedEventArgs args2 = null;
- if ( errObj != null )
+ // Fire Completed event
+ CompletedEventArgs args2 = null;
+ if (errObj != null)
{
- args2 = new CompletedEventArgs (context, hResult,
- new ManagementBaseObject (errObj)
+ args2 = new CompletedEventArgs(context, hResult,
+ new ManagementBaseObject(errObj)
);
}
- else
+ else
{
- args2 = new CompletedEventArgs (context, hResult,
+ args2 = new CompletedEventArgs(context, hResult,
null
);
}
- watcher.FireCompleted (args2);
+ watcher.FireCompleted(args2);
- // Unhook and tidy up
- watcher.RemoveSink (this);
- }
- else if (0 != (flags & (int) tag_WBEM_STATUS_TYPE.WBEM_STATUS_PROGRESS))
- {
- // Fire Progress event
- ProgressEventArgs args = new ProgressEventArgs (context,
- (int) (((uint)hResult & 0xFFFF0000) >> 16), hResult & 0xFFFF, message);
+ // Unhook and tidy up
+ watcher.RemoveSink(this);
+ }
+ else if (0 != (flags & (int)tag_WBEM_STATUS_TYPE.WBEM_STATUS_PROGRESS))
+ {
+ // Fire Progress event
+ ProgressEventArgs args = new ProgressEventArgs(context,
+ (int)(((uint)hResult & 0xFFFF0000) >> 16), hResult & 0xFFFF, message);
- watcher.FireProgress (args);
+ watcher.FireProgress(args);
+ }
}
- } catch {}
- }
+ catch { }
+ }
- internal void Cancel ()
- {
- try {
- scope.GetIWbemServices().CancelAsyncCall_((IWbemObjectSink) stub);
- } catch {}
- }
+ internal void Cancel()
+ {
+ try
+ {
+ scope.GetIWbemServices().CancelAsyncCall_((IWbemObjectSink)stub);
+ }
+ catch { }
+ }
- internal void ReleaseStub ()
- {
- try {
- /*
- * We force a release of the stub here so as to allow
- * unsecapp.exe to die as soon as possible.
- */
- if (null != stub)
+ internal void ReleaseStub()
+ {
+ try
{
- System.Runtime.InteropServices.Marshal.ReleaseComObject(stub);
- stub = null;
+ /*
+ * We force a release of the stub here so as to allow
+ * unsecapp.exe to die as soon as possible.
+ */
+ if (null != stub)
+ {
+ System.Runtime.InteropServices.Marshal.ReleaseComObject(stub);
+ stub = null;
+ }
}
- } catch {}
- }
+ catch { }
+ }
-}
+ }
-// Special sink implementation for ManagementObject.Get
-// Doesn't issue ObjectReady events
-internal class WmiGetEventSink : WmiEventSink
-{
- private readonly ManagementObject managementObject;
+ // Special sink implementation for ManagementObject.Get
+ // Doesn't issue ObjectReady events
+ internal class WmiGetEventSink : WmiEventSink
+ {
+ private readonly ManagementObject managementObject;
- private static ManagementOperationObserver watcherParameter;
- private static object contextParameter;
- private static ManagementScope scopeParameter;
- private static ManagementObject managementObjectParameter;
+ private static ManagementOperationObserver watcherParameter;
+ private static object contextParameter;
+ private static ManagementScope scopeParameter;
+ private static ManagementObject managementObjectParameter;
- private static WmiGetEventSink wmiGetEventSinkNew;
+ private static WmiGetEventSink wmiGetEventSinkNew;
- internal static WmiGetEventSink GetWmiGetEventSink(
- ManagementOperationObserver watcher,
- object context,
- ManagementScope scope,
- ManagementObject managementObject)
- {
- if (MTAHelper.IsNoContextMTA())
- return new WmiGetEventSink(watcher, context, scope, managementObject);
+ internal static WmiGetEventSink GetWmiGetEventSink(
+ ManagementOperationObserver watcher,
+ object context,
+ ManagementScope scope,
+ ManagementObject managementObject)
+ {
+ if (MTAHelper.IsNoContextMTA())
+ return new WmiGetEventSink(watcher, context, scope, managementObject);
- watcherParameter = watcher;
- contextParameter = context;
- scopeParameter = scope;
- managementObjectParameter = managementObject;
+ watcherParameter = watcher;
+ contextParameter = context;
+ scopeParameter = scope;
+ managementObjectParameter = managementObject;
- //
- // Ensure we are able to trap exceptions from worker thread.
- //
- ThreadDispatch disp = new ThreadDispatch ( new ThreadDispatch.ThreadWorkerMethod ( HackToCreateWmiGetEventSink ) );
- disp.Start ( );
+ //
+ // Ensure we are able to trap exceptions from worker thread.
+ //
+ ThreadDispatch disp = new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethod(HackToCreateWmiGetEventSink));
+ disp.Start();
- return wmiGetEventSinkNew;
- }
+ return wmiGetEventSinkNew;
+ }
- private static void HackToCreateWmiGetEventSink()
- {
- wmiGetEventSinkNew = new WmiGetEventSink(watcherParameter, contextParameter, scopeParameter, managementObjectParameter);
- }
+ private static void HackToCreateWmiGetEventSink()
+ {
+ wmiGetEventSinkNew = new WmiGetEventSink(watcherParameter, contextParameter, scopeParameter, managementObjectParameter);
+ }
- private WmiGetEventSink (ManagementOperationObserver watcher,
- object context,
- ManagementScope scope,
- ManagementObject managementObject) :
- base (watcher, context, scope, null, null)
- {
- this.managementObject = managementObject;
- }
+ private WmiGetEventSink(ManagementOperationObserver watcher,
+ object context,
+ ManagementScope scope,
+ ManagementObject managementObject) :
+ base(watcher, context, scope, null, null)
+ {
+ this.managementObject = managementObject;
+ }
- public override void Indicate (IntPtr pIWbemClassObject)
- {
- Marshal.AddRef(pIWbemClassObject);
- IWbemClassObjectFreeThreaded obj = new IWbemClassObjectFreeThreaded(pIWbemClassObject);
- if (null != managementObject)
+ public override void Indicate(IntPtr pIWbemClassObject)
{
- try {
- managementObject.wbemObject = obj;
- } catch {}
+ Marshal.AddRef(pIWbemClassObject);
+ IWbemClassObjectFreeThreaded obj = new IWbemClassObjectFreeThreaded(pIWbemClassObject);
+ if (null != managementObject)
+ {
+ try
+ {
+ managementObject.wbemObject = obj;
+ }
+ catch { }
+ }
}
}
-}
[ComImport]
[Guid("1CF2B120-547D-101B-8E65-08002B2BD119")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
- internal interface IErrorInfo
+ internal interface IErrorInfo
{
Guid GetGUID();
- [return:MarshalAs(UnmanagedType.BStr)]
+ [return: MarshalAs(UnmanagedType.BStr)]
string GetSource();
- [return:MarshalAs(UnmanagedType.BStr)]
+ [return: MarshalAs(UnmanagedType.BStr)]
string GetDescription();
- [return:MarshalAs(UnmanagedType.BStr)]
+ [return: MarshalAs(UnmanagedType.BStr)]
string GetHelpFile();
uint GetHelpContext();
ICredentials proxyCreds = state.Proxy == null ?
state.DefaultProxyCredentials :
state.Proxy.Credentials;
- if (proxyCreds == null)
- {
- break;
- }
+ if (proxyCreds == null)
+ {
+ break;
+ }
// Determine authorization scheme to use. We ignore the firstScheme
// parameter which is included in the supportedSchemes flags already.
authScheme == Interop.WinHttp.WINHTTP_AUTH_SCHEME_NTLM)
{
// Allow WinHTTP to transmit the default credentials.
- ChangeDefaultCredentialsPolicy(requestHandle, authTarget, allowDefaultCredentials:true);
+ ChangeDefaultCredentialsPolicy(requestHandle, authTarget, allowDefaultCredentials: true);
userName = null;
password = null;
}
state.DefaultProxyCredentials = _defaultProxyCredentials;
state.PreAuthenticate = _preAuthenticate;
- Task.Factory.StartNew(
- s => {
+ Task.Factory.StartNew(s =>
+ {
var whrs = (WinHttpRequestState)s;
_ = whrs.Handler.StartRequestAsync(whrs);
},
_authHelper.ChangeDefaultCredentialsPolicy(
state.RequestHandle,
Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER,
- allowDefaultCredentials:false);
+ allowDefaultCredentials: false);
}
private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle)
public bool CheckCertificateRevocationList { get; set; }
- public Func<
- HttpRequestMessage,
- X509Certificate2,
- X509Chain,
- SslPolicyErrors,
- bool> ServerCertificateValidationCallback { get; set; }
+ public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateValidationCallback { get; set; }
public WinHttpTransportContext TransportContext
{
return true;
}
}
- else if (parent.ContainsParsedValue(KnownHeaders.Connection.Descriptor, HeaderUtilities.ConnectionClose))
+ else if (parent.ContainsParsedValue(KnownHeaders.Connection.Descriptor, HeaderUtilities.ConnectionClose))
{
return true;
}
{
for (int i = 0; i < input.Length; i++)
{
- if (!IsTokenChar((char) input[i]))
+ if (!IsTokenChar((char)input[i]))
{
return false;
}
{
try
{
- var streams = new Stream[2 + (_nestedContent.Count*2)];
+ var streams = new Stream[2 + (_nestedContent.Count * 2)];
var scratch = new StringBuilder();
int streamIndex = 0;
[Event(HandlerMessageId, Keywords = Keywords.Debug, Level = EventLevel.Verbose)]
public void HandlerMessage(int poolId, int workerId, int requestId, string memberName, string message) =>
WriteEvent(HandlerMessageId, poolId, workerId, requestId, memberName, message);
- //Console.WriteLine($"{poolId}/{workerId}/{requestId}: ({memberName}): {message}"); // uncomment for debugging only
[Event(HandlerErrorId, Keywords = Keywords.Debug, Level = EventLevel.Error)]
public void HandlerMessageError(int poolId, int workerId, int requestId, string memberName, string message) =>
WriteEvent(HandlerErrorId, poolId, workerId, requestId, memberName, message);
- //Console.WriteLine($"{poolId}/{workerId}/{requestId}: ({memberName}): {message}"); // uncomment for debugging only
[NonEvent]
public static void AuthenticationInfo(Uri uri, string message)
}
ChannelBinding channelBinding = connection.TransportContext?.GetChannelBinding(ChannelBindingKind.Endpoint);
- NTAuthentication authContext = new NTAuthentication(isServer:false, challenge.SchemeName, challenge.Credential, spn, ContextFlagsPal.Connection, channelBinding);
+ NTAuthentication authContext = new NTAuthentication(isServer: false, challenge.SchemeName, challenge.Credential, spn, ContextFlagsPal.Connection, channelBinding);
string challengeData = challenge.ChallengeData;
try
{
public static Task<HttpResponseMessage> SendWithNtProxyAuthAsync(HttpRequestMessage request, Uri proxyUri, ICredentials proxyCredentials, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken)
{
- return SendWithNtAuthAsync(request, proxyUri, proxyCredentials, isProxyAuth:true, connection, connectionPool, cancellationToken);
+ return SendWithNtAuthAsync(request, proxyUri, proxyCredentials, isProxyAuth: true, connection, connectionPool, cancellationToken);
}
public static Task<HttpResponseMessage> SendWithNtConnectionAuthAsync(HttpRequestMessage request, ICredentials credentials, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken)
{
- return SendWithNtAuthAsync(request, request.RequestUri, credentials, isProxyAuth:false, connection, connectionPool, cancellationToken);
+ return SendWithNtAuthAsync(request, request.RequestUri, credentials, isProxyAuth: false, connection, connectionPool, cancellationToken);
}
}
}
public static Task<HttpResponseMessage> SendWithProxyAuthAsync(HttpRequestMessage request, Uri proxyUri, ICredentials proxyCredentials, bool doRequestAuth, HttpConnectionPool pool, CancellationToken cancellationToken)
{
- return SendWithAuthAsync(request, proxyUri, proxyCredentials, preAuthenticate:false, isProxyAuth:true, doRequestAuth, pool, cancellationToken);
+ return SendWithAuthAsync(request, proxyUri, proxyCredentials, preAuthenticate: false, isProxyAuth: true, doRequestAuth, pool, cancellationToken);
}
public static Task<HttpResponseMessage> SendWithRequestAuthAsync(HttpRequestMessage request, ICredentials credentials, bool preAuthenticate, HttpConnectionPool pool, CancellationToken cancellationToken)
{
- return SendWithAuthAsync(request, request.RequestUri, credentials, preAuthenticate, isProxyAuth:false, doRequestAuth:true, pool, cancellationToken);
+ return SendWithAuthAsync(request, request.RequestUri, credentials, preAuthenticate, isProxyAuth: false, doRequestAuth: true, pool, cancellationToken);
}
}
}
{
if (cancellationToken.IsCancellationRequested)
{
- ThrowOperationCanceledException(innerException:null, cancellationToken);
+ ThrowOperationCanceledException(innerException: null, cancellationToken);
}
}
}
/// "chunk extensions" are allowed. We place a limit on how long a line can be to avoid OOM issues if an
/// infinite chunk length is sent. This value is arbitrary and can be changed as needed.
/// </remarks>
- private const int MaxChunkBytesAllowed = 16*1024;
+ private const int MaxChunkBytesAllowed = 16 * 1024;
/// <summary>How long a trailing header can be. This value is arbitrary and can be changed as needed.</summary>
- private const int MaxTrailingHeaderLength = 16*1024;
+ private const int MaxTrailingHeaderLength = 16 * 1024;
/// <summary>The number of bytes remaining in the chunk.</summary>
private ulong _chunkBytesRemaining;
/// <summary>The current state of the parsing state machine for the chunked response.</summary>
{
// Make sure that we don't inadvertently consume trailing headers
// while draining a connection that's being returned back to the pool.
- HttpConnection.ParseHeaderNameValue(_connection, currentLine, _response, isFromTrailer : true);
+ HttpConnection.ParseHeaderNameValue(_connection, currentLine, _response, isFromTrailer: true);
}
}
_outgoingBuffer.Commit(FrameHeader.Size);
}
- /// <summary>Abort all streams and cause further processing to fail.</summary>
- /// <param name="abortException">Exception causing Abort to be called.</param>
+ /// <summary>Abort all streams and cause further processing to fail.</summary>
+ /// <param name="abortException">Exception causing Abort to be called.</param>
private void Abort(Exception abortException)
{
// The connection has failed, e.g. failed IO or a connection-level frame error.
// (4) Receiving EOF from the server. If so, resetException will contain an exception like "expected 9 bytes of data", and canRetry will be false.
public void OnReset(Exception resetException, Http2ProtocolErrorCode? resetStreamErrorCode = null, bool canRetry = false)
{
- if (NetEventSource.IsEnabled) Trace($"{nameof(resetException)}={resetException}, {nameof(resetStreamErrorCode )}={resetStreamErrorCode}");
+ if (NetEventSource.IsEnabled) Trace($"{nameof(resetException)}={resetException}, {nameof(resetStreamErrorCode)}={resetStreamErrorCode}");
bool cancel = false;
CancellationTokenSource requestBodyCancellationSource = null;
protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
- return _poolManager.SendAsync(request, doRequestAuth:true, cancellationToken);
+ return _poolManager.SendAsync(request, doRequestAuth: true, cancellationToken);
}
protected override void Dispose(bool disposing)
// TODO: Remove this overload once https://github.com/dotnet/csharplang/issues/1331 is addressed
// and the compiler doesn't prevent using spans in async methods.
private static void ParseHeaderNameValue(HttpConnection connection, ArraySegment<byte> line, HttpResponseMessage response) =>
- ParseHeaderNameValue(connection, (Span<byte>)line, response, isFromTrailer:false);
+ ParseHeaderNameValue(connection, (Span<byte>)line, response, isFromTrailer: false);
private static void ParseHeaderNameValue(HttpConnection connection, ReadOnlySpan<byte> line, HttpResponseMessage response, bool isFromTrailer)
{
protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
- return _poolManager.SendAsync(request, doRequestAuth:false, cancellationToken);
+ return _poolManager.SendAsync(request, doRequestAuth: false, cancellationToken);
}
protected override void Dispose(bool disposing)
public Task<HttpResponseMessage> SendProxyConnectAsync(HttpRequestMessage request, Uri proxyUri, CancellationToken cancellationToken)
{
- return SendAsyncCore(request, proxyUri, doRequestAuth:false, isProxyConnect:true, cancellationToken);
+ return SendAsyncCore(request, proxyUri, doRequestAuth: false, isProxyConnect: true, cancellationToken);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, bool doRequestAuth, CancellationToken cancellationToken)
{
if (_proxy == null)
{
- return SendAsyncCore(request, null, doRequestAuth, isProxyConnect:false, cancellationToken);
+ return SendAsyncCore(request, null, doRequestAuth, isProxyConnect: false, cancellationToken);
}
// Do proxy lookup.
throw new NotSupportedException(SR.net_http_invalid_proxy_scheme);
}
- return SendAsyncCore(request, proxyUri, doRequestAuth, isProxyConnect:false, cancellationToken);
+ return SendAsyncCore(request, proxyUri, doRequestAuth, isProxyConnect: false, cancellationToken);
}
/// <summary>Disposes of the pools, disposing of each individual pool.</summary>
private readonly WinInetProxyHelper _proxyHelper;
private SafeWinHttpHandle _sessionHandle;
private bool _disposed;
- private static readonly char[] s_proxyDelimiters = {';', ' ', '\n', '\r', '\t'};
+ private static readonly char[] s_proxyDelimiters = { ';', ' ', '\n', '\r', '\t' };
public static bool TryCreate(out IWebProxy proxy)
{
}
}
- proxy = new HttpWindowsProxy(proxyHelper, sessionHandle);
+ proxy = new HttpWindowsProxy(proxyHelper, sessionHandle);
return true;
}
if (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] == '[')
{
// Strip [] from IPv6 so we can use IdnHost laster for matching.
- idx +=1;
+ idx += 1;
}
start = idx;
- while (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] != ' ' && proxyHelper.ProxyBypass[idx] != ';' && proxyHelper.ProxyBypass[idx] != ']') {idx += 1; };
+ while (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] != ' ' && proxyHelper.ProxyBypass[idx] != ';' && proxyHelper.ProxyBypass[idx] != ']') { idx += 1; };
if (idx == start)
{
}
else
{
- tmp = proxyHelper.ProxyBypass.Substring(start, idx-start);
+ tmp = proxyHelper.ProxyBypass.Substring(start, idx - start);
}
// Skip trailing characters if any.
if (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] != ';')
{
// Got stopped at space or ']'. Strip until next ';' or end.
- while (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] != ';' ) {idx += 1; };
+ while (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] != ';') { idx += 1; };
}
- if (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] == ';')
+ if (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] == ';')
{
idx++;
}
if (_bypassLocal)
{
- _localIp = new List<IPAddress>();
+ _localIp = new List<IPAddress>();
foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties ipProps = netInterface.GetIPProperties();
private string m_domainKey = string.Empty; // Do not rename (binary serialization)
-/*
- TODO: #13607
- VSO 449560
- Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
- block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
- public, this is a temporary workaround till that happens.
-*/
+ /*
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
+ */
#if uap
public
#else
#endif
bool IsQuotedVersion = false;
-/*
- TODO: #13607
- VSO 449560
- Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
- block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
- public, this is a temporary workaround till that happens.
-*/
+ /*
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
+ */
#if uap
public
#else
}
}
-/*
- TODO: #13607
- VSO 449560
- Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
- block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
- public, this is a temporary workaround till that happens.
-*/
+ /*
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
+ */
#if uap
public
#else
}
}
-/*
- TODO: #13607
- VSO 449560
- Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
- block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
- public, this is a temporary workaround till that happens.
-*/
+ /*
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
+ */
#if uap
public
#else
}
}
-/*
- TODO: #13607
- VSO 449560
- Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
- block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
- public, this is a temporary workaround till that happens.
-*/
+ /*
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
+ */
#if uap
public
#else
}
}
-/*
- TODO: #13607
- VSO 449560
- Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
- block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
- public, this is a temporary workaround till that happens.
-*/
+ /*
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
+ */
#if uap
public
#else
// If isStrict == true, replace the cookie if found same with newest Variant.
// Returns 1 if added, 0 if replaced or rejected.
-/*
- TODO: #13607
- VSO 449560
- Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
- block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
- public, this is a temporary workaround till that happens.
-*/
+ /*
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
+ */
#if uap
public
#else
using System.Threading.Tasks;
namespace System.Net
{
- public abstract class WebRequest : MarshalByRefObject, ISerializable
+ public abstract class WebRequest : MarshalByRefObject, ISerializable
{
internal class WebRequestPrefixElement
{
/// </devdoc>
public virtual Stream GetResponseStream()
{
- throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
+ throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
/// <devdoc>
SetException(e);
if (_exception.SourceException != e)
{
- ThrowIfExceptional();
+ ThrowIfExceptional();
}
throw;
}
}
}
- [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError=true)]
+ [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)]
internal unsafe delegate bool AcceptExDelegate(
SafeSocketHandle listenSocketHandle,
SafeSocketHandle acceptSocketHandle,
out int bytesReceived,
NativeOverlapped* overlapped);
- [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError=true)]
+ [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)]
internal delegate void GetAcceptExSockaddrsDelegate(
IntPtr buffer,
int receiveDataLength,
out int remoteSocketAddressLength);
- [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError=true)]
+ [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)]
internal unsafe delegate bool ConnectExDelegate(
SafeSocketHandle socketHandle,
IntPtr socketAddress,
out int bytesSent,
NativeOverlapped* overlapped);
- [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError=true)]
+ [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)]
internal unsafe delegate bool DisconnectExDelegate(
SafeSocketHandle socketHandle,
NativeOverlapped* overlapped,
int flags,
int reserved);
- [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError=true)]
+ [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)]
internal delegate bool DisconnectExDelegateBlocking(
SafeSocketHandle socketHandle,
IntPtr overlapped,
int flags,
int reserved);
- [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError=true)]
+ [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)]
internal unsafe delegate SocketError WSARecvMsgDelegate(
SafeSocketHandle socketHandle,
IntPtr msg,
NativeOverlapped* overlapped,
IntPtr completionRoutine);
- [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError=true)]
+ [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)]
internal delegate SocketError WSARecvMsgDelegateBlocking(
SafeSocketHandle socketHandle,
IntPtr msg,
IntPtr overlapped,
IntPtr completionRoutine);
- [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError=true)]
+ [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)]
internal unsafe delegate bool TransmitPacketsDelegate(
SafeSocketHandle socketHandle,
IntPtr packetArray,
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_innerSocket={_innerSocket}");
#if DEBUG
- // If this throws it could be very bad.
+ // If this throws it could be very bad.
try
{
#endif
}
ValidateForMultiConnect(isMultiEndpoint: false);
- return UnsafeBeginConnect(remoteEP, callback, state, flowContext:true);
+ return UnsafeBeginConnect(remoteEP, callback, state, flowContext: true);
}
private bool CanUseConnectEx(EndPoint remoteEP)
// Count them first.
for (int i = 0; i < count; i++)
{
- char ch = (char) bytes[offset + i];
+ char ch = (char)bytes[offset + i];
if (ch == ' ')
{
for (int i = 0; i < count; i++)
{
- byte b = bytes[offset+i];
- char ch = (char) b;
+ byte b = bytes[offset + i];
+ char ch = (char)b;
if (IsSafe(ch))
{
}
else if (ch == ' ')
{
- expandedBytes[pos++] = (byte) '+';
+ expandedBytes[pos++] = (byte)'+';
}
else
{
- expandedBytes[pos++] = (byte) '%';
- expandedBytes[pos++] = (byte) IntToHex((b >> 4) & 0xf);
- expandedBytes[pos++] = (byte) IntToHex(b & 0x0f);
+ expandedBytes[pos++] = (byte)'%';
+ expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf);
+ expandedBytes[pos++] = (byte)IntToHex(b & 0x0f);
}
}
public static bool IsRestricted(string headerName, bool response)
{
- headerName = HttpValidationHelpers.CheckBadHeaderNameChars(headerName);
+ headerName = HttpValidationHelpers.CheckBadHeaderNameChars(headerName);
return response ? HeaderInfo[headerName].IsResponseRestricted : HeaderInfo[headerName].IsRequestRestricted;
}
if (response.StatusCode != HttpStatusCode.SwitchingProtocols)
{
- throw new WebSocketException(WebSocketError.NotAWebSocket, SR.Format(SR.net_WebSockets_Connect101Expected, (int) response.StatusCode));
+ throw new WebSocketException(WebSocketError.NotAWebSocket, SR.Format(SR.net_WebSockets_Connect101Expected, (int)response.StatusCode));
}
// The Connection, Upgrade, and SecWebSocketAccept headers are required and with specific values.
for (int i = 0; i < sourceStrides.Length; i++)
{
// reverse the index for reverseStride so that we divide by largest stride first
- var nIndex = sourceReverseStride ? sourceStrides.Length - 1 - i: i;
+ var nIndex = sourceReverseStride ? sourceStrides.Length - 1 - i : i;
var sourceStride = sourceStrides[nIndex];
var transformStride = transformStrides[nIndex];
private static Type s_typeOfDBNull;
internal static Type TypeOfDBNull
{
- get
+ get
{
if (s_typeOfDBNull == null)
s_typeOfDBNull = typeof(DBNull);
}
else
{
- tempDelegate = new JsonFormatReaderGenerator().GenerateGetOnlyCollectionReader(TraditionalCollectionDataContract);
+ tempDelegate = new JsonFormatReaderGenerator().GenerateGetOnlyCollectionReader(TraditionalCollectionDataContract);
}
Interlocked.MemoryBarrier();
return ParseJsonDate(ReadElementContentAsString(), _dateTimeFormat);
}
- #if USE_REFEMIT
+#if USE_REFEMIT
public override bool TryReadDateTimeArray(XmlObjectSerializerReadContext context,
#else
internal override bool TryReadDateTimeArray(XmlObjectSerializerReadContext context,
obj = ResolveAdapterType(obj, classContract);
if (classContract.IsISerializable)
{
- context.WriteISerializable(xmlWriter, (ISerializable) obj);
+ context.WriteISerializable(xmlWriter, (ISerializable)obj);
}
else
{
{
for (int i = 0; i < xmlAttributes.Count; i++)
{
- wrapperElement.Attributes.Append((XmlAttribute) xmlAttributes[i]);
+ wrapperElement.Attributes.Append((XmlAttribute)xmlAttributes[i]);
}
}
if (xmlChildNodes != null)
public string? String;
public Offset Offset;
public string? DnsSafeHost; // stores dns safe host when idn is on and we have unicode or idn host
- public MoreInfo? MoreInfo; // Multi-threading: This field must be always accessed through a _local_
- // stack copy of m_Info.
+ public MoreInfo? MoreInfo; // Multi-threading: This field must be always accessed through a _local_
+ // stack copy of m_Info.
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System {
+namespace System
+{
- public class HttpStyleUriParser: UriParser
+ public class HttpStyleUriParser : UriParser
{
- public HttpStyleUriParser():base(UriParser.HttpUri.Flags)
+ public HttpStyleUriParser() : base(UriParser.HttpUri.Flags)
{
}
}
- public class FtpStyleUriParser: UriParser
+ public class FtpStyleUriParser : UriParser
{
- public FtpStyleUriParser():base(UriParser.FtpUri.Flags)
+ public FtpStyleUriParser() : base(UriParser.FtpUri.Flags)
{
}
}
- public class FileStyleUriParser: UriParser
+ public class FileStyleUriParser : UriParser
{
- public FileStyleUriParser():base(UriParser.FileUri.Flags)
+ public FileStyleUriParser() : base(UriParser.FileUri.Flags)
{
}
}
- public class NewsStyleUriParser: UriParser
+ public class NewsStyleUriParser : UriParser
{
- public NewsStyleUriParser():base(UriParser.NewsUri.Flags)
+ public NewsStyleUriParser() : base(UriParser.NewsUri.Flags)
{
}
}
- public class GopherStyleUriParser: UriParser
+ public class GopherStyleUriParser : UriParser
{
- public GopherStyleUriParser():base(UriParser.GopherUri.Flags)
+ public GopherStyleUriParser() : base(UriParser.GopherUri.Flags)
{
}
}
- public class LdapStyleUriParser: UriParser
+ public class LdapStyleUriParser : UriParser
{
- public LdapStyleUriParser():base(UriParser.LdapUri.Flags)
+ public LdapStyleUriParser() : base(UriParser.LdapUri.Flags)
{
}
}
- public class NetPipeStyleUriParser: UriParser
+ public class NetPipeStyleUriParser : UriParser
{
- public NetPipeStyleUriParser():base(UriParser.NetPipeUri.Flags)
+ public NetPipeStyleUriParser() : base(UriParser.NetPipeUri.Flags)
{
}
}
- public class NetTcpStyleUriParser: UriParser
+ public class NetTcpStyleUriParser : UriParser
{
- public NetTcpStyleUriParser():base(UriParser.NetTcpUri.Flags)
+ public NetTcpStyleUriParser() : base(UriParser.NetTcpUri.Flags)
{
}
}
internal void CheckSetIsSimpleFlag()
{
- Type type = this.GetType();
-
- if ( type == typeof(GenericUriParser)
- || type == typeof(HttpStyleUriParser)
- || type == typeof(FtpStyleUriParser)
- || type == typeof(FileStyleUriParser)
- || type == typeof(NewsStyleUriParser)
- || type == typeof(GopherStyleUriParser)
- || type == typeof(NetPipeStyleUriParser)
- || type == typeof(NetTcpStyleUriParser)
- || type == typeof(LdapStyleUriParser)
+ Type type = this.GetType();
+
+ if (type == typeof(GenericUriParser)
+ || type == typeof(HttpStyleUriParser)
+ || type == typeof(FtpStyleUriParser)
+ || type == typeof(FileStyleUriParser)
+ || type == typeof(NewsStyleUriParser)
+ || type == typeof(GopherStyleUriParser)
+ || type == typeof(NetPipeStyleUriParser)
+ || type == typeof(NetTcpStyleUriParser)
+ || type == typeof(LdapStyleUriParser)
)
{
_flags |= UriSyntaxFlags.SimpleUserSyntax;
/// The content of this <see cref="XAttribute"/> as a <see cref="string"/>.
/// </returns>
[CLSCompliant(false)]
- public static explicit operator string (XAttribute attribute)
+ public static explicit operator string(XAttribute attribute)
{
if (attribute == null) return null;
return attribute.value;
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
- public static explicit operator bool (XAttribute attribute)
+ public static explicit operator bool(XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException(nameof(attribute));
return XmlConvert.ToBoolean(attribute.value.ToLowerInvariant());
/// The content of this <see cref="XAttribute"/> as a <see cref="bool"/>?.
/// </returns>
[CLSCompliant(false)]
- public static explicit operator bool? (XAttribute attribute)
+ public static explicit operator bool?(XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToBoolean(attribute.value.ToLowerInvariant());
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
- public static explicit operator int (XAttribute attribute)
+ public static explicit operator int(XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException(nameof(attribute));
return XmlConvert.ToInt32(attribute.value);
/// The content of this <see cref="XAttribute"/> as an <see cref="int"/>?.
/// </returns>
[CLSCompliant(false)]
- public static explicit operator int? (XAttribute attribute)
+ public static explicit operator int?(XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToInt32(attribute.value);
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
- public static explicit operator uint (XAttribute attribute)
+ public static explicit operator uint(XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException(nameof(attribute));
return XmlConvert.ToUInt32(attribute.value);
/// The content of this <see cref="XAttribute"/> as an <see cref="uint"/>?.
/// </returns>
[CLSCompliant(false)]
- public static explicit operator uint? (XAttribute attribute)
+ public static explicit operator uint?(XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToUInt32(attribute.value);
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
- public static explicit operator long (XAttribute attribute)
+ public static explicit operator long(XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException(nameof(attribute));
return XmlConvert.ToInt64(attribute.value);
/// The content of this <see cref="XAttribute"/> as a <see cref="long"/>?.
/// </returns>
[CLSCompliant(false)]
- public static explicit operator long? (XAttribute attribute)
+ public static explicit operator long?(XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToInt64(attribute.value);
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
- public static explicit operator ulong (XAttribute attribute)
+ public static explicit operator ulong(XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException(nameof(attribute));
return XmlConvert.ToUInt64(attribute.value);
/// The content of this <see cref="XAttribute"/> as an <see cref="ulong"/>?.
/// </returns>
[CLSCompliant(false)]
- public static explicit operator ulong? (XAttribute attribute)
+ public static explicit operator ulong?(XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToUInt64(attribute.value);
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
- public static explicit operator float (XAttribute attribute)
+ public static explicit operator float(XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException(nameof(attribute));
return XmlConvert.ToSingle(attribute.value);
/// The content of this <see cref="XAttribute"/> as a <see cref="float"/>?.
/// </returns>
[CLSCompliant(false)]
- public static explicit operator float? (XAttribute attribute)
+ public static explicit operator float?(XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToSingle(attribute.value);
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
- public static explicit operator double (XAttribute attribute)
+ public static explicit operator double(XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException(nameof(attribute));
return XmlConvert.ToDouble(attribute.value);
/// The content of this <see cref="XAttribute"/> as a <see cref="double"/>?.
/// </returns>
[CLSCompliant(false)]
- public static explicit operator double? (XAttribute attribute)
+ public static explicit operator double?(XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToDouble(attribute.value);
/// Thrown if the specified attribute is null.
/// </exception>
[CLSCompliant(false)]
- public static explicit operator decimal (XAttribute attribute)
+ public static explicit operator decimal(XAttribute attribute)
{
if (attribute == null) throw new ArgumentNullException(nameof(attribute));
return XmlConvert.ToDecimal(attribute.value);
/// The content of this <see cref="XAttribute"/> as a <see cref="decimal"/>?.
/// </returns>
[CLSCompliant(false)]
- public static explicit operator decimal? (XAttribute attribute)
+ public static explicit operator decimal?(XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToDecimal(attribute.value);
/// The content of this <see cref="XAttribute"/> as a <see cref="DateTime"/>?.
/// </returns>
[CLSCompliant(false)]
- public static explicit operator DateTime? (XAttribute attribute)
+ public static explicit operator DateTime?(XAttribute attribute)
{
if (attribute == null) return null;
return DateTime.Parse(attribute.value, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind);
/// The content of this <see cref="XAttribute"/> as a <see cref="DateTimeOffset"/>?.
/// </returns>
[CLSCompliant(false)]
- public static explicit operator DateTimeOffset? (XAttribute attribute)
+ public static explicit operator DateTimeOffset?(XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToDateTimeOffset(attribute.value);
/// The content of this <see cref="XAttribute"/> as a <see cref="TimeSpan"/>?.
/// </returns>
[CLSCompliant(false)]
- public static explicit operator TimeSpan? (XAttribute attribute)
+ public static explicit operator TimeSpan?(XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToTimeSpan(attribute.value);
/// The content of this <see cref="XAttribute"/> as a <see cref="Guid"/>?.
/// </returns>
[CLSCompliant(false)]
- public static explicit operator Guid? (XAttribute attribute)
+ public static explicit operator Guid?(XAttribute attribute)
{
if (attribute == null) return null;
return XmlConvert.ToGuid(attribute.value);
XDocument d = InitLoad(reader, options);
d.ReadContentFrom(reader, options);
- if ( !reader.EOF) throw new InvalidOperationException(SR.InvalidOperation_ExpectedEndOfFile);
+ if (!reader.EOF) throw new InvalidOperationException(SR.InvalidOperation_ExpectedEndOfFile);
if (d.Root == null) throw new InvalidOperationException(SR.InvalidOperation_MissingRoot);
return d;
}
/// </returns>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator string (XElement element)
+ public static explicit operator string(XElement element)
{
if (element == null) return null;
return element.Value;
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator bool (XElement element)
+ public static explicit operator bool(XElement element)
{
if (element == null) throw new ArgumentNullException(nameof(element));
return XmlConvert.ToBoolean(element.Value.ToLowerInvariant());
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator bool? (XElement element)
+ public static explicit operator bool?(XElement element)
{
if (element == null) return null;
return XmlConvert.ToBoolean(element.Value.ToLowerInvariant());
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator int (XElement element)
+ public static explicit operator int(XElement element)
{
if (element == null) throw new ArgumentNullException(nameof(element));
return XmlConvert.ToInt32(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator int? (XElement element)
+ public static explicit operator int?(XElement element)
{
if (element == null) return null;
return XmlConvert.ToInt32(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator uint (XElement element)
+ public static explicit operator uint(XElement element)
{
if (element == null) throw new ArgumentNullException(nameof(element));
return XmlConvert.ToUInt32(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator uint? (XElement element)
+ public static explicit operator uint?(XElement element)
{
if (element == null) return null;
return XmlConvert.ToUInt32(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator long (XElement element)
+ public static explicit operator long(XElement element)
{
if (element == null) throw new ArgumentNullException(nameof(element));
return XmlConvert.ToInt64(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator long? (XElement element)
+ public static explicit operator long?(XElement element)
{
if (element == null) return null;
return XmlConvert.ToInt64(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator ulong (XElement element)
+ public static explicit operator ulong(XElement element)
{
if (element == null) throw new ArgumentNullException(nameof(element));
return XmlConvert.ToUInt64(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator ulong? (XElement element)
+ public static explicit operator ulong?(XElement element)
{
if (element == null) return null;
return XmlConvert.ToUInt64(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator float (XElement element)
+ public static explicit operator float(XElement element)
{
if (element == null) throw new ArgumentNullException(nameof(element));
return XmlConvert.ToSingle(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator float? (XElement element)
+ public static explicit operator float?(XElement element)
{
if (element == null) return null;
return XmlConvert.ToSingle(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator double (XElement element)
+ public static explicit operator double(XElement element)
{
if (element == null) throw new ArgumentNullException(nameof(element));
return XmlConvert.ToDouble(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator double? (XElement element)
+ public static explicit operator double?(XElement element)
{
if (element == null) return null;
return XmlConvert.ToDouble(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator decimal (XElement element)
+ public static explicit operator decimal(XElement element)
{
if (element == null) throw new ArgumentNullException(nameof(element));
return XmlConvert.ToDecimal(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator decimal? (XElement element)
+ public static explicit operator decimal?(XElement element)
{
if (element == null) return null;
return XmlConvert.ToDecimal(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator DateTime? (XElement element)
+ public static explicit operator DateTime?(XElement element)
{
if (element == null) return null;
return DateTime.Parse(element.Value, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator DateTimeOffset? (XElement element)
+ public static explicit operator DateTimeOffset?(XElement element)
{
if (element == null) return null;
return XmlConvert.ToDateTimeOffset(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator TimeSpan? (XElement element)
+ public static explicit operator TimeSpan?(XElement element)
{
if (element == null) return null;
return XmlConvert.ToTimeSpan(element.Value);
/// </exception>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Operator marked with CLSCompliant(false).")]
- public static explicit operator Guid? (XElement element)
+ public static explicit operator Guid?(XElement element)
{
if (element == null) return null;
return XmlConvert.ToGuid(element.Value);
}
else
{
- n = ((XNode) e.content).next;
+ n = ((XNode)e.content).next;
continue;
}
}
if (annotation == null) throw new ArgumentNullException(nameof(annotation));
if (annotations == null)
{
- annotations = annotation is object[] ? new object[] { annotation } : annotation;
+ annotations = annotation is object[]? new object[] { annotation } : annotation;
}
else
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
- return parent is XDocument?
+ return parent is XDocument ?
writer.WriteWhitespaceAsync(text) :
writer.WriteStringAsync(text);
}
pSrc += 2;
}
/* Invalid XML character */
- else if (ch <= 0x7F || ch >= 0xFFFE)
+ else if (ch <= 0x7F || ch >= 0xFFFE)
{
pDst = InvalidXmlChar(ch, pDst, true);
pSrc++;
pSrc += 2;
}
/* Invalid XML character */
- else if (ch <= 0x7F || ch >= 0xFFFE)
+ else if (ch <= 0x7F || ch >= 0xFFFE)
{
pDst = InvalidXmlChar(ch, pDst, true);
pSrc++;
pSrc += 2;
}
/* Invalid XML character */
- else if (ch <= 0x7F || ch >= 0xFFFE)
+ else if (ch <= 0x7F || ch >= 0xFFFE)
{
pDst = InvalidXmlChar(ch, pDst, false);
pSrc++;
pSrc += 2;
}
/* Invalid XML character */
- else if (ch <= 0x7F || ch >= 0xFFFE)
+ else if (ch <= 0x7F || ch >= 0xFFFE)
{
pDst = InvalidXmlChar(ch, pDst, false);
pSrc++;
pSrc += 2;
}
/* Invalid XML character */
- else if (ch <= 0x7F || ch >= 0xFFFE)
+ else if (ch <= 0x7F || ch >= 0xFFFE)
{
pDst = InvalidXmlChar(ch, pDst, false);
pSrc++;
pSrc += 2;
}
/* Invalid XML character */
- else if (ch <= 0x7F || ch >= 0xFFFE)
+ else if (ch <= 0x7F || ch >= 0xFFFE)
{
pDst = InvalidXmlChar(ch, pDst, false);
pSrc++;
}
else
{
- *pDst = (char)ch;
- pDst++;
+ *pDst = (char)ch;
+ pDst++;
return pDst;
}
}
pSrc += 2;
}
/* Invalid XML character */
- else if (ch <= 0x7F || ch >= 0xFFFE)
+ else if (ch <= 0x7F || ch >= 0xFFFE)
{
pDst = InvalidXmlChar(ch, pDst, false);
pSrc++;
fixed (char* pSrc = s)
{
char* pS = pSrc;
- while ((*pDst++ = (char)*pS++) != 0);
+ while ((*pDst++ = (char)*pS++) != 0) ;
}
pDst[-1] = (char)';';
pSrc += 2;
}
/* Invalid XML character */
- else if (ch <= 0x7F || ch >= 0xFFFE)
+ else if (ch <= 0x7F || ch >= 0xFFFE)
{
pDst = InvalidXmlChar(ch, pDst, true);
pSrc++;
pSrc += 2;
}
/* Invalid XML character */
- else if (ch <= 0x7F || ch >= 0xFFFE)
+ else if (ch <= 0x7F || ch >= 0xFFFE)
{
pDst = InvalidXmlChar(ch, pDst, true);
pSrc++;
pSrc += 2;
}
/* Invalid XML character */
- else if (ch <= 0x7F || ch >= 0xFFFE)
+ else if (ch <= 0x7F || ch >= 0xFFFE)
{
pDst = InvalidXmlChar(ch, pDst, false);
pSrc++;
pSrc += 2;
}
/* Invalid XML character */
- else if (ch <= 0x7F || ch >= 0xFFFE)
+ else if (ch <= 0x7F || ch >= 0xFFFE)
{
pDst = InvalidXmlChar(ch, pDst, false);
pSrc++;
pSrc += 2;
}
/* Invalid XML character */
- else if (ch <= 0x7F || ch >= 0xFFFE)
+ else if (ch <= 0x7F || ch >= 0xFFFE)
{
pDst = InvalidXmlChar(ch, pDst, false);
pSrc++;
pSrc += 2;
}
/* Invalid XML character */
- else if (ch <= 0x7F || ch >= 0xFFFE)
+ else if (ch <= 0x7F || ch >= 0xFFFE)
{
pDst = InvalidXmlChar(ch, pDst, false);
pSrc++;
{
read = input.Read(bytes, byteCount, bytes.Length - byteCount);
byteCount += read;
- } while (read > 0 && byteCount< 2);
+ } while (read > 0 && byteCount < 2);
// create text or binary XML reader depenting on the stream first 2 bytes
if (byteCount >= 2 && (bytes[0] == 0xdf && bytes[1] == 0xff))
}
}
- return AddValidationAndConformanceInternal(reader, resolver, addConformanceWrapper: false);
+ return AddValidationAndConformanceInternal(reader, resolver, addConformanceWrapper: false);
}
private XmlReader AddValidationAndConformanceWrapper(XmlReader reader)
resolver = GetXmlResolver_CheckConfig();
}
- return AddValidationAndConformanceInternal(reader, resolver, addConformanceWrapper: true);
+ return AddValidationAndConformanceInternal(reader, resolver, addConformanceWrapper: true);
}
private XmlReader AddValidationAndConformanceInternal(XmlReader reader, XmlResolver resolver, bool addConformanceWrapper)
if (_dtdInfo == null ||
((entity = _dtdInfo.LookupEntity(name)) == null))
{
- // Needed only for XmlTextReader (when used from XmlDocument)
+ // Needed only for XmlTextReader (when used from XmlDocument)
if (_disableUndeclaredEntityCheck)
{
SchemaEntity schemaEntity = new SchemaEntity(new XmlQualifiedName(name), false);
public virtual XmlSchemaDatatypeVariety Variety { get { return XmlSchemaDatatypeVariety.Atomic; } }
- internal XmlSchemaDatatype() {}
+ internal XmlSchemaDatatype() { }
public virtual object ChangeType(object value, Type targetType)
{
public abstract class XmlSchemaGroupBase : XmlSchemaParticle
{
- internal XmlSchemaGroupBase() {}
+ internal XmlSchemaGroupBase() { }
[XmlIgnore]
public abstract XmlSchemaObjectCollection Items { get; }
AddImport(intf, types);
ConstructorInfo[] ctors = type.GetConstructors();
- for (int i = 0; i<ctors.Length; i++)
+ for (int i = 0; i < ctors.Length; i++)
{
ParameterInfo[] parms = ctors[i].GetParameters();
- for (int j = 0; j<parms.Length; j++)
+ for (int j = 0; j < parms.Length; j++)
{
AddImport(parms[j].ParameterType, types);
}
if (type.IsGenericType)
{
Type[] arguments = type.GetGenericArguments();
- for (int i = 0; i<arguments.Length; i++)
+ for (int i = 0; i < arguments.Length; i++)
{
AddImport(arguments[i], types);
}
}
}
- private bool CanOptimizeWriteListSequence(TypeDesc listElementTypeDesc) {
+ private bool CanOptimizeWriteListSequence(TypeDesc listElementTypeDesc)
+ {
// check to see if we can write values of the attribute sequentially
// currently we have only one data type (XmlQualifiedName) that we can not write "inline",
// because we need to output xmlns:qx="..." for each of the qnames
{
if (mapping.Members[j].Name == memberNameSpecified)
{
- specifiedSource = (bool) p[j];
+ specifiedSource = (bool)p[j];
break;
}
}
}
}
- public static implicit operator string (SourceInfo source)
+ public static implicit operator string(SourceInfo source)
{
return source.Source;
}
}
}
#if DEBUG
- // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
- if (choiceSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Can not find " + member.ChoiceIdentifier.MemberName + " in the members mapping."));
+ // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
+ if (choiceSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Can not find " + member.ChoiceIdentifier.MemberName + " in the members mapping."));
#endif
}
string methodName = ReferenceMapping(derived);
#if DEBUG
- // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
- if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name));
+ // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
+ if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name));
#endif
Writer.Write("return ");
Writer.WriteLine("Reader.ReadStartElement();");
string methodName = ReferenceMapping(mapping);
#if DEBUG
- // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
- if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name));
+ // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
+ if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name));
#endif
Writer.Write("object e = ");
Writer.Write(methodName);
{
string methodName = ReferenceMapping(mapping);
#if DEBUG
- // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
- if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name));
+ // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
+ if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name));
#endif
if (checkForNull)
if (choice != null)
{
#if DEBUG
- // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
- if (choiceSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "need parent for the " + source));
+ // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
+ if (choiceSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "need parent for the " + source));
#endif
string enumTypeName = choice.Mapping.TypeDesc.CSharpName;
internal static string GetName(Assembly a)
{
- return s_assemblyToNameMap != null ? (string) s_assemblyToNameMap[a] : null;
+ return s_assemblyToNameMap != null ? (string)s_assemblyToNameMap[a] : null;
}
}
string methodName = ReferenceMapping(mapping);
#if DEBUG
- // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
- if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name) + Environment.StackTrace);
+ // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
+ if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name) + Environment.StackTrace);
#endif
Writer.Write(methodName);
if (mapping is EnumMapping)
{
#if DEBUG
- // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
- if (defaultValue.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, name + " has invalid default type " + defaultValue.GetType().Name));
+ // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
+ if (defaultValue.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, name + " has invalid default type " + defaultValue.GetType().Name));
#endif
Writer.Write("if (");
}
#if DEBUG
- // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
- if (enumSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Can not find " + member.ChoiceIdentifier.MemberName + " in the members mapping."));
+ // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
+ if (enumSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Can not find " + member.ChoiceIdentifier.MemberName + " in the members mapping."));
#endif
}
string methodName = ReferenceMapping(derived);
#if DEBUG
- // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
- if (methodName == null) throw new InvalidOperationException("derived from " + mapping.TypeDesc.FullName + ", " + SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name) + Environment.StackTrace);
+ // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
+ if (methodName == null) throw new InvalidOperationException("derived from " + mapping.TypeDesc.FullName + ", " + SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name) + Environment.StackTrace);
#endif
Writer.Write(methodName);
string methodName = ReferenceMapping(mapping);
#if DEBUG
- // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
- if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name) + Environment.StackTrace);
+ // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
+ if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name) + Environment.StackTrace);
#endif
Writer.WriteLine("Writer.WriteStartElement(n, ns);");
Writer.Write("WriteXsiType(");
string methodName = ReferenceMapping(mapping);
#if DEBUG
- // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
- if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name) + Environment.StackTrace);
+ // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
+ if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name) + Environment.StackTrace);
#endif
Writer.Write(methodName);
Writer.Write("(");
Writer.Write("!");
Writer.Write(source);
Writer.Write(".Equals(");
- Type type= Type.GetType(mapping.TypeDesc.Type.FullName);
+ Type type = Type.GetType(mapping.TypeDesc.Type.FullName);
WriteValue(type != null ? Convert.ChangeType(value, type) : value);
Writer.Write(")");
}
set { _value = value; }
}
- public static implicit operator string (QilLiteral literal)
+ public static implicit operator string(QilLiteral literal)
{
return (string)literal._value;
}
- public static implicit operator int (QilLiteral literal)
+ public static implicit operator int(QilLiteral literal)
{
return (int)literal._value;
}
- public static implicit operator long (QilLiteral literal)
+ public static implicit operator long(QilLiteral literal)
{
return (long)literal._value;
}
- public static implicit operator double (QilLiteral literal)
+ public static implicit operator double(QilLiteral literal)
{
return (double)literal._value;
}
- public static implicit operator decimal (QilLiteral literal)
+ public static implicit operator decimal(QilLiteral literal)
{
return (decimal)literal._value;
}
}
}
- public static implicit operator int (Options options)
+ public static implicit operator int(Options options)
{
return options._value;
}
}
// Get the double value.
- public static explicit operator double (BigNumber bn)
+ public static explicit operator double(BigNumber bn)
{
uint uEx;
int exp;
Returns the double value of this floating decimal.
*/
- public static explicit operator double (FloatingDecimal dec)
+ public static explicit operator double(FloatingDecimal dec)
{
BigNumber num, numHi, numLo;
uint ul;
_prefix = rec.prefix;
_localName = rec.localName;
}
- public static implicit operator string (DelayedQName qn)
+ public static implicit operator string(DelayedQName qn)
{
return qn._prefix.Length == 0 ? qn._localName : (qn._prefix + ':' + qn._localName);
}
if (left.IsStatic != right.IsStatic)
return false;
- if ( left.Name != right.Name)
+ if (left.Name != right.Name)
return false;
Type[] leftGenericParameters = left.GetGenericArguments();
public Guid ReadGuid()
{
const int size = 16;
- byte * ptr = GetCurrentPointerAndAdvance(size);
+ byte* ptr = GetCurrentPointerAndAdvance(size);
if (BitConverter.IsLittleEndian)
{
return *(Guid*)ptr;
public static PEHeaderBuilder CreateExecutableHeader()
{
- return new PEHeaderBuilder(imageCharacteristics : Characteristics.ExecutableImage);
+ return new PEHeaderBuilder(imageCharacteristics: Characteristics.ExecutableImage);
}
public static PEHeaderBuilder CreateLibraryHeader()
int newMin = FindMostSpecificMethod(
candidates[currentMin],
paramOrder,
- paramArrayType1:null,
+ paramArrayType1: null,
candidates[i],
paramOrder,
- paramArrayType2:null,
- types, args:null);
+ paramArrayType2: null,
+ types, args: null);
if (newMin == 0)
{
newMin = FindMostSpecific(
candidates[currentMin].GetIndexParameters(),
paramOrder,
- paramArrayType1:null,
+ paramArrayType1: null,
candidates[i].GetIndexParameters(),
paramOrder,
paramArrayType2: null,
indexes,
- args:null);
+ args: null);
if (newMin == 0)
{
throw new BadImageFormatException(SR.NoMetadataInPeImage);
string location = (peStream is FileStream fs) ? (fs.Name ?? string.Empty) : string.Empty;
- MetadataReader reader = peReader.GetMetadataReader();
+ MetadataReader reader = peReader.GetMetadataReader();
RoAssembly candidate = new EcmaAssembly(this, peReader, reader, location);
AssemblyNameData defNameData = candidate.GetAssemblyNameDataNoCopy();
byte[] pkt = defNameData.PublicKeyToken ?? Array.Empty<byte>();
if (br.RemainingBytes == 0)
break;
- ma.MarshalType = br.ReadSerializedString();
+ ma.MarshalType = br.ReadSerializedString();
ma.MarshalTypeRef = Helpers.LoadTypeFromAssemblyQualifiedName(ma.MarshalType, module.GetRoAssembly(), ignoreCase: false, throwOnError: false);
if (br.RemainingBytes == 0)
{
internal static class Utf8Constants
{
- public static readonly byte[] System = {83, 121, 115, 116, 101, 109};
- public static readonly byte[] SystemReflection = {83, 121, 115, 116, 101, 109, 46, 82, 101, 102, 108, 101, 99, 116, 105, 111, 110};
- public static readonly byte[] SystemCollectionsGeneric = {83, 121, 115, 116, 101, 109, 46, 67, 111, 108, 108, 101, 99, 116, 105, 111, 110, 115, 46, 71, 101, 110, 101, 114, 105, 99};
- public static readonly byte[] SystemRuntimeInteropServices = {83, 121, 115, 116, 101, 109, 46, 82, 117, 110, 116, 105, 109, 101, 46, 73, 110, 116, 101, 114, 111, 112, 83, 101, 114, 118, 105, 99, 101, 115};
- public static readonly byte[] SystemRuntimeCompilerServices = {83, 121, 115, 116, 101, 109, 46, 82, 117, 110, 116, 105, 109, 101, 46, 67, 111, 109, 112, 105, 108, 101, 114, 83, 101, 114, 118, 105, 99, 101, 115};
+ public static readonly byte[] System = { 83, 121, 115, 116, 101, 109 };
+ public static readonly byte[] SystemReflection = { 83, 121, 115, 116, 101, 109, 46, 82, 101, 102, 108, 101, 99, 116, 105, 111, 110 };
+ public static readonly byte[] SystemCollectionsGeneric = { 83, 121, 115, 116, 101, 109, 46, 67, 111, 108, 108, 101, 99, 116, 105, 111, 110, 115, 46, 71, 101, 110, 101, 114, 105, 99 };
+ public static readonly byte[] SystemRuntimeInteropServices = { 83, 121, 115, 116, 101, 109, 46, 82, 117, 110, 116, 105, 109, 101, 46, 73, 110, 116, 101, 114, 111, 112, 83, 101, 114, 118, 105, 99, 101, 115 };
+ public static readonly byte[] SystemRuntimeCompilerServices = { 83, 121, 115, 116, 101, 109, 46, 82, 117, 110, 116, 105, 109, 101, 46, 67, 111, 109, 112, 105, 108, 101, 114, 83, 101, 114, 118, 105, 99, 101, 115 };
- public static readonly byte[] Array = {65, 114, 114, 97, 121};
- public static readonly byte[] Boolean = {66, 111, 111, 108, 101, 97, 110};
- public static readonly byte[] Byte = {66, 121, 116, 101};
- public static readonly byte[] Char = {67, 104, 97, 114};
- public static readonly byte[] Double = {68, 111, 117, 98, 108, 101};
- public static readonly byte[] Enum = {69, 110, 117, 109};
- public static readonly byte[] Int16 = {73, 110, 116, 49, 54};
- public static readonly byte[] Int32 = {73, 110, 116, 51, 50};
- public static readonly byte[] Int64 = {73, 110, 116, 54, 52};
- public static readonly byte[] IntPtr = {73, 110, 116, 80, 116, 114};
- public static readonly byte[] Object = {79, 98, 106, 101, 99, 116};
+ public static readonly byte[] Array = { 65, 114, 114, 97, 121 };
+ public static readonly byte[] Boolean = { 66, 111, 111, 108, 101, 97, 110 };
+ public static readonly byte[] Byte = { 66, 121, 116, 101 };
+ public static readonly byte[] Char = { 67, 104, 97, 114 };
+ public static readonly byte[] Double = { 68, 111, 117, 98, 108, 101 };
+ public static readonly byte[] Enum = { 69, 110, 117, 109 };
+ public static readonly byte[] Int16 = { 73, 110, 116, 49, 54 };
+ public static readonly byte[] Int32 = { 73, 110, 116, 51, 50 };
+ public static readonly byte[] Int64 = { 73, 110, 116, 54, 52 };
+ public static readonly byte[] IntPtr = { 73, 110, 116, 80, 116, 114 };
+ public static readonly byte[] Object = { 79, 98, 106, 101, 99, 116 };
public static readonly byte[] NullableT = { 78, 117, 108, 108, 97, 98, 108, 101, 96, 49 };
- public static readonly byte[] SByte = {83, 66, 121, 116, 101};
- public static readonly byte[] Single = {83, 105, 110, 103, 108, 101};
- public static readonly byte[] String = {83, 116, 114, 105, 110, 103};
- public static readonly byte[] TypedReference = {84, 121, 112, 101, 100, 82, 101, 102, 101, 114, 101, 110, 99, 101};
- public static readonly byte[] UInt16 = {85, 73, 110, 116, 49, 54};
- public static readonly byte[] UInt32 = {85, 73, 110, 116, 51, 50};
- public static readonly byte[] UInt64 = {85, 73, 110, 116, 54, 52};
- public static readonly byte[] UIntPtr = {85, 73, 110, 116, 80, 116, 114};
- public static readonly byte[] ValueType = {86, 97, 108, 117, 101, 84, 121, 112, 101};
- public static readonly byte[] Void = {86, 111, 105, 100};
- public static readonly byte[] MulticastDelegate = {77, 117, 108, 116, 105, 99, 97, 115, 116, 68, 101, 108, 101, 103, 97, 116, 101};
- public static readonly byte[] IEnumerableT = {73, 69, 110, 117, 109, 101, 114, 97, 98, 108, 101, 96, 49};
- public static readonly byte[] ICollectionT = {73, 67, 111, 108, 108, 101, 99, 116, 105, 111, 110, 96, 49};
- public static readonly byte[] IListT = {73, 76, 105, 115, 116, 96, 49};
- public static readonly byte[] IReadOnlyListT = {73, 82, 101, 97, 100, 79, 110, 108, 121, 76, 105, 115, 116, 96, 49};
- public static readonly byte[] Type = {84, 121, 112, 101};
- public static readonly byte[] DBNull = {68, 66, 78, 117, 108, 108};
- public static readonly byte[] Decimal = {68, 101, 99, 105, 109, 97, 108};
- public static readonly byte[] DateTime = {68, 97, 116, 101, 84, 105, 109, 101};
- public static readonly byte[] ComImportAttribute = {67, 111, 109, 73, 109, 112, 111, 114, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101};
- public static readonly byte[] DllImportAttribute = {68, 108, 108, 73, 109, 112, 111, 114, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101};
- public static readonly byte[] CallingConvention = {67, 97, 108, 108, 105, 110, 103, 67, 111, 110, 118, 101, 110, 116, 105, 111, 110};
- public static readonly byte[] CharSet = {67, 104, 97, 114, 83, 101, 116};
- public static readonly byte[] MarshalAsAttribute = {77, 97, 114, 115, 104, 97, 108, 65, 115, 65, 116, 116, 114, 105, 98, 117, 116, 101};
- public static readonly byte[] UnmanagedType = {85, 110, 109, 97, 110, 97, 103, 101, 100, 84, 121, 112, 101};
- public static readonly byte[] VarEnum = {86, 97, 114, 69, 110, 117, 109};
- public static readonly byte[] InAttribute = {73, 110, 65, 116, 116, 114, 105, 98, 117, 116, 101};
- public static readonly byte[] OutAttriubute = {79, 117, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101};
- public static readonly byte[] OptionalAttribute = {79, 112, 116, 105, 111, 110, 97, 108, 65, 116, 116, 114, 105, 98, 117, 116, 101};
- public static readonly byte[] PreserveSigAttribute = {80, 114, 101, 115, 101, 114, 118, 101, 83, 105, 103, 65, 116, 116, 114, 105, 98, 117, 116, 101};
- public static readonly byte[] FieldOffsetAttribute = {70, 105, 101, 108, 100, 79, 102, 102, 115, 101, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101};
- public static readonly byte[] IsByRefLikeAttribute = {73, 115, 66, 121, 82, 101, 102, 76, 105, 107, 101, 65, 116, 116, 114, 105, 98, 117, 116, 101};
- public static readonly byte[] DecimalConstantAttribute = {68, 101, 99, 105, 109, 97, 108, 67, 111, 110, 115, 116, 97, 110, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101};
- public static readonly byte[] CustomConstantAttribute = {67, 117, 115, 116, 111, 109, 67, 111, 110, 115, 116, 97, 110, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101};
- public static readonly byte[] GuidAttribute = {71, 117, 105, 100, 65, 116, 116, 114, 105, 98, 117, 116, 101};
- public static readonly byte[] DefaultMemberAttribute = {68, 101, 102, 97, 117, 108, 116, 77, 101, 109, 98, 101, 114, 65, 116, 116, 114, 105, 98, 117, 116, 101};
+ public static readonly byte[] SByte = { 83, 66, 121, 116, 101 };
+ public static readonly byte[] Single = { 83, 105, 110, 103, 108, 101 };
+ public static readonly byte[] String = { 83, 116, 114, 105, 110, 103 };
+ public static readonly byte[] TypedReference = { 84, 121, 112, 101, 100, 82, 101, 102, 101, 114, 101, 110, 99, 101 };
+ public static readonly byte[] UInt16 = { 85, 73, 110, 116, 49, 54 };
+ public static readonly byte[] UInt32 = { 85, 73, 110, 116, 51, 50 };
+ public static readonly byte[] UInt64 = { 85, 73, 110, 116, 54, 52 };
+ public static readonly byte[] UIntPtr = { 85, 73, 110, 116, 80, 116, 114 };
+ public static readonly byte[] ValueType = { 86, 97, 108, 117, 101, 84, 121, 112, 101 };
+ public static readonly byte[] Void = { 86, 111, 105, 100 };
+ public static readonly byte[] MulticastDelegate = { 77, 117, 108, 116, 105, 99, 97, 115, 116, 68, 101, 108, 101, 103, 97, 116, 101 };
+ public static readonly byte[] IEnumerableT = { 73, 69, 110, 117, 109, 101, 114, 97, 98, 108, 101, 96, 49 };
+ public static readonly byte[] ICollectionT = { 73, 67, 111, 108, 108, 101, 99, 116, 105, 111, 110, 96, 49 };
+ public static readonly byte[] IListT = { 73, 76, 105, 115, 116, 96, 49 };
+ public static readonly byte[] IReadOnlyListT = { 73, 82, 101, 97, 100, 79, 110, 108, 121, 76, 105, 115, 116, 96, 49 };
+ public static readonly byte[] Type = { 84, 121, 112, 101 };
+ public static readonly byte[] DBNull = { 68, 66, 78, 117, 108, 108 };
+ public static readonly byte[] Decimal = { 68, 101, 99, 105, 109, 97, 108 };
+ public static readonly byte[] DateTime = { 68, 97, 116, 101, 84, 105, 109, 101 };
+ public static readonly byte[] ComImportAttribute = { 67, 111, 109, 73, 109, 112, 111, 114, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
+ public static readonly byte[] DllImportAttribute = { 68, 108, 108, 73, 109, 112, 111, 114, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
+ public static readonly byte[] CallingConvention = { 67, 97, 108, 108, 105, 110, 103, 67, 111, 110, 118, 101, 110, 116, 105, 111, 110 };
+ public static readonly byte[] CharSet = { 67, 104, 97, 114, 83, 101, 116 };
+ public static readonly byte[] MarshalAsAttribute = { 77, 97, 114, 115, 104, 97, 108, 65, 115, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
+ public static readonly byte[] UnmanagedType = { 85, 110, 109, 97, 110, 97, 103, 101, 100, 84, 121, 112, 101 };
+ public static readonly byte[] VarEnum = { 86, 97, 114, 69, 110, 117, 109 };
+ public static readonly byte[] InAttribute = { 73, 110, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
+ public static readonly byte[] OutAttriubute = { 79, 117, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
+ public static readonly byte[] OptionalAttribute = { 79, 112, 116, 105, 111, 110, 97, 108, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
+ public static readonly byte[] PreserveSigAttribute = { 80, 114, 101, 115, 101, 114, 118, 101, 83, 105, 103, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
+ public static readonly byte[] FieldOffsetAttribute = { 70, 105, 101, 108, 100, 79, 102, 102, 115, 101, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
+ public static readonly byte[] IsByRefLikeAttribute = { 73, 115, 66, 121, 82, 101, 102, 76, 105, 107, 101, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
+ public static readonly byte[] DecimalConstantAttribute = { 68, 101, 99, 105, 109, 97, 108, 67, 111, 110, 115, 116, 97, 110, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
+ public static readonly byte[] CustomConstantAttribute = { 67, 117, 115, 116, 111, 109, 67, 111, 110, 115, 116, 97, 110, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
+ public static readonly byte[] GuidAttribute = { 71, 117, 105, 100, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
+ public static readonly byte[] DefaultMemberAttribute = { 68, 101, 102, 97, 117, 108, 116, 77, 101, 109, 98, 101, 114, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
public static readonly byte[] DateTimeConstantAttribute = { 68, 97, 116, 101, 84, 105, 109, 101, 67, 111, 110, 115, 116, 97, 110, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101 };
}
}
public sealed override Guid ModuleVersionId => ModuleDefinition.Mvid.GetGuid(Reader);
public sealed override string ScopeName => ModuleDefinition.Name.GetString(Reader);
- public sealed override IEnumerable<CustomAttributeData> CustomAttributes => ModuleDefinition.GetCustomAttributes().ToTrueCustomAttributes(this);
+ public sealed override IEnumerable<CustomAttributeData> CustomAttributes => ModuleDefinition.GetCustomAttributes().ToTrueCustomAttributes(this);
internal MethodInfo ComputeEntryPoint(bool fileRefEntryPointAllowed)
{
MemberInfo[] results;
- if ((results = QuerySpecificMemberTypeIfRequested(type, optionalName, bindingAttr, predicate, MemberTypes.Method, out QueryResult<MethodInfo> methods)) != null)
+ if ((results = QuerySpecificMemberTypeIfRequested(type, optionalName, bindingAttr, predicate, MemberTypes.Method, out QueryResult<MethodInfo> methods)) != null)
return results;
- if ((results = QuerySpecificMemberTypeIfRequested(type, optionalName, bindingAttr, predicate, MemberTypes.Constructor, out QueryResult<ConstructorInfo> constructors)) != null)
+ if ((results = QuerySpecificMemberTypeIfRequested(type, optionalName, bindingAttr, predicate, MemberTypes.Constructor, out QueryResult<ConstructorInfo> constructors)) != null)
return results;
if ((results = QuerySpecificMemberTypeIfRequested(type, optionalName, bindingAttr, predicate, MemberTypes.Property, out QueryResult<PropertyInfo> properties)) != null)
return results;
internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter filter, Type reflectedType)
{
- int rank =_rank;
+ int rank = _rank;
int uniquifier = 0;
RoType systemInt32 = Loader.GetCoreType(CoreType.Int32);
}
return token;
- }
+ }
}
public static class MethodInfoExtensions
ReadOnlySpan<char> typeSpan = assemblyQualifiedTypeName.AsSpan().TrimStart(s_whiteSpaceChars);
ReadOnlySpan<char> typeName = ReadTypeName(typeSpan);
- int hashCode = 0;
+ int hashCode = 0;
for (int i = 0; i < typeName.Length; i++)
{
hashCode = HashHelpers.Combine(hashCode, typeName[i].GetHashCode());
namespace System.Resources
{
//internal sealed class FastResourceComparer : IComparer, IEqualityComparer, IComparer<String>, IEqualityComparer<String>
- internal sealed class FastResourceComparer :IComparer<string>, IEqualityComparer<string>
+ internal sealed class FastResourceComparer : IComparer<string>, IEqualityComparer<string>
{
internal static readonly FastResourceComparer Default = new FastResourceComparer();
[AttributeUsage(AttributeTargets.All)]
internal sealed class DecoratedNameAttribute : Attribute
{
- public DecoratedNameAttribute(string decoratedName) {}
+ public DecoratedNameAttribute(string decoratedName) { }
}
// Indicates that the modified instance is pinned in memory.
public NativeCppClassAttribute() { }
}
- [AttributeUsage (AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface, AllowMultiple=true, Inherited=false)]
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
public sealed class RequiredAttributeAttribute : Attribute
{
public RequiredAttributeAttribute(Type requiredContract) => RequiredContract = requiredContract;
HResult = HResults.COR_E_CONTEXTMARSHAL;
}
- protected ContextMarshalException(SerializationInfo info, StreamingContext context): base(info, context)
+ protected ContextMarshalException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
public LoaderOptimizationAttribute(LoaderOptimization value)
{
- _val = (byte) value;
+ _val = (byte)value;
}
public LoaderOptimization Value => (LoaderOptimization)_val;
}
: base(SR.Arg_SwitchExpressionException) { }
public SwitchExpressionException(Exception? innerException) :
- base(SR.Arg_SwitchExpressionException, innerException) { }
+ base(SR.Arg_SwitchExpressionException, innerException)
+ {
+ }
public SwitchExpressionException(object? unmatchedValue) : this()
{
safeName.Append('r');
safeName.Append(clrID);
}
- if ((requires & SxSRequirements.AppDomainID) != 0) {
+ if ((requires & SxSRequirements.AppDomainID) != 0)
+ {
safeName.Append(separator);
safeName.Append("ad");
safeName.Append(AppDomain.CurrentDomain.Id);
[ComImport]
[Guid("0000010E-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
- public interface IDataObject {
+ public interface IDataObject
+ {
/// <summary>
/// Called by a data consumer to obtain data from a source data object.
/// in NULL for that parameter).
/// </summary>
[PreserveSig]
- int Next(int celt, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] STATDATA[] rgelt, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst=1)] int[] pceltFetched);
+ int Next(int celt, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] STATDATA[] rgelt, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] int[] pceltFetched);
/// <summary>
/// Skips over the next specified number of elements in the enumeration sequence.
{
}
- public BigInteger(ReadOnlySpan<byte> value, bool isUnsigned=false, bool isBigEndian=false)
+ public BigInteger(ReadOnlySpan<byte> value, bool isUnsigned = false, bool isBigEndian = false)
{
int byteCount = value.Length;
/// </item>
/// </list>
/// </remarks>
- public byte[] ToByteArray(bool isUnsigned=false, bool isBigEndian=false)
+ public byte[] ToByteArray(bool isUnsigned = false, bool isBigEndian = false)
{
int ignored = 0;
return TryGetBytes(GetBytesMode.AllocateArray, default, isUnsigned, isBigEndian, ref ignored);
/// <param name="isBigEndian">Whether or not to write the bytes in a big-endian byte order</param>
/// <returns>true if the bytes fit in <paramref name="destination"/>; false if not all bytes could be written due to lack of space.</returns>
/// <exception cref="OverflowException">If <paramref name="isUnsigned"/> is <c>true</c> and <see cref="Sign"/> is negative.</exception>
- public bool TryWriteBytes(Span<byte> destination, out int bytesWritten, bool isUnsigned=false, bool isBigEndian=false)
+ public bool TryWriteBytes(Span<byte> destination, out int bytesWritten, bool isUnsigned = false, bool isBigEndian = false)
{
bytesWritten = 0;
if (TryGetBytes(GetBytesMode.Span, destination, isUnsigned, isBigEndian, ref bytesWritten) == null)
/// <summary>Gets the number of bytes that will be output by <see cref="ToByteArray(bool, bool)"/> and <see cref="TryWriteBytes(Span{byte}, out int, bool, bool)"/>.</summary>
/// <returns>The number of bytes.</returns>
- public int GetByteCount(bool isUnsigned=false)
+ public int GetByteCount(bool isUnsigned = false)
{
int count = 0;
// Big or Little Endian doesn't matter for the byte count.
return new Complex(u, v);
}
- public static Complex Cos(Complex value) {
+ public static Complex Cos(Complex value)
+ {
double p = Math.Exp(value.m_imaginary);
double q = 1.0 / p;
double sinh = (p - q) * 0.5;
return (ImaginaryOne / two) * (Log(One - ImaginaryOne * value) - Log(One + ImaginaryOne * value));
}
- private static void Asin_Internal (double x, double y, out double b, out double bPrime, out double v) {
+ private static void Asin_Internal(double x, double y, out double b, out double bPrime, out double v)
+ {
// This method for the inverse complex sine (and cosine) is described in Hull, Fairgrieve,
// and Tang, "Implementing the Complex Arcsine and Arccosine Functions Using Exception Handling",
}
else
{
- return index > _objects.Length - 1 ? null : _objects[index];
+ return index > _objects.Length - 1 ? null : _objects[index];
}
}
set
}
protected LayoutCycleException(SerializationInfo serializationInfo, StreamingContext streamingContext)
- : base (serializationInfo, streamingContext)
+ : base(serializationInfo, streamingContext)
{
}
}
#region State bit field operations
- internal bool CompletedSynchronously {[Pure] get { return (0 != (_state & STATEFLAG_COMPLETED_SYNCHRONOUSLY)); } }
+ internal bool CompletedSynchronously { [Pure] get { return (0 != (_state & STATEFLAG_COMPLETED_SYNCHRONOUSLY)); } }
- private bool IsInStartedState {[Pure] get { return (0 != (_state & STATE_STARTED)); } }
+ private bool IsInStartedState { [Pure] get { return (0 != (_state & STATE_STARTED)); } }
- private bool IsInRunToCompletionState {[Pure] get { return (0 != (_state & STATE_RUN_TO_COMPLETION)); } }
+ private bool IsInRunToCompletionState { [Pure] get { return (0 != (_state & STATE_RUN_TO_COMPLETION)); } }
- private bool IsInErrorState {[Pure] get { return (0 != (_state & STATE_ERROR)); } }
+ private bool IsInErrorState { [Pure] get { return (0 != (_state & STATE_ERROR)); } }
- private bool IsInClosedState {[Pure] get { return (0 != (_state & STATE_CLOSED)); } }
+ private bool IsInClosedState { [Pure] get { return (0 != (_state & STATE_CLOSED)); } }
private bool IsInRunningState
{
#region Constructors
- internal AceEnumerator( GenericAcl collection )
+ internal AceEnumerator(GenericAcl collection)
{
- if ( collection == null )
+ if (collection == null)
{
- throw new ArgumentNullException( nameof(collection));
+ throw new ArgumentNullException(nameof(collection));
}
_acl = collection;
{
get
{
- if ( _current == -1 ||
- _current >= _acl.Count )
+ if (_current == -1 ||
+ _current >= _acl.Count)
{
- throw new InvalidOperationException( SR.Arg_InvalidOperationException );
+ throw new InvalidOperationException(SR.Arg_InvalidOperationException);
}
return _acl[_current];
public GenericAce Current
{
- get { return (( IEnumerator )this ).Current as GenericAce; }
+ get { return ((IEnumerator)this).Current as GenericAce; }
}
public bool MoveNext()
{
_current++;
- return ( _current < _acl.Count );
+ return (_current < _acl.Count);
}
public void Reset()
// Returns the binary representation of the ACL
//
- public abstract void GetBinaryForm( byte[] binaryForm, int offset );
+ public abstract void GetBinaryForm(byte[] binaryForm, int offset);
#endregion
#region ICollection Implementation
- void ICollection.CopyTo( Array array, int index )
+ void ICollection.CopyTo(Array array, int index)
{
- if ( array == null )
+ if (array == null)
{
- throw new ArgumentNullException( nameof(array));
+ throw new ArgumentNullException(nameof(array));
}
- if ( array.Rank != 1 )
+ if (array.Rank != 1)
{
- throw new RankException( SR.Rank_MultiDimNotSupported );
+ throw new RankException(SR.Rank_MultiDimNotSupported);
}
- if ( index < 0 )
+ if (index < 0)
{
- throw new ArgumentOutOfRangeException(
-nameof(index),
- SR.ArgumentOutOfRange_NeedNonNegNum );
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- else if ( array.Length - index < Count )
+ else if (array.Length - index < Count)
{
- throw new ArgumentOutOfRangeException(
-nameof(array),
- SR.ArgumentOutOfRange_ArrayTooSmall );
+ throw new ArgumentOutOfRangeException(nameof(array), SR.ArgumentOutOfRange_ArrayTooSmall);
}
- for ( int i = 0; i < Count; i++ )
+ for (int i = 0; i < Count; i++)
{
- array.SetValue( this[i], index + i );
+ array.SetValue(this[i], index + i);
}
}
- public void CopyTo( GenericAce[] array, int index )
+ public void CopyTo(GenericAce[] array, int index)
{
- (( ICollection )this ).CopyTo( array, index );
+ ((ICollection)this).CopyTo(array, index);
}
public abstract int Count { get; }
IEnumerator IEnumerable.GetEnumerator()
{
- return new AceEnumerator( this );
+ return new AceEnumerator(this);
}
public AceEnumerator GetEnumerator()
{
- return (( IEnumerable )this ).GetEnumerator() as AceEnumerator;
+ return ((IEnumerable)this).GetEnumerator() as AceEnumerator;
}
#endregion
#region Private Methods
- private static void VerifyHeader( byte[] binaryForm, int offset, out byte revision, out int count, out int length )
+ private static void VerifyHeader(byte[] binaryForm, int offset, out byte revision, out int count, out int length)
{
- if ( binaryForm == null )
+ if (binaryForm == null)
{
- throw new ArgumentNullException( nameof(binaryForm));
+ throw new ArgumentNullException(nameof(binaryForm));
}
- if ( offset < 0 )
+ if (offset < 0)
{
//
// Offset must not be negative
//
- throw new ArgumentOutOfRangeException(
-nameof(offset),
- SR.ArgumentOutOfRange_NeedNonNegNum );
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if ( binaryForm.Length - offset < HeaderLength )
+ if (binaryForm.Length - offset < HeaderLength)
{
//
// We expect at least the ACL header
}
revision = binaryForm[offset + 0];
- length = ( binaryForm[offset + 2] << 0 ) + ( binaryForm[offset + 3] << 8 );
- count = ( binaryForm[offset + 4] << 0 ) + ( binaryForm[offset + 5] << 8 );
+ length = (binaryForm[offset + 2] << 0) + (binaryForm[offset + 3] << 8);
+ count = (binaryForm[offset + 4] << 0) + (binaryForm[offset + 5] << 8);
- if ( length > binaryForm.Length - offset )
+ if (length > binaryForm.Length - offset)
{
//
// Reported length of ACL ought to be no longer than the
InvalidParameter:
- throw new ArgumentOutOfRangeException(
-nameof(binaryForm),
- SR.ArgumentOutOfRange_ArrayTooSmall );
+ throw new ArgumentOutOfRangeException(nameof(binaryForm), SR.ArgumentOutOfRange_ArrayTooSmall);
}
- private void MarshalHeader( byte[] binaryForm, int offset )
+ private void MarshalHeader(byte[] binaryForm, int offset)
{
- if ( binaryForm == null )
+ if (binaryForm == null)
{
- throw new ArgumentNullException( nameof(binaryForm));
+ throw new ArgumentNullException(nameof(binaryForm));
}
- else if ( offset < 0 )
+ else if (offset < 0)
{
- throw new ArgumentOutOfRangeException(
-nameof(offset),
- SR.ArgumentOutOfRange_NeedNonNegNum );
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- else if ( BinaryLength > MaxBinaryLength )
+ else if (BinaryLength > MaxBinaryLength)
{
- throw new InvalidOperationException( SR.AccessControl_AclTooLong );
+ throw new InvalidOperationException(SR.AccessControl_AclTooLong);
}
- else if ( binaryForm.Length - offset < BinaryLength )
+ else if (binaryForm.Length - offset < BinaryLength)
{
- throw new ArgumentOutOfRangeException(
-nameof(binaryForm),
- SR.ArgumentOutOfRange_ArrayTooSmall );
+ throw new ArgumentOutOfRangeException(nameof(binaryForm), SR.ArgumentOutOfRange_ArrayTooSmall);
}
binaryForm[offset + 0] = Revision;
binaryForm[offset + 1] = 0;
- binaryForm[offset + 2] = unchecked(( byte )( BinaryLength >> 0 ));
- binaryForm[offset + 3] = ( byte )( BinaryLength >> 8 );
- binaryForm[offset + 4] = unchecked(( byte )( Count >> 0 ));
- binaryForm[offset + 5] = ( byte )( Count >> 8 );
+ binaryForm[offset + 2] = unchecked((byte)(BinaryLength >> 0));
+ binaryForm[offset + 3] = (byte)(BinaryLength >> 8);
+ binaryForm[offset + 4] = unchecked((byte)(Count >> 0));
+ binaryForm[offset + 5] = (byte)(Count >> 8);
binaryForm[offset + 6] = 0;
binaryForm[offset + 7] = 0;
}
- internal void SetBinaryForm( byte[] binaryForm, int offset )
+ internal void SetBinaryForm(byte[] binaryForm, int offset)
{
int count, length;
// Verify the header and extract interesting header info
//
- VerifyHeader( binaryForm, offset, out _revision, out count, out length );
+ VerifyHeader(binaryForm, offset, out _revision, out count, out length);
//
// Remember how far ahead the binary form should end (for later verification)
offset += HeaderLength;
- _aces = new List<GenericAce>( count );
+ _aces = new List<GenericAce>(count);
int binaryLength = HeaderLength;
- for ( int i = 0; i < count; i++ )
+ for (int i = 0; i < count; i++)
{
- GenericAce ace = GenericAce.CreateFromBinaryForm( binaryForm, offset );
+ GenericAce ace = GenericAce.CreateFromBinaryForm(binaryForm, offset);
int aceLength = ace.BinaryLength;
- if ( binaryLength + aceLength > MaxBinaryLength )
+ if (binaryLength + aceLength > MaxBinaryLength)
{
//
// The ACE was too long - it would overflow the ACL maximum length
throw new ArgumentException(SR.ArgumentException_InvalidAclBinaryForm, nameof(binaryForm));
}
- _aces.Add( ace );
+ _aces.Add(ace);
- if ( aceLength % 4 != 0 )
+ if (aceLength % 4 != 0)
{
//
// This indicates a bug in one of the ACE classes.
// Binary length of an ace must ALWAYS be divisible by 4.
//
- Debug.Assert( false, "aceLength % 4 != 0" );
+ Debug.Assert(false, "aceLength % 4 != 0");
// Replacing SystemException with InvalidOperationException. This code path
// indicates a bad ACE, but I don't know of a great exception to represent that.
// InvalidOperation seems to be the closest, though it's definitely not exactly
binaryLength += aceLength;
- if ( _revision == AclRevisionDS )
+ if (_revision == AclRevisionDS)
{
//
// Increment the offset by the advertised length rather than the
// Verify that no more than the advertised length of the ACL was consumed
//
- if ( offset > length )
+ if (offset > length)
{
goto InvalidParameter;
}
// Creates an empty ACL
//
- public RawAcl( byte revision, int capacity )
+ public RawAcl(byte revision, int capacity)
: base()
{
_revision = revision;
- _aces = new List<GenericAce>( capacity );
+ _aces = new List<GenericAce>(capacity);
}
//
// Creates an ACL from its binary representation
//
- public RawAcl( byte[] binaryForm, int offset )
+ public RawAcl(byte[] binaryForm, int offset)
: base()
{
- SetBinaryForm( binaryForm, offset );
+ SetBinaryForm(binaryForm, offset);
}
#endregion
// Returns the binary representation of the ACL
//
- public override void GetBinaryForm( byte[] binaryForm, int offset )
+ public override void GetBinaryForm(byte[] binaryForm, int offset)
{
//
// Populate the header
//
- MarshalHeader( binaryForm, offset );
+ MarshalHeader(binaryForm, offset);
offset += HeaderLength;
- for ( int i = 0; i < Count; i++ )
+ for (int i = 0; i < Count; i++)
{
GenericAce ace = _aces[i];
- ace.GetBinaryForm( binaryForm, offset );
+ ace.GetBinaryForm(binaryForm, offset);
int aceLength = ace.BinaryLength;
- if ( aceLength % 4 != 0 )
+ if (aceLength % 4 != 0)
{
//
// This indicates a bug in one of the ACE classes.
// Binary length of an ace must ALWAYS be divisible by 4.
//
- Debug.Assert( false, "aceLength % 4 != 0" );
+ Debug.Assert(false, "aceLength % 4 != 0");
// Replacing SystemException with InvalidOperationException. This code path
// indicates a bad ACE, but I don't know of a great exception to represent that.
// InvalidOperation seems to be the closest, though it's definitely not exactly
set
{
- if ( value == null )
+ if (value == null)
{
- throw new ArgumentNullException( nameof(value));
+ throw new ArgumentNullException(nameof(value));
}
- if ( value.BinaryLength % 4 != 0 )
+ if (value.BinaryLength % 4 != 0)
{
//
// This indicates a bug in one of the ACE classes.
// Binary length of an ace must ALWAYS be divisible by 4.
//
- Debug.Assert( false, "aceLength % 4 != 0" );
+ Debug.Assert(false, "aceLength % 4 != 0");
// Replacing SystemException with InvalidOperationException. This code path
// indicates a bad ACE, but I don't know of a great exception to represent that.
// InvalidOperation seems to be the closest, though it's definitely not exactly
throw new InvalidOperationException();
}
- int newBinaryLength = BinaryLength - ( index < _aces.Count ? _aces[index].BinaryLength : 0 ) + value.BinaryLength;
+ int newBinaryLength = BinaryLength - (index < _aces.Count ? _aces[index].BinaryLength : 0) + value.BinaryLength;
- if ( newBinaryLength > MaxBinaryLength )
+ if (newBinaryLength > MaxBinaryLength)
{
- throw new OverflowException( SR.AccessControl_AclTooLong );
+ throw new OverflowException(SR.AccessControl_AclTooLong);
}
_aces[index] = value;
// Adds an ACE at the specified index
//
- public void InsertAce( int index, GenericAce ace )
+ public void InsertAce(int index, GenericAce ace)
{
- if ( ace == null )
+ if (ace == null)
{
- throw new ArgumentNullException( nameof(ace));
+ throw new ArgumentNullException(nameof(ace));
}
- if ( BinaryLength + ace.BinaryLength > MaxBinaryLength )
+ if (BinaryLength + ace.BinaryLength > MaxBinaryLength)
{
- throw new OverflowException( SR.AccessControl_AclTooLong );
+ throw new OverflowException(SR.AccessControl_AclTooLong);
}
- _aces.Insert( index, ace );
+ _aces.Insert(index, ace);
}
//
// Removes an ACE at the specified index
//
- public void RemoveAce( int index )
+ public void RemoveAce(int index)
{
GenericAce ace = _aces[index];
- _aces.RemoveAt( index );
+ _aces.RemoveAt(index);
}
#endregion
[Flags]
private enum AF // ACE flags
{
- CI = 0x8, // container inherit
- OI = 0x4, // object inherit
- IO = 0x2, // inherit only
- NP = 0x1, // no propagate inherit
- Invalid = NP, // not a valid combination of flags
+ CI = 0x8, // container inherit
+ OI = 0x4, // object inherit
+ IO = 0x2, // inherit only
+ NP = 0x1, // no propagate inherit
+ Invalid = NP, // not a valid combination of flags
}
[Flags]
private enum PM // Propagation matrix
{
- F = 0x10, // folder
- CF = 0x08, // child folder
- CO = 0x04, // child object
- GF = 0x02, // grandchild folder
- GO = 0x01, // grandchild object
- Invalid = GO, // not a valid combination of flags
+ F = 0x10, // folder
+ CF = 0x08, // child folder
+ CO = 0x04, // child object
+ GF = 0x02, // grandchild folder
+ GO = 0x01, // grandchild object
+ Invalid = GO, // not a valid combination of flags
}
private static readonly PM[] s_AFtoPM = CreateAFtoPMConversionMatrix(); // AceFlags-to-Propagation conversion matrix
{
var afToPm = new PM[16];
- for ( int i = 0; i < afToPm.Length; i++ )
+ for (int i = 0; i < afToPm.Length; i++)
{
afToPm[i] = PM.Invalid;
}
// Important: Not all combinations of inheritance bits are valid
//
- afToPm[( int )( 0 | 0 | 0 | 0 )] = PM.F | 0 | 0 | 0 | 0;
- afToPm[( int )( 0 | AF.OI | 0 | 0 )] = PM.F | 0 | PM.CO | 0 | PM.GO;
- afToPm[( int )( 0 | AF.OI | 0 | AF.NP )] = PM.F | 0 | PM.CO | 0 | 0;
- afToPm[( int )( 0 | AF.OI | AF.IO | 0 )] = 0 | 0 | PM.CO | 0 | PM.GO;
- afToPm[( int )( 0 | AF.OI | AF.IO | AF.NP )] = 0 | 0 | PM.CO | 0 | 0;
- afToPm[( int )( AF.CI | 0 | 0 | 0 )] = PM.F | PM.CF | 0 | PM.GF | 0;
- afToPm[( int )( AF.CI | 0 | 0 | AF.NP )] = PM.F | PM.CF | 0 | 0 | 0;
- afToPm[( int )( AF.CI | 0 | AF.IO | 0 )] = 0 | PM.CF | 0 | PM.GF | 0;
- afToPm[( int )( AF.CI | 0 | AF.IO | AF.NP )] = 0 | PM.CF | 0 | 0 | 0;
- afToPm[( int )( AF.CI | AF.OI | 0 | 0 )] = PM.F | PM.CF | PM.CO | PM.GF | PM.GO;
- afToPm[( int )( AF.CI | AF.OI | 0 | AF.NP )] = PM.F | PM.CF | PM.CO | 0 | 0;
- afToPm[( int )( AF.CI | AF.OI | AF.IO | 0 )] = 0 | PM.CF | PM.CO | PM.GF | PM.GO;
- afToPm[( int )( AF.CI | AF.OI | AF.IO | AF.NP )] = 0 | PM.CF | PM.CO | 0 | 0;
+ afToPm[(int)( 0 | 0 | 0 | 0 )] = PM.F | 0 | 0 | 0 | 0;
+ afToPm[(int)( 0 | AF.OI | 0 | 0 )] = PM.F | 0 | PM.CO | 0 | PM.GO;
+ afToPm[(int)( 0 | AF.OI | 0 | AF.NP )] = PM.F | 0 | PM.CO | 0 | 0;
+ afToPm[(int)( 0 | AF.OI | AF.IO | 0 )] = 0 | 0 | PM.CO | 0 | PM.GO;
+ afToPm[(int)( 0 | AF.OI | AF.IO | AF.NP )] = 0 | 0 | PM.CO | 0 | 0;
+ afToPm[(int)( AF.CI | 0 | 0 | 0 )] = PM.F | PM.CF | 0 | PM.GF | 0;
+ afToPm[(int)( AF.CI | 0 | 0 | AF.NP )] = PM.F | PM.CF | 0 | 0 | 0;
+ afToPm[(int)( AF.CI | 0 | AF.IO | 0 )] = 0 | PM.CF | 0 | PM.GF | 0;
+ afToPm[(int)( AF.CI | 0 | AF.IO | AF.NP )] = 0 | PM.CF | 0 | 0 | 0;
+ afToPm[(int)( AF.CI | AF.OI | 0 | 0 )] = PM.F | PM.CF | PM.CO | PM.GF | PM.GO;
+ afToPm[(int)( AF.CI | AF.OI | 0 | AF.NP )] = PM.F | PM.CF | PM.CO | 0 | 0;
+ afToPm[(int)( AF.CI | AF.OI | AF.IO | 0 )] = 0 | PM.CF | PM.CO | PM.GF | PM.GO;
+ afToPm[(int)( AF.CI | AF.OI | AF.IO | AF.NP )] = 0 | PM.CF | PM.CO | 0 | 0;
return afToPm;
}
{
var pmToAf = new AF[32];
- for ( int i = 0; i < pmToAf.Length; i++ )
+ for (int i = 0; i < pmToAf.Length; i++)
{
pmToAf[i] = AF.Invalid;
}
// the four ACE inheritance bits
//
- pmToAf[( int )( PM.F | 0 | 0 | 0 | 0 )] = 0 | 0 | 0 | 0;
- pmToAf[( int )( PM.F | 0 | PM.CO | 0 | PM.GO )] = 0 | AF.OI | 0 | 0;
- pmToAf[( int )( PM.F | 0 | PM.CO | 0 | 0 )] = 0 | AF.OI | 0 | AF.NP;
- pmToAf[( int )( 0 | 0 | PM.CO | 0 | PM.GO )] = 0 | AF.OI | AF.IO | 0;
- pmToAf[( int )( 0 | 0 | PM.CO | 0 | 0 )] = 0 | AF.OI | AF.IO | AF.NP;
- pmToAf[( int )( PM.F | PM.CF | 0 | PM.GF | 0 )] = AF.CI | 0 | 0 | 0;
- pmToAf[( int )( PM.F | PM.CF | 0 | 0 | 0 )] = AF.CI | 0 | 0 | AF.NP;
- pmToAf[( int )( 0 | PM.CF | 0 | PM.GF | 0 )] = AF.CI | 0 | AF.IO | 0;
- pmToAf[( int )( 0 | PM.CF | 0 | 0 | 0 )] = AF.CI | 0 | AF.IO | AF.NP;
- pmToAf[( int )( PM.F | PM.CF | PM.CO | PM.GF | PM.GO )] = AF.CI | AF.OI | 0 | 0;
- pmToAf[( int )( PM.F | PM.CF | PM.CO | 0 | 0 )] = AF.CI | AF.OI | 0 | AF.NP;
- pmToAf[( int )( 0 | PM.CF | PM.CO | PM.GF | PM.GO )] = AF.CI | AF.OI | AF.IO | 0;
- pmToAf[( int )( 0 | PM.CF | PM.CO | 0 | 0 )] = AF.CI | AF.OI | AF.IO | AF.NP;
+ pmToAf[(int)( PM.F | 0 | 0 | 0 | 0 )] = 0 | 0 | 0 | 0;
+ pmToAf[(int)( PM.F | 0 | PM.CO | 0 | PM.GO )] = 0 | AF.OI | 0 | 0;
+ pmToAf[(int)( PM.F | 0 | PM.CO | 0 | 0 )] = 0 | AF.OI | 0 | AF.NP;
+ pmToAf[(int)( 0 | 0 | PM.CO | 0 | PM.GO )] = 0 | AF.OI | AF.IO | 0;
+ pmToAf[(int)( 0 | 0 | PM.CO | 0 | 0 )] = 0 | AF.OI | AF.IO | AF.NP;
+ pmToAf[(int)( PM.F | PM.CF | 0 | PM.GF | 0 )] = AF.CI | 0 | 0 | 0;
+ pmToAf[(int)( PM.F | PM.CF | 0 | 0 | 0 )] = AF.CI | 0 | 0 | AF.NP;
+ pmToAf[(int)( 0 | PM.CF | 0 | PM.GF | 0 )] = AF.CI | 0 | AF.IO | 0;
+ pmToAf[(int)( 0 | PM.CF | 0 | 0 | 0 )] = AF.CI | 0 | AF.IO | AF.NP;
+ pmToAf[(int)( PM.F | PM.CF | PM.CO | PM.GF | PM.GO )] = AF.CI | AF.OI | 0 | 0;
+ pmToAf[(int)( PM.F | PM.CF | PM.CO | 0 | 0 )] = AF.CI | AF.OI | 0 | AF.NP;
+ pmToAf[(int)( 0 | PM.CF | PM.CO | PM.GF | PM.GO )] = AF.CI | AF.OI | AF.IO | 0;
+ pmToAf[(int)( 0 | PM.CF | PM.CO | 0 | 0 )] = AF.CI | AF.OI | AF.IO | AF.NP;
return pmToAf;
}
// Canonicalizes AceFlags into a form that the mapping tables understand
//
- private static AF AFFromAceFlags( AceFlags aceFlags, bool isDS )
+ private static AF AFFromAceFlags(AceFlags aceFlags, bool isDS)
{
AF af = 0;
- if (( aceFlags & AceFlags.ContainerInherit ) != 0)
+ if ((aceFlags & AceFlags.ContainerInherit) != 0)
{
af |= AF.CI;
}
// ObjectInherit applies only to regular aces not object aces
// so it can be ignored in the object aces case
//
- if (( !isDS ) && (( aceFlags & AceFlags.ObjectInherit ) != 0 ))
+ if ((!isDS) && ((aceFlags & AceFlags.ObjectInherit) != 0))
{
af |= AF.OI;
}
- if (( aceFlags & AceFlags.InheritOnly ) != 0 )
+ if ((aceFlags & AceFlags.InheritOnly) != 0)
{
af |= AF.IO;
}
- if (( aceFlags & AceFlags.NoPropagateInherit ) != 0 )
+ if ((aceFlags & AceFlags.NoPropagateInherit) != 0)
{
af |= AF.NP;
}
// Converts lookup table representation of AceFlags into the "public" form
//
- private static AceFlags AceFlagsFromAF( AF af, bool isDS )
+ private static AceFlags AceFlagsFromAF(AF af, bool isDS)
{
AceFlags aceFlags = 0;
- if (( af & AF.CI ) != 0 )
+ if ((af & AF.CI) != 0)
{
aceFlags |= AceFlags.ContainerInherit;
}
// ObjectInherit applies only to regular aces not object aces
// so it can be ignored in the object aces case
//
- if (( !isDS ) && (( af & AF.OI ) != 0 ))
+ if ((!isDS) && ((af & AF.OI) != 0))
{
aceFlags |= AceFlags.ObjectInherit;
}
- if (( af & AF.IO ) != 0 )
+ if ((af & AF.IO) != 0)
{
aceFlags |= AceFlags.InheritOnly;
}
- if (( af & AF.NP ) != 0 )
+ if ((af & AF.NP) != 0)
{
aceFlags |= AceFlags.NoPropagateInherit;
}
// Implements the merge of inheritance bits during the 'ADD' operation
//
- private static bool MergeInheritanceBits( AceFlags left, AceFlags right, bool isDS, out AceFlags result )
+ private static bool MergeInheritanceBits(AceFlags left, AceFlags right, bool isDS, out AceFlags result)
{
result = 0;
- AF leftAF = AFFromAceFlags( left, isDS );
- AF rightAF = AFFromAceFlags( right, isDS );
+ AF leftAF = AFFromAceFlags(left, isDS);
+ AF rightAF = AFFromAceFlags(right, isDS);
PM leftPM = s_AFtoPM[(int)leftAF];
PM rightPM = s_AFtoPM[(int)rightAF];
- if ( leftPM == PM.Invalid || rightPM == PM.Invalid )
+ if (leftPM == PM.Invalid || rightPM == PM.Invalid)
{
return false; // incorrect ACE flags?
}
PM resultPM = leftPM | rightPM;
- AF resultAF = s_PMtoAF[( int )resultPM];
+ AF resultAF = s_PMtoAF[(int)resultPM];
- if ( resultAF == AF.Invalid )
+ if (resultAF == AF.Invalid)
{
return false;
}
else
{
- result = AceFlagsFromAF( resultAF, isDS );
+ result = AceFlagsFromAF(resultAF, isDS);
return true;
}
}
- private static bool RemoveInheritanceBits( AceFlags existing, AceFlags remove, bool isDS, out AceFlags result, out bool total )
+ private static bool RemoveInheritanceBits(AceFlags existing, AceFlags remove, bool isDS, out AceFlags result, out bool total)
{
result = 0;
total = false;
- AF leftAF = AFFromAceFlags( existing, isDS );
- AF rightAF = AFFromAceFlags( remove, isDS );
+ AF leftAF = AFFromAceFlags(existing, isDS);
+ AF rightAF = AFFromAceFlags(remove, isDS);
- PM leftPM = s_AFtoPM[( int )leftAF];
- PM rightPM = s_AFtoPM[( int )rightAF];
+ PM leftPM = s_AFtoPM[(int)leftAF];
+ PM rightPM = s_AFtoPM[(int)rightAF];
- if ( leftPM == PM.Invalid || rightPM == PM.Invalid )
+ if (leftPM == PM.Invalid || rightPM == PM.Invalid)
{
return false; // incorrect ACE flags?
}
// communicate back the fact that removal is "total"
//
- if ( resultPM == 0 )
+ if (resultPM == 0)
{
total = true;
return true;
}
- AF resultAF = s_PMtoAF[( int )resultPM];
+ AF resultAF = s_PMtoAF[(int)resultPM];
- if ( resultAF == AF.Invalid )
+ if (resultAF == AF.Invalid)
{
return false;
}
else
{
- result = AceFlagsFromAF( resultAF, isDS );
+ result = AceFlagsFromAF(resultAF, isDS);
return true;
}
}
private void CanonicalizeIfNecessary()
{
- if ( _isDirty )
+ if (_isDirty)
{
- Canonicalize( false, this is DiscretionaryAcl );
+ Canonicalize(false, this is DiscretionaryAcl);
_isDirty = false;
}
}
// - user-defined ACEs (in the original order )
//
- private static int DaclAcePriority( GenericAce ace)
+ private static int DaclAcePriority(GenericAce ace)
{
int result;
AceType type = ace.AceType;
- if (( ace.AceFlags & AceFlags.Inherited ) != 0 )
+ if ((ace.AceFlags & AceFlags.Inherited) != 0)
{
//
// inherited aces are at the end as a group
result = 2 * ushort.MaxValue + ace._indexInAcl;
}
- else if ( type == AceType.AccessDenied ||
- type == AceType.AccessDeniedCallback )
+ else if (type == AceType.AccessDenied ||
+ type == AceType.AccessDeniedCallback)
{
result = 0;
}
- else if ( type == AceType.AccessDeniedObject ||
- type == AceType.AccessDeniedCallbackObject )
+ else if (type == AceType.AccessDeniedObject ||
+ type == AceType.AccessDeniedCallbackObject)
{
result = 1;
}
- else if ( type == AceType.AccessAllowed ||
- type == AceType.AccessAllowedCallback )
+ else if (type == AceType.AccessAllowed ||
+ type == AceType.AccessAllowedCallback)
{
result = 2;
}
- else if ( type == AceType.AccessAllowedObject ||
- type == AceType.AccessAllowedCallbackObject )
+ else if (type == AceType.AccessAllowedObject ||
+ type == AceType.AccessAllowedCallbackObject)
{
result = 3;
}
// - user-defined ACEs (in the original order )
//
- private static int SaclAcePriority( GenericAce ace )
+ private static int SaclAcePriority(GenericAce ace)
{
int result;
AceType type = ace.AceType;
- if (( ace.AceFlags & AceFlags.Inherited ) != 0 )
+ if ((ace.AceFlags & AceFlags.Inherited) != 0)
{
result = 2 * ushort.MaxValue + ace._indexInAcl;
}
- else if ( type == AceType.SystemAudit ||
+ else if (type == AceType.SystemAudit ||
type == AceType.SystemAlarm ||
type == AceType.SystemAuditCallback ||
- type == AceType.SystemAlarmCallback )
+ type == AceType.SystemAlarmCallback)
{
result = 0;
}
- else if ( type == AceType.SystemAuditObject ||
+ else if (type == AceType.SystemAuditObject ||
type == AceType.SystemAlarmObject ||
type == AceType.SystemAuditCallbackObject ||
- type == AceType.SystemAlarmCallbackObject )
+ type == AceType.SystemAlarmCallbackObject)
{
result = 1;
}
return result;
}
- private static ComparisonResult CompareAces( GenericAce ace1, GenericAce ace2, bool isDacl )
+ private static ComparisonResult CompareAces(GenericAce ace1, GenericAce ace2, bool isDacl)
{
- int ace1Priority = isDacl ? DaclAcePriority( ace1 ) : SaclAcePriority( ace1 );
- int ace2Priority = isDacl ? DaclAcePriority( ace2 ) : SaclAcePriority( ace2 );
+ int ace1Priority = isDacl ? DaclAcePriority(ace1) : SaclAcePriority(ace1);
+ int ace2Priority = isDacl ? DaclAcePriority(ace2) : SaclAcePriority(ace2);
- if ( ace1Priority < ace2Priority )
+ if (ace1Priority < ace2Priority)
{
return ComparisonResult.LessThan;
}
- else if ( ace1Priority > ace2Priority )
+ else if (ace1Priority > ace2Priority)
{
return ComparisonResult.GreaterThan;
}
KnownAce k_ace1 = ace1 as KnownAce;
KnownAce k_ace2 = ace2 as KnownAce;
- if ( k_ace1 != null && k_ace2 != null )
+ if (k_ace1 != null && k_ace2 != null)
{
- int result = k_ace1.SecurityIdentifier.CompareTo( k_ace2.SecurityIdentifier );
+ int result = k_ace1.SecurityIdentifier.CompareTo(k_ace2.SecurityIdentifier);
- if ( result < 0 )
+ if (result < 0)
{
return ComparisonResult.LessThan;
}
- else if ( result > 0 )
+ else if (result > 0)
{
return ComparisonResult.GreaterThan;
}
}
}
- private void QuickSort( int left, int right, bool isDacl )
+ private void QuickSort(int left, int right, bool isDacl)
{
GenericAce pivot;
int leftHold, rightHold;
int pivotIndex;
- if ( left >= right )
+ if (left >= right)
{
return;
}
pivot = _acl[left];
pivotIndex = left;
- while ( left < right )
+ while (left < right)
{
-// while (( _acl[right] >= pivot ) && ( left < right ))
- while (( ComparisonResult.LessThan != CompareAces( _acl[right], pivot, isDacl ) ) && ( left < right ))
+ // while (( _acl[right] >= pivot ) && ( left < right ))
+ while ((ComparisonResult.LessThan != CompareAces(_acl[right], pivot, isDacl)) && (left < right))
{
right--;
}
- if ( left != right )
+ if (left != right)
{
_acl[left] = _acl[right];
left++;
}
-// while (( _acl[left] <= pivot ) && ( left < right ))
- while (( ComparisonResult.GreaterThan != CompareAces( _acl[left], pivot, isDacl ) ) && ( left < right ))
+ // while (( _acl[left] <= pivot ) && ( left < right ))
+ while ((ComparisonResult.GreaterThan != CompareAces(_acl[left], pivot, isDacl)) && (left < right))
{
left++;
}
- if ( left != right )
+ if (left != right)
{
_acl[right] = _acl[left];
right--;
left = leftHold;
right = rightHold;
- if ( left < pivotIndex )
+ if (left < pivotIndex)
{
- QuickSort( left, pivotIndex - 1, isDacl );
+ QuickSort(left, pivotIndex - 1, isDacl);
}
- if ( right > pivotIndex )
+ if (right > pivotIndex)
{
- QuickSort( pivotIndex + 1, right, isDacl );
+ QuickSort(pivotIndex + 1, right, isDacl);
}
}
// Returns 'true' if the ACE should remain in the ACL, 'false' otherwise
//
- private bool InspectAce( ref GenericAce ace, bool isDacl )
+ private bool InspectAce(ref GenericAce ace, bool isDacl)
{
const AceFlags AuditFlags =
AceFlags.SuccessfulAccess |
KnownAce knownAce = ace as KnownAce;
- if ( knownAce != null )
+ if (knownAce != null)
{
- if ( knownAce.AccessMask == 0 )
+ if (knownAce.AccessMask == 0)
{
return false;
}
}
- if ( !IsContainer )
+ if (!IsContainer)
{
//
// On a leaf object ACL, inheritance bits are meaningless.
// no meaning.
//
- if (( ace.AceFlags & AceFlags.InheritOnly ) != 0 )
+ if ((ace.AceFlags & AceFlags.InheritOnly) != 0)
{
return false;
}
- if (( ace.AceFlags & InheritFlags ) != 0 )
+ if ((ace.AceFlags & InheritFlags) != 0)
{
unchecked { ace.AceFlags &= ~InheritFlags; }
}
// the InheritOnly bit is meaningless and the entire ACE can be removed.
//
- if ((( ace.AceFlags & AceFlags.InheritOnly ) != 0 ) &&
- (( ace.AceFlags & AceFlags.ContainerInherit ) == 0 ) &&
- (( ace.AceFlags & AceFlags.ObjectInherit ) == 0 ))
+ if (((ace.AceFlags & AceFlags.InheritOnly) != 0) &&
+ ((ace.AceFlags & AceFlags.ContainerInherit) == 0) &&
+ ((ace.AceFlags & AceFlags.ObjectInherit) == 0))
{
return false;
}
// Without either "container inherit" or "object inherit" to go with it,
// the NoPropagateInherit bit is meaningless and can be turned off.
//
- if ((( ace.AceFlags & AceFlags.NoPropagateInherit ) != 0 ) &&
- (( ace.AceFlags & AceFlags.ContainerInherit ) == 0 ) &&
- (( ace.AceFlags & AceFlags.ObjectInherit ) == 0 ))
+ if (((ace.AceFlags & AceFlags.NoPropagateInherit) != 0) &&
+ ((ace.AceFlags & AceFlags.ContainerInherit) == 0) &&
+ ((ace.AceFlags & AceFlags.ObjectInherit) == 0))
{
unchecked { ace.AceFlags &= ~AceFlags.NoPropagateInherit; }
}
QualifiedAce qualifiedAce = knownAce as QualifiedAce;
- if ( isDacl )
+ if (isDacl)
{
//
// There is no place for audit flags on a DACL
unchecked { ace.AceFlags &= ~AuditFlags; }
- if ( qualifiedAce != null )
+ if (qualifiedAce != null)
{
//
// Qualified ACEs in a DACL must be allow or deny ACEs
//
- if ( qualifiedAce.AceQualifier != AceQualifier.AccessAllowed &&
- qualifiedAce.AceQualifier != AceQualifier.AccessDenied )
+ if (qualifiedAce.AceQualifier != AceQualifier.AccessAllowed &&
+ qualifiedAce.AceQualifier != AceQualifier.AccessDenied)
{
return false;
}
// flags can be removed
//
- if (( ace.AceFlags & AuditFlags ) == 0 )
+ if ((ace.AceFlags & AuditFlags) == 0)
{
return false;
}
// Qualified ACEs in a SACL must be audit ACEs
//
- if ( qualifiedAce != null )
+ if (qualifiedAce != null)
{
- if ( qualifiedAce.AceQualifier != AceQualifier.SystemAudit )
+ if (qualifiedAce.AceQualifier != AceQualifier.SystemAudit)
{
return false;
}
// Strips meaningless flags from ACEs, removes meaningless ACEs
//
- private void RemoveMeaninglessAcesAndFlags( bool isDacl )
+ private void RemoveMeaninglessAcesAndFlags(bool isDacl)
{
//
// Be warned: do NOT use the Count property because it has
// side-effect of calling canonicalization.
//
- for ( int i = _acl.Count - 1; i >= 0; i-- )
+ for (int i = _acl.Count - 1; i >= 0; i--)
{
GenericAce ace = _acl[i];
- if ( false == InspectAce( ref ace, isDacl ))
+ if (false == InspectAce(ref ace, isDacl))
{
- _acl.RemoveAce( i );
+ _acl.RemoveAce(i);
}
}
}
// Converts the ACL to its canonical form
//
- private void Canonicalize( bool compact, bool isDacl )
+ private void Canonicalize(bool compact, bool isDacl)
{
//
// for quick sort to work, we must not allow the ace's indexes - which are constantly
_acl[aclIndex]._indexInAcl = aclIndex;
}
- QuickSort( 0, _acl.Count - 1, isDacl );
+ QuickSort(0, _acl.Count - 1, isDacl);
- if ( compact )
+ if (compact)
{
- for ( int i = 0; i < Count - 1; i++ )
+ for (int i = 0; i < Count - 1; i++)
{
QualifiedAce thisAce = _acl[i] as QualifiedAce;
- if ( thisAce == null )
+ if (thisAce == null)
{
continue;
}
QualifiedAce nextAce = _acl[i + 1] as QualifiedAce;
- if ( nextAce == null )
+ if (nextAce == null)
{
continue;
}
- if ( true == MergeAces( ref thisAce, nextAce ))
+ if (true == MergeAces(ref thisAce, nextAce))
{
_acl.RemoveAce(i + 1);
}
// This method determines whether the object type and inherited object type from the original ace
// should be retained or not based on access mask and aceflags for a given split
//
- private void GetObjectTypesForSplit( ObjectAce originalAce, int accessMask, AceFlags aceFlags, out ObjectAceFlags objectFlags, out Guid objectType, out Guid inheritedObjectType )
+ private void GetObjectTypesForSplit(ObjectAce originalAce, int accessMask, AceFlags aceFlags, out ObjectAceFlags objectFlags, out Guid objectType, out Guid inheritedObjectType)
{
objectFlags = 0;
//
// We should retain the object type if the access mask for this split contains any bits that refer to object type
//
- if (( accessMask & ObjectAce.AccessMaskWithObjectType ) != 0 )
+ if ((accessMask & ObjectAce.AccessMaskWithObjectType) != 0)
{
// keep the original ace's object flags and object type
objectType = originalAce.ObjectAceType;
//
// We should retain the inherited object type if the aceflags for this contains inheritance (ContainerInherit)
//
- if (( aceFlags & AceFlags.ContainerInherit ) != 0 )
+ if ((aceFlags & AceFlags.ContainerInherit) != 0)
{
// keep the original ace's object flags and object type
inheritedObjectType = originalAce.InheritedObjectAceType;
}
}
- private bool ObjectTypesMatch( QualifiedAce ace, QualifiedAce newAce )
+ private bool ObjectTypesMatch(QualifiedAce ace, QualifiedAce newAce)
{
- Guid objectType = ( ace is ObjectAce ) ? (( ObjectAce ) ace ).ObjectAceType : Guid.Empty;
- Guid newObjectType = ( newAce is ObjectAce ) ? (( ObjectAce ) newAce ).ObjectAceType : Guid.Empty;
+ Guid objectType = (ace is ObjectAce) ? ((ObjectAce)ace).ObjectAceType : Guid.Empty;
+ Guid newObjectType = (newAce is ObjectAce) ? ((ObjectAce)newAce).ObjectAceType : Guid.Empty;
- return objectType.Equals( newObjectType );
+ return objectType.Equals(newObjectType);
}
- private bool InheritedObjectTypesMatch( QualifiedAce ace, QualifiedAce newAce )
+ private bool InheritedObjectTypesMatch(QualifiedAce ace, QualifiedAce newAce)
{
- Guid inheritedObjectType = ( ace is ObjectAce ) ? (( ObjectAce ) ace ).InheritedObjectAceType : Guid.Empty;
- Guid newInheritedObjectType = ( newAce is ObjectAce ) ? (( ObjectAce ) newAce ).InheritedObjectAceType : Guid.Empty;
+ Guid inheritedObjectType = (ace is ObjectAce) ? ((ObjectAce)ace).InheritedObjectAceType : Guid.Empty;
+ Guid newInheritedObjectType = (newAce is ObjectAce) ? ((ObjectAce)newAce).InheritedObjectAceType : Guid.Empty;
- return inheritedObjectType.Equals( newInheritedObjectType );
+ return inheritedObjectType.Equals(newInheritedObjectType);
}
- private bool AccessMasksAreMergeable( QualifiedAce ace, QualifiedAce newAce )
+ private bool AccessMasksAreMergeable(QualifiedAce ace, QualifiedAce newAce)
{
//
// The access masks are mergeable in any of the following conditions
// already contains all the bits of the new ace which refer to the object type
//
- if ( ObjectTypesMatch( ace, newAce ))
+ if (ObjectTypesMatch(ace, newAce))
{
// case 1
return true;
}
- ObjectAceFlags objectFlags = ( ace is ObjectAce ) ? (( ObjectAce ) ace ).ObjectAceFlags : ObjectAceFlags.None;
- if ((( ace.AccessMask & newAce.AccessMask & ObjectAce.AccessMaskWithObjectType ) == ( newAce.AccessMask & ObjectAce.AccessMaskWithObjectType )) &&
- (( objectFlags & ObjectAceFlags.ObjectAceTypePresent ) == 0 ))
+ ObjectAceFlags objectFlags = (ace is ObjectAce) ? ((ObjectAce)ace).ObjectAceFlags : ObjectAceFlags.None;
+ if (((ace.AccessMask & newAce.AccessMask & ObjectAce.AccessMaskWithObjectType) == (newAce.AccessMask & ObjectAce.AccessMaskWithObjectType)) &&
+ ((objectFlags & ObjectAceFlags.ObjectAceTypePresent) == 0))
{
// case 2
return true;
return false;
}
- private bool AceFlagsAreMergeable( QualifiedAce ace, QualifiedAce newAce )
+ private bool AceFlagsAreMergeable(QualifiedAce ace, QualifiedAce newAce)
{
//
// The ace flags can be considered for merge in any of the following conditions
// already contains all the bits of the new ace
//
- if ( InheritedObjectTypesMatch( ace, newAce ))
+ if (InheritedObjectTypesMatch(ace, newAce))
{
// case 1
return true;
}
- ObjectAceFlags objectFlags = ( ace is ObjectAce ) ? (( ObjectAce ) ace ).ObjectAceFlags : ObjectAceFlags.None;
- if (( objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent ) == 0 )
+ ObjectAceFlags objectFlags = (ace is ObjectAce) ? ((ObjectAce)ace).ObjectAceFlags : ObjectAceFlags.None;
+ if ((objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent) == 0)
{
// case 2
// This method is called only when the access masks of the two aces are already confirmed to be exact matches
// therefore the second condition of case 2 is already verified
//
- Debug.Assert(( ace.AccessMask & newAce.AccessMask) == newAce.AccessMask, "AceFlagsAreMergeable:: AccessMask of existing ace does not contain all access bits of new ace.");
+ Debug.Assert((ace.AccessMask & newAce.AccessMask) == newAce.AccessMask, "AceFlagsAreMergeable:: AccessMask of existing ace does not contain all access bits of new ace.");
return true;
}
return false;
}
- private bool GetAccessMaskForRemoval( QualifiedAce ace, ObjectAceFlags objectFlags, Guid objectType, ref int accessMask )
+ private bool GetAccessMaskForRemoval(QualifiedAce ace, ObjectAceFlags objectFlags, Guid objectType, ref int accessMask)
{
- if (( ace.AccessMask & accessMask & ObjectAce.AccessMaskWithObjectType ) != 0 )
+ if ((ace.AccessMask & accessMask & ObjectAce.AccessMaskWithObjectType) != 0)
{
//
//
- if ( ace is ObjectAce )
+ if (ace is ObjectAce)
{
bool commonAccessBitsWithObjectTypeExist = true;
ObjectAce objectAce = ace as ObjectAce;
// if what we are trying to remove has an object type
// but the existing ace does not then this is an invalid case
//
- if ((( objectFlags & ObjectAceFlags.ObjectAceTypePresent ) != 0 ) &&
- (( objectAce.ObjectAceFlags & ObjectAceFlags.ObjectAceTypePresent ) == 0 ))
+ if (((objectFlags & ObjectAceFlags.ObjectAceTypePresent) != 0) &&
+ ((objectAce.ObjectAceFlags & ObjectAceFlags.ObjectAceTypePresent) == 0))
{
return false;
}
// if object types match (since at this point we have ensured that both have object types present)
// then we have common access bits with object type
//
- commonAccessBitsWithObjectTypeExist = (( objectFlags & ObjectAceFlags.ObjectAceTypePresent ) == 0 ) ||
- objectAce.ObjectTypesMatch( objectFlags, objectType );
- if ( !commonAccessBitsWithObjectTypeExist )
+ commonAccessBitsWithObjectTypeExist = ((objectFlags & ObjectAceFlags.ObjectAceTypePresent) == 0) ||
+ objectAce.ObjectTypesMatch(objectFlags, objectType);
+ if (!commonAccessBitsWithObjectTypeExist)
{
accessMask &= ~ObjectAce.AccessMaskWithObjectType;
}
}
- else if (( objectFlags & ObjectAceFlags.ObjectAceTypePresent ) != 0 )
+ else if ((objectFlags & ObjectAceFlags.ObjectAceTypePresent) != 0)
{
// the existing ace is a common ace and the one we're removing
// refers to a specific object type so this is invalid
}
- private bool GetInheritanceFlagsForRemoval( QualifiedAce ace, ObjectAceFlags objectFlags, Guid inheritedObjectType, ref AceFlags aceFlags )
+ private bool GetInheritanceFlagsForRemoval(QualifiedAce ace, ObjectAceFlags objectFlags, Guid inheritedObjectType, ref AceFlags aceFlags)
{
- if ((( ace.AceFlags & AceFlags.ContainerInherit ) != 0 ) && (( aceFlags & AceFlags.ContainerInherit ) != 0 ))
+ if (((ace.AceFlags & AceFlags.ContainerInherit) != 0) && ((aceFlags & AceFlags.ContainerInherit) != 0))
{
//
//
- if ( ace is ObjectAce )
+ if (ace is ObjectAce)
{
bool commonInheritanceFlagsExist = true;
ObjectAce objectAce = ace as ObjectAce;
// if what we are trying to remove has an inherited object type
// but the existing ace does not then this is an invalid case
//
- if ((( objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent ) != 0 ) &&
- (( objectAce.ObjectAceFlags & ObjectAceFlags.InheritedObjectAceTypePresent ) == 0 ))
+ if (((objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent) != 0) &&
+ ((objectAce.ObjectAceFlags & ObjectAceFlags.InheritedObjectAceTypePresent) == 0))
{
return false;
}
// if what we are trying to remove has no inherited object type or
// if inherited object types match then we have common inheritance flags
//
- commonInheritanceFlagsExist = (( objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent ) == 0 ) ||
- objectAce.InheritedObjectTypesMatch( objectFlags, inheritedObjectType );
- if ( !commonInheritanceFlagsExist )
+ commonInheritanceFlagsExist = ((objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent) == 0) ||
+ objectAce.InheritedObjectTypesMatch(objectFlags, inheritedObjectType);
+ if (!commonInheritanceFlagsExist)
{
aceFlags &= ~AceFlags.InheritanceFlags;
}
}
- else if (( objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent ) != 0 )
+ else if ((objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent) != 0)
{
// the existing ace is a common ace and the one we're removing
// refers to a specific child type so this is invalid
}
- private static bool AceOpaquesMatch( QualifiedAce ace, QualifiedAce newAce )
+ private static bool AceOpaquesMatch(QualifiedAce ace, QualifiedAce newAce)
{
byte[] aceOpaque = ace.GetOpaque();
byte[] newAceOpaque = newAce.GetOpaque();
- if ( aceOpaque == null || newAceOpaque == null )
+ if (aceOpaque == null || newAceOpaque == null)
{
return aceOpaque == newAceOpaque;
}
- if ( aceOpaque.Length != newAceOpaque.Length )
+ if (aceOpaque.Length != newAceOpaque.Length)
{
return false;
}
- for ( int i = 0; i < aceOpaque.Length; ++i )
+ for (int i = 0; i < aceOpaque.Length; ++i)
{
- if ( aceOpaque[i] != newAceOpaque[i] )
+ if (aceOpaque[i] != newAceOpaque[i])
{
return false;
}
return true;
}
- private static bool AcesAreMergeable( QualifiedAce ace, QualifiedAce newAce )
+ private static bool AcesAreMergeable(QualifiedAce ace, QualifiedAce newAce)
{
//
// Only interested in ACEs with the specified type
//
- if ( ace.AceType != newAce.AceType )
+ if (ace.AceType != newAce.AceType)
{
return false;
}
// Only interested in explicit (non-inherited) ACEs
//
- if (( ace.AceFlags & AceFlags.Inherited ) != 0 )
+ if ((ace.AceFlags & AceFlags.Inherited) != 0)
{
return false;
}
- if (( newAce.AceFlags & AceFlags.Inherited ) != 0 )
+ if ((newAce.AceFlags & AceFlags.Inherited) != 0)
{
return false;
}
// Only interested in ACEs with the specified qualifier
//
- if ( ace.AceQualifier != newAce.AceQualifier )
+ if (ace.AceQualifier != newAce.AceQualifier)
{
return false;
}
// Only interested in ACEs with the specified SID
//
- if ( ace.SecurityIdentifier != newAce.SecurityIdentifier )
+ if (ace.SecurityIdentifier != newAce.SecurityIdentifier)
{
return false;
}
// Only interested in ACEs with the specified callback data
//
- if ( !AceOpaquesMatch( ace, newAce ))
+ if (!AceOpaquesMatch(ace, newAce))
{
return false;
}
// Merge routine for qualified ACEs
//
- private bool MergeAces( ref QualifiedAce ace, QualifiedAce newAce )
+ private bool MergeAces(ref QualifiedAce ace, QualifiedAce newAce)
{
//
// Check whether the ACEs are potentially mergeable
//
- if ( !AcesAreMergeable( ace, newAce ))
+ if (!AcesAreMergeable(ace, newAce))
{
return false;
}
// Stage 1: if flags match, add to the access mask
//
- if ( ace.AceFlags == newAce.AceFlags )
+ if (ace.AceFlags == newAce.AceFlags)
{
- if ( ace is ObjectAce || newAce is ObjectAce )
+ if (ace is ObjectAce || newAce is ObjectAce)
{
// for object aces we need to match the inherited object types (for ace flags equality)
- if ( InheritedObjectTypesMatch( ace, newAce ))
+ if (InheritedObjectTypesMatch(ace, newAce))
{
// also since access mask bits are further qualified by object type, they cannot always be added on
- if ( AccessMasksAreMergeable( ace, newAce ))
+ if (AccessMasksAreMergeable(ace, newAce))
{
ace.AccessMask |= newAce.AccessMask;
return true;
// flags (both access mask and inheritance) match
//
- if ((( ace.AceFlags & AceFlags.InheritanceFlags ) == ( newAce.AceFlags & AceFlags.InheritanceFlags )) &&
- ( ace.AccessMask == newAce.AccessMask ))
+ if (((ace.AceFlags & AceFlags.InheritanceFlags) == (newAce.AceFlags & AceFlags.InheritanceFlags)) &&
+ (ace.AccessMask == newAce.AccessMask))
{
- if (( ace is ObjectAce ) || ( newAce is ObjectAce ))
+ if ((ace is ObjectAce) || (newAce is ObjectAce))
{
// for object aces we need to match the inherited object types (for inheritance flags equality) and object type (for access mask equality) as well
- if ( InheritedObjectTypesMatch( ace, newAce ) &&
- ( ObjectTypesMatch( ace, newAce )))
+ if (InheritedObjectTypesMatch(ace, newAce) &&
+ (ObjectTypesMatch(ace, newAce)))
{
- ace.AceFlags |= ( newAce.AceFlags & AceFlags.AuditFlags );
+ ace.AceFlags |= (newAce.AceFlags & AceFlags.AuditFlags);
return true;
}
}
else
{
- ace.AceFlags |= ( newAce.AceFlags & AceFlags.AuditFlags );
+ ace.AceFlags |= (newAce.AceFlags & AceFlags.AuditFlags);
return true;
}
// provided access mask and audit bits are the same
//
- if ((( ace.AceFlags & AceFlags.AuditFlags ) == ( newAce.AceFlags & AceFlags.AuditFlags )) &&
- ( ace.AccessMask == newAce.AccessMask ))
+ if (((ace.AceFlags & AceFlags.AuditFlags) == (newAce.AceFlags & AceFlags.AuditFlags)) &&
+ (ace.AccessMask == newAce.AccessMask))
{
AceFlags merged;
// See whether the inheritance bits can be merged
//
- if (( ace is ObjectAce ) || ( newAce is ObjectAce ))
+ if ((ace is ObjectAce) || (newAce is ObjectAce))
{
// object types need to match (for access mask equality) and inheritance flags need additional DS specific logic
// to check whether they can be merged
- if (( ObjectTypesMatch( ace, newAce )) &&
- ( AceFlagsAreMergeable( ace, newAce )))
+ if ((ObjectTypesMatch(ace, newAce)) &&
+ (AceFlagsAreMergeable(ace, newAce)))
{
- if ( true == MergeInheritanceBits( ace.AceFlags, newAce.AceFlags, IsDS, out merged ))
+ if (true == MergeInheritanceBits(ace.AceFlags, newAce.AceFlags, IsDS, out merged))
{
- ace.AceFlags = ( merged | ( ace.AceFlags & AceFlags.AuditFlags ));
+ ace.AceFlags = (merged | (ace.AceFlags & AceFlags.AuditFlags));
return true;
}
}
}
else
{
- if ( true == MergeInheritanceBits( ace.AceFlags, newAce.AceFlags, IsDS, out merged ))
+ if (true == MergeInheritanceBits(ace.AceFlags, newAce.AceFlags, IsDS, out merged))
{
- ace.AceFlags = ( merged | ( ace.AceFlags & AceFlags.AuditFlags ));
+ ace.AceFlags = (merged | (ace.AceFlags & AceFlags.AuditFlags));
return true;
}
}
// Returns 'true' if the ACL is in canonical order; 'false' otherwise
//
- private bool CanonicalCheck( bool isDacl )
+ private bool CanonicalCheck(bool isDacl)
{
- if ( isDacl )
+ if (isDacl)
{
//
// DACL canonical order:
// of this check!
//
- for ( int i = 0; i < _acl.Count; i++ )
+ for (int i = 0; i < _acl.Count; i++)
{
int aceStage;
GenericAce ace = _acl[i];
- if (( ace.AceFlags & AceFlags.Inherited ) != 0 )
+ if ((ace.AceFlags & AceFlags.Inherited) != 0)
{
aceStage = Inherited;
}
{
QualifiedAce qualifiedAce = ace as QualifiedAce;
- if ( qualifiedAce == null )
+ if (qualifiedAce == null)
{
//
// Explicit ACE is not recognized - this is not a canonical ACL
return false;
}
- if ( qualifiedAce.AceQualifier == AceQualifier.AccessAllowed )
+ if (qualifiedAce.AceQualifier == AceQualifier.AccessAllowed)
{
aceStage = AccessAllowed;
}
- else if ( qualifiedAce.AceQualifier == AceQualifier.AccessDenied )
+ else if (qualifiedAce.AceQualifier == AceQualifier.AccessDenied)
{
aceStage = AccessDenied;
}
// Only allow and deny ACEs are allowed here
//
- Debug.Assert( false, "Audit and alarm ACEs must have been stripped by remove-meaningless logic" );
+ Debug.Assert(false, "Audit and alarm ACEs must have been stripped by remove-meaningless logic");
return false;
}
}
- if ( aceStage > currentStage )
+ if (aceStage > currentStage)
{
currentStage = aceStage;
}
- else if ( aceStage < currentStage )
+ else if (aceStage < currentStage)
{
return false;
}
// of this check!
//
- for ( int i = 0; i < _acl.Count; i++ )
+ for (int i = 0; i < _acl.Count; i++)
{
int aceStage;
GenericAce ace = _acl[i];
- if ( ace == null )
+ if (ace == null)
{
//
// <markpu-9/19/2004> Afraid to yank this statement now
// for fear of destabilization, so adding an assert instead
//
- Debug.Assert( ace != null, "How did a null ACE end up in a SACL?" );
+ Debug.Assert(ace != null, "How did a null ACE end up in a SACL?");
continue;
}
- if (( ace.AceFlags & AceFlags.Inherited ) != 0 )
+ if ((ace.AceFlags & AceFlags.Inherited) != 0)
{
aceStage = Inherited;
}
{
QualifiedAce qualifiedAce = ace as QualifiedAce;
- if ( qualifiedAce == null )
+ if (qualifiedAce == null)
{
//
// Explicit ACE is not recognized - this is not a canonical ACL
return false;
}
- if ( qualifiedAce.AceQualifier == AceQualifier.SystemAudit ||
- qualifiedAce.AceQualifier == AceQualifier.SystemAlarm )
+ if (qualifiedAce.AceQualifier == AceQualifier.SystemAudit ||
+ qualifiedAce.AceQualifier == AceQualifier.SystemAlarm)
{
aceStage = Explicit;
}
// Only audit and alarm ACEs are allowed here
//
- Debug.Assert( false, "Allow and deny ACEs must have been stripped by remove-meaningless logic" );
+ Debug.Assert(false, "Allow and deny ACEs must have been stripped by remove-meaningless logic");
return false;
}
}
- if ( aceStage > currentStage )
+ if (aceStage > currentStage)
{
currentStage = aceStage;
}
- else if ( aceStage < currentStage )
+ else if (aceStage < currentStage)
{
return false;
}
private void ThrowIfNotCanonical()
{
- if ( !_isCanonical )
+ if (!_isCanonical)
{
- throw new InvalidOperationException( SR.InvalidOperation_ModificationOfNonCanonicalAcl );
+ throw new InvalidOperationException(SR.InvalidOperation_ModificationOfNonCanonicalAcl);
}
}
// Creates an empty ACL
//
- internal CommonAcl( bool isContainer, bool isDS, byte revision, int capacity )
+ internal CommonAcl(bool isContainer, bool isDS, byte revision, int capacity)
: base()
{
_isContainer = isContainer;
_isDS = isDS;
- _acl = new RawAcl( revision, capacity );
+ _acl = new RawAcl(revision, capacity);
_isCanonical = true; // since it is empty
}
// copy of the ACL passed in
//
- internal CommonAcl( bool isContainer, bool isDS, RawAcl rawAcl, bool trusted, bool isDacl )
+ internal CommonAcl(bool isContainer, bool isDS, RawAcl rawAcl, bool trusted, bool isDacl)
: base()
{
- if ( rawAcl == null )
+ if (rawAcl == null)
{
- throw new ArgumentNullException( nameof(rawAcl));
+ throw new ArgumentNullException(nameof(rawAcl));
}
_isContainer = isContainer;
_acl = rawAcl;
- RemoveMeaninglessAcesAndFlags( isDacl );
+ RemoveMeaninglessAcesAndFlags(isDacl);
}
else
{
// In the untrusted case, we create our own raw ACL to keep the ACEs in
//
- _acl = new RawAcl( rawAcl.Revision, rawAcl.Count );
+ _acl = new RawAcl(rawAcl.Revision, rawAcl.Count);
- for ( int i = 0; i < rawAcl.Count; i++ )
+ for (int i = 0; i < rawAcl.Count; i++)
{
//
// Clone each ACE prior to putting it in
// Avoid inserting meaningless ACEs
//
- if ( true == InspectAce( ref ace, isDacl ))
+ if (true == InspectAce(ref ace, isDacl))
{
- _acl.InsertAce( _acl.Count, ace );
+ _acl.InsertAce(_acl.Count, ace);
}
}
}
// See whether the ACL is canonical to begin with
//
- if ( true == CanonicalCheck( isDacl ))
+ if (true == CanonicalCheck(isDacl))
{
//
// Sort and compact the array
//
- Canonicalize( true, isDacl );
+ Canonicalize(true, isDacl);
_isCanonical = true;
}
#region Protected Methods
- internal void CheckAccessType( AccessControlType accessType )
+ internal void CheckAccessType(AccessControlType accessType)
{
- if ( accessType != AccessControlType.Allow &&
- accessType != AccessControlType.Deny )
+ if (accessType != AccessControlType.Allow &&
+ accessType != AccessControlType.Deny)
{
throw new ArgumentOutOfRangeException(
nameof(accessType),
- SR.ArgumentOutOfRange_Enum );
+ SR.ArgumentOutOfRange_Enum);
}
}
- internal void CheckFlags( InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags )
+ internal void CheckFlags(InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
{
- if ( IsContainer )
+ if (IsContainer)
{
//
// Supplying propagation flags without inheritance flags is illegal
//
- if ( inheritanceFlags == InheritanceFlags.None &&
- propagationFlags != PropagationFlags.None )
+ if (inheritanceFlags == InheritanceFlags.None &&
+ propagationFlags != PropagationFlags.None)
{
throw new ArgumentException(
SR.Argument_InvalidAnyFlag,
nameof(propagationFlags));
}
}
- else if ( inheritanceFlags != InheritanceFlags.None )
+ else if (inheritanceFlags != InheritanceFlags.None)
{
throw new ArgumentException(
SR.Argument_InvalidAnyFlag,
nameof(inheritanceFlags));
}
- else if ( propagationFlags != PropagationFlags.None )
+ else if (propagationFlags != PropagationFlags.None)
{
throw new ArgumentException(
SR.Argument_InvalidAnyFlag,
// Helper function behind all the AddXXX methods for qualified aces
//
- internal void AddQualifiedAce( SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType )
+ internal void AddQualifiedAce(SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
{
- if ( sid == null )
+ if (sid == null)
{
- throw new ArgumentNullException( nameof(sid));
+ throw new ArgumentNullException(nameof(sid));
}
ThrowIfNotCanonical();
bool aceMerged = false; // if still false after all attempts to merge, create new entry
- if ( qualifier == AceQualifier.SystemAudit &&
- (( flags & AceFlags.AuditFlags ) == 0 ))
+ if (qualifier == AceQualifier.SystemAudit &&
+ ((flags & AceFlags.AuditFlags) == 0))
{
throw new ArgumentException(
SR.Arg_EnumAtLeastOneFlag,
nameof(flags));
}
- if ( accessMask == 0 )
+ if (accessMask == 0)
{
throw new ArgumentException(
SR.Argument_ArgumentZero,
GenericAce newAce;
- if (( !IsDS ) || ( objectFlags == ObjectAceFlags.None ))
+ if ((!IsDS) || (objectFlags == ObjectAceFlags.None))
{
- newAce = new CommonAce( flags, qualifier, accessMask, sid, false, null );
+ newAce = new CommonAce(flags, qualifier, accessMask, sid, false, null);
}
else
{
- newAce = new ObjectAce( flags, qualifier, accessMask, sid, objectFlags, objectType, inheritedObjectType, false, null );
+ newAce = new ObjectAce(flags, qualifier, accessMask, sid, objectFlags, objectType, inheritedObjectType, false, null);
}
//
// Make sure the new ACE wouldn't be meaningless before proceeding
//
- if ( false == InspectAce( ref newAce, ( this is DiscretionaryAcl )))
+ if (false == InspectAce(ref newAce, (this is DiscretionaryAcl)))
{
return;
}
// See if the new ACE can be merged with any of the existing ones
//
- for ( int i = 0; i < Count; i++ )
+ for (int i = 0; i < Count; i++)
{
QualifiedAce ace = _acl[i] as QualifiedAce;
- if ( ace == null )
+ if (ace == null)
{
continue;
}
- if ( true == MergeAces( ref ace, newAce as QualifiedAce ))
+ if (true == MergeAces(ref ace, newAce as QualifiedAce))
{
aceMerged = true;
break;
// Couldn't modify any existing entry, so add a new one
//
- if ( !aceMerged )
+ if (!aceMerged)
{
- _acl.InsertAce( _acl.Count, newAce );
+ _acl.InsertAce(_acl.Count, newAce);
_isDirty = true;
}
// Helper function behind all the SetXXX methods
//
- internal void SetQualifiedAce( SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType )
+ internal void SetQualifiedAce(SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
{
- if ( sid == null )
+ if (sid == null)
{
- throw new ArgumentNullException( nameof(sid));
+ throw new ArgumentNullException(nameof(sid));
}
- if ( qualifier == AceQualifier.SystemAudit &&
- (( flags & AceFlags.AuditFlags ) == 0 ))
+ if (qualifier == AceQualifier.SystemAudit &&
+ ((flags & AceFlags.AuditFlags) == 0))
{
throw new ArgumentException(
SR.Arg_EnumAtLeastOneFlag,
nameof(flags));
}
- if ( accessMask == 0 )
+ if (accessMask == 0)
{
throw new ArgumentException(
SR.Argument_ArgumentZero,
GenericAce newAce;
- if (( !IsDS ) || ( objectFlags == ObjectAceFlags.None ))
+ if ((!IsDS) || (objectFlags == ObjectAceFlags.None))
{
- newAce = new CommonAce( flags, qualifier, accessMask, sid, false, null );
+ newAce = new CommonAce(flags, qualifier, accessMask, sid, false, null);
}
else
{
- newAce = new ObjectAce( flags, qualifier, accessMask, sid, objectFlags, objectType, inheritedObjectType, false, null );
+ newAce = new ObjectAce(flags, qualifier, accessMask, sid, objectFlags, objectType, inheritedObjectType, false, null);
}
//
// Make sure the new ACE wouldn't be meaningless before proceeding
//
- if ( false == InspectAce( ref newAce, ( this is DiscretionaryAcl )))
+ if (false == InspectAce(ref newAce, (this is DiscretionaryAcl)))
{
return;
}
- for ( int i = 0; i < Count; i++ )
+ for (int i = 0; i < Count; i++)
{
QualifiedAce ace = _acl[i] as QualifiedAce;
// Not a qualified ACE - keep going
//
- if ( ace == null )
+ if (ace == null)
{
continue;
}
// Only interested in explicit (non-inherited) ACEs
//
- if (( ace.AceFlags & AceFlags.Inherited ) != 0 )
+ if ((ace.AceFlags & AceFlags.Inherited) != 0)
{
continue;
}
// Only interested in ACEs with the specified qualifier
//
- if ( ace.AceQualifier != qualifier )
+ if (ace.AceQualifier != qualifier)
{
continue;
}
// Only interested in ACEs with the specified SID
//
- if ( ace.SecurityIdentifier != sid )
+ if (ace.SecurityIdentifier != sid)
{
continue;
}
// This ACE corresponds to the SID and qualifier in question - remove it
//
- _acl.RemoveAce( i );
+ _acl.RemoveAce(i);
i--;
}
// Add it at the end - we'll re-canonicalize later.
//
- _acl.InsertAce( _acl.Count, newAce );
+ _acl.InsertAce(_acl.Count, newAce);
//
// To aid the efficiency of batch operations, recanonicalize this later
// Helper function behind all the RemoveXXX methods
//
- internal bool RemoveQualifiedAces( SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, bool saclSemantics, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType )
+ internal bool RemoveQualifiedAces(SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, bool saclSemantics, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
{
- if ( accessMask == 0 )
+ if (accessMask == 0)
{
throw new ArgumentException(
SR.Argument_ArgumentZero,
nameof(accessMask));
}
- if ( qualifier == AceQualifier.SystemAudit &&
- (( flags & AceFlags.AuditFlags ) == 0 ))
+ if (qualifier == AceQualifier.SystemAudit &&
+ ((flags & AceFlags.AuditFlags) == 0))
{
throw new ArgumentException(
SR.Arg_EnumAtLeastOneFlag,
nameof(flags));
}
- if ( sid == null )
+ if (sid == null)
{
- throw new ArgumentNullException( nameof(sid));
+ throw new ArgumentNullException(nameof(sid));
}
ThrowIfNotCanonical();
//
byte[] recovery = new byte[BinaryLength];
- GetBinaryForm( recovery, 0 );
+ GetBinaryForm(recovery, 0);
MakeAnotherPass:
try
{
- for ( int i = 0; i < Count; i++ )
+ for (int i = 0; i < Count; i++)
{
QualifiedAce ace = _acl[i] as QualifiedAce;
// Not a qualified ACE - keep going
//
- if ( ace == null )
+ if (ace == null)
{
continue;
}
// Only interested in explicit (non-inherited) ACEs
//
- if (( ace.AceFlags & AceFlags.Inherited ) != 0 )
+ if ((ace.AceFlags & AceFlags.Inherited) != 0)
{
continue;
}
// Only interested in ACEs with the specified qualifier
//
- if ( ace.AceQualifier != qualifier )
+ if (ace.AceQualifier != qualifier)
{
continue;
}
// Only interested in ACEs with the specified SID
//
- if ( ace.SecurityIdentifier != sid )
+ if (ace.SecurityIdentifier != sid)
{
continue;
}
// If access masks have nothing in common, skip the whole exercise
//
- if ( IsDS )
+ if (IsDS)
{
//
// incase of directory aces, if the access mask of the
// the object types are different in which case they are really not common bits.
//
accessMask = originalAccessMask;
- bool objectTypesConflict = !GetAccessMaskForRemoval( ace, objectFlags, objectType, ref accessMask );
+ bool objectTypesConflict = !GetAccessMaskForRemoval(ace, objectFlags, objectType, ref accessMask);
// if the access masks have nothing in common, skip
- if (( ace.AccessMask & accessMask ) == 0 )
+ if ((ace.AccessMask & accessMask) == 0)
{
continue;
}
// the inherited object types are different the inheritance may not be common.
//
flags = originalFlags;
- bool inheritedObjectTypesConflict = !GetInheritanceFlagsForRemoval( ace, objectFlags, inheritedObjectType, ref flags );
+ bool inheritedObjectTypesConflict = !GetInheritanceFlagsForRemoval(ace, objectFlags, inheritedObjectType, ref flags);
- if (((( ace.AceFlags & AceFlags.ContainerInherit ) == 0 ) && (( flags & AceFlags.ContainerInherit ) != 0 ) && (( flags & AceFlags.InheritOnly ) != 0 )) ||
- ((( flags & AceFlags.ContainerInherit ) == 0 ) && (( ace.AceFlags & AceFlags.ContainerInherit ) != 0 ) && (( ace.AceFlags & AceFlags.InheritOnly ) != 0)))
+ if ((((ace.AceFlags & AceFlags.ContainerInherit) == 0) && ((flags & AceFlags.ContainerInherit) != 0) && ((flags & AceFlags.InheritOnly) != 0)) ||
+ (((flags & AceFlags.ContainerInherit) == 0) && ((ace.AceFlags & AceFlags.ContainerInherit) != 0) && ((ace.AceFlags & AceFlags.InheritOnly) != 0)))
{
// if one ace applies only to self and the other only to children/descendents we have nothing in common
continue;
// if the ace being removed referred only to child types and child types among existing ace and
// ace being removed are not common then there is nothing in common between these aces (skip)
//
- if ((( originalFlags & AceFlags.ContainerInherit ) != 0 ) && (( originalFlags & AceFlags.InheritOnly ) != 0 ) && (( flags & AceFlags.ContainerInherit ) == 0 ))
+ if (((originalFlags & AceFlags.ContainerInherit) != 0) && ((originalFlags & AceFlags.InheritOnly) != 0) && ((flags & AceFlags.ContainerInherit) == 0))
{
continue;
}
- if ( objectTypesConflict || inheritedObjectTypesConflict )
+ if (objectTypesConflict || inheritedObjectTypesConflict)
{
//
// if we reached this stage, then we've found something common between the two aces.
}
else
{
- if (( ace.AccessMask & accessMask ) == 0 )
+ if ((ace.AccessMask & accessMask) == 0)
{
continue;
}
// skip the whole exercise
//
- if ( saclSemantics &&
- (( ace.AceFlags & flags & AceFlags.AuditFlags ) == 0 ))
+ if (saclSemantics &&
+ ((ace.AceFlags & flags & AceFlags.AuditFlags) == 0))
{
continue;
}
ps_AceFlags = ace.AceFlags;
unchecked { ps_AccessMask = ace.AccessMask & ~accessMask; }
- if ( ace is ObjectAce )
+ if (ace is ObjectAce)
{
//
// determine what should be the object/inherited object types on the permission split
//
- GetObjectTypesForSplit( ace as ObjectAce, ps_AccessMask /* access mask for this split */, ps_AceFlags /* flags remain the same */, out ps_ObjectAceFlags, out ps_ObjectAceType, out ps_InheritedObjectAceType );
+ GetObjectTypesForSplit(ace as ObjectAce, ps_AccessMask /* access mask for this split */, ps_AceFlags /* flags remain the same */, out ps_ObjectAceFlags, out ps_ObjectAceType, out ps_InheritedObjectAceType);
}
//
// Next, for SACLs only, compute the auditing split
//
- if ( saclSemantics )
+ if (saclSemantics)
{
//
// This operation can set the audit bits region
// This case will be handled later
//
- unchecked { as_AceFlags = ace.AceFlags & ~( flags & AceFlags.AuditFlags ); }
+ unchecked { as_AceFlags = ace.AceFlags & ~(flags & AceFlags.AuditFlags); }
//
// The result of this evaluation is guaranteed
// not to be zero by now
//
- as_AccessMask = ( ace.AccessMask & accessMask );
+ as_AccessMask = (ace.AccessMask & accessMask);
- if ( ace is ObjectAce )
+ if (ace is ObjectAce)
{
//
// determine what should be the object/inherited object types on the audit split
//
- GetObjectTypesForSplit( ace as ObjectAce, as_AccessMask /* access mask for this split */, as_AceFlags /* flags remain the same for inheritance */, out as_ObjectAceFlags, out as_ObjectAceType, out as_InheritedObjectAceType );
+ GetObjectTypesForSplit(ace as ObjectAce, as_AccessMask /* access mask for this split */, as_AceFlags /* flags remain the same for inheritance */, out as_ObjectAceFlags, out as_ObjectAceType, out as_InheritedObjectAceType);
}
}
// Finally, compute the merge split
//
- ms_AceFlags = ( ace.AceFlags & AceFlags.InheritanceFlags ) | ( flags & ace.AceFlags & AceFlags.AuditFlags );
- ms_AccessMask = ( ace.AccessMask & accessMask );
+ ms_AceFlags = (ace.AceFlags & AceFlags.InheritanceFlags) | (flags & ace.AceFlags & AceFlags.AuditFlags);
+ ms_AccessMask = (ace.AccessMask & accessMask);
//
// produced no auditing flags
//
- if ( !saclSemantics ||
- (( ms_AceFlags & AceFlags.AuditFlags ) != 0 ))
+ if (!saclSemantics ||
+ ((ms_AceFlags & AceFlags.AuditFlags) != 0))
{
- if ( false == RemoveInheritanceBits( ms_AceFlags, flags, IsDS, out mergeResultFlags, out mergeRemoveTotal ))
+ if (false == RemoveInheritanceBits(ms_AceFlags, flags, IsDS, out mergeResultFlags, out mergeRemoveTotal))
{
removePossible = false;
break;
}
- if ( !mergeRemoveTotal )
+ if (!mergeRemoveTotal)
{
- mergeResultFlags |= ( ms_AceFlags & AceFlags.AuditFlags );
+ mergeResultFlags |= (ms_AceFlags & AceFlags.AuditFlags);
- if ( ace is ObjectAce )
+ if (ace is ObjectAce)
{
//
// determine what should be the object/inherited object types on the merge split
//
- GetObjectTypesForSplit( ace as ObjectAce, ms_AccessMask /* access mask for this split */, mergeResultFlags /* flags for this split */, out ms_ObjectAceFlags, out ms_ObjectAceType, out ms_InheritedObjectAceType );
+ GetObjectTypesForSplit(ace as ObjectAce, ms_AccessMask /* access mask for this split */, mergeResultFlags /* flags for this split */, out ms_ObjectAceFlags, out ms_ObjectAceType, out ms_InheritedObjectAceType);
}
}
}
// If this is no longer an evaluation, go ahead and make the changes
//
- if ( !evaluationPass )
+ if (!evaluationPass)
{
QualifiedAce newAce;
// we would be changing the size of this ace
//
- if ( ps_AccessMask != 0 )
+ if (ps_AccessMask != 0)
{
- if (( ace is ObjectAce ) &&
- (((( ObjectAce) ace ).ObjectAceFlags & ObjectAceFlags.ObjectAceTypePresent ) != 0 ) &&
- (( ps_ObjectAceFlags & ObjectAceFlags.ObjectAceTypePresent ) == 0 ))
+ if ((ace is ObjectAce) &&
+ ((((ObjectAce)ace).ObjectAceFlags & ObjectAceFlags.ObjectAceTypePresent) != 0) &&
+ ((ps_ObjectAceFlags & ObjectAceFlags.ObjectAceTypePresent) == 0))
{
ObjectAce newObjectAce;
_acl.RemoveAce(i);
- newObjectAce = new ObjectAce( ps_AceFlags, qualifier, ps_AccessMask, ace.SecurityIdentifier, ps_ObjectAceFlags, ps_ObjectAceType, ps_InheritedObjectAceType, false, null );
- _acl.InsertAce( i, newObjectAce );
+ newObjectAce = new ObjectAce(ps_AceFlags, qualifier, ps_AccessMask, ace.SecurityIdentifier, ps_ObjectAceFlags, ps_ObjectAceType, ps_InheritedObjectAceType, false, null);
+ _acl.InsertAce(i, newObjectAce);
}
else
{
ace.AceFlags = ps_AceFlags;
ace.AccessMask = ps_AccessMask;
- if ( ace is ObjectAce )
+ if (ace is ObjectAce)
{
ObjectAce objectAce = ace as ObjectAce;
// On a SACL, the result of the auditing split must be recorded
//
- if ( saclSemantics && (( as_AceFlags & AceFlags.AuditFlags ) != 0 ))
+ if (saclSemantics && ((as_AceFlags & AceFlags.AuditFlags) != 0))
{
- if ( ace is CommonAce )
+ if (ace is CommonAce)
{
- newAce = new CommonAce( as_AceFlags, qualifier, as_AccessMask, ace.SecurityIdentifier, false, null );
+ newAce = new CommonAce(as_AceFlags, qualifier, as_AccessMask, ace.SecurityIdentifier, false, null);
}
else
{
// object ace
- newAce = new ObjectAce( as_AceFlags, qualifier, as_AccessMask, ace.SecurityIdentifier, as_ObjectAceFlags, as_ObjectAceType, as_InheritedObjectAceType, false, null );
+ newAce = new ObjectAce(as_AceFlags, qualifier, as_AccessMask, ace.SecurityIdentifier, as_ObjectAceFlags, as_ObjectAceType, as_InheritedObjectAceType, false, null);
}
i++; // so it's not considered again
- _acl.InsertAce( i, newAce );
+ _acl.InsertAce(i, newAce);
}
//
// as a separate ACE
//
- if ( !mergeRemoveTotal )
+ if (!mergeRemoveTotal)
{
- if ( ace is CommonAce )
+ if (ace is CommonAce)
{
- newAce = new CommonAce( mergeResultFlags, qualifier, ms_AccessMask, ace.SecurityIdentifier, false, null );
+ newAce = new CommonAce(mergeResultFlags, qualifier, ms_AccessMask, ace.SecurityIdentifier, false, null);
}
else
{
// object ace
- newAce = new ObjectAce( mergeResultFlags, qualifier, ms_AccessMask, ace.SecurityIdentifier, ms_ObjectAceFlags, ms_ObjectAceType, ms_InheritedObjectAceType, false, null );
+ newAce = new ObjectAce(mergeResultFlags, qualifier, ms_AccessMask, ace.SecurityIdentifier, ms_ObjectAceFlags, ms_ObjectAceType, ms_InheritedObjectAceType, false, null);
}
i++; // so it's not considered again
- _acl.InsertAce( i, newAce );
+ _acl.InsertAce(i, newAce);
}
}
}
}
- catch ( OverflowException )
+ catch (OverflowException)
{
//
// Oops, overflow means that the ACL became too big.
// Inform the caller that the remove was not possible.
//
- _acl.SetBinaryForm( recovery, 0 );
+ _acl.SetBinaryForm(recovery, 0);
return false;
}
// If it looks like it's doable, go ahead and do it.
//
- if ( evaluationPass && removePossible )
+ if (evaluationPass && removePossible)
{
evaluationPass = false;
goto MakeAnotherPass;
return removePossible;
}
- internal void RemoveQualifiedAcesSpecific( SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType )
+ internal void RemoveQualifiedAcesSpecific(SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
{
- if ( accessMask == 0 )
+ if (accessMask == 0)
{
throw new ArgumentException(
SR.Argument_ArgumentZero,
nameof(accessMask));
}
- if ( qualifier == AceQualifier.SystemAudit &&
- (( flags & AceFlags.AuditFlags ) == 0 ))
+ if (qualifier == AceQualifier.SystemAudit &&
+ ((flags & AceFlags.AuditFlags) == 0))
{
throw new ArgumentException(
SR.Arg_EnumAtLeastOneFlag,
nameof(flags));
}
- if ( sid == null )
+ if (sid == null)
{
- throw new ArgumentNullException( nameof(sid));
+ throw new ArgumentNullException(nameof(sid));
}
ThrowIfNotCanonical();
- for ( int i = 0; i < Count; i++ )
+ for (int i = 0; i < Count; i++)
{
QualifiedAce ace = _acl[i] as QualifiedAce;
// Not a qualified ACE - keep going
//
- if ( ace == null )
+ if (ace == null)
{
continue;
}
// Only interested in explicit (non-inherited) ACEs
//
- if (( ace.AceFlags & AceFlags.Inherited ) != 0 )
+ if ((ace.AceFlags & AceFlags.Inherited) != 0)
{
continue;
}
// Only interested in ACEs with the specified qualifier
//
- if ( ace.AceQualifier != qualifier )
+ if (ace.AceQualifier != qualifier)
{
continue;
}
// Only interested in ACEs with the specified SID
//
- if ( ace.SecurityIdentifier != sid )
+ if (ace.SecurityIdentifier != sid)
{
continue;
}
// Only interested in exact ACE flag matches
//
- if ( ace.AceFlags != flags )
+ if (ace.AceFlags != flags)
{
continue;
}
// Only interested in exact access mask matches
//
- if ( ace.AccessMask != accessMask )
+ if (ace.AccessMask != accessMask)
{
continue;
}
- if ( IsDS )
+ if (IsDS)
{
//
// Incase of object aces, only interested in ACEs which match in their
// objectType and inheritedObjectType
//
- if (( ace is ObjectAce ) && ( objectFlags != ObjectAceFlags.None ))
+ if ((ace is ObjectAce) && (objectFlags != ObjectAceFlags.None))
{
//
// both are object aces, so must match in object type and inherited object type
//
ObjectAce objectAce = ace as ObjectAce;
- if (( !objectAce.ObjectTypesMatch( objectFlags, objectType ))
- || ( !objectAce.InheritedObjectTypesMatch( objectFlags, inheritedObjectType )))
+ if ((!objectAce.ObjectTypesMatch(objectFlags, objectType))
+ || (!objectAce.InheritedObjectTypesMatch(objectFlags, inheritedObjectType)))
{
continue;
}
}
- else if (( ace is ObjectAce ) || ( objectFlags != ObjectAceFlags.None ))
+ else if ((ace is ObjectAce) || (objectFlags != ObjectAceFlags.None))
{
// one is object ace and the other is not, so no match
continue;
// Returns the binary representation of the ACL
//
- public sealed override void GetBinaryForm( byte[] binaryForm, int offset )
+ public sealed override void GetBinaryForm(byte[] binaryForm, int offset)
{
CanonicalizeIfNecessary();
- _acl.GetBinaryForm( binaryForm, offset );
+ _acl.GetBinaryForm(binaryForm, offset);
}
//
set
{
- throw new NotSupportedException( SR.NotSupported_SetMethod );
+ throw new NotSupportedException(SR.NotSupported_SetMethod);
}
}
// are usually in the back of the ACL
//
- for ( int i = _acl.Count - 1; i >= 0; i-- )
+ for (int i = _acl.Count - 1; i >= 0; i--)
{
GenericAce ace = _acl[i];
- if (( ace.AceFlags & AceFlags.Inherited ) != 0 )
+ if ((ace.AceFlags & AceFlags.Inherited) != 0)
{
- _acl.RemoveAce( i );
+ _acl.RemoveAce(i);
}
}
OnAclModificationTried();
}
- public void Purge( SecurityIdentifier sid )
+ public void Purge(SecurityIdentifier sid)
{
- if ( sid == null )
+ if (sid == null)
{
- throw new ArgumentNullException( nameof(sid));
+ throw new ArgumentNullException(nameof(sid));
}
ThrowIfNotCanonical();
- for ( int i = Count - 1; i >= 0; i-- )
+ for (int i = Count - 1; i >= 0; i--)
{
KnownAce ace = _acl[i] as KnownAce;
// Skip over unknown ACEs
//
- if ( ace == null )
+ if (ace == null)
{
continue;
}
// Skip over inherited ACEs
//
- if (( ace.AceFlags & AceFlags.Inherited ) != 0 )
+ if ((ace.AceFlags & AceFlags.Inherited) != 0)
{
continue;
}
// SID matches - ACE is out
//
- if ( ace.SecurityIdentifier == sid )
+ if (ace.SecurityIdentifier == sid)
{
- _acl.RemoveAce( i );
+ _acl.RemoveAce(i);
}
}
OnAclModificationTried();
// Creates an emtpy ACL
//
- public SystemAcl( bool isContainer, bool isDS, int capacity )
- : this( isContainer, isDS, isDS ? AclRevisionDS : AclRevision, capacity )
+ public SystemAcl(bool isContainer, bool isDS, int capacity)
+ : this(isContainer, isDS, isDS ? AclRevisionDS : AclRevision, capacity)
{
}
- public SystemAcl( bool isContainer, bool isDS, byte revision, int capacity )
- : base( isContainer, isDS, revision, capacity )
+ public SystemAcl(bool isContainer, bool isDS, byte revision, int capacity)
+ : base(isContainer, isDS, revision, capacity)
{
}
// after canonicalizing it
//
- public SystemAcl( bool isContainer, bool isDS, RawAcl rawAcl )
- : this( isContainer, isDS, rawAcl, false )
+ public SystemAcl(bool isContainer, bool isDS, RawAcl rawAcl)
+ : this(isContainer, isDS, rawAcl, false)
{
}
// takes ownership of the given raw ACL
//
- internal SystemAcl( bool isContainer, bool isDS, RawAcl rawAcl, bool trusted )
- : base( isContainer, isDS, rawAcl, trusted, false )
+ internal SystemAcl(bool isContainer, bool isDS, RawAcl rawAcl, bool trusted)
+ : base(isContainer, isDS, rawAcl, trusted, false)
{
}
#region Public Methods
- public void AddAudit( AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags )
+ public void AddAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
{
- CheckFlags( inheritanceFlags, propagationFlags );
- AddQualifiedAce( sid, AceQualifier.SystemAudit, accessMask, GenericAce.AceFlagsFromAuditFlags( auditFlags ) | GenericAce.AceFlagsFromInheritanceFlags( inheritanceFlags, propagationFlags ), ObjectAceFlags.None, Guid.Empty, Guid.Empty );
+ CheckFlags(inheritanceFlags, propagationFlags);
+ AddQualifiedAce(sid, AceQualifier.SystemAudit, accessMask, GenericAce.AceFlagsFromAuditFlags(auditFlags) | GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), ObjectAceFlags.None, Guid.Empty, Guid.Empty);
}
- public void SetAudit( AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags )
+ public void SetAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
{
- CheckFlags( inheritanceFlags, propagationFlags );
- SetQualifiedAce( sid, AceQualifier.SystemAudit, accessMask, GenericAce.AceFlagsFromAuditFlags( auditFlags ) | GenericAce.AceFlagsFromInheritanceFlags( inheritanceFlags, propagationFlags ), ObjectAceFlags.None, Guid.Empty, Guid.Empty );
+ CheckFlags(inheritanceFlags, propagationFlags);
+ SetQualifiedAce(sid, AceQualifier.SystemAudit, accessMask, GenericAce.AceFlagsFromAuditFlags(auditFlags) | GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), ObjectAceFlags.None, Guid.Empty, Guid.Empty);
}
- public bool RemoveAudit( AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags )
+ public bool RemoveAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
{
- return RemoveQualifiedAces(sid, AceQualifier.SystemAudit, accessMask, GenericAce.AceFlagsFromAuditFlags( auditFlags ) | GenericAce.AceFlagsFromInheritanceFlags( inheritanceFlags, propagationFlags ), true, ObjectAceFlags.None, Guid.Empty, Guid.Empty );
+ return RemoveQualifiedAces(sid, AceQualifier.SystemAudit, accessMask, GenericAce.AceFlagsFromAuditFlags(auditFlags) | GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), true, ObjectAceFlags.None, Guid.Empty, Guid.Empty);
}
- public void RemoveAuditSpecific( AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags )
+ public void RemoveAuditSpecific(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
{
- RemoveQualifiedAcesSpecific( sid, AceQualifier.SystemAudit, accessMask, GenericAce.AceFlagsFromAuditFlags( auditFlags ) | GenericAce.AceFlagsFromInheritanceFlags( inheritanceFlags, propagationFlags ), ObjectAceFlags.None, Guid.Empty, Guid.Empty );
+ RemoveQualifiedAcesSpecific(sid, AceQualifier.SystemAudit, accessMask, GenericAce.AceFlagsFromAuditFlags(auditFlags) | GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), ObjectAceFlags.None, Guid.Empty, Guid.Empty);
}
public void AddAudit(SecurityIdentifier sid, ObjectAuditRule rule)
//
// This is valid only for DS Acls
//
- if ( !IsDS )
+ if (!IsDS)
{
throw new InvalidOperationException(
- SR.InvalidOperation_OnlyValidForDS );
+ SR.InvalidOperation_OnlyValidForDS);
}
- CheckFlags( inheritanceFlags, propagationFlags );
+ CheckFlags(inheritanceFlags, propagationFlags);
AddQualifiedAce(sid, AceQualifier.SystemAudit, accessMask, GenericAce.AceFlagsFromAuditFlags(auditFlags) | GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), objectFlags, objectType, inheritedObjectType);
}
//
// This is valid only for DS Acls
//
- if ( !IsDS )
+ if (!IsDS)
{
throw new InvalidOperationException(
- SR.InvalidOperation_OnlyValidForDS );
+ SR.InvalidOperation_OnlyValidForDS);
}
- CheckFlags( inheritanceFlags, propagationFlags );
+ CheckFlags(inheritanceFlags, propagationFlags);
SetQualifiedAce(sid, AceQualifier.SystemAudit, accessMask, GenericAce.AceFlagsFromAuditFlags(auditFlags) | GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), objectFlags, objectType, inheritedObjectType);
}
//
// This is valid only for DS Acls
//
- if ( !IsDS )
+ if (!IsDS)
{
throw new InvalidOperationException(
- SR.InvalidOperation_OnlyValidForDS );
+ SR.InvalidOperation_OnlyValidForDS);
}
return RemoveQualifiedAces(sid, AceQualifier.SystemAudit, accessMask, GenericAce.AceFlagsFromAuditFlags(auditFlags) | GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), true, objectFlags, objectType, inheritedObjectType);
//
// This is valid only for DS Acls
//
- if ( !IsDS )
+ if (!IsDS)
{
throw new InvalidOperationException(
- SR.InvalidOperation_OnlyValidForDS );
+ SR.InvalidOperation_OnlyValidForDS);
}
RemoveQualifiedAcesSpecific(sid, AceQualifier.SystemAudit, accessMask, GenericAce.AceFlagsFromAuditFlags(auditFlags) | GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), objectFlags, objectType, inheritedObjectType);
public sealed class DiscretionaryAcl : CommonAcl
{
#region
- private static readonly SecurityIdentifier _sidEveryone = new SecurityIdentifier( WellKnownSidType.WorldSid, null );
+ private static readonly SecurityIdentifier _sidEveryone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
private bool everyOneFullAccessForNullDacl = false;
#endregion
// Creates an emtpy ACL
//
- public DiscretionaryAcl( bool isContainer, bool isDS, int capacity )
- : this( isContainer, isDS, isDS ? AclRevisionDS : AclRevision, capacity )
+ public DiscretionaryAcl(bool isContainer, bool isDS, int capacity)
+ : this(isContainer, isDS, isDS ? AclRevisionDS : AclRevision, capacity)
{
}
- public DiscretionaryAcl( bool isContainer, bool isDS, byte revision, int capacity )
- : base( isContainer, isDS, revision, capacity )
+ public DiscretionaryAcl(bool isContainer, bool isDS, byte revision, int capacity)
+ : base(isContainer, isDS, revision, capacity)
{
}
// after canonicalizing it
//
- public DiscretionaryAcl( bool isContainer, bool isDS, RawAcl rawAcl )
- : this( isContainer, isDS, rawAcl, false )
+ public DiscretionaryAcl(bool isContainer, bool isDS, RawAcl rawAcl)
+ : this(isContainer, isDS, rawAcl, false)
{
}
// takes ownership of the given raw ACL
//
- internal DiscretionaryAcl( bool isContainer, bool isDS, RawAcl rawAcl, bool trusted )
- : base( isContainer, isDS, rawAcl == null ? new RawAcl( isDS ? AclRevisionDS : AclRevision, 0 ) : rawAcl, trusted, true )
+ internal DiscretionaryAcl(bool isContainer, bool isDS, RawAcl rawAcl, bool trusted)
+ : base(isContainer, isDS, rawAcl == null ? new RawAcl(isDS ? AclRevisionDS : AclRevision, 0) : rawAcl, trusted, true)
{
}
#region Public Methods
- public void AddAccess( AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags )
+ public void AddAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
{
- CheckAccessType( accessType );
- CheckFlags( inheritanceFlags, propagationFlags );
+ CheckAccessType(accessType);
+ CheckFlags(inheritanceFlags, propagationFlags);
everyOneFullAccessForNullDacl = false;
- AddQualifiedAce( sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags( inheritanceFlags, propagationFlags ), ObjectAceFlags.None, Guid.Empty, Guid.Empty );
+ AddQualifiedAce(sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), ObjectAceFlags.None, Guid.Empty, Guid.Empty);
}
- public void SetAccess( AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags )
+ public void SetAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
{
- CheckAccessType( accessType );
- CheckFlags( inheritanceFlags, propagationFlags );
+ CheckAccessType(accessType);
+ CheckFlags(inheritanceFlags, propagationFlags);
everyOneFullAccessForNullDacl = false;
- SetQualifiedAce( sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags( inheritanceFlags, propagationFlags ), ObjectAceFlags.None, Guid.Empty, Guid.Empty );
+ SetQualifiedAce(sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), ObjectAceFlags.None, Guid.Empty, Guid.Empty);
}
- public bool RemoveAccess( AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags )
+ public bool RemoveAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
{
- CheckAccessType( accessType );
+ CheckAccessType(accessType);
everyOneFullAccessForNullDacl = false;
- return RemoveQualifiedAces( sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags( inheritanceFlags, propagationFlags ), false, ObjectAceFlags.None, Guid.Empty, Guid.Empty );
+ return RemoveQualifiedAces(sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), false, ObjectAceFlags.None, Guid.Empty, Guid.Empty);
}
- public void RemoveAccessSpecific( AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags )
+ public void RemoveAccessSpecific(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
{
- CheckAccessType( accessType );
+ CheckAccessType(accessType);
everyOneFullAccessForNullDacl = false;
- RemoveQualifiedAcesSpecific(sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags( inheritanceFlags, propagationFlags ), ObjectAceFlags.None, Guid.Empty, Guid.Empty );
+ RemoveQualifiedAcesSpecific(sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), ObjectAceFlags.None, Guid.Empty, Guid.Empty);
}
public void AddAccess(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule)
//
// This is valid only for DS Acls
//
- if ( !IsDS )
+ if (!IsDS)
{
throw new InvalidOperationException(
- SR.InvalidOperation_OnlyValidForDS );
+ SR.InvalidOperation_OnlyValidForDS);
}
- CheckAccessType( accessType );
- CheckFlags( inheritanceFlags, propagationFlags );
+ CheckAccessType(accessType);
+ CheckFlags(inheritanceFlags, propagationFlags);
everyOneFullAccessForNullDacl = false;
- AddQualifiedAce( sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags( inheritanceFlags, propagationFlags ), objectFlags, objectType, inheritedObjectType );
+ AddQualifiedAce(sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), objectFlags, objectType, inheritedObjectType);
}
public void SetAccess(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule)
//
// This is valid only for DS Acls
//
- if ( !IsDS )
+ if (!IsDS)
{
throw new InvalidOperationException(
- SR.InvalidOperation_OnlyValidForDS );
+ SR.InvalidOperation_OnlyValidForDS);
}
- CheckAccessType( accessType );
- CheckFlags( inheritanceFlags, propagationFlags );
+ CheckAccessType(accessType);
+ CheckFlags(inheritanceFlags, propagationFlags);
everyOneFullAccessForNullDacl = false;
- SetQualifiedAce( sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags( inheritanceFlags, propagationFlags ), objectFlags, objectType, inheritedObjectType);
+ SetQualifiedAce(sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), objectFlags, objectType, inheritedObjectType);
}
public bool RemoveAccess(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule)
//
// This is valid only for DS Acls
//
- if ( !IsDS )
+ if (!IsDS)
{
throw new InvalidOperationException(
- SR.InvalidOperation_OnlyValidForDS );
+ SR.InvalidOperation_OnlyValidForDS);
}
- CheckAccessType( accessType );
+ CheckAccessType(accessType);
everyOneFullAccessForNullDacl = false;
- return RemoveQualifiedAces(sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags( inheritanceFlags, propagationFlags ), false, objectFlags, objectType, inheritedObjectType );
+ return RemoveQualifiedAces(sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), false, objectFlags, objectType, inheritedObjectType);
}
public void RemoveAccessSpecific(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule)
//
// This is valid only for DS Acls
//
- if ( !IsDS )
+ if (!IsDS)
{
throw new InvalidOperationException(
- SR.InvalidOperation_OnlyValidForDS );
+ SR.InvalidOperation_OnlyValidForDS);
}
- CheckAccessType( accessType );
+ CheckAccessType(accessType);
everyOneFullAccessForNullDacl = false;
- RemoveQualifiedAcesSpecific( sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags( inheritanceFlags, propagationFlags ), objectFlags, objectType, inheritedObjectType );
+ RemoveQualifiedAcesSpecific(sid, accessType == AccessControlType.Allow ? AceQualifier.AccessAllowed : AceQualifier.AccessDenied, accessMask, GenericAce.AceFlagsFromInheritanceFlags(inheritanceFlags, propagationFlags), objectFlags, objectType, inheritedObjectType);
}
#endregion
/// single ACE DACL to replace null DACL from CommonSecurityObject.
internal static DiscretionaryAcl CreateAllowEveryoneFullAccess(bool isDS, bool isContainer)
{
- DiscretionaryAcl dcl = new DiscretionaryAcl( isContainer, isDS, 1 );
+ DiscretionaryAcl dcl = new DiscretionaryAcl(isContainer, isDS, 1);
dcl.AddAccess(
AccessControlType.Allow,
_sidEveryone,
-1,
- isContainer ? ( InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit ) : InheritanceFlags.None,
- PropagationFlags.None );
+ isContainer ? (InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit) : InheritanceFlags.None,
+ PropagationFlags.None);
dcl.everyOneFullAccessForNullDacl = true;
return dcl;
public enum AccessControlModification
{
- Add = 0,
- Set = 1,
- Reset = 2,
- Remove = 3,
- RemoveAll = 4,
- RemoveSpecific = 5,
+ Add = 0,
+ Set = 1,
+ Reset = 2,
+ Remove = 3,
+ RemoveAll = 4,
+ RemoveSpecific = 5,
}
{
}
- protected ObjectSecurity( bool isContainer, bool isDS )
+ protected ObjectSecurity(bool isContainer, bool isDS)
: this()
{
// we will create an empty DACL, denying anyone any access as the default. 5 is the capacity.
DiscretionaryAcl dacl = new DiscretionaryAcl(isContainer, isDS, 5);
- _securityDescriptor = new CommonSecurityDescriptor( isContainer, isDS, ControlFlags.None, null, null, null, dacl );
+ _securityDescriptor = new CommonSecurityDescriptor(isContainer, isDS, ControlFlags.None, null, null, null, dacl);
}
protected ObjectSecurity(CommonSecurityDescriptor securityDescriptor)
: this()
{
- if ( securityDescriptor == null )
+ if (securityDescriptor == null)
{
- throw new ArgumentNullException( nameof(securityDescriptor));
+ throw new ArgumentNullException(nameof(securityDescriptor));
}
- _securityDescriptor = securityDescriptor;
+ _securityDescriptor = securityDescriptor;
}
#endregion
#region Private methods
- private void UpdateWithNewSecurityDescriptor( RawSecurityDescriptor newOne, AccessControlSections includeSections )
+ private void UpdateWithNewSecurityDescriptor(RawSecurityDescriptor newOne, AccessControlSections includeSections)
{
- Debug.Assert( newOne != null, "Must not supply a null parameter here" );
+ Debug.Assert(newOne != null, "Must not supply a null parameter here");
- if (( includeSections & AccessControlSections.Owner ) != 0 )
+ if ((includeSections & AccessControlSections.Owner) != 0)
{
_ownerModified = true;
_securityDescriptor.Owner = newOne.Owner;
}
- if (( includeSections & AccessControlSections.Group ) != 0 )
+ if ((includeSections & AccessControlSections.Group) != 0)
{
_groupModified = true;
_securityDescriptor.Group = newOne.Group;
}
- if (( includeSections & AccessControlSections.Audit ) != 0 )
+ if ((includeSections & AccessControlSections.Audit) != 0)
{
_saclModified = true;
- if ( newOne.SystemAcl != null )
+ if (newOne.SystemAcl != null)
{
- _securityDescriptor.SystemAcl = new SystemAcl( IsContainer, IsDS, newOne.SystemAcl, true );
+ _securityDescriptor.SystemAcl = new SystemAcl(IsContainer, IsDS, newOne.SystemAcl, true);
}
else
{
_securityDescriptor.UpdateControlFlags(SACL_CONTROL_FLAGS, (ControlFlags)(newOne.ControlFlags & SACL_CONTROL_FLAGS));
}
- if (( includeSections & AccessControlSections.Access ) != 0 )
+ if ((includeSections & AccessControlSections.Access) != 0)
{
_daclModified = true;
- if ( newOne.DiscretionaryAcl != null )
+ if (newOne.DiscretionaryAcl != null)
{
- _securityDescriptor.DiscretionaryAcl = new DiscretionaryAcl( IsContainer, IsDS, newOne.DiscretionaryAcl, true );
+ _securityDescriptor.DiscretionaryAcl = new DiscretionaryAcl(IsContainer, IsDS, newOne.DiscretionaryAcl, true);
}
else
{
_securityDescriptor.UpdateControlFlags(DACL_CONTROL_FLAGS,
(ControlFlags)((newOne.ControlFlags | daclFlag) & DACL_CONTROL_FLAGS));
}
- }
+ }
#endregion
{
get
{
- if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld ))
+ if (!(_lock.IsReadLockHeld || _lock.IsWriteLockHeld))
{
- throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite );
+ throw new InvalidOperationException(SR.InvalidOperation_MustLockForReadOrWrite);
}
return _ownerModified;
set
{
- if ( !_lock.IsWriteLockHeld )
+ if (!_lock.IsWriteLockHeld)
{
- throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite );
+ throw new InvalidOperationException(SR.InvalidOperation_MustLockForWrite);
}
_ownerModified = value;
{
get
{
- if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld ))
+ if (!(_lock.IsReadLockHeld || _lock.IsWriteLockHeld))
{
- throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite );
+ throw new InvalidOperationException(SR.InvalidOperation_MustLockForReadOrWrite);
}
return _groupModified;
set
{
- if ( !_lock.IsWriteLockHeld )
+ if (!_lock.IsWriteLockHeld)
{
- throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite );
+ throw new InvalidOperationException(SR.InvalidOperation_MustLockForWrite);
}
_groupModified = value;
{
get
{
- if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld ))
+ if (!(_lock.IsReadLockHeld || _lock.IsWriteLockHeld))
{
- throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite );
+ throw new InvalidOperationException(SR.InvalidOperation_MustLockForReadOrWrite);
}
return _saclModified;
set
{
- if ( !_lock.IsWriteLockHeld )
+ if (!_lock.IsWriteLockHeld)
{
- throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite );
+ throw new InvalidOperationException(SR.InvalidOperation_MustLockForWrite);
}
_saclModified = value;
{
get
{
- if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld ))
+ if (!(_lock.IsReadLockHeld || _lock.IsWriteLockHeld))
{
- throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite );
+ throw new InvalidOperationException(SR.InvalidOperation_MustLockForReadOrWrite);
}
return _daclModified;
set
{
- if ( !_lock.IsWriteLockHeld )
+ if (!_lock.IsWriteLockHeld)
{
- throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite );
+ throw new InvalidOperationException(SR.InvalidOperation_MustLockForWrite);
}
_daclModified = value;
// This overloaded method takes a name of an existing object
//
- protected virtual void Persist( string name, AccessControlSections includeSections )
+ protected virtual void Persist(string name, AccessControlSections includeSections)
{
throw NotImplemented.ByDesign;
}
// privilege while persisting if the enableOwnershipPrivilege is true.
// Integrators can override it if this is not desired.
//
- protected virtual void Persist(bool enableOwnershipPrivilege, string name, AccessControlSections includeSections )
+ protected virtual void Persist(bool enableOwnershipPrivilege, string name, AccessControlSections includeSections)
{
Privilege ownerPrivilege = null;
catch
{
// protection against exception filter-based luring attacks
- if ( ownerPrivilege != null )
+ if (ownerPrivilege != null)
{
ownerPrivilege.Revert();
}
// This overloaded method takes a handle to an existing object
//
- protected virtual void Persist( SafeHandle handle, AccessControlSections includeSections )
+ protected virtual void Persist(SafeHandle handle, AccessControlSections includeSections)
{
throw NotImplemented.ByDesign;
}
// Sets and retrieves the owner of this object
//
- public IdentityReference GetOwner( System.Type targetType )
+ public IdentityReference GetOwner(System.Type targetType)
{
ReadLock();
try
{
- if ( _securityDescriptor.Owner == null )
+ if (_securityDescriptor.Owner == null)
{
return null;
}
- return _securityDescriptor.Owner.Translate( targetType );
+ return _securityDescriptor.Owner.Translate(targetType);
}
finally
{
}
}
- public void SetOwner( IdentityReference identity )
+ public void SetOwner(IdentityReference identity)
{
- if ( identity == null )
+ if (identity == null)
{
- throw new ArgumentNullException( nameof(identity));
+ throw new ArgumentNullException(nameof(identity));
}
WriteLock();
try
{
- _securityDescriptor.Owner = identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier;
+ _securityDescriptor.Owner = identity.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier;
_ownerModified = true;
}
finally
// Sets and retrieves the group of this object
//
- public IdentityReference GetGroup( System.Type targetType )
+ public IdentityReference GetGroup(System.Type targetType)
{
ReadLock();
try
{
- if ( _securityDescriptor.Group == null )
+ if (_securityDescriptor.Group == null)
{
return null;
}
- return _securityDescriptor.Group.Translate( targetType );
+ return _securityDescriptor.Group.Translate(targetType);
}
finally
{
}
}
- public void SetGroup( IdentityReference identity )
+ public void SetGroup(IdentityReference identity)
{
- if ( identity == null )
+ if (identity == null)
{
- throw new ArgumentNullException( nameof(identity));
+ throw new ArgumentNullException(nameof(identity));
}
WriteLock();
try
{
- _securityDescriptor.Group = identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier;
+ _securityDescriptor.Group = identity.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier;
_groupModified = true;
}
finally
}
}
- public virtual void PurgeAccessRules( IdentityReference identity )
+ public virtual void PurgeAccessRules(IdentityReference identity)
{
- if ( identity == null )
+ if (identity == null)
{
- throw new ArgumentNullException( nameof(identity));
+ throw new ArgumentNullException(nameof(identity));
}
WriteLock();
try
{
- _securityDescriptor.PurgeAccessControl( identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier );
+ _securityDescriptor.PurgeAccessControl(identity.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier);
_daclModified = true;
}
finally
public virtual void PurgeAuditRules(IdentityReference identity)
{
- if ( identity == null )
+ if (identity == null)
{
- throw new ArgumentNullException( nameof(identity));
+ throw new ArgumentNullException(nameof(identity));
}
WriteLock();
try
{
- _securityDescriptor.PurgeAudit( identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier );
+ _securityDescriptor.PurgeAudit(identity.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier);
_saclModified = true;
}
finally
try
{
- return (( _securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected ) != 0 );
+ return ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0);
}
finally
{
}
}
- public void SetAccessRuleProtection( bool isProtected, bool preserveInheritance )
+ public void SetAccessRuleProtection(bool isProtected, bool preserveInheritance)
{
WriteLock();
try
{
- _securityDescriptor.SetDiscretionaryAclProtection( isProtected, preserveInheritance );
+ _securityDescriptor.SetDiscretionaryAclProtection(isProtected, preserveInheritance);
_daclModified = true;
}
finally
try
{
- return (( _securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected ) != 0 );
+ return ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != 0);
}
finally
{
}
}
- public void SetAuditRuleProtection( bool isProtected, bool preserveInheritance )
+ public void SetAuditRuleProtection(bool isProtected, bool preserveInheritance)
{
WriteLock();
try
{
- _securityDescriptor.SetSystemAclProtection( isProtected, preserveInheritance );
+ _securityDescriptor.SetSystemAclProtection(isProtected, preserveInheritance);
_saclModified = true;
}
finally
return true; // SDDL to binary conversions are supported on Windows 2000 and higher
}
- public string GetSecurityDescriptorSddlForm( AccessControlSections includeSections )
+ public string GetSecurityDescriptorSddlForm(AccessControlSections includeSections)
{
ReadLock();
try
{
- return _securityDescriptor.GetSddlForm( includeSections );
+ return _securityDescriptor.GetSddlForm(includeSections);
}
finally
{
}
}
- public void SetSecurityDescriptorSddlForm( string sddlForm )
+ public void SetSecurityDescriptorSddlForm(string sddlForm)
{
- SetSecurityDescriptorSddlForm( sddlForm, AccessControlSections.All );
+ SetSecurityDescriptorSddlForm(sddlForm, AccessControlSections.All);
}
- public void SetSecurityDescriptorSddlForm( string sddlForm, AccessControlSections includeSections )
+ public void SetSecurityDescriptorSddlForm(string sddlForm, AccessControlSections includeSections)
{
- if ( sddlForm == null )
+ if (sddlForm == null)
{
- throw new ArgumentNullException( nameof(sddlForm));
+ throw new ArgumentNullException(nameof(sddlForm));
}
- if (( includeSections & AccessControlSections.All ) == 0 )
+ if ((includeSections & AccessControlSections.All) == 0)
{
throw new ArgumentException(
SR.Arg_EnumAtLeastOneFlag,
try
{
- UpdateWithNewSecurityDescriptor( new RawSecurityDescriptor( sddlForm ), includeSections );
+ UpdateWithNewSecurityDescriptor(new RawSecurityDescriptor(sddlForm), includeSections);
}
finally
{
{
byte[] result = new byte[_securityDescriptor.BinaryLength];
- _securityDescriptor.GetBinaryForm( result, 0 );
+ _securityDescriptor.GetBinaryForm(result, 0);
return result;
}
}
}
- public void SetSecurityDescriptorBinaryForm( byte[] binaryForm )
+ public void SetSecurityDescriptorBinaryForm(byte[] binaryForm)
{
- SetSecurityDescriptorBinaryForm( binaryForm, AccessControlSections.All );
+ SetSecurityDescriptorBinaryForm(binaryForm, AccessControlSections.All);
}
- public void SetSecurityDescriptorBinaryForm( byte[] binaryForm, AccessControlSections includeSections )
+ public void SetSecurityDescriptorBinaryForm(byte[] binaryForm, AccessControlSections includeSections)
{
- if ( binaryForm == null )
+ if (binaryForm == null)
{
- throw new ArgumentNullException( nameof(binaryForm));
+ throw new ArgumentNullException(nameof(binaryForm));
}
- if (( includeSections & AccessControlSections.All ) == 0 )
+ if ((includeSections & AccessControlSections.All) == 0)
{
throw new ArgumentException(
SR.Arg_EnumAtLeastOneFlag,
try
{
- UpdateWithNewSecurityDescriptor( new RawSecurityDescriptor( binaryForm, 0 ), includeSections );
+ UpdateWithNewSecurityDescriptor(new RawSecurityDescriptor(binaryForm, 0), includeSections);
}
finally
{
public abstract Type AccessRuleType { get; }
public abstract Type AuditRuleType { get; }
- protected abstract bool ModifyAccess( AccessControlModification modification, AccessRule rule, out bool modified);
- protected abstract bool ModifyAudit( AccessControlModification modification, AuditRule rule, out bool modified );
+ protected abstract bool ModifyAccess(AccessControlModification modification, AccessRule rule, out bool modified);
+ protected abstract bool ModifyAudit(AccessControlModification modification, AuditRule rule, out bool modified);
public virtual bool ModifyAccessRule(AccessControlModification modification, AccessRule rule, out bool modified)
{
- if ( rule == null )
+ if (rule == null)
{
- throw new ArgumentNullException( nameof(rule));
+ throw new ArgumentNullException(nameof(rule));
}
- if ( !this.AccessRuleType.GetTypeInfo().IsAssignableFrom(rule.GetType().GetTypeInfo()) )
+ if (!this.AccessRuleType.GetTypeInfo().IsAssignableFrom(rule.GetType().GetTypeInfo()))
{
throw new ArgumentException(
SR.AccessControl_InvalidAccessRuleType,
public virtual bool ModifyAuditRule(AccessControlModification modification, AuditRule rule, out bool modified)
{
- if ( rule == null )
+ if (rule == null)
{
- throw new ArgumentNullException( nameof(rule));
+ throw new ArgumentNullException(nameof(rule));
}
- if ( !this.AuditRuleType.GetTypeInfo().IsAssignableFrom(rule.GetType().GetTypeInfo()) )
+ if (!this.AuditRuleType.GetTypeInfo().IsAssignableFrom(rule.GetType().GetTypeInfo()))
{
throw new ArgumentException(
SR.AccessControl_InvalidAuditRuleType,
}
}
- public abstract AccessRule AccessRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type );
+ public abstract AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type);
- public abstract AuditRule AuditRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags );
+ public abstract AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags);
#endregion
}
}
public enum AccessControlType
{
- Allow = 0,
- Deny = 1,
+ Allow = 0,
+ Deny = 1,
}
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
- PropagationFlags propagationFlags )
+ PropagationFlags propagationFlags)
{
- if ( identity == null )
+ if (identity == null)
{
- throw new ArgumentNullException( nameof(identity));
+ throw new ArgumentNullException(nameof(identity));
}
- if ( accessMask == 0 )
+ if (accessMask == 0)
{
- throw new ArgumentException(
- SR.Argument_ArgumentZero,
-nameof(accessMask));
+ throw new ArgumentException(SR.Argument_ArgumentZero, nameof(accessMask));
}
- if ( inheritanceFlags < InheritanceFlags.None || inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit) )
+ if (inheritanceFlags < InheritanceFlags.None || inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit))
{
throw new ArgumentOutOfRangeException(
-nameof(inheritanceFlags),
- SR.Format( SR.Argument_InvalidEnumValue, inheritanceFlags, "InheritanceFlags" ));
+ nameof(inheritanceFlags), SR.Format(SR.Argument_InvalidEnumValue, inheritanceFlags, "InheritanceFlags"));
}
- if ( propagationFlags < PropagationFlags.None || propagationFlags > (PropagationFlags.NoPropagateInherit | PropagationFlags.InheritOnly) )
+ if (propagationFlags < PropagationFlags.None || propagationFlags > (PropagationFlags.NoPropagateInherit | PropagationFlags.InheritOnly))
{
throw new ArgumentOutOfRangeException(
-nameof(propagationFlags),
- SR.Format(SR.Argument_InvalidEnumValue, inheritanceFlags, "PropagationFlags"));
+ nameof(propagationFlags), SR.Format(SR.Argument_InvalidEnumValue, inheritanceFlags, "PropagationFlags"));
}
if (identity.IsValidTargetType(typeof(SecurityIdentifier)) == false)
_isInherited = isInherited;
_inheritanceFlags = inheritanceFlags;
- if ( inheritanceFlags != 0 )
+ if (inheritanceFlags != 0)
{
_propagationFlags = propagationFlags;
}
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
- AccessControlType type )
- : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags )
+ AccessControlType type)
+ : base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags)
{
- if ( type != AccessControlType.Allow &&
- type != AccessControlType.Deny )
+ if (type != AccessControlType.Allow &&
+ type != AccessControlType.Deny)
{
- throw new ArgumentOutOfRangeException(
-nameof(type),
- SR.ArgumentOutOfRange_Enum );
+ throw new ArgumentOutOfRangeException(nameof(type), SR.ArgumentOutOfRange_Enum);
}
- if ( inheritanceFlags < InheritanceFlags.None || inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit) )
+ if (inheritanceFlags < InheritanceFlags.None || inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit))
{
throw new ArgumentOutOfRangeException(
-nameof(inheritanceFlags),
- SR.Format(SR.Argument_InvalidEnumValue, inheritanceFlags, "InheritanceFlags"));
+ nameof(inheritanceFlags), SR.Format(SR.Argument_InvalidEnumValue, inheritanceFlags, "InheritanceFlags"));
}
- if ( propagationFlags < PropagationFlags.None || propagationFlags > (PropagationFlags.NoPropagateInherit | PropagationFlags.InheritOnly) )
+ if (propagationFlags < PropagationFlags.None || propagationFlags > (PropagationFlags.NoPropagateInherit | PropagationFlags.InheritOnly))
{
throw new ArgumentOutOfRangeException(
-nameof(propagationFlags),
- SR.Format(SR.Argument_InvalidEnumValue, inheritanceFlags, "PropagationFlags"));
+ nameof(propagationFlags), SR.Format(SR.Argument_InvalidEnumValue, inheritanceFlags, "PropagationFlags"));
}
_type = type;
}
- public abstract class ObjectAccessRule: AccessRule
+ public abstract class ObjectAccessRule : AccessRule
{
#region Private Members
#region Constructors
- protected ObjectAccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AccessControlType type )
- : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type )
+ protected ObjectAccessRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AccessControlType type)
+ : base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type)
{
- if (( !objectType.Equals( Guid.Empty )) && (( accessMask & ObjectAce.AccessMaskWithObjectType ) != 0 ))
+ if ((!objectType.Equals(Guid.Empty)) && ((accessMask & ObjectAce.AccessMaskWithObjectType) != 0))
{
_objectType = objectType;
_objectFlags |= ObjectAceFlags.ObjectAceTypePresent;
_objectType = Guid.Empty;
}
- if (( !inheritedObjectType.Equals( Guid.Empty )) && ((inheritanceFlags & InheritanceFlags.ContainerInherit ) != 0 ))
+ if ((!inheritedObjectType.Equals(Guid.Empty)) && ((inheritanceFlags & InheritanceFlags.ContainerInherit) != 0))
{
_inheritedObjectType = inheritedObjectType;
_objectFlags |= ObjectAceFlags.InheritedObjectAceTypePresent;
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
- AuditFlags auditFlags )
- : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags )
+ AuditFlags auditFlags)
+ : base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags)
{
- if ( auditFlags == AuditFlags.None )
+ if (auditFlags == AuditFlags.None)
{
throw new ArgumentException(SR.Arg_EnumAtLeastOneFlag, nameof(auditFlags));
}
- else if (( auditFlags & ~( AuditFlags.Success | AuditFlags.Failure )) != 0 )
+ else if ((auditFlags & ~(AuditFlags.Success | AuditFlags.Failure)) != 0)
{
- throw new ArgumentOutOfRangeException(nameof(auditFlags), SR.ArgumentOutOfRange_Enum );
+ throw new ArgumentOutOfRangeException(nameof(auditFlags), SR.ArgumentOutOfRange_Enum);
}
_flags = auditFlags;
}
- public abstract class ObjectAuditRule: AuditRule
+ public abstract class ObjectAuditRule : AuditRule
{
#region Private Members
#region Constructors
- protected ObjectAuditRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AuditFlags auditFlags )
- : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, auditFlags )
+ protected ObjectAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AuditFlags auditFlags)
+ : base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, auditFlags)
{
- if (( !objectType.Equals( Guid.Empty )) && (( accessMask & ObjectAce.AccessMaskWithObjectType ) != 0 ))
+ if ((!objectType.Equals(Guid.Empty)) && ((accessMask & ObjectAce.AccessMaskWithObjectType) != 0))
{
_objectType = objectType;
_objectFlags |= ObjectAceFlags.ObjectAceTypePresent;
_objectType = Guid.Empty;
}
- if (( !inheritedObjectType.Equals( Guid.Empty )) && ((inheritanceFlags & InheritanceFlags.ContainerInherit ) != 0 ))
+ if ((!inheritedObjectType.Equals(Guid.Empty)) && ((inheritanceFlags & InheritanceFlags.ContainerInherit) != 0))
{
_inheritedObjectType = inheritedObjectType;
_objectFlags |= ObjectAceFlags.InheritedObjectAceTypePresent;
public void AddRule(AuthorizationRule rule)
{
- InnerList.Add( rule );
+ InnerList.Add(rule);
}
#endregion
#region ICollection Members
- public void CopyTo( AuthorizationRule[] rules, int index )
+ public void CopyTo(AuthorizationRule[] rules, int index)
{
- (( ICollection )this ).CopyTo( rules, index );
+ ((ICollection)this).CopyTo(rules, index);
}
#endregion
{
public abstract class AsymmetricKeyExchangeDeformatter
{
- protected AsymmetricKeyExchangeDeformatter() {}
- public abstract string Parameters {get; set; }
+ protected AsymmetricKeyExchangeDeformatter() { }
+ public abstract string Parameters { get; set; }
public abstract void SetKey(AsymmetricAlgorithm key);
public abstract byte[] DecryptKeyExchange(byte[] rgb);
}
{
public abstract class AsymmetricKeyExchangeFormatter
{
- protected AsymmetricKeyExchangeFormatter() {}
+ protected AsymmetricKeyExchangeFormatter() { }
- public abstract string Parameters {get; }
+ public abstract string Parameters { get; }
public abstract void SetKey(AsymmetricAlgorithm key);
public abstract byte[] CreateKeyExchange(byte[] data);
{
public abstract class AsymmetricSignatureDeformatter
{
- protected AsymmetricSignatureDeformatter() {}
+ protected AsymmetricSignatureDeformatter() { }
public abstract void SetKey(AsymmetricAlgorithm key);
public abstract void SetHashAlgorithm(string strName);
{
public abstract class AsymmetricSignatureFormatter
{
- protected AsymmetricSignatureFormatter() {}
+ protected AsymmetricSignatureFormatter() { }
public abstract void SetKey(AsymmetricAlgorithm key);
public abstract void SetHashAlgorithm(string strName);
using Microsoft.Win32.SafeHandles;
-using ErrorCode=Interop.NCrypt.ErrorCode;
+using ErrorCode = Interop.NCrypt.ErrorCode;
namespace System.Security.Cryptography
{
public override string Parameters
{
- get {return null; }
+ get { return null; }
set { }
}
public override string Parameters
{
- get {return null; }
+ get { return null; }
}
- public RandomNumberGenerator Rng {
+ public RandomNumberGenerator Rng
+ {
get { return RngValue; }
set { RngValue = value; }
}
_rsaKey = (RSA)key;
}
- public RandomNumberGenerator RNG {
+ public RandomNumberGenerator RNG
+ {
get { return RngValue; }
set { RngValue = value; }
}
public override string Parameters
{
- get {return null; }
+ get { return null; }
set { }
}
}
}
- public RandomNumberGenerator Rng {
+ public RandomNumberGenerator Rng
+ {
get { return RngValue; }
set { RngValue = value; }
}
{
protected TripleDES()
{
- KeySizeValue = 3*64;
+ KeySizeValue = 3 * 64;
BlockSizeValue = 64;
FeedbackSizeValue = BlockSizeValue;
LegalBlockSizesValue = s_legalBlockSizes.CloneKeySizesArray();
if (value == null)
throw new ArgumentNullException(nameof(value));
- if (!(value.Length*8).IsLegalSize(s_legalKeySizes))
+ if (!(value.Length * 8).IsLegalSize(s_legalKeySizes))
throw new ArgumentException(SR.Cryptography_InvalidKeySize);
if (IsWeakKey(value))
if (rgbKey == null)
throw new CryptographicException(SR.Cryptography_InvalidKeySize); // Desktop compat: Strange exception for a null value, but this is what we threw in classic CLR.
- if (!(rgbKey.Length*8).IsLegalSize(s_legalKeySizes))
+ if (!(rgbKey.Length * 8).IsLegalSize(s_legalKeySizes))
throw new CryptographicException(SR.Cryptography_InvalidKeySize);
byte[] rgbOddParityKey = rgbKey.FixupKeyParity();
CngKey key = _core.GetOrGenerateKey(curve);
ForceSetKeySize(key.KeySize);
}
- else {
+ else
+ {
int keySize = 0;
// Get the proper KeySize from algorithm name
if (alg == CngAlgorithm.ECDsaP256)
/// <summary>
/// Read a parameter from the current key using CRYPT_SILENT, to avoid any potential UI prompts.
/// </summary>
- private object ReadKeyParameterSilent(int keyParam, bool throwOnNotFound=true)
+ private object ReadKeyParameterSilent(int keyParam, bool throwOnNotFound = true)
{
const uint SilentFlags = (uint)Interop.Advapi32.CryptAcquireContextFlags.CRYPT_SILENT;
{
private readonly RandomNumberGenerator _impl;
- public RNGCryptoServiceProvider() : this((CspParameters) null) { }
+ public RNGCryptoServiceProvider() : this((CspParameters)null) { }
public RNGCryptoServiceProvider(string str) : this((CspParameters)null) { }
public RNGCryptoServiceProvider(byte[] rgb) : this((CspParameters)null) { }
_incrementalHash.Dispose();
}
base.Dispose(disposing);
- }
+ }
}
}
if (index < 0 || index >= array.Length)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
- _list.CopyTo(array, index);
+ _list.CopyTo(array, index);
}
public bool IsSynchronized
break;
}
- return new AlgorithmIdentifier(new Oid(asn.Algorithm), keyLength) {
+ return new AlgorithmIdentifier(new Oid(asn.Algorithm), keyLength)
+ {
Parameters = parameters
};
}
using Microsoft.Win32.SafeHandles;
-using CryptProvParam=Interop.Advapi32.CryptProvParam;
+using CryptProvParam = Interop.Advapi32.CryptProvParam;
using static Interop.Crypt32;
namespace Internal.Cryptography.Pal.Windows
public static AttributeAsn[] NormalizeAttributeSet(
AttributeAsn[] setItems,
- Action<byte[]> encodedValueProcessor=null)
+ Action<byte[]> encodedValueProcessor = null)
{
byte[] normalizedValue;
}
#if netstandard
-internal
+ internal
#else
-public
+ public
#endif
CmsRecipient(X509Certificate2 certificate, RSAEncryptionPadding rsaEncryptionPadding)
: this(certificate)
}
#if netstandard
-internal
+ internal
#else
-public
+ public
#endif
CmsRecipient(SubjectIdentifierType recipientIdentifierType, X509Certificate2 certificate, RSAEncryptionPadding rsaEncryptionPadding)
: this(recipientIdentifierType, certificate)
}
#if netstandard
-internal
+ internal
#else
-public
+ public
#endif
RSAEncryptionPadding? RSAEncryptionPadding { get; }
public SubjectIdentifierType RecipientIdentifierType { get; }
{
public sealed class Pkcs12KeyBag : Pkcs12SafeBag
{
- public Pkcs12KeyBag(ReadOnlyMemory<byte> pkcs8PrivateKey, bool skipCopy=false)
+ public Pkcs12KeyBag(ReadOnlyMemory<byte> pkcs8PrivateKey, bool skipCopy = false)
: base(Oids.Pkcs12KeyBag, pkcs8PrivateKey, skipCopy)
{
}
}
}
- protected Pkcs12SafeBag(string bagIdValue, ReadOnlyMemory<byte> encodedBagValue, bool skipCopy=false)
+ protected Pkcs12SafeBag(string bagIdValue, ReadOnlyMemory<byte> encodedBagValue, bool skipCopy = false)
{
if (string.IsNullOrEmpty(bagIdValue))
throw new ArgumentNullException(nameof(bagIdValue));
{
public sealed class Pkcs12ShroudedKeyBag : Pkcs12SafeBag
{
- public Pkcs12ShroudedKeyBag(ReadOnlyMemory<byte> encryptedPkcs8PrivateKey, bool skipCopy=false)
+ public Pkcs12ShroudedKeyBag(ReadOnlyMemory<byte> encryptedPkcs8PrivateKey, bool skipCopy = false)
: base(Oids.Pkcs12ShroudedKeyBag, encryptedPkcs8PrivateKey, skipCopy)
{
}
{
CBC = 1,
ECB = 2,
- [EditorBrowsable(EditorBrowsableState.Never)]OFB = 3,
- [EditorBrowsable(EditorBrowsableState.Never)]CFB = 4,
+ [EditorBrowsable(EditorBrowsableState.Never)] OFB = 3,
+ [EditorBrowsable(EditorBrowsableState.Never)] CFB = 4,
CTS = 5
}
}
throw new ObjectDisposedException(null);
}
- if (destination.Length < HashSizeValue/8)
+ if (destination.Length < HashSizeValue / 8)
{
bytesWritten = 0;
return false;
byte[] thumbprint = new byte[cbData];
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_SHA1_HASH_PROP_ID, thumbprint, ref cbData))
- throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
+ throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
return thumbprint;
}
}
CERT_CHAIN_PARA chainPara = new CERT_CHAIN_PARA();
chainPara.cbSize = sizeof(CERT_CHAIN_PARA);
if (!Interop.crypt32.CertGetCertificateChain(ChainEngine.HCCE_CURRENT_USER, _certContext, (FILETIME*)null, SafeCertStoreHandle.InvalidHandle, ref chainPara, CertChainFlags.None, IntPtr.Zero, out certChainContext))
- throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
+ throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData))
- throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
+ throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
}
byte[] keyAlgorithmParameters = new byte[cbData];
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, keyAlgorithmParameters, ref cbData))
- throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
+ throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
return keyAlgorithmParameters;
}
{
using (IExportPal storePal = StorePal.FromCertificate(this))
{
- return storePal.Export (contentType, password);
+ return storePal.Export(contentType, password);
}
}
}
public void FindBySubjectDistinguishedName(string subjectDistinguishedName)
{
FindCore(
- delegate(SafeCertContextHandle pCertContext)
+ delegate (SafeCertContextHandle pCertContext)
{
string actual = GetCertNameInfo(pCertContext, CertNameType.CERT_NAME_RDN_TYPE, CertNameFlags.None);
return subjectDistinguishedName.Equals(actual, StringComparison.OrdinalIgnoreCase);
public void FindByIssuerDistinguishedName(string issuerDistinguishedName)
{
FindCore(
- delegate(SafeCertContextHandle pCertContext)
+ delegate (SafeCertContextHandle pCertContext)
{
string actual = GetCertNameInfo(pCertContext, CertNameType.CERT_NAME_RDN_TYPE, CertNameFlags.CERT_NAME_ISSUER_FLAG);
return issuerDistinguishedName.Equals(actual, StringComparison.OrdinalIgnoreCase);
public unsafe void FindBySerialNumber(BigInteger hexValue, BigInteger decimalValue)
{
FindCore(
- delegate(SafeCertContextHandle pCertContext)
+ delegate (SafeCertContextHandle pCertContext)
{
byte[] actual = pCertContext.CertContext->pCertInfo->SerialNumber.ToByteArray();
GC.KeepAlive(pCertContext);
FILETIME fileTime = FILETIME.FromDateTime(dateTime);
FindCore(
- delegate(SafeCertContextHandle pCertContext)
+ delegate (SafeCertContextHandle pCertContext)
{
int comparison = Interop.crypt32.CertVerifyTimeValidity(ref fileTime,
pCertContext.CertContext->pCertInfo);
public unsafe void FindByTemplateName(string templateName)
{
FindCore(
- delegate(SafeCertContextHandle pCertContext)
+ delegate (SafeCertContextHandle pCertContext)
{
// The template name can have 2 different formats: V1 format (<= Win2K) is just a string
// V2 format (XP only) can be a friendly name or an OID.
byte[] extensionRawData = pV1Template->Value.ToByteArray();
if (!extensionRawData.DecodeObjectNoThrow(
CryptDecodeObjectStructType.X509_UNICODE_ANY_STRING,
- delegate(void* pvDecoded, int cbDecoded)
+ delegate (void* pvDecoded, int cbDecoded)
{
Debug.Assert(cbDecoded >= sizeof(CERT_NAME_VALUE));
CERT_NAME_VALUE* pNameValue = (CERT_NAME_VALUE*)pvDecoded;
byte[] extensionRawData = pV2Template->Value.ToByteArray();
if (!extensionRawData.DecodeObjectNoThrow(
CryptDecodeObjectStructType.X509_CERTIFICATE_TEMPLATE,
- delegate(void* pvDecoded, int cbDecoded)
+ delegate (void* pvDecoded, int cbDecoded)
{
Debug.Assert(cbDecoded >= sizeof(CERT_TEMPLATE_EXT));
CERT_TEMPLATE_EXT* pTemplateExt = (CERT_TEMPLATE_EXT*)pvDecoded;
public unsafe void FindByCertificatePolicy(string oidValue)
{
FindCore(
- delegate(SafeCertContextHandle pCertContext)
+ delegate (SafeCertContextHandle pCertContext)
{
CERT_INFO* pCertInfo = pCertContext.CertContext->pCertInfo;
CERT_EXTENSION* pCertExtension = Interop.crypt32.CertFindExtension(Oids.CertPolicies,
byte[] extensionRawData = pCertExtension->Value.ToByteArray();
if (!extensionRawData.DecodeObjectNoThrow(
CryptDecodeObjectStructType.X509_CERT_POLICIES,
- delegate(void* pvDecoded, int cbDecoded)
+ delegate (void* pvDecoded, int cbDecoded)
{
Debug.Assert(cbDecoded >= sizeof(CERT_POLICIES_INFO));
CERT_POLICIES_INFO* pCertPoliciesInfo = (CERT_POLICIES_INFO*)pvDecoded;
{
int cbEncoded = 0;
if (!Interop.crypt32.CertSerializeCertificateStoreElement(pCertContext, 0, null, ref cbEncoded))
- throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
+ throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
byte[] pbEncoded = new byte[cbEncoded];
if (!Interop.crypt32.CertSerializeCertificateStoreElement(pCertContext, 0, pbEncoded, ref cbEncoded))
- throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
+ throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
return pbEncoded;
}
CRYPTOAPI_BLOB dataBlob = new CRYPTOAPI_BLOB(0, (byte*)null);
if (!Interop.crypt32.PFXExportCertStore(_certStore, ref dataBlob, password, PFXExportFlags.EXPORT_PRIVATE_KEYS | PFXExportFlags.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY))
- throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
+ throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
byte[] pbEncoded = new byte[dataBlob.cbData];
fixed (byte* ppbEncoded = pbEncoded)
{
dataBlob.pbData = ppbEncoded;
if (!Interop.crypt32.PFXExportCertStore(_certStore, ref dataBlob, password, PFXExportFlags.EXPORT_PRIVATE_KEYS | PFXExportFlags.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY))
- throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
+ throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
}
return pbEncoded;
CertStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG | CertStoreFlags.CERT_STORE_CREATE_NEW_FLAG | CertStoreFlags.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG,
null);
if (certStore.IsInvalid)
- throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
+ throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
if (!Interop.crypt32.CertAddCertificateLinkToStore(certStore, certificatePal.CertContext, CertStoreAddDisposition.CERT_STORE_ADD_ALWAYS, IntPtr.Zero))
- throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
+ throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
return new StorePal(certStore);
}
CertStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG | CertStoreFlags.CERT_STORE_CREATE_NEW_FLAG,
null);
if (certStore.IsInvalid)
- throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
+ throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
//
// We use CertAddCertificateLinkToStore to keep a link to the original store, so any property changes get
internal SafeCertStoreHandle SafeCertStoreHandle
{
- get {return _certStore; }
+ get { return _certStore; }
}
SafeHandle IStorePal.SafeHandle
int cb = 20;
byte[] buffer = new byte[cb];
if (!Interop.crypt32.CryptHashPublicKeyInfo(IntPtr.Zero, AlgId.CALG_SHA1, 0, CertEncodingType.All, ref publicKeyInfo, buffer, ref cb))
- throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
+ throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
if (cb < buffer.Length)
{
byte[] newBuffer = new byte[cb];
AddGeneralName(new GeneralNameAsn { OtherName = otherName });
}
- public X509Extension Build(bool critical=false)
+ public X509Extension Build(bool critical = false)
{
using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
{
base.OnValidate(value);
if (!(value is X509Certificate))
- throw new ArgumentException(SR.Arg_InvalidType, nameof(value));
+ throw new ArgumentException(SR.Arg_InvalidType, nameof(value));
}
}
}
_chainElements = new X509ChainElementCollection(_pal.ChainElements);
}
- public static X509Chain Create() {
+ public static X509Chain Create()
+ {
return new X509Chain();
}
private XmlResolver _xmlResolver;
// hash table defining the key name mapping
private const int _capacity = 4; // 4 is a reasonable capacity for
- // the key name mapping hash table
+ // the key name mapping hash table
private readonly Hashtable _keyNameMapping;
private PaddingMode _padding;
private CipherMode _mode;
throw new CryptographicException(SR.Cryptography_Partial_Chain);
}
- elements = (X509ChainElementCollection)chain.ChainElements;
+ elements = (X509ChainElementCollection)chain.ChainElements;
for (int index = 0; index < (Utils.IsSelfSigned(chain) ? 1 : elements.Count - 1); index++)
{
AddCertificate(elements[index].Certificate);
return collection;
}
- private static readonly char[] s_hexValues = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+ private static readonly char[] s_hexValues = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
internal static string EncodeHexString(byte[] sArray)
{
return EncodeHexString(sArray, 0, (uint)sArray.Length);
{
foreach (XmlQualifiedName attr in attrs.Keys)
{
- Debug.Assert(!FeedUtils.IsXmlns(attr.Name, attr.Namespace), "XML namespace attributes should not be added to the list." );
+ Debug.Assert(!FeedUtils.IsXmlns(attr.Name, attr.Namespace), "XML namespace attributes should not be added to the list.");
result.AttributeExtensions.Add(attr, attrs[attr]);
}
}
public IEnumerable<SyndicationItem> Items
{
- get =>_items ?? (_items = new NullNotAllowedCollection<SyndicationItem>());
+ get => _items ?? (_items = new NullNotAllowedCollection<SyndicationItem>());
set => _items = value ?? throw new ArgumentNullException(nameof(value));
}
public Collection<SyndicationLink> Links
{
- get =>_links ?? (_links = new NullNotAllowedCollection<SyndicationLink>());
+ get => _links ?? (_links = new NullNotAllowedCollection<SyndicationLink>());
}
public TextSyndicationContent Title { get; set; }
/// <devdoc>
/// can be used to write notification of service command calls, such as Start and Stop, to the Application event log. This property is read-only.
/// </devdoc>
- [Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
+ [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual EventLog EventLog
{
get
throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
{
// Validate Parameters
if (bytes == null || chars == null)
- throw new ArgumentNullException(bytes == null ? nameof(bytes): nameof(chars), SR.ArgumentNull_Array);
+ throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex): nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
// Just call pointer version
fixed (byte* pBytes = &bytes[0])
- fixed (char* pChars = &chars[0])
- // Remember that charCount is # to decode, not size of array
- return GetChars(pBytes + byteIndex, byteCount,
- pChars + charIndex, charCount, flush);
+ fixed (char* pChars = &chars[0])
+ // Remember that charCount is # to decode, not size of array
+ return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush);
}
public override unsafe int GetChars(byte* bytes, int byteCount,
{
// Validate parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException((chars == null ? nameof(chars): nameof(bytes)), SR.ArgumentNull_Array);
+ throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
// Remember our flush
m_mustFlush = flush;
{
// Validate parameters
if (bytes == null || chars == null)
- throw new ArgumentNullException((bytes == null ? nameof(bytes): nameof(chars)), SR.ArgumentNull_Array);
+ throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)), SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex): nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
{
// Validate input parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException(chars == null ? nameof(chars): nameof(bytes), SR.ArgumentNull_Array);
+ throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
// We don't want to throw
m_mustFlush = flush;
throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
{
// Validate parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException((chars == null ? nameof(chars): nameof(bytes)), SR.ArgumentNull_Array);
+ throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
// Just call pointer version
fixed (char* pChars = &chars[0])
- fixed (byte* pBytes = &bytes[0])
-
- // Remember that charCount is # to decode, not size of array.
- return GetBytes(pChars + charIndex, charCount,
- pBytes + byteIndex, byteCount, flush);
+ fixed (byte* pBytes = &bytes[0])
+ // Remember that charCount is # to decode, not size of array.
+ return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush);
}
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException((chars == null ? nameof(chars): nameof(bytes)), SR.ArgumentNull_Array);
+ throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
m_mustFlush = flush;
m_throwOnOverflow = true;
{
// Validate parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException((chars == null ? nameof(chars): nameof(bytes)), SR.ArgumentNull_Array);
+ throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex): nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
{
// Validate input parameters
if (bytes == null || chars == null)
- throw new ArgumentNullException(bytes == null ? nameof(bytes): nameof(chars), SR.ArgumentNull_Array);
+ throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount): nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
// We don't want to throw
m_mustFlush = flush;
throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
byte[] bytes, int byteIndex)
{
if (s == null || bytes == null)
- throw new ArgumentNullException((s == null ? nameof(s): nameof(bytes)), SR.ArgumentNull_Array);
+ throw new ArgumentNullException((s == null ? nameof(s) : nameof(bytes)), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (s.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount);
bytes = new byte[1];
fixed (char* pChars = s)
- fixed (byte* pBytes = &bytes[0])
- return GetBytes(pChars + charIndex, charCount,
- pBytes + byteIndex, byteCount, null);
+ fixed (byte* pBytes = &bytes[0])
+ return GetBytes(pChars + charIndex, charCount,
+ pBytes + byteIndex, byteCount, null);
}
// Encodes a range of characters in a character array into a range of bytes
{
// Validate parameters
if (chars == null || bytes == null)
- throw new ArgumentNullException((chars == null ? nameof(chars): nameof(bytes)), SR.ArgumentNull_Array);
+ throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
bytes = new byte[1];
fixed (char* pChars = &chars[0])
- fixed (byte* pBytes = &bytes[0])
- // Remember that byteCount is # to decode, not size of array.
- return GetBytes(pChars + charIndex, charCount,
- pBytes + byteIndex, byteCount, null);
+ fixed (byte* pBytes = &bytes[0])
+ // Remember that byteCount is # to decode, not size of array.
+ return GetBytes(pChars + charIndex, charCount,
+ pBytes + byteIndex, byteCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
{
// Validate Parameters
if (bytes == null || chars == null)
- throw new ArgumentNullException(bytes == null ? nameof(bytes): nameof(chars), SR.ArgumentNull_Array);
+ throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount): nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
return GetBytes(chars, charCount, bytes, byteCount, null);
}
throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
{
// Validate Parameters
if (bytes == null || chars == null)
- throw new ArgumentNullException(bytes == null ? nameof(bytes): nameof(chars), SR.ArgumentNull_Array);
+ throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex): nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
chars = new char[1];
fixed (byte* pBytes = &bytes[0])
- fixed (char* pChars = &chars[0])
- // Remember that charCount is # to decode, not size of array
- return GetChars(pBytes + byteIndex, byteCount,
- pChars + charIndex, charCount, null);
+ fixed (char* pChars = &chars[0])
+ // Remember that charCount is # to decode, not size of array
+ return GetChars(pBytes + byteIndex, byteCount,
+ pChars + charIndex, charCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
{
// Validate Parameters
if (bytes == null || chars == null)
- throw new ArgumentNullException(bytes == null ? nameof(bytes): nameof(chars), SR.ArgumentNull_Array);
+ throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount): nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
return GetChars(bytes, byteCount, chars, charCount, null);
}
throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
/// </remarks>
public JsonCommentHandling CommentHandling
{
- readonly get => _commentHandling;
+ readonly get => _commentHandling;
set
{
Debug.Assert(value >= 0);
[Serializable]
internal sealed class JsonReaderException : JsonException
{
- public JsonReaderException(string message, long lineNumber, long bytePositionInLine) : base(message, path : null, lineNumber, bytePositionInLine)
+ public JsonReaderException(string message, long lineNumber, long bytePositionInLine) : base(message, path: null, lineNumber, bytePositionInLine)
{
}
/// <summary>
/// Allow string values.
/// </summary>
- AllowStrings = 0b0001,
+ AllowStrings = 0b0001,
/// <summary>
/// Allow number values.
/// </summary>
- AllowNumbers = 0b0010
+ AllowNumbers = 0b0010
}
}
}
public JsonConverterEnum(EnumConverterOptions options)
- : this (options, namingPolicy: null)
+ : this(options, namingPolicy: null)
{
}
// dictionaries. Typically it would represent a CLR type such as System.String.
PolicyProperty = AddProperty(
propertyType,
- propertyInfo : null, // Not a real property so this is null.
- classType : typeof(object), // A dummy type (not used).
- options : options);
+ propertyInfo: null, // Not a real property so this is null.
+ classType: typeof(object), // A dummy type (not used).
+ options: options);
}
private JsonPropertyInfo AddProperty(Type propertyType, PropertyInfo propertyInfo, Type classType, JsonSerializerOptions options)
case ClassType.Dictionary:
{
// Add a single property that maps to the class type so we can have policies applied.
- AddPolicyProperty(type, options);
+ AddPolicyProperty(type, options);
Type objectType;
if (IsNativelySupportedCollection(type))
if (!jsonPropertyInfo.IgnoreNullValues)
{
- state.Current.JsonPropertyInfo.SetValueAsObject(state.Current.ReturnValue, value : null);
+ state.Current.JsonPropertyInfo.SetValueAsObject(state.Current.ReturnValue, value: null);
}
return false;
// the cache of code and factories that are currently loaded:
// Dictionary for large cache
private static readonly Dictionary<CachedCodeEntryKey, CachedCodeEntry> s_cache = new Dictionary<CachedCodeEntryKey, CachedCodeEntry>(s_cacheSize);
- // linked list for LRU and for small cache
+ // linked list for LRU and for small cache
private static int s_cacheCount = 0;
private static CachedCodeEntry s_cacheFirst;
private static CachedCodeEntry s_cacheLast;
{
// The following primitive operations come directly from the parser
- // lef/back operands description
+ // lef/back operands description
public const int Onerep = 0; // lef,back char,min,max a {n}
public const int Notonerep = 1; // lef,back char,min,max .{n}
public const int Setrep = 2; // lef,back set,min,max [\d]{n}
/*
* True if we need to do the backtrack logic for the current operation
*/
- private bool IsBack() {
+ private bool IsBack()
+ {
return (_regexopcode & RegexCode.Back) != 0;
}
/*
* True if we need to do the second-backtrack logic for the current operation
*/
- private bool IsBack2() {
+ private bool IsBack2()
+ {
return (_regexopcode & RegexCode.Back2) != 0;
}
#endif
private void CallToLower()
{
- Ldloc(_cultureV);
- Call(s_chartolowerM);
+ Ldloc(_cultureV);
+ Call(s_chartolowerM);
}
/*
/*
* Some simple debugging stuff
*/
- private static readonly MethodInfo s_debugWriteLine = typeof(Debug).GetMethod("WriteLine", new Type[] {typeof(string)});
+ private static readonly MethodInfo s_debugWriteLine = typeof(Debug).GetMethod("WriteLine", new Type[] { typeof(string) });
/*
* Debug only: emit code to print out a message
*/
- private void Message(string str) {
+ private void Message(string str)
+ {
Ldstr(str);
Call(s_debugWriteLine);
}
private void GenerateOneCode()
{
#if DEBUG
- if ((_options & RegexOptions.Debug) != 0) {
+ if ((_options & RegexOptions.Debug) != 0)
+ {
Mvlocfld(_textposV, s_textposF);
Mvlocfld(_trackposV, s_trackposF);
Mvlocfld(_stackposV, s_stackposF);
// In release, cutoff at a length to which we can still reasonably construct a string
// In debug, use a smaller cutoff to exercise the cutoff path in tests
const int Cutoff =
- #if DEBUG
+#if DEBUG
50;
- #else
+#else
1_000_000;
- #endif
+#endif
if (curNode.M > 0 && curNode.M < Cutoff)
{
}
}
- /// <summary>
+ /// <summary>
/// Given a Match, emits into the ValueStringBuilder the evaluated
/// Right-to-Left substitution pattern.
/// </summary>
protected internal int[] runtrack; // The backtracking stack. Opcodes use this to store data regarding
protected internal int runtrackpos; // what they have matched and where to backtrack to. Each "frame" on
- // the stack takes the form of [CodePosition Data1 Data2...], where
- // CodePosition is the position of the current opcode and
- // the data values are all optional. The CodePosition can be negative, and
- // these values (also called "back2") are used by the BranchMark family of opcodes
- // to indicate whether they are backtracking after a successful or failed
- // match.
- // When we backtrack, we pop the CodePosition off the stack, set the current
- // instruction pointer to that code position, and mark the opcode
- // with a backtracking flag ("Back"). Each opcode then knows how to
- // handle its own data.
+ // the stack takes the form of [CodePosition Data1 Data2...], where
+ // CodePosition is the position of the current opcode and
+ // the data values are all optional. The CodePosition can be negative, and
+ // these values (also called "back2") are used by the BranchMark family of opcodes
+ // to indicate whether they are backtracking after a successful or failed
+ // match.
+ // When we backtrack, we pop the CodePosition off the stack, set the current
+ // instruction pointer to that code position, and mark the opcode
+ // with a backtracking flag ("Back"). Each opcode then knows how to
+ // handle its own data.
protected internal int[] runstack; // This stack is used to track text positions across different opcodes.
protected internal int runstackpos; // For example, in /(a*b)+/, the parentheses result in a SetMark/CaptureMark
- // pair. SetMark records the text position before we match a*b. Then
- // CaptureMark uses that position to figure out where the capture starts.
- // Opcodes which push onto this stack are always paired with other opcodes
- // which will pop the value from it later. A successful match should mean
- // that this stack is empty.
+ // pair. SetMark records the text position before we match a*b. Then
+ // CaptureMark uses that position to figure out where the capture starts.
+ // Opcodes which push onto this stack are always paired with other opcodes
+ // which will pop the value from it later. A successful match should mean
+ // that this stack is empty.
protected internal int[] runcrawl; // The crawl stack is used to keep track of captures. Every time a group
protected internal int runcrawlpos; // has a capture, we push its group number onto the runcrawl stack. In
- // the case of a balanced match, we push BOTH groups onto the stack.
+ // the case of a balanced match, we push BOTH groups onto the stack.
protected internal int runtrackcount; // count of states that may do backtracking
namespace System.Transactions
{
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification="Serialization not yet supported and will be done using DistributedTransaction")]
+ [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Serialization not yet supported and will be done using DistributedTransaction")]
public sealed class CommittableTransaction : Transaction, IAsyncResult
{
internal bool _completedSynchronously = false;
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
- etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionException, message, innerException==null?string.Empty:innerException.ToString());
+ etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionException, message, innerException == null ? string.Empty : innerException.ToString());
}
return new TransactionException(message, innerException);
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
- etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionException, message, innerException==null?string.Empty:innerException.ToString());
+ etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionException, message, innerException == null ? string.Empty : innerException.ToString());
}
return new TransactionException(message, innerException);
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
- etwLog.TransactionExceptionTrace(TransactionExceptionType.InvalidOperationException, messagewithTxId, innerException==null?string.Empty:innerException.ToString());
+ etwLog.TransactionExceptionTrace(TransactionExceptionType.InvalidOperationException, messagewithTxId, innerException == null ? string.Empty : innerException.ToString());
}
return new InvalidOperationException(messagewithTxId, innerException);
}
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
- etwLog.TransactionExceptionTrace(traceSource, TransactionExceptionType.InvalidOperationException, message, innerException==null?string.Empty:innerException.ToString());
+ etwLog.TransactionExceptionTrace(traceSource, TransactionExceptionType.InvalidOperationException, message, innerException == null ? string.Empty : innerException.ToString());
}
return new InvalidOperationException(message, innerException);
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
- etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionAbortedException, message, innerException==null?string.Empty:innerException.ToString());
+ etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionAbortedException, message, innerException == null ? string.Empty : innerException.ToString());
}
return new TransactionAbortedException(message, innerException);
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
- etwLog.TransactionExceptionTrace(traceSource, TransactionExceptionType.TransactionInDoubtException, message, innerException==null?string.Empty:innerException.ToString());
+ etwLog.TransactionExceptionTrace(traceSource, TransactionExceptionType.TransactionInDoubtException, message, innerException == null ? string.Empty : innerException.ToString());
}
return new TransactionInDoubtException(message, innerException);
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
- etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionManagerCommunicationException, message, innerException==null?string.Empty:innerException.ToString());
+ etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionManagerCommunicationException, message, innerException == null ? string.Empty : innerException.ToString());
}
return new TransactionManagerCommunicationException(message, innerException);
// pHeader.signature will always be 0x1c15.
// "PBrush" should be the 6 chars after position 12 as well.
- if ( rawData.Length <= pHeader.headersize + 18 ||
+ if (rawData.Length <= pHeader.headersize + 18 ||
!rawData.Slice(pHeader.headersize + 12, 6).SequenceEqual(PBrush))
{
return null;
internal abstract class SafePointerHandle<T> : SafeHandle where T : SafeHandle, new()
{
- protected SafePointerHandle(): base(IntPtr.Zero, true)
+ protected SafePointerHandle() : base(IntPtr.Zero, true)
{
}