Inherited method dependencies using NDepend - ndepend

The class browser of NDepend doesn't seem to have an option for revealing inherited methods.
We have a scenario where we have thousands of singly-rooted Model objects that descend from RootModel, for instance. Only RootModel defines Save(). How does one form a query for finding all instances where SampleModel (:RootModel) invokes Save()?
SELECT METHODS WHERE IsUsing "SampleModel.Save()" ORDER BY DepthOfIsUsing
...is rejected: Not a valid assembly, namespace, typ, method or field name.
This seems to be the best approximation but is not exact:
SELECT METHODS WHERE IsUsing "SampleModel" AND IsUsing "RootModel.Save()" ORDER BY DepthOfIsUsing
This seems like a pretty heavy limitation, no? What's the workaround?

From the static point of view of NDepend the class SampleModel doesn't declare a Save() method. This is why the first query doesn't compile.
The second query is indeed the good thing to do in your case. To get it right, you can use the Code Query on LINQ (CQLinq capabilities) and rewrite it this way:
from m in Application.Types.Where(t => t.DeriveFrom("MyNamespace.RootModel"))
.ChildMethods()
where m.IsUsing("MyNamespace.RootModel.Save()")
select new { m, m.ParentType }

Related

Extend DbFunctions EF6

Is it possible to extend DbFunctions, assuming you are using existing DbFunctions as helper methods. I am essentially rewriting the exact same line of sql code again and again. Are there any alternatives?
Update:
Here is an example of what I'm trying to do, but I want to define my own Add function, not use one that I've constructed in my database
var locations = context.Data.Where(e => Functions.Add(e.X, e.Y) >= 10)
Yes of course you can extend it. Class DbFunctions only contains code that helps the provider of your IQueryable to translate the expression into SQL.
An IEnumerable holds all code to create an Enumerator for you upon request. The Enumerator represents a sequence. Upon request it will give you the first element of the sequence, and once you've got an element it will give you the next one (provided there is one).
An IQueryable works differently. Usually an IQueryable is not meant to be performed by your process, but for instance a database, a remote web site, a CSV file controller, etc.
That is why you need to tell an object that produces IQueryables for which process it must create the IQueryable. In case of Entity Framework you inform the DbContext which database to use.
The IQueryable object holds an Expression to be performed and a Provider. The provider knows which process will perform the query. It also knows how to translate the Expression into the format that the other process understands. Quite often this will be SQL.
If you investigate the remarks section of the MSDN descriptions of IQueryable functions like Where, GroupBy, Select, you'll see that most of these functions will only change the Expression.
As long as you don't ask for the Enumerator, usually implicitly by asking for the first element of a sequence, like in ToList, foreach, FirstOrDefault, etc, the Provider has nothing to do.
But once you ask for the Enumerator, the Expression will be translated by the Provider, who will use the translation to query the data from the other process and create an Enumerator object that can give you the first element of the sequence, and the next ones.
DbFunctions are used when the Provider translates the Expression into SQL. If you create a Queryable with DbFunctions and in your debugger look at the created Expression, you'll still find the used DbFunctions.
The DbFunctions only translate the input into SQL. If does not perform the query itself. The translation is done in local memory.
Having understood this, you can use any function as long as it only changes the Expression into new Expressions into formats that your provider understands.
This means you can't use any of your own functions, or classes. There are even several LINQ functions you can't use
See supported and non-supported LINQ methods
However, if your extension functions input an IQueryable and output an IQueryable, then your extension function will only change the Expression. As long as you fill the Expression with supported LINQ methods you're fine
So if you want to extend IQueryable with a function that returns an IQueryable containing only the invoice that are due to day:
public static IQueryable<Invoice> WhereDueToday(this IQueryable<Invoice> invoices)
{ // returns all invoices that must be paid today
return invoices
.Where(invoice => DbFunctions.TruncateTime(invoice.DueDate) == DateTime.Today);
}
Usage:
IQueryable<Invoice> invoices = dbContext.Invoices
.Where(invoice => ..);
IQueryable<Invoice> invoicesDueToDay = invoices
.WhereDueToday();
You can define a method that returns an Expression and use that in your where clause. Since you want to pass different properties of the object in you can't just write one expressions
public Expression<Func<T, bool>> MyFunc<T>(Expression<T, int> property1, Expression<T, int> property2, int greaterThan)
{
// Build expression tree
}
I realise "Build Expression tree" isn't hugely useful, but if you don't really want to do add writing out the code to build "add" isn't going to help you either.
If there are just a couple of combinations it might be easier to just hard code for those
public Expression<Func<T, bool>> MyFunc<T>(PropertiesEnum p, int greaterThan)
{
switch(p)
{
case (p.XandY):
return item => (item.X + item.Y) > greaterThan;
case (p.XandZ):
return item => (item.X + item.Z) > greaterThan;
case (p.YandZ):
return item => (item.X + item.Z) > greaterThan;
// other cases
}
}
You would call this like:
var locations = context.Data.Where(MyFunc(PropertiesEnum.XandY, 10));

