How to introduce new property based on existing property and modify existing one?
Asked Answered
O

0

6

I am trying to automate this XmlSerializer workaround pattern. See update below.

Is it possible to introduce new property based on existing property and modify attributes of existing one using PostSharp (or maybe some other AOP tool) ?

It would be preferable to make this modification at build time.

Sample source property:

public class TestType {
  // Original version
  [XmlAttribute()]
  public DateTime ReqDateTime {
      get { return this.reqDateTimeField; }
      set { this.reqDateTimeField = value; }
  }
}

Desired result (class declaration omitted):

// Modified version
// <original property> = "ReqDateTime"
// <original property> marked as XmlIgnore
// New property with name "<original property>ForXml" is introduced with code as per below
// XmlAttribute moved to the newly introduced <original property>ForXml property with parameter "<original property>" 
[XmlIgnore()]
public DateTime ReqDateTime {
    get { return this.reqDateTimeField;}
    set { this.reqDateTimeField = value;}
}

[XmlAttribute("ReqDateTime")]
[EditorBrowsable(EditorBrowsableState.Never)]
public string ReqDateTimeForXml {
    get { return Common.GetAndFormatDate(this, Common.GetCaller()); }
    set { Common.ParseAndSetDate(this, value, Common.GetCaller()); }
}

I have found PostSharp tutorial on introducing members, but no information on (a) how to introduce members with dynamic names and (b) how to move attributes ([XmlAttribute] in my case) from existing member to the newly created one.

I do not need an exact solution - just some hints would be enough.


Update: From further research I can conclude that PostSharp does not support dynamic method naming. Also PostSharpIt cannot remove attribute from existing method.

So let me reword the problem in yet another approach to solve it:

1) Inject 10 new properties named IntroducedProperty0, IntroducedProperty1, ... This seems to be trivial. Properties are hardcoded.

2) Somehow after/with (1) add attribute [XmlAttribute("nameOftheOriginalProperty#N")] to the first M of the IntroducedPropertyN where N=0..9 and M<=N. This is kind of dynamic. This is possible when adding attributes to existing (not injected) members. However they say you cannot add attributes to injected members. Rest of the injected methods (from M to N) should be marked as [XmlIgnore].

3) Mark original methods of class with [XmlIgnore].

Maybe this is achievable with Fody?

Orphaorphan answered 1/6, 2017 at 16:23 Comment(2)
What is the problem behind your problem? Maybe a custom serializer, which proper formats DateTime would be an better aproach?Millsap
Yeah, writing custom serializer, custom xsd.exe and implemening related wcf would be a better approach. See my other question. The only problem is the amount of coding involved.Orphaorphan

© 2022 - 2024 — McMap. All rights reserved.