Change code based on existing attribute? - c#

I'm writing a library which is shared between .net and silverlight. I have several places where I am doing this, to satisfy the silverlight deserialization (which can't access private members):
[DataMember (IsRequired = true)]
public Object MyProperty { get;
#if SILVERLIGHT
internal
#else
private
#endif
set; }
I know the rules for this, which are that if the setter is private and SILVERLIGHT is defined then the setter should be internal.
Could I use an aspect oriented framework like postsharp to help me reduce this code so that I don't need to specify anything and it will inspect the property, if it has the DataMember attribute and the setter is private, then make the setter internal instead?
Or is there some other technique I could use for this?
EDIT
There seems to be some confusion. My goal is to avoid having the compiler directives at all, but to still have code which is generated with a private member in .net and with a member that can be set by the DataContractDeserializer in Silverlight, which can't access private members. If possible I'd like to automatically modify the property in a silverlight build so it is internal, whilst not having anything other than the DataMember attribute in the source.
Ideally I see the solution being something like:
Write an aspect which checks every property or field.
If the property/field has the [DataMember] attribute then
If the silverlight compiler directive exists then
if the setter is private make it internal (for properties) or if it is declared as private make it internal (for fields)
but I'm not sure which bits of that it would be possible to do using a tool like post sharp.

