Wednesday, July 2, 2008

.NET interview questions

.NET Windows Forms basics

1. Write a simple Windows Forms MessageBox statement.

  System.Windows.Forms.MessageBox.Show

("Hello, Windows Forms");
 

2. Can you write a class without specifying namespace? Which namespace does it belong to by default??
Yes, you can, then the class belongs to global namespace which has no name. For commercial products, naturally, you wouldn’t want global namespace.

3. You are designing a GUI application with a windows and several widgets on it. The user then resizes the app window and sees a lot of grey space, while the widgets stay in place. What’s the problem?

One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-left, so it stays at the same location when resized.

4. How can you save the desired properties of Windows Forms application?

.config files in .NET are supported through the API to allow storing and retrieving information. They are nothing more than simple XML files, sort of like what .ini files were before for Win32 apps.

5. So how do you retrieve the customized properties of a .NET application from XML .config file?

Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable.

6. Can you automate this process?

In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.

7. My progress bar freezes up and dialog window shows blank, when an intensive background process takes over.

Yes, you should’ve multi-threaded your GUI, with taskbar and main form being one thread, and the background process being the other.

8. What’s the safest way to deploy a Windows Forms app?

Web deployment: the user always downloads the latest version of the code, the program runs within security sandbox, properly written app will not require additional security privileges.

9. Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio?

The designer will likely through it away, most of the code inside InitializeComponent is auto-generated.

10. What’s the difference between WindowsDefaultLocation and WindowsDefaultBounds? WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified size. WindowsDefaultBounds delegates both size and starting position choices to the OS.

11. What’s the difference between Move and LocationChanged? Resize and SizeChanged? Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.

12. How would you create a non-rectangular window, let’s say an ellipse?

Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will effectively make the background of the form transparent. Then set the FormBorderStyle to FormBorderStyle.None, which will remove the contour and contents of the form.

13. How do you create a separator in the Menu Designer?

A hyphen ‘-’ would do it. Also, an ampersand ‘&’ would underline the next letter.

14. How’s anchoring different from docking?

Anchoring treats the component as having the absolute size and adjusts its location relative to the parent form. Docking treats the component location as absolute and disregards the component size. So if a status bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but change its position with the form being resized, use anchoring.

.NET interview questions - Windows Forms

1. I am constantly writing the drawing procedures with System.Drawing.Graphics, but having to use the try and dispose blocks is too time-consuming with Graphics objects. Can I automate this?

Yes, the code

     System.Drawing.Graphics canvas = new System.Drawing.Graphics();

try
{
//some code
}
finally
canvas.Dispose();

is functionally equivalent to

using (System.Drawing.Graphics canvas = new System.Drawing.Graphics())

{
//some code
} //canvas.Dispose() gets called automatically

2. How do you trigger the Paint event in System.Drawing?

Invalidate the current form, the OS will take care of repainting. The Update method forces the repaint.

3. With these events, why wouldn’t Microsoft combine Invalidate and Paint, so that you wouldn’t have to tell it to repaint, and then to force it to repaint?

Painting is the slowest thing the OS does, so usually telling it to repaint, but not forcing it allows for the process to take place in the background.

4. How can you assign an RGB color to a System.Drawing.Color object?

Call the static method FromArgb of this class and pass it the RGB values.

5. What class does Icon derive from? Isn’t it just a Bitmap with a wrapper name around it?

No, Icon lives in System.Drawing namespace. It’s not a Bitmap by default, and is treated separately by .NET. However, you can use ToBitmap method to get a valid Bitmap object from a valid Icon object.

6. Before in my VB app I would just load the icons from DLL. How can I load the icons provided by .NET dynamically?

By using System.Drawing.SystemIcons class, for example System.Drawing.SystemIcons.Warning produces an Icon with a warning sign in it.

7. When displaying fonts, what’s the difference between pixels, points and ems?

A pixel is the lowest-resolution dot the computer monitor supports. Its size depends on user’s settings and monitor size. A point is always 1/72 of an inch. An em is the number of pixels that it takes to display the letter M.

.NET Remoting questions and answers

1. What’s a Windows process?

It’s an application that’s running and had been allocated memory.

2. What’s typical about a Windows process in regards to memory allocation?

