Showing posts with label Attribute. Show all posts
Showing posts with label Attribute. Show all posts

Wednesday, January 30, 2013

Creating an Attribute in C#

In C#, attribute is one of the common declarative technique that most of us is using into our application. Usually, we use the attribute to tag or flag a class, method or property in the form of object base recognition. It also simplify our determination in every object.

Furthermore, in C# there are lots of pre-defined attribute that we can embed into our application. One common sample is SerializableAttribute which flag/tag our class to participate in serialization/deserialization process. If however you would like to extend the attribute functionality and define your own, you can extend/inherit the attribute class from System namespace.

Please visit C# Flags Attribute blog before you continue. The reason is to let you explore the enumeration named Privilege.

Now, we are expecting that you already explore the Privilege enumeration form mentioned  blog above.

Let say for example you would like to define a scenario that gives your code-level to determine whether a class (or a stub object) can be deleted from database. See below our sample custom attribute.

public class SecurityAccess : Attribute
{
    public SecurityAccess()
    {
    }

    public SecurityAccess(Privilege privilege)
        : this()
    {
        this.Privilege = privilege;
    }

    public Privilege Privilege
    {
        get;
        set;
    }
}

What the class SecurityAccess is doing above is just simply handling the value for the Privilege enumeration. This property defines whether the class that declare this attribute has an enough level of privilege before doing necessary action in the database.

How to use custom attribute?

Now, in this section, we will going to guide you how to use the attribute we created above.

Suppose we have two class that inherits from one object. Let's call them Animal, and the two other class in Cat and Dog. See below implementation.

public class Animal
{
    public bool IsDeletable
    {
        get;
        protected set;
    }
}

public class Cat : Animal
{
    public Cat()
    {
    }
}

public class Dog : Animal
{
    public Dog()
    {
    }
}

The Dog and Cat is an Animal base on our implementation. With the use of our custom attribute named SecurityPrivilege, we can declare each privilege in every class. Suppose we would like different breed of Cat cannot be deleted from our database, then we can declare our custom attribute like below.

[SecurityAccess(Privilege = Privilege.Read | Privilege.Write | Privilege.Create)]
public class Cat : Animal
{
    public Cat()
    {

    }
}

And the Dog breed is deletable. See below.

[SecurityAccess(Privilege = Privilege.Read | Privilege.Write | Privilege.Create | Privilege.Delete)]
public class Dog : Animal
{
    public Dog()
    {

    }
}

How to access an attribute value declared in the class/method and other object?

Now, in this section, we will going to guide you how to access the value of the attribute per class level.

In C#, the only way to get the attribute value is to use Reflection. First, we need to get the current type of the object, from there check if there are declared custom attributes and determine the attribute type. If its match the attribute we're looking for, then that is the custom attribute we had created. See below the process.

protected T GetCustomAttribute<T>(object @object)
{
    if (!object.ReferenceEquals(@object, null))
    {
        var type = @object.GetType();
        var attrs = type.GetCustomAttributes(false);
        if (attrs.Length > 0)
        {
            foreach (var attr in attrs)
            {
                if (attr is T)
                {
                    return (T)(object)attr;
                }
            }
        }
    }
    return default(T);
}

What the code is doing above is to simply return the embedded attribute in the object you passed in the parameter named @object. If there is no attribute found, then it will return null. Best to place this code in the Animal base class so both derive class can use it.

And now, in the construction of Dog and Cat class, you should call the method directly from there.

public Dog()
{
    var attr = this.GetCustomAttribute<SecurityAccess>(this);
    base.IsDeletable = (attr.Privilege & Privilege.Delete) == Privilege.Delete;
}

public Cat()
{
    var attr = this.GetCustomAttribute<SecurityAccess>(this);
    base.IsDeletable = (attr.Privilege & Privilege.Delete) == Privilege.Delete;
}

Now, in the base class IsDeletable property, we then set it depends on the privilege level we declared on the class.

Please note that we can override the attribute value declared in the base class into derive class. So if you want that the Siamese Cat breed be deletable, you can declare your own SecurityAccess attribute in Siamese class.

That's all about this blog. Please follow us so you will get more interesting topics soon.

