MEF and WPF custom import definition - wpf

I have this idea to try to use a custom IMPORT attribute to new up a class based on a condition. For example, if I have:
[Import("Position_32")] this should exist if I'm running a 32bit OS, and then:
[Import("Position_64")] if Im running a 64 bit OS. Is there any way to make the type name for the attribute dynamic based on a condition?
Conceptually it could look like this:
[Import(((IsWIN64()) ? "Position_64" : "Position_32"))] This doesn't work because the type name needs to be a constant.
I want to make the newing up of the proper position class as transparent as possible. I mean I did a factory based method using funcs to get my desired effect but I'd love to use MEF for this. Ideas?
THanks much,
David

You could use ExportMetadataAttribute like so:
[Import("Position")]
[ExportMetadata("Platform", "32bit")]
public YourType ...
Then, when you go to import, use:
[ImportMany]
public Lazy<YourType,IDictionary<string,object>>[] Positions { get; set; }
You can then check the Dictionary for the appropriate metadata, and use that specific platform, at runtime.
In addition, you can make a custom interface for strongly typed metadata (instead of strings). For details, see Exports and Metadata.

Related

How to convert one object present in one dll to same object of another dll?

I have two dlls that are dllA and dllB.
I have same object in both the dlls mentioned as below.
class OrderObect
{
public string firstName {get;set;}
public string lastName {get;set;}
}
I am sending the List from dllA to dllB.
I am getting one exception that is Cannot convert list of dllA.OrderObject to list of dllB.OrderObject.
So how to solve that, Thank you :)
Why duplicating those classes? Whatever, if properties name are the same, you could use reflection and loop through properties to copy values from one to other.
Look to this post to know how to achieve this : here
As Creep says if the properties are the same in both then you can use reflection. A slightly easier way if to use something like express mapper to do the mapping for you

Visual Studio - naming forms

this might be a very very basic question, but what is the best way to name my forms?
I mean, can I use spaces or will that give me problems later on?
Example
Should I use "Logged on Popup" or "Logged_on_Popup"?
Thanks!
Don't use spaces. Or Underscores. Microsoft do have some naming conventions that they recommend. Whilst they don't specifically have any recommendations re: form naming, they may be quite a good read:
Do favor readability over brevity. The property name CanScrollHorizontally is better than ScrollableX (an obscure reference to the X-axis).
Do not use underscores, hyphens, or any other nonalphanumeric characters.
Also, bear in mind that the name used in your code isn't exposed to the end users - whereas the captions of your forms are - make sure that those captions are well chosen.
Since Forms are also classes, you should follow the Class Namings:
Use a noun or noun phrase to name a class.
Use Pascal case.
Use abbreviations sparingly.
Do not use a type prefix, such as C for class, on a class name. For example, use the class name FileStream rather than CFileStream.
Do not use the underscore character (_).
Occasionally, it is necessary to provide a class name that begins with the letter I, even though the class is not an interface. This is appropriate as long as I is the first letter of an entire word that is a part of the class name. For example, the class name IdentityStore is appropriate.
Where appropriate, use a compound word to name a derived class. The second part of the derived class's name should be the name of the base class. For example, ApplicationException is an appropriate name for a class derived from a class named Exception, because ApplicationException is a kind of Exception. Use reasonable judgment in applying this rule. For example, Button is an appropriate name for a class derived from Control. Although a button is a kind of control, making Control a part of the class name would lengthen the name unnecessarily.
So Log On Popup is invalid and Log_On_Popup should be valid from a compiler perspective, but not from the class naming guidelines. I should opt for LogOnPopup. Where some people like to add a suffix to it LogOnPopupForm.
public partial class LoggedOnPopupForm
In component name you can use spaces but I don't recommend doing it
Simple,
You can use log_on_popup
If your doubt is how to name it then, When your Form designer is open, open the properties window (If properties window is not there, just right click on the form and select properties), In properties , You will find (Name) just type there log_on_popup :)

Creating new Instance of the window by string Type