Setting global variables in working memory in Drools planner

How do I add a global variable to working memory in drools planner's solver to be able to use in scores drool. This is similar to https://issues.jboss.org/browse/JBRULES-2700 but couldn't find a solution though.
What you might be looking for is a #ProblemFactProperty.
Quoting from the documentation:
All objects returned by those [annotated] methods will be inserted into the
ConstraintStreams or Drools session, so the constraint steams or score
rules can access them.
In my own words: You can hold a reference to your global object in your #PlanningSolution class. If you annotate its getter with #ProblemFactProperty you can access it from your drools file.
First some preaching: Using a service (set as a global) to calculate part of the score will break delta based score calculation (read the manual section on that topic), resulting in much less score calculations per second (say 50 instead of 5000 per second on big data sets).
Then a HACK solution: In the StartingSolutionInitializer (soon known as CustomSolverPhaseCommand) do solverScope.getWorkingMemory().setGlobal("key", value).
Then a real, long-term solution: Could you motivate why you need to be able to do this? We can think about adding support for this with something like an optional WorkingMemoryPreperator.
After set the planningProblem:
solver.setPlanningProblem(planningProblem);
You can get access the workingMemory via solutionDirector(HACK) :
DefaultSolutionDirector solutionDirector = ((DefaultSolver)solver).getSolverScope().getSolutionDirector();
solutionDirector.getWorkingMemory().setGlobal("list", new ArrayList<String>());
Cheers!
If you need to use some helper methods in the planner rules, try the following approach which I used in my project:
Create a utility class which includes the helper methods.
Import the utility class in the rule file like importing it in a java class.
Use the helper method in the rule. If you want to use a helper method in the condition, wrap using eval(). If you want to use a helper method in the then part, just use it as normal java method call.
For example, say you have a utility class named PlanningUtil like below:
public class PlanningUtil {
public boolean isGood() {return true;}
public void doSomething() {//...}
}
Then import the utility class in the rule file,
import PlanningUtil;
Use the utility method in the rule
rule "MyRule"
when
eval(PlanningUtil.isGood())
then
PlanningUtil.doSomething(); // note the ';' is a must.
end

MEF: metadata seem to override interface when using GetExports

I'm building a MEF-based plugin-centric WPF application and I'm facing an issue with GetExports, maybe it's just my ignorance but I find an odd behaviour. I have a number of exported parts, all derived from 2 different interfaces (let's name them A and B), but all marked with the same metadata attribute X. So I have code like:
[Export(typeof(A))]
[TheXAttributeHere...]
public class SomePart1 : A { ... }
for each part, and the same for classes implementing B:
[Export(typeof(B))]
[TheXAttributeHere...]
public class SomePart2 : B { ... }
Now, when I try getting all the parts implementing A and decorated by attribute X with some values, MEF returns not only the A-implementing parts, but ALSO the B-implementing parts. So, when I expect to deal with A-objects I get a B, whence a cast exception.
In the real world, interfaces are named IItemPartEditorViewModel and IItemPartEditorView, while their common attribute is named ItemPartEditorAttribute and exposes a PartType string property on which I do some filtering. My code to get parts is thus like e.g.:
var p = (from l in container.GetExports<IItemPartEditorViewModel, IItemPartEditorMetadata>()
where l.Metadata.PartType == sPartType
select l).FirstOrDefault();
When looking for IItemPartEditorViewModel whose PartType is equal to some value, I get the IItemPartEditorView instead of IItemPartEditorViewModel implementing object. If I comment out the attribute in the IItemPartEditorView object instead, I correctly get the IItemPartEditorViewModel implementing object.
Update the suggested "templated" method was used, but I mistyped it here as I forgot to change lessthan and greaterthan into entities. Anyway, reviewing the code I noticed that in the attribute I had "ViewModel" instead or "View" for the interface type, so this was the problem. Shame on me, sorry for bothering :)!
I think I'd need to see more of the code to know for sure what's going on. However, I'd suggest you call GetExports like this:
// Get exports of type A
container.GetExports<A>();
// Get exports of type B
container.GetExports<B>();
Then do your filtering on the list returned. This will probably fix the cast issues you are having. I'd also be interested in seeing the code for the custom metadata attribute. If it derives from ExportAttribute for example, that might be part of the problem.

