NET Interoperability Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on NET Interoperability

Question 1.
How can we use COM Components in .NET?
.NET components communicate with COM using RCW (Runtime Callable Wrapper). Following are the ways with which you can generate RCW:

  • Adding reference in Visual Studio.NET. See Figure 19.1 (Adding reference using VS.NET 2005). Wrapper class is generated and placed in the “BIN” directory.

NET Interoperability Interview Questions in .NET chapter 19 img 1

  • UsingTypelibraryimporttool.Tlbimp.exeyourname.dll.

• Using interopservices .The system, runtime. Interopservic’es namespace contains class TypeLibConverter that provides methods to convert COM classes and interface into assembly metadata.
• Make your custom wrappers, if your COM component does not have a type library then the only way to communicate is by writing custom wrappers. That means communicating directly with COM components.

Question 2.
We have developed the COM wrapper do we have to still register the COM?

Question 3.
How can we use .NET components in COM?
.NET components cannot be used in a straightforward way with COM. You will need to create CCW (COM Callable Wrapper) in order that COM components communicate with .NET assemblies. Following are the different approaches to implement it:

  • Explicitly declare interfaces.
Public Interface ICustomer
Property CustomerName( ) As String
Property CustomerCode() As String
Sub AddCustomer( )
End Interface
Public Class Customer
Implements ICustomer
Private PstrCustomerName As String
Private PstrCustomerCode As String
Public Sub AddCustomer() Implements ICustomer.AddCustomer
' addin of database code can go here
Catch ex As Exception
Throw ex
End Try
End Sub
Public Property CustomerCode() As String Implements ICustomer.CustomerCode
Return PstrCustomerCode
End Get
Set(ByVal value As String)
PstrCustomerCode = value
End Set
End Property
Public Property CustomerName() As String Implements ICustomer.CustomerName
Return PstrCustomerName End Get
Set(ByVal value As String)
PstrCustomerName = value End Set
End Property
Public Sub New( )
End Sub
End Class

The above Customer class is going to be used by COM components so all the properties and methods are declared in the interface and implemented in the Customer class. CustomerName, CustomerCode, and AddCustomer are first declared in customer and then implemented in Customer Class. Also, note that the class must have a default constructor.

Note: All source code in this book is provided in VB.NET that does not mean that author of the book does 
not like C#. In fact, the main programming language of the author is C#. In order to keep things small,
 I have only used one language. However, the conversion is so seamless that it is of the least matter.
  • The second way to create CCW is by using interop services attributes. Here interfaces are created automatically.

Question 4.
Following are different types of class attributes:
None: No class interface is generated for the class. This is the default setting when you do not specify anything.

AutoDispatch: Interface that supports IDispatch is created for the class. However, no type of information is produced.

Auto Dual: A dual interface is created for the class. Type information is produced and made available in the type library.
Below in the source code we have used the third attribute.

Imports System.Runtime.InteropServices
<ClassInterfaceAttribute (ClassInterfaceType.AutoDual)>
PublicClass ClsCompliant

Other than class, attributes defined up there are other attributes with which you can govern another part of the assembly. Example “GuidAttribute” allows you to specify the GUiD (Globally Unique identifier),
“ComVisibleAttribute” can be used to hide .NET types from COM etc. All attributes are not in the scope of the book as this is an interview questions book refer to MSDN (Microsoft Developer Network) for more details.

NET Interoperability Interview Questions in .NET chapter 19 img 2

  • Once .NET assembly is created using either interface or using InteropServices method we need to create a COM type library using Type Library’ Export Tool.
    Tbsp (Assembly Name)

The final thing is registering the CCW in the registry using regasm Tool. reason Assembly Name [Options]

  • Finally refer to the TLB (Translation Lookaside Buffer) in your COM IDE (Integrated Development Environment) Figure 19.2 shows VB6 IDE referencing the DLL (Dynamic Link Library).
Note: DLL and TLB should be in the same directory where the application is executed.2..NET Interoperability

Question 5.
How can we make Windows API calls in .NET?
Windows API calls are not COM-based and they are invoked through Platform Invoke Services.

Declare StringConversionType (Function I Sub) MethodName Lib “DIIName” ([Args]) As Type

  • StringConversionType is for what type of conversion should take place. Either we can specify Unicode to convert all strings to Unicode values, or Auto to convert strings according to the .NET runtime rules.
  • MethodName is the name of the API to call.
  • DiiName is the name of the DLL.
  • Args are any arguments to the API call.
  • Type is the return type of the API call.

Below is a sample code for VB.NET, which uses sleep windows API for delaying.

