How to change "Potentially dead Methods" CQLinq to be useful in a WPF MVVM project - mvvm

Just started NDepend on a WPF project. Changed the "potentially dead types" built-in query to include our System.Windows.Application derived class instead of the class called Program:
// <Name>Potentially dead Types</Name>
warnif count > 0
let canTypeBeConsideredAsDeadProc = new Func<IType, bool>(
t => !t.IsPublic &&
(t.BaseClass == null || t.BaseClass.FullName != "System.Windows.Application") &&
!t.IsGeneratedByCompiler && ...
After tackling these, I would still need to deal with lots of dead methods found by NDepend that are actually used in a WPF Binding. Any ideas how to start on this without marking all such view-model properties with an attribute?
Unfortunately all methods used by only those properties also seem to be dead code, so this query "leaks" into parts of the model, too.

Related

What and when can "Target" be instead of an Entity and should I check its logical name when working on a single entity type?

I'm a newbie in developing in CRM, so I want to get some things clear. And you first you need to know the reason why you have to do something in order to fully understand it. So lets get to the question.
I know you have to do this when making a plugin:
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if (context.InputParameters.Contains("Target") && context.InputParameters.["Target"] is Entity)
{
var entity = (Entity)context.InputParameters["Target"];
if(entity.LogicalName == "myEntity")
{
//Do something with your entity
}
}
Now, in the PluginRegistration Tool, you can set up that your plugin will be fired on the defined Message and which entities (and specific attributes from them) will be affected by it, besides other stuff.
I can see the validations are very useful when manipulating several entities with a single plugin.
Now, let's suppose you only are updating a single entity with your plugin. Why should I check if the entity that's on "Target" is the entity I want to work on, if I already know because I set it up for that entity in particular? What can an Entity be otherwise in that scenario?
Also, in what cases "Target" is NOT an Entity (in the current context)?
Thanks in advance, and sorry if this is a silly question.
See this answer: Is Target always an Entity or can it be EntityReference?
Per the SDK (https://msdn.microsoft.com/en-us/library/gg309673.aspx):
Note that not all requests contain a Target property that is of type
Entity, so you have to look at each request or response. For example,
DeleteRequest has a Target property, but its type is
EntityReference.
The bottom line is that you need to look at the request (all plugin's fire on an OrganizationRequest) of which there are many derived types (https://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.organizationrequest.aspx) to determine the type for the Target property.
As Nicknow said, the Input Parameters will change depending on the Message being executed.
You can get that information from the MSDN (every request will list the Input Parameters under the Properties section, for instance the CreateRequest) or using the ParameterBrowser.
There's also a really nice alternative to deal with this in a type-safe approach (intellisense included) described in the following blog article: mktange's blog.

Excluding classes instantiated via IOC container from NDepend warning

My NDepend reports warn that 'Non-static classes should be instantiated or turned to static.' Most of the classes in the returned list are registered via my IOC container (Unity) and instantiated by my IOC framework at runtime.
Given that NDepend is performing static analysis, it's not going to be aware of the runtime instantiation. I'm hoping that it's possible to tweak the CQL to make it aware of my container.
This is the boilerplate query that NDepend executes:
warnif count > 0
from t in JustMyCode.Types
where t.IsClass &&
//!t.IsPublic && // if you are developping a framework,
// you might not want to match public classes
!t.IsStatic &&
!t.IsAttributeClass && // Attributes class are never seen as instantiated
!t.DeriveFrom("System.MarshalByRefObject".AllowNoMatch()) // Types instantiated through remoting infrstructure
// find the first constructor of t called
let ctorCalled = t.Constructors.FirstOrDefault(ctor => ctor.NbMethodsCallingMe > 0)
// match t if none of its constructors is called.
where ctorCalled == null
select new { t, t.Visibility }
Is it possible for me to tweak this query to exclude classes that are referenced in my IOC container registration?
Indeed, you can vote for NDepend supports of IoC Framework on the NDepend User Voices site. This is a feature that will be implemented in the future.
For now, you can handle this with an attribute. Create an attribute class in your code, for example named MyProduct.IoCInstantiatedAttribute.
Then you can tag all your classes instantiated solely by IoC with this attribute. Since this attribute is only needed on DEBUG build (the one analyzed by NDepend) I'd advice using a conditional DEBUG syntax.
#if DEBUG
[IoCInstantiated]
#endif
class MyClass { ... }
Finally, you just have to add && !t.HasAttribute("MyProduct.IoCInstantiatedAttribute") in your concerned rule(s) et voilà!
Additionally, you can also write a rule to make sure that classes that have this attribute are not instantiated somewhere. This way you'll keep the usage of this attribute clean!
// <Name>Types tagged with attribute IoCInstantiated must not be instantiated elsewhere</Name>
warnif count > 0
from t in Types
where t.HasAttribute ("MyProduct.IoCInstantiatedAttribute")
let methodsInstiatingMe = Application.Methods.ThatCreateA(t)
where methodsInstiatingMe.Any()
select new { t, methodsInstiatingMe }
Personally I found that using such attribute is great, because it also documents code. When a developer is reviewing such class, he can have this important piece of information (instantiated solely through IoC) at a glance.

Get entity facets and other metadata on runtime

I have .NET 4.0 WinForms Application, and I use Entity Framework 5 with Model First Approach. In VS EF Designer, I have created a dozen or so entities with a lot of scalar properties of String type, then in Properties Toolbar I have configured parameters (i.e. General parameters, Facets Parameters) for them, to fit DB requirements.
In BL layer I am able to validate entity object in purpose to check whether it contains correct values, for example by using DbContext.Entry(Of T)(entity).GetValidationResult() method. But I need to develop also GUI layer input fields validation for WinForms. I would like to implement dynamic GUI validation, based on metadata values of entity set properties, to have BL validation synchronized with GUI validation, and to avoid redundancy of source code written.
My question is: How can I get metadata values, particularly facets metadata values (i.e. Fixed Length, Max Length, Nullable) of auto-generated entities on runtime?
As I know, there is a possibility to take advantage of data annotations based on properties attributes in manually created partial class. However, in Model First approach, this solution may also involve redundancy issues and synchronization problems with metadata from VS EF Designer Properties Toolbar and Database.
This should help you get started, but you'd need to get to debugger and test specifically to get what you need...
A sample code...
using (var db = new MyContext())
{
var objectContext = ((IObjectContextAdapter)db).ObjectContext;
var baseset = objectContext
.MetadataWorkspace
.GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace)
.BaseEntitySets
.First(meta => meta.ElementType.Name == "YourEntityClassName");
var elementType = objectContext
.MetadataWorkspace
.GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace)
.BaseEntitySets
.First(meta => meta.ElementType.Name == "YourEntityClassName")
.ElementType;
EdmMember member = elementType.Members[2];
Facet item;
// if (member.TypeUsage.Facets.TryGetValue(EdmProviderManifest.StoreGeneratedPatternFacetName, false, out item))
if (member.TypeUsage.Facets.TryGetValue("StoreGeneratedPattern", false, out item))
{
var value = ((StoreGeneratedPattern)item.Value) == StoreGeneratedPattern.Computed;
}
But that's just part of the story.
What I realized is that's working in some cases (thus you need to experiment a bit) depending on what you need. But you also have other spaces in there - e.g. the SSpace. So e.g. for table names this works better...
var ssSpaceSet = objectContext.MetadataWorkspace.GetItems<EntityContainer>(DataSpace.SSpace).First()
.BaseEntitySets
.First(meta => meta.ElementType.Name == "YourTableName");
...and then private Table property.
In your case you should most info in there - but e.g. the above store generated is not populated there - but in some other 'space' I guess (more in one of the links on that).
And take a look at the following links:
Get Model schema to programmatically create database using a provider that doesn't support CreateDatabase
How I can read EF DbContext metadata programmatically?
How check by unit test that properties mark as computed in ORM model?

Techniques used with Entity Framework navigation properties

Starting to explore EF4.3.
Using navigation properties makes things very easy, although I have a concern in one area, where I'd appreciate some advice on how other people deal with this scenario.
Take the scenario - Store.Programme.ProgrammeAccountNumber when lazy loading nested properties.
Store is the entity I'm querying.
Programme is an entity, and also a navigation property of Store, and ProgrammeAccountNumber is a property of Programme.
To get the original entity, I write something like this:
public static IQueryable<Store> FindActive()
{
var r = new ReadRepo<Store>(Local.Items.Uow.Context);
return r.Find(s => s.StoreStatusId == (int)StoreStatus.Active);
}
But lets suppose that Programme has it's own status fields:
var store = StoreBL.FindActive()
.Where(s => s.Programme != null && s.Programme.ProgramStatusId = (int)ProgrammeStatus);
It's not easy to remember all the conditions for each entity each time the query extends beyond the original entity.
Imagine a chain of properties where I have a product, that has a start/end dates and a status, that belongs to a store, that has a programme with a status and is valid if the category it operates is live.
I got to thinking there must be a technique for dealing with this effectively, or is it a case of using Lazy Loading sparingly?
Any advice appreciated.

How to get an IType from a class name in Eclipse JDT

I'm implementing a variant of the JUnit New Test Suite Wizard, and instead of getting test classes from the current project, I need to get them from another source. They come to me as strings of fully-qualified class names.
Some of them may not yet exist in this user's workspace, let alone in the classpath of the current project. The user will need to import the projects for these later, but I don't want to mess with that in my wizard yet. I need to just add all classes to the new suite whether they exist yet or not.
For those classes that are already in this project's classpath, I can use IJavaProject.findType(String fullyQualifiedName) . Is there an analogous way to get ITypes for classes that are not (yet) visible?
I would be happy to construct an IType out of thin air, but ITypes don't seem to like being constructed.
I don't think that is possible: the Java Document Model interfaces are created based on the classpath.
Even worse, if the project do not exist in the users workspace, the resulting code would not compile, and that is another reason for not allowing the arbitrary creation of such constructs.
If I were you, I would try to help the user to import the non-existing projects in case of types are not available, thus avoiding the tackling with the Java Document Model.
For my purposes, creating a HypotheticalType and a HypotheticalMethod got the job done. I'm attaching an overview in case anyone else needs to follow this path.
First I created a HypotheticalType and had it implement the IType interface. I instantiated one of these at the proper spot in my modified wizard. Using Eclipse's Outline view I created a method breakpoint on all methods in my new class. This let me detect which methods were actually getting called during execution of my wizard. I also modified the constructor to take, as a String, the name of the class I needed the wizard to handle.
Almost all of the new methods are ignored in this exercise. I found that I could keep the default implementation (return null or return false in most cases) for all methods except the following:
the constructor
exists() - no modification needed
getAncestor(int) - no modification needed, but it might be useful to return the package of my hypothetical class, e.g. if my class is java.lang.Object.class, return java.lang.
getDeclaringType() - no modification needed
getElementName() - modified to return the class name, e.g. if my class is java.lang.Object.class, return Object.
getElementType() - modified to return IJavaElement.TYPE
getFlags() - not modified yet, but might be
getMethod(String, String[]) - modified to return a new HypotheticalMethod(name)
getMethods() - modified to return new IMethod[] { new HypotheticalMethod("dudMethod") }
In the process I discovered that I need to be able to return a HypotheticalMethod, so I created that type as well, inheriting from IMethod, and used the same techniques to determine which methods had to be implemented. These are the only methods that get called while this wizard runs:
The constructor - add a String parameter to bring in the name of the method
exists() - no modification needed
isMainMethod() - no modification needed
That covers the solution to my original question. Zoltán, I'll be doing as you suggested in an upcoming iteration and trying to assist the user in both the case in which the desired class is not yet in this project's classpath, and the case in which the desired class is in some project not yet in the workspace.