Camarades,
I have a WindowForm application and that contains multiple forms, each with a specific name. Well, I wanted to develop a class that manages the creation of these windows, where, through the parameter type of screen (her name), the system create one for me...
I'm thinking in the property "AcessibleName" in the MenuItem, put the name of the class that I want. Then to click on each item, the system performs the following verification
private void mnMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
try
{
if (!String.IsNullOrEmpty(((MenuStrip)sender).AccessibleName))
{
string[] _Parametros = ((MenuStrip)sender).AccessibleName.Split(uConstantes.CtSeparadorMenu);
uMenu.CreateWindow(((MenuStrip)sender).AccessibleName, _Parametros);
}
}
catch (uException __Excp)
{
throw __Excp;
}
}
uMenu.CreateWindow and within the class, I would receive the parameters and instantiate a new object, and display it. Does anyone have any idea? Reflection solves this problem? (Unfortunately I do not know much about reflection)
Thanks
I would look at the Activator.CreateInstance method to do specifically what you're asking for.
However, I'm inclined to ask if it's even necessary (based on the information you've provided.) Let's say that you have a menu that contains 3 items. When the user clicks on MenuItem1, they're presented with Form1. Likewise, MenuItem2->Form2 and MenuItem3->Form3. Why wouldn't you just launch the forms directly? What benefit is this providing you?
Actually, I was doing something wrong. I need to put the name of the Window, including its full path (namespace). Then, the command will work, and the type will be identified.
Thank you all.

Change Default Winform Icon Across Entire App

Can I change the default icon used on a Winform?
Most of my forms have their icon property set to a custom icon. For the few forms that slip through the cracks, I don't want the generic "hey look, he made this in visual studio" icon.
One solution is to tediously check every one of my forms to make sure they either have a custom icon set or have ShowIcon set to False.
Another solution is to have every one of my forms inherit from a base class that sets a custom icon in the constructor.
Aside from those solutions, what other options do I have?
EDIT:
I was hoping there would be a way to replace the source of the stock icon with my own. Is it in a resource file somewhere? Or is it embedded in a .NET dll that I can't (or really, really shouldn't) modify?
BOUNTY EDIT:
Is there a way to accomplish this without editing or writing a single line of code? I don't care how impractical, complicated, waste-of-time the solution is... I just want to know if it's possible. I need to satisfy my curiosity.
The default icon is embedded in the winforms dll - looking at reflector (DefaultIcon) it is:
defaultIcon = new Icon(typeof(Form), "wfc.ico");
There is no magic in there that checks another common location, so you can't do it without changing code.
You could always embrace the forces of darkness with field-based reflection? Note: this is hacky and brittle. On your own head! But it works:
[STAThread]
static void Main() {
// pure evil
typeof(Form).GetField("defaultIcon",
BindingFlags.NonPublic | BindingFlags.Static)
.SetValue(null, SystemIcons.Shield);
// all forms now default to a shield
using (Form form = new Form()) {
Application.Run(form);
}
}
To do it properly; two common options;
a base Form class which has the icon set
a factory Form method - perhaps something like:
code:
public static T CreateForm<T>() where T : Form, new() {
T frm = new T();
frm.Icon = ...
// any other common code
return frm;
}
Then instead of:
using(var frm = new MySpecificForm()) {
// common init code
}
Something like:
using(var frm = Utils.CreateForm<MySpecificForm>()) {
}
Of course - that isn't much prettier! Another option might be a C# 3.0 extension method, perhaps as a fluent API:
public static T CommonInit<T>(this T form) where T : Form {
if(form != null) {
form.Icon = ...
//etc
}
return form;
}
and
using(var frm = new MySpecificForm().CommonInit()) {
// ready to use
}
This is then just a .CommonInit() away from your existing code.
The base class option is the one that we use.
If you are looking for an alternative (not necessarily good ones), you could:
1. Use IOC to instantiate all of your forms and modify the IOC container to set the application icon.
2. Use AOP to insert code into all of the forms that sets the application icon.
Personally, I'd just use the base class...
My useful answer:
No
Would be a nice feature for microsoft to implement though, since most apps use the same icon across the entire application.
If you want to update all the icons by another one, you can build a small app that edits all the *.Designer.vb files (in vb.net) and adding the folowing line to InitializeComponent:
Me.Icon = New System.Drawing.Icon("C:\PathTo\icon.ico")
Hope it helps.
If all your forms are in just one project then you can take the dll of the project and use reflection to get every type in the dll. If the type derives from Form you can set the type's Icon property to whatever you want. I am not sure what the performance overhead will be if the project is very big.

Castle ValidateEmail Attribute fails on plus sign

I am using Castle Validators on my model. I have an EmailAddress property defined like so:
[ValidateEmail]
public string EmailAddress { get; set; }
The problem is that the regex (?) that the ValidateEmail attribute uses is incorrect. For instance, if I put in an email address like foo#foo.com, it validates correctly, but if I put in an address like foo+1#foo.com, it says it is not valid.
I realize that I can just use the ValidateRegExp attribute with my own regex, but if possible, I'd prefer to use what's already built in to the system.
So is there some way to "fix" the ValidateEmail attribute?
Please get the latest build from the build server, this was fixed a couple of weeks ago.
Given that the Castle project is open-source, grab the source and fix it yourself. Then submit the patch back to the project.
The project maintainers will appreciate it (normally; YMMV) and the project gets stronger.

Resources