Each process is allocated its own block of available RAM space, no process can access another process’ code or data. If the process crashes, it dies alone without taking the entire OS or a bunch of other applications down.

3. Why do you call it a process? What’s different between process and application in .NET, not common computer usage, terminology?

A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application.

4. What distributed process frameworks outside .NET do you know?

Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object Model (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation (RMI).

5. What are possible implementations of distributed applications in .NET?

.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.

6. When would you use .NET Remoting and when Web services?

Use remoting for more efficient exchange of information when you control both ends of the application. Use Web services for open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.

7. What’s a proxy of the server object in .NET Remoting?

It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.

8. What are remotable objects in .NET Remoting?

Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.

9. What are channels in .NET Remoting?

Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.

10. What security measures exist for .NET Remoting in System.Runtime.Remoting?

None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.

11. What is a formatter?

A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.

12. Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?

Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.

13. What’s SingleCall activation mode used for?

If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.

14. What’s Singleton activation mode?

A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.

15. How do you define the lease of the object?

By implementing ILease interface when writing the class code.

16. Can you configure a .NET Remoting object via XML file?

Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.

17. How can you automatically generate interface for the remotable object in .NET with Microsoft tools?

Use the Soapsuds tool.

Microsoft .NET Framework interview questions

1. What is .NET FrameWork ?

2. Is .NET a runtime service or a development platform?

It’s bothand actually a lot more. Microsoft .NET is a company-wide initiative. It includes a new way of delivering software and services to businesses and consumers. A part of Microsoft.NET is the .NET Frameworks. The frameworks is the first part of the MS.NET initiate to ship and it was given out to attendees at the PDC in July. The .NET frameworks consists of two parts: the .NET common language runtime and the .NET class library. These two components are packaged together into the .NET Frameworks SDK which will be available for free download from Microsoft’s MSDN web site later this month. In addition, the SDK also includes command-line compilers for C#, C++, JScript, and VB. You use these compilers to build applications and components. These components require the runtime to execute so this is a development platform. When Visual Studio.NET ships, it will include the .NET SDK and a GUI editor, wizards, tools, and a slew of other things. However, Visual Studio.NET is NOT required to build .NET applications

3. What is strong name?

A name that consists of an assembly’s identity—its simple text name, version number, and culture information (if provided)—strengthened by a public key and a digital signature generated over the assembly.

4. What is portable executable (PE)

The file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR. The specification for the PE/COFF file formats is available at http://www.microsoft.com/whdc/hwdev/hardware/pecoffdown.mspx

5. Which is the base class for .net Class library?

Ans: system.object

6. What is Event?

Delegate, clear syntax for writing a event delegate// keyword_delegate.cs // delegate declaration delegate void MyDelegate(int i);

class Program
{
public static void Main()
{
TakesADelegate(new MyDelegate(DelegateFunction));
}
public static void TakesADelegate(MyDelegate SomeFunction)
{
SomeFunction(21);
}
public static void DelegateFunction(int i)
{
System.Console.WriteLine("Called by delegate withnumber: {0}.", i);
}
}

7. What is Application Domain?

Application domains provide a unit of isolation for the common language runtime. They are created and run inside a process. Application domains are usually created by a runtime host, which is an application responsible for loading the runtime into a process and executing user code within an application domain. The runtime host creates a process and a default application domain, and runs managed code inside it. Runtime hosts include ASP.NET, Microsoft Internet Explorer, and the Windows shell.

8. What is serialization in .NET?

What are the ways to control serialization? Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.

* Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects “by value” from one computer or application domain to another.


* XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice.

9. What are the different authentication modes in the .NET environment?


protection=”All|None|Encryption|Validation”
timeout=”30″ path=”/” > requireSSL=“true|false”
slidingExpiration=“true|false”><
credentials passwordFormat=”Clear|SHA1|MD5″><
user name=”username” password=”password”/>


10. What is exception handling?

When an exception occurs, the system searches for the nearest catch clause that can handle the exception, as determined by the run-time type of the exception. First, the current method is searched for a lexically enclosing try statement, and the associated catch clauses of the try statement are considered in order. If that fails, the method that called the current method is searched for a lexically enclosing try statement that encloses the point of the call to the current method. This search continues until a catch clause is found that can handle the current exception, by naming an exception class that is of the same class, or a base class, of the run-time type of the exception being thrown. A catch clause that doesn’t name an exception class can handle any exception. Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated withtry statements more nested that than the one that caught the exception. Exceptions that occur during destructor execution are worthspecial mention. If an exception occurs during destructor execution, and that exception is not caught, then the execution of that destructor is terminated and the destructor of the base class (if any) is called. If there is no base class (as in the case of the object type) or if there is no base class destructor, then the exception is discarded.

11. What is Assembly?

Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime withthe information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly. Assemblies are a fundamental part of programming withthe .NET Framework. An assembly performs the following functions:

* It contains code that the common language runtime executes. Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. Note that each assembly can have only one entry point (that is,DllMain,WinMain, orMain).
* It forms asecurity boundary. An assembly is the unit at which permissions are requested and granted.
* It forms atype boundary. Every type’s identity includes the name of the assembly in which it resides. A type called MyType loaded in the scope of one assembly is not the same as a type called MyType loaded in the scope of another assembly.
* It forms areference scope boundary. The assembly’s manifest contains assembly metadata that is used for resolving types and satisfying resource requests. It specifies the types and resources that are exposed outside the assembly. The manifest also enumerates other assemblies on which it depends.
* It forms aversion boundary. The assembly is the smallest versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit. The assembly’s manifest describes the version dependencies you specify for any dependent assemblies.
* It forms a deployment unit. When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes, can be retrieved on demand. This allows applications to be kept simple and thin when first downloaded.
* It is the unit at which side-by-side execution is supported.

Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in PE files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed.

There are several ways to create assemblies. You can use development tools, such as Visual Studio .NET, that you have used in the past to create .dll or .exe files. You can use tools provided in the .NET Framework SDK to create assemblies withmodules created in other development environments. You can also use common language runtime APIs, such as Reflection.Emit, to create dynamic assemblies.

12. Types of assemblies?

Private, Public/Shared, Satellite

13. What are Satellite Assemblies? How you will create this? How will you get the different language strings?

Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated witha given language and .NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being removed. For example, English and Japanese editions of the .NET Framework version 1.1 share the same core files. The Japanese .NET Framework version 1.1 adds satellite assemblies withlocalized resources in a \ja subdirectory. An application that supports the .NET Framework version 1.1, regardless of its language, always uses the same core runtime files.

14. What is Assembly manifest? what all details the assembly manifest will contain ?

Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly’s version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) withMicrosoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information. It contains Assembly name, Version number, Culture, Strong name information, List of all files in the assembly, Type reference information, Information on referenced assemblies.

