Resharper Search with pattern method call - c#

I want to replace this part of code using "Search with pattern...":
public bool IsDbObjectsOK()
{
var result = 0;
result = usp_IsDbObjectsOK();
if (result == 0)
return true;
return false;
}
public bool UnlockWindow()
{
var result = 0;
result = usp_UnlockWindow();
if (result == 0)
return true;
return false;
}
Replace with:
public bool IsDbObjectsOK()
{
return usp_IsDbObjectsOK() == 0;
}
public bool UnlockWindow()
{
return usp_UnlockWindow() == 0;
}
I tried to use
var $result$ = 0;
$result$ = $usp_IsDbObjectsOK$();
if ($result$ == 0)
return true;
return false;
This doesn't work, because the method call isn't found in any of the code that needs to be replaced.
How to do this?

You need to make sure that you use the correct placeholder type when you set up the search.
Here, result should be an Identifier Placeholder and usp_IsDbObjectsOK should be an Expression Placeholder. When I do that, the replace works as you'd expect.

Related

Find an identical function signature with different name

Given an object and an instance method, I want to get a method that has the exact same signature but with a different, known name. That includes parameter list, generic parameters, possibly attributes if they're a part of the signature. How can I do that?
I know GetMethod() exists but I couldn't figure out which overload covers all the different possible signature variations.
Something like this may work in some cases:
public static bool HasSameSignature(MethodInfo m1, MethodInfo m2)
{
if (m1.GetGenericArguments().Length != m2.GetGenericArguments().Length)
return false;
var args1 = m1.GetParameters();
var args2 = m2.GetParameters();
if (args1.Length != args2.Length)
return false;
for (var idx = 0; idx < args1.Length; idx++)
{
if (!AreEquivalentTypes(args1[idx].ParameterType, args2[idx].ParameterType))
return false;
}
return true;
}
static bool AreEquivalentTypes(Type t1, Type t2)
{
if (t1 == null || t2 == null)
return false;
if (t1 == t2)
return true;
if (t1.DeclaringMethod != null && t2.DeclaringMethod != null && t1.GenericParameterPosition == t2.GenericParameterPosition)
return true;
if (AreEquivalentTypes(t1.GetElementType(), t2.GetElementType()))
return true;
if (t1.IsGenericType && t2.IsGenericType && t1.GetGenericTypeDefinition() == t2.GetGenericTypeDefinition())
{
var ta1 = t1.GenericTypeArguments;
var ta2 = t2.GenericTypeArguments;
for (var idx = 0; idx < ta1.Length; idx++)
{
if (!AreEquivalentTypes(ta1[idx], ta2[idx]))
return false;
}
return true;
}
return false;
}
So given your one method, you can do .GetMethods() on the type in question, and find the one whose name is correct, and for which HasSameSignature(...) on it and your one given method is true.
Type givenType = ...;
MethodInfo givenMethod = ...;
string givenDifferentName = ...;
var answer = givenType.GetMethods()
.SingleOrDefault(m => m.Name == givenDifferentName && HasSameSignature(m, givenMethod));

Evaluating boolean expression in C#