The other answers either attack the merit of the problem or present alternative approaches that do not directly answer the question. The question was whether there was a way to change the visibility of the setter for a property with a DataMember attribute after it is compiled, to support two versions (.NET and Silverlight).
I suspect the PostSharp SDK would support this. However, this is a problem I had to solve while developing Afterthought, as I needed to change the visibility of anonymous static delegates generated by the C# compiler (normally private until I made them internal). Afterthought itself does not currently support your scenario directly, but it leverages the open source Microsoft CCI libraries, which do. The IL Mutator example shows how to use the CCI libraries to load a compiled assembly and modify it by creating a mutable copy. The example is actually much more complex than your scenario, as you will not be modifying IL, just the visibility of a setter.
This is an example of changing the visibility of a method from within a mutator in CCI:
public override MethodDefinition Mutate(MethodDefinition methodDef)
{
// Automatically make all private static methods to have internal scope
if (methodDef.IsStatic && methodDef.Visibility == TypeMemberVisibility.Private)
methodDef.Visibility = TypeMemberVisibility.Assembly;
This is a slightly simplified excerpt from the Afterthought amender. There are also examples in the same class for how to determine if a method is a setter (starts with set_, HideBySig, etc). You would just need to create a mutator, override the method in this example, verify that the method is a property setter with a DataMember attribute on the containing property definition, and change the visibility.

Simple answer is NO. PostSharp is a Post-Compile framework so you cannot use your compiler directives (as you're trying to do in your question). You can use PostSharp to
Introduce properties into the class with the accessors desired (which doesn't give you access at design time) Directives can be applied to the aspect at design time to determine which property to inject though
Or use reflection to change the accessor (I dont think you can do that)
An alternative is to use T4 templates to generate these classes for you
Edit: Example of property injection
[Serializable]
[MulticastAttributeUsage(MulticastTargets.Class, Inheritance = MulticastInheritance.Strict)]
public class PropInj : InstanceLevelAspect
{
#if SILVERLIGHT
[IntroduceMember(OverrideAction = MemberOverrideAction.Ignore, IsVirtual=true, Visibility=Visibility.FamilyAndAssembly)]
public string MyProperty { get; set; }
#else
[IntroduceMember(OverrideAction = MemberOverrideAction.Ignore, IsVirtual = true, Visibility = Visibility.Private)]
public string MyProperty { get; set; }
#endif
}
[PropInj]
public class test
{
//public int MyProperty { get; set; }
public test()
{
}
}
but really you need to rethink your design.

Related

Dotfuscator accessors renaming get and set

My issue is with Dotfuscator configuration for renaming. Imagine a class that would look like this:
Class MyClass
{
private int _propertyA;
private int _propertyB;
public int PropertyA
{
get{return _propertyA;}
set{_propertyA = value;}
}
[Obfuscation(Feature = "renaming", Exclude = true)]
public int DestinationReference
{
get{return _propertyB;}
}
}
The obfuscated class will be written into someting like this
Class a
{
int s()
void z(int a)
public int DestinationReference
{
get{return _propertyB;}
}
}
This is my assumption from what I can see using .Net Reflector
My issue is the following:
- In our code we implemented a method that look for all attributes of a class using reflection in order to find specific parameters
- This method does not work in the obfuscated code as my accessor PropertyA, has been replaced with two distinct methods for the get accessor and set accessor.
- I know that if I exclude an accessor from renaming it stays an accessor in the msil code and will be found by my method that looks for accessors
My question is:
- Is not renaming the only option?
- Is there a parameter in Dotfuscator that would allow renaming of the accessor without splitting it into two distinct methods and loosing the accessor?
I'm pretty new to obfuscation so pardon my imperfections, this is what I can see for a class similar to the one described above in reflector.
As you can see the property that is excluded from renaming stays a property with a get accessor. But for the other one that got obfuscated I can see two distinct methods s and z
I'm trying to see if there would be a way of obtaining a single accessor, renamed "s" for example with the underlying getter and setter
I found some answers to my question, first after looking at this article : http://vicky4147.wordpress.com/2007/10/23/exploring-msil-properties/
I see that MSIL generates get_XXX() method and set_XXX(int) methods as well as adding a property. Dotfuscator is responsible for renaming the get and set methods (which is what we want) but also for removing the property itself (which I do not want)
A solution is to enable "Library mode" for the obfuscated DLL, if library mode is enabled, the documentation states that:
Names of public classes and nested public classes are not renamed. Members (fields and methods) of these classes are also not renamed if they have public, family, or famorassem access.
In addition, no virtual methods are renamed, regardless of access specifier. This allows clients of your library to override private virtual methods if need be (this is allowed behavior in the .NET architecture).
Any user-specified custom renaming exclusions are applied in addition to the exclusions implied by the above rules.
Property and Event metadata are always preserved.
And this can be seen after obfuscation in reflector, at the top library mode is disabled, at the bottom library mode is enabled
As it can be seen, none of the public classes/methods/fields have been renamed, and more important to me the Property metadata has been preserved.
Now my next question would be, how to preserve the property metadata but allow the renaming of the property itself. I would like to find a solution that is satisfying without having to define manually decorate each properties with custom obfuscation attributes.
I'll keep searching for another day and if I can't find anything will mark this answer as solution to the issue.

Do I need to use { get; set; } with c# fields that have no special actions when getting and setting

I have been coding classes like this:
public class ReportViewModel
{
public string Status;
public string DataSource;
public String DataStore { get; set; }
public PageMeta PageMeta { get; set; }
public ICollection<Question> List { get; set; }
}
Note that most of the fields use { get; set; } except the first two which I let Visual Studio add for me.
What I am wondering is do I really need to use { get; set; }. It seems to me that VS2010 does not automatically add this so do I need it?
You've created a class with two public fields (Status and DataSource) and three public properties (DataStore, PageMeta and List). I would advise against having public fields - and you should actually consider whether you really need all of these to be mutable properties at all.
There are various advantages to using properties over public fields, but the main one in my mind is that a property is logically part of the API of a class, whereas a field is logically an implementation detail. The property says what callers can do - a field says how a value is stored.
{ get; set; } indicate autoimplemented properties. In .NET there is a difference between properties and fields. Normally fields should be private. They are used for some specific implementation and should in most cases be internal to the class. Properties on the other hand are used to encapsulate behavior that is exposed to the consumers.
If you want them properly exposed as properties, yes.
They are different: your first two members are fields - not properties. The others are properties with auto-implemented accessors.
When you don't add the get and set you are using a field rather than a property. Which in many cases won't make a lot of difference. However, you can't databind to a field like you can with a Property. So you would lose that.
At all depends on how this class will be used.
If this is in your code, just used in your current product, then there isn't really much difference between fields (no {get;set;}) and properties (with the {get;set;}).
However in that case they probably shouldn't be public, make them internal or private instead so that it's clear that external code shouldn't use them.
If your class is going to be used by other assemblies then you should always convert public fields to properties.
The reason is that if you want to extend properties later on (i.e. add a body to the set) then your users can just get the new DLL from you. However if you've used fields then converting them to a property will look the same in the IDE, but require your users to recompile when they get the altered DLL.
Being public tells consumers that they can rely on that member being present, being a property gives you more control of how you deliver it to them.
There is a difference. The first two are fields and the remainder are auto-properties.
The second one, the compiler generates a private backing field and some boiler-plate get/set methods. These then allow you to access the properties like they were fields, but with the advantages only available to properties.
It is always recommended to hide fields behind properties, by either making them private and writing your own property around it or using an auto-property.
There's some advantages to properties. One being that properties can be made read-only, or even write-only, or read-only with an internal write-only, etc. Since they act just like methods, you can execute any arbitrary code inside of them. This is useful for when you need to implement things like INotifyPropertyChanged or if the property is actually calculated from several fields behind it.
The other advantage is encapsulation. You aren't tying yourself directly to the fields of the class, but rather the property. So if some detail about the field changes (say it goes away and becomes calculated), by using the property you are insulating yourself from those implementation details.
You should certainly look at using properties (for now adding the { get; set; }) for all cases. They are good practice in that they provide a level of encapsulation that shields the user from implementation specific details.
You do not have to, but this just coding stundart, with its pros and cons.
Consider this link for more resources:
Property Acessors

What is the difference between public int i and public int i {get; set;} (what is the difference between automatic property and a public member?) [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
c#: why have empty get set properties instead of using a public member variable?
C#: Public Fields versus Automatic Properties
I am using "automatic" properties in my code,
and I wonder what is the actual difference between
this code:
public class foo{
public int i;
}
and
public class foo{
public int i {get; set;}
}
I know there is a difference, as sine 3rd parties that I've used missed the public members but found them once adding the {get; set;}.
AS there is no private field behind that, what is going behind the scene ?
A private field gets generated by the compiler when using automatic properties.
When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
In regards to the difference between the two examples - the first one exposes the field directly for manipulation. This is considered bad practice (think information hiding, loss of encapsulation).
With the second example, you must use the getter and setter and you can add any kind of validation and other logic around these actions.
See this blog post:
If I have a field with no special behavior, should I write a "just in case" property (with trivial get/set), or should I expose a public field?
The reason that the library design guidelines suggest you write a property here is that it is important that libraries be easily versioned. If you put a property in there ahead of time, you can change the property implementation without requiring users to recompile their code.
The first is a field and could be described as POD. The second is a property and allow for derived classes to overload and Shadow while the first does not. Also the second is a nicety since the complier silently creates a backing store.
That's an auto property, not an anonymous property. There is, in fact, a private backing field for it, it's just generated automatically by the compiler and isn't available to you at compile time. If you run your class through something like Reflector (or examine it at runtime with reflection), you'll see the backing field.
To answer your question of "What's the difference?", the obvious answer is that one is a field, whereas one is a property. The advantage to using auto properties is that it gives you the flexibility to move to traditional properties later, should the need arise, without changing your API. As far as third party code being able to "reach" one but not the other, that would be a question best answered by the other developer. That being said, most API's are designed to work on properties, not fields (since conventional wisdom is that you do not expose fields outside of the declaring class). If the third-party library is reflectively scanning your class, then it's likely only looking for properties.
The important thing to remember is that:
private string backingField;
public string Data
{
get { return backingField; }
set { backingField = value; }
}
and
public string Data { get; set; }
Are compiled to essentially the same code. The only substantive difference is the name of the backing field.

Why does my .NET Attribute not perform an action?

I've created a simple Attribute:
[AttributeUsage(AttributeTargets.Method)]
public class InitAttribute : System.Attribute
{
public InitAttribute()
{
Console.WriteLine("Works!");
}
}
and I apply it to a simple method:
static class Logger
{
public static string _severity;
public static void Init(string severity)
{
_severity = severity;
}
[Init()]
public static void p()
{
Console.WriteLine(_severity);
}
}
What is going on is pretty streight-forward. Only, I expect the attribute to perform an action (printing Works!), but this does not happen.
Addictionally, printing "Works!" is of course just for debugging purposes: I'd like to access the instance's property _severity (to check if is != null, for example), but everything I keep reading about attributes (that are pretty new to me) is about accessing the class' methods or properties and so on via reflection. Once I've evaluated _severity, how can I modify the behavior of the decorated method (in this case, rise an exception "Logger is not initialized" and do not execute it)?
Any help appreciated.
If you need to perform an action as control enters a method, you should look at aspect-oriented programming and frameworks such as PostSharp. Attributes are not designed to perform anything by themselves. They are just a bunch of data (or metadata if you will) attached to stuff in IL assemblies that can be queried at runtime.
Attributes only allow decoration of types and members, but the attribute itself cannot acces the decorated object. You will have to use the constructor parameters of the attribute to pass in any data you require to work with within the attribute.
If you wish to use attributes to automatically alter the behaviour of their target objects, you will have to look at AOP solutions like PostSharp.
The attribute is never actually instantiated and so its constructor is never called. The attribute remains as meta-data until you use reflection to retrieve it. As has been mentioned previously what you are after is an Aspect Oriented Programming tool. PostSharp works by altering the assembly as a post-build step. If you are using the Castle Windsor or Unity Inversion of Control Containers they both offer AOP capabilities as well.

C#: Can I remove "{ get; set; }"?

Is there a difference between:
public T RequestedValue { get; set; }
and
public T RequestedValue;
?
Taken from this code:
public class PropertyChangeRequestEventArgs<T>:EventArgs
{
public PropertyChangeRequestEventArgs(T pRequestedValue)
{
RequestedValue = pRequestedValue;
}
public T RequestedValue { get; set; }
}
The first is an Auto-Implemented Property the second is a Field. Regular Properties expose Getters and Setters but have a private field to actually store the value:
private int someProperty;
public int SomeProperty
{
get { return someProperty; }
set { someProperty = value; }
}
The first allows you to change certain aspects of the implementation of your class without affecting all the other code in your application. The most important point is that, with properties, changes can be made without breaking binary compatibility (although a field can often be changed to a property without breaking code). If it is a public member, a property is advisable. (Stealing shamelessly from Snarfblam's comment)
From the Properties page:
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
Properties with a backing field are the most flexible form as they allow easy implementation of things like the INotifyPropertyChanged event for updating the UI in Model-View-ViewModel implementations.
deep explanation!
The {get; set;} is an automatic property, while the second is a field.
a field is a normal variable, from some type, that contains data.
a property is a couple of methods (well sometimes it's just one), one for get, and one for set. they only have a syntax like fields, but actually they are quite different.
properties are usually for filtering the set of the value, or virtualizing something in the get, etc.
automatic properties, also create a private field behind the scenes, return its value in the get, and set its value in the set.
seemingly this is just like a normal field, but behind the scenes (IL) using properties is totally different from using fields.
a.Property1 = 4;
is translate into something like:
a.Set_Propert1(4);
and this:
x = a.Property1;
is translate to something like this:
x = a.Get_Property1();
so why is it a good practice to use only public properties, even if they are automatic?
say you are writing a library, that is used by other application, and someday you want to release a new version of that library that constrains one of your class' fields..
if you are using properties, you can just change the property (even if it is an automatic one, you can replace it by a full one), and then any application which used your library can still use it in the same way.
but if you made a public field, which you now want to constrain, you'll need to make a property for this and make the field private, but if you will, any application that used you library will no more be bale to, because the way it use fields and property is different.
You may write:
public T RequestedValue { get; set; }
as a shortcut of:
private T _requestedValue;
public T RequestedValue
{
get { return this._requestedValue; }
set { this._requestedValue = value; }
}
They are totally equivalent, also considering the performance.
The answer is, yes you can remove the { get; set; } but then a whole load subtle differences kick in. Some will say fields and properties express radically different design intent but in practice this distinction has been eroded over the years as C# evolves and progressively blurs the the syntactic differences.
For a good list of compiler-binary level differences between fields and properties refer to SO question difference-between-property-and-field-in-c. But the answers to that question missed one significant point about the special role of properties when declaring interfaces.

Categories

Resources