Public Class Form1
Declare Auto Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
Private Sub Forml_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MessageBox.Show(" start sleeping for 5000 Milli seconds . . . . . ")
MessageBox.Show(" end of sleeping . . . . . ")
End Sub
End Class
Note: Source code is provided in CD in the “APICAL” folder. In VB.NET we use declare keyword but in C# it 
goes a little bit different, we need to use DllImport, InteropServices, and extern keyword. Below is a simple 
sample for the same.
#region Using directives using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace CSharpCode
     partial class Form1: Form
           static extern int Sleep(long dwMilliseconds); 
           public Forml()
           private void Forml_Load(object sender, EventArgs e)
               MessageBox.Show("Starting of 5000 ms...");
               Sleep(5000) ;
               MessageBox.Show("End of 5000 ms...");

Question 6.
When we use windows API in .NET is it managed or unmanaged code?
Windows API in .NET is unmanaged code.

Note: Even though VB6 and V C++ has gone off still many people do ask these old questions again and again. 
Still there are decent old application which are working with COM very much fine. So interviewer still asks you 
these questions so that those application’s can be ported to .NET. So let’s play some old music... By the way 
my favourite music is Kish ore, what’s yours???

Question 7.
What is COM?
Microsoft’s COM is a technology for component software development. It is a binary standard, which is language independent. DCOM is a distributed extension of COM.

Question 8.
What is Reference counting in COM?
Reference counting is a memory management technique used to count how many times an object has a pointer referring to it. The first time it is created, the reference count is set to one. When the last reference to the object is nulled, the reference count is set to zero and the object is deleted. Care must be exercised to prevent a context switch from changing the reference count at the time of deletion. In the methods that follow, the syntax is shortened to keep the scope of the discussion brief and manageable.

Question 9.
Can you describe the IUnknown interface in short?
Every COM object supports at least one interface, the IUnknown interface. All interfaces are classes derived from the base class IUnknown. Each interface supports methods to access data and perform operations transparently to the programmer. For example, IUnknown supports three methods, AddRef, Released, and Querylnterf ace ( ). Suppose that pinterf is a pointer to an IUnknown.

pinterf->AddRef increments the reference count. pinterf->Release ( ) decrements the reference count, deleting the object when the reference count reaches zero, pinterf- >QueryInterface (IDesired, pDesired) checks to see if the current interface (IUnknown) supports another interface, IDesired, creates an instance (via a call to CoCreateinstance ()) of the object if the reference count is zero (the object does not yet exist), and then calls pDesired- >AddRef () to increment the reference count (where pDesired is a pointer to IDesired) and returns the pointer to the caller.

Question 10.
Can you explain what DCOM is?
DCOM (Distributed Component Object Model) differs from COM in that it allows for creating objects distributed across a network, a protocol for invoking that object’s methods, and secures access to the object. DCOM provides a wrapper around COM, hence it is a backwards compatible extension. DCOM uses Remote Procedural Calls (RPC) using Open Software Foundation’s Distributed Computing Environment.

These RPC are implemented over TCP/IP (Transmission Control Protocol/Internet Protocol) and named pipes. The protocol, which is actually being used, is registered just prior to use, as opposed to being registered at initialization time. The reason for this is that if a protocol is not being used, it will not be loaded. »

In order to inform an object that the client is still alive, periodic pinging is used. Hence, when the client has died and no ping has been received (to refresh it) before the expiration time, the server object will perform some clean up tasks (including decrementing its reference count).
Since RPC across a network are typically slow (compared to processes residing on the same machine), DCOM sends multiple requests in the same call. For example, in COM, the program performs a Queryinterf ace, one interface at a time. In DCOM, multiple Querylnterfaces are all clustered into one call.

This clustering optimization trick is also used when creating an instance of the object and serializing it with data. Since these two operations usually occur together, DCOM allows one method, which will perform both operations in one call without waiting for an acknowledgment from the first task before performing the second one.

Similarly, when a client pings its server object, he can do it in one call. Moreover, if there are multiple clients sending pings to multiple servers, an optimization is made where the multiple pings going to the same object are consolidated into just one ping. This is to cut down on the use of precious bandwidth used only for pinging.

The client has the control to set the computer, which will be responsible for the lifetime of the object. That is to say, these objects are not created just somewhere where the system resources and access privileges allow for it.

Call security is implemented in all four ways: authentication (to prevent false clients from impersonating the true client), authorization (to insure that a client only does what it is authorized to do), data integrity (to insure that data was not tampered with during transit), and data privacy (to insure that only designated sources can read it). The security issues are handled as they are on operating systems. The client gives the server various access privileges to access memory or disk space.

