Mixing custom and basic serialization? - c#

I've got a class with well over 100 properties (it's a database mapping class) and one of the properties has to be in a method. In other words this data is not exposed via a property but via methods:
"ABCType GetABC(), SetABC(ABCType value)"
It's all very un-C#-like. I shudder when I see it.
The class needs to be serializable so it can be sent over web services, and the data exposed by the Get/Set methods needs to be serialized too. (It's in a method because of a strange thing the grid I'm using does with reflection; it can't handle objects that contain properties of the same type as the containing object. The problem property stores the original state of the database object in case a revert is required. Inefficient implementation, yes - but I'm unable to re-engineer it.)
My question is this: since only this 1 field needs custom serialization code, I'd like to use custom serialization only for calling GetABC and SetABC, reverting to basic XML serialization for the rest of the class. It'll minimize potential for bugs in my serialization code. Is there a way?

The first thing I'd try is adding a property for serialization, but hiding it from the UI:
[Browsable(false)] // hide in UI
public SomeType ABC {
get {return GetABC();}
set {SetABC(value);}
}
You can't really mix and match serialization unfortunately; once you implement IXmlSerializable, you own everything. If you were using WCF, then DataContractSerialier supports non-public properties for serialization, so you could use:
[DataMember]
private SomeType ABC {
get {return GetABC();}
set {SetABC(value);}
}
but this doesn't apply for "asmx" web-services via XmlSerializer.
Does the [Browsable] trick work at all? Assuming the custom grid uses TypeDescriptor, another option might be to hide it via ICustomTypeDescriptor, but that is a lot of work just to hide a property...

Related

Scope of class variables in C# [duplicate]