Please visit Microsoft documentation for further details.

Tuesday, January 22, 2013

C# Flags Attribute

The FlagsAttribute is an attribute that can be placed on your enumeration in order to be comparable with multiple enumeration values. Usually, this attribute uses bitwise operation in the comparison. Please visit Microsoft documentation for further details.

Please visit C# Bitwise blog for you to understand further the bitwise operation.

Here we created a very simple enumeration named Privilege that enumerate the kind of privileges we can give to every user of our website.

[FlagsAttribute]
public enum Privilege : short
{
    Read = 1,
    Write = 2,
    Delete = 4,
    Create = 8,
    Share = 16,
    Append = 32,
    Assign = 64
}

You will see above we declared the Privilege enumeration with FlagsAttribute. Unfortunately in order the value of the enumerations to be participated in bitwise operation we need to declare its value in proper decimal value. In our case, we need to enumerate the value 1, 2, 4, 8, 16, 32 and so on.

Now, using this enumeration in your class can now be checked with bitwise comparison. See our class below declaring the Privilege class.

public class User
{
    public User(string username)
    {
        this.Username = username;
    }

    public string Username
    {
        get;
        private set;
    }

    public Privilege Privilege
    {
        get;
        set;
    }
}

The class declared above named User has property Username of type String and Privilege of type Privilege. Now using this class, we can set the bitwise value of the Privilege property. See the codes below how to do it.

var user = new User(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
user.Privilege = (Privilege.Read | Privilege.Write | Privilege.Delete | Privilege.Create);

What the above code is doing is, it has created a new object User passing the current Windows Log On name. After that, it set the Privilege property value to Read, Write, Delete and Create. With the help of the Flags attribute, we now participated in bitwise operation by the use of the "|" operator. This mean that the privilege property has now the value of the Privilege enum's Read, Write, Delete and Create.

Checking the presence of the Enumeration value in bitmap operation is very easy in C#. We are now required to use the "&" operator to address it. See the code below.

if ((user.Privilege & Privilege.Delete) == Privilege.Delete)
{
    /* do the delete code */
}
else if ((user.Privilege & Privilege.Append) == Privilege.Append)
{
    /* do the append code */
}
else
{
    /* do nothing */
}

What the code doing above is to simply determine whether the Privilege property has the defined Privilege enumeration value. In short, we are asking if the User.Privilege property has Privilege.Delete value.

Narrowing Bitwise Operations

The operator "-" is used to narrow the values of the Bitwise operation. See the code below how to do it.

user.Privilege -= Privilege.Delete;

With the code above, we are removing the Delete Privilege value from the User.Privilege property. You will then see that the only remaining bitwise value for the User.Privilege property is Read, Write and Create.

Widening Bitwise Operations

The operator "|" is used in widening of the Bitwise operation. See the code below how to do it.

user.Privilege |= Privilege.Assign;

Same with narrowing, what we did is that we simply added a new Privilege enumeration value Assign in to the User.Privilege property. By checking the User.Privilege property value is now Read, Write, Create and Assign.

Now that you know how to do it, have a happy coding. Tweak tweak tweak your codes now ;)

C# Bitwise

Understanding Bitwise Operation

The bitwise comparison commonly used the binary to build bit-mask entries same of what by boolean type used (AND, OR, XOR, NOT)In computer world, each bit is the sum of smaller bits based on the placement. It is very easy for the computer's algorithm to read and understand it as it only uses 1 or 0 value (same with the boolean type). Please see the table below for you to understand further.


In the above's table, the bit value is 00101100. Also, you will notice that above each bit octet has its corresponding decimal value. In every bit 1 value is equal to its corresponding decimal value. So based on the table above we have:

( 1 = 0, 2 = 0, 4 = 1, 8 = 1, 16 = 0, 32 = 1, 64 = 0, 128 = 0 )

We have 4, 8 and 32 decimal values equates by bit 1. By adding this value, it would equal the decimal value of the bits total. In our case, 4 + 8 + 32 is equals to 44.

So the decimal value of binary value 00101100 is 44.

Please visit Microsoft documentation for the bitwise and its operators for more information.