Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to the Compact Framework Marcus Perryman Principal Consultant Microsoft.

Similar presentations


Presentation on theme: "Introduction to the Compact Framework Marcus Perryman Principal Consultant Microsoft."— Presentation transcript:

1 Introduction to the Compact Framework Marcus Perryman Principal Consultant Microsoft

2 Agenda  Design goals  Key components  Common features with the desktop  Differences from the desktop  What’s in and out

3 What is Compact Framework Design Goals Target mobile and embedded devices  Portable subset of.NET Framework  No new ‘compact’ namespaces  Visual Basic.NET & C# compiler support in v1  Leverage Visual Studio.NET  Run managed.EXEs and.DLLs directly  Debug with Visual Studio.NET  Peacefully co-exist with host OS  Run on native threads, P/Invoke to call native code

4 Key Components Host Operating System Platform Adaptation Layer Applications.NET Compact Framework App Domain Host ManagedNative Platform Specific Class Libs Base Class Libs Execution Engine (MSCOREE.DLL) - CLR Smart Device Extensions

5 Compact CLR Common Features  Verifiable type safe execution  No uninitialized variables, unsafe casts, bad array indexing, bad pointer math  Garbage Collection  No ref-counting, no leaks  JIT compilation  Error handling with exceptions  Common type system  Call, inherit, and source-level debug across different languages

6 Compact CLR Differences  COM Interop  Good support for calling native DLLs  Support for calling a COM object through DLL wrappers  No support for writing a COM / ActiveX object in C# or Visual Basic  No Install-time JIT (nGen)  No Reflection Emit  No Remoting  Client web services is fully supported  No Generic Serialization  Datasets can be serialized to XML  Subsets of other areas of functionality

7 .NET Compact Framework System System.DataSystem.Xml System.Web Globalization Text Security Collections Resources Reflection Net IO Threading Diagnostics ServiceProcess Configuration Design ADO.NET SqlServerCe SqlClient Xslt/XPath XmlDocument Runtime InteropServices Remoting Serialization Serialization ConfigurationSessionState CachingSecurity Services Description Discovery Protocols UI HtmlControls WebControls System.Drawing Imaging Drawing2D Text Printing System.WinForms DesignComponentModel Reader/Writers

8 Supported Controls ButtonCheckBoxComboBoxContextMenuDataGridDomainUpDownFileOpenDialog  Supported controls HScrollBarImageListLabelListBoxListViewTreeViewFileSaveDialog MainMenuNumericUpDownPanelPictureBoxProgressBarRadioButton GroupBox Printing Controls RichTextBox NotificationBubble (PPC) StatusBarTabControlTextBoxTimerToolBarVScrollBar  Unsupported controls  Unsupported controls – not available in CE CheckedListBoxColorDialogErrorProvider HelpProviderLinkLabelNotifyIcon ToolTipSplitterFontDialog

9 Framework Size  Framework size (RAM or ROM)  ~1.5 MB  Running RAM needs  1 MB+ (depends on app)  Typical application sizes  5 - 100 KB  Apps often smaller due to use of platform features in the framework

10 DEMO Creating a basic form Consuming a web service

11 Advanced.NET Compact Framework Development

12 Agenda  Under the hood – what goes on with CF  JIT, GC and Pitching  Performance  The art of tuning  Platform Interop  Getting to native code  Marshalling  Callback’s  Summary

13 Under the hood

14 Architecture Host Operating System Platform Adaptation Layer Execution Engine (MSCOREE.DLL) Platform Specific Class Libs Base Class Libs Applications.NET Compact Framework App Domain Host … Launch ManagedNative

15 The EE A short review  Compiled managed code is a binary in Microsoft Intermediate Language  Code is just-in-time compiled to the native processor language on type-by-type, method-by- method basis  Resulting native code is cached for later reuse  Over the lifetime of the app, the up front cost of jitting is amortized, and becomes less and less significant

16 Under the Hood  Build process  Same compilers  Local exe produced – additional Deploy step  File format  Standard PE format with no native code  Module load upgraded on device  Contains Intermediate Language (IL) blocks  Resources bound in or deployed in parallel  Deploy  Uses Connection Manager not Platform Manager  Again over Active Sync

17 DEMO ILDASM Multiple environments

18 Active Sync Connection Manager Remote Deploy And Debug Visual Studio.NET Windows DebugManager Device or Emulator STREAM CONNECT Process Enumerate App.exe File Copy App.pdb App.exe Remote Exec STREAM CONNECT Remote Debug

19 Per-Thread Control Flow ExecuteManagedMethod JITCompiled? Verify & JIT CompileMethod Load Base Classes Locate “Main” Class Class Execute Native (Until next Method) Yes LoadContainingClass No OtherClasses? Load Other Class Yes -Parents -Containing called methods -Declaring Args, Locals, Fields -Allocated (new) Jump to Native Code Return to CLR

20 Garbage Collection Desktop: G 0G 1G 2 2k Mark Promote Mark Promote

21 Garbage Collection Compact Framework : 5K Threshold MarkCompact Pitch Code? LRU

22 Performance

23 What Is Performance?  Affected by two principles  Absolute Performance of the system; the raw processing horsepower  Apparent Performance of the application; affected by how the application is written Application performance is qualitatively measured by how responsive the application is to the end user

24 Code Pitching  Occurs when large volumes of allocated memory cause memory pressure  Runtime will discard or pitch code from the code cache  Qualitative inspection will tell you when this occurs

25 Behavior Under Memory Pressure Memory utilization Performance