Derived Type with DateTime Condition

I have a Show table, and I would like to have a derived type called ActiveShow which only returns shows in the future
Show.ShowDateTime > DateTime.Now
Is there a way that I can achieve this using the designer or some other way so that creating an instance of ActiveShow will always adhere to the date condition?
Absolutely you could do this using a DefiningQuery (which is essentially a TSQL view) in the SSDL.
But I don't recommend it.
The problem is type memberships would be transient, when it should be permanent, or at the very least require you to explicitly change it.
I.e. you could end up in a situation where at one point something is an ActiveShow (and loaded in memory) but if you do a subsequent query you might attempt to load the same object as a Show. In this situation what would happen to identity resolution is anyone's guess.
This will more than likely resort in some very nasty unexpected side-effects.
As an alternative perhaps an extra Property in your Context added in a partial class:
i.e.
public partial class MyContext
{
public ObjectQuery<Show> ActiveShows
{
get{
return this.Shows.Where(s => ShowDateTime > DateTime.Now)
as ObjectQuery<Show>;
}
}
}
This probably gives you most of the benefits without most of the risks.
Hope this helps
Alex

Is there a way to generically return all of the records from a table with the Entity Framework

Basically I'd be looking to implement a method like this.
IQueryAble GetQuery<T>(Entities db) or extension method Entities.GetQuery<T>()
This way you could do things like this
public IQueryable<T> GetAll()
{
return yourEntityClasses.GetQuery<T>();
}
which would return a SELECT * FROM query expression and obviously from there you could make addtional generic methods for sorting, pagination, where expressions, etc on top of this would save you from having to repeat the code for these methods for each table. I know SubSonic3 does a very good job of this, but was trying to duplicate some of the functionality in an EntityFramework project I am working on. Only thing I see in EF is CreateQuery and ObjectQuery but both of those require you to pass a querystring in which would require you to know the table name.
Well it is possible to get the string that you need to put into the CreateQuery method automatically.
Basically it is just string.Format("[{0}]",entitySetName);
How do you get the entity set name, assuming you have don't use something called MEST, most people don't, you can use some a functions I wrote in this Tip to get the EntitySet for T and from that the name.
Once you do that it should be pretty trivial for you to write the Extension Method
i.e.
public static IQueryable<T> GetAll<T>(this ObjectContext context)
{
var wkspace = context.MetadataWorkspace;
EntitySet set = wkspace
.GetEntitySets(wkspace.GetCSpaceEntityType<T>())
.Single();
return context.CreateQuery<T>(string.Format("[{0}]",set.Name);
}
See the above tip for the other functions used.
Hope this helps
Alex