Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 11 additions & 25 deletions src/System.Management.Automation/DscSupport/CimDSCParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1935,8 +1935,7 @@ private static ParseError[] CheckMandatoryPropertiesPresent(DynamicKeywordStatem
object evalResultObject;
if (IsConstantValueVisitor.IsConstant(pair.Item1, out evalResultObject, forAttribute: false, forRequires: false))
{
var presentName = evalResultObject as string;
if (presentName != null)
if (evalResultObject is string presentName)
{
if (mandatoryPropertiesNames.Remove(presentName) && mandatoryPropertiesNames.Count == 0)
{
Expand Down Expand Up @@ -2298,8 +2297,7 @@ internal static string GenerateMofForAst(TypeDefinitionAst typeAst)
internal static string MapTypeNameToMofType(ITypeName typeName, string memberName, string className, out bool isArrayType, out string embeddedInstanceType, List<object> embeddedInstanceTypes, ref string[] enumNames)
{
TypeName propTypeName;
var arrayTypeName = typeName as ArrayTypeName;
if (arrayTypeName != null)
if (typeName is ArrayTypeName arrayTypeName)
{
isArrayType = true;
propTypeName = arrayTypeName.ElementType as TypeName;
Expand Down Expand Up @@ -2362,15 +2360,13 @@ private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder s
while (bases.Count > 0)
{
var b = bases.Dequeue();
var tc = b as TypeConstraintAst;

if (tc != null)
if (b is TypeConstraintAst tc)
{
b = tc.TypeName.GetReflectionType();
if (b == null)
{
var td = tc.TypeName as TypeName;
if (td != null && td._typeDefinitionAst != null)
if (tc.TypeName is TypeName td && td._typeDefinitionAst != null)
{
ProcessMembers(sb, embeddedInstanceTypes, td._typeDefinitionAst, className);
foreach (var b1 in td._typeDefinitionAst.BaseTypes)
Expand Down Expand Up @@ -2412,8 +2408,7 @@ private static bool GetResourceMethodsLineNumber(TypeDefinitionAst typeDefinitio
methodsLinePosition = new Dictionary<string, int>();
foreach (var member in typeDefinitionAst.Members)
{
var functionMemberAst = member as FunctionMemberAst;
if (functionMemberAst != null)
if (member is FunctionMemberAst functionMemberAst)
{
if (functionMemberAst.Name.Equals(getMethodName, StringComparison.OrdinalIgnoreCase))
{
Expand Down Expand Up @@ -2493,9 +2488,7 @@ private static void ProcessMembers(StringBuilder sb, List<object> embeddedInstan
{
foreach (var member in typeDefinitionAst.Members)
{
var property = member as PropertyMemberAst;

if (property == null || property.IsStatic ||
if (member is not PropertyMemberAst property || property.IsStatic ||
property.Attributes.All(a => a.TypeName.GetReflectionAttributeType() != typeof(DscPropertyAttribute)))
{
continue;
Expand Down Expand Up @@ -2598,8 +2591,7 @@ private static bool GetResourceDefinitionsFromModule(string fileName, out IEnume

resourceDefinitions = ast.FindAll(n =>
{
var typeAst = n as TypeDefinitionAst;
if (typeAst != null)
if (n is TypeDefinitionAst typeAst)
{
for (int i = 0; i < typeAst.Attributes.Count; i++)
{
Expand Down Expand Up @@ -2674,13 +2666,9 @@ private static bool ImportKeywordsFromScriptFile(string fileName, PSModuleInfo m
{
foreach (var na in attr.NamedArguments)
{
if (na.ArgumentName.Equals("RunAsCredential", StringComparison.OrdinalIgnoreCase))
if (na.ArgumentName.Equals("RunAsCredential", StringComparison.OrdinalIgnoreCase) && attr.GetAttribute() is DscResourceAttribute dscResourceAttribute)
{
var dscResourceAttribute = attr.GetAttribute() as DscResourceAttribute;
if (dscResourceAttribute != null)
{
runAsBehavior = dscResourceAttribute.RunAsCredential;
}
runAsBehavior = dscResourceAttribute.RunAsCredential;
}
}
}
Expand Down Expand Up @@ -2914,8 +2902,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable<object>
bool needComma = false;
foreach (var attr in customAttributes)
{
var dscProperty = attr as DscPropertyAttribute;
if (dscProperty != null)
if (attr is DscPropertyAttribute dscProperty)
{
if (dscProperty.Key)
{
Expand All @@ -2938,8 +2925,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable<object>
continue;
}

var validateSet = attr as ValidateSetAttribute;
if (validateSet != null)
if (attr is ValidateSetAttribute validateSet)
{
bool valueMapComma = false;
StringBuilder sbValues = new(", Values{");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,20 +62,17 @@ internal IEnumerable<T> GetArgumentsOfType<T>() where T : class
continue;
}

var objectInstance = methodParameter.Value as T;
if (objectInstance != null)
if (methodParameter.Value is T objectInstance)
{
result.Add(objectInstance);
continue;
}

var objectInstanceArray = methodParameter.Value as IEnumerable;
if (objectInstanceArray != null)
if (methodParameter.Value is IEnumerable objectInstanceArray)
{
foreach (object element in objectInstanceArray)
{
var objectInstance2 = element as T;
if (objectInstance2 != null)
if (element is T objectInstance2)
{
result.Add(objectInstance2);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ internal void Initialize(PSCmdlet cmdlet, string className, string classVersion,
_classVersion = classVersion;
_privateData = privateData;

var compiledScript = this.Cmdlet as PSScriptCmdlet;
if (compiledScript != null)
if (this.Cmdlet is PSScriptCmdlet compiledScript)
{
compiledScript.StoppingEvent += delegate { this.StopProcessing(); };
compiledScript.DisposingEvent +=
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,12 @@ internal ScriptWriter(
}
catch (InvalidOperationException e)
{
XmlSchemaException schemaException = e.InnerException as XmlSchemaException;
if (schemaException != null)
if (e.InnerException is XmlSchemaException schemaException)
{
throw new XmlException(schemaException.Message, schemaException, schemaException.LineNumber, schemaException.LinePosition);
}

XmlException xmlException = e.InnerException as XmlException;
if (xmlException != null)
if (e.InnerException is XmlException xmlException)
{
throw xmlException;
}
Expand Down Expand Up @@ -828,8 +826,7 @@ private void SetParameters(CommandMetadata commandMetadata, params Dictionary<st
private CommandMetadata GetCommandMetadata(CommonCmdletMetadata cmdletMetadata)
{
string defaultParameterSetName = null;
StaticCmdletMetadataCmdletMetadata staticCmdletMetadata = cmdletMetadata as StaticCmdletMetadataCmdletMetadata;
if (staticCmdletMetadata != null)
if (cmdletMetadata is StaticCmdletMetadataCmdletMetadata staticCmdletMetadata)
{
if (!string.IsNullOrEmpty(staticCmdletMetadata.DefaultCmdletParameterSet))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,7 @@ private static PSAdaptedProperty GetPSComputerNameAdapter(CimInstance cimInstanc
public override System.Collections.ObjectModel.Collection<PSAdaptedProperty> GetProperties(object baseObject)
{
// baseObject should never be null
CimInstance cimInstance = baseObject as CimInstance;
if (cimInstance == null)
if (baseObject is not CimInstance cimInstance)
{
string msg = string.Format(CultureInfo.InvariantCulture,
CimInstanceTypeAdapterResources.BaseObjectNotCimInstance,
Expand Down Expand Up @@ -107,8 +106,7 @@ public override PSAdaptedProperty GetProperty(object baseObject, string property
}

// baseObject should never be null
CimInstance cimInstance = baseObject as CimInstance;
if (cimInstance == null)
if (baseObject is not CimInstance cimInstance)
{
string msg = string.Format(CultureInfo.InvariantCulture,
CimInstanceTypeAdapterResources.BaseObjectNotCimInstance,
Expand Down Expand Up @@ -142,8 +140,7 @@ public override PSAdaptedProperty GetFirstPropertyOrDefault(object baseObject, M
}

// baseObject should never be null
CimInstance cimInstance = baseObject as CimInstance;
if (cimInstance == null)
if (baseObject is not CimInstance cimInstance)
{
string msg = string.Format(
CultureInfo.InvariantCulture,
Expand Down Expand Up @@ -197,8 +194,7 @@ public override string GetPropertyTypeName(PSAdaptedProperty adaptedProperty)
{
ArgumentNullException.ThrowIfNull(adaptedProperty);

CimProperty cimProperty = adaptedProperty.Tag as CimProperty;
if (cimProperty != null)
if (adaptedProperty.Tag is CimProperty cimProperty)
{
return CimTypeToTypeNameDisplayString(cimProperty.CimType);
}
Expand All @@ -219,8 +215,7 @@ public override object GetPropertyValue(PSAdaptedProperty adaptedProperty)
{
ArgumentNullException.ThrowIfNull(adaptedProperty);

CimProperty cimProperty = adaptedProperty.Tag as CimProperty;
if (cimProperty != null)
if (adaptedProperty.Tag is CimProperty cimProperty)
{
return cimProperty.Value;
}
Expand Down
4 changes: 1 addition & 3 deletions src/System.Management.Automation/logging/LogProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,9 +189,7 @@ protected static void AppendException(StringBuilder sb, Exception except)
{
sb.AppendLine(StringUtil.Format(EtwLoggingStrings.ErrorRecordMessage, except.Message));

IContainsErrorRecord ier = except as IContainsErrorRecord;

if (ier != null)
if (except is IContainsErrorRecord ier)
{
ErrorRecord er = ier.ErrorRecord;

Expand Down
22 changes: 13 additions & 9 deletions src/System.Management.Automation/logging/MshLog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,11 @@ internal static void LogEngineHealthEvent(ExecutionContext executionContext,
}

InvocationInfo invocationInfo = null;
IContainsErrorRecord icer = exception as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
if (exception is IContainsErrorRecord icer && icer.ErrorRecord != null)
{
invocationInfo = icer.ErrorRecord.InvocationInfo;
}

foreach (LogProvider provider in GetLogProvider(executionContext))
{
if (NeedToLogEngineHealthEvent(provider, executionContext))
Expand Down Expand Up @@ -413,9 +415,11 @@ Severity severity
}

InvocationInfo invocationInfo = null;
IContainsErrorRecord icer = exception as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
if (exception is IContainsErrorRecord icer && icer.ErrorRecord != null)
{
invocationInfo = icer.ErrorRecord.InvocationInfo;
}

foreach (LogProvider provider in GetLogProvider(executionContext))
{
if (NeedToLogCommandHealthEvent(provider, executionContext))
Expand Down Expand Up @@ -605,9 +609,11 @@ Severity severity
}

InvocationInfo invocationInfo = null;
IContainsErrorRecord icer = exception as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
if (exception is IContainsErrorRecord icer && icer.ErrorRecord != null)
{
invocationInfo = icer.ErrorRecord.InvocationInfo;
}

foreach (LogProvider provider in GetLogProvider(executionContext))
{
if (NeedToLogProviderHealthEvent(provider, executionContext))
Expand Down Expand Up @@ -804,9 +810,7 @@ private static LogContext GetLogContext(ExecutionContext executionContext, Invoc
logContext.User = Logging.UnknownUserName;
}

System.Management.Automation.Remoting.PSSenderInfo psSenderInfo =
executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo;
if (psSenderInfo != null)
if (executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") is System.Management.Automation.Remoting.PSSenderInfo psSenderInfo)
{
logContext.ConnectedUser = psSenderInfo.UserInfo.Identity.Name;
}
Expand Down
3 changes: 1 addition & 2 deletions src/System.Management.Automation/security/SecurityManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -651,8 +651,7 @@ protected internal override bool ShouldRun(CommandInfo commandInfo,
break;

case CommandTypes.ExternalScript:
ExternalScriptInfo si = commandInfo as ExternalScriptInfo;
if (si == null)
if (commandInfo is not ExternalScriptInfo si)
{
reason = PSTraceSource.NewArgumentException("scriptInfo");
}
Expand Down
3 changes: 1 addition & 2 deletions src/System.Management.Automation/security/SecuritySupport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -663,8 +663,7 @@ private static bool CertHasKeyUsage(X509Certificate2 c, X509KeyUsageFlags keyUsa
{
foreach (X509Extension extension in c.Extensions)
{
X509KeyUsageExtension keyUsageExtension = extension as X509KeyUsageExtension;
if (keyUsageExtension != null)
if (extension is X509KeyUsageExtension keyUsageExtension)
{
if ((keyUsageExtension.KeyUsages & keyUsage) == keyUsage)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -761,8 +761,7 @@ private static Collection<string> ReadMultiStringValue(RegistryKey mshsnapinKey,
if (msv == null)
{
// Check if the value is in string format
string singleValue = value as string;
if (singleValue != null)
if (value is string singleValue)
{
msv = new string[1];
msv[0] = singleValue;
Expand Down
12 changes: 5 additions & 7 deletions src/System.Management.Automation/utils/CryptoUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,9 +235,9 @@ internal static byte[] ToCapiSimpleKeyBlob(byte[] encryptedKey)
// [2], [3] // RESERVED - Always 0
blob[4] = (byte)CALG_AES_256; // AES-256 algo id (0x10)
blob[5] = 0x66; // ??
// [6], [7], [8] // 0x00
// [6], [7], [8] // 0x00
blob[9] = (byte)CALG_RSA_KEYX; // 0xa4
// [10], [11] // 0x00
// [10], [11] // 0x00

// create a reversed copy and add the encrypted key
byte[] reversedKey = CreateReverseByteArray(encryptedKey);
Expand Down Expand Up @@ -365,7 +365,7 @@ internal sealed class PSRSACryptoServiceProvider : IDisposable
// handle to the AES provider object (houses session key and iv)
private readonly Aes _aes;

// this flag indicates that this class has a key imported from the
// this flag indicates that this class has a key imported from the
// remote end and so can be used for encryption
private bool _canEncrypt;

Expand Down Expand Up @@ -423,7 +423,7 @@ internal void GenerateSessionKey()
{
if (!_sessionKeyGenerated)
{
// Aes object gens key automatically on construction, so this is somewhat redundant,
// Aes object gens key automatically on construction, so this is somewhat redundant,
// but at least the actionable key will not be in-memory until it's requested fwiw.
_aes.GenerateKey();
_sessionKeyGenerated = true;
Expand Down Expand Up @@ -880,12 +880,10 @@ internal PSRemotingCryptoHelperServer()

internal override string EncryptSecureString(SecureString secureString)
{
ServerRemoteSession session = Session as ServerRemoteSession;

// session!=null check required for DRTs TestEncryptSecureString* entries in CryptoUtilsTest/UTUtils.dll
// for newer clients, server will never initiate key exchange.
// for server, just the session key is required to encrypt/decrypt anything
if ((session != null) && (session.Context.ClientCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM))
if (Session is ServerRemoteSession session && session.Context.ClientCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM)
{
_rsaCryptoProvider.GenerateSessionKey();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ internal CmdletInvocationException(Exception innerException,
ArgumentNullException.ThrowIfNull(innerException);
// invocationInfo may be null

IContainsErrorRecord icer = innerException as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
if (innerException is IContainsErrorRecord icer && icer.ErrorRecord != null)
{
_errorRecord = new ErrorRecord(icer.ErrorRecord, innerException);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -665,8 +665,7 @@ internal ParameterBindingValidationException(
errorId,
args)
{
ValidationMetadataException validationException = innerException as ValidationMetadataException;
if (validationException != null && validationException.SwallowException)
if (innerException is ValidationMetadataException validationException && validationException.SwallowException)
{
_swallowException = true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,8 @@ internal static string SafeToString(object obj)

try
{
PSObject pso = obj as PSObject;
string result;
if (pso != null)
if (obj is PSObject pso)
{
object baseObject = pso.BaseObject;
if (baseObject != null && baseObject is not PSCustomObject)
Expand Down
Loading