Why would you use 'custom attributes' in your code (.NET) - c#

Could anyone explain the benefits (or reasons) to use custom attributes in your code. Of course I use (and understand the purpose of) defined attributes in certain scenarios (WCF, Serialization etc.), but I cannot imagine any algorithms where I would need to create and use my own custom attributes. Could someone provide a real-world case where usages of custom defined attributes bring something to a project.

The same reason as for WCF etc, but something that's specific to your project - you want to add some metadata to some members (types, fields, methods, whatever) to specify something about the mechanism involved, and it's not something which is covered by existing attributes.
For example, NUnit wanted to add their own indication that a particular type contained unit tests - there was no such existing attribute, so they created TestFixtureAttribute.
It's a relatively rare event, sure - but it can happen.

If you want to write your own system like WCF, Serialization, etc...
If you write code that iterates over types or members and does things with them, you will frequently want to use your own custom attributes to mark some members as being different or special.

I regularly use custom .Net attributes to support tooling in my infrastructure. One example was from very early in the .Net days (C# 1.0 to be exact). I was working on a research project which had a native C++ front and a brand new C# back end written by yours truly.
The front and back end shared a very similar object model which was evolving very rapidly. Not wanting to have to hand code both a C++ front end model, C++ serialization mechanism and a C# serialization mechanism I chose instead to attribute my C# types with custom attributes. They told me the parts of the model which were shared between the front and back end.
Once those attributes were in place I wrote a quick and dirty tool which
Parsed out the attributes to construct the core shared model
Generated the C# serialization code
Generated the C++ code
Generated the C++ serialization code
This made it dirt simple to keep my model up to date between my 2 projects. Just change the C# code, compile and re-run my tool.

I have used annotations in a custom AOP (Aspect-Oriented Programming) system I developed a while back. Attributes are also very useful for controlling orthogonal concerns like code generation.

Custom validation is a very good use case and can be seen from these links:
http://odetocode.com/blogs/scott/archive/2011/02/21/custom-data-annotation-validator-part-i-server-code.aspx
How to create Custom Data Annotation Validators

They can be used for marking tests, as in MBUnit for example. They can also be useful for code that inspects and loads classes (like a Plugin system) to provide meta-information.

They are really useful in building object mappers / ORM tools as well. If you ever decide to roll your own mapping system they are almost "required" to get all the functionality one would need. It's used more for making methods / classes more generic and using reflection to determine how to handle objects / select objects /etc...

To give you a specific case where I've used them. I once had to interact with a Mainframe screenscraper. I created a custom attribute to annotate which fields I wanted to send from my classes to the Mainframe, names that fell outside of conventions, special rules to deal with formatting and collections. I then had a class which was able to reflect over instances and realise which subset of fields were needed to interact with the mainframe screen scraper appropriately.

Related

How I can convert this c# class to brotobuf in proto3 version? [duplicate]

Trying to get my mind around google protobuf. I found some implementation of protobuf in C# but they seems to lack one feature: the ability to generate .proto files automatically from an existing C# class decorated with attributes.
The reason I want to do it this way instead of going from auto-generated C# classes from .proto file is because I already have the C# classes defined in my project and I don't want to duplicate them just to satisfy ProtoBuf.
Does anyone have encountered such a scenario?
Update
Is this possible to just decorate a C# class and not use a .proto file to use protobuf?
Good news; what you have described (having existing C# classes) is the expected use-case of protobuf-net. All the .proto stuff ("protogen", the VS add-in, etc) were all added as afterthoughts. The core of protobuf-net doesn't know about them or care about them.
protocol buffers defines a DSL (.proto, as you mention) that is shared between implementations, and is (sometimes) used for code generation. When I first wrote protobuf-net, the code-generation aspect wasn't my biggest concern - simply that .NET developers are generally guilty (myself included) of "implementation first" rather than "contract first".
As a consequence, protobuf-net doesn't need .proto files to work; an attributed class is sufficient to unambiguously serialize/deserialize. Just use Serializer.Serialize , .Merge and .Deserialize (etc).
That said; it does include some very under-developed and experimental support for this:
string proto = Serializer.GetProto<YourType>();
This is far from complete, but may work for simple types. If you have some specific cases where it fails, then let me know (add a comment or log an issue). However; most of the time, people interested in .proto would write the .proto first and work from there.
Examples of working decorated types are shown on the project home page; it is entirely up to you whether you use WCF attributes, xml attributes or protobuf-net attributes (although the latter provide more control over some specific serialization points, such as inheritance and numeric layouts).
Before Skeet Marc runs in here and gets massive ups, let me point out protobuf.net.

using attribute to read Method Parameters

I want to log the entry of methods. In entry log I would have inputs\parameters received by the method. This has to be done for thousands of methods.
I thought of doing this logging of input parameters using C# ATTRIBUTES, since they fired before method call. (Something similar to ActionFilters in MVC)
Is that possible to read method parameters through attributes?
The concept you are looking for is called aspect oriented programming (AOP). It is a technique that allows you to "weave" in blocks of boilerplate code across your application code. Logging is a perfect example for that. You can either go the hard way and implement logging before and after each method call manually (which is on the one hand not feasible in large projects and on the other hand error prone).
Or you can use an AOP Framework that allows you to define these cross cutting functions in one place and apply it declaratively to your application code. There are several approaches to achieve this; one is to create IL after the build of the application logic and therefore integrating the aspects at compile time. A well known example for this is PostSharp. There also is a free edition that is good for the start.
BTW: PostSharp heavily relies on attributes, so you're on the right track.
Another option is to integrate the aspects at run time (keyword is interception). Most IoC Frameworks offer this. This approach is easy to use but has some downsides IMHO (weaker runtime Performance, only virtual methods can be intercepted).
Attributes are not 'fired before method call', the code that invokes a method that is decorated with an Attribute may (or may not) do something based on the presence of the Attribute.
The Attribute doesn't know the member it is applied on, nor can access it in any (straight forward) way.

How can I make a program to support custom requirements for multiple customers with a single codebase?

As the title states, I'm looking for a way to organize code with various customer "settings" that control program logic and sometimes display logic without introducing a nest of if/else branches in both the client (javascript) and the server (C#).
What mechanisms do I have to choose from for making a series of modules used for validation, field visibility, processing rules and such that can be loaded dynamically based on, say, a username or other bit of customer data? I am aware of IOC, I need something more specific than "configurable modules". Are there libraries out there to provide a structure for organizing code and loading it conditionally?
What about in javascript? Are there well-known mechanisms for dynamically loading javascript from small files to be executed conditionally?
Most of all, is there a name for what I'm describing? I don't want a rules engine or decision engine where the code is stored as a set of values and operators. I want to keep the code in its original files. I also want to use strong typing and interfaces where I can.
Any ideas?
You should look at either (or both) of
Microsoft's Managed Extensibility Framework
http://msdn.microsoft.com/en-us/magazine/ee291628.aspx
Mono.Addins
Here's the MSDN docs on the System.Addin namespace(s) as well: http://msdn.microsoft.com/en-us/library/gg145020.aspx
This discussion talks about the difference between MEF and System.Addin: Choosing between MEF and MAF (System.AddIn)
The wiring and configuration of your extension system is of course highly domain specific.
Good Luck!
If you wish to use strong typing and interfaces, then why not just go that route? You could create an interface that defines callable methods for your individual customer logic, and then create the implementation classes for each. That way you would only have one piece of conditional logic, perhaps a switch statement, in your system startup routine that loads the correct implementation.

Serializing on Desktop, Deserializing in Silverlight

I'm trying to create content via a small C# desktop app, and have it appear inside a Silverlight application. (I'm creating plain, ordinary C# objects, and trying to make them easily persist.) The context is a game of some sort, where I have a desktop tool that lets me create and edit the content I want, and then the Silverlight binaries consume it.
How can I serialize something in (desktop) C# and deserialize it in Silverlight?
I have a small library I created for serialization; it uses Mike Talbot's amazing serializer for Silverlight, and a simple BinaryFormatter for desktop. Within each platform, these are OK; but across platforms, these two are obviously incompatible.
Is it possible to do this? I would not like to revert back to manually serializing by saving data as text and then parsing it, and I would not like to use an embedded database if possible. I may have lists of lists and other complex data, and manually parsing it is too painful.
If it's not possible, what alternatives do I have?
Edit: ProtoBuf .NET looks OK, but as I mentioned in Marc's comment, I'm using the serializer inside my own library. This means that requiring users of my persistence library to add attribution to classes to serialize them will break encapsulation. I don't want to do that.
What do I mean by breaking encapsulation?
The target user of my library (Persistent Storage) is a game developer. They will use the library to persist information within their games.
Hence, they only consume PersistentStorage.dll. Internally, Persistent Storage uses a serializer (currently, Mike Talbot's for Silverlight, and a simple Binary one for non-Silverlight) to persist data.
For me to say "to use my library, put [ProtoContract] or [Serializable] on all your classes" breaks encapsulation. It means the user knows about the internals of my library usage, which they shouldn't. I can change serializers tomorrow, and they shouldn't care.
I am aware that as a work-around, I can ask them to attribute everything with [PersistMe] and have that as a plain empty attribute that, in turn, extends whatever attribute my serializer needs. But I'm hoping that other serializers, like Mike Talbot's, will not require any attribution to use.
You can try to use Silverlight Serializer
From the author's page:
Serializing Classes Between .NET 4 and Silverlight
You may want to use SilverlightSerializer to share objects between Silverlight and .NET 4, perhaps across a WCF link.
The vital thing to do in these circumstances is to define the classes you want to share in a Silverlight assembly that only references System, System.Core and mscorlib. These are the requirements for assemblies that can be used in both types of project. If you define your classes in this way then they can be deserialized on the back end without a problem, reference anything else and it won’t work. Fortunately most of what you will need is included in those system assemblies!
You need to use the same format in this scenario. Since BinaryFormatter isn't OK for Silverlight, that is out. Personally I'd use protobuf-net, which works on both and can be configured to work on vanilla objects (but is easier if you can add attributes), but if your linked serialiser works on desktop that is a viable option too.
With an example of your model I can be more specific.
Why not try old school xml serialization with the XmlSerializer, both the .Net framework on the desktop and silverlight should have that class. This way there is no addition library to include, its in the framework.
You could also look at Sharp serializer. It allows you to either use xml based formatting or binary formatting for serialization.
I have used it in a similar scenario to share data between a Silverlight and a non Silverlight application and it works beautifully.
Just for reference:
you can build a single SilverlightSerializer DLL and reference it in .net and Silverlight. this works even though the DLL targets Silverlight
Silverlight doesn't run with enough security permissions to enable the inspection of private class members. SilverlightSerializer let's you write support classes to serialize third party components with non-standard requirements, and this can work for private members, but in that particular case it's manual and requires that the serialization class and the serialized class are one in the same.
Have you tried a JSON Serializer like JSON.net ( http://json.codeplex.com/ )?
JSON Specification: http://json.org
We use WCF to do all our serialization to the Silverlight client. We have a dll shared between the client and the server that has all the data transfer objects and interfaces. This allows us to not use the wsdl to generate service ref in silverlight.
To do the searlization we use the DataContractSerializer with a BinaryMessageEncoding. Also you do have to watch out for private setters of objects (which cant be done in silverlight, as you cant set a property with a private setter in the partial trust enviroment of silverlight). If you want to use generics and other things like that, use the NetDataContractSerializer, but that will break compatability with Java and other standards based web services outside of .net (but should work fine for silverlight).
All our DTO's are POCO, other then we add a [ItemKey] Attribute to one of the properties (no other attributes or interfaces), so that our system knows which property is the primary key (this isnt required but it makes things easier to do updates in the persistance layer if things change in the objects).

How do I generate a .proto file from a C# class decorated with attributes?

Trying to get my mind around google protobuf. I found some implementation of protobuf in C# but they seems to lack one feature: the ability to generate .proto files automatically from an existing C# class decorated with attributes.
The reason I want to do it this way instead of going from auto-generated C# classes from .proto file is because I already have the C# classes defined in my project and I don't want to duplicate them just to satisfy ProtoBuf.
Does anyone have encountered such a scenario?
Update
Is this possible to just decorate a C# class and not use a .proto file to use protobuf?
Good news; what you have described (having existing C# classes) is the expected use-case of protobuf-net. All the .proto stuff ("protogen", the VS add-in, etc) were all added as afterthoughts. The core of protobuf-net doesn't know about them or care about them.
protocol buffers defines a DSL (.proto, as you mention) that is shared between implementations, and is (sometimes) used for code generation. When I first wrote protobuf-net, the code-generation aspect wasn't my biggest concern - simply that .NET developers are generally guilty (myself included) of "implementation first" rather than "contract first".
As a consequence, protobuf-net doesn't need .proto files to work; an attributed class is sufficient to unambiguously serialize/deserialize. Just use Serializer.Serialize , .Merge and .Deserialize (etc).
That said; it does include some very under-developed and experimental support for this:
string proto = Serializer.GetProto<YourType>();
This is far from complete, but may work for simple types. If you have some specific cases where it fails, then let me know (add a comment or log an issue). However; most of the time, people interested in .proto would write the .proto first and work from there.
Examples of working decorated types are shown on the project home page; it is entirely up to you whether you use WCF attributes, xml attributes or protobuf-net attributes (although the latter provide more control over some specific serialization points, such as inheritance and numeric layouts).
Before Skeet Marc runs in here and gets massive ups, let me point out protobuf.net.

Categories

Resources