V3022. Expression is always true/false.
V3022 Expression 'c > '\xFFFF'' is always false. Output.cs 685
private static string Encode(string s)
{
....
foreach( char c in s ) {
if (c == splitC || c == '\n' || c == '\\') {
specialCount++;
}
else if (c > '\x7F') {
if (c > '\xFFFF') specialCount += 9;
else specialCount += 5;
}
}
....
}
V3022 Expression 'readercount >= 0' is always true. Unsigned type value is always >= 0. ReaderWriterLockSlim.cs 977
private void ExitAndWakeUpAppropriateWaitersPreferringWriters()
{
....
uint readercount = GetNumReaders();
....
if (readercount == 1 && _numWriteUpgradeWaiters > 0)
{
....
}
else if (readercount == 0 && _numWriteWaiters > 0)
{
ExitMyLock();
_writeEvent.Set();
}
else if (readercount >= 0)
{
....
}
else
ExitMyLock();
....
}
V3022 Expression 'x < 0' is always false. Unsigned type value is always >= 0. IntOps.Generated.cs 1967
public static int __hash__(UInt64 x) {
int total = unchecked((int) (((uint)x) + (uint)(x >> 32)));
if (x < 0) {
return unchecked(-total);
}
return total;
}
V3022 Expression 'lmrType.IsPointer || lmrType.IsEnum || typeCode != TypeCode.DateTime || typeCode != TypeCode.Object' is always true. DkmClrValue.cs 136
public enum TypeCode
{
....
Object = 1,
....
DateTime = 16,
....
}
static object GetHostObjectValue(Type lmrType, object rawValue)
{
var typeCode = Metadata.Type.GetTypeCode(lmrType);
return (lmrType.IsPointer || lmrType.IsEnum ||
typeCode != TypeCode.DateTime ||
typeCode != TypeCode.Object)
? rawValue : null;
}
V3022 Expression is always false. Atf.Gui.Wpf.vs2010 PriorityQuadTree.cs 575
public Rect Extent
{
get { return _extent; }
set
{
if (value.Top < -1.7976931348623157E+308 ||
value.Top > 1.7976931348623157E+308 ||
value.Left < -1.7976931348623157E+308 ||
value.Left > 1.7976931348623157E+308 ||
value.Width > 1.7976931348623157E+308 ||
value.Height > 1.7976931348623157E+308)
{
throw new ArgumentOutOfRangeException("value");
}
_extent = value;
ReIndex();
}
}
V3022 Expression 'bagEntityId != null' is always true. Sandbox.Game MyCharacterInventorySpawnComponent.cs 60
private long SpawnInventoryContainer(
MyDefinitionId bagDefinition)
{ ... }
public override void OnCharacterDead()
{
....
var bagEntityId = SpawnInventoryContainer(
Character.Definition.InventorySpawnContainerId.Value);
if (bagEntityId != null)
....
}
Similar errors can be found in some other places:
V3022 Expression 'i == 0' is always true. Sandbox.Game MyGridClipboardAdvanced.cs 790
private new bool TestPlacement()
{
....
for (int i = 0; i < PreviewGrids.Count; ++i)
{
....
if (retval && i == 0)
{
....
var settings = i == 0 ?
m_settings.GetGridPlacementSettings(grid, false) :
MyPerGameSettings.BuildingSettings.SmallStaticGrid;
....
}
....
}
}
Similar errors can be found in some other places:
V3022 Expression 'moveNextFrame' is always true. SiliconStudio.Xenko.Engine AnimationChannel.cs 314
private void SetTime(CompressedTimeSpan timeSpan)
{
....
while (....)
{
var moveNextFrame = currentKeyFrame.MoveNext();
if (!moveNextFrame)
{
....
break;
}
var keyFrame = moveNextFrame ? currentKeyFrame.Current :
data.ValueNext;
....
}
....
}
Similar errors can be found in some other places:
V3022 Expression 'genericParameter.Owner.GenericParameterType == GenericParameterType.Type' is always false. ICSharpCode.Decompiler TypesHierarchyHelpers.cs 441
public TypeReference ResolveWithContext(TypeReference type)
{
....
if (genericParameter.Owner.GenericParameterType ==
GenericParameterType.Type)
return TypeArguments[genericParameter.Position];
else
return genericParameter.Owner.GenericParameterType
== GenericParameterType.Type
? UnresolvedGenericTypeParameter :
UnresolvedGenericMethodParameter;
....
}
V3022 Expression 'forceInferChildren' is always true. ICSharpCode.Decompiler TypeAnalysis.cs 632
TypeReference
DoInferTypeForExpression(
ILExpression expr,
TypeReference expectedType,
bool forceInferChildren = false)
{
....
if (forceInferChildren) {
....
if (forceInferChildren) {
InferTypeForExpression(
expr.Arguments.Single(), lengthType);
}
}
....
}
V3022 Expression 'values != null' is always true. Util.cs 287
public static string FindNumeric(string content)
{
string[] values = content.Split(' ');
if (values != null)
{
return values[0];
}
return "none";
}
V3022 Expression '(_i_inc < 0)' is always false. Accord.Math BoundedBroydenFletcherGoldfarbShanno.FORTRAN.cs 5222
private static void dscal(int n, double da, double[] dx,
int _dx_offset, int incx)
{
....
if (((n <= 0) || (incx <= 0)))
{
return;
}
....
int _i_inc = incx;
for (i = 1;
(_i_inc < 0) ? i >= nincx : i <= nincx;
i += _i_inc)
....
}
V3022 Expression 'this.linePoints != null' is always true. PathLine.cs 346
public override void Render(DrawArgs drawArgs)
{
....
if(this.linePoints.Length > 1) // <=
{
....
if(this.linePoints != null) // <=
{
....
}
}
....
}
Also see V3095
V3022 Expression 'setting == "GlobalClasspath"' is always false. PluginMain.cs 1194
private void SettingChanged(string setting)
{
if (setting == "ExcludedFileTypes"
|| setting == "ExcludedDirectories"
|| setting == "ShowProjectClasspaths"
|| setting == "ShowGlobalClasspaths"
|| setting == "GlobalClasspath")
{
Tree.RebuildTree();
}
else if (setting == "ExecutableFileTypes")
{
FileInspector.ExecutableFileTypes =
Settings.ExecutableFileTypes;
}
else if (setting == "GlobalClasspath") // <=
{
// clear compile cache for all projects
FlexCompilerShell.Cleanup();
}
}
Similar errors can be found in some other places:
V3022 Expression 'pointerEvent.pointerDrag != null' is always false. UnityEngine.UI TouchInputModule.cs 227
private void ProcessTouchPress(....)
{
....
pointerEvent.pointerDrag = null;
if (pointerEvent.pointerDrag != null)
ExecuteEvents.Execute(pointerEvent.pointerDrag,
pointerEvent,
ExecuteEvents.endDragHandler);
....
}
Similar errors can be found in some other places:
V3022 Expression 'itemsAndMetadataFound.Metadata.Values.Count > 0' is always true. Evaluator.cs 1752
private void EvaluateItemElement(....)
{
....
if (itemsAndMetadataFound.Metadata != null &&
itemsAndMetadataFound.Metadata.Values.Count > 0)
{
....
if (itemsAndMetadataFound.Metadata.Values.Count > 0) // <=
{
needToProcessItemsIndividually = true;
}
....
}
....
}
Similar errors can be found in some other places:
V3022 Expression '(lineLength > 0)' is always true. GitUI EditNetSpell.cs 807
public void EnsureEmptyLine(bool addBullet, int afterLine)
{
....
if (lineLength > 0)
{
....
var newLine = (lineLength > 0) ?
Environment.NewLine :
String.Empty;
....
}
}
Similar errors can be found in some other places:
V3022 Expression 'stateInfo.State == RunspacePoolState.Disconnected' is always false. System.Management.Automation RunspacePoolInternal.cs 581
public enum RunspacePoolState
{
BeforeOpen = 0,
Opening = 1,
Opened = 2,
Closed = 3,
Closing = 4,
Broken = 5,
Disconnecting = 6,
Disconnected = 7,
Connecting = 8,
}
internal virtual int GetAvailableRunspaces()
{
....
if (stateInfo.State == RunspacePoolState.Opened)
{
....
return (pool.Count + unUsedCapacity);
}
else if (stateInfo.State != RunspacePoolState.BeforeOpen &&
stateInfo.State != RunspacePoolState.Opening)
{
throw new InvalidOperationException(
HostInterfaceExceptionsStrings.RunspacePoolNotOpened);
}
else if (stateInfo.State == RunspacePoolState.Disconnected)
{
throw new InvalidOperationException(
RunspacePoolStrings.CannotWhileDisconnected);
}
else
{
return maxPoolSz;
}
....
}
V3022 Expression 'i == 4' is always false. WebHost.cs 162
public void Clean() {
// Try to delete temporary files for up to ~1.2 seconds.
for (int i = 0; i < 4; i++) {
Log("Waiting 300msec before trying to delete ....");
Thread.Sleep(300);
if (TryDeleteTempFiles(i == 4)) {
Log("Successfully deleted all ....");
break;
}
}
}
Similar errors can be found in some other places:
V3022 Expression 'name != "Min" || name != "Max"' is always true. Probably the '&&' operator should be used here. DynamicPublishedContentList.cs 415
private object Aggregate(....)
{
....
if (name != "Min" || name != "Max")
{
throw new ArgumentException(
"Can only use aggregate min or max methods on properties
which are datetime");
}
....
}
Similar errors can be found in some other places:
V3022 Expression '!stop' is always true. template.cs 229
public Control parseStringBuilder(....)
{
....
bool stop = false;
....
while (!stop)
{
....
}
....
}
V3022 Expression '"Invalid header name: " + name' is always not null. The operator '??' is excessive. HttpRequest.cs 309
public void AddHeader(string name, string value)
{
if (string.IsNullOrEmpty(name))
throw new BadRequestException(
"Invalid header name: " + name ?? "<null>"); // <=
}
'+' operator has higher priority than operator '??'. So experssion '"Invalid header name: " + name' has been evaluated first.
Similar errors can be found in some other places:
V3022 Expression 't == null' is always true. VisualPascalABCNET Debugger.cs 141
public static Type GetTypeForStatic(string name)
{
Type t = stand_types[name] as Type;
if (t != null) return t;
if (t == null) // <=
foreach (string s in ns_ht.Keys)
{
....
}
t = PascalABCCompiler.NetHelper.NetHelper.FindType(name);
....
}
Similar errors can be found in some other places:
V3022 CWE-570 Expression '_networkSession != null && _networkSession.LastSubtitle != null && i < _networkSession.LastSubtitle.Paragraphs.Count' is always false. Main.cs 7242
private void DeleteSelectedLines()
{
....
if (_networkSession != null) // <=
{
_networkSession.TimerStop();
NetworkGetSendUpdates(indices, 0, null);
}
else
{
indices.Reverse();
foreach (int i in indices)
{
_subtitle.Paragraphs.RemoveAt(i);
if (_networkSession != null && // <=
_networkSession.LastSubtitle != null &&
i < _networkSession.LastSubtitle.Paragraphs.Count)
_networkSession.LastSubtitle.Paragraphs.RemoveAt(i);
}
....
}
....
}
V3022 CWE-570 Expression 'param.Bitmap.Width == 720 && param.Bitmap.Width == 480' is always false. Probably the '||' operator should be used here. ExportPngXml.cs 1808
private static string FormatFabTime(TimeCode time,
MakeBitmapParameter param)
{
if (param.Bitmap.Width == 720 && param.Bitmap.Width == 480)
return $"....";
// drop frame
if (Math.Abs(param.... - 24 * (999 / 1000)) < 0.01 ||
Math.Abs(param.... - 29 * (999 / 1000)) < 0.01 ||
Math.Abs(param.... - 59 * (999 / 1000)) < 0.01)
return $"....";
return $"....";
}
V3022 CWE-571 Expression 'listBoxVobFiles.Items.Count > 0' is always true. DvdSubRip.cs 533
private void DvdSubRip_Shown(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(_initialFileName))
return;
if (_initialFileName.EndsWith(".ifo", ....))
{
OpenIfoFile(_initialFileName);
}
else if (_initialFileName.EndsWith(".vob", ....))
{
listBoxVobFiles.Items.Add(_initialFileName);
buttonStartRipping.Enabled = listBoxVobFiles.Items.Count > 0;
}
_initialFileName = null;
}
V3022 CWE-570 Expression 'index < 0 && index >= parameters.Length' is always false. AnimatorControllerPlayable.bindings.cs 287
public AnimatorControllerParameter GetParameter(int index)
{
AnimatorControllerParameter[] param = parameters;
if (index < 0 && index >= parameters.Length)
throw new IndexOutOfRangeException(
"Index must be between 0 and " + parameters.Length);
return param[index];
}
Similar errors can be found in some other places:
V3022 CWE-570 Expression 'handle.valueIndex < 0 && handle.valueIndex >= list.Length' is always false. StyleSheet.cs 81
static T CheckAccess<T>(T[] list, StyleValueType type,
StyleValueHandle handle)
{
T value = default(T);
if (handle.valueType != type)
{
Debug.LogErrorFormat(.... );
}
else if (handle.valueIndex < 0 &&
handle.valueIndex >= list.Length)
{
Debug.LogError("Accessing invalid property");
}
else
{
value = list[handle.valueIndex];
}
return value;
}
V3022 CWE-571 Expression 'bRegisterAllDefinitions || (AudioSettings.GetSpatializerPluginName() == "GVR Audio Spatializer")' is always true. AudioExtensions.cs 463
// This is where we register our built-in spatializer extensions.
static private void RegisterBuiltinDefinitions()
{
bool bRegisterAllDefinitions = true;
if (!m_BuiltinDefinitionsRegistered)
{
if (bRegisterAllDefinitions ||
(AudioSettings.GetSpatializerPluginName() ==
"GVR Audio Spatializer"))
{
}
if (bRegisterAllDefinitions ||
(AudioSettings.GetAmbisonicDecoderPluginName() ==
"GVR Audio Spatializer"))
{
}
m_BuiltinDefinitionsRegistered = true;
}
}
Similar errors can be found in some other places:
V3022 CWE-570 Expression 'PerceptionRemotingPlugin.GetConnectionState() != HolographicStreamerConnectionState.Disconnected' is always false. HolographicEmulationWindow.cs 171
private void Disconnect()
{
if (PerceptionRemotingPlugin.GetConnectionState() !=
HolographicStreamerConnectionState.Disconnected)
PerceptionRemotingPlugin.Disconnect();
}
internal static HolographicStreamerConnectionState
GetConnectionState()
{
return HolographicStreamerConnectionState.Disconnected;
}
V3022 CWE-570 Expression 'PerceptionRemotingPlugin.GetConnectionState() == HolographicStreamerConnectionState.Connected' is always false. HolographicEmulationWindow.cs 177
private bool IsConnectedToRemoteDevice()
{
return PerceptionRemotingPlugin.GetConnectionState() ==
HolographicStreamerConnectionState.Connected;
}
internal static HolographicStreamerConnectionState
GetConnectionState()
{
return HolographicStreamerConnectionState.Disconnected;
}
V3022 Expression 'resultIndex == null' is always false. Compiler FactorManager.cs 382
internal static DependencyInformation GetDependencyInfo(....)
{
....
IExpression resultIndex = null;
....
if (resultIndex != null)
{
if (parameter.IsDefined(
typeof(SkipIfMatchingIndexIsUniformAttribute), false))
{
if (resultIndex == null)
throw new InferCompilerException(
parameter.Name
+ " has SkipIfMatchingIndexIsUniformAttribute but "
+ StringUtil.MethodNameToString(method)
+ " has no resultIndex parameter");
....
}
....
}
....
}
V3022 Expression 'genres.Length < 1 && genres.Length > 3' is always false. Probably the '||' operator should be used here. Evaluator Features.cs 242
public static Tuple<int, string> ComputeMovieGenre(int offset,
string feature)
{
string[] genres = feature.Split('|');
if (genres.Length < 1 && genres.Length > 3)
{
throw
new ArgumentException(string.Format(
"Movies should have between 1 and 3 genres; given {0}.",
genres.Length));
}
double value = 1.0 / genres.Length;
var result
= new StringBuilder(
string.Format(
"{0}:{1}",
offset + MovieGenreBuckets[genres[0]],
value));
for (int i = 1; i < genres.Length; ++i)
{
result.Append(
string.Format(
"|{0}:{1}",
offset + MovieGenreBuckets[genres[i].Trim()],
value));
}
return new Tuple<int, string>(MovieGenreBucketCount, result.ToString());
}
V3022 Expression 'saveStreams' is always false. HTMLExport.cs 849
protected override void Finish()
{
....
if (saveStreams)
{
FinishSaveStreams();
}
else
{
if (singlePage)
{
if (saveStreams)
{
int fileIndex = GeneratedFiles.IndexOf(singlePageFileName);
DoPageEnd(generatedStreams[fileIndex]);
}
else { .... }
....
}
....
}
....
}
V3022 [CWE-571] Expression 'doLog' is always true. AWSSDK.Core.Net45 StoredProfileAWSCredentials.cs 235
private static bool ValidCredentialsExistInSharedFile(....)
{
....
var doLog = false;
try
{
if (....)
{
return true;
}
else
{
doLog = true;
}
}
catch (InvalidDataException)
{
doLog = true;
}
if (doLog) // <=
{
....
}
....
}
V3022 Expression '!result' is always false. AWSSDK.CognitoSync.PCL SQLiteLocalStorage.cs 353
public void PutValue(....)
{
....
bool result = PutValueHelper(....);
if (!result) <=
{
_logger.DebugFormat("{0}",
@"Cognito Sync - SQLiteStorage - Put Value Failed");
}
else
{
UpdateLastModifiedTimestamp(....);
}
....
}
private bool PutValueHelper(....)
{
....
if (....))
{
return true;
}
if (record == null)
{
....
return true;
}
else
{
....
return true;
}
}
V3022 Expression 'names != null' is always true. DynamicDebuggerProxy.cs 426
private static IList<KeyValuePair<string, object>>
QueryDynamicObject(object obj)
{
....
List<string> names = new List<string>(mo.GetDynamicMemberNames());
names.Sort();
if (names != null)
{ .... }
....
}
V3022 Expression 'newLength == int.MaxValue' is always false. ObjectManager.cs 1423
private void EnlargeArray()
{
int newLength = _values.Length * 2;
if (newLength < 0)
{
if (newLength == int.MaxValue)
{
throw new SerializationException(SR.Serialization_TooManyElements);
}
....
}
....
}
Similar errors can be found in some other places:
V3022 Expression '!string.IsNullOrEmpty(quotePrefix) || quotePrefix != " "' is always true. OdbcCommandBuilder.cs 338
public string UnquoteIdentifier(....)
{
....
if (!string.IsNullOrEmpty(quotePrefix) || quotePrefix != " ")
....
....
}
V3022 Expression 'cacheMemoryLimit != 0 && _memoryLimit != 0' is always false. CacheMemoryMonitor.cs 250
internal void SetLimit(int cacheMemoryLimitMegabytes)
{
long cacheMemoryLimit = cacheMemoryLimitMegabytes;
cacheMemoryLimit = cacheMemoryLimit << MEGABYTE_SHIFT;
_memoryLimit = 0; // <=
if (cacheMemoryLimit == 0 && _memoryLimit == 0)
....
else if (cacheMemoryLimit != 0 && _memoryLimit != 0) // <=
....
else if (cacheMemoryLimit != 0)
....
....
}
V3022 [CWE-571] Expression 'dataObject != null' is always true. TaskThumbnailPanel.cs 415
private void PbThumbnail_MouseMove(object sender, MouseEventArgs e)
{
....
IDataObject dataObject
= new DataObject(DataFormats.FileDrop,
new string[] { Task.Info.FilePath });
if (dataObject != null) // <=
{
Program.MainForm.AllowDrop = false;
dragBoxFromMouseDown = Rectangle.Empty;
pbThumbnail.DoDragDrop(dataObject,
DragDropEffects.Copy | DragDropEffects.Move);
Program.MainForm.AllowDrop = true;
}
....
}
V3022 [CWE-571] Expression 'img != null' is always true. ClipboardHelpers.cs 289
private static Image GetDIBImage(MemoryStream ms)
{
....
try
{
....
return new Bitmap(bmp);
....
}
finally
{
if (gcHandle != IntPtr.Zero)
{
GCHandle.FromIntPtr(gcHandle).Free();
}
}
....
}
private static Image GetImageAlternative()
{
....
using (MemoryStream ms = dataObject.GetData(format) as MemoryStream)
{
if (ms != null)
{
try
{
Image img = GetDIBImage(ms);
if (img != null) // <=
{
return img;
}
}
catch (Exception e)
{
DebugHelper.WriteException(e);
}
}
}
....
}
V3022 [CWE-571] Expression 'lvClipboardFormats.SelectedItems.Count > 0' is always true. AfterUploadForm.cs 155
private void btnCopyLink_Click(object sender, EventArgs e)
{
....
if (lvClipboardFormats.SelectedItems.Count == 0)
{
url = lvClipboardFormats.Items[0].SubItems[1].Text;
}
else if (lvClipboardFormats.SelectedItems.Count > 0) // <=
{
url = lvClipboardFormats.SelectedItems[0].SubItems[1].Text;
}
....
}
V3022 Expression 'itemCount > 0' is always false. RegionCaptureForm.cs 1100
private void DrawCursorGraphics(Graphics g)
{
....
int cursorOffsetX = 10, cursorOffsetY = 10, itemGap = 10, itemCount = 0;
Size totalSize = Size.Empty;
int magnifierPosition = 0;
Bitmap magnifier = null;
if (Options.ShowMagnifier)
{
if (itemCount > 0) totalSize.Height += itemGap; // <=
....
}
....
}
V3022 Expression 'apiType.HasValue' is always false. ApiManagementClient.cs 1134
private string GetApiTypeForImport(...., PsApiManagementApiType? apiType)
{
....
if (apiType.HasValue)
{
switch(apiType.Value)
{
case PsApiManagementApiType.Http: return SoapApiType.SoapToRest;
case PsApiManagementApiType.Soap: return SoapApiType.SoapPassThrough;
default: return SoapApiType.SoapPassThrough;
}
}
return apiType.HasValue ? // <=
apiType.Value.ToString("g") :
PsApiManagementApiType.Http.ToString("g");
}
V3022 Expression 'automationJob != null && automationJob == null' is always false. NodeConfigurationDeployment.cs 199
public NodeConfigurationDeployment(
....,
Management.Automation.Models.Job automationJob = null,
....)
{
....
if (automationJob != null && automationJob == null) return;
....
}
V3022 Expression is always false. DataFactoryClient.Encrypt.cs 37
public virtual string OnPremisesEncryptString(....)
{
....
if ( linkedServiceType == LinkedServiceType.OnPremisesSqlLinkedService
&& linkedServiceType == LinkedServiceType.OnPremisesOracleLinkedService
&& linkedServiceType == LinkedServiceType.OnPremisesFileSystemLinkedService
&& (value == null || value.Length == 0))
{
throw new ArgumentNullException("value");
}
....
}
Similar errors can be found in some other places:
V3022 Expression 'String.IsNullOrEmpty("winName")' is always false. Cv2_highgui.cs 46
public static void
DestroyWindow(string winName)
{
if (String.IsNullOrEmpty("winName"))
....
}
Similar errors can be found in some other places:
V3022 Expression 'objectPoints == null' is always false. Cv2_calib3d.cs 1372
public static double CalibrateCamera(....)
{
if (objectPoints == null)
throw new ArgumentNullException(nameof(objectPoints));
if (objectPoints == null)
throw new ArgumentNullException(nameof(objectPoints));
....
}
Also see V3021
Similar errors can be found in some other places:
V3022 Expression 'label == MarkerValue' is always false. Labeller.cs 135
internal static class Labeller
{
....
private const int MarkerValue = -1;
public static int Perform(Mat img, CvBlobs blobs)
{
....
int label = 0;
int lastLabel = 0;
CvBlob lastBlob = null;
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
if (imgIn[x + y * step] == 0)
continue;
bool labeled = labels[y, x] != 0;
if (....)
{
labeled = true;
// Label contour.
label++;
if (label == MarkerValue) // <=
throw new Exception();
....
}
....
}
....
}
}
}
V3022 Expression is always true. Probably the '&&' operator should be used here. NavigationDirection.cs 89
public static bool IsDirectional(this NavigationDirection direction)
{
return direction > NavigationDirection.Previous ||
direction <= NavigationDirection.PageDown;
}
V3022 Expression 'processUnsupportedFrame(frame, CloseStatusCode.PolicyViolation, null)' is always false. WebSocket.cs 462
private bool processWebSocketFrame(WebSocketFrame frame)
{
return frame.IsCompressed && _compression == CompressionMethod.None
? processUnsupportedFrame(....)
: frame.IsFragmented
? processFragmentedFrame(frame)
: frame.IsData
? processDataFrame(frame)
: frame.IsPing
? processPingFrame(frame)
: frame.IsPong
? processPongFrame(frame)
: frame.IsClose
? processCloseFrame(frame)
: processUnsupportedFrame(....);
}
private bool processUnsupportedFrame(....)
{
processException(....);
return false;
}
private bool processDataFrame(WebSocketFrame frame)
{
....
return true;
}
private bool processPingFrame(WebSocketFrame frame)
{
var mask = Mask.Unmask;
return true;
}
private bool processPongFrame(WebSocketFrame frame)
{
_receivePong.Set();
return true;
}
private bool processCloseFrame(WebSocketFrame frame)
{
var payload = frame.PayloadData;
close(payload, !payload.ContainsReservedCloseStatusCode, false);
return false;
}
Similar errors can be found in some other places:
V3022 [CWE-571] Expression 'shortPrompt' is always true. InteractivePrompt.cs 101
public static string
prompt_for_confirmation(.... bool shortPrompt = false, ....)
{
....
if (shortPrompt)
{
var choicePrompt = choice.is_equal_to(defaultChoice) //1
?
shortPrompt //2
?
"[[{0}]{1}]".format_with(choice.Substring(0, 1).ToUpperInvariant(), //3
choice.Substring(1,choice.Length - 1))
:
"[{0}]".format_with(choice.ToUpperInvariant()) //0
:
shortPrompt //4
?
"[{0}]{1}".format_with(choice.Substring(0,1).ToUpperInvariant(), //5
choice.Substring(1,choice.Length - 1))
:
choice; //0
....
}
....
}
Similar errors can be found in some other places:
V3022 [CWE-571] Expression 'installedPackageVersions.Count != 1' is always true. NugetService.cs 1405
private void remove_nuget_cache_for_package(....)
{
if (!config.AllVersions && installedPackageVersions.Count > 1)
{
const string allVersionsChoice = "All versions";
if (installedPackageVersions.Count != 1)
{
choices.Add(allVersionsChoice);
}
....
}
....
}
V3022 Expression 'missingParamsCount != 0' is always true. Nethermind.JsonRpc JsonRpcService.cs 127
if (missingParamsCount != 0)
{
bool incorrectParametersCount = missingParamsCount != 0; // <=
if (missingParamsCount > 0)
{
....
}
....
}
Similar errors can be found in some other places:
V3022 Expression 'dirpath == null' is always false. PosixHelper.cs(124) Voron
public static void EnsurePathExists(string file)
{
var dirpath = Path.GetDirectoryName(file);
List<string> dirsToCreate = new List<string>();
while (Directory.Exists(dirpath) == false)
{
dirsToCreate.Add(dirpath);
dirpath = Directory.GetParent(dirpath).ToString();
if (dirpath == null) // <=
break;
}
dirsToCreate.ForEach(x => Directory.CreateDirectory(x));
}
V3022 Expression '_continuationState.Count > 0' is always true. ManualBlittableJsonDocumentBuilder.cs(152) Sparrow
public void WriteObjectEnd()
{
....
if (_continuationState.Count > 1)
{
var outerState =
_continuationState.Count > 0 ? _continuationState.Pop() : currentState;
if (outerState.FirstWrite == -1)
outerState.FirstWrite = start;
_continuationState.Push(outerState);
}
....
}
V3022 Expression 'command != null' is always true. AsyncDocumentSession.Load.cs(175) Raven.Client
public partial class AsyncDocumentSession
{
....
private async Task LoadStartingWithInternal(....)
{
....
var command = operation.CreateRequest();
if (command != null) // <=
{
await RequestExecutor
.ExecuteAsync(command, Context, SessionInfo, token)
.ConfigureAwait(false);
if (stream != null)
Context.Write(stream, command.Result.Results.Parent);
else
operation.SetResult(command.Result);
}
....
}
....
}
internal class LoadStartingWithOperation
{
....
public GetDocumentsCommand CreateRequest()
{
_session.IncrementRequestCount();
if (Logger.IsInfoEnabled)
Logger.Info(....);
return new GetDocumentsCommand(....);
}
....
}
V3022 Expression 'GetCounterValueAndCheckIfShouldSkip(item.DocumentId, null, prop, out long value, out bool delete)' is always false. RavenEtlDocumentTransformer.cs(362) Raven.Server
private List<CounterOperation> GetCounterOperationsFor(RavenEtlItem item)
{
....
for (var i = 0; i < counters.Count; i++)
{
counters.GetPropertyByIndex(i, ref prop);
if (
GetCounterValueAndCheckIfShouldSkip(
item.DocumentId,
null,
prop,
out long value,
out bool delete
)
) continue;
....
}
....
}
private bool GetCounterValueAndCheckIfShouldSkip(
LazyStringValue docId,
string function,
BlittableJsonReaderObject.PropertyDetails prop,
out long value,
out bool delete
)
{
value = 0;
if (prop.Value is LazyStringValue)
{
delete = true;
}
else
{
delete = false;
value = CountersStorage.InternalGetCounterValue(
prop.Value as BlittableJsonReaderObject.RawBlob,
docId,
prop.Name
);
if (function != null)
{
using (var result = BehaviorsScript.Run(
Context,
Context,
function,
new object[] { docId, prop.Name }
))
{
if (result.BooleanValue != true)
return true;
}
}
}
return false;
}
V3022 Expression 'suspend.HasValue' is always true. RachisAdminHandler.cs(116) Raven.Server
public Task SuspendObserver()
{
if (ServerStore.IsLeader())
{
var suspend = GetBoolValueQueryString("value");
if (suspend.HasValue) // <=
{
Server.ServerStore.Observer.Suspended = suspend.Value;
}
NoContentStatus();
return Task.CompletedTask;
}
RedirectToLeader();
return Task.CompletedTask;
}
protected bool? GetBoolValueQueryString(string name, bool required = true)
{
var boolAsString = GetStringQueryString(name, required);
if (boolAsString == null)
return null;
if (bool.TryParse(boolAsString, out bool result) == false)
ThrowInvalidBoolean(name, boolAsString);
return result;
}
protected string GetStringQueryString(string name, bool required = true)
{
var val = HttpContext.Request.Query[name];
if (val.Count == 0 || string.IsNullOrWhiteSpace(val[0]))
{
if (required)
ThrowRequiredMember(name);
return null;
}
return val[0];
}
private static void ThrowRequiredMember(string name)
{
throw new ArgumentException(
$"Query string {name} is mandatory, but wasn't specified."
);
}
V3022 Expression 'me.Arguments.Count < 2 && me.Arguments.Count > 3' is always false. Probably the '||' operator should be used here. QueryMetadata.cs(861) Raven.Server
private OrderByField ExtractOrderByFromMethod(....)
{
....
if (me.Arguments.Count < 2 && me.Arguments.Count > 3)
throw new InvalidQueryException(....);
....
}
V3022 Expression is always true. Probably the '&&' operator should be used here. DeleteCertificateFromClusterCommand.cs(21) Raven.Server
public override void VerifyCanExecuteCommand(
ServerStore store, TransactionOperationContext context, bool isClusterAdmin
)
{
using (context.OpenReadTransaction())
{
var read = store.Cluster.GetCertificateByThumbprint(context, Name);
if (read == null)
return;
var definition = JsonDeserializationServer.CertificateDefinition(read);
if (
definition.SecurityClearance != SecurityClearance.ClusterAdmin || // <=
definition.SecurityClearance != SecurityClearance.ClusterNode // <=
)
return;
}
AssertClusterAdmin(isClusterAdmin);
}
V3022 Expression 'Active' is always true. SupportPowerManager.cs 206
public virtual void Tick()
{
....
Active = !Disabled && Instances.Any(i => !i.IsTraitPaused);
if (!Active)
return;
if (Active)
{
....
}
}
V3022 Expression 'highlightStart > 0' is always true. LabelWithHighlightWidget.cs 54
Pair<string, bool>[] MakeComponents(string text)
{
....
if (highlightStart > 0 && highlightEnd > highlightStart) // <=
{
if (highlightStart > 0) // <=
{
// Normal line segment before highlight
var lineNormal = line.Substring(0, highlightStart);
components.Add(Pair.New(lineNormal, false));
}
// Highlight line segment
var lineHighlight = line.Substring(
highlightStart + 1,
highlightEnd - highlightStart – 1
);
components.Add(Pair.New(lineHighlight, true));
line = line.Substring(highlightEnd + 1);
}
else
{
// Final normal line segment
components.Add(Pair.New(line, false));
break;
}
....
}
V3022 Expression '!order.Queued && currentTransform.NextActivity != null' is always false. TransformsIntoTransforms.cs 44
void IResolveOrder.ResolveOrder(Actor self, Order order)
{
....
if (!order.Queued || currentTransform == null)
return;
if (!order.Queued && currentTransform.NextActivity != null)
currentTransform.NextActivity.Cancel(self);
....
}
V3022 Expression 'lobbyInfo == null' is always false. LobbyCommands.cs 851
public class LobbyCommands : ....
{
....
static bool SyncLobby(....)
{
if (!client.IsAdmin)
{
server.SendOrderTo(conn, "Message", "Only the host can set lobby info");
return true;
}
var lobbyInfo = Session.Deserialize(s);
if (lobbyInfo == null) // <=
{
server.SendOrderTo(conn, "Message", "Invalid Lobby Info Sent");
return true;
}
server.LobbyInfo = lobbyInfo;
server.SyncLobbyInfo();
return true;
}
....
}
public class Session
{
....
public static Session Deserialize(string data)
{
try
{
var session = new Session();
....
return session;
}
catch (YamlException)
{
throw new YamlException(....);
}
catch (InvalidOperationException)
{
throw new YamlException(....);
}
}
....
}
V3022 Expression 'frameSlider != null' is always true. AssetBrowserLogic.cs 128
public class AssetBrowserLogic : ChromeLogic
{
....
public AssetBrowserLogic(....)
{
....
frameSlider = panel.Get<SliderWidget>("FRAME_SLIDER");
if (frameSlider != null)
{
....
}
....
}
....
}
public abstract class Widget
{
....
public T Get<T>(string id) where T : Widget
{
var t = GetOrNull<T>(id);
if (t == null)
throw new InvalidOperationException(
"Widget {0} has no child {1} of type {2}".F(Id, id, typeof(T).Name));
return t;
}
....
}
V3022 Expression 'namespaceUri != null' is always true. OpenXmlElement.cs 497
public OpenXmlAttribute GetAttribute(string localName, string namespaceUri)
{
....
if (namespaceUri == null)
{
// treat null string as empty.
namespaceUri = string.Empty;
}
....
if (HasAttributes)
{
if (namespaceUri != null) // <=
{
....
}
....
}
....
}
V3022 Expression 'Complete()' is always false. ParticleCollection.cs 243
private bool IsComplete => Current is null ||
Current == _collection._element.FirstChild;
public bool MoveNext()
{
....
if (IsComplete)
{
return Complete();
}
if (....)
{
return Complete();
}
return IsComplete ? Complete() : true;
}
V3022 Expression '_elementStack.Count > 0' is always true. OpenXmlDomReader.cs 501
private readonly Stack<OpenXmlElement> _elementStack;
private bool MoveToNextSibling()
{
....
if (_elementStack.Count == 0)
{
_elementState = ElementState.EOF;
return false;
}
....
if (_elementStack.Count > 0) // <=
{
_elementState = ElementState.End;
}
else
{
// no more element, EOF
_elementState = ElementState.EOF;
}
....
}
V3022 Expression 'rootElement == null' is always false. OpenXmlPartReader.cs 746
private static OpenXmlElement CreateElement(string namespaceUri, string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(....);
}
if (NamespaceIdMap.TryGetNamespaceId(namespaceUri, out byte nsId)
&& ElementLookup.Parts.Create(nsId, name) is OpenXmlElement element)
{
return element;
}
return new OpenXmlUnknownElement();
}
private bool ReadRoot()
{
....
var rootElement = CreateElement(....);
if (rootElement == null) // <=
{
throw new InvalidDataException(....);
}
....
}
V3022 Expression 'nameProvider' is always not null. The operator '?.' is excessive. OpenXmlSimpleTypeExtensions.cs 50
public static XmlQualifiedName GetSimpleTypeQualifiedName(....)
{
foreach (var validator in validators)
{
if (validator is INameProvider nameProvider &&
nameProvider?.QName is XmlQualifiedName qname) // <=
{
return qname;
}
}
return type.GetSimpleTypeQualifiedName();
}
V3022 Expression 'extension == ".xlsx" || extension == ".xlsm"' is always false. PresentationDocument.cs 246
public static PresentationDocument CreateFromTemplate(string path)
{
....
string extension = Path.GetExtension(path);
if (extension != ".pptx" && extension != ".pptm" &&
extension != ".potx" && extension != ".potm")
{
throw new ArgumentException("...." + path, nameof(path));
}
using (PresentationDocument template = PresentationDocument.Open(....)
{
PresentationDocument document = (PresentationDocument)template.Clone();
if (extension == ".xlsx" || extension == ".xlsm")
{
return document;
}
....
}
....
}
V3022 Expression 'OpenSettings.MarkupCompatibilityProcessSettings == null' is always false. OpenXmlPackage.cs 661
public MarkupCompatibilityProcessSettings MarkupCompatibilityProcessSettings
{
get
{
if (_mcSettings is null)
{
_mcSettings = new MarkupCompatibilityProcessSettings(....);
}
return _mcSettings;
}
set
{
_mcSettings = value;
}
}
public MarkupCompatibilityProcessSettings MarkupCompatibilityProcessSettings
{
get
{
if (OpenSettings.MarkupCompatibilityProcessSettings == null) // <=
{
return new MarkupCompatibilityProcessSettings(....);
}
else
{
return OpenSettings.MarkupCompatibilityProcessSettings;
}
}
}
V3022 Expression '_random.Next(0, 1) == 0' is always true. RandomValueGenerator.cs 142
public virtual DateTime NextDate(....)
{
....
// both are valid dates, so chose one randomly
if ( IsWithinRange(nextDayOfWeek, minDateTime, maxDateTime)
&& IsWithinRange(previousDayOfWeek, minDateTime, maxDateTime))
{
return _random.Next(0, 1) == 0 // <=
? previousDayOfWeek
: nextDayOfWeek;
}
....
}
Similar errors can be found in some other places:
V3022 Expression 'string.IsNullOrEmpty("password")' is always false. SmtpSettings.cs 104
public void SetCredentials(string userName, string password, string domain)
{
if (string.IsNullOrEmpty(userName))
{
throw new ArgumentException("Empty user name.", "userName");
}
if (string.IsNullOrEmpty("password"))
{
throw new ArgumentException("Empty password.", "password");
}
CredentialsUserName = userName;
CredentialsUserPassword = password;
CredentialsDomain = domain;
}
V3022 Expression 'String.IsNullOrEmpty("name")' is always false. SendInterceptorSkeleton.cs 36
public SendInterceptorSkeleton(
string name, // <=
....,
Func<NotifyRequest, InterceptorPlace, bool> sendInterceptor)
{
if (String.IsNullOrEmpty("name")) // <=
throw new ArgumentNullException("name");
if (String.IsNullOrEmpty("sendInterceptor"))
throw new ArgumentNullException("sendInterceptor");
method = sendInterceptor;
Name = name;
PreventPlace = preventPlace;
Lifetime = lifetime;
}
Similar errors can be found in some other places:
V3022 Expression 'id < 0' is always false. Unsigned type value is always >= 0. UserFolderEngine.cs 173
public MailUserFolderData Update(uint id, string name, uint? parentId = null)
{
if (id < 0)
throw new ArgumentException("id");
....
}
V3022 Expression 'portalUser.BirthDate.ToString()' is always not null. The operator '??' is excessive. LdapUserManager.cs 436
public DateTime? BirthDate { get; set; }
private bool NeedUpdateUser(UserInfo portalUser, UserInfo ldapUser)
{
....
_log.DebugFormat("NeedUpdateUser by BirthDate -> portal: '{0}', ldap: '{1}'",
portalUser.BirthDate.ToString() ?? "NULL", // <=
ldapUser.BirthDate.ToString() ?? "NULL"); // <=
needUpdate = true;
....
}
Similar errors can be found in some other places:
V3022 Expression is always true. Probably the '&&' operator should be used here. ListItemHistoryDao.cs 140
public virtual int CreateItem(ListItemHistory item)
{
if (item.EntityType != EntityType.Opportunity || // <=
item.EntityType != EntityType.Contact)
throw new ArgumentException();
if (item.EntityType == EntityType.Opportunity &&
(DaoFactory.DealDao.GetByID(item.EntityID) == null ||
DaoFactory.DealMilestoneDao.GetByID(item.StatusID) == null))
throw new ArgumentException();
if (item.EntityType == EntityType.Contact &&
(DaoFactory.ContactDao.GetByID(item.EntityID) == null ||
DaoFactory.ListItemDao.GetByID(item.StatusID) == null))
throw new ArgumentException();
....
}
V3022 Expression 'pt != null' is always true. ICSharpCode.Decompiler FunctionPointerType.cs 168
public override IType VisitChildren(TypeVisitor visitor)
{
....
IType[] pt = (r != ReturnType) ? new IType[ParameterTypes.Length] : null;
....
if (pt == null)
return this;
else
return new FunctionPointerType(
module, CallingConvention, CustomCallingConventions,
r, ReturnIsRefReadOnly,
pt != null ? pt.ToImmutableArray() : ParameterTypes, // <=
ParameterReferenceKinds);
}
V3022 Expression 'settings.LoadInMemory' is always true. ICSharpCode.Decompiler CSharpDecompiler.cs 394
static PEFile LoadPEFile(string fileName, DecompilerSettings settings)
{
settings.LoadInMemory = true;
return new PEFile(
fileName,
new FileStream(fileName, FileMode.Open, FileAccess.Read),
streamOptions: settings.LoadInMemory ? // <=
PEStreamOptions.PrefetchEntireImage : PEStreamOptions.Default,
metadataOptions: settings.ApplyWindowsRuntimeProjections ?
MetadataReaderOptions.ApplyWindowsRuntimeProjections :
MetadataReaderOptions.None
);
}
public bool LoadInMemory {
get { return loadInMemory; }
set {
if (loadInMemory != value)
{
loadInMemory = value;
OnPropertyChanged();
}
}
}
V3022 Expression 'ta' is always not null. The operator '??' is excessive. ICSharpCode.Decompiler ParameterizedType.cs 354
public IType VisitChildren(TypeVisitor visitor)
{
....
if (ta == null)
return this;
else
return new ParameterizedType(g, ta ?? typeArguments); // <=
}
V3022 Expression 'negatedOp == BinaryOperatorType.Any' is always true. ICSharpCode.Decompiler CSharpUtil.cs 79
static Expression InvertConditionInternal(Expression condition)
{
var bOp = (BinaryOperatorExpression)condition;
if ( (bOp.Operator == BinaryOperatorType.ConditionalAnd)
|| (bOp.Operator == BinaryOperatorType.ConditionalOr))
{
....
}
else if ( (bOp.Operator == BinaryOperatorType.Equality)
|| (bOp.Operator == BinaryOperatorType.InEquality)
|| (bOp.Operator == BinaryOperatorType.GreaterThan)
|| (bOp.Operator == BinaryOperatorType.GreaterThanOrEqual)
|| (bOp.Operator == BinaryOperatorType.LessThan)
|| (bOp.Operator == BinaryOperatorType.LessThanOrEqual))
{
....
}
else
{
var negatedOp = NegateRelationalOperator(bOp.Operator);
if (negatedOp == BinaryOperatorType.Any) // <=
return new UnaryOperatorExpression(....);
bOp = (BinaryOperatorExpression)bOp.Clone();
bOp.Operator = negatedOp;
return bOp;
}
}
public static BinaryOperatorType NegateRelationalOperator(BinaryOperatorType op)
{
switch (op)
{
case BinaryOperatorType.GreaterThan:
return BinaryOperatorType.LessThanOrEqual;
case BinaryOperatorType.GreaterThanOrEqual:
return BinaryOperatorType.LessThan;
case BinaryOperatorType.Equality:
return BinaryOperatorType.InEquality;
case BinaryOperatorType.InEquality:
return BinaryOperatorType.Equality;
case BinaryOperatorType.LessThan:
return BinaryOperatorType.GreaterThanOrEqual;
case BinaryOperatorType.LessThanOrEqual:
return BinaryOperatorType.GreaterThan;
case BinaryOperatorType.ConditionalOr:
return BinaryOperatorType.ConditionalAnd;
case BinaryOperatorType.ConditionalAnd:
return BinaryOperatorType.ConditionalOr;
}
return BinaryOperatorType.Any;
}
V3022 Expression 'setTargetAsPrincipal.Value' is always true. EFCore InternalEntityTypeBuilder.cs 2747
private InternalForeignKeyBuilder? HasRelationship(....,
bool? setTargetAsPrincipal,
....)
{
....
var navigationProperty = navigationToTarget?.MemberInfo;
if (setTargetAsPrincipal == false || ....) // <=
{
return ....
}
if ( configurationSource == ConfigurationSource.Explicit
&& setTargetAsPrincipal.HasValue) // <=
{
if (setTargetAsPrincipal.Value) // <=
{
....
throw new InvalidOperationException(....); // Exception 1
}
else
{
....
throw new InvalidOperationException(....); //Exception 2
}
}
....
}
V3022 Expression 'columnName == null' is always false. EFCore.Relational RelationalModel.cs 244
private static void AddDefaultMappings(....)
{
....
foreach (var property in entityType.GetProperties())
{
var columnName = property.GetColumnBaseName();
if (columnName == null)
{
continue;
}
....
}
....
}
public static string GetColumnBaseName(....)
=> (string?)property.FindAnnotation(....)?.Value
?? property.GetDefaultColumnBaseName();
public static string GetDefaultColumnBaseName(....)
=> Uniquifier.Truncate(property.Name,
property.DeclaringEntityType
.Model
.GetMaxIdentifierLength());
public static string Truncate(....)
{
....
var builder = new StringBuilder();
....
return builder.ToString();
}