Download presentation
Presentation is loading. Please wait.
1
Browne Bag Seminar Applied .Net Attributes
Presented by : Mario Tayah Nov
2
Def. of Attributes Attributes provided special functionality to a block of code. Some are already defined for the user to make use of. New attributes can be also defined. They inherit from the System.Attribute class
3
Def. of attribute(cont.)
You simply declare an attribute by adding the following code: [obsolete(“this is a bad class”)] { block of code(assembly,class,method…) } Will cause a worning [obsolete(“this is a bad class”, true)] Will cause a compilation error Note: assembly cannot be put obsolete
4
Def. of attributes(cont.)
From a compilation perspective, there is nothing to do, to be able to use attributes. Usually stored in a .custom directive. Note that some another type of attributes, pseudo-custom is not stored in a .custom directive.
5
Categories of attributes
Compiler attributes Conditional attributes Assembly attributes Com interoperability attributes Identity, versioning and GUID attributes Design time attributes
6
Compiler attributes They are detected by the compiler and they affect the way the compiler treats the code. CLS subset of CTS [Assembly: clscompliant(true)] You can apply this to the whole assembly and remove it from one method
7
Conditional attributes
Instead of using #if(TEST) Use [Conditional(test)] This would make the compiler completely ingnore this method if the test is not set. /define test at compilation time the compiler will not ignore the method listed below the [Conditional(test)] attribute definition
8
Assembly attribute General information: supplemental info: copyright, company name… Informational and behavioral attributes: information about the assembly and affects behavior of runtime and compiler
9
Assembly attribute(Gen. inf.)
Should be added to the assemblyinfo.cs file and the compiler will add it to the manifest Ex: [assembly: assemblytitle(“new assembly”)]
10
Assembly attribute (informational and behavioral assembly attributes)
Assembly key file: sn –k mykey.snk [assembly: Adv.: Malicious code V # no wrong mapping of versions Shared by installing on the GAC
11
Assembly attribute (informational and behavioral assembly attributes)
Most of the time, private keys are not available for developers to use But, versioning is a very important issue. use assembly delay signing. Acts same as for strong named, but can be accessed through public keys. At deployment switch back to the use of private keys
12
Assembly attribute (informational and behavioral assembly attributes)
Version is usually found in the AssemblyInfo.cs file You can explicitlt set the version as fixed by adding/altering the following: [assembly: AssemblyVersion(“ ”)]
13
Com interoperability attributes
Com use .Net and vice versa Usually handled by regasm, tlbimp, tlbexp Diff. betw .net&com cause problems: Locating dll Lifetime Type system …
14
Class interface Regasm takes care of making the code available both ways Importing from .Net to Com better provide an interface. In order to be able to generate the interface when the code is changes to COM(interface based language). Can use attributes[ClassInterface(ClassInterfaceType.(the selected mode))] AutoDispatch (def. late binding) AutoDual (included all class members and inherited) Non (no generated interface) Fixes the problem of late binding(now all methods are known from interface)no errors due to lack of message signature
15
Identity Versioning Com interoperability too GUID used to locate dll
From .net to C++GUID might be diff. than the old file that was used What if the GUID is changed? Bounds built with old GUID are broken use [GUID(“num”)]
16
Design Time attributes
If you create a new control(:UserControl) and want to change its properties… You use attributes Which can define descrption, defaultvalues…
17
Runtime behavior These attributes affect the runtime and not the compiler. This category includes: Securing code Declarative vs imperative security Platform invoke attributes
18
Securing code Suppose that you have a function that reads from a file…. But what if this function is malicious and performs something bad do the system folder? You can use the securityaction attribute in 2 ways: Declarative imperative
19
Securing Code(Declarative)
[FileIOPermission(SecurityAction.Deny), Method code Straight forward Security will show in metadata
20
Securing Code(Imperative)
FileIOPermission fp=new FileIOPermission(FileIOPermissionAccess .Read,Environment.SystemDirectory); fp.Deny(); Path of folder where browsing is denied is not hard coded In case you need some complex computation to determine security
21
Platform invoke attributes
This is mainly concerned with making calls to unmanaged code from a managed code Now suppose that you have a method in C++ has following signature: Bool Beep(Dword dwfreq, Dword Dwduration) to use this method, you do the following: [DLLImport(“Kernel32”)] Private static extern int Beep(int freq, int duration); Static void Main(string[]args) { Beep(100,100) }
22
Marshaling structure As you have noticed before that we have replaced the Dword with an int. this is being taken care of by the Platform invoke wich provides standard marshaling of simple types but what if you have a method that actually uses a type declared in unmanaged code? [Structure(LayoutKind.Sequential)] struct… the used type Using [Structur tells the runtime that it should preserve the order and use it define the imported unmanaged code that contains this type i.e. you are explaining that this is how I want this unmanaged object to be marshaled.
23
Fixed length strings in C, C++
In C and C++, there is a lot of use of fixed length strings, collections… To map these into managed code: Suppose the following C line of code: Char FirstName[20]; This maps to the following [MarshalAs(UnmanagedType.ByteValStr, SizeConst = 20)]
24
Serialization in order to indicate that a type, property… is sirealizable using attributes, you just add the following: [Serializable()] Note: in case you do not want to serialize some element from a serializable class, you just add the following before this element: [NonSerialized()] Note: serializable does not indicate how the sirealization is perfomed(text, xml…) This is done through either using a soapformatter or a binaryformatter.
25
XmlSerializer Attributes play a role in supporting:
[XmlIgnore] which, when placed infront of an element will cause this element not to be serialized by the XmlSerializer. Moreover, more attributes are provided that customize the schema of the generated XML file wich represents the serialized object. Ex:[XmlAtribute(“Name”)] [XmlRoot(“VIP”)]
26
Remote By ref A proxy is created in order to communicate with the object By value The actual object is serialized and moved over the network
27
By ref and The [oneway()]
A way to apply asynchronous call no plumbing for the return no overhead asynchronous call for clientclient goes on with his work Use: [OneWay()] Before the method that you want to be asynchronous
28
Context Attributes Use: What is a context?
An environment with a set of shared properties; like appdomainone appdomain contains many contexts Isolation from the outside proxy creation in case of communication no pointers Good to use with objects with similar runtime. Use: [Synchronization] public class myclass: ContextBoundObject Creates an object that is synchronized and created in a context Note:[ContextStatic()] identifies that the static member is static for only the objects included in the same context
29
Creating your attribute
Derive from System.attribute Ex:sealed class MyCustomAttribute:System.Attribute Note: you declare it MyCustomAttribute but you can use it as [MyCustom]
30
Restricting usage You do that by adding an attribute on top of the attribute class Ex: [AttributeUsage(AttributeTarget.Class)] sealed class MyCustomAttribute: System.Attribute Note: AttributeTarget is a collection where you can select class, assembly…. Or all
31
Attribute paramters You have the necessary onesshould be included in the constructor Public myattr(string name string ) { Name = name; = }
32
Cust. Attributes use Custom attributes are used to server some functionality that the user wants to support. He can get the declared attributes through the metadata and let his code execute adequately. Note that neither the runtime nor the compiler have something to do with the cust. attributes
33
How to get the declared attributes
Attribute[] attributes= Attribute.GetCustomAttributes(typeof(SomeClass),typeof(DeveloperInfoAttribute)) Will return all the attributes declared on the class(someclass). Note that this command will also get the derived attributes from DeveloperInfoAttribute
34
Use example of cust. attribute
Attribute devenfo with name as param Declare devenfo on a class that throws an exception and calls custom exception. And passes itself as param In custom exception get the attribute and print the developer name whose code caused the exception WOULDN’T IT BE NICE IF WE CAN GET RID OF THE TRY CATCH TOO?
35
AOP If an object is in a context, it is wrapped and access to it is done through message passing. What if we can intercept these messages? To throw exceptions, do logging…. This is done through Sink chains
36
Sink Chains Usually four: Envoy Sink Client Context Server Context
Object Sink So?... Create your own sink
37
Sink Creation Implement the IMessageSink interface
Constructor that accepts a ref to next sink Implement Next sink to return the reference to the next sink Implement SyncProcessMesage() that performes preprocessing of the message before passing it on to the next sink. In addition to processing the return of this message Implement the AsynProcessMessage(). Preprocess asynchronous calls.
38
How the process works Create a context attribute(an attribute that implements the IContextAttribute interface) Add it to a context bound object When the runtime creatise the context bound object, it iterates through all the attributes applied to the object’s class and calls IsContextOk(). If any of the call return falsecall GetPropertiesForNewContext() wich instantiates a contect property and creates the chain.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.