Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Interop Best Practices and Common Pitfalls (That We Learned the Hard Way) Please write your name on a card in the back and place it in the box… Please.

Similar presentations


Presentation on theme: "1 Interop Best Practices and Common Pitfalls (That We Learned the Hard Way) Please write your name on a card in the back and place it in the box… Please."— Presentation transcript:

1 1 Interop Best Practices and Common Pitfalls (That We Learned the Hard Way) Please write your name on a card in the back and place it in the box… Please write your name on a card in the back and place it in the box… ARC310 Book Raffle! …for a chance to win a signed copy of.NET and COM: The Complete Interoperability Guide! Repeat session tomorrow @ 1pm in 511ABC

2 2 Interop Best Practices and Common Pitfalls (That We Learned the Hard Way) Sonja Keserovic Adam Nathan Program Manager QA Lead sonjake@microsoft.com anathan@microsoft.com Microsoft Corporation Sonja Keserovic Adam Nathan Program Manager QA Lead sonjake@microsoft.com anathan@microsoft.com Microsoft Corporation ARC310 Repeat session tomorrow @ 1pm in 511ABC

3 3 Tools Client Application Model AvalonWindows Forms Web & Service Application Model ASP.NET / Indigo Win FS Compact Framework Yukon Mobile PC Optimized System.Help System.Drawing System.NaturalLanguageServices Data Systems Application Model Presentation Data Mobile PC & Devices Application Model Communication Command Line NT Service DataSet Mapping ObjectSpaces ObjectSpace Query Schema Item Relationship Media Audio Video Images System.Messaging System. Discovery System.DirectoryServices System.Remoting System.Runtime.Remoting Active Directory Uddi System.Web.Services Web.Service Description Discovery Protocols System.MessageBus Transport Port Channel Service Queue PubSub Router System.Timers System.Globalization System.Serialization System.Threading System.Text System.Design Base & Application Services Fundamentals System.ComponentModel System.CodeDom System.Reflection System.EnterpriseServices System.Transactions Security System.Windows. TrustManagement System.Web. Security System.Message Bus.Security Authorization AccessControl Credentials Cryptography System.Web.Configuration System.MessageBus.Configuration System.Configuration System.Resources System.Management System.Deployment System.Diagnostics ConfigurationDeployment/Management System.Windows System.Windows.Forms System.Console System.ServiceProcess System.Windows.Forms System.Web System.Storage System.Data.SqlServer Animation Controls Control Design Panel Controls Dialogs SideBar Notification System.Windows Documents Text Element Shapes Shape Ink UI Element Explorer Media System.Windows.Forms Forms Control Print Dialog Design System.Web.UI Page Control HtmlControls MobileControls WebControls Adaptors Design Ports InteropServices System.Runtime System.IO System.Collections Generic System.Search Annotations Monitoring Logging Relevance System.Data SqlClient SqlTypes SqlXML OdbcClient OleDbClient OracleClient Core Contact Location Message Document Event System.Storage System.Web Personalization Caching SessionState System.Xml Schema Serialization Xpath Query Permissions Policy Principal Token System.Security System.Collaboration RealTimeEndpoint TransientDataSession SignalingSession Media Activities HttpWebRequest FtpWebListener SslClientStream WebClient System.Net NetworkInformation Sockets Cache System.Web Administration Management Navigation Peer Group Policy Serialization CompilerServices Recognition System.Speech Synthesis You are here

4 4 Session Structure Three demos that: Represent common interop scenarios Show common pitfalls Explain best practices Best practices review Book raffle Q & A Three demos that: Represent common interop scenarios Show common pitfalls Explain best practices Best practices review Book raffle Q & A Quiz questions!

5 5 Managed Screen Saver & CLR Debug Probes Adam Nathan QA Lead Common Language Runtime Adam Nathan QA Lead Common Language Runtime

6 6 Performance Pitfalls General Not having clear performance goals Not performing regular measurements Interop specific Calling ANSI version of API instead of Unicode version Calling from wrong apartment General Not having clear performance goals Not performing regular measurements Interop specific Calling ANSI version of API instead of Unicode version Calling from wrong apartment