I have written the code below to evaluate a boolean expression. The expression is coded in the form of objects.
It's one of those moments when I look at the code and think: I'm sure there's a better way to code that, using less boolean variables but can't see the right way to go. Any help? Unit tests have been written and are passing for a variety of inputs.
if (tree == null || !tree.IsActive || tree.FilterNodes == null)
{
return false;
}
var result = false;
foreach (var filter in tree.FilterNodes.Where(a => a.IsActive && a.ConditionNodes != null))
{
var tempBool = false;
foreach (var condition in filter.ConditionNodes.Where(a => a.IsActive))
{
if (!string.IsNullOrWhiteSpace(condition.FieldName) && values.ContainsKey(condition.FieldName))
{
var value = values[condition.FieldName];
if (filter.LogicalOperator == LogicalOperator.Or && ApplyCondition(condition.ConditionOperator, value, condition.FieldValue))
{
tempBool = true;
break;
}
else if (filter.LogicalOperator == LogicalOperator.And)
{
tempBool = ApplyCondition(condition.ConditionOperator, value, condition.FieldValue);
if (!tempBool)
{
break;
}
}
else
{
tempBool = false;
}
}
else if (!string.IsNullOrWhiteSpace(condition.FieldName) && filter.LogicalOperator == LogicalOperator.And)
{
tempBool = false;
}
}
result = tempBool;
if (!result)
{
break;
}
}
return result;
You could set tempBool = false first thing in the loop and leave out the else and last else if:
foreach (var condition in filter.ConditionNodes.Where(a => a.IsActive))
{
tempBool = false;
if (!string.IsNullOrWhiteSpace(condition.FieldName) && values.ContainsKey(condition.FieldName))
{
var value = values[condition.FieldName];
if (filter.LogicalOperator == LogicalOperator.Or && ApplyCondition(condition.ConditionOperator, value, condition.FieldValue))
{
tempBool = true;
break;
}
else if (filter.LogicalOperator == LogicalOperator.And)
{
tempBool = ApplyCondition(condition.ConditionOperator, value, condition.FieldValue);
if (!tempBool)
{
break;
}
}
}
}
EDIT
It gets even simpler:
foreach (var condition in filter.ConditionNodes.Where(a => a.IsActive))
{
tempBool = false;
if (!string.IsNullOrWhiteSpace(condition.FieldName) && values.ContainsKey(condition.FieldName))
{
var value = values[condition.FieldName];
tempBool == ApplyCondition(condition.ConditionOperator, value, condition.FieldValue);
if ((filter.LogicalOperator == LogicalOperator.And && !tempBool) || (filter.LogicalOperator == LogicalOperator.Or && tempBool))
{
break;
}
}
}
In the if you need ApplyCondition to be true and then set tempBool to true (also the result of ApplyCondition). In the else if you set tempBoolto the result of ApplyCondition. That means you can set tempBoolto the result of ApplyConditionin the first place. Now you just need to decide if you need to break.
Taking a more o-o approach, I think your operators need to be defined by classes that inherit from a base class. The base class would have an abstract Evaluate method that your operators implement. You can then use o-o polymorphism to evaluate your operators without worrying about the internal details. Effectively you have the beginnings of a simple interpreter.
A more formal way to code a boolean interpreter is considering a boolean expression as generated by a formal grammar and writing a parser and an interpreter for it. The interpreter could be implemented as an abstract syntax tree.
I made an open source library to achieve this, if you want you can take a look on GitHub.

c# List with Arithmetic Operations

I want realize arithmetic operations with my list, in this case:
Column "width" * Column "height" should re-Write the Column "Partial".
I have tried do a loop but It is not working.
I put a breakPoint at the row:
_Area[i].Partial = _Area[i].width * _Area[i].height;
And the debug never stop them I can think this line is not been readed.
This is my Collection View Model:
public class CollectionVM_Area : BindableBase
{
private Values_Area _Area = new Values_Area();
public Values_Area Area
{
get { return _Area; }
set { SetProperty(ref _Area, value); }
}
public CollectionVM_Area()
{
_Area.Add(new Area()
{
width=10,
height=11,
});
_Area.Add(new Area()
{
width=5,
height=5,
Partial=1,
});
bool NeedPartial = false;
int i = 0;
while (NeedPartial = false && i < _Area.Count)
{
if (_Area[i].Partida == true)
{
NeedPartial = true;
}
else
{
i++;
}
}
if (NeedPartial==true)
{
_Area[i].Partial = _Area[i].width * _Area[i].height;
NeedPartial = false;
}
else
{
NeedPartial = true;
}
}
}
My Project is a UWP but I think is no different in with a windows forms in lists, any help is appreciated.
You have two mistalkes in your code. First your while-loop makes an assignement instead of a comparisson (= towards ==). Thus the first term within your while-condition allways evaluates to false. Secondly your calculation is located outside the loop causing the NeedPartial-value to be set but not never be read which I doubt is what you want.
Write this therefor:
bool NeedPartial = false;
int i = 0;
while (NeedPartial == false && i < _Area.Count) // or even simpler: while (!NeedPartial ...)
{
if (_Area[i].Partida == true) // or simply: if (_Area[i].Partida) { ... }
{
NeedPartial = true;
}
else
{
i++;
}
if (NeedPartial==true) // if (NeedPartial) ...
{
_Area[i].Partial = _Area[i].width * _Area[i].height;
NeedPartial = false;
}
else
{
NeedPartial = true;
}
}
Edit: Answered.
The Correct Loop is:
bool NeedPartial = false;
int i = 0;
while (!NeedPartial && i < _Area.Count)
{
if (_Area[i].Partida)
{
NeedPartial = true;
}
else
{
i++;
}
if (NeedPartial)
{
_Area[i].Partial = _Area[i].width * _Area[i].height;
NeedPartial = false;
i++;
}
else
{
NeedPartial = true;
}
}
Thanks to HimBromBeere for your help.

Check whenever string is valid path

I'm trying to use Uri.IsWellFormedUriString but it doesn't work, and question is - why:
class Program
{
static void Main()
{
Console.WriteLine(IsWellFormed(#"C:\Windows"));
Console.WriteLine(IsWellFormed(#"C:\\:\\//Windows32"));
}
public static bool IsWellFormed(string path)
{
string uriString = "file:///" + path;
string wellFormed = uriString.Replace('\\', '/');
return Uri.IsWellFormedUriString(wellFormed, UriKind.Absolute);
}
}
expected true false output but it returns true in both cases. And I'm really confused a bit.
Here is an approach without try/catch, though it may not be optimal:
public static bool IsWellFormed(string path)
{
string path = "C:\\windows\\:ppz";
var isRooted = Path.IsPathRooted(path);
var root = Path.GetPathRoot(path);
var list = path.Split(new char[] {Path.DirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < list.Length; i ++)
{
if(i == 0 && isRooted && s[i]+"\\" == root) continue;
if (s[i].Intersect(Path.GetInvalidPathChars()).Count() != 0)
return false;
if (s[i].Intersect(Path.GetInvalidFileNameChars()).Count() != 0)
return false;
}
return true;
}
You can play with your values and see if this fits your task. You can also customize your own lists for invalid chars.

How to fail test if UI element is not found?

I use a method that searches an UI element:
public static bool findtopuielm(string uiitemname)
{
bool res = false;
try
{
AutomationElement desktopelem = AutomationElement.RootElement;
if (desktopelem != null)
{
Condition condition = new PropertyCondition(AutomationElement.NameProperty, uiitemname);
AutomationElement appElement = desktopelem.FindFirst(TreeScope.Descendants, condition);
if (appElement != null)
{
res = true;
}
}
return res;
}
catch (Win32Exception)
{
// To do: error handling
return false;
}
}
This method is called by another one that waits an element until it appears on desktop.
public static void waittopuielm(string appname, int retries = 1000, int retrytimeout = 1000)
{
for (int i = 1; i <= retries; i++)
{
if (findtopuielm(appname))
break;
Thread.Sleep(retrytimeout);
}
}
The thing is that when I call the last function for example:
waittopuielm("Test");
It always returns true even if the element is not found, in that case I want the test to fail.
Any suggestion would be welcomed.
It looks like your waittopuielem method returns void - did you mean to post something like this version, which returns a bool?
public static bool waittopuielm(string appname, int retries = 1000, int retrytimeout = 1000)
{
bool foundMatch = false;
for (int i = 1; i <= retries; i++)
{
if (findtopuielm(appname))
{
foundMatch = true;
break;
}
else
{
Console.WriteLine("No match found, sleeping...");
}
Thread.Sleep(retrytimeout);
}
return foundMatch;
}
Other than that, your code seems to work as expected for me.
One suggestion: In your findtopuielm method, change the TreeScope value in the desktop element search from TreeScope.Descendants to TreeScope.Children:
AutomationElement appElement = desktopelem.FindFirst(TreeScope.Children, condition);
TreeScope.Descendants is probably doing more recursive searching than you want - all children of the desktop element will be searched, as well as every child of those elements (i.e. buttons, edit controls, and so forth).
So, the chances of finding the wrong element when searching for a relatively common string are high, unless you combine your NameProperty PropertyCondition with other properties in an AndCondition to narrow your search.

Categories

Resources