How to identify parts in MEF? - c#

The question is as simple as that: I need some way to identify composable part definitions before actually creating the parts.
In other words, I need to be able to send a string identifying the part to some remote site, which later would send the string back to me, and I should be able to pick that same part based on the string. I do not necessarily need a string (I can build my own map), but I need something that is unique and equality-comparable.
Some things I thought about and rejected:
I do realize that the "right" way for doing this is to decorate my parts with metadata, but I don't want to. First, using a meaningful string for identifier means risk of duplication, while using a random one (like GUID) means it would be ugly. Second, my plugins are numerous and I don't want to have to remember about decorating them all the time.
Another way that immediately jumps to mind is to use the part's type. However, MEF is generic enough to be above such formalities: a part is not necessarily a .NET class.
In trying to "fix" the previous point, I could use type of the actual object that is returned when I go and create the part, but then I would have to create all parts, which are numerous.

Metadata is really the only viable option, especially if you want the identifier to remain stable over time, e.g. in the face of application restarts or implementation class refactoring/renaming.
If you don't need stability between application restarts, you could either:
Use MEF 2's RegistrationBuilder to programmatically generate the necessary metadata values, e.g. based on an incrementing integer; or,
Create a custom [MetadataAttribute] that does roughly the same thing to generate an id value at runtime
If you need stability between restarts, but not between rebuilds, then using RegistrationBuilder to assign ids based on the type name is an option.
Of course, RegistrationBuilder is only available in the CodePlex preview builds of MEF 2 or the .NET 4.5 Developer Preview at this point.
TLDR; manually applying metadata attributes is your best bet. In debug mode you could write a post-initialisation routine in your app to ensure uniqueness/presence.

Related

Executing the code stored in string field of XML file

So, I'm making myself a small C# library for dialogues to use in an cRPG game.
The idea is, that the Dialogue object and it's fields (like DialogueNode and DialogueOption objects) are created based on an XML file, which I aim to make as simple as possible. The fields, except for lists or objects of types contained within the library, are - at best - string identifiers, to be acquired and parsed by outside means when needed.
I've basic funcionality implemented - XML serialization, running through the dialogue and exiting it - as well as basic, console based application interpreter and a WPF editor to create the dialogues, because writing the dialogue in plain XML is not the most comfortable thing in the world. (the last two are meant to be as much independent from the library as possible, except maybe for implementing what's inside to show/create)
All that being said, I've encountered a problem (actually two, the other one I'll cover in different question when I've the time after my exams).
After giving it some of my unexperienced 'noobish' thought, I've come to think, that I'd like to have some basic predicates stored either in my nodes or options - they would be later checked in game to determine, whether to display the node/option or leave it be (or whatever meddling with those to be honest). For example - an option is displayed if the player character have item X in his inventory, or the node is displayed when player has a certain minimum value of an attribute.
My idea of implementing is so far like that:
Having a field PredicateScript in an object
Having a bool method, that would be executed in runtime by the interpreter like this:
public bool DisplayPredicate(string predicateCode)
{
bool result = FunctionExecutingCSharpCode(predicateCode);
return result;
}
I've read some topics about compiling on the fly very brielfy, but I'm not sure if it's exactly what I want - I'm not sure how it would affect the performance of application (either the interpreter or the game itself), if it would be recompiled every few seconds...
I'm not pasting any code of what I'm trying to do, because either I'm yet to do this (as I'm not writing the code I'm not sure it will work) or it's the library structure which I don't think would be of relevance aside from what I explained I aim to do. ^^
Thanks. ^^
Given the standard .NET framework, there's no such thing as a C# "interpreter" you can feed code that gets executed. You could try to dynamically create C# code and have that compiled on the fly into an in-memory assembly, which you can then use using the .NET compiler services.
And example of this is given here: http://www.codeproject.com/Tips/715891/Compiling-Csharp-Code-at-Runtime.

C# Resources: display resource string names instead of localized values

Having rather large project using Resources for internationalization (following this guide: ASP.NET MVC 2 Localization complete guide, using things like data attributes, and so on) we run into the need of translating the resource files. In the beggining of project I selected approach to have lot of small resource files - for each view, viewmodel, controller, ... So I ended up having hundreds of resources. During the translations (which is done by our partners using ResXManager tool we run into trouble identifying the context of the string (where is it displayed, to find out the correct form of translation to make sense when displayed).
So I was asked to make the mutation of application which do not display the localized values, but the keys (or string names). E.g. having string in resources TBL_NAME used somewhere in the view like #ResX.TBL_NAME and translated into english as "Name", I would like to show it in this special mutation as "TBL_NAME", so the translator may see the context - where exactly this string is used.
The best would be, if this is not special build of application, but rather the another "language" of the application available for translators, so he can switch between english and this "unlocalized" languages.
I'm looking some easy ideas of doing this. So far I was thinking of these approaches:
Override ResourceManager.GetString - cannot use, because we use generated Designer classes to access strings massively and so far I haven't find a way to change created ResourceManager (see this answer). Did I miss something?
Create resources for some unused language, which will contain pairs string name/translated value as TBL_NAME/TBL_NAME - viable, but very exhausting since we have hundreds of resources. Also the addition of new resource will require us to remeber that we need to add also this unused language resource will exact same strings name. You also have to do twice much work when adding single string to application.
At the moment, it seems for me, that using resources and current approach it is impossible to solve this task, so I decided to ask this as question (and I'm aware it is rather discussion than question) here, hoping, someone will give me some hint about other approach to solve this problem.
My preferred option would be to give the translators an environment where they can see what they are translating. Rigi requires a bit of setup (basically you need to add an additional UI language), but once you have done that translators can work within the live website - or in a test instance, which is what we did.
They can also work in screenshots, which is convenient when translators would have to access admin or other role specific pages but you do not want to bother giving them all kinds of user rights. These screenshots can be generated as part of automated UI tests or during manual UI testing.
I am afraid I can't say anything about the cost of the solution, but our translators are really happy with it. I am not sure if this is what you are looking for since you asked for an easy solution, but it definitely solves the issue of giving translators the context they need to do their job - better than displaying resource IDs.

Writing and changing code at runtime

I have a situation where I'd like to build MVC style views at runtime using their EditorFor/DisplayFor templates (or something similar).
Ideally our application would let the user choose which fields they want in their UI (so they can add /remove any as they see fit), to this end I thinking it'd be handy to be create viewmodel classess at runtime and add the various dataannotation attributes to them according to what user selects (ie. stringlength, required etc).
One thing I need to be able to support is changing of the generated classes at runtime without affecting other users or having to do a full iisreset.
To go about this I've been doing a bit of research and it seems like there might be 3 different approaches, CodeDom, RunSharp / Relfection.Emit,Roslyn.
From what I can tell reflection.Emit/Runsharp would allow me to create the classes and add attibutes and properties to them at runtime and probably also modify them when I need to without adverse effects.
I'm not sure if Roslyn would allow this, I haven't been able to track down any simple examples of creating a class with properties or attributes in it, and I've seen a few mentions that Roslyn's output is immutable so I'm not sure how that goes for allowing me to modify it at a later date without adverse effects.
In general from what I've seen most people don't recommend CodeDom so I'm not entirely sure if I should bother going down that route.
Can anyone give me an idea of which of these directions might be viable for me?
So, none of these solutions are going to work, and honestly, generating type at runtime really isn't what you want here.
When it comes to the CLR, once you have a type with fields and methods, you can't really add new members or change members at runtime. The closest we come to doing that is the edit-and-continue features in Visual Studio, we're highly restricted to what changes we can make. We often 'cheat' by not adding methods or attributes where you think they added, but we hide them somewhere else and emit IL that references this secret location when you make an edit. Crazy things like removing members is entirely unsupported. Even if it was supported, lots of code likes to presume that doing someObject.GetType().GetMembers() returns the same thing over and over again.
As far as Roslyn is concerned, when we say the results are "immutable" we don't mean that puts any requirement on any IL that you might generate with it. Rather, when you ask Roslyn to parse something or analyze source code, the objects (syntax trees, type information, etc) is immutable. Still, it doesn't matter since you can't modify types in the CLR once they exist.
I'm with svick in his comment -- this isn't what you want to do. Use some appropriate data structures to represent your information at runtime, rather than trying to think of this as a concrete class that can be mutated somehow.

How do you set OptionSet Values in Microsoft CRM 2011, based on the text or label?

I am implementing a web service that receives information and needs to map them on the MS Dynamics CRM.
So, when it comes to setting OptionSet values, since I am not the one who implemented the CRM, I have no idea what indices are set up. All I know are the labels. Naturally so do the ones consuming my service. e.g. I call an Opportunity Warm or Cold, not 10033004 and 10033005. But I still need to set this value on the Opportunity entity.
I have found this link - but I think it's really overkill and if that's the only way I can access the OptionSet, then that's just sad.
Couple of options here.
Use the metadata services e.g. Your link, I agree this feels like a bit of an overkill, but you could add caching to reduce the overhead of multiple service calls. If you really don't know what the value is going to be at run time then this is probably the best way.
Just hard code it, if you know at compile time what the values will be then this is probably the quickest option. I've done this before and its usually fine. However this will obviously break if someone changes CRM.
Use the strongly typed classes, this is effectively hard coding just the system does it for you. However you will have regenerate them if CRM changes.
So none of these are a perfect option I'm afraid, but they all get the job done.
Edit
Re: option 3; I mean the early bound entities described here: http://msdn.microsoft.com/en-us/library/gg328210.aspx. I'm not sure how much they will help in this situation. They are strongly types classes which are used instead of the entity class. E.g. contact.firstname instead of entity["firstname"]. I suppose you might be able to use them as a form of metadata - never tried it myself though. Also it has the same problem as option 2, when CRM changes they need to be updated and then compiled.
In this case I'm veering towards option 1 and querying the metadata services, if you do this once and cache the results at the beginning of your process you will always have the most up to date information. This example shows how to get all the metadata in the system http://msdn.microsoft.com/en-us/library/jj603008.

ASP.NET MVC 3 Razor View Restrictions

I apologize in advance for the generic nature of my question, but I was unable to find any helpful advice from people trying to do the same thing as me on the web. Let me describe my scenario:
I am providing end users/designers of a website the ability to customize their views by storing the views (using Razor) in the database. I have all of this working, but my question is the following; From a security standpoint, how can I ensure and enforce that unwanted code doesn't get executed in the user-defined view? There are two basic approaches that I think will work conceptually, but am not sure which one is more possible or feasible.
Option 1: Create a validation method in the administration tool that allows the user to input the view code. This would need to either take a whitelist or blacklist approach to what is allowable or not.
Option 2: Prevent unwanted code from being able to execute when rendering of the view occurs.
As a quick example of something that would need to be blocked, we wouldn't want to allow access to read or write files, access any data access functions, or even access configuration settings, etc. in the web.config. There will likely be a decently-sized list of things that probably shouldn't be allowable, but I'll need to sit down and try to think of as many security-related concerns as possible.
My question then is, which method would be the best bet? Also, can any direction be provided on how to go about either? I thought I might be able to make trust-level based change which would be Option 2, but couldn't find any way to make that work in a per-view based manor (the administration code is allowed to execute whatever it wants). I'm thinking Option 1 will end up being the best bet and I'll have to check for the input of certain framework functions that shouldn't be allowed. Does anyone have any experience doing anything like what I'm trying to do? ANY feedback is much appreciated!
This would be extremely difficult.
You could run the the template through the Razor preprocessor, then use Roslyn (still in early beta) to parse the generated file and look through all method calls (or constructors) and return an error if it calls something you don't like.
I strongly recommend that you use a whitelist for that, since the .Net framework is big enough that you are bound to overlook something in a blacklist.
However, I would instead recommend that you not use Razor at all and instead use a templating engine that does not allow real C# code.

Categories