7 7 Performance Best Practices Know performance goals and measure against them often [ARCL01] CLR: Tips and Tricks for Faster Managed Code: How To and What's New (tomorrow @ 1 PM) Make native/managed split wisely Know interop performance basics Call Unicode API versions Make calls from right apartment STAThread attribute & Thread.ApartmentState property Only when necessary (based on measurements) make additional optimizations Know performance goals and measure against them often [ARCL01] CLR: Tips and Tricks for Faster Managed Code: How To and What's New (tomorrow @ 1 PM) Make native/managed split wisely Know interop performance basics Call Unicode API versions Make calls from right apartment STAThread attribute & Thread.ApartmentState property Only when necessary (based on measurements) make additional optimizations

8 8 Handles Pitfalls public class OSHandle { public IntPtr h; public OSHandle { h = NativeMethods.CreateOSHandle(); } ~OSHandle { NativeMethods.ReleaseOSHandle(h); } public class MyClass { public DoWork { OSHandle osh = new OSHandle(); NativeMethods.UseHandle(osh.h); } public class OSHandle { public IntPtr h; public OSHandle { h = NativeMethods.CreateOSHandle(); } ~OSHandle { NativeMethods.ReleaseOSHandle(h); } } public class MyClass { public DoWork { OSHandle osh = new OSHandle(); NativeMethods.UseHandle(osh.h); } } leak lifetime recycle

9 9 Handles Best Practices Use SafeHandle subclasses when dealing with native handles For example, SafeFileHandle is already available in.NET Framework … But don’t use SafeHandle subclasses when you don’t own the handle IntPtr is good representation for these cases Use SafeHandle subclasses when dealing with native handles For example, SafeFileHandle is already available in.NET Framework … But don’t use SafeHandle subclasses when you don’t own the handle IntPtr is good representation for these cases Quiz question!

10 10 Portability Pitfalls Not all C# or VB.NET code is automatically 32/64 bit platform agnostic; especially if you are using interop! Defining pointers as integers is a bad idea (even when it works on your machine) Structures with explicit layout are often not portable Data alignment rules are different Not all C# or VB.NET code is automatically 32/64 bit platform agnostic; especially if you are using interop! Defining pointers as integers is a bad idea (even when it works on your machine) Structures with explicit layout are often not portable Data alignment rules are different

11 11 Portability.NET Framework Example IEnumVARIANT native definition HRESULT Next(unsigned long celt, VARIANT FAR *rgVar, unsigned long FAR *pCeltFetched); UCOMIEnumVARIANT definition Int32 Next (Int32 celt, Int32 rgVar, Int32 pCeltFetched); IEnumVARIANT Whidbey definition Int32 Next (Int32 celt, Object[] rgVar, IntPtr pCeltFetched); IEnumVARIANT native definition HRESULT Next(unsigned long celt, VARIANT FAR *rgVar, unsigned long FAR *pCeltFetched); UCOMIEnumVARIANT definition Int32 Next (Int32 celt, Int32 rgVar, Int32 pCeltFetched); IEnumVARIANT Whidbey definition Int32 Next (Int32 celt, Object[] rgVar, IntPtr pCeltFetched);

12 12 Portability Best Practices Make sure native parts of your app are available for 64 bit platform Use IntPtr type for generic pointers Do not use structures with explicit layouts except for unions (all field offsets are 0) Be aware of data alignment issues Use methods from Marshal class Manually handle unaligned access Make sure native parts of your app are available for 64 bit platform Use IntPtr type for generic pointers Do not use structures with explicit layouts except for unions (all field offsets are 0) Be aware of data alignment issues Use methods from Marshal class Manually handle unaligned access

13 13 Managed Screen Saver in C++ Adam Nathan QA Lead Common Language Runtime Adam Nathan QA Lead Common Language Runtime

14 14 Interop Technologies Pitfalls CLR interop Writing p/invoke declarations for methods and structures in VB.NET or C# can be hard TlbImp.exe might produce incorrect interop assemblies if COM API is IDL based No compile time check if native API is changing C++ interop No magic; requires deep understanding of both native and managed worlds Handling AppDomain transitions is tricky today, especially for library development CLR interop Writing p/invoke declarations for methods and structures in VB.NET or C# can be hard TlbImp.exe might produce incorrect interop assemblies if COM API is IDL based No compile time check if native API is changing C++ interop No magic; requires deep understanding of both native and managed worlds Handling AppDomain transitions is tricky today, especially for library development

15 15 Interop Technologies Best Practices Use CLR interop when calling: Automation compatible COM APIs Simple flat APIs Limited number of native APIs Consider using C++ interop when developing applications and calling: IDL based COM APIs Large and/or complex native APIs Native APIs that are changing Long term direction: using C++ interop for both library and application development Use CLR interop when calling: Automation compatible COM APIs Simple flat APIs Limited number of native APIs Consider using C++ interop when developing applications and calling: IDL based COM APIs Large and/or complex native APIs Native APIs that are changing Long term direction: using C++ interop for both library and application development Quiz question!

16 16 COM Interface Pointers Pitfalls Apartment related problems are more likely to happen Managed C++ code executes in MTA by default There is always one additional thread, finalizer Apartment related problems are more likely to happen Managed C++ code executes in MTA by default There is always one additional thread, finalizer

17 17 COM Interface Pointers Best Practices Use interop templates when calling COM APIs in C++ Templates use RCW internally to get correct proxy Pick the right template for your COM API com_handle, com_handle_context_bound, com_handle_disposable, com_handle_context_bound_disposable, com_ptr Use interop templates when calling COM APIs in C++ Templates use RCW internally to get correct proxy Pick the right template for your COM API com_handle, com_handle_context_bound, com_handle_disposable, com_handle_context_bound_disposable, com_ptr

18 18 Shell Extension Adam Nathan QA Lead Common Language Runtime Adam Nathan QA Lead Common Language Runtime

19 19 COM Visibility Pitfalls Types are visible to COM by default; so what? Are they usable from COM by default? Maybe not! Default constructors supplied? All functionality in instance methods? Testing from COM done? Types are visible to COM by default; so what? Are they usable from COM by default? Maybe not! Default constructors supplied? All functionality in instance methods? Testing from COM done?

20 20 COM Visibility.NET Framework Example System.Math Contains only static methods System.Collections.BitArray No default constructor System.Math Contains only static methods System.Collections.BitArray No default constructor

21 21 COM Visibility Best Practices When developing library Make everything COM invisible by default Consider recompiling C++ COM clients with /clr switch No COM wrappers needed Design explicitly for COM clients (if recompilation is not an option) Build COM friendly APIs on top of managed- clients-only APIs When developing library Make everything COM invisible by default Consider recompiling C++ COM clients with /clr switch No COM wrappers needed Design explicitly for COM clients (if recompilation is not an option) Build COM friendly APIs on top of managed- clients-only APIs

22 22 Versioning Pitfalls AutoDual & AutoDispatch class interfaces: everything automatically callable from COM; isn’t that great?! What about next version? Ouch! COM clients are broken! Adding new methods breaks AutoDual class clients Adding new overloads breaks AutoDispatch class clients (overloads can come from base classes as well) Public structures can’t be changed at all AutoDual & AutoDispatch class interfaces: everything automatically callable from COM; isn’t that great?! What about next version? Ouch! COM clients are broken! Adding new methods breaks AutoDual class clients Adding new overloads breaks AutoDispatch class clients (overloads can come from base classes as well) Public structures can’t be changed at all

23 23 Versioning.NET Framework System.Type was AutoDual in v1.0 _Type interface was added in order to preserve backwards compatibility [GuidAttribute("…")] [InterfaceTypeAttribute(…)] public interface _Type { String ToString(); … Guid GUID { get; } Module Module { get; } … }; System.Type was AutoDual in v1.0 _Type interface was added in order to preserve backwards compatibility [GuidAttribute("…")] [InterfaceTypeAttribute(…)] public interface _Type { String ToString(); … Guid GUID { get; } Module Module { get; } … };

24 24 Versioning Best Practices When developing library Design explicitly for COM clients (if recompilation is not an option) Build COM friendly APIs on top of managed- clients-only APIs Implement interfaces explicitly Use ClassInterface.None and ComDefaultInterfaceAttribute Add new interfaces when making COM breaking changes When developing library Design explicitly for COM clients (if recompilation is not an option) Build COM friendly APIs on top of managed- clients-only APIs Implement interfaces explicitly Use ClassInterface.None and ComDefaultInterfaceAttribute Add new interfaces when making COM breaking changes

25 25 Best Practices Review Project Design Know your options Do not rewrite for the sake of rewriting Use CLR interop or C++ interop when appropriate Be careful about performance Know your goals and measure often Make native/managed split wisely Use interop resources to get more information Know your options Do not rewrite for the sake of rewriting Use CLR interop or C++ interop when appropriate Be careful about performance Know your goals and measure often Make native/managed split wisely Use interop resources to get more information

26 26 Best Practices Review Project Development Turn on CLR debug probes during debugging Enable mixed mode debugging Run FxCop And avoid common pitfalls Turn on CLR debug probes during debugging Enable mixed mode debugging Run FxCop And avoid common pitfalls

27 27 Related Sessions [ARCL01] CLR: Tips and Tricks for Faster Managed Code: How To and What's New (tomorrow @ 1 PM) [TLS311] Visual C++ "Whidbey": Leveraging Native Code with.NET (tomorrow @ 11:30 AM) [CLI390] Exploiting Windows "Longhorn" Features from within Win32/MFC Applications (tomorrow @ 10 AM) [TLS401] Visual C++ "Whidbey" Under the Covers: Targeting the CLR (yesterday) [ARCL01] CLR: Tips and Tricks for Faster Managed Code: How To and What's New (tomorrow @ 1 PM) [TLS311] Visual C++ "Whidbey": Leveraging Native Code with.NET (tomorrow @ 11:30 AM) [CLI390] Exploiting Windows "Longhorn" Features from within Win32/MFC Applications (tomorrow @ 10 AM) [TLS401] Visual C++ "Whidbey" Under the Covers: Targeting the CLR (yesterday)

28 28 Interop Resources “The Developer’s Guide To Migration and Interoperability in Longhorn: Alpha Patterns and Practices” on Longhorn 2 DVD (white paper folder) “.NET and COM: The Complete Interoperability Guide” by Adam Nathan Chris Brumme’s blog http://blogs.gotdotnet.com/cbrumme/ Adam Nathan’s blog http://blogs.gotdotnet.com/anathan/ GotDotNet.com Mattias Sjögren’s N/Direct site http://www.dotnetinterop.com/ “The Developer’s Guide To Migration and Interoperability in Longhorn: Alpha Patterns and Practices” on Longhorn 2 DVD (white paper folder) “.NET and COM: The Complete Interoperability Guide” by Adam Nathan Chris Brumme’s blog http://blogs.gotdotnet.com/cbrumme/ Adam Nathan’s blog http://blogs.gotdotnet.com/anathan/ GotDotNet.com Mattias Sjögren’s N/Direct site http://www.dotnetinterop.com/

29 29 Community Resources Get Your Questions Answered! Newsgroup microsoft.private.whidbey.clr Client Lounge: middle of the Exhibit Hall Connect with Microsoft client product teams, and PDC 2003 Speakers Birds of a Feather: Real World.NET and COM Interop Today 10:00 PM-11:00 PM PDC Weblogs: http://pdcbloggers.net Newsgroup microsoft.private.whidbey.clr Client Lounge: middle of the Exhibit Hall Connect with Microsoft client product teams, and PDC 2003 Speakers Birds of a Feather: Real World.NET and COM Interop Today 10:00 PM-11:00 PM PDC Weblogs: http://pdcbloggers.net

30 30 More Community Public newsgroups microsoft.public.dotnet.framework.interop microsoft.public.dotnet.general microsoft.public.dotnet.framework microsoft.public.dotnet.clr http://discuss.develop.com list server ADVANCED-DOTNET DOTNET-CLR DOTNET-ROTOR Attend a free chat or webcast http://microsoft.com/communities/chats/default.mspx http://microsoft.com/usa/webcasts/default.asp Locate a local user groups http://microsoft.com/communities/usergroups/default.mspx Community sites http://microsoft.com/communities/related/default.mspx Public newsgroups microsoft.public.dotnet.framework.interop microsoft.public.dotnet.general microsoft.public.dotnet.framework microsoft.public.dotnet.clr http://discuss.develop.com list server ADVANCED-DOTNET DOTNET-CLR DOTNET-ROTOR Attend a free chat or webcast http://microsoft.com/communities/chats/default.mspx http://microsoft.com/usa/webcasts/default.asp Locate a local user groups http://microsoft.com/communities/usergroups/default.mspx Community sites http://microsoft.com/communities/related/default.mspx

31 31 Book Raffle!

32 32 Q & A Please submit your session evals and help us make this talk better in the future. Thanks! Sonja & Adam Please submit your session evals and help us make this talk better in the future. Thanks! Sonja & Adam

33 33 © 2003-2004 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

34


Download ppt "1 Interop Best Practices and Common Pitfalls (That We Learned the Hard Way) Please write your name on a card in the back and place it in the box… Please."

Similar presentations


Ads by Google