Creating global aspects in postsharp - postsharp

I am looking for a way in which to all aspects to run on methods in many places in my project, without having to manually add in the attribute tag to each method or class.
My entire solution holds around 20 separate projects. One of which I have created called myname.space.Attributes which holds my attribute declarations, as well as a file called GlobalAspects which has the following:
using PostSharp.Patterns.Diagnostics;
using PostSharp.Extensibility;
using myname.space.Attributes;
// This file contains registration of aspects that are applied to several classes of this project.
[assembly: TraceLoggingAttribute(AttributeTargetTypes = "myname.space.Controllers.*",
AttributeTargetTypeAttributes = MulticastAttributes.AnyVisibility,
AttributeTargetMemberAttributes = MulticastAttributes.AnyVisibility)
]
[assembly: TraceLoggingAttribute(AttributeTargetTypes = "myname.space.Repositories.*",
AttributeTargetTypeAttributes = MulticastAttributes.AnyVisibility,
AttributeTargetMemberAttributes = MulticastAttributes.AnyVisibility)
]
The goal of this was to add my TraceLoggingAttribute to all the methods held within these other 2 projects, Controllers and Repositories.
I have set up these 2 other projects to reference the Attributes project, and the attribute works perfectly fine if I put the [TraceLoggingAttribute] tag on the classes and methods within the Controller and Repositories projects.
Is there a way in which I can set up my GlobalAspects.cs to work in the way I am looking for? Please ask question if I have not explained the issue well enough here
For interest, the TraceLoggingAttribute is defined as:
namespace myname.space.Attributes
{
[MulticastAttributeUsage(MulticastTargets.Method, TargetMemberAttributes = MulticastAttributes.Instance)]
[Serializable]
public class TraceLoggingAttribute : OnMethodBoundaryAspect
{

Unfortunately you can only apply attributes to currently compiled assembly (or to calls to other assemblies through TargetAssembly property but that also affects only currently compiled assembly).
I think that the easiest solution would be to link GlobalAspects.cs into all projects that you want to be affected by it. This should work as you expect and not cause any problems.
Hope that helps.

Related

Enterprise Architect Code Generation: Get tags of interface

I use Enterprise Architect for code generation and I would like to automatically retrieve all tags (in my case Java annotations) of the interfaces that a class realizes. Consider the following example:
From this model, I want to generate a class that looks like this:
#AnnotationOfMyInterface
public class MyClass {
...
}
So I want to add annotations as tags to MyInterface that should be applied to MyClass during code generation. In the UI, tags of implemented interfaces are shown so I was hoping there is a way to get these tags during code generation.
I tried to edit the code generation templates and found macros to get
All interfaces that a class implements: %list="ClassInterface" #separator=", "%
All tags with a given name (of the class that code is being generated for): %classTag:"annotations"%
But unfortunately, I cannot combine these macros, i.e., I cannot pass one interface to the classTag macro so that I can retrieve the tags of that particular interface (and not the one I'm generating code for). Is there a way to get classTags of a specific class / interface?
I also tried to create a separate code generation template and "call" it from the main class code generation template. But inside my template, the classTag macro still only gets the tags of the class.
Thanks to the comments above and especially because of an answer to my question in EA's forum, I was able to setup a little proof of concept achieving what I wanted. I'm answering my question to document my solution in case someone has a similar problem in the future.
After Eve's hint in EA's forum I looked into creating an AddIn for Enterprise Architect to use this AddIn from a code generation template. I started by writing a basic AddIn as explained by #Geert Bellekens in this tutorial. Afterwards I changed the AddIn to fit my needs. This is how I finally got the tagged values (annotations) of the interfaces a class realizes:
First step:
Inside a code generation template, I get all the interfaces a class realizes and pass them to my AddIn:
$interfaces=%list="ClassInterface" #separator=", "%
%EXEC_ADD_IN("MyAddin","getInterfaceTags", $interfaces)%
Second step:
As documented here the repository objects gets passed along with the EXEC_ADD_IN call. I use the repository object and query for all interfaces using the names contained in $interfaces. I can then get the tagged values of each interface element. Simple prototype that achieves this for a single interface:
public Object getInterfaceTags(EA.Repository repo, Object args)
{
String[] interfaceNames = args as String[];
String firstInterfaceName = interfaceNames[0];
EA.Element interfaceElement = repo.GetElementsByQuery("Simple", firstInterfaceName).GetAt(0);
String tag = interfaceElement.TaggedValues.GetAt(0);
return interfaceElement.Name + " has tag value" + tag.Value;
}
I know, there are a couple of shortcomings but this is just a simple proof of concept for an idea that will most likely never be production code.

Eclipse 4 RCP - how to change what is showed in specific area?

I have splitted my application into two main areas.
Part(A)
PartStashContainer(B)
The content of A should be set based on what user wants.
So basically i can have 1..N classes which could be used in Class URI of Part in application model.
I don't know if i should replace the whole Part(A) with new dynamically created Part(C) which has content i want, or i should somehow to modify the existing Part (call setContributionURI, or setObject methods on Part object?).
It does make more sense to me to modify the existing Part, because it is defined in Application model and therefore already describing the location where the content should be.
Possible solutions:
Modify the Part object so it "reload" its content based on new setup (But how? Can setContributionURI or setObject methods help?)
Remove the old Part and add dynamically on same place in Application model the new Part (using EModelService and EPartService).
other solution??
If you want to reuse the Part then do something like:
MPart part = find or inject your part
MyClass myClass = (MyClass)part.getObject();
... call a method of MyClass to change the contents
MyClass is the class you specify for the object in the application model. You should add a method to that to let you change the contents.
Don't try to call setObject, this is really only for use by Eclipse. I don't think setContributionURI would do anything after the part is created (but I am not sure).
If you want to use different classes for the different data then you really should use different Parts.

Entity Framework generated classes are not in the namespace I require, is there a way of changing the namespace it uses without regenerating?

If I need to regenerate where should the namespace be specified. I am trying to use partial classes from within the Models namespace however they don't match.
The simplified code fragment below is where the entity framework classes have been generated
namespace projectname
{
#region Contexts
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public partial class MyClass
{
}
}
When I add a class to my models folder,
namespace projectname.Models
{
public partial class MyClass
{
//etc, etc
}
}
As you can see the namespaces don't match causing issues when I try and use them as the compiler is seeing both projectname.Models.MyClass and projectname.MyClass.
I would like some advice on the correct way to fix this, preferably to update the E.F. classes so they exist in the projectname.Models namespace, but I am not sure how to go about it.
In line with Roman O's comment, namespace can be changed by updating "Custom Tool Namespace" property of text transform (.tt) file, which ties generated entity classes (in Database First approach) to entity model (.edmx) file. This works in VS 2012 Express with EF 5.0.
I would post a screenshot but for lack of reputation.
IIRC, if you are using an Entity data model, you should be able to change the namespace directly through the xml file or files (you may have to change it for all the various storage and and conceptual models). There might even be some way to change it in the designer.. seems simple enough.
Actually, the solution might be here:
Generated Code Overview (Entity Data Model Designer) (see Custom Tool Namespace)
Right click the .edmx file in the project in Solution Explorer and select Properties
In the VS properties pane, fine Custom Tool Namespace
Enter the full CLR namespace you'd like
Rebuild the project
Namespace of auto-generated classes will be inherited from VS project settings (and even change if you change it there). Of course you should have "Custom Tool Namespace" property empty. (just tested it with VS2013 and EF6.1)
Unlike settings files which had always been pita :)
For older version there is a good video on manual changing :
https://youtu.be/B7Cqc9F0Ih8

CodeDom - Linking multiple classes within a single Assembly

I have a C# application that I am trying to re-create through the use of CodeDom. This application has four classes inside of it. If I were to go into this applications directory, I would find the project file (App.csproj), and if I were to start this project file, all four classes would load together. Furthermore, if I were to build this application, all four classes would build together.
My Question: How on earth can I create this functionality through the use of CodeDom?
I have sucessfully created one of the four classes using CodeDom, but how can I go about creating the next three classes (and linking them) to the first class that I already created?
I know this may sound confusing but I will explain more if necessary.
If the classes are in the same namespace you can add them all to one CodeNamespace object and generate the code from that.
If there in different namespaces you can add the namespace of the other Classes to your first class by adding the namespaces reference of the other class's to the namespace object you are working in:-
// Add the Namespace of the other class to the current namespace onject
defaultNameSpace.Imports.Add(new CodeNamespaceImport("Project.Namespace.Namespace"));
Where defaultNameSpace is a type of CodeNamespace. The first Class you have built is added to this CodeNamespace object as below and then the code is generated from that :-
defaultNameSpace.Types.Add(mainClass);
mainClass being a type of CodeTypeDeclaration.
Hope this helps.

Loading workflow activity dynamically from XOML

I am trying to implement an activity similar to InvokeWorkflow, which could dynamically load a XOML file, instantiate an activity tree from it, and use it as its only child.
This would be similar to InvokeWorkflow except that the activities which are dynamically loaded are inlined into the main workflow (which is better from a monitoring perspective).
I looked at XamlReader as a potential way of doing this, but apparently it is not suitable for loading workflows (only UI stuff).
Thanks,
Julien
Achieving your goal here is likely to be quite tricky however lets start with the easy bit:-
You can reconstruct a workflow from XOML using the WorkflowMarkupSerializer found in the System.Workflow.ComponentModel.Serialization namespace.
var serializer = new WorkflowMarkupSerializer();
object root = serializer.Deserialize(myXmlReader);
Similarly you could reconstruct a "snippet" of activities held in something that inherits from CompositeActivity using the CompostiteActivityMarkupSerializer.
However, to integrate the new root activity into the currently running workflow requires more work. You need to use an instance of the WorkflowChanges class to make the new activity by modifing the Workflow definition used by the current instance.
Now the documentation is some what sketchy and even a little evasive on this subject. Two important points can be gleaned though:-
Ultimately a call to ApplyWorkflowChanges is needed and this member has protected accessibility.
The documentation indicates that this needs to occur on the root activity of a workflow.
Hence we can deduce that we will need a custom root activity to at least assist in this requirement.
There are probably more ways that this could be structured but lets assume we have a SequenceActivity in which we have a custom "InvokeWorkflow" activity performing the workflow modification and we intend to place the resulting new activity at the end this containing sequence.
First we'll need an interface definition which we can implement on the custom root activity:-
internal interface IModifiableWorkflow
{
void ApplyWorkflowChanges(WorkflowChanges workflowChanges);
}
In our custom root activity we would implement this interface explicitly:-
public class CustomSequentialActivity : SequentialWorkflowActivity, IModifiableWorkflow
{
void IModifiableWorkflow.ApplyWorkflowChanges(WorkflowChanges workflowChanges)
{
base.ApplyWorkflowChanges(workflowChanges);
}
}
In the Execute method of the custom "InvokeWorkflow" activity:-
// Get root activity
var root = this.Parent;
while (root.Parent != null) { root = root.Parent; }
// Create an instance of WorkflowChanges based on the root activity
var changes = new WorkflowChanges(root);
//Find the parent sequence activity in the transient workflow definition
var target = changes.TransientWorkflow.GetActivityByName(this.Parent.Name);
Activity newActivity = YourCodeToLoadActivityDetailsFromXoml();
target.Activities.Add(newActivity);
//Apply the new changes
((IModifiableWorkflow)root).ApplyWorkflowChanges(changes);
Note I haven't actually tested any of this, its cobbled together from crumbs of info buried in the documentation.
Thanks so much Anthony.
I have to say that your dynamic workflow modification is cool, but it was a little scary. I ended up composing workflows using a modification of Jon Flander's CallWorkflowActivity.
Some tricks I learned with XOML-only workflows loaded at runtime (using WF 3.5):
remove x:Class attribute inside the XOML
delete the code-behind file
for the VS designer to work, those XOML files need to be separated in their own projects (no code, such as base activities or common types, in the project where the XOML is located)
mark the XOML as Content in VS and Copy Always so it is placed with your binaries
even so, VS 2008 usually needs a full Rebuild in order to properly copy newly modified XOML files...
you may need to set breakpoints manually, as explained here