15. What are the contents of assembly?

In general, a static assembly can consist of four elements:
* The assembly manifest, which contains assembly metadata.
* Type metadata.
* Microsoft intermediate language (MSIL) code that implements the types.
* A set of resources.

16. Difference between assembly manifest & metadata

assembly manifest -An integral part of every assembly that renders the assembly self-describing. The assembly manifest contains the assembly’s metadata. The manifest establishes the assembly identity, specifies the files that make up the assembly implementation, specifies the types and resources that make up the assembly, itemizes the compile-time dependencies on other assemblies, and specifies the set of permissions required for the assembly to run properly. This information is used at run time to resolve references, enforce version binding policy, and validate the integrity of loaded assemblies. The self-describing nature of assemblies also helps makes zero-impact install and XCOPY deployment feasible.

metadata -Information that describes every element managed by the common language runtime: an assembly, loadable file, type, method, and so on. This can include information required for debugging and garbage collection, as well as security attributes, marshaling data, extended class and member definitions, version binding, and other information required by the runtime.

17. What is Global Assembly Cache (GAC) and what is the purpose of it? (How to make an assembly to public? Steps)

Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer. You should share assemblies by installing them into the global assembly cache only when you need to.

18. What is Garbage Collection in .Net? Garbage collection process?

The process of transitively tracing through all pointers to actively used objects in order to locate all objects that can be referenced, and then arranging to reuse any heap memory that was not found during this trace. The common language runtime garbage collector also compacts the memory that is in use to reduce the working space needed for the heap.

19. Readonly vs. const?

Aconstfield can only be initialized at the declaration of the field. Areadonlyfield can be initialized either at the declaration or in a constructor. Therefore,readonlyfields can have different values depending on the constructor used. Also, while aconstfield is a compile-time constant, thereadonlyfield can be used for runtime constants, as in the following example: public static readonly uint l1 = (uint) DateTime.Now.Ticks;

20. What is the managed and unmanaged code in .net?

The .NET Framework provides a run-time environment called the Common Language Runtime, which manages the execution of code and provides services that make the development process easier. Compilers and tools expose the runtime’s functionality and enable you to write code that benefits from this managed execution environment. Code that you develop witha language compiler that targets the runtime is calledmanaged code; itbenefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.

.NET Windows services development questions

1. Explain Windows service.

You often need programs that run continuously in the background. For example, an email server is expected to listen continuously on a network port for incoming email messages, a print spooler is expected to listen continuously to print requests, and so on.

2. What’s the Unix name for a Windows service equivalent?

Daemon.

3. So basically a Windows service application is just another executable? What’s different about a Windows service as compared to a regular application?

Windows services must support the interface of the Service Control Manager (SCM). A Windows service must be installed in the Windows service database before it can be launched.

4. How is development of a Windows service different from a Windows Forms application?

A Windows service typically does not have a user interface, it supports a set of commands and can have a GUI that’s built later to allow for easier access to those commands.

5. How do you give a Windows service specific permissions?

Windows service always runs under someone’s identity. Can be System or Administrator account, but if you want to restrict the behavior of a Windows service, the best bet is to create a new user account, assign and deny necessary privileges to that account, and then associate the Windows service with that new account.

6. Can you share processes between Windows services?

Yes.

7. Where’s Windows service database located? HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

8. What does SCM do?

SCM is Windows Service Control Manager. Its responsibilities are as follows:

1. Accepts requests to install and uninstall Windows services from the Windows service database.

2. To start Windows services either on system startup or requested by the user.

3. To enumerate installed Windows services.

4. To maintain status information for currently running Windows services.

5. To transmits control messages (such as Start, Stop, Pause, and Continue) to available Windows services.

6. To lock/unlock Windows service database.

9. When developing a Windows service for .NET, which namespace do you typically look in for required classes?

System.ServiceProcess. The classes are ServiceBase, ServiceProcessInstaller, ServiceInstaller and ServiceController.

10. How do you handle Start, Pause, Continue and Stop calls from SCM within your application?

By implementing OnStart, OnPause, OnContinue and OnStop methods.

11. Describe the start-up process for a Windows service.

Main() is executed to create an instance of a Web service, then Run() to launch it, then OnStart() from within the instance is executed.

12. I want to write a Windows service that cannot be paused, only started and stopped. How do I accomplish that?

Set CanPauseAndContinue attribute to false.

13. What application do you use to install a Windows service?

installutil.exe

14. I am trying to install my Windows service under NetworkService account, but keep getting an error.

The LocalService and NetworkService accounts are only available on Windows XP and Windows Server 2003. These accounts do not exist on Windows 2000 or older operating systems.

15. How can you see which services are running on a Windows box?

Admin Tools -> Computer Management -> Services and Application -> Services. You can also open the Computer Management tool by right-clicking on My Computer and selecting Manage from the popup menu.

16. How do you start, pause, continue or stop a Windows service off the command line?

net start ServiceName, net pause ServiceName and so on. Also sc.exe provides a command-line interface for Windows services. View the OS documentation or proper book chapters on using sc.exe.

17. Can I write an MMC snap-in for my Windows service?

Yes, use classes from the System.Management.Instrumentation namespace.

COM/COM+ services and components in .NET

1. Explain transaction atomicity.

We must ensure that the entire transaction is either committed or rolled back.

2. Explain consistency.

We must ensure that the system is always left at the correct state in case of the failure or success of a transaction.

3. Explain integrity.

Ensure data integrity by protecting concurrent transactions from seeing or being adversely affected by each other’s partial and uncommitted results.

4. Explain durability.

Make sure that the system can return to its original state in case of a failure.

5. Explain object pooling.

With object pooling, COM+ creates objects and keeps them in a pool, where they are ready to be used when the next client makes a request. This improves the performance of a server application that hosts the objects that are frequently used but are expensive to create.

6. Explain JIT activation.

The objective of JIT activation is to minimize the amount of time for which an object lives and consumes resources on the server. With JIT activation, the client can hold a reference to an object on the server for a long time, but the server creates the object only when the client calls a method on the object. After the method call is completed, the object is freed and its memory is reclaimed. JIT activation enables applications to scale up as the number of users increases.

7. Explain role-based security.

In the role-based security model, access to parts of an application are granted or denied based on the role to which the callers belong. A role defines which members of a Windows domain are allowed to work with what components, methods, or interfaces.

8. Explain queued components.

The queued components service enables you to create components that can execute asynchronously or in disconnected mode. Queued components ensure availability of a system even when one or more sub-systems are temporarily unavailable. Consider a scenario where salespeople take their laptop computers to the field and enter orders on the go. Because they are in disconnected mode, these orders can be queued up in a message queue. When salespeople connect back to the network, the orders can be retrieved from the message queue and processed by the order processing components on the server.

9. Explain loosely coupled events.

Loosely coupled events enable an object (publisher) to publish an event. Other objects (subscribers) can subscribe to an event. COM+ does not require publishers or subscribers to know about each other. Therefore, loosely coupled events greatly simplify the programming

model for distributed applications.

10. Define scalability.

The application meets its requirement for efficiency even if the number of users increases.

11. Define reliability.

The application generates correct and consistent information all the time.

12. Define availability.

Users can depend on using the application when needed.

13. Define security.

The application is never disrupted or compromised by the efforts of malicious or ignorant users.

14. Define manageability.

Deployment and maintenance of the application is as efficient and painless as possible.

15. Which namespace do the classes, allowing you to support COM functionality, are located?

System.EnterpriseServices

16. How do you make a NET component talk to a COM component?

To enable the communication between COM and .NET components, the .NET Framework generates a COM Callable Wrapper (CCW). The CCW enables communication between the calling COM code and the managed code. It also handles conversion between the data types, as well as other messages between the COM types and the .NET types.

.NET and COM interop questions

1. Describe the advantages of writing a managed code application instead of unmanaged one. What’s involved in certain piece of code being managed?

The advantages include automatic garbage collection, memory management, support for versioning and security. These advantages are provided through .NET FCL and CLR, while with the unmanaged code similar capabilities had to be implemented through third-party libraries or as a part of the application itself.

2. Are COM objects managed or unmanaged?

Since COM objects were written before .NET, apparently they are unmanaged.

3. So can a COM object talk to a .NET object?

Yes, through Runtime Callable Wrapper (RCW) or PInvoke.

4. How do you generate an RCW from a COM object?

Use the Type Library Import utility shipped with SDK. tlbimp COMobject.dll /out:.NETobject.dll or reference the COM library from Visual Studio in your project.

5. I can’t import the COM object that I have on my machine. Did you write that object?

You can only import your own objects. If you need to use a COM component from another developer, you should obtain a Primary Interop Assembly (PIA) from whoever authored the original object.

6. How do you call unmanaged methods from your .NET code through PInvoke?

Supply a DllImport attribute. Declare the methods in your .NET code as static extern. Do not implement the methods as they are implemented in your unmanaged code, you’re just providing declarations for method signatures.

7. Can you retrieve complex data types like structs from the PInvoke calls?

Yes, just make sure you re-declare that struct, so that managed code knows what to do with it.

8. I want to expose my .NET objects to COM objects. Is that possible?

Yes, but few things should be considered first. Classes should implement interfaces explicitly. Managed types must be public. Methods, properties, fields, and events that are exposed to COM must be public. Types must have a public default constructor with no arguments to be activated from COM. Types cannot be abstract.

9. Can you inherit a COM class in a .NET application?

The .NET Framework extends the COM model for reusability by adding implementation inheritance. Managed types can derive directly or indirectly from a COM coclass; more specifically, they can derive from the runtime callable wrapper generated by the runtime. The derived type can expose all the method and properties of the COM object as well as methods and properties implemented in managed code. The resulting object is partly implemented in managed code and partly implemented in unmanaged code.

10. Suppose I call a COM object from a .NET applicaiton, but COM object throws an error. What happens on the .NET end?

COM methods report errors by returning HRESULTs; .NET methods report them by throwing exceptions. The runtime handles the transition between the two. Each exception class in the .NET Framework maps to an HRESULT.

No comments: