Using Generics in MEF-Context - c#

I want to use generics in combination with MEF-"[ImportMany(....))]", but I get compile-errors.
The following code without using generics works fine: The factory-class "HelperOneFactory" (see below) is searching für all implementations of the "IHelperOne"-interface. From this list it takes the first one without Metadata-value "Original". If it doesn't exist, it takes the first without checking the Metadata-value.
/// =====================================================================================
/// factory-implementation for interface-type "IHelperOne" (==> works fine)
/// =====================================================================================
[Export(typeof(HelperOneFactory))]
public class HelperOneFactory: IPartImportsSatisfiedNotification
{
[ImportMany(typeof(IHelperOne))]
private IEnumerable<Lazy<IHelperOne, Dictionary<string, object>>> Helper;
/// <summary>
/// reference to the relevant implementaion (HelperOneOriginal or HelperOneCusto)
/// </summary>
public IHelperOne Current { get; private set; }
/// <summary>
/// looking for all implementations of IHelperOne to find out the one to use
/// </summary>
public void OnImportsSatisfied()
{
Current = Helper.Count() > 1 ? Helper.First<Lazy<IHelperOne, Dictionary<string, object>>>(s => !s.Metadata.ContainsValue("Original")).Value :
Helper.First<Lazy<IHelperOne, Dictionary<string, object>>>().Value;
}
That works fine, but I have to implement factory-classes for many interface-types. So I try to use generics for the interface-type, but then I get compile-errors (using .NET Framework 4.6.1):
/// =====================================================================================
/// a version with using generic ==> compiler-errors !!
/// =====================================================================================
[Export(typeof(HelperTemplateFactory<>))]
public class HelperTemplateFactory<THelperInterface> : IPartImportsSatisfiedNotification
{
[ImportMany(typeof(THelperInterface))] // ==> ERROR: "Attribute argument cannot use type parameters"
[ImportMany(THelperInterface)] // ==> also ERROR: "Type parameter name is not valid at this point"
private IEnumerable<Lazy<THelperInterface, Dictionary<string, object>>> Helper;
...
Is it possible to use a generic type for the "ImportMany" command?
The context of the problem:
A "normal" class "HelperOneOriginal" is the Standard-version of the HelperOne and can be overwritten in Custom-Projects by defining a sub-class "HelperOneCustom", normaly placed in a separate VisualStudio-Project.
Both classes have the interface "IHelperOne".
The main-Program should use the Custom-class if defined, or otherwise the Original-class. The Original-class has the Metadata-Information "Orginal".
Therefore the "HelperOneFactory" looks for all realisations of "IHelperOne"-Interfaces and takes the first one without Metadata "Original".
If it doesn't exist it takes the Original-class. The reference to the relevant class ist stored inside the HelperClass in the member "Current" for using by the main-program.
If necessary a small test-project can be provided.

I suggest, I have to write an "answer" to mark the question als "resolved" =>
a line with only "[ImportMany]" is the solution!
Thanks to Dave M

Related

Instantiating class with NO constructor results in 'does not contain constructor which takes 0 arguments' error

I'm trying to instantiate a FacetResult from the Azure.Search.Documents library:
var facetResult = new Azure.Search.Documents.Models.FacetResult();
VS is telling me the class does not contain a constructor with zero arguments. When I check the metadata for the class - no constructor.
Looking at the docs for the class seems to confirm that there is no constructor - so what's the issue?
I'm having the same issue with other library classes with no constructors such as Azure.Storage.Blobs.Models.BlobItem, while classes which appear to explicitly declare a parameterless constructor seem fine, such as System.Exception
Any help with this would be much appreciated, it's blocking my unit tests!
Constructors for this class are internal.
Instances are likely created and returned by factories.
//src code # https://github.com/Azure/azure-sdk-for-net/
namespace Azure.Search.Documents.Models
{
/// <summary> A single bucket of a facet query result. Reports the number of documents with a field value falling within a particular range or having a particular value or interval. </summary>
public partial class FacetResult
{
/// <summary> Initializes a new instance of FacetResult. </summary>
internal FacetResult()
{
AdditionalProperties = new ChangeTrackingDictionary<string, object>();
}
/// <summary> Initializes a new instance of FacetResult. </summary>
/// <param name="count"> The approximate count of documents falling within the bucket described by this facet. </param>
/// <param name="additionalProperties"> Additional Properties. </param>
internal FacetResult(long? count, IReadOnlyDictionary<string, object> additionalProperties)
{
Count = count;
AdditionalProperties = additionalProperties;
}
https://github.com/Azure/azure-sdk-for-net/blob/4162f6fa2445b2127468b9cfd080f01c9da88eba/sdk/search/Azure.Search.Documents/src/Generated/Models/FacetResult.cs

How to create a generic class that can take many parameters

Okay, so I am creating a Utility AI framework. For this to work I need a class that can change a lot depending on the situation I am sure, and I hope that there is a way to use polymorphism or some sort of design pattern to solve my issue.
Let me show you what I mean
I have an action for the sake of example let's say I have the following action Attack Target
This action can have a number of considerations that will vary a lot but all implement the same interface:
public interface IConsideration
{
/// <summary>
/// A unique named identifier for this consideration.
/// </summary>
string NameId { get; }
/// <summary>
/// The weight of this consideration.
/// </summary>
float Weight { get; set; }
/// <summary>
/// If true, then the output of the associated evaluator is inverted, in effect, inverting the
/// consideration.
/// </summary>
bool IsInverted { get; set; }
/// <summary>Calculates the utility given the specified context.</summary>
/// <param name="context">The context.</param>
/// <param name="value"></param>
/// <returns>The utility.</returns>
float Consider<T>(BaseAiContext context, T value);
}
The above is my current implementation it doesn't really solve the issue I have
As you can see the "most" important method of this interface is the Consider
and here lies the issue preferably I should be able to pass data to this class in a way that I can control.
For the sake of example let's say one consideration I have is Move To Location here I want to send the following parameters:
Location of target
Weapon type (ranged / melee)
location list
The above is just an example to prove my point. There is another issue with this - how can I pass the correct parameters when I finally have them? say that I have the following code:
public List<IConsideration> considerations;
float targetDistance = 2;
for (int i = 0; i < considerations.Count; i++)
{
float AxisScore = considerations[i].Consider(BaseAiContext,targetDistance );
}
Since I have to use the Interface type I am unable to know exactly which values to parse as parameters.
To sum it up:
How can i "parameterize" my class in a generic way?
How can I distinguish these parameterizations so I can provide a consideration with the correct values?
As #MarcRasmussen requested an example
As each implementation of your interface might consume different sets of arguments one way to solve it would be to kind of have key-value storage like a dictionary.
There are plenty of improvements to be made like, using ENUMS instead of strings, and having a static manager class for things like that to add/modify/remove settings.
This is a quick example and not tested, with the information available.
public class MoveToTarget : IConsideration
{
//method is changed to have generic return type and accept dictionary for settings
float Consider(BaseAiContext context, Dictionary<string,object> settings){
//make sure required keys exist
if(!settings.ContainsKey("DESTINATION"))
throw new ApplicationException("Missing key DESTINATION");
if(!settings.ContainsKey("SPEED"))
throw new ApplicationException("Missing key SPEED");
// retrieve you required settings, at this stage since you cast an object, you should check the type ... this problem would be solved if you have (as further below mentioned) a specific settings class for all your implementations. this way you ensure type safety too.
Point destination = (Point)settings["DESTINATION"];
float speed = (float)settings["SPEED"];
// and perform whatever logic you need. etc.
}
}
public List<IConsideration> considerations;
//this should be probably static and globally available (?) probably better to have a singleton manager class to deal with that.
Dictionary<string,object> Settings = new Dictionary<string,object>()
{
{"SPEED", 1.0f},
{"RANDOM", new Random()},
{"DESTINATION", new Point()},
{"XYZ", "XYZ"},
//etc.
}
//use foreach unless you need to have access to the index
foreach(var consideration in considerations)
{
float AxisScore = consideration.Consider(BaseAiContext, Settings);
}
some other improvements could be to have a specific settings class for each of your implementations like MoveToTargetSettings and then instead of havin ambiguous "KEYS" in a dictionary you can retrieve the specific settings by its class etc. like var settings = settingDictionary["MoveToTargetSettins"] as MoveToTargetSettings
I think for anything better more details are required, happy to discuss and answer any further questions outside of SO as that will be off-topic :)

How to manage classes from a loaded DLL?

How can I get a class into a variable to call function and get properties?
I have been told to look into reflection but I don't get how it's done when the DLL was not known at compile time.
To be clear: I have a 'main' class which loads an DLL and I want to create an instance of a class within the DLL and directly get properties.
You should do something like this:
Assembly asm = Assembly.Load("DLL File Path"); //load DLL from file
Type t = asm.GetType("Test.ExternalDllTest"); //fully qualified name
dynamic oDynamic = Activator.CreateInstance(t, args);//create an instance of specified type, and assign it to DYNAMIC object
EDIT
oDynamic.SomeMethod(); //call the method of your type. Being DYNAMIC it will route the call to correct method.
Naturally, the DLL has to be a managed DLL (so written in .NET language)
I didn't compile this, honestly, but basically this is an idea of how to do that.
Here also an example, that may help.
In case you are talking about another .NET dll you can use this to load the assembly and get all the types in there:
var asm = Assembly.LoadFile("yourassembly.dll");
foreach (var t in asm.GetTypes())
{
Console.WriteLine("Type: {0}", t.Name);
}
You can instantiate an object with either the Activator:
Activator.CreateInstance(t, additional arguments);
or you can get a list of all public constructors for that type with GetConstructors:
var constructors = t.GetConstructors();
However unless you know what type you are looking for and what its constructor parameters are it is a bit pointless to try to instatiate and use it.
Example. Here is a method I use that searches a plug-in directory tree and returns a list of WPF ValueConverter classes...
private static List<IValueConverter> GetValueConverters( string rootDirectoryName)
{
List<IValueConverter> result = new List<IValueConverter>();
string[] exts = new string[]{"*.exe", "*.dll"};
DirectoryInfo di = new DirectoryInfo(rootDirectoryName);
foreach(string ext in exts)
{
foreach(FileInfo fi in (di.GetFiles(ext, SearchOption.AllDirectories)))
{
Assembly a = Assembly.LoadFrom(fi.FullName);
try
{
List<Type> ts = a.GetExportedTypes().ToList();
foreach (Type t in ts)
{
var d2 = t.GetInterfaces().Where(q => q.Name == "IValueConverter");
if (d2.Count() > 0)
{
result.Add(Activator.CreateInstance(t) as IValueConverter);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
return result;
}
The code searches through the directory tree for files matching 'dll' and 'exe'. When it finds one, it attempts to load it and then looks to see if there's any WPF ValueConverters in it.
If it finds one, the code creates an instances and adds it to the list, and ultimately returns the list. Of course the 'dll's' and 'exe's' must be in the managed world. And if you were interested in classes other than ValueConverters, you would have to change it accordingly.
This is a purpose built method (i.e., I know what's going to happen with the result) and the code is given here only as an example...
Write your self an Interface (IKnowAboutSomething) that is accessible via your Loaded DLL and also your Loading Program.
Scan through your Loaded DLL and find the classes which implement this interface.
Then you can use Activator.CreateInstance to create an instance of the Types you found (where you know the interface)
Now you just call methods on your IKnowAboutSomething.GetThingINeed() etc and you can interact with things you don't know about at compile time. (Well you know a little bit because they are using the Interface and therefore have an agreement)
Place this code in an External DLL (eg Core.Dll) that is accessible by both projects.
using System.IO;
public interface ISettings
{
/// <summary>
/// Will be called after you Setup has executed if it returns True for a save to be performed. You are given a Stream to write your data to.
/// </summary>
/// <param name="s"></param>
/// <remarks></remarks>
void Save(Stream s);
/// <summary>
/// Will be called before your Setup Method is to enable the loading of existing settings. If there is no previous configuration this method will NOT be called
/// </summary>
/// <param name="s"></param>
/// <remarks></remarks>
void Load(Stream s);
/// <summary>
/// Your plugin must setup a GUID that is unique for your project. The Main Program will check this and if it is duplicated your DLL will not load
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
Guid Identifier { get; }
/// <summary>
/// This Description will be displayed for the user to select your Plugin. You should make this descriptive so the correct one is selected in the event they have multiple plugins active.
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
string Description { get; }
}
Now in your Main Project add a Reference to the above DLL.
In your main project scan a directory for the DLL's you are planning to load (c:\myDlls*.dll) use a DirectoryInfo (or similar) to scan.
Once you have found a DLL, use the Assembly asm = Assembly.LoadFrom(filename) to get it loaded.
Now you can do this in the main project.
foreach (Type t in asm.GetTypes())
{
if (typeof(ISettings).IsAssignableFrom(t))
{
//Found a Class that is usable
ISettings loadedSetting = Activator.CreateInstance(t);
Console.WriteLine(loadedSetting.Description);
}
}

WCF service proxy not setting "FieldSpecified" property

I've got a WCF DataContract that looks like the following:
namespace MyCompanyName.Services.Wcf
{
[DataContract(Namespace = "http://mycompanyname/services/wcf")]
[Serializable]
public class DataContractBase
{
[DataMember]
public DateTime EditDate { get; set; }
// code omitted for brevity...
}
}
When I add a reference to this service in Visual Studio, this proxy code is generated:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.3082")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://mycompanyname/services/wcf")]
public partial class DataContractBase : object, System.ComponentModel.INotifyPropertyChanged {
private System.DateTime editDateField;
private bool editDateFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=0)]
public System.DateTime EditDate {
get {
return this.editDateField;
}
set {
this.editDateField = value;
this.RaisePropertyChanged("EditDate");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool EditDateSpecified {
get {
return this.editDateFieldSpecified;
}
set {
this.editDateFieldSpecified = value;
this.RaisePropertyChanged("EditDateSpecified");
}
}
// code omitted for brevity...
}
As you can see, besides generating a backing property for EditDate, an additional <propertyname>Specified property is generated. All good, except that when I do the following:
DataContractBase myDataContract = new DataContractBase();
myDataContract.EditDate = DateTime.Now;
new MyServiceClient.Update(new UpdateRequest(myDataContract));
the EditDate was not getting picked up by the endpoint of the service (does not appear in the transmitted XML).
I debugged the code and found that, although I was setting EditDate, the EditDateSpecified property wasn't being set to true as I would expect; hence, the XML serializer was ignoring the value of EditDate, even though it's set to a valid value.
As a quick hack I modified the EditDate property to look like the following:
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=0)]
public System.DateTime EditDate {
get {
return this.editDateField;
}
set {
this.editDateField = value;
// hackhackhack
if (value != default(System.DateTime))
{
this.EditDateSpecified = true;
}
// end hackhackhack
this.RaisePropertyChanged("EditDate");
}
}
Now the code works as expected, but of course every time I re-generate the proxy, my modifications are lost. I could change the calling code to the following:
DataContractBase myDataContract = new DataContractBase();
myDataContract.EditDate = DateTime.Now;
myDataContract.EditDateSpecified = true;
new MyServiceClient.Update(new UpdateRequest(myDataContract));
but that also seems like a hack-ish waste of time.
So finally, my question: does anyone have a suggestion on how to get past this unintuitive (and IMO broken) behavior of the Visual Studio service proxy generator, or am I simply missing something?
It might be a bit unintuitive (and caught me off guard and reeling, too!) - but it's the only proper way to handle elements that might or might not be specified in your XML schema.
And it also might seem counter-intuitive that you have to set the xyzSpecified flag yourself - but ultimately, this gives you more control, and WCF is all about the Four Tenets of SOA of being very explicit and clear about your intentions.
So basically - that's the way it is, get used to it :-) There's no way "past" this behavior - it's the way the WCF system was designed, and for good reason, too.
What you always can do is catch and handle the this.RaisePropertyChanged("EditDate"); event and set the EditDateSpecified flag in an event handler for that event.
try this
[DataMember(IsRequired=true)]
public DateTime EditDate { get; set; }
This should omit the EditDateSpecified property since the field is specified as required
Rather than change the setters of the autogenerated code, you can use an extension class to 'autospecify' (bind the change handler event). This could have two implementations -- a "lazy" one (Autospecify) using reflection to look for fieldSpecified based on the property name, rather than listing them all out for each class in some sort of switch statement like Autonotify:
Lazy
public static class PropertySpecifiedExtensions
{
private const string SPECIFIED_SUFFIX = "Specified";
/// <summary>
/// Bind the <see cref="INotifyPropertyChanged.PropertyChanged"/> handler to automatically set any xxxSpecified fields when a property is changed. "Lazy" via reflection.
/// </summary>
/// <param name="entity">the entity to bind the autospecify event to</param>
/// <param name="specifiedSuffix">optionally specify a suffix for the Specified property to set as true on changes</param>
/// <param name="specifiedPrefix">optionally specify a prefix for the Specified property to set as true on changes</param>
public static void Autospecify(this INotifyPropertyChanged entity, string specifiedSuffix = SPECIFIED_SUFFIX, string specifiedPrefix = null)
{
entity.PropertyChanged += (me, e) =>
{
foreach (var pi in me.GetType().GetProperties().Where(o => o.Name == specifiedPrefix + e.PropertyName + specifiedSuffix))
{
pi.SetValue(me, true, BindingFlags.SetField | BindingFlags.SetProperty, null, null, null);
}
};
}
/// <summary>
/// Create a new entity and <see cref="Autospecify"/> its properties when changed
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="specifiedSuffix"></param>
/// <param name="specifiedPrefix"></param>
/// <returns></returns>
public static T Create<T>(string specifiedSuffix = SPECIFIED_SUFFIX, string specifiedPrefix = null) where T : INotifyPropertyChanged, new()
{
var ret = new T();
ret.Autospecify(specifiedSuffix, specifiedPrefix);
return ret;
}
}
This simplifies writing convenience factory methods like:
public partial class MyRandomClass
{
/// <summary>
/// Create a new empty instance and <see cref="PropertySpecifiedExtensions.Autospecify"/> its properties when changed
/// </summary>
/// <returns></returns>
public static MyRandomClass Create()
{
return PropertySpecifiedExtensions.Create<MyRandomClass>();
}
}
A downside (other than reflection, meh) is that you have to use the factory method to instantiate your classes or use .Autospecify before (?) you make any changes to properties with specifiers.
No Reflection
If you don't like reflection, you could define another extension class + interface:
public static class PropertySpecifiedExtensions2
{
/// <summary>
/// Bind the <see cref="INotifyPropertyChanged.PropertyChanged"/> handler to automatically call each class's <see cref="IAutoNotifyPropertyChanged.Autonotify"/> method on the property name.
/// </summary>
/// <param name="entity">the entity to bind the autospecify event to</param>
public static void Autonotify(this IAutoNotifyPropertyChanged entity)
{
entity.PropertyChanged += (me, e) => ((IAutoNotifyPropertyChanged)me).WhenPropertyChanges(e.PropertyName);
}
/// <summary>
/// Create a new entity and <see cref="Autonotify"/> it's properties when changed
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T Create<T>() where T : IAutoNotifyPropertyChanged, new()
{
var ret = new T();
ret.Autonotify();
return ret;
}
}
/// <summary>
/// Used by <see cref="PropertySpecifiedExtensions.Autonotify"/> to standardize implementation behavior
/// </summary>
public interface IAutoNotifyPropertyChanged : INotifyPropertyChanged
{
void WhenPropertyChanges(string propertyName);
}
And then each class themselves defines the behavior:
public partial class MyRandomClass: IAutoNotifyPropertyChanged
{
public void WhenPropertyChanges(string propertyName)
{
switch (propertyName)
{
case "field1": this.field1Specified = true; return;
// etc
}
}
}
The downside to this is, of course, magic strings for property names making refactoring difficult, which you could get around with Expression parsing?
Further information
On the MSDN here
In her answer, Shreesha explains that:
"Specified" fields are only generated on optional parameters that are structs. (int, datetime, decimal etc). All such variables will have additional variable generated with the name Specified.
This is a way of knowing if a parameter is really passed between the client and the server.
To elaborate, an optional integer, if not passed, would still have the dafault value of 0. How do you differentiate between this and the one that was actually passed with a value 0 ? The "specified" field lets you know if the optional integer is passed or not. If the "specified" field is false, the value is not passed across. If it true, the integer is passed.
so essentially, the only way to have these fields set is to set them manually, and if they aren't set to true for a field that has been set, then that field will be missed out in the SOAP message of the web-service call.
What I did in the end was build a method to loop through all the members of the object, and if the property has been set, and if there is a property called name _Specified then set that to true.
Ian,
Please ignore my previous answers, was explaining how to suck eggs. I've voted to delete them.
Could you tell me which version of Visual Studio you're using, please?
In VS2005 client - in the generated code, I get the <property>Specified flags, but no event raised on change of values. To pass data I have to set the <property>Specified flag.
In Visual Web Developer 2008 Express client - in the generated code, I get no <property>Specified flags, but I do get the event on change of value.
Seems to me that this functionality has evolved and the Web Dev 2008 is closer to what you're after and is more intuitive, in that you don't need to set flags once you've set a value.
Bowthy
Here's a simple project that can modify the setters in generated WCF code for optional properties to automatically set the *Specified flags to true when setting the related value.
https://github.com/b9chris/WcfClean
Obviously there are situations where you want manual control over the *Specified flag so I'm not recommending it to everyone, but in most simple use cases the *Specified flags are just an extra nuisance and automatically setting them saves time, and is often more intuitive.
Note that Mustafa Magdy's comment on another answer here will solve this for you IF you control the Web Service publication point. However, I usually don't control the Web Service publication and am just consuming one, and have to cope with the *Specified flags in some simple software where I'd like this automated. Thus this tool.
Change proxy class properties to nullable type
ex :
bool? confirmed
DateTime? checkDate

Obsolete attribute causes property to be ignored by XmlSerialization

I'm refactoring some objects that are serialized to XML but need to keep a few properties for backwards compatibility, I've got a method that converts the old object into the new one for me and nulls the obsolete property. I want to use the Obsolete attribute to tell other developers not to use this property but it is causing the property to be ignored by the XmlSerializer.
Similar Code:
[Serializable]
public class MySerializableObject
{
private MyObject _oldObject;
private MyObject _anotherOldObject;
private MyObject _newBetterObject;
[Obsolete("Use new properties in NewBetterObject to prevent duplication")]
public MyObject OldObject
{
get { return _oldObject; }
set { _oldObject = value; }
}
[Obsolete("Use new properties in NewBetterObject to prevent duplication")]
public MyObject AnotherOldObject
{
get { return _anotherOldObject; }
set { _anotherOldObject = value; }
}
public MyObject NewBetterObject
{
get { return _anotherOldObject; }
set { _anotherOldObject = value; }
}
}
Any ideas on a workaround? My best solution is to write obsolete in the XML comments...
Update: I'm using .NET 2.0
EDIT: After reading a MS Connect article, it appears that .Net 2.0 has a 'feature' where it makes ObsoleteAttribute equivalent to XmlIgnoreAttribute without any notification in the documentation. So I'm going to revise my answer to say that the only way to have your cake and eat it too in this instance is to follow #Will's advice and implement serialization manually. This will be your only future proof way of including Obsolete properties in your XML. It is not pretty in .Net 2.0, but .Net 3.0+ can make life easier.
From XmlSerializer:
Objects marked with the Obsolete Attribute no longer serialized
In the .NET Framework 3.5 the XmlSerializer class no longer serializes objects that are marked as [Obsolete].
Another workaround is to subscribe to XmlSerializer.UnknownElement, when creating the serializer for the datatype, and then fix old data that way.
http://weblogs.asp.net/psteele/archive/2011/01/31/xml-serialization-and-the-obsolete-attribute.aspx
Maybe consider to have the method for subscribing as a static method on the class for datatype.
static void serializer_UnknownElement(object sender, XmlElementEventArgs e)
{
if( e.Element.Name != "Hobbies")
{
return;
}
var target = (MyData) e.ObjectBeingDeserialized;
foreach(XmlElement hobby in e.Element.ChildNodes)
{
target.Hobbies.Add(hobby.InnerText);
target.HobbyData.Add(new Hobby{Name = hobby.InnerText});
}
}
I have struggled with this a lot - there is no solution other than doing serialization manually or using another serializer.
However, instead of writing shims for each obsolete property which quickly becomes a pain, you could consider adding an Obsolete prefix to property names (e.g. Foo becomes ObsoleteFoo. This will not generate a compiler warning like the attribute will, but at least it's visible in code.
1) WAG: Try adding the XmlAttributeAttribute to the property; perhaps this will override the ObsoleteAttribute
2) PITA: Implement IXmlSerializable
Yes I agree with marking things with the name "Obsolete" we do this with Enum values
/// <summary>
/// Determines the swap file location for a cluster.
/// </summary>
/// <remarks>This enum contains the original text based values for backwards compatibility with versions previous to "8.1".</remarks>
public enum VMwareClusterSwapFileLocation
{
/// <summary>
/// The swap file location is unknown.
/// </summary>
Unknown = 0,
/// <summary>
/// The swap file is stored in the virtual machine directory.
/// </summary>
VmDirectory = 1,
/// <summary>
/// The swap file is stored in the datastore specified by the host.
/// </summary>
HostLocal = 2,
/// <summary>
/// The swap file is stored in the virtual machine directory. This value is obsolete and used for backwards compatibility.
/// </summary>
[XmlElement("vmDirectory")]
ObseleteVmDirectory = 3,
/// <summary>
/// The swap file is stored in the datastore specified by the host. This value is obsolete and used for backwards compatibility.
/// </summary>
[XmlElement("hostLocal")]
ObseleteHostLocal = 4,
}
You may try the following workaround:
add a method named
ShouldSerializeOldObject ()
{
return true;
}
ShouldSerializeAnotherOldObject ()
{
return true
}
this may override the obsolete Attribute

Categories