Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Ads by Lake Quincy Media
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » COM Interop » Create DCOM application from within .Net environment: Part V

Create DCOM application from within .Net environment: Part V

This article explains how to develop a DCOM (Distributed Component Model) application.

Author Rank:
Total page views :  5333
Total downloads :  84
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Bejaoui2.zip
 
Become a Sponsor


It may be a necessity to develop a serviced component that will be consumed from a remote machine and at the same time it must be COM in order to cover the largest kind of client needs regardless of their natures as the clients aren't only .Net applications but they could be also issued from other environments such as Visual basic 6.0, Visual C++ or even a Java client applications, therefore, DCOM that stands for distributed component object model is used.

I invite you to follow this walkthrough to understand how a DCOM application is developed from A to Z.

Walkthrough:

  1. First, let's start by creating a new (*.dll) application under Visual Studio 2005/2008 by selecting File>New> Project>Class library then name it Person.

  2. Then create a new object called Person that looks like bellow and don't forget to add reference to System.IO and System.Xml.Serialization in order to use the StreamWriter and the XmlSerializer objects.

    public class Person
    {
        public string FirstName{get;set;}
        public string LastName { get; set; }
        public bool IsMale { get; set; }
        public void Persist(string FilePath)
        {
            StreamWriter oFile = new StreamWriter(FilePath);
            XmlSerializer oXmlSerializer = new XmlSerializer(typeof(Person));
            oXmlSerializer.Serialize(oFile, this);
            oFile.Flush();
            oFile.Close();
        }

    }

  3. Add a reference to the System.Runtime.InteropServices that contains some useful classes used for exposing the initial .Net assembly to COM.

    In order to be exposed to COM, an assembly has to be strongly named. It means that it must be signed before. To sign the given assembly, go to Project menu> <Project name> property. As your project is named Person then you will find exactly Person Properties… at the bottom of the Project menu.

  4. Select the signing tab



    Figure 1.

  5. Check the "Sign the assembly checkbox".

  6. A combo box just as bellow will invite you either to create a new key pair for the assembly and store them in a *.snk file or to use an already existing *.snk file.

  7. Choose the first alternative

  8. Then set the file name in the above text box and the password in the other text boxes then click OK.



    Figure 2.

  9. As you create a key pair, the assembly could be strongly named.

  10. In the solution explorer, expand the project properties node and edit the AssemblyInfo.cs then add those three attributes, if you can't find ApplicationName, ApplicationActivation and AssemblyKeyFile elements then add a reference to System.EnterpriseServices

    //Those are additional attributes that have to be added to the project
    [assembly:ApplicationName("Person") ]
    [assembly:ApplicationActivation(ActivationOption.Library)]
    [assembly: AssemblyKeyFile(@"C:\Person\Person\yournameanddate.snk")]

    The first attribute indicates the application name. The second one indicates the activation option, by the way, the activation option could have one among two values either library or server.

At the difference of the COM context, within witch the Activation Option of the Application Activation attribute is set to library. This once is set to server to indicate that the serviced component will run in its own process context.

Always within the AssemblyInfo.cs, do change the ComVisible attribute to true in order to be visible to the COM client application

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]

Remarque about the GUID:

At the contrast of the .Net serviced component that is identified by the IP address and a given serial port. The COM serviced component is identified by the GUID that stands for globally unique identifier. It is a 128-bit integer (16 bytes) that could be used across all computers and networks as a COM assembly unique identifier.

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a383a2de-fbf7-4195-cb2e-zb929e027f6a")]

  1. Now, turn back to the Person class because there are some modifications and tasks that one should do before exposing the assembly to COM.

  2. In fact when you expose the assembly to COM, the client application will interact with your serviced component via interface. Therefore you have to extract an interface from your class as follow.

    a) Go to Refactor menu then select extract interface, but first be sure to put the cursor inside the class.



    Figure 3.

    b) Choose all members of the Person class then click OK



    Figure 4.

  3. Decorate the class with [ClassInterface( ClassInterfaceType.None)]

  4. In the other side, Person class inherits from System.EnterpriseServices.ServicedComponent as an obligation, because all the classes exposed to COM must inherits from this class , the resulted class must look like this

    namespace COM
    {
       [ClassInterface( ClassInterfaceType.None)]
       public class Person : System.EnterpriseServices.ServicedComponent, COM.IPerson
        {
            public string FirstName{get;set;}
            public string LastName { get; set; }
            public bool IsMale { get; set; }
            public void Persist(string FilePath)
            {
                StreamWriter oFile = new StreamWriter(FilePath);
                XmlSerializer oXmlSerializer = new XmlSerializer(typeof(Person));
                oXmlSerializer.Serialize(oFile, this);
                oFile.Flush();
                oFile.Close();
            }
            static public Person Retrieve(string FilePath)
            {
                StreamReader oFile = new StreamReader(FilePath);
                XmlSerializer oXmlSerilizer = new XmlSerializer(typeof(Person));
                Person oPerson = oXmlSerilizer.Deserialize(oFile) as Person;
                return oPerson;
              
            }
        }
    }

  5. Don't forget to change the accessibility of the interface to public

    using
    System;
    namespace COM
    {
        public interface IPerson
        {
            string FirstName { get; set; }
            bool IsMale { get; set; }
            string LastName { get; set; }
            void Persist(string FilePath);
        }
     
  6. Finally, build the project, and verify if there aren't any error within the application.

  7. Now it is the ultimate step, so open the SDK command prompt Start>All programs>Accessories>Command prompt then type this


     

  8. Now, you will expose your serviced component to be largely consumed by different client applications within a remoting context, to perform that, you have to browse to Start>Configuration panel>Administration tools>Serviced components.

  9. Open the management console and expand the tree then localize the Person COM serviced component



    Figure 5.

  10. Then export it by right clicking the Person application as bellow



    Figure 6.

  11. Then the bellow window appears, in fact this dialog box will lead you to generate an (*.msi)



    Figure 7.

File that it will be deployed easily in the remoting machines. So in the browse machine, put the path where you exactly want your component to be deployed, and then check the server application radio because you don't need a proxy in this case, but check the application proxy if you have to install your COM in the distant machine so that a proxy class that represent the remote serviced component will be generated and exposed to the client. Other important issue, if you want to prefix the users and roles and embed information about them for a pure security purposes based on roles and identities, then check export the identity of users and roles check box. Also, there is another important issue, is that you have to check the save application as COM+ 1.0, if you want to ship your product according to this format. After that, click next then finally click finish and an (*.msi) file will be generated of you.

24. Browse to the location where the (*.msi) is generated



Figure 8.

Lastly, the serviced component is ready to be distributed and consumed. That's it. Now, to consume DCOM serviced component, you should first determine the nature of the client application whether it is a .Net client application or other kind of client applications.

In this case, I will be concerned only by the first kind of clients as the others are out of the scope of this article. Now, concerning the .Net client application the .Net remoting is the only way to consume a DCOM services as the DCOM protocol is not supported in such context. In the other side, two ways those could be proposed to consume a DCOM service namely the Singleton server object or Single call server object. But you ask me how to consume a DCOM serviced component using .Net remoting and at the same time it doesn't inherits the Marshal By Ref Object class, I answer you, remember that the class Person inherits the class Serviced Component and this last one inherits the Marshal By Ref Object something that renders the COM distributed, hence, it could be consumed through a .Net remoting like any other .Net server side applications.

Good Dotneting!!!







 


Login to add your contents and source code to this article
 About the author
 
Bechir Bejaoui
The author holds a master degree in NTIC specialized  in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by  the  economic sciences and  management  university of Tunis "FSEGT". He's a freelance developer since 2006. Actually woking on the WPF, .Net framewok 3.5, silverlight and the other .Net new features, in addition, he is painter and sculptor.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Bejaoui2.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Consuming DCOM by Maxim On November 26, 2008
Awesome! Just p.7 is missing (regsvcs.exe) - it can be found in the Part II of the series. So, I created a package, installed it on a server machine as  Application Server and installed it on a client machine as Application Proxy and it can be consumed by non managed client?
Reply | Email | Delete | Modify | 
Re: Consuming DCOM by Bechir On November 26, 2008

It could be consumed by both managed and unmanaged client but  there are a couple of advises that I could provide in this context, is in fact, if a DCOM is leveraged by  .Net then it is worth to use .Net remoting if you will consume the DCOM from a .Net client, you tell me why should I use .Net over the DCOM protocol, it simply because it id not supported by .Net client application and all DCOM objects are derived from the ServicedComponent class that inherit it self the famous MarshalByRefObject class, the main used class in a .Net remoting context
Other thing that could be said,  in certain condition that happened to me and I don't know if you have already encountred this situation, the Visual Studio is not able to recompile or update the component when it is modified during the developement cycle. It dues to the dllhost assembly  to prevent that from happening you have to kill the dllhost.exe relative process
Reply | Email | Delete | Modify | 
Re: Re: Consuming DCOM by Maxim On November 26, 2008
First I recompiled the component project and it was updated on my development machine on condition that no application was consuming it that moment.
My problem is: i need to consume it by non managed clients and if possible without installing .NET framework on every client machine (only on the server).
Another issue was config file, that is not loaded by a library and must be forced to load (like ConfigurationManager.OpenExeConfiguration(...) or any suitable IO class).

Reply | Email | Delete | Modify | 
Re: Consuming DCOM by Bechir On November 26, 2008

Please don't forget to give you rate
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.