Question 11.
How do we create DCOM object in VB6?
Using the CreateObject method, you can create a DCOM object. You have to put the server name in the registry.

Question 12.
How to implement DTC in .NET?
DTC (Distributed Transaction Coordinator) is implemented using COM+ (See Figure 19.3).
Following are the steps to implement COM+ in .NET:

  • “EnterpriseServices” namespace has all the classes by which we can implement DTC in .NETas shown in Figure 19.3. You have to add reference “EnterpriseServices” namespace.

NET Interoperability Interview Questions in .NET chapter 19 img 3

  • You class must derive from the “ServicedComponent” object.
  • Then you have to define your class with the transaction attribute.

(For all transaction attribute look at the down question)
[Transaction (TransactionOption.RequiresNew) ]

After the class level, the transaction type is defined. Its time to define at the method level the AutoComplete attribute. AutoComplete attribute says that if no exception is thrown then mark its part of the transaction as being okay. This helps cut down on the amount of code required. If the implementation sets AutoComplete to false, or omits it all together, then we would need to manage the transaction manually. To manually, control the transaction you will need to use the Contextutil class and its static members. Following is small snippet of Contextutil:

public void SampleFunction( )
          // Do something to a database
        // Everything okay so far Commit the transaction
       // Something went wrong Abort and Rollback the Transaction.
  • Component derived from “ServicedComponent” should be strongly named as they run under COM+.
  • Once the classes are compiled using the string name. Register the Component in COM+ services using:
    regsvcs c: \DIIPath\TransactionComponent.dll
  • You can see that the component is registered using the COM+ Explorer.

Question 12.
How many types of Transactions are there in COM + .NET?
Five transactions types can be used with COM+. Whenever an object is registered with COM+, it has to abide either to these Five 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 support will be a part of the transaction. This will be only 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 the required new transaction type instantiate a new transaction for themselves every time.

Question 13.
How do you do object pooling in .NET?
COM+ reduces overhead by not creating object from scratch. So in CCM+ when object is activated it’s activated, from pool and when it has deactivated it is pushed back to the pool. Object pooling is configured by using the “ObjectPoolingAttribute” to the class.

Note: When a class is marked with objectpooling attribute it can not be inherited.
ObjectPooling(MinPoolSize: = 2, MaxPoolSize: = 5, CreationTimeout: = 20000)>
Public Class testingclass
Inherits ServicedComponent
Public Sub DoWork()
' Method contents go here.
End Sub
End Class

Above is a sample code, which has the “Objectpooling” attribute defined. Below is a sample code, which uses the class.

Public Class App
Overloads Public Shared Sub Main(args( ) As String)
Dim xyz As New TestObjectPooling( )
xyz.doWork( )
ServicedComponent.DisposeObj ect (xyz)
End Sub
End Class

Above is a sample code, which uses the object pooled object. Note the DisposeObj ect (). This ensures its safe return to the object pool.

Question 14.
What are types of compatibility in VB6?
There are three possible project compatibility settings:

  • No Compatibility
  • Project Compatibility
  • Binary Compatibility

No Compatibility: With this setting, new class ID’s, new interface ID’s and a new type library ID will be generated by VB each time the ActiveX component project is compiled. This will cause any compiled client components to fail (with error 429!) and report a missing reference to the ‘VB ActiveX Test Component’ when a client project is loaded in the VB IDE (Integrated Development Environment).

Note: Use this setting to compile the initial release of a component to other developers.

Project Compatibility

With this setting, VB will generate new interface ID’s for classes whose interfaces have changed, but will not change the class ID’s or the type library ID. This will still cause any compiled client components to fail (with error 429!) but will not report a missing reference to the ‘VB ActiveX Test Component’ when a client project is loaded in the VB IDE. Recompilation of client components will restore them to working order again.

Note: Use this setting during the initial development and testing of a component within the IDE and before 
the component is released to other developers.(A)How many types of Transactions are there in COM + .NET ?

Binary Compatibility

VB makes it possible to extend an existing class or interface by adding new methods and properties, etc., and yet still retain binary compatibility. It can do this, because it silently creates a new interface ID for the extended interface and adds registration code to register the original interface ID but with a new Forward key containing the value of this new interface ID. COM will then substitute calls having the old ID with the new ID and hence applications built against the old interface will continue to work (assuming the inner workings of the component remain backward compatible!).

With this setting, Visual Basic will not change any of the existing class, interface or type library ID’s, however in order that it can do so, Visual Basic requires the project to specify an existing compiled version that it can compare against to eisure that existing interfaces have not been broken.

Question 15.
What is equivalent for regsvr32 exe in .NET?

Leave a Comment