namrata's profileNashaPhotosBlogListsMore Tools Help

Blog


    January 19

    Article : COM + Services Part 6 ( Security )

    Today we will implement Role based Security in COM+ Components

    Before we go ahead there have been a lot of times when I have been approached with these questions: - 

    a) How do we start a transaction on COM+?
            In COM+ transaction is implicitly started for all the methods, which are present in the serviced component. There is no way to explicitly start the transaction like begin trans etc.

    b) What type of methods should be present in COM+ components?
            Only those methods that change data should be kept in serviced components. Methods that only retrieve data like GetEmployeeList etc. should not be placed in serviced components.

    c) Is using AutoComplete good?
            Yes. But provided you have done a robust error handling and u are sure to complete your transaction. If not go in for the SetComplete and SetAbort style ... I know its a little old fashioned but it is robust.

    d) If there are two methods in a serviced class say method A and method B and from A there is a call to B then should I call SetComplete from B?
            Yes. We should always remember that COM+ and MTS works on a two phase commit protocol hence every operation has to acknowledge whether it was a success or a failure. Hence all the methods need to either call SetAbort or SetComplete.

    Enabling Role-based security: -

    To enable Role - based Security in our COM+ Components .NET Framework provides us with ContextUtil.IsCallerRole() method. This method authenticates the current user with a Windows 2000 user group and returns a boolean value.

    E.g. To validate whether the current user is a part of  a windows user group "DotNet"

            If(ContextUtil.IsCallerInRole("DotNet") == true)
            {
                    // to perform the required operation
            }

    Add the above code to our Manager classes so that only those users, which belong to the Dot Net user group, will be able to update employee' s details.

    We can also check whether the called component has an existing transaction or not.

    To check whether the called component is in transaction or not .NET framework provides us with ContextUtil.IsInTransaction() method.

    e.g. To check whether there is an existing transaction or not

            If(ContextUtil.IsInTransaction == false)
            {
                    // Perform the required action
            }

    Article : COM + Services Part 5 ( .NET Implementation Contd.)

    Today we will create a client app for our COM+ component the different types of COM+ applications and how to implement JIT and ObjectPooling in them.

    Registering our component and creating a client App:   

    Well All COM+ Components need to be registered with COM+ Services.But before that they need to be strong named hence we will create a strong name using strong name utility and sign all our assemblies with it.

    a. Create a strong name key pair using sn -k "MyKey.snk"
    b. Sign your Serviced Assembly i.e. your Buss Layer and also all those, which are used by your Serviced Component
    c. Change the AssemblyInfo.cs and set the AssemblyKeyFile Attribute as follows [assembly: AssemblyKeyFile    ("..\\..\\MyKey.snk")] and place the MyKey.snk in the project folder.
    d. Build the Solution Components will be registered on the local machines.
    e. To register the assembly on any other machine you can user regsvcs .. Check my blog on .Net framework Tools to know more about it.

    Note:- If your COM Component is used by Managed Code then you dont need to register them explicitly with regscvs as the moment you call a function on the serviced component CLR will automatically register it with COM+. You need to register COM+ components explicitly only if they are being used by unmanaged code coz in that case regsvcs will create corresponding type library for it.

    Lets us now create our cliient app.

    a.Open a Windows or an ASP.NET application
    b. Add References to EmpEntity and Buss Layer DLLs. Also add reference to System.EnterpriseServices
    c. Add a button and write the following code to create the Employee entity and an Arraylist containing Skill entities.
    d. Pass the Employee entity to the EmployeeManager for updation.

                    private void button1_Click(object sender, System.EventArgs e)
                    {
                            EmpEntity.Employee emp = new EmpEntity.Employee();
                            emp.Skills = new ArrayList();
                            Skill skill;
                            for(int i=0; i<10; i++)
                            {
                                    skill = new Skill();
                                    skill.Name = "Skill "  + i;
                                    skill.TotalExpWithSkill = i;
                                    emp.Skills.Add(skill);
                            }
                            BussDLL.EmployeeManager empMgr = new BussDLL.EmployeeManager();
                            empMgr.UpdateEmployee(emp);
                    }

    Compile the project and run it.

    Types of COM+ Components:-

    There are two types of COM+ applications Library Application and Server Application.

    Library Application: - Components of libaray application type are instantiated in client process i.e. there instantiation is done in the caller's process.

    Server Application: - Server application components are instantiated in a serparate process this process is generally a surrogate process that is instantiated only for the components.

    To set the type COM+ application can be done both from the MMC for COM+ Services and code. We will check out how to set it from code.

    There is an attribute called ApplicationActivation you can use this to set the Activation type to either Library or Server. We need to add this to the AssemblyInfo.cs file

            [assembly: ApplicationActivation(ActivationOption.Server)]

    The ActivationOption can be either Server or Library.


    Enabling ObjectPooling : -

    To enable object pooling for .NET components we need to add ObjectPooling attribute to the class.

    [ObjectPooling(Enabled=true, MinPoolSize=1,MaxPoolSize=10)]

    You can even override the following methods to provide customization
    a.CanBePooled
    b.Activate
    c.Deactivate

    Enable JIT: -

    To enable JIT we need to add JustInTimeActivation Attribute to the class

    [JustInTimeActivation(true)]

    Article : COM + Services Part 4 ( .NET Implementation )

    For using COM+ Services from .NET Assemblies is possible with help of System.EnterprisesServices Namespace.

    Let us create a three tiered application containing a Business Manager classes, an Entity and a Data Layer class along with a client which uses the Buss layer object. We will start by creating Entity and DB layer classes.

    The flow goes like this: Our Client creates an Employee object. This employee object has Employee data  and data about employee's skills. Our client calls methods on the Employee Manager by passing the Employee object. Employee Manager calls the UpdateEmployee method on the EmpDataStore by passing the Employee object and then calls the UpdateEmpSkills method on EmpSkillsManager to update employee's skills data. 

    Creating the Employee and Skill Entities

    1) Open a Class Library name it EmpEntity and add a class named Employee and add the below code to it.

    using System;
    namespace EmpEntity
    {
            public class Employee
            {
                    private string name;
                    private ArrayList skills; // will hold an arraylist of Skill objects
                    private string address;
                    public Employee()
                    {}

                    public string Name
                    {
                            get{return name;}
                            set{ name = value;}
                    }
                   
                    public string Address
                    {
                            get{return address;}                   
                            set{address = value;}
                    }

                    public ArrayList Skills
                    {
                            get{return skills;}
                            set{skills = value;}
                    }
            }
    }

    using System;
    namespace EmpEntity
    {
            public class Skill
            {
                    private string name;
                    private int totexp;
                    public Skill()
                    {}
                    public string Name
                    {
                            get{return name;}
                            set{name = value;}
                    }
                    public int TotalExpWithSkill
                    {
                            get{return totexp;}
                            set{totexp =value;}
                    }
            }
    }



    Creating the EmpDataStore and SkillDataStore

    1) Open a new class library project name it EmpDataDLL and add the below two classes
    2) Add Reference to EmpEntity

    using System;
    using EmpEntity;
    using System.Data;
    using System.Data.SqlClient;

    namespace EmpDataDLL
    {
            public class EmpDataStore
            {
                    public EmpDataStore()
                    {}

                    public void UpdateEmployee(Employee emp)
                    {
                            // Implementation using ADO.NET to update the
                            // Emp details to the Employee Table
                    }
            }
    }
                   

    using System;

    namespace EmpDataDLL
    {
            public class SkillDataStore
            {
                    public SkillDataStore()
                    {}

                    public void UpdateSkill(ArrayList skills)
                    {
                        // Implementation using ADO.NET to update the  Emp Skills

                        //details by parsing through the arraylist to update the Employee Skills table
                    }
            }
    }

    Creating the Buss Managers or the Serviced Components

    Any component that has to be COM+ component or as we call it a serviced component in .NET has to subclass from a class called
    Serviced Component.

    1) Open a new class Library project named BussDLL.
    2) Add Reference to System.Enterprises namespace
    3) Create two new classes EmployeeManager and EmpSkillsManager and subclass it from ServicedComponent.

    After we have created a serviced component let us see how we can implement transactions using Transaction and AutoComplete
    Attribute and ContextUtil class.

    We have seen that there are various transaction types that COM+ components can have. You can set the components transaction type from the COM+ Services MMC interface but to implement the transaction type of the component you need to set the Transaction attribute.

    To implement Transactions in .NET we need to first set the transaction option.

    Transaction option can be set only at a class level using the Transaction Attribute. Transaction Attribute takes a parameter called as TransactionOption where you can mention the transaction type as follows :

    [Transaction(TransactionOption.Required)]  // you can mention any one of the five available types.

    4) Add the Transaction attribute at the top of the classes.

    MTS and COM+ both work on a two-phase commit protocol i.e. the transaction will either succeed or fail and all operations taking part in the transaction need to acknowledge its caller whether it succeeded or not. Hence when the transaction is through successfully we need to complete the transaction if we have to rollback we need to abort the transaction.  When a transaction is aborted at any stage all the operations prior to the operation, which failed, are automatically roll-backed. To complete or abort a transaction we need to get its Context.... when I say context what I mean is a handle to the current transaction. There is a class in .NET called as ContextUtil that retrieves the current transaction context. All you need to do is just refer to the class in your code.

    5) Add a method named UpdateEmployee to EmployeeManager class from where we will update employee's info. In this method we receive an employee object which we will send to EmpDataStore class to update employee data in the DB.

    Any Transaction is completed using the SetComplete() method of ContextUtil class and aborted using SetAbort() method.

    6) Finally our class should look something like this

    using System.EnterpriseServices;
    using EmpEntity;
    using EmpDataDLL;
    using System;

    namespace BussDLL
    {
            [Transaction(TransactionOption.Required)]
            public class EmployeeManager:ServicedComponent
            {
                    public EmployeeManager()
                    {}             
                    public void UpdateEmployee(Employee emp)
                    {
                            try
                            {
                                EmpDataDLL.EmpDataStore empDataStore= new EmpDataDLL.EmpDataStore();
                                empDataStore.UpdateEmployee(emp);
                                EmpSkillsManager empSkillMgr = new EmpSkillsManager();
                                empSkillMgr.UpdateSkill(emp);                          
                                ContextUtil.SetComplete();
                            }
                            catch(Exception ex)
                            {
                                    ContextUtil.SetAbort();
                                    throw ex;
                            }
                    }
            }
    }

    Note: - The call to the EmpDataStore is in a try catch block hence if any exception is thrown from the Database layer it will be caught and we will successfully rollback the transaction. If everything goes smooth we go ahead and complete the transaction.

    Similarly we will create the EmpSkillsManager class

    using System;
    using System.Collections;
    using System.EnterpriseServices;
    using EmpDataDLL;
    namespace BussDLL
    {
            public class EmpSkillsManager:ServicedComponent
            {
                    public EmpSkillsManager() {}
                    public void UpdateSkill(EmpEntity.Employee emp)
                    {
                            EmpDataDLL.SkillDataStore skillsDB = new SkillDataStore();
                                    skillsDB.UpdateSkill(emp.Skills);
                                    ContextUtil.SetComplete();
                    }
            }
    }


    Sometimes we want that if everything goes fine the transaction should be automatically completed only incase of any failure when an exception is raised the transaction should be aborted. In that case we can use the AutoComplete attribute i.e. [AutoComplete]

    AutoComplete attribute is used at function level. When we use AutoComplete we need not call SetComplete but yes we need to call SetAbort.

    Using the AutoComplete attribute

    namespace BussDLL
    {
            [Transaction(TransactionOption.Required)]
            public class EmployeeManager
            {
                    public EmployeeManager()
                    {}
                    [AutoComplete] 
                    public void UpdateEmployee(Employee emp)
                    {
                            try
                            {
                                    EmpDataDLL.EmployeeDataStore empDataStore= new EmpDataDLL.EmployeeDataStore();
                                    empDataStore.Update(emp);
                            }
                            catch(Exception ex)
                            {
                                    ContextUtil.SetAbort();
                                    throw ex;
                            }
                    }
            }
    }

    January 16

    COM+ Services Series ( Part - 3 )

    Today we will discuss ECC features of COM+. These features were not present in MTS and but are present in COM+ Services.

    Events: - This is a new service that has been added in COM+. This service one has to register an event interface with COM+ Services. Then you register classes that raise this event. These classes are called as publishers. After registering publishers you create classes that handle the raised events. These are called as subscribers. This model is also called as publisher-subscriber model. Hence when publisher raises an event COM+ will notify all its subscribers.

    Here COM+ acts as an intermediate layer between publisher class and subscriber classes so that they do not refer each other directly.

    Component Message Queuing: - In the past a lot of times there have been instances when we have faced problems of the component not being available or the component being offline. For these situations we had to provide some error handling logic. But COM+ now provides us with a new option for queuing requests for any offline component so that when the component comes online it can forward the request to the component. All these things happen behind the scene and the client is completely unaware of this. As soon as the component available the requests are executed and the results are sent to the client.

    But if we have looking forward for this option then we should have robust error handling coz it should not happen the client is waiting for prolonged period of time or even if the component is available the request raised an error or exception.

    Component Load Balancing: - This is one of the most important feature of COM+. Component load balancing is used to cater a large number of clients by balancing client requests between COM+ Components. When one feels that one server is not enough to provide a quick response to the clients and the client response time is increasing, you can have multiple servers hosting your components. Component Load balancing is used to balance the number requests across servers. It distributes client requests across component servers thus enabling a fast and better performance and reducing the response time.

     If we were to consider component load balancing we should keep in mind the fact the request may not go to the same server every time. Hence the architecture of all our objects should stateless. I had discussed this before also when we checked out JIT and object pooling. Object pooling is not available when Component Load balancing is done for obvious reasons coz you do not where the previous request was executed

    COM+ Services Series ( Part - 2 )

    Let us first discuss the JOTS features. These features were present in MTS and are present in COM+ Service also.

    Just-In-Time Activation: - Object creation by itself is a very expensive process hence before instantiating an object we need to consider a lot of parameters like the amount of memory it will take, how many objects will be created at any given point of time, after instantiating objects how will we deallocate its memory, etc.

    Just-in-time Activation allows the developer to create an object once and then use it wherever required without worrying about resources consumed by that object. This is because behind the scenes JIT deallocates the memory when the object is not used and then reallocates then when the client references the object or calls any method on them. Thus the client can hold references to as many objects required coz COM+ will provide objects whenever necessary and deallocate them when required.

    Since JIT deallocates memory it is quite possible that it may dellocate memory between two function calls, thus there is no guarantee that the same property values will be available between subsequent calls. Hence the COM+ objects should ideally be stateless (i.e. should not have properties).

    Object Pooling:

    - We just discussed JIT and saw how COM+ handles its memory allocation and deallocation coz object creation is an expensive process. Further on to that COM+ even allows you to create an object pool to reuse objects that are created. Whenever any COM+ client releases an object COM+ does not destroy the object if ObjectPooling is enabled but sends the object to the Pool to reuse the object when some other client asks for the same.

    By Nature object Pooling can share the object instance between several clients. Thus if you have properties in your class they will be shared across all the clients. Hence to avoid this it is a good practice to create class that are stateless. So that in between function calls there is no need to maintain the state.

    Note:

    - JIT and Object Pooling together make the heart of COM+. Object Pooling may have a pool of objects reusable across clients but its JIT that decides its allocation and deallocation. Thus making the objects stateless is a very good practice coz then we can use both the services effectively as our classes reduce to function libraries.

    Transaction Enforcement: - There are 5 transactions types that can be used with COM+. Whenever an object is registered with COM+ it has to abide either to these 5 transaction types.

    Disabled: - There is no transaction. COM+ does not provide transaction support for this component.

    Not Supported: - Component does not support transactions. Hence even if the calling component in the hierarchy is transaction enabled this component will not participate in the transaction.

    Supported

    : - Components with transaction type supported will be a part of the transaction if the calling component has an active transaction.

    If the calling component is not transaction enabled this component will not start a new transaction.

    Required: - Components with this attribute require a transaction i.e. either the calling should have a transaction in place else this component will start a new transaction.

    Required

    New: - Components enabled with this transaction type always require a new transaction. Components with required new transaction type instantiate a new transaction for themselves every time.

    Security

    : - This is another important aspect of COM+. This allows granting access rights to users at component level. COM+ allows you to create roles and add users to these roles. Hence when a user tries to instantiate an object COM+ checks the users role. You can define different roles and access rights for these roles. If the user is in role defined he/she will be granted rights as defined for that role.

    COM+ Services Series ( Part - 1 )

    Today we are going to discuss COM+ Services. Some of us know COM+ coz we have worked with MTS during our VB days. However COM+ can be used with .NET also. As a developer I have always inquisitive about a lot questions and I am sure that you must also be having these questions in mind. Let us discuss these: -

    Why COM+ ?

    Well COM+ by itself is a service where you deploy your transaction-based components. Once can say that it is reusable service which can help you in implementing and executing your transactions so that you need not be bothered about the repetitive" transaction execution and management" logic all the time.

    What is MTS and what is difference between MTS and COM +?

    During our VB days with Win NT one could use COM+ Services with the help of MTS i.e. Microsoft Transaction Server. You needed to explicitly install MTS.  After WinNT came Win 2k where it has been an integral part of OS. COM+ services in addition to MTS has come more features like:

    Common features in both MTS and COM+:

    • Just In Time object activation (JIT)
    • Object Pooling
    • Transaction Enforcement
    • Security

    I remember them as JOTS features.

    New Features in COM+:

    • Event Support
    • Component message queuing
    • Component Load Balancing

    I remember them as ECC features.

    What are Transactions? Are they really necessary? What can they do for you?

    Transaction is a set operations that need to work as a unit to either fail or succeed. Whether transactions are really necessary or not totally depends on your requirement e.g. If you are making a banking application where during a Credit transaction money has to be debited from one account and credited to another account. In this scenario it will not work if either debit or credit happens both either need to happen or not. You can also use the ADO or ADO.NET Connection object to execute them under a single transaction.

    How do transactions work?

    COM+ services are controlled by DTC i.e. Distributed Transaction Coordinator. It is DTC, which takes care of transaction execution and is responsible for commit or rollback. DTC works on a "Two - Phase Commit" protocol. Transaction by itself is a unit containing a number of operations. Two phase commit ensures that the transaction is commit only if each of these operations succeed if any one of these operations participating in the transaction fail, the entire transaction is roll backed completely. Thus protocol ensures a successful commit or a rollback.

    Tomorrow we will discuss each of COM+ features in depth. If you have any questions on the basics that we discussed today please post them.