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
21 changes: 7 additions & 14 deletions src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1187,8 +1187,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession
//
// Build xpath for <Suppress>
//
Hashtable suppresshash = hash[hashkey_supress_lc] as Hashtable;
if (suppresshash != null)
if (hash[hashkey_supress_lc] is Hashtable suppresshash)
{
xpathStringSuppress = BuildXPathFromHashTable(suppresshash);
}
Expand Down Expand Up @@ -1255,8 +1254,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession
private static string HandleEventIdHashValue(object value)
{
StringBuilder ret = new();
Array idsArray = value as Array;
if (idsArray != null)
if (value is Array idsArray)
{
ret.Append('(');
for (int i = 0; i < idsArray.Length; i++)
Expand Down Expand Up @@ -1285,8 +1283,7 @@ private static string HandleEventIdHashValue(object value)
private static string HandleLevelHashValue(object value)
{
StringBuilder ret = new();
Array levelsArray = value as Array;
if (levelsArray != null)
if (value is Array levelsArray)
{
ret.Append('(');
for (int i = 0; i < levelsArray.Length; i++)
Expand Down Expand Up @@ -1317,8 +1314,7 @@ private string HandleKeywordHashValue(object value)
long keywordsMask = 0;
long keywordLong = 0;

Array keywordArray = value as Array;
if (keywordArray != null)
if (value is Array keywordArray)
{
foreach (object keyword in keywordArray)
{
Expand Down Expand Up @@ -1473,8 +1469,7 @@ private string HandleEndTimeHashValue(object value, Hashtable hash)
private static string HandleDataHashValue(object value)
{
StringBuilder ret = new();
Array dataArray = value as Array;
if (dataArray != null)
if (value is Array dataArray)
{
ret.Append('(');
for (int i = 0; i < dataArray.Length; i++)
Expand Down Expand Up @@ -1504,8 +1499,7 @@ private static string HandleDataHashValue(object value)
private static string HandleNamedDataHashValue(string key, object value)
{
StringBuilder ret = new();
Array dataArray = value as Array;
if (dataArray != null)
if (value is Array dataArray)
{
ret.Append('(');
for (int i = 0; i < dataArray.Length; i++)
Expand Down Expand Up @@ -1752,8 +1746,7 @@ private void CheckHashTablesForNullValues()
}
else
{
Array eltArray = value as Array;
if (eltArray != null)
if (value is Array eltArray)
{
foreach (object elt in eltArray)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -491,8 +491,7 @@ private IEnumerable<TSession> GetSessionsToActAgainst(QueryBuilder queryBuilder)
return this.Session;
}

var sessionBoundQueryBuilder = queryBuilder as ISessionBoundQueryBuilder<TSession>;
if (sessionBoundQueryBuilder != null)
if (queryBuilder is ISessionBoundQueryBuilder<TSession> sessionBoundQueryBuilder)
{
TSession sessionOfTheQueryBuilder = sessionBoundQueryBuilder.GetTargetSession();
if (sessionOfTheQueryBuilder != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,16 +98,14 @@ internal static CimJobException CreateFromAnyException(
Dbg.Assert(jobContext != null, "Caller should verify jobContext != null");
Dbg.Assert(inner != null, "Caller should verify inner != null");

CimException cimException = inner as CimException;
if (cimException != null)
if (inner is CimException cimException)
{
return CreateFromCimException(jobDescription, jobContext, cimException);
}

string message = BuildErrorMessage(jobDescription, jobContext, inner.Message);
CimJobException cimJobException = new(message, inner);
var containsErrorRecord = inner as IContainsErrorRecord;
if (containsErrorRecord != null)
if (inner is IContainsErrorRecord containsErrorRecord)
{
cimJobException.InitializeErrorRecord(
jobContext,
Expand Down Expand Up @@ -356,8 +354,7 @@ internal bool IsTerminatingError
{
get
{
var cimException = this.InnerException as CimException;
if ((cimException == null) || (cimException.ErrorData == null))
if ((this.InnerException is not CimException cimException) || (cimException.ErrorData == null))
{
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,17 +66,15 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m
methodParameter.Value = dotNetValue;
cmdletOutput.Add(methodParameter.Name, methodParameter);

var cimInstances = dotNetValue as CimInstance[];
if (cimInstances != null)
if (dotNetValue is CimInstance[] cimInstances)
{
foreach (var instance in cimInstances)
{
CimCmdletAdapter.AssociateSessionOfOriginWithInstance(instance, this.JobContext.Session);
}
}

var cimInstance = dotNetValue as CimInstance;
if (cimInstance != null)
if (dotNetValue is CimInstance cimInstance)
{
CimCmdletAdapter.AssociateSessionOfOriginWithInstance(cimInstance, this.JobContext.Session);
}
Expand Down Expand Up @@ -191,15 +189,13 @@ public override void OnNext(CimMethodResultBase item)
this.ExceptionSafeWrapper(
delegate
{
var methodResult = item as CimMethodResult;
if (methodResult != null)
if (item is CimMethodResult methodResult)
{
this.OnNext(methodResult);
return;
}

var streamedResult = item as CimMethodStreamedResult;
if (streamedResult != null)
if (item is CimMethodStreamedResult streamedResult)
{
this.OnNext(streamedResult);
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,7 @@ private static int GetNumberOfSessions(InvocationInfo invocationInfo)
int maxNumberOfSessionsIndicatedByCimInstanceArguments = 1;
foreach (object cmdletArgument in invocationInfo.BoundParameters.Values)
{
CimInstance[] array = cmdletArgument as CimInstance[];
if (array != null)
if (cmdletArgument is CimInstance[] array)
{
int numberOfSessionsAssociatedWithArgument = array
.Select(CimCmdletAdapter.GetSessionOfOriginFromCimInstance)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -623,8 +623,7 @@ internal void ReportJobFailure(IContainsErrorRecord exception)
}
else
{
CimJobException cje = exception as CimJobException;
if ((cje != null) && (cje.IsTerminatingError))
if ((exception is CimJobException cje) && (cje.IsTerminatingError))
{
terminatingErrorTracker.MarkSessionAsTerminated(this.JobContext.Session, out sessionWasAlreadyTerminated);
isThisTerminatingError = true;
Expand Down Expand Up @@ -1013,8 +1012,7 @@ internal static bool IsShowComputerNameMarkerPresent(CimInstance cimInstance)

internal static void AddShowComputerNameMarker(PSObject pso)
{
PSPropertyInfo psShowComputerNameProperty = pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] as PSPropertyInfo;
if (psShowComputerNameProperty != null)
if (pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] is PSPropertyInfo psShowComputerNameProperty)
{
psShowComputerNameProperty.Value = true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ public NotFoundError(string propertyName, object propertyValue, bool wildcardsEn

if (wildcardsEnabled)
{
var propertyValueAsString = propertyValue as string;
if ((propertyValueAsString != null) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString)))
if ((propertyValue is string propertyValueAsString) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString)))
{
this.ErrorMessageGenerator =
(queryDescription, className) => GetErrorMessageForNotFound_ForWildcard(this.PropertyName, this.PropertyValue, className);
Expand Down Expand Up @@ -466,8 +465,7 @@ protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object
}
else
{
string expectedPropertyValueAsString = cimTypedExpectedPropertyValue as string;
if (expectedPropertyValueAsString != null && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString))
if (cimTypedExpectedPropertyValue is string expectedPropertyValueAsString && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString))
{
return BehaviorOnNoMatch.SilentlyContinue;
}
Expand Down Expand Up @@ -504,8 +502,7 @@ private static bool NonWildcardEqual(string propertyName, object actualPropertyV
actualPropertyValue = actualPropertyValue.ToString();
}

var expectedPropertyValueAsString = expectedPropertyValue as string;
if (expectedPropertyValueAsString != null)
if (expectedPropertyValue is string expectedPropertyValueAsString)
{
var actualPropertyValueAsString = (string)actualPropertyValue;
return actualPropertyValueAsString.Equals(expectedPropertyValueAsString, StringComparison.OrdinalIgnoreCase);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -903,8 +903,7 @@ internal bool DoStartService(ServiceController serviceController)
}
catch (InvalidOperationException e)
{
Win32Exception eInner = e.InnerException as Win32Exception;
if (eInner == null
if (e.InnerException is not Win32Exception eInner
|| eInner.NativeErrorCode != NativeMethods.ERROR_SERVICE_ALREADY_RUNNING)
{
exception = e;
Expand Down Expand Up @@ -1020,9 +1019,7 @@ internal List<ServiceController> DoStopService(ServiceController serviceControll
}
catch (InvalidOperationException e)
{
Win32Exception eInner =
e.InnerException as Win32Exception;
if (eInner == null
if (e.InnerException is not Win32Exception eInner
|| eInner.NativeErrorCode != NativeMethods.ERROR_SERVICE_NOT_ACTIVE)
{
exception = e;
Expand Down Expand Up @@ -1117,8 +1114,7 @@ internal bool DoPauseService(ServiceController serviceController)
}
catch (InvalidOperationException e)
{
Win32Exception eInner = e.InnerException as Win32Exception;
if (eInner != null
if (e.InnerException is Win32Exception eInner
&& eInner.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE)
{
serviceNotRunning = true;
Expand Down Expand Up @@ -1198,8 +1194,7 @@ internal bool DoResumeService(ServiceController serviceController)
}
catch (InvalidOperationException e)
{
Win32Exception eInner = e.InnerException as Win32Exception;
if (eInner != null
if (e.InnerException is Win32Exception eInner
&& eInner.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE)
{
serviceNotRunning = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -560,9 +560,8 @@ private sealed class ValidateNotePropertyNameAttribute : ValidateArgumentsAttrib
{
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
{
string notePropertyName = arguments as string;
PSMemberTypes memberType;
if (notePropertyName != null && LanguagePrimitives.TryConvertTo<PSMemberTypes>(notePropertyName, out memberType))
if (arguments is string notePropertyName && LanguagePrimitives.TryConvertTo<PSMemberTypes>(notePropertyName, out memberType))
{
switch (memberType)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -502,9 +502,8 @@ protected override void BeginProcessing()
MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
string Message = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]);
WarningRecord record = new(Message);
InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;

if (invocationInfo != null)
if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo)
{
record.SetInvocationInfo(invocationInfo);
}
Expand Down Expand Up @@ -553,16 +552,14 @@ private void WriteColumns(List<MshParameter> mshParams)
foreach (MshParameter p in mshParams)
{
COLTag.Append("<col");
string width = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string;
if (width != null)
if (p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) is string width)
{
COLTag.Append(" width = \"");
COLTag.Append(width);
COLTag.Append('"');
}

string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string;
if (alignment != null)
if (p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) is string alignment)
{
COLTag.Append(" align = \"");
COLTag.Append(alignment);
Expand Down Expand Up @@ -608,8 +605,7 @@ private void WriteListEntry()
private static void WritePropertyName(StringBuilder Listtag, MshParameter p)
{
// for writing the property name
string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string;
if (label != null)
if (p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) is string label)
{
Listtag.Append(label);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -338,8 +338,7 @@ private bool HandlePrimitiveKnownTypePSObject(object source, string property, in
Dbg.Assert(source != null, "caller should validate the parameter");

bool sourceHandled = false;
PSObject moSource = source as PSObject;
if (moSource != null && !moSource.ImmediateBaseObjectIsEmpty)
if (source is PSObject moSource && !moSource.ImmediateBaseObjectIsEmpty)
{
// Check if baseObject is primitive known type
object baseObject = moSource.ImmediateBaseObject;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -407,8 +407,7 @@ private void RemoveDataEventHandlers()
private void HandleRunspaceAvailabilityChanged(object sender, RunspaceAvailabilityEventArgs e)
{
// Ignore nested commands.
LocalRunspace localRunspace = sender as LocalRunspace;
if (localRunspace != null)
if (sender is LocalRunspace localRunspace)
{
var basePowerShell = localRunspace.GetCurrentBasePowerShell();
if ((basePowerShell != null) && (basePowerShell.IsNested))
Expand Down Expand Up @@ -438,17 +437,15 @@ private void HandleDebuggerNestedDebuggingCancelledEvent(object sender, EventArg

private void HandlePipelineOutputDataReady(object sender, EventArgs e)
{
PipelineReader<PSObject> reader = sender as PipelineReader<PSObject>;
if (reader != null && reader.IsOpen)
if (sender is PipelineReader<PSObject> reader && reader.IsOpen)
{
WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Output);
}
}

private void HandlePipelineErrorDataReady(object sender, EventArgs e)
{
PipelineReader<object> reader = sender as PipelineReader<object>;
if (reader != null && reader.IsOpen)
if (sender is PipelineReader<object> reader && reader.IsOpen)
{
WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Error);
}
Expand Down Expand Up @@ -538,8 +535,7 @@ private void EnableHostDebugger(Runspace runspace, bool enabled)
// Only enable and disable the host's runspace if we are in process attach mode.
if (_debugger is ServerRemoteDebugger)
{
LocalRunspace localRunspace = runspace as LocalRunspace;
if ((localRunspace != null) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null))
if ((runspace is LocalRunspace localRunspace) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null))
{
try
{
Expand All @@ -552,8 +548,7 @@ private void EnableHostDebugger(Runspace runspace, bool enabled)

private static void SetLocalMode(System.Management.Automation.Debugger debugger, bool localMode)
{
ServerRemoteDebugger remoteDebugger = debugger as ServerRemoteDebugger;
if (remoteDebugger != null)
if (debugger is ServerRemoteDebugger remoteDebugger)
{
remoteDebugger.LocalDebugMode = localMode;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,13 @@ internal override object GetValue(PSObject liveObject)

// The live object has the liveObjectPropertyName property.
object liveObjectValue = propertyInfo.Value;
ICollection collectionValue = liveObjectValue as ICollection;
if (collectionValue != null)
if (liveObjectValue is ICollection collectionValue)
{
liveObjectValue = _parentCmdlet.ConvertToString(PSObjectHelper.AsPSObject(propertyInfo.Value));
}
else
{
PSObject psObjectValue = liveObjectValue as PSObject;
if (psObjectValue != null)
if (liveObjectValue is PSObject psObjectValue)
{
// Since PSObject implements IComparable there is a need to verify if its BaseObject actually implements IComparable.
if (psObjectValue.BaseObject is IComparable)
Expand Down
Loading