Why do I even need to Serialize in the first place? - c#

So, I'm working with the following assembly, which has the following defined (fairly harmless):
public class QueryDefinition
{
private List<QueryFilter> TheCurrentFilters = null;
public List<QueryFilter> CurrentFilters
{
set { TheCurrentFilters = value; }
get { return TheCurrentFilters; }
}
// other code
public class QueryFilter
{
// member variables are: seven public string's & two public int's
public override string ToString()
{
return FilterText;
}
}
}
Within another assembly, we have a UserControl:
public partial class QueryWizard : UserControl
{
private List<QueryDefinition.QueryFilter> TheCurrentFilters = null;
public List<QueryDefinition.QueryFilter> CurrentFilters
{
set { TheCurrentFilters = value; }
get { return TheCurrentFilters; }
}
// other code
}
Interesting code, but that's what I have to work with.
Anyhow, if I go to another project (that references this UserControl), create a Form, and then drop the control onto the Form, I get this error:
'System.Runtime.Serialization.SerializationException: Type QueryDefinition+QueryFilter' in Assembly ... is not marked as serializable.'
I'm not actually using any Serialization code, so what of this List of QueryFilter's is the reason for a SerializationException?
I have used the [Serializable] tag, to get rid of this. But recently we were rebuilding projects (Visual WebGUI upgrade) and now I run into the "unable to load type required for deserialization" issue. Instead of figuring out that problem, I decided to try and figure out why we need the Serialization tags in the first place! Thanks.

It is because the designer tries to serialize the contents of the usercontrols "CurrentFilters" property into the form initialization code.
Check the DesignerSerializationVisibility attribute: http://msdn.microsoft.com/en-us/library/system.componentmodel.designerserializationvisibility.aspx
If you don't intend to support designtime editing of the CurrentFilters property, setting it to hidden should fix the problem (I think, was ages since I built winforms controls)

The actual values for the CurrentFilters are getting serialized using BinaryFormatter and stored in a .resx file. You almost certainly don't want this to happen. For one, you'll take a dependency on the [AssemblyVersion] number of the assembly that contains your QueryFilter class. Which should explain the "unable to load type" exception you get now.
First find out how CurrentFilters ended up with values at design time. You'll need to beware of events that run at design time. The typical candidates are the constructor and the Load event. Use the Control.DesignTime property to prevent code from running.
Next, ensure that the property value doesn't get persisted by applying an attribute:
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public List<QueryFilter> CurrentFilters
{
}

Related

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

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?

How set value when the property has the getter method using reflection in c#

public class test
{
public test()
{
ting=10;
}
private int ting{get;set;}
public int tring
{
get
{
return ting;
}
}
}
void Main()
{
var t= new test();
//Below line giving error
Console.Write(t.GetType().GetProperty("tring").SetValue(t,20));
}
How to resolve this using reflection?
Well yes - the property can't be set. It's read-only, presumably deliberately.
If the designer of the class hasn't given you the opportunity of setting the value, you shouldn't be trying to set it. In many cases it would be impossible to do so, as the value may not even be backed by a field (think DateTime.Now) or may be computed some non-reversible way (as per Marcin's answer).
In this particular case if you were really devious you could get hold of the IL implementing tring.get, work out that it's fetching from the ting property, and then call that setter by reflection - but at that point you're going down a very dark path which you're almost certain to regret.
You can't do that, unless you know what is the backing field name. When you do, you can just set the field value, and it will reflect to property value.
Consider the situation when it would be possible and your property wouldn't be backed by a field (like that):
public string tring
{
get
{
return string.format("foo {0} foo", ting);
}
}
What should be desired output of setting that property?

PropertyGrid - Dynamically changing ReadOnlyAttribute

Sigh, another PropertyGrid question. I thought I could get around this until I ran into a problem where I couldn't actually avoid it.
I have a boolean property that sometimes needs to be read-only and sometimes needs to be changeable depending on the object selected from a TreeView.
My question is how can I change the ReadOnlyAttribute of a property dynamically? Obviously, creating a boolean variable and then trying to set it like ReadOnlyAttribute(boolVar) doesn't work and now I'm out of ideas.
The only solution I can think of is creating separate, near-identical classes for items where this property is writable and one for read-only, but this seems a bit unelegant to me.
Help? :)
You can provide dynamic information about the properties of a class to a property grid by implementing ICustomTypeDescriptor.
The property grid will call ICustomTypeDescriptor.GetProperties() and you return a collection of objects derived from PropertyDescriptors. In your implementation you can override the PropertyDescriptor.IsReadOnly property and implement your logic.
This is quite a bit of work in the first place, but it gives you the possibility to dynamically return a property name and description (helpful for localization), dynamically mark properties as read-only, dynamiclly show and hide properties, and do a lot of other usefull things.
What I would do is create a base class with a protected version the property, then create two classes that inherit the base class that have the readonly and the non-readonly bits.
You could try something along these lines to avoid the type conversion involved with multiple classes:
class TestClass
{
private bool isMyPropertyReadOnly;
public bool IsMyPropertyReadOnly
{
get { return isMyPropertyReadOnly; }
set { isMyPropertyReadOnly = value; }
}
private int myVar;
public int MyProperty
{
get { return myVar; }
set
{
if (isMyPropertyReadOnly)
{
throw new System.Exception("The MyProperty property is read-only.");
}
else
{
myVar = value;
}
}
}
}

