Writing Secure Mobile Applications for Windows Mobile Pocket PCs and Smartphones Marcus Perryman.
Introduction to the Compact Framework Marcus Perryman Principal Consultant Microsoft.
-
Upload
lucas-archibald-wade -
Category
Documents
-
view
217 -
download
2
Transcript of Introduction to the Compact Framework Marcus Perryman Principal Consultant Microsoft.
Introduction to the Introduction to the Compact FrameworkCompact Framework
Marcus PerrymanMarcus Perryman
Principal ConsultantPrincipal Consultant
MicrosoftMicrosoft
AgendaAgenda
Design goalsDesign goals Key componentsKey components Common features with the desktopCommon features with the desktop Differences from the desktopDifferences from the desktop What’s in and outWhat’s in and out
What is Compact What is Compact FrameworkFrameworkDesign GoalsDesign GoalsTarget mobile and embedded devicesTarget mobile and embedded devices Portable subset of .NET FrameworkPortable subset of .NET Framework
No new ‘compact’ namespacesNo new ‘compact’ namespaces Visual Basic .NET & C# compiler support Visual Basic .NET & C# compiler support
in v1in v1 Leverage Visual Studio .NETLeverage Visual Studio .NET
Run managed .EXEs and .DLLs directlyRun managed .EXEs and .DLLs directly Debug with Visual Studio .NETDebug with Visual Studio .NET
Peacefully co-exist with host OSPeacefully co-exist with host OS Run on native threads, P/Invoke to call Run on native threads, P/Invoke to call
native codenative code
Key Components Key Components
Host Operating SystemHost Operating System
Platform Adaptation LayerPlatform Adaptation Layer
ApplicationsApplications .NET Compact Framework.NET Compact Framework
Ap
p D
om
ain
Ho
st
Ap
p D
om
ain
Ho
st
ManagedManaged
NativeNative
Platform Specific Class LibsPlatform Specific Class Libs
Base Class LibsBase Class Libs
Execution Engine (MSCOREE.DLL) - CLRExecution Engine (MSCOREE.DLL) - CLR
Smart Device Smart Device ExtensionsExtensions
Smart Device Smart Device ExtensionsExtensions
Compact CLR Compact CLR CommonCommon FeaturesFeatures Verifiable type safe executionVerifiable type safe execution
No uninitialized variables, unsafe casts, No uninitialized variables, unsafe casts, bad array indexing, bad pointer mathbad array indexing, bad pointer math
Garbage CollectionGarbage Collection No ref-counting, no leaksNo ref-counting, no leaks
JIT compilationJIT compilation Error handling with exceptionsError handling with exceptions Common type systemCommon type system
Call, inherit, and source-level debug Call, inherit, and source-level debug across different languagesacross different languages
Compact CLR DifferencesCompact CLR Differences
COM InteropCOM Interop Good support for calling native DLLsGood support for calling native DLLs Support for calling a COM object through DLL Support for calling a COM object through DLL
wrapperswrappers No support for writing a COM / ActiveX object in No support for writing a COM / ActiveX object in
C# or Visual BasicC# or Visual Basic No Install-time JIT (nGen)No Install-time JIT (nGen) No Reflection EmitNo Reflection Emit No RemotingNo Remoting
Client web services is fully supportedClient web services is fully supported No No GenericGeneric Serialization Serialization
Datasets can be serialized to XMLDatasets can be serialized to XML Subsets of other areas of functionalitySubsets of other areas of functionality
.NET Compact Framework.NET Compact Framework
SystemSystem
System.DataSystem.Data System.XmlSystem.Xml
System.WebSystem.Web
GlobalizationGlobalization
TextText
SecuritySecurity
CollectionsCollections
ResourcesResources
ReflectionReflection
NetNet
IOIO
ThreadingThreading
DiagnosticsDiagnostics
ServiceProcessServiceProcess
ConfigurationConfiguration
DesignDesign
ADO.NETADO.NET
SqlServerCeSqlServerCe
SqlClientSqlClient
Xslt/XPathXslt/XPath
XmlDocumentXmlDocument
RuntimeRuntimeInteropServicesInteropServices
RemotingRemoting
SerializationSerialization
SerializationSerialization
ConfigurationConfiguration SessionStateSessionState
CachingCaching SecuritySecurity
ServicesServicesDescriptionDescription
DiscoveryDiscovery
ProtocolsProtocols
UIUIHtmlControlsHtmlControls
WebControlsWebControls
System.DrawingSystem.Drawing
ImagingImaging
Drawing2DDrawing2D
TextText
PrintingPrinting
System.WinFormsSystem.WinForms
DesignDesign ComponentModelComponentModel
Reader/WritersReader/Writers
Supported ControlsSupported Controls
ButtonButtonCheckBoxCheckBoxComboBoxComboBoxContextMenuContextMenuDataGridDataGridDomainUpDownDomainUpDownFileOpenDialogFileOpenDialog
Supported controlsSupported controlsHScrollBarHScrollBarImageListImageListLabelLabelListBoxListBoxListViewListViewTreeView TreeView FileSaveDialog FileSaveDialog
MainMenuMainMenuNumericUpDownNumericUpDownPanelPanelPictureBoxPictureBoxProgressBarProgressBarRadioButtonRadioButton
GroupBoxGroupBoxPrinting Printing
ControlsControls
RichTextBoxRichTextBox NotificationBubble (PPC)NotificationBubble (PPC)
StatusBarStatusBarTabControlTabControlTextBoxTextBoxTimerTimerToolBarToolBarVScrollBarVScrollBar
Unsupported controls Unsupported controls
Unsupported controls – not available in CEUnsupported controls – not available in CE
CheckedListBoxCheckedListBoxColorDialogColorDialogErrorProviderErrorProvider
HelpProviderHelpProviderLinkLabelLinkLabelNotifyIconNotifyIcon
ToolTipToolTipSplitterSplitterFontDialogFontDialog
Framework SizeFramework Size
Framework size (RAM or ROM)Framework size (RAM or ROM) ~1.5 MB~1.5 MB
Running RAM needsRunning RAM needs 1 MB+ (depends on app)1 MB+ (depends on app)
Typical application sizesTypical application sizes 5 - 100 KB5 - 100 KB Apps often smaller due to use of platform Apps often smaller due to use of platform
features in the frameworkfeatures in the framework
AgendaAgenda Under the hood – what goes on with Under the hood – what goes on with
CFCF JIT, GC and PitchingJIT, GC and Pitching
PerformancePerformance The art of tuningThe art of tuning
Platform InteropPlatform Interop Getting to native codeGetting to native code MarshallingMarshalling Callback’sCallback’s
SummarySummary
ArchitectureArchitecture
Host Operating SystemHost Operating System
Platform Adaptation LayerPlatform Adaptation Layer
Execution Engine (MSCOREE.DLL)Execution Engine (MSCOREE.DLL)
Platform Specific Class LibsPlatform Specific Class Libs
Base Class LibsBase Class Libs
ApplicationsApplications
.NET Compact Framework.NET Compact Framework
Ap
p D
om
ain
Ho
stA
pp
Do
mai
n H
ost
… LaunchManagedManagedNativeNative
The EEThe EEA short reviewA short review
Compiled managed code is a binary in Compiled managed code is a binary in Microsoft Intermediate LanguageMicrosoft Intermediate Language
Code is just-in-time compiled to the native Code is just-in-time compiled to the native processor language on type-by-type, processor language on type-by-type, method-by-method basismethod-by-method basis
Resulting native code is cached for Resulting native code is cached for later reuselater reuse
Over the lifetime of the app, the up front Over the lifetime of the app, the up front cost of jitting is amortized, and becomes cost of jitting is amortized, and becomes less and less significantless and less significant
Under the HoodUnder the Hood Build processBuild process
Same compilersSame compilers Local exe produced – additional Deploy Local exe produced – additional Deploy
stepstep File formatFile format
Standard PE format with no native codeStandard PE format with no native code Module load upgraded on deviceModule load upgraded on device
Contains Intermediate Language (IL) Contains Intermediate Language (IL) blocksblocks
Resources bound in or deployed in Resources bound in or deployed in parallelparallel
DeployDeploy Uses Connection Manager not Platform Uses Connection Manager not Platform
ManagerManager Again over Active SyncAgain over Active Sync
ActiveSync
ConnectionManager
Remote Deploy And Remote Deploy And DebugDebug
Visual StudioVisual Studio.NET.NET
WindowsWindows
DebugDebugManagerManager
Device or Device or EmulatorEmulator
STREAM STREAM CONNECTCONNECT
Process EnumerateProcess EnumerateApp.exeApp.exe
File CopyFile Copy
App.pdbApp.pdb
App.exeApp.exe
Remote ExecRemote Exec
STREAM STREAM CONNECTCONNECT
Remote DebugRemote Debug
Per-Thread Control FlowPer-Thread Control Flow
ExecuteExecuteManagedManagedMethodMethod
JITJITCompiled?Compiled?
Verify & JITVerify & JITCompileCompileMethod Method
Load BaseLoad BaseClassesClasses
Locate “Main”Locate “Main” ClassClass
Execute NativeExecute Native(Until next (Until next
Method)Method)
YesYes
LoadLoadContainingContaining
ClassClassNoNo
OtherOtherClasses?Classes?
Load OtherLoad OtherClass Class YesYes
-ParentsParents
-Containing called methodsContaining called methods
-Declaring Args, Locals, FieldsDeclaring Args, Locals, Fields
-Allocated (new)Allocated (new)
Jump to Native CodeJump to Native CodeReturn to CLRReturn to CLR
Garbage CollectionGarbage Collection
Compact Framework :Compact Framework :
5K
Threshold
MarkCompact
Pitch Code?LRU
What Is Performance?What Is Performance?
Affected by two principlesAffected by two principles Absolute PerformanceAbsolute Performance of the system; the of the system; the
raw processing horsepowerraw processing horsepower Apparent PerformanceApparent Performance of the of the
application; affected by how the application; affected by how the application is writtenapplication is written
Application performance is qualitatively Application performance is qualitatively measured by how responsive the measured by how responsive the application is to the end userapplication is to the end user
Code PitchingCode Pitching
Occurs when large volumes Occurs when large volumes of allocated memory cause of allocated memory cause memory pressurememory pressure
Runtime will discard or pitch code Runtime will discard or pitch code from the code cachefrom the code cache
Qualitative inspection will tell you Qualitative inspection will tell you when this occurswhen this occurs
Behavior Under Behavior Under Memory PressureMemory Pressure
Memory utilizationMemory utilization
Per
form
ance
Per
form
ance
Compact Framework Compact Framework PerformancePerformance User Interface:User Interface:
Version 1 performance is excellent!Version 1 performance is excellent! System.Drawing and System.Drawing and
System.Windows.Forms call to native System.Windows.Forms call to native APIs beneathAPIs beneath
Call “batching” where possibleCall “batching” where possible Pools and reuses Window HandlesPools and reuses Window Handles
Data And XML PerformanceData And XML Performance Version 1 performance is goodVersion 1 performance is good Mostly implemented in managed codeMostly implemented in managed code Memory pressure effect data Memory pressure effect data
perfomanceperfomance
Performance TuningPerformance Tuning Analyze Performance of ApplicationAnalyze Performance of Application
Discover where the application is slowDiscover where the application is slow Choose where to optimizeChoose where to optimize
What’s important to the customer What’s important to the customer scenarios? scenarios?
Understand The APIsUnderstand The APIs How abstract is the API?How abstract is the API?
Example: XmlDocument vs Example: XmlDocument vs XmlTextReader/WriterXmlTextReader/Writer
What work has to happen under the What work has to happen under the hood?hood?
Be aware of how events fireBe aware of how events fire Keep responsivenessKeep responsiveness
Execution EngineExecution Engine
Don’t call GC.Collect()!Don’t call GC.Collect()! Minimize the number of function callsMinimize the number of function calls
Consider making functions larger rather than Consider making functions larger rather than having incredibly deep call stackshaving incredibly deep call stacks
Make use of asynchronous calls where Make use of asynchronous calls where useful, but avoid creating useful, but avoid creating tootoo many threads many threads
Reduce, reuse, recycle!Reduce, reuse, recycle! The less memory you allocate, the faster your app The less memory you allocate, the faster your app
will be!will be!
User InterfaceUser Interface
Reduce number of method callsReduce number of method calls Example use Control.Bounds instead of Example use Control.Bounds instead of
Control.Location + Control.SizeControl.Location + Control.Size Create the Window tree top down, Create the Window tree top down,
rather than bottom uprather than bottom up Opposite of what VS.NET does by defaultOpposite of what VS.NET does by default
Minimize control addition on Minimize control addition on Form.Load()Form.Load() Defer loading of controls until they Defer loading of controls until they
are usedare used
Handling DataHandling Data
Make asynchronous requestsMake asynchronous requests Defer data loading until it is required, Defer data loading until it is required,
discard when data no longer in usediscard when data no longer in use Minimize data in memory at any timeMinimize data in memory at any time Forward only reading is always faster Forward only reading is always faster
than in memory representationsthan in memory representations XmlDocument versus XmlTextReaderXmlDocument versus XmlTextReader DataReader versus DataAdapterDataReader versus DataAdapter
Use StringBuilder for complex Use StringBuilder for complex string manipulationsstring manipulations
Types Of Native CodeTypes Of Native CodeInteropInterop
Calling native DLLs from C# and VB .NETCalling native DLLs from C# and VB .NET DLL Interop with P/Invoke is supportedDLL Interop with P/Invoke is supported
Some limitationsSome limitations No support for COM Interop No support for COM Interop
Some COM support through P/Invoke and DLL Some COM support through P/Invoke and DLL wrapperswrappers
Exposing managed code objects as native Exposing managed code objects as native DLLs, COM or ActiveX objectsDLLs, COM or ActiveX objects Not supportedNot supported
Overall Native CodeOverall Native CodeInterop strategyInterop strategy
Focus on enabling versus exhaustiveFocus on enabling versus exhaustive PInvoke is powerful, but advanced or PInvoke is powerful, but advanced or
edge case scenarios are more difficult edge case scenarios are more difficult than the desktopthan the desktop
It is possible for COM and .NET It is possible for COM and .NET components to peacefully coexist in the components to peacefully coexist in the same process/threadsame process/thread
Focus on simplicity for Version 1.0Focus on simplicity for Version 1.0 Native code interop is very fast Native code interop is very fast
and simpleand simple
Platform InvocationPlatform InvocationPInvokePInvoke
Allows users to call custom native Allows users to call custom native code and Windows APIscode and Windows APIs
Declare statement in Visual BasicDeclare statement in Visual Basic DLLImport Attribute in C#DLLImport Attribute in C# Very flexibleVery flexible Good support on the deviceGood support on the device Extensively used in Forms and other Extensively used in Forms and other
parts of the frameworkparts of the framework
Simple ExampleSimple ExampleMessageBoxMessageBoxint MessageBox(int MessageBox(
HWND hWnd, HWND hWnd, LPCTSTR lpText, LPCTSTR lpText, LPCTSTR lpCaption, LPCTSTR lpCaption, UINT uType );UINT uType );
[DllImport("coredll.dll")][DllImport("coredll.dll")]private static extern int MessageBox(private static extern int MessageBox(
IntPtr hWnd, IntPtr hWnd, string lpText, string lpText, string lpCaption, string lpCaption, uint uType);uint uType);
Private Declare Function MessageBox Lib "coredll.dll" ( _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 IntegerByVal uType As Integer) As Integer
MessageBoxMessageBox
using System.Runtime.InteropServices;using System.Runtime.InteropServices;
[DllImport("coredll.dll")][DllImport("coredll.dll")]private static extern int MessageBox(private static extern int MessageBox(
IntPtr hWnd, IntPtr hWnd, string lpText, string lpText, string lpCaption, string lpCaption, uint uType);uint uType);
MessageBox(IntPtr.Zero, "Hello World!", "Interop1", 0);MessageBox(IntPtr.Zero, "Hello World!", "Interop1", 0);
1.1. Loads and initialises coredll.dllLoads and initialises coredll.dll
2.2. Locates the entry point MessageBoxLocates the entry point MessageBox
3.3. Calls into the unmanaged codeCalls into the unmanaged code
4.4. Completes and returns back to managed codeCompletes and returns back to managed code
Data MarshalingData Marshaling
Simple TypesSimple Types Direct TranslationDirect Translation
Simple Objects and ValueTypesSimple Objects and ValueTypes Objects that contain simple typesObjects that contain simple types Execution engine points at the data of the objectExecution engine points at the data of the object Some exceptionsSome exceptions
Complex Objects and Value TypesComplex Objects and Value Types Objects containing other objects need to manually Objects containing other objects need to manually
marshal datamarshal data
Marshaling Of Simple Marshaling Of Simple TypesTypes The execution engine marshaling of simple The execution engine marshaling of simple
data typesdata types
C#C# Visual BasicVisual Basic Native CodeNative Code
intint IntegerInteger int (32-bit integer)int (32-bit integer)
shortshort ShortShort short (16-bit)short (16-bit)
boolbool BooleanBoolean BYTE (8-bit)BYTE (8-bit)**
charchar CharChar wchar (16-bit)wchar (16-bit)
StringString StringString wchar *wchar *
Array Array
int []int []ArrayArray
Integer ()Integer ()Data of the ArrayData of the Array
int *int *
longlong LongLong Not Supported (64-bit)Not Supported (64-bit)
doubledouble DoubleDouble Not Supported (floating Not Supported (floating point)point)
*bool and Boolean DO NOT convert to a Win32 BOOL*bool and Boolean DO NOT convert to a Win32 BOOL
Marshaling Simple Marshaling Simple ObjectsObjects Members of classes are always laid Members of classes are always laid
out sequentially out sequentially Only classes containing simple Only classes containing simple
types will be automatically types will be automatically marshaledmarshaled
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;
}
Marshaling Complex Marshaling Complex ObjectsObjects Marshal classMarshal class
Located in Located in System.Runtime.InteropServicesSystem.Runtime.InteropServices
Provides advanced functionality to Provides advanced functionality to customize marshalingcustomize marshaling
Allows you to get copy managed Allows you to get copy managed objects into native codeobjects into native code
Allows you to read and write raw Allows you to read and write raw memory if neededmemory if needed
CallbacksCallbacks
No support for direct native to No support for direct native to managed function callsmanaged function calls
Use MessageWindowUse MessageWindow Part of Microsoft.WindowsCE.FormsPart of Microsoft.WindowsCE.Forms
Steps for CallbackSteps for Callback Create a MessageWindow in ManagedCreate a MessageWindow in Managed Pass window handle to nativePass window handle to native Native sends messages back with it Native sends messages back with it Managed code can trap Managed code can trap
window messageswindow messages
SummarySummary
Performance:Performance: Understand what is acceptable for data Understand what is acceptable for data
“freshness”“freshness” Think asynchronously for best UI performanceThink asynchronously for best UI performance Design, test and iterate on your design Design, test and iterate on your design
considering multiple approachesconsidering multiple approaches Reduce, reuse and recycle objectsReduce, reuse and recycle objects
Interop:Interop: Native DLL entry points can be calledNative DLL entry points can be called COM objects can be wrapped by std DLLsCOM objects can be wrapped by std DLLs ActiveX controls not supported (3ActiveX controls not supported (3rdrd party solution) party solution) C# and Visual Basic components cannot C# and Visual Basic components cannot
be exposed as COM components or be exposed as COM components or ActiveX controlsActiveX controls