26 Compact Framework Performance  User Interface:  Version 1 performance is excellent!  System.Drawing and System.Windows.Forms call to native APIs beneath  Call “batching” where possible  Pools and reuses Window Handles  Data And XML Performance  Version 1 performance is good  Mostly implemented in managed code  Memory pressure effect data perfomance

27 Performance Tuning  Analyze Performance of Application  Discover where the application is slow  Choose where to optimize  What’s important to the customer scenarios?  Understand The APIs  How abstract is the API?  Example: XmlDocument vs XmlTextReader/Writer  What work has to happen under the hood?  Be aware of how events fire  Keep responsiveness

28 Performance Tips and Tricks

29 Execution Engine  Don’t call GC.Collect()!  Minimize the number of function calls  Consider making functions larger rather than having incredibly deep call stacks  Make use of asynchronous calls where useful, but avoid creating too many threads  Reduce, reuse, recycle!  The less memory you allocate, the faster your app will be!

30 User Interface  Reduce number of method calls  Example use Control.Bounds instead of Control.Location + Control.Size  Create the Window tree top down, rather than bottom up  Opposite of what VS.NET does by default  Minimize control addition on Form.Load()  Defer loading of controls until they are used

31 Handling Data  Make asynchronous requests  Defer data loading until it is required, discard when data no longer in use  Minimize data in memory at any time  Forward only reading is always faster than in memory representations  XmlDocument versus XmlTextReader  DataReader versus DataAdapter  Use StringBuilder for complex string manipulations

32 Interop

33 Types Of Native Code Interop  Calling native DLLs from C# and VB.NET  DLL Interop with P/Invoke is supported  Some limitations  No support for COM Interop  Some COM support through P/Invoke and DLL wrappers  Exposing managed code objects as native DLLs, COM or ActiveX objects  Not supported

34 Overall Native Code Interop strategy  Focus on enabling versus exhaustive  PInvoke is powerful, but advanced or edge case scenarios are more difficult than the desktop  It is possible for COM and.NET components to peacefully coexist in the same process/thread  Focus on simplicity for Version 1.0  Native code interop is very fast and simple

35 Platform Invocation PInvoke  Allows users to call custom native code and Windows APIs  Declare statement in Visual Basic  DLLImport Attribute in C#  Very flexible  Good support on the device  Extensively used in Forms and other parts of the framework

36 Simple Example MessageBox int MessageBox( HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType ); [DllImport("coredll.dll")] private static extern int MessageBox( IntPtr hWnd, string lpText, string lpCaption, uint uType); Private Declare Function MessageBox Lib "coredll.dll" ( _ ByVal hwndOwner As IntPtr, _ ByVal hwndOwner As IntPtr, _ ByVal lpText As String, _ ByVal lpText As String, _ ByVal lpCaption As String, _ ByVal lpCaption As String, _ ByVal uType As Integer) As Integer ByVal uType As Integer) As Integer

37 MessageBox using System.Runtime.InteropServices; [DllImport("coredll.dll")] private static extern int MessageBox( IntPtr hWnd, string lpText, string lpCaption, uint uType); MessageBox(IntPtr.Zero, "Hello World!", "Interop1", 0); 1.Loads and initialises coredll.dll 2.Locates the entry point MessageBox 3.Calls into the unmanaged code 4.Completes and returns back to managed code

38 DEMO Calling MessageBox

39 Data Marshaling  Simple Types  Direct Translation  Simple Objects and ValueTypes  Objects that contain simple types  Execution engine points at the data of the object  Some exceptions  Complex Objects and Value Types  Objects containing other objects need to manually marshal data

40 Marshaling Of Simple Types  The execution engine marshaling of simple data types C# Visual Basic Native Code intInteger int (32-bit integer) shortShort short (16-bit) boolBoolean BYTE (8-bit)* charChar wchar (16-bit) StringString wchar * Array int [] Array Integer () Data of the Array int * longLong Not Supported (64-bit) doubleDouble Not Supported (floating point) *bool and Boolean DO NOT convert to a Win32 BOOL

41 Marshaling Simple Objects  Members of classes are always laid out sequentially  Only classes containing simple types will be automatically marshaled Native Code - C typedef struct _RECT { LONG left; LONG top; LONG right; LONG bottom; } RECT; C# public class Rect { int left; int top; int right; int bottom; }

42 Marshaling Complex Objects  Marshal class  Located in System.Runtime.InteropServices  Provides advanced functionality to customize marshaling  Allows you to get copy managed objects into native code  Allows you to read and write raw memory if needed

43 DEMO Make a phone call

44 Callbacks  No support for direct native to managed function calls  Use MessageWindow  Part of Microsoft.WindowsCE.Forms  Steps for Callback  Create a MessageWindow in Managed  Pass window handle to native  Native sends messages back with it  Managed code can trap window messages

45 DEMO Using MessageWindow

46 Summary  Performance:  Understand what is acceptable for data “freshness”  Think asynchronously for best UI performance  Design, test and iterate on your design considering multiple approaches  Reduce, reuse and recycle objects  Interop:  Native DLL entry points can be called  COM objects can be wrapped by std DLLs  ActiveX controls not supported (3 rd party solution)  C# and Visual Basic components cannot be exposed as COM components or ActiveX controls

47 Advanced.NET Compact Framework Development BRIEF: In this session we will examine some of the more advanced topics around.NET CF starting with a look under the hood at what Compact Framework actually does. We will consider some design approaches and coding techniques that can lead to higher performance of your application, explore how to call and be called by native code, see the flexibility in ADO.NET on the device and finish by looking at the packaging, deployment and installation options available.


Download ppt "Introduction to the Compact Framework Marcus Perryman Principal Consultant Microsoft."

Similar presentations


Ads by Google