First off, I have read through a list of postings on this topic and I don't feel I have grasped properties because of what I had come to understand about encapsulation and field modifiers (private, public..ect).
One of the main aspects of C# that I have come to learn is the importance of data protection within your code by the use of encapsulation. I 'thought' I understood that to be because of the ability of the use of the modifiers (private, public, internal, protected). However, after learning about properties I am sort of torn in understanding not only properties uses, but the overall importance/ability of data protection (what I understood as encapsulation) within C#.
To be more specific, everything I have read when I got to properties in C# is that you should try to use them in place of fields when you can because of:
1) they allow you to change the data type when you can't when directly accessing the field directly.
2) they add a level of protection to data access
However, from what I 'thought' I had come to know about the use of field modifiers did #2, it seemed to me that properties just generated additional code unless you had some reason to change the type (#1) - because you are (more or less) creating hidden methods to access fields as opposed to directly.
Then there is the whole modifiers being able to be added to Properties which further complicates my understanding for the need of properties to access data.
I have read a number of chapters from different writers on "properties" and none have really explained a good understanding of properties vs. fields vs. encapsulation (and good programming methods).
Can someone explain:
1) why I would want to use properties instead of fields (especially when it appears I am just adding additional code
2) any tips on recognizing the use of properties and not seeing them as simply methods (with the exception of the get;set being apparent) when tracing other peoples code?
3) Any general rules of thumb when it comes to good programming methods in relation to when to use what?
Thanks and sorry for the long post - I didn't want to just ask a question that has been asked 100x without explaining why I am asking it again.
1) why I would want to use properties
instead of fields (especially when it
appears I am just adding additional
code
You should always use properties where possible. They abstract direct access to the field (which is created for you if you don't create one). Even if the property does nothing other than setting a value, it can protect you later on. Changing a field to a property later is a breaking change, so if you have a public field and want to change it to a public property, you have to recompile all code which originally accessed that field.
2) any tips on recognizing the use of
properties and not seeing them as
simply methods (with the exception of
the get;set being apparent) when
tracing other peoples code?
I'm not totally certain what you are asking, but when tracing over someone else's code, you should always assume that the property is doing something other than just getting and setting a value. Although it's accepted practice to not put large amounts of code in getters and setter, you can't just assume that since it's a property it will behave quickly.
3) Any general rules of thumb when it
comes to good programming methods in
relation to when to use what?
I always use properties to get and set methods where possible. That way I can add code later if I need to check that the value is within certain bounds, not null etc. Without using properties, I have to go back and put those checks in every place I directly accessed the field.
One of the nice things about Properties is that the getter and the setter can have different levels of access. Consider this:
public class MyClass {
public string MyString { get; private set; }
//...other code
}
This property can only be changed from within, say in a constructor. Have a read up on Dependency Injection. Constructor injection and Property injection both deal with setting properties from some form of external configuration. There are many frameworks out there. If you delve into some of these you will get a good feel for properties and their use. Dependency injection will also help you with your 3rd question about good practice.
When looking at other people's code, you can tell whether something is a method or a property because their icons are different. Also, in Intellisence, the first part of a property's summary is the word Property.
You should not worry about the extra code needed for accessing fields via properties, it will be "optimized" away by the JIT compiler (by inlining the code). Except when it is too large to be inlined, but then you needed the extra code anyway.
And the extra code for defining simple properties is also minimal:
public int MyProp { get; set; } // use auto generated field.
When you need to customize you can alway define your own field later.
So you are left with the extra layer of encapsulation / data protection, and that is a good thing.
My rule: expose fields always through properties
While I absolutely dislike directly exposing fields to the public, there's another thing: Fields can't be exposed through Interfaces; Properties can.
There are several reasons why you might want to use Properties over Fields, here are just a couple:
a. By having the following
public string MyProperty { get; private set; }
you are making the property "read only". No one using your code can modify it's value. There are cases where this isn't strictly true (if your property is a list), but these are known and have solutions.
b. If you decide you need to increase the safety of your code use properties:
public string MyProperty
{
get { return _myField; }
set
{
if (!string.IsNullOrEmpty(value))
{
_myField = value;
}
}
}
You can tell they're properties because they don't have (). The compiler will tell you if you try to add brackets.
It's considered good practise to always use properties.
There are many scenarios where using a simple field would not cause damage, but
a Property can be changed more easily later, i.e. if you want to add an event whenever the value changes or want to perform some value/range checking.
Also, If you have several projects that depend on each other you have to recompile all that depend on the one where a field was changed to a property.
Using fields is usually practiced in private classes that is not intended to share data with other classes, When we want our data to be accessible by other classes we use properties which has the ability to share data with other classes through get and set which are access methods called Auto Properties that have access to data in private classes, also you can use both with access modifiers Full Property in the same class allowing the class to use data privately as data field and in the same time link the private field to a property that makes the data accessible to other classes as well, see this simple example:
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
The private string _name is used by the class only, while the Name property is accessible by other classes in the same namespace.
why I would want to use properties instead of fields (especially when it appears I am just adding additional code
You want to use properties over fields becuase, when you use properties you can use events with them, so in a case when you want to do some action when a property changes, you can bind some handlers to PropertyChanging or PropertyChanged events. In case of fields this is not possible. Fields can either be public or private or protected, in case of props you can make them read-only publicly but writable privately.
any tips on recognizing the use of properties and not seeing them as simply methods (with the exception of the get;set being apparent) when tracing other peoples code?
A method should be used when the return value is expected to be dynamic every-time you call, a property should be used when the return value is not that greatly dynamic.
Any general rules of thumb when it comes to good programming methods in relation to when to use what?
Yes, I strongly recommend to read Framework Design guidelines for best practices of good programming.
Properties are the preferred way to cover fields to enforce encapsulation. However, they are functional in that you can expose a property that is of a different type and marshal the casting; you can change access modifiers; they are used in WinForms data binding; they allow you to embed lightweight per-property logic such as change notifications; etc.
When looking at other peoples code, properties have different intellisense icons to methods.
If you think properties are just extra code, I would argue sticking with them anyway but make your life easier by auto-generating the property from the field (right-click -> Refactor -> Encapsulate Field...)
Properties allow you to do things other than set or get a value when you use them. Most notably, they allow you to do validation logic.
A Best Practice is to make anything exposed to the public a Property. That way, if you change the set/get logic at a later time, you only have to recompile your class, not every class linked against it.
One caveat is that things like "Threading.Interlocked.Increment" can work with fields, but cannot work with properties. If two threads simultaneously call Threading.Interlocked.Increment on SomeObject.LongIntegerField, the value will get increased by two even if there is no other locking. By contrast, if two threads simultaneously call Threading.Interlocked.Increment on SomeObject.LongIntegerProperty, the value of that property might get incremented by two, or by one, or by -4,294,967,295, or who knows what other values (the property could be written to use locking prevent values other than one or two in that scenario, but it could not be written to ensure the correct increment by two).
I was going to say Properties (setters) are a great place to raise events like NotifyPropertyChanged, but someone else beat me to it.
Another good reason to consider Properties: let's say you use a factory to construct some object that has a default constructor, and you prepare the object via its Properties.
new foo(){Prop1 = "bar", Prop2 = 33, ...};
But if outside users new up your object, maybe there are some properties that you want them to see as read-only and not be able to set (only the factory should be able to set them)? You can make the setters internal - this only works, of course, if the object's class is in the same assembly as the factory.
There are other ways to achieve this goal but using Properties and varying accessor visibility is a good one to consider if you're doing interface-based development, or if you expose libraries to others, etc.

Best way to implement an "Inheritance Square"

Here is my class diagram.
The problem is in AgendaInstance (see red dot). I'm trying to inherit (reuse) Agenda.Tasks to contain its own tasks, which are of type TaskInstance, a subtype of Task.
I can put this.Tasks.Add(new TaskInstance()); inside AgendaInstance. That code works, but the problem comes in when I try to serialize or bind. Since Tasks is statically bound to Task all that gets serialized (e.g., to xml) or bound (e.g., to a grid row) are the properties of Task, not TaskInstance.
Is there a design pattern I can use here to overcome this issue? I don't want to shadow (new) Tasks in AgendaInstance. That would defeat the purpose of having an inheritance hierarchy. My midi-chlorians tell me there's a solution that is higher than directly dealing with serialization or binding specifics; it's a "deeper" issue that lends itself to a more fundamental solution. I'm going to fiddle around with generics but perhaps you know of an even better way or a better pattern.
90% of my experience with xml serialization is bad. They tend to break inheritance model and does not support interfaces. Therefore, it resulting you to hack and tinker the existing class to suit the serialization. XmlIgnore and duplicated properties usually come to hand when dealing with it.
Therefore usually I create another class for the serialization purpose only. Ex: AgendaSerializable, with TaskSerializeable as Tasks. The benefit is: you keep your inheritance and data model clean, while you need to handle with data conversion as the cons.
may the force be with you.
You could make Agenda generic on the Task, like this:
class Agenda<T> where T : Task {
public IList<T> Tasks {get; private set;}
...
}
class AgendaInstance<TaskInstance> {
...
}
Now there is only one Task property in the hierarchy. However, Agenda requires a type parameter to be instantiated, so what used to be a "plain" Agenda becomes Agenda<Task>.

Why can't we use public fields for data binding in C#?

I am aware of the advantages of using properties over fields, like being able to provide additional logic when required in the future.
But I really wonder why it's not possible to use public fields for data binding or even for JSON serializers like JavaScriptSerializer class.
Is there any good reason to ignore public fields in these cases? Or is it just some kind of convention? Or just to force users to use properties?
The short version is that always using properties instead of public (or, really, even protected) fields has been a fundamental design choice in .NET since the very beginning.
The slightly longer version is that adding support for public fields would add complexity to the data binding framework (whichever one you're referring to). Fields also lack any kind of support for change notification, which is a fairly important aspect of data binding (at least in a stateful environment like Winforms development). Even at the level of retrieving and setting values, fields and properties are different; while the syntax in VB.NET or C# for retrieving or setting the value of a property is (by design) the same as that of a field, the mechanism used to do this in a programmatic scenario like data binding is different for properties vs. fields.
In the end, this all just means that it would take more work to add support for public fields to any data binding scenario, so since it's an anti-pattern anyhow this work isn't done.
There is no technical reason behind this restriction: it is certainly possible to add public fields to the list of properties, and allow binding to them. In fact, there are APIs in .NET that would pick a property or a public field automatically, based on a name alone. For example, LINQ's Expression has PropertyOrField method that would pick one or the other, based on the type returned by the expression in its first parameter.
However, leaving fields public exposes you to such an array of potential problems, that the designers of systems dependent on reflection often try to discourage use of public fields by withholding support for them from their system design.
In addition, in systems that rely on events for binding, using a field would not be possible for technical reasons, because one cannot fire an event on setting a public field.
Since you can't declare Fields in Interfaces, you should not use Public Fields. All fields should be private only.
If your code depends upon Abstractions, you need to use Interfaces and here the Public Fields are not available.

WCF Xml/Json serialization of domain objects, what exactly is getting serialized?

I have a domain class User that has at least 20 properties, and it is from another library so it doesn't have any contract decorations. When I return this over a WCF service as xml or json, its only bringing back like 3 of the properties. I thought maybe it was leaving out collections and whatnot, but even simple fields like Name and Email were not being returned at all.
So I guess my question is, can someone explain what exactly is being serialized and returned over the service? None of the properties are decorated with anything like [DataMember], yet some are serialized and returned while others are not. As I understand, it should automatically serialize all public properties. And on a side thought, if someone could point me in the right direction of how to add these declarations to an existing library to assist in the serialization, it would be appreciated.
UPDATE:
I was looking at the wsdl and found the reference to an xsd file (assumingly generated by the serializer). I noticed that I only has those 3 [mapping]
fields listed. not sure what this is or if I can mess with it.
It turns out that the reason these properties weren't serializing is because they weren't exactly public in that they were read-only. I actually had the properties set to:
public string MyProperty { get; internal set; }
I did this because I do use object initializers in my internal system classes (controller type stuff) and do not wish to allow the consumer to set these properties. I read that you can set them to protected and it will allow it to serialize, however this doesn't work for my implementation.
These are POCO classes, so my solution (albeit not exactly an answer to the problem) was to create DTO classes. Since all of the properties in the DTOs were fully public, all I do is populate those with data from the POCO and return the dto. Everything gets serialized properly.
Take a look at your domain class, and see if it is inheriting from another class. If it is, the User class probably only has the three properties you are seeing.
What I have found to work well is to create a special service model (or view model) as the public data interface, not a direct interface to the domain model. As a benefit, you have much greater control of the data that can be exposed - you limit the risk of unintentional data leakage, as well as optimizing the data sent over the wire.
Best of luck!

Associate "Code/Properties/Stuff" with Fields in C# without reflection. I am too indoctrinated by Javascript

I am building a library to automatically create forms for Objects in the project that I am working on.
The codebase is in C#, and essentially we have a HUGE number of different objects to store information about different things. If I send these objects to the client side as JSON, it is easy enough to programatically inspect them to generate a form for all of the properties.
The problem is that I want to be able to create a simple way of enforcing permissions and doing validation on the client side. It needs to be done on a field by field level.
In javascript I would do this by creating a parallel object structure, which had some sort of { permissions : "someLevel", validator : someFunction } object at the nodes. With empty nodes implying free permissions and universal validation. This would let me simply iterate over the new object and the permissions object, run the check, and deal with the result.
Because I am overfamilar with the hammer that is javascript, this is really the only way that I can see to deal with this problem. My first implementation thus uses reflection to let me treat objects as dictionaries, that can be programatically iterated over, and then I just have dictionaries of dictionaries of PermissionRule objects which can be compared with.
Very javascripty. Very awkward.
Is there some better way that I can do this? Essentially a way to associate a data set with each property, and then iterate over those properties.
Or else am I Doing It Wrong?
It sounds like you are describing custom attributes - i.e.
[Permissions("someLevel"), Validator("someFunction")]
public string Foo {get;set;}
This requires some reflection to read the attributes, but is quite a nice way of decorating types / members / etc. You might also look at the pre-rolled [PrincipalPermission] for security checks. Is this what you mean?
Note the above would require:
public class PermissionsAttribute : Attribute {
private readonly string permissions;
public string Permissions { get {return permissions;}}
public PermissionsAttribute(string permissions) {
this.permissions = permissions;
}
}
(and similar for the other)
You can read them out with Attribute.GetCustomAttributes

Categories

Resources