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.

Slides:



Advertisements
Similar presentations
Best Practices for Interop with Visual C++ Boris Jabes Program Manager Microsoft Corporation.
Advertisements

DEV392: Extending SharePoint Products And Technologies Through Web Parts And ASP.NET Clint Covington, Program Manager Data And Developer Services - Office.
1 Federating Identity and Authorization Across Organizations and Platforms Matthew Hur Lead Program Manager Microsoft Corporation
Thursday Evening 6.30VB.NET Introduction 7.30Break for food 8.00VB.NET Migration 8.45Q & A 9.00Done.
Module 1: Overview of the Microsoft.NET Framework.
SQL Server 2005 CLR Integration ADO.NET 2.0 Mike Taulty
1 Introducing ClickOnce: The New Application Deployment Model for Windows Forms and “Avalon” Jamie Cool Program Manager Microsoft.
Future Directions for Leveraging Advanced XML Tools and Building Custom XML Solutions Denise Draper DAT321 Microsoft Corporation.
Building Rights Management Enabled Applications For Windows "Longhorn" Steve Bourne Chandramouli Venkatesh Microsoft Corporation Steve Bourne Chandramouli.
1 Programming Windows Help Shane McRoberts Group Program Manager Microsoft Corporation Shane McRoberts Group Program Manager Microsoft.
Using.NET Skills To Build Mobile Applications In Compact Framework Punit Shah Technical Lead | Microsoft |
Plataformas.NET para desenvolvimento de aplicações web José António Silva
© 2004 by The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill/Irwin Programming the Web Using ASP.Net Chapter 2: The ASP.Net Template Dave.
1 Introduction to.NET Framework. 2.NETFramework Internet COM+ Orchestration Orchestration Windows.NET Enterprise ServersBuildingBlockServices Visual Studio.NET.
Data Access Design Patterns: Navigating the Data Access Maze Michael Pizzo Software Architect Microsoft Corporation Michael Pizzo Software Architect Microsoft.
NOTE: To change the image on this slide, select the picture and delete it. Then click the Pictures icon in the placeholder to insert your own image. WEB.
1 Using XSD, CLR Types, And Serialization In Web Services Doug Purdy Program Manager Microsoft Corporation Doug Purdy Program Manager.
1 Keyboard, Speech, and Pen Input in Your Controls Kevin Gjerstad Lead Program Manager Kevin Gjerstad Lead Program Manager
Assemblies & Namespaces1. 2 Assemblies (1).NET applications are represented by an assembly An assembly is a collection of all software of which the application.
Nilotpal Bhattacharya Partner Technical Consultant| Microsoft.
DEV290 Building Office Solutions with Visual Studio Eric Carter Lead Developer Developer Platform & Evangelism Microsoft Corporation.
Module 1: Overview of the Microsoft.NET Platform.
“Indigo”: Building Peer-To-Peer Applications Todd R. Manion Program Manager Microsoft Corporation Todd R. Manion Program Manager.
.NET Framework Danish Sami UG Lead.NetFoundry
DEV325 Deploying Visual Studio.NET Applications Billy Hollis Author / Consultant.
NOTE: To change the image on this slide, select the picture and delete it. Then click the Pictures icon in the placeholder to insert your own image. WEB.
Programming Handheld and Mobile devices 1 Programming of Handheld and Mobile Devices Lecture 17 Microsoft’s Approach 1 –.NET Mobile Framework Rob Pooley.
1.NET Framework Overview: A Road Map Brad Abrams.NET Framework Team Microsoft Corporation Brad Abrams.NET Framework.
Slide 1.NET Development for Project 2003 Samples from the Project 2003 SDK Jim Corbin Programmer Writer Office Developer Documentation Microsoft Corporation.
DotNet Michelle Johnston, Firebird Services Ltd. What is Dot Net Aims to simplify web development Language independent – CLR (Common Language Runtime)
A Deep Dive into Best Practices with the Windows Communication Foundation John Justice COM415 Program Manager Microsoft Corporation.
.NET Enterprise Services COM+ 1.5 麥超俊 Bobby Mak 架構技術推廣經理開發工具暨平台推廣處台灣微軟股份有限公司.
1 Application Model Fundamentals Chris Anderson Software Architect Microsoft Corporation Chris Anderson Software Architect Microsoft.
Name Microsoft Student Partner Overview of the Visual Studio 2005 Express Products.
Microsoft.Net Sven Groot. Common Language Runtime Superset of ECMA Common Language Infrastructure Defines  Language-neutral platform  Intermediate Language.
Windows Role-Based Access Control Longhorn Update
“Avalon”: Using UI Automation to Improve Application Testability Robert Sinclair Group Manager Microsoft Corporation Robert Sinclair.
1 Integrating Real-time Collaboration into your Applications Stephanie Lindsey Program Manager Microsoft Corporation Stephanie.
1 Visual Basic “Whidbey”: RAD for the Visual Basic Developer Jay Schmelzer and Shamez Rajan Program Manager Microsoft Corporation Jay Schmelzer and Shamez.
NAMESPACE. Namespaces Namespaces are a way to define the classes and other types of information into one hierarchical structure. System is the basic namespace.
DEV394.NET Framework: Migrating To Managed Code Adam Nathan QA Lead Richard Lander Program Manager Microsoft Corporation.
.NET Mobile Application Development XML Web Services.
SQL Server Notifications: Invalidating Cached Results Michael Pizzo Software Architect Microsoft Corporation Michael Pizzo Software.
Extending Workflow With Custom Activities Dennis Pilarinos COM328 Program Manager Microsoft Corporation.
1 Programming ADO.NET in Whidbey Pablo Castro/Brad Rhodes ADO.NET Team Microsoft Corporation Pablo Castro/Brad Rhodes.
Integrating and Extending Workflow 8 AA301 Carl Sykes Ed Heaney.
Building Complete Web Application Using ASP.NET 3.5 & Visual Studio 2008 Omar Khan Group Program Manager Visual Studio.
Introducing the Microsoft® .NET Framework
12/29/2017 2:33 PM © Microsoft Corporation. All rights reserved. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN.
Using Audio, Video, and Imaging in your Longhorn Applications
ASP.NET Core: Web apps, cloud apps, and containers
6/2/2018 4:08 AM BRK3327 Ten things you didn't know about building .NET UWP apps in Visual Studio 2017 Daniel Jacobson Program Manager – Visual Studio.
System.Search, aka “Find My Stuff”
The Modern ASP.NET Tech Stack!
Visual Studio Tools for Office 2005
Transactional Programming In A Windows World
Enterprise Library Overview
Building Innovative Apps using the Microsoft Developer Platform
Michael Wallent General Manager Windows Client Platform
“Whidbey” CLR Internals
11/17/2018 9:30 PM Session Code: ARC 420
Learn. Imagine. Build. .NET Conf
Building Rich, Interactive Controls for Windows “Longhorn”
New User Interface Possibilities in Longhorn
"Avalon": Building Applications With Controls And Dialogs
People And Groups Controls In Windows "Longhorn"
NAMESPACE.
Session Code: CLI391 Windows Forms: Exploiting Windows “Longhorn” Features from Within Your Application Mark Boulter .NET Client Team Microsoft Corporation.
Mark Quirk Head of Technology Developer & Platform Group
.NET Framework Design Goals
Presentation transcript:

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 1pm in 511ABC

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

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 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 Managed Screen Saver & CLR Debug Probes Adam Nathan QA Lead Common Language Runtime Adam Nathan QA Lead Common Language Runtime

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 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 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 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 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 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 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 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 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 Managed Screen Saver in C++ Adam Nathan QA Lead Common Language Runtime Adam Nathan QA Lead Common Language Runtime

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 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 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 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 Shell Extension Adam Nathan QA Lead Common Language Runtime Adam Nathan QA Lead Common Language Runtime

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

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 Adam Nathan’s blog GotDotNet.com Mattias Sjögren’s N/Direct site “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 Adam Nathan’s blog GotDotNet.com Mattias Sjögren’s N/Direct site

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: 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:

30 More Community Public newsgroups microsoft.public.dotnet.framework.interop microsoft.public.dotnet.general microsoft.public.dotnet.framework microsoft.public.dotnet.clr list server ADVANCED-DOTNET DOTNET-CLR DOTNET-ROTOR Attend a free chat or webcast Locate a local user groups Community sites Public newsgroups microsoft.public.dotnet.framework.interop microsoft.public.dotnet.general microsoft.public.dotnet.framework microsoft.public.dotnet.clr list server ADVANCED-DOTNET DOTNET-CLR DOTNET-ROTOR Attend a free chat or webcast Locate a local user groups Community sites

31 Book Raffle!

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 © Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.