NDpend CQLinq to signal code rule - ndepend

I'm a new customer of NDpend, so please excuse me my question is stupid...I wish to have a rule that shows me when I've got a constructor has a particular line of code. Consider that example
public StatusViewModel
{
this.userService = ServiceLocator.Default.ResolveType<IUserService>();
}
Is it possible? considering that I have it to be defined in the Constructor and need to have a reference to ServiceLocator.Default.ResolveType
Thanks

If you want to enforce that the constructor is accessing
ServiceLocator.Default.ResolveType<IUserService>()
The rule should look like
warnif count > 0
from m in Application.Methods
where m.IsConstructor
&& !m.IsUsing("Microsoft.Practices.ServiceLocation.ServiceLocator.get_Default()")
&& !m.IsUsing("Microsoft.Practices.ServiceLocation.ServiceLocator.ResolveType<T>()")
select m

Related

Finding partial attribute value in Katalon

Trying to find a partial attribute value. Full value is no problem.
I have h1 class="a b c" and want to find out, whether this h1 has a as a class attribute.
Trying WebUI.verifyMatch(findTestObject('mytest/mytest-h1'),'a', 'a.*', false, FailureHandling.STOP_ON_FAILURE) and fails on finding.
Also answered via this Katalon Forum post (Apologies if the link is broken, in the future).
As per Mate Mrše's answer you can also try the following:
def attribute = WebUI.getAttribute(findTestObject('mytest/mytest-h1'), 'class')
boolean doesAttributeExist = attribute.contains('a')
if (!doesAttributeExist) {
// Add some logic/interaction
}
Since you added FailureHandling.STOP_ON_FAILURE the test will fail regardless of the condition.
Should you want the test to continue rather use FailureHandling.OPTIONAL
Try this:
def attribute = WebUI.getAttribute(findTestObject('mytest/mytest-h1'), 'class')
assert attribute.contains('a ')
Alternatively, create an object using the CSS class as the locator and verify the element exists:
assert WebUI.verifyElementClickable(findTestObject('mytest/mytest-h1-a')) == true

Codeeffect Rule Engine - How to define rules to check length of string

I have to define a rule like <> length is < 5 or >5 AND not equal to 'N/A'.
I am not able to get Len() function in the list of operators for the string data type.
Please suggest if any field level attributes needs to define.
In your source class define a method like this:
public int Length(string str)
{
return string.IsNullOrEmpty(str) ? 0 : str.Length;
}
Then run your project, open the rule editor and create your rule like this:
Check if YourString has any value and Length(YourString) is greater than [5]
Details on in-rule methods can be found here

Activate Rules on child objects in Drools

I have two Facts named OptionalCover and OptionalPremiumComponent and OptionalCover has a reference of OptionalPremiumComponent in it. So this is what I'm inserting into working memory.
private static OptionalCover getOptionalCover(Double sumAssured, Double premiumRate) {
OptionalPremiumComponent premiumComponent = new OptionalPremiumComponent();
premiumComponent.setSumAssured(sumAssured);
premiumComponent.setPremiumRate(premiumRate);
OptionalCover optionalCover = new OptionalCover();
optionalCover.setPremiumComponent(premiumComponent);
return optionalCover;
}
kieSession.insert(getOptionalCover(1000000.0, 0.02));
I have created the following rule in drools
import java.lang.Number;
rule "OptionalCoverCalculation"
dialect "java"
when
opc : OptionalPremiumComponent( sumAssured > 1I && sumAssured != null && premiumRate != null && premiumRate > 0.0 )
then
opc.setPremium( opc.getSumAssured() * 0.001 * opc.getPremiumRate() );
System.out.println("Here");
end
The problem is, the above rule is not being fired when I insert the parent object. Do I have to do anything else to enable this behaviour? Is it supported?
Thank you.
The Drools engine has no way of telling that your Cover contains a Component. (Well, it has, as it might use reflection - but where should it stop?)
So, you'll have to insert the OptionalPremiumComponent as well.
To reduce the amount of clutter in your code you might write a sorts of clever methods so that you can insert Cover and Component with a single call.
For instance, if you have many similar "contains" relationships and if you want to reason freely, you might implement s.th. like
interface FactContainer {
List<Object> factChildren(); -- return all contained fact objects
-- OR --
void insertAll( KieSession ks );
}
where factChildren would return a List with the premiumComponent or an empty List, or, alternatively, one method insertAll that handles everything internally.

Refining CQLinq rule for nested visibility

We have NDepend 5.4.1 and we want to alter the queries for field/type/method that could have lower visibility. We want the query to take the scope of the enclosing class into account when deciding whether to consider it a violation.
For example,
internal class X
{
public int A;
public void B() { }
public class C
{
// …
}
}
We don’t want A, B or C to generate a violation saying that any of them should be made internal. If class X was public, on the other hand, and none of A, B and C is used outside the assembly, then they should all generate violations.
To accomplish this, I added the following line to the queries:
// consider visibility of enclosing class
f.ParentType.Visibility < f.OptimalVisibility
So for fields, the new query looks like:
// <Name>Fields that could have a lower visibility</Name>
warnif count > 0 from f in JustMyCode.Fields where
f.Visibility != f.OptimalVisibility &&
!f.HasAttribute("NDepend.Attributes.CannotDecreaseVisibilityAttribute".AllowNoMatch()) &&
!f.HasAttribute("NDepend.Attributes.IsNotDeadCodeAttribute".AllowNoMatch()) &&
// consider visibility of enclosing class
f.ParentType.Visibility < f.OptimalVisibility
select new { f,
f.Visibility ,
CouldBeDeclared = f.OptimalVisibility,
f.MethodsUsingMe }
I altered the query for method visibility and type visibility in a similar manner, except for types I make sure there is an enclosing parent type:
(t.ParentType == null || t.ParentType.Visibility < t.OptimalVisibility)
At first glance and after running some tests, this seems to be doing the right thing. My question is whether this will generate any false positives or miss any violations, since I am not sure whether the enum visibility orderings (comparisons) will do the right thing in all cases.
Here is the NDepend.CodeModel.Visibility enumeration declaration:
public enum Visibility {
None = 0,
Public = 1,
ProtectedAndInternal = 2,
ProtectedOrInternal = 3,
Internal = 4,
Protected = 5,
Private = 6
}
Hence x.ParentType.Visibility < x.OptimalVisibility means x parent type visibility is strictly less restrictive than x optimal visibility.
Notice that Protected is ordered as more restrictive than Internal which is not true neither Internal is more restrictive than Protected. So we had to provide an arbitrary ordering between these two visibility level.
Notice also that a method/field/nested type can be declared in a nested type (recursive) so to be correct we'd need to gather all outter types visibility.
These two facts make me thing that we could construct edge cases where your rule would return false positive, but after tinkering a bit I didn't succeed so.
What we advice is to look at your code base(s) how your custom rules behave to see if they should be modified. If it is fine, then consider it is fine until you eventually find a false positive.
There is a long related debate on the Eric Lippert blog about if a member of an internal type should be declared public or internal. There are solid arguments on both side, and the way our code rule is written favor the side it should be declared as internal, and your change favor the side it should be declared as public.

How to bind parameters in replaced expression nodes in Entity Framework on the fly

I'm trying to replace a function call like (simplified) Utility.GetString(MyEntity.SomePropertyWithRelatedEntity)=="abc" with an expression visitor into something like p => p.SubRelatedEntities.FirstOrDefault(sre => sre.SomeFlag==true).SomePropertyWithRelatedEntity.
It means, the datamodel goes like:
MyEntity -> RelatedEntity -> SubRelatedEntity
I'm trying to return a string value from the SubRelatedEntity, based on some rules in the RelatedEntity, so I don't have to re-write / copy/paste the whole filtering rules in every usage; that's why I put inside a "call-signature", so my expression visitor can identify it and replace the fake-call to Utility.GetString to some complicated lambda expressions.
My expression visitor contains something like:
public override Expression Visit(Expression node)
{
if (node == null)
return null;
Expression result = null;
if (node.NodeType == ExpressionType.Call)
{
MethodCallExpression mce = node as MethodCallExpression;
if (mce.Method.DeclaringType == typeof(Utility) && mce.Method.Name == "GetString")
{
Expression<Func<RelatedEntity, string>> exp = re => re.SubRelatedEntities.FirstOrDefault(sre => sre.SomeFlag == true).SomeStringValue;
result = exp.Body;
}
else
result = base.Visit(node);
}
else
result = base.Visit(node);
return result;
}
Now, the problem is, the "sre" parameter is not bound when called the injected lambda expression. After much research, I see the lambda parameters should be replaced with another expression visitor, specifically searching for the new parameters and replacing them with the old ones. In my situation, however, I don't have an "old parameter" - I have the expression MyEntity.SomePropertyWithRelatedEntity (e.g. an property filled with the related entities) which I need to insert somehow in the generated lambda.
I hope my problem is understandable. Thank you for any insights!
After getting no answers for long time and trying hard to find a solution, I've solved it at the end :o)! It goes like this:
The newly injected lambda expression gets an ParameterExpression - well, this is a 'helper', used when directly calling the lambda, what I don't want (hence, 'parameter not bound' exception when ToEnumerable is called). So, the clue is to make a specialized ExpressionVisitor, which replaces this helper with the original expression, which is of course available in the Arguments[] for the method call, which I try to replace.
Works like a charm, like this you can reuse the same LINQ expressions, something like reusable sub-queries, instead of writing all the same LINQ stuff all time. Notice as well, that expression calling a method is not allowed in EF, in Linq2Sql it worked. Also, all the proposed web articles only replace the parameter instances, when constructing/merging more LINQ expressions together - here, I needed to replace a parameter with an faked-method-call argument, e.g. the method should not be called, it only stands for a code-marker, where I need to put my LINQ sub-query.
Hope this helps somebody, at the end it's pretty simple and logical, when one knows how the expression trees are constructed ;-).
Bye,
Andrej