More private than private? (C#)

Sometimes you have a private field that backs a property, you only ever want to set the field via the property setter so that additional processing can be done whenever the field changes. The problem is that it's still easy to accidentally bypass the property setter from within other methods of the same class and not notice that you've done so. Is there a way in C# to work around this or a general design principle to avoid it?
IMHO, it is not used, because:
The class must trust itself
If your class gets as large that one part does not know the other, it should be divided.
If the logic behind the property is slightly more complex, consider to encapsulate it in an own type.
I'd consider this a nasty hack and try to avoid it if possible, but...
You can mark the backing field as obsolete so that the compiler will generate a warning when you try to access it, and then suppress that warning for the property getter/setter.
The warning codes that you'd need to suppress are CS0612 for the plain Obsolete attribute and CS0618 if the attribute has a custom message.
[Obsolete("Please don't touch the backing field!")]
private int _backingField;
public int YourProperty
{
#pragma warning disable 612, 618
get { return _backingField; }
set { _backingField = value; }
#pragma warning restore 612, 618
}
There's no inbuilt way to do what you want to do, but by the sounds of things you need another layer of abstraction between your class and that value.
Create a separate class and put the item in there, then your outer class contains the new class, and you can only access it through its properties.
No, there isn't. I'd quite like this myself - something along the lines of:
public string Name
{
private string name; // Only accessible within the property
get { return name; /* Extra processing here */ }
set { name = value; /* Extra processing here */ }
}
I think I first suggested this about 5 years ago on the C# newsgroups... I don't expect to ever see it happen though.
There are various wrinkles to consider around serialization etc, but I still think it would be nice. I'd rather have automatically implemented readonly properties first though...
You CAN do this, by using a closure over a local in the constructor (or other initialisation function). But it requires significantly more work that the helper class approach.
class MyClass {
private Func<Foo> reallyPrivateFieldGetter;
private Action<Foo> reallyPrivateFieldSetter;
private Foo ReallyPrivateBackingFieldProperty {
get { return reallyPrivateFieldGetter(); }
set { reallyPrivateFieldSetter(value); }
}
public MyClass() {
Foo reallyPrivateField = 0;
reallyPrivateFieldGetter = () => { return reallyPrivateField; }
reallyPrivateFieldSetter = v => { reallyPrivateField = v; };
}
}
I suspect that the underlying field type Foo will need to be a reference class, so the two closures are created over the same object.
There is no such provisioning in C#.
However I would name private variables differently (e.g. m_something or just _something) so it is easier to spot it when it is used.
You can put all of your private fields into a nested class and expose them via public properties. Then within your class, you instantiate that nested class and use it. This way those private fields are not accessible as they would have been if they were part of your main class.
public class A
{
class FieldsForA
{
private int number;
public int Number
{
get
{
//TODO: Extra logic.
return number;
}
set
{
//TODO: Extra logic.
number = value;
}
}
}
FieldsForA fields = new FieldsForA();
public int Number
{
get{ return fields.Number;}
set{ fields.Number = value;}
}
}
It just provides a level of obstruction. The underlying problem of accessing private backing fields is still there within the nested class. However, the code within class A can't access those private fields of nested class FieldForA. It has to go through the public properties.
Perhaps a property backing store, similar to the way WPF stores properties?
So, you could have:
Dictionary<string,object> mPropertyBackingStore = new Dictionary<string,object> ();
public PropertyThing MyPropertyThing
{
get { return mPropertyBackingStore["MyPropertyThing"] as PropertyThing; }
set { mPropertyBackingStore["MyPropertyThing"] = value; }
}
You can do all the pre-processing you want now, safe in the knowledge that if anyone did access the variable directly, it would have been really really hard compared to the property accessor.
P.S. You may even be able to use the dependency property infrastructure from WPF...
P.P.S. This is obviously going to incur the cost of casting, but it depends on your needs - if performance is critical, perhaps this isn't the solution for you.
P.P.P.S Don't forget to initialise the backing store! (;
EDIT:
In fact, if you change the value property stored to a property storage object (using the Command pattern for example), you could do your processing in the command object...just a thought.
Can't do this in standard C#, however you could
define a custom attribute say OnlyAccessFromProperty
write your code like
[OnlyAccessFromProperty(Name)]
String name
Name
{
get{return name;}
}
etc …
Then write a custom rule for FxCop (or another checker)
Add FxCop to your build system so if your custom rule find an error the build is failed.
Do we need a set of standard custom rules/attributes to enforce common design patens like this without the need to extend C#
C# has no language feature for this. However, you can rely on naming conventions, similar to languages which have no private properties at all. Prefix your more private variable names with _p_, and you'll be pretty sure that you don't type it accidentally.
I don't know C# but in Java you may have a base class with only private instance variables and public setters and getters (should return a copy of the instance var.) and do all other in an inherited class.
A "general design principle" would be "use inheritance".
There is no build in solution in C#, but I think your problem can be solved by good OO design:
Each class should have a single purpose. So try to extract the logic around your field into a class as small as possible. This reduces the code where you can access the field by accident. If you do such errors by accident, your class is probably to big.
Often interface are good to restrict access to only a certain "subset" of an object. If that's appropriate for your case depends on your setting of course. More details about the work to be done would help to provide a better answer.
You say that you do additional processing. Presumably this would be detectable under the correct conditions. My solution, then, would be to create unit tests that implement conditions such that if the backing field is used directly the test will fail. Using these tests you should be able to ensure that your code correctly uses the property interface as long as the tests pass.
This has the benefit that you don't need to compromise your design. You get the safety of the unit tests to ensure that you don't accidently make breaking changes and you capture the understanding of how the class works so that others who come along later can read your tests as "documentation."
Wrap it in a class? The property thing is a bit like that anyway, associating data with methods - the "Encapsulation" they used to rave about...
class MyInt
{
private int n;
public static implicit operator MyInt(int v) // Set
{
MyInt tmp = new MyInt();
tmp.n = v;
return tmp;
}
public static implicit operator int(MyInt v) // Get
{
return v.n;
}
}
class MyClass
{
private MyInt myint;
public void func()
{
myint = 5;
myint.n = 2; // Can't do this.
myint = myint + 5 * 4; // Works just like an int.
}
}
I'm sure I'm missing something? It seems too normal...
BTW I do like the closures one, superbly mad.
My favorite solution to this (and what I follow) is to name private backing fields that are never intended to be used directly with a leading underscore, and private fields that are intended to be used without the underscore (but still lowercase).
I hate typing the underscore, so if I ever start to access a variable that starts with the underscore, I know somethings wrong - I'm not supposed to be directly accessing that variable. Obviously, this approach still doesn't ultimately stop you from accessing that field, but as you can see from the other answers, any approach that does is a work around and/or hardly practical.
Another benefit of using the underscore notation is that when you use the dropdown box to browse your class, it puts all of your private, never-to-be-used backing fields all in one place at the top of the list, instead of allowing them to be mixed in with their respective properties.
As a design practice, you could use a naming convention for "private properties" that's different from normal public members - for instance, using m_ItemName for private items instead of ItemName for public ones.
If you're using the C# 3.0 compiler you can define properties which have compiler-generated backing fields like this:
public int MyInt { get; set; }
That will mean there is only one way to access the property, sure it doesn't mean you can only access the field but it does mean that there's nothing but the property to access.
I agree with the general rule that the class should trust itself (and by inference anybody coding within the class).
It is a shame that the field is exposed via intellisense.
Sadly placing [EditorBrowsable(EditorBrowsableState.Never)] does not work within that class (or indeed the assembly(1))
In Visual C#, EditorBrowsableAttribute does not suppress members from a class in the same assembly.
If you really do wish to solve this aspect of it the the following class may be useful and makes the intent clear as well.
public sealed class TriggerField<T>
{
private T data;
///<summary>raised *after* the value changes, (old, new)</summary>
public event Action<T,T> OnSet;
public TriggerField() { }
///<summary>the initial value does NOT trigger the onSet</summary>
public TriggerField(T initial) { this.data=initial; }
public TriggerField(Action<T,T> onSet) { this.OnSet += onSet; }
///<summary>the initial value does NOT trigger the onSet</summary>
public TriggerField(Action<T,T> onSet, T initial) : this(onSet)
{
this.data=initial;
}
public T Value
{
get { return this.data;}
set
{
var old = this.data;
this.data = value;
if (this.OnSet != null)
this.OnSet(old, value);
}
}
}
Allowing you to (somewhat verbosely) use it like so:
public class Foo
{
private readonly TriggerField<string> flibble = new TriggerField<string>();
private int versionCount = 0;
public Foo()
{
flibble.OnSet += (old,current) => this.versionCount++;
}
public string Flibble
{
get { return this.flibble.Value; }
set { this.flibble.Value = value; }
}
}
alternatively you can go for a less verbose option but accessing Flibble is by the not idiomatic bar.Flibble.Value = "x"; which would be problematic in reflective scenarios
public class Bar
{
public readonly TriggerField<string> Flibble;
private int versionCount = 0;
public Bar()
{
Flibble = new TriggerField<string>((old,current) => this.versionCount++);
}
}
or solution if you look at the community content!
The new Lazy class in .net 4.0
provides support for several common
patterns of lazy initialization
In my experience this is the most common reason I wish to wrap a field in a private properly, so solves a common case nicely. (If you are not using .Net 4 yet you can just create your own “Lazy” class with the same API as the .Net 4 version.)
See this and this and this for details of using the Lazy class.
Use the "veryprivate" construct type
Example:
veryprivate void YourMethod()
{
// code here
}

Retrieve target element in CodeAccessSecurityAttribute

I realize you can't get the target entity in the Attribute itself, but what about in an associated Permission object when using a CodeAccessSecurityAttribute? The Permission object gets called at runtime so it seems there should be a way but I'm at a loss.
public sealed class MySecurityAttribute : CodeAccessSecurityAttribute
{
public override IPermission CreatePermission()
{
MySecurityPermission permission = new MySecurityPermission();
//set its properties
permission.Name = this.Name;
permission.Unrestricted = this.Unrestricted;
return permission;
}
}
public class MySecurityPermission : IPermission, IUnrestrictedPermission
{
public MySecurityPermission(PermissionState state)
{
// what method was the attribute decorating that
// created this MySecurityPermission?
}
public void Demand()
{
// Or here?
}
}
What about walking the call stack? At least that would narrow down what you need to reflect over. Grab System.Diagnostics.StackTrace and use GetFrame to get the stack frame one step up from where you are.
It's rather nasty though - CAS attributes really, in my opinion, shouldn't be conditional on what was decorated, rather they should depend on the conditions set in their parameters.
Well, I guess you could use reflection to scan through all the loaded assemblies, looking for any class/member that has this as an attribute. It'd be quite slow, though, so it's not something you'd want to do often, or in a large project.

Categories

Resources