introduction to managed code development for windows mobile paul foster [email protected]
TRANSCRIPT
Introduction to managed Introduction to managed code development for code development for Windows MobileWindows Mobile
Paul FosterPaul [email protected]@microsoft.com
Event agendaEvent agenda
18.00 Registration18.00 Registration
18:30 Introduction to managed code 18:30 Introduction to managed code application development for Windows application development for Windows MobileMobile
19:30 Break / Refreshments19:30 Break / Refreshments
20:00 Session continued 20:00 Session continued
20:50 Q&A20:50 Q&A
21:00 Close21:00 Close
AgendaAgenda
Smart Client designSmart Client design Introduction to managed codeIntroduction to managed code
.Net Compact Framework – overview.Net Compact Framework – overview Design and performance tipsDesign and performance tips DeploymentDeployment
Windows Mobile 2003 2Windows Mobile 2003 2ndnd Edition Edition Orientation supportOrientation support DPI supportDPI support
Momentum Continues To Build…Momentum Continues To Build…600600
500500
400400
300300
200200
100100
Source: Gartner Dataquest (Dec. 2003)
PC ShipmentsPC Shipments
Un
it S
hip
men
ts (
M)
Un
it S
hip
men
ts (
M)
2001 2002 2003 2004 2005 2006 20072001 2002 2003 2004 2005 2006 2007
Mobile Device ShipmentsMobile Device ShipmentsFor Mobile Devices:For Mobile Devices: Mobile device adoption continues to growMobile device adoption continues to grow Growing Pocket PC market shareGrowing Pocket PC market share Smartphones launching, 37+ leading OEMs Smartphones launching, 37+ leading OEMs
and 50+ Mobile Operators partnersand 50+ Mobile Operators partners New form factors for landscape, high DPINew form factors for landscape, high DPI
For Mobile Applications:For Mobile Applications: $5.8 billion market$5.8 billion market for ISVs by 2006 for ISVs by 2006 (source: Forrester, 2002)
Customers demand Customers demand more mobile applicationsmore mobile applications (source: Handango, 2003)
Mobile Operators report monthly Mobile Operators report monthly ARPU increasesARPU increases of of 25% on Windows Mobile-based devices25% on Windows Mobile-based devices
700 700 applicationsapplications added to Mobile Application Catalog since launch added to Mobile Application Catalog since launch of Mobile2Market program last yearof Mobile2Market program last year
58% want more 58% want more Personal productivity Personal productivity appsapps58% want more 58% want more Business and professional Business and professional appsapps54% want more 54% want more GamesGames44% want more 44% want more UtilitiesUtilities
Windows Mobile RoadmapWindows Mobile Roadmap
Richer Richer Platform Platform CapabilitiesCapabilities
.NET CF “Whidbey”.NET CF “Whidbey”MFC 8.0, ATL 8.0MFC 8.0, ATL 8.0
Broad managed Broad managed code support code support
Notification broker, Notification broker, Location, Camera, Location, Camera, Watson, D3DM, Watson, D3DM,
.NET CF SP2.NET CF SP2
VGA (PPC)VGA (PPC)QVGA (SP)QVGA (SP)SquareSquareLandscapeLandscape
ATL 4.2, .NET CFATL 4.2, .NET CF Enhanced Enhanced Emulator Emulator Configuration Configuration Mgr,Mgr,Bluetooth, SMSBluetooth, SMS
MFC, MFC, ATL ATL
Active SyncActive SyncConnection MgrConnection MgrMAPIMAPIOBEXOBEXTelephonyTelephony
MFC MFC
Win32, Win32, POOM POOM
BetterBetterDevelopmentDevelopment VS “Whidbey”VS “Whidbey”
(C#, VB.NET, C++)(C#, VB.NET, C++)
eVC 3 eVC 3 (C++)(C++)eVC 4 eVC 4 (C++)(C++)
VS.NET 2003 VS.NET 2003 (C#, VB.NET)(C#, VB.NET)
eVC 3 eVC 3 (C++)(C++)eVC 4 eVC 4 (C++)(C++)
VS.NET 2003VS.NET 2003(C#, VB.NET)(C#, VB.NET)
eVC 3 eVC 3 (C++)(C++)eVB 3 eVB 3 (VB)(VB)
eVC 3 eVC 3 (C++)(C++)eVB 3 eVB 3 (VB)(VB)
Core OSCore OS WinCE WinCE “Macallan”“Macallan”WinCE 4.2WinCE 4.2WinCE 4.2WinCE 4.2WinCE 3.0WinCE 3.0 WinCE 3.0WinCE 3.0
MoreMoreDevice Device ChoicesChoices FutureFuture
Windows MobileWindows Mobile20032003Second EditionSecond Edition
200320032002200220002000
Smart Client designSmart Client design
For .Net Compact FrameworkFor .Net Compact Framework
The Mobile Device UniverseThe Mobile Device Universe
Infrastructure Servers, e.g. Network OperatorsInfrastructure Servers, e.g. Network Operators
ToolsTools
Web servicesWeb services
ClientsClients
User E
xperien
ces & S
olu
tion
sU
ser Exp
eriences &
So
lutio
nsAuthenticationAuthentication SMSSMS Voice CallsVoice Calls
Subscriber DBSubscriber DB MMSMMS Data CallsData CallsPersonalizationPersonalization BillingBilling etc…etc…
Police Force case studyPolice Force case study
Business driverBusiness driver Need to improve officer productivityNeed to improve officer productivity
GoalGoal Improve productivity to eqv. 100 additional Improve productivity to eqv. 100 additional
officersofficers Very public projectVery public project
Council tax contribution to fund projectCouncil tax contribution to fund project ResultsResults
PNC search results ~4 seconds back on devicePNC search results ~4 seconds back on device
The need for a Smart ClientThe need for a Smart Client
Application supports key business Application supports key business activitiesactivities
User needs to ‘fire and forget’ tasksUser needs to ‘fire and forget’ tasks Device security requires code on the Device security requires code on the
clientclient
What is a Smart Client design?What is a Smart Client design?
Client installed app using local CPUClient installed app using local CPU Works in both connect and Works in both connect and
disconnected network statesdisconnected network states In-built application change In-built application change
managementmanagement
Smart Client architectureSmart Client architecture
Why consciously factor code?Why consciously factor code? Increased abstractionIncreased abstraction Decreased complexity Decreased complexity Increase reusabilityIncrease reusability
How to factor code?How to factor code? Move code (functions, classes, Move code (functions, classes,
assemblies)assemblies) Change code visibilityChange code visibility Share or Split implementationsShare or Split implementations
Specific Factoring Specific Factoring OpportunitiesOpportunities The .NET Compact Framework has The .NET Compact Framework has
additional opportunities to gain value additional opportunities to gain value by factoringby factoring
Divide them into two key sub-groups:Divide them into two key sub-groups: Cross-tier factoringCross-tier factoring Intra-tier (on-device) factoringIntra-tier (on-device) factoring
Multi-tier FactoringMulti-tier Factoring
How much can you put on a server?How much can you put on a server? How will you handle being unable to How will you handle being unable to
reach the server? reach the server? Duplication of sending (idempotence)Duplication of sending (idempotence) Mobile apps must be able to continue Mobile apps must be able to continue
running while mobile running while mobile Client data stores: XML, SQLCE, flat Client data stores: XML, SQLCE, flat
files…files…
Cross-tier factoringCross-tier factoring
Device application functionality
Server application functionality
Unreliable wireless connectivity
Intra-tier FactoringIntra-tier Factoring
Strict separation of UI and client-side Strict separation of UI and client-side logic (UI Processing code)logic (UI Processing code) User interface code handles the specifics User interface code handles the specifics
of the screen drawingof the screen drawing All logic associated with client validation, All logic associated with client validation,
logic, rules, etc., should be considered UI logic, rules, etc., should be considered UI ProcessingProcessing
Allows reuse of the maximum possible Allows reuse of the maximum possible subset of codesubset of code
Device VarietyDevice Variety
.NET Compact Framework allows for .NET Compact Framework allows for unified API for many devicesunified API for many devices
The underlying form factors can be The underlying form factors can be quite diverse, though.quite diverse, though.
This means input methods may be This means input methods may be differentdifferent
Consider factoring to allow for Consider factoring to allow for additional devices to be supported additional devices to be supported later.later.
N-tier application architectureN-tier application architecture
Op
era
tion
al M
an
ag
em
en
t
Secu
rity
Com
mu
nica
tion
UI Components
UI Process Components
Business Workflows
Service Interfaces
Business Components Business Entities
Users
Data Sources Services
Data Access Logic Components Service Agents
Introduction to the .Net Introduction to the .Net Compact FrameworkCompact Framework
DisplayDisplayUSB or SerialUSB or Serial
ProcessorProcessorMemoryMemory
GSM/GPRSGSM/GPRSCDMA/1xRTTCDMA/1xRTT
Device Device HardwareHardware
WiFiWiFiBluetoothBluetooth
RadioRadio
DriversDrivers
Windows MobileWindows Mobile CE DBCE DBActiveSyncActiveSync
Pocket OutlookPocket OutlookPocket Internet ExplorerPocket Internet ExplorerWindows Media PlayerWindows Media Player
Windows CEWindows CE
Software Platform (APIs)Software Platform (APIs)
Home ScreenHome ScreenUser Interface/ShellUser Interface/ShellHTML ControlHTML Control
GAPIGAPIRemote APIRemote APIConfigurationConfigurationBluetoothBluetoothSecuritySecurity
Connection ManagerConnection Manager TAPITAPISMS SMS MAPI MAPI POOM POOM ActiveSyncActiveSync
MultimediaMultimediaCommunicatioCommunicationn
Device ManagementDevice Management PresentationPresentation
ADO CEADO CEXMLXMLCE DBCE DBOLE DBOLE DB
Data AccessData Access
NativeNative
Win32Win32
MFCMFC ATLATL
ManagedManaged
.NET Compact.NET CompactFrameworkFramework
Server sideServer side
ASP .NETASP .NETMobile ControlsMobile Controls
NativeNative
Win32Win32
MFCMFC ATLATL
ManagedManaged
.NET Compact.NET CompactFrameworkFramework
Server sideServer side
ASP .NETASP .NETMobile ControlsMobile Controls
Windows Mobile Development PlatformWindows Mobile Development Platform:: TodayToday
Embedded VC++Embedded VC++ Visual Studio .NETVisual Studio .NET
DisplayDisplayUSB or SerialUSB or Serial
ProcessorProcessorMemoryMemory
GSM/GPRSGSM/GPRSCDMA/1xRTTCDMA/1xRTT
Device Device HardwareHardware
WiFiWiFiBluetoothBluetooth
RadioRadio
DriversDrivers
Windows MobileWindows Mobile CE DBCE DBActiveSyncActiveSyncSQL CESQL CE
Pocket OutlookPocket OutlookPocket Internet ExplorerPocket Internet ExplorerWindows Media PlayerWindows Media Player
Windows CEWindows CE
Software Platform (APIs)Software Platform (APIs)
Home ScreenHome ScreenUser Interface/ShellUser Interface/ShellHTML ControlHTML ControlDOMDOM
GAPIGAPICameraCameraD3DMD3DMLocation*Location*
Remote APIRemote APIConfigurationConfiguration**BluetoothBluetoothStatsor*Statsor*Pocket WatsonPocket Watson
Connection ManagerConnection Manager TAPI*TAPI*SMSSMS** MAPIMAPI** POOMPOOM**
MultimediaMultimediaCommunicatioCommunicationn
Device ManagementDevice Management PresentationPresentation
SQL CESQL CEADO CEADO CEXMLXMLCE DBCE DBOLE DBOLE DB
Data AccessData Access
NativeNative
Win32Win32
MFCMFC ATLATL
ManagedManaged
.NET Compact.NET CompactFrameworkFramework
Server sideServer side
ASP .NETASP .NETMobile ControlsMobile Controls
Orange = Added/Enhanced in Future Windows Mobile Orange = Added/Enhanced in Future Windows Mobile PlatformPlatform* = Managed wrappers* = Managed wrappers
This Session Will Focus On …This Session Will Focus On …
Visual Studio “Whidbey”Visual Studio “Whidbey”
.NET Compact Framework Today….NET Compact Framework Today… Service Pack 2 ImprovementsService Pack 2 Improvements
Download it today from MSDNDownload it today from MSDN Performance Gains over RTMPerformance Gains over RTM
~ 40% faster XML~ 40% faster XML ~ 20% faster ADO.NET~ 20% faster ADO.NET
ForeColor and BackColor!!!ForeColor and BackColor!!! Keyboard EventsKeyboard Events Support for Future DevicesSupport for Future Devices
Developer AdoptionDeveloper Adoption Fourth most active .NET newsgroupFourth most active .NET newsgroup Developer Focused Web sites likeDeveloper Focused Web sites like
http://www.OpenNetCF.orghttp://www.OpenNetCF.org http://www.dotnetdn.com/http://www.dotnetdn.com/ http://http://www.pocketPCDN.comwww.pocketPCDN.com
http://http://msdn.microsoft.commsdn.microsoft.com//mobilitymobility// Information direct from product team Information direct from product team
membersmembers
.NET Compact Framework Today….NET Compact Framework Today…Third Party Controls and LibrariesThird Party Controls and Libraries
ComponentOne Studio for ComponentOne Studio for Mobile DevicesMobile Devices
/n Software’s IP*Works /n Software’s IP*Works for .NET Compact for .NET Compact FrameworkFramework
InstallShield Developer InstallShield Developer Mobile EditionMobile Edition
Odyssey CFComOdyssey CFCom Preemptive DotfuscatorPreemptive Dotfuscator And More!And More!
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
The .NET Compact FrameworkThe .NET Compact Framework
SystemSystem
System.DataSystem.Data System.XmlSystem.Xml
System.WebSystem.Web
GlobalizationGlobalization
TextText
SecuritySecurity
CollectionsCollections
ResourcesResources
ReflectionReflection
NetNet
IOIO
ThreadingThreading
DiagnosticsDiagnostics
ADO.NETADO.NET
SqlServerCeSqlServerCe
SqlClientSqlClient XmlDocumentXmlDocument
common languagecommon languageruntimeruntime
InteropServicesInteropServices
SecuritySecurity
ServicesServicesDescriptionDescription
DiscoveryDiscovery
ProtocolsProtocols System.DrawingSystem.Drawing
Drawing2DDrawing2D
TextText
System.Windows.FormsSystem.Windows.Forms
DesignDesign ComponentModelComponentModel
Reader/WritersReader/Writers
The .NET Common The .NET Common Language RuntimeLanguage Runtime Core functionality for execution Core functionality for execution No worries about initialized pointers!No worries about initialized pointers! Provides garbage collection servicesProvides garbage collection services Good performance through JIT compilationGood performance through JIT compilation Straightforward error handling with Straightforward error handling with
exceptionsexceptions Support for Win32 APIs through platform Support for Win32 APIs through platform
invocationinvocation All these benefits, and you can pick your All these benefits, and you can pick your
development favourite language too!development favourite language too!
SystemSystem
System.DataSystem.Data System.XmlSystem.Xml
System.WebSystem.Web
GlobalizationGlobalization
TextText
SecuritySecurity
CollectionsCollections
ResourcesResources
ReflectionReflection
NetNet
IOIO
ThreadingThreading
DiagnosticsDiagnostics
ADO.NETADO.NET
SqlServerCeSqlServerCe
SqlClientSqlClient XmlDocumentXmlDocument
common languagecommon languageruntimeruntime
InteropServicesInteropServices
RemotingRemoting
SerializationSerialization
SecuritySecurity
ServicesServices
DescriptionDescription
DiscoveryDiscovery
ProtocolsProtocols System.DrawingSystem.Drawing
Drawing2DDrawing2D
TextText
System.Windows.FormsSystem.Windows.Forms
DesignDesign ComponentModelComponentModel
Reader/WritersReader/Writers
CompilerCompiler AssemblyAssemblyAssemblyAssembly
Common Language RuntimeCommon Language RuntimeDEVELOPMENTDEVELOPMENT
C#C#J#J#VBVB
CobolCobol……
MSILMSILMetadataMetadata
ResourcesResources
public static void Main(String[] args ){ String usr; FileStream f; StreamWriter w; try { usr=Environment.GetEnvironmentVariable("USERNAME"); f=new FileStream(“C:\\test.txt",FileMode.Create); w=new StreamWriter(f); w.WriteLine(usr); w.Close(); } catch (Exception e){ Console.WriteLine("Exception:"+e.ToString()); }}
public static void Main(String[] args ){ String usr; FileStream f; StreamWriter w; try { usr=Environment.GetEnvironmentVariable("USERNAME"); f=new FileStream(“C:\\test.txt",FileMode.Create); w=new StreamWriter(f); w.WriteLine(usr); w.Close(); } catch (Exception e){ Console.WriteLine("Exception:"+e.ToString()); }}
Source codeSource code
CompilerCompiler AssemblyAssemblyAssemblyAssembly
DEVELOPMENTDEVELOPMENT
C#C#J#J#VBVB
CobolCobol……
MSILMSILMetadataMetadata
ResourcesResources
public static void Main(String[] args ){ String usr; FileStream f; StreamWriter w; try { usr=Environment.GetEnvironmentVariable("USERNAME"); f=new FileStream(“C:\\test.txt",FileMode.Create); w=new StreamWriter(f); w.WriteLine(usr); w.Close(); } catch (Exception e){ Console.WriteLine("Exception:"+e.ToString()); }}
public static void Main(String[] args ){ String usr; FileStream f; StreamWriter w; try { usr=Environment.GetEnvironmentVariable("USERNAME"); f=new FileStream(“C:\\test.txt",FileMode.Create); w=new StreamWriter(f); w.WriteLine(usr); w.Close(); } catch (Exception e){ Console.WriteLine("Exception:"+e.ToString()); }}
Source codeSource code
ApplicationApplicationDirectoryDirectory
ApplicationApplicationDirectoryDirectory
GlobalGlobalAssemblyAssembly
Cache (GAC)Cache (GAC)
GlobalGlobalAssemblyAssembly
Cache (GAC)Cache (GAC)
Common Language RuntimeCommon Language Runtime
AssemblyAssemblyAssemblyAssembly
DEVELOPMENTDEVELOPMENT DEPLOYMENTDEPLOYMENT
SetupSetupCopyCopy
BrowserBrowser
Download Download CacheCache
Download Download CacheCache
InstallInstall
Debug EngineDebug Engine
IL to NativeIL to NativeCompilerCompiler
ApplicationApplicationDirectoryDirectory
ApplicationApplicationDirectoryDirectory
SetupSetupCopyCopy
BrowserBrowser
Download Download CacheCache
Download Download CacheCache
GlobalGlobalAssemblyAssembly
Cache (GAC)Cache (GAC)
GlobalGlobalAssemblyAssembly
Cache (GAC)Cache (GAC)
AssemblyAssemblyon Target on Target MachineMachine
AssemblyAssemblyon Target on Target MachineMachine
Common Language RuntimeCommon Language Runtime
AssemblyAssemblyAssemblyAssembly
DEVELOPMENTDEVELOPMENT DEPLOYMENTDEPLOYMENT
InstallInstall
EXECUTIONEXECUTION
AssemblyAssemblyLoaderLoaderSecuritySecurityClass Class
LoaderLoader
Native .exe Native .exe + GC table + GC table Native .exe Native .exe + GC table + GC table
Code Code ManagerManager
Garbage CollectionGarbage Collection
Exception ManagerException Manager
Thread SupportThread Support
COM InteropCOM Interop
Policy<?xml version="1.0" encoding="utf-8" ?><configuration> <mscorlib> <security> <policy> <PolicyLevel version="1"> <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="Nothing" Name="All_Code" Description="Code group grants no permissions and forms the root of the code group tree."> <IMembershipCondition class="AllMembershipCondition" version="1"/> <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="FullTrust"
Networking SupportNetworking SupportSystem.NetSystem.Net SocketsSockets
Provides synchronous and asynchronousProvides synchronous and asynchronous Multiple protocolsMultiple protocols
StreamsStreams Built on top of socketsBuilt on top of sockets Synchronous and asynchronousSynchronous and asynchronous
HTTP request and responseHTTP request and response Use stream modelUse stream model Requires no user knowledge of HTTPRequires no user knowledge of HTTP
SystemSystem
System.DataSystem.Data System.XmlSystem.Xml
System.WebSystem.Web
GlobalizationGlobalization
TextText
SecuritySecurity
CollectionsCollections
ResourcesResources
ReflectionReflection
NetNet
IOIO
ThreadingThreading
DiagnosticsDiagnostics
ADO.NETADO.NET
SqlServerCeSqlServerCe
SqlClientSqlClient XmlDocumentXmlDocument
common languagecommon languageruntimeruntime
InteropServicesInteropServices
RemotingRemoting
SerializationSerialization
SecuritySecurity
ServicesServices
DescriptionDescription
DiscoveryDiscovery
ProtocolsProtocols System.DrawingSystem.Drawing
Drawing2DDrawing2D
TextText
System.Windows.FormsSystem.Windows.Forms
DesignDesign ComponentModelComponentModel
Reader/WritersReader/Writers
Web Service SupportWeb Service SupportSystem.WebSystem.Web
Calling Web servicesCalling Web services All encoding typesAll encoding types Synchronous and asynchronous invocationSynchronous and asynchronous invocation Basic and Digest authenticationBasic and Digest authentication Secure Sockets Layer support for encryption (SSL)Secure Sockets Layer support for encryption (SSL) Custom SOAP headersCustom SOAP headers Read more about it!Read more about it!
Consuming XML Web Services with the Microsoft .NET Consuming XML Web Services with the Microsoft .NET Compact Framework Compact Framework http://msdn.microsoft.com/mobility/understanding/articles/default.aspx?http://msdn.microsoft.com/mobility/understanding/articles/default.aspx?pull=/library/en-us/dnnetcomp/html/netcfwebservices.asppull=/library/en-us/dnnetcomp/html/netcfwebservices.asp
SystemSystem
System.DataSystem.Data System.XmlSystem.Xml
System.WebSystem.Web
GlobalizationGlobalization
TextText
SecuritySecurity
CollectionsCollections
ResourcesResources
ReflectionReflection
NetNet
IOIO
ThreadingThreading
DiagnosticsDiagnostics
ADO.NETADO.NET
SqlServerCeSqlServerCe
SqlClientSqlClient XmlDocumentXmlDocument
common languagecommon languageruntimeruntime
InteropServicesInteropServices
RemotingRemoting
SerializationSerialization
SecuritySecurity
ServicesServices
DescriptionDescription
DiscoveryDiscovery
ProtocolsProtocols System.DrawingSystem.Drawing
Drawing2DDrawing2D
TextText
System.Windows.FormsSystem.Windows.Forms
DesignDesign ComponentModelComponentModel
Reader/WritersReader/Writers
Data SupportData SupportSystem.DataSystem.Data
Handling data offline with DataSetHandling data offline with DataSet Common data model from server to PC to Common data model from server to PC to
devicedevice Extensible ADO.NET provider modelExtensible ADO.NET provider model SQL Server (System.Data.SqlClient)SQL Server (System.Data.SqlClient) SQL Server CE (System.Data.SqlServerCe)SQL Server CE (System.Data.SqlServerCe)
Managed access to rich, robust device databaseManaged access to rich, robust device database Efficient, complex queryingEfficient, complex querying Enables online/offline applicationsEnables online/offline applications Data synchronization to SQL Server with server Data synchronization to SQL Server with server
and client trackingand client tracking
SystemSystem
System.DataSystem.Data System.XmlSystem.Xml
System.WebSystem.Web
GlobalizationGlobalization
TextText
SecuritySecurity
CollectionsCollections
ResourcesResources
ReflectionReflection
NetNet
IOIO
ThreadingThreading
DiagnosticsDiagnostics
ADO.NETADO.NET
SqlServerCeSqlServerCe
SqlClientSqlClient XmlDocumentXmlDocument
common languagecommon languageruntimeruntime
InteropServicesInteropServices
RemotingRemoting
SerializationSerialization
SecuritySecurity
ServicesServices
DescriptionDescription
DiscoveryDiscovery
ProtocolsProtocols System.DrawingSystem.Drawing
Drawing2DDrawing2D
TextText
System.Windows.FormsSystem.Windows.Forms
DesignDesign ComponentModelComponentModel
Reader/WritersReader/Writers
DataDataBest PracticesBest Practices
If data is local…instead of DataSet…If data is local…instead of DataSet… Leverage SQL Server CE native in-proc databaseLeverage SQL Server CE native in-proc database Query data using DataReaderQuery data using DataReader Use TableDirect command type for fast index searchesUse TableDirect command type for fast index searches
Equivalent to “Equivalent to “SELECT * FROM SELECT * FROM foofoo WHERE WHERE barbar > 3” > 3” Limit open SqlCeCommand/DataReadersLimit open SqlCeCommand/DataReaders
Dispose when completeDispose when complete If data is remote…If data is remote…
Use SQL Server CE replicationUse SQL Server CE replication When using Web ServicesWhen using Web Services
Use DiffGrams to read and write DataSets to limit data transferUse DiffGrams to read and write DataSets to limit data transfer Save data locally in SQL Server CE for faster access and Save data locally in SQL Server CE for faster access and
storagestorage Don’t save remote DataSets as XML to deviceDon’t save remote DataSets as XML to device
If you do, save Schema as wellIf you do, save Schema as well
XMLXMLBest Practices for Managing Large XML Data Best Practices for Managing Large XML Data FilesFiles
Use XmlTextReader and XmlTextWriterUse XmlTextReader and XmlTextWriter Smaller memory footprint than using Smaller memory footprint than using
XmlDocumentXmlDocument XmlTextReader is a pull model parser XmlTextReader is a pull model parser
which only reads a “window” of the datawhich only reads a “window” of the data Design XML schema first, then codeDesign XML schema first, then code
Understand the structure of your XML Understand the structure of your XML documentdocument
Use elements to groupUse elements to group Allows use of Skip() in XmlTextReaderAllows use of Skip() in XmlTextReader
Use attributes to reduce sizeUse attributes to reduce size
XMLXMLBest Practices for SerializationBest Practices for Serialization
Use XmlTextReader and XmlTextWriterUse XmlTextReader and XmlTextWriter XmlDocument builds a generic, untyped object XmlDocument builds a generic, untyped object
model using a treemodel using a tree Type stored as stringType stored as string
Use XmlConvert to convert each element to Use XmlConvert to convert each element to appropriate managed type for efficiencyappropriate managed type for efficiency e.g. Int32e.g. Int32
Design XML schema first, then codeDesign XML schema first, then code Use elements for objects and arraysUse elements for objects and arrays Use attributes for simple properties and fieldsUse attributes for simple properties and fields
XML And DataXML And Data.NET Compact Framework 2.0 .NET Compact Framework 2.0 PerformancePerformance Vastly improved XmlTextReader (SP2) Vastly improved XmlTextReader (SP2)
and XmlTextWriterand XmlTextWriter XmlSerializerXmlSerializer Improved ADO.NET performance with Improved ADO.NET performance with
SQL Server CE 3.0 SQL Server CE 3.0 SqlCeResultSetSqlCeResultSet
Direct access to scrollable, updatable cursorDirect access to scrollable, updatable cursor
User Interface DesignUser Interface Design
Wide range of controls Wide range of controls Supported controls are tailored to each Supported controls are tailored to each
devicedevice Rich designer support in Visual Studio .NETRich designer support in Visual Studio .NET Some desktop functionality isn’t supportedSome desktop functionality isn’t supported
ActiveX ControlsActiveX Controls PrintingPrinting Drag and DropDrag and Drop GDI+ (transparency)GDI+ (transparency)
SystemSystem
System.DataSystem.Data System.XmlSystem.Xml
System.WebSystem.Web
GlobalizationGlobalization
TextText
SecuritySecurity
CollectionsCollections
ResourcesResources
ReflectionReflection
NetNet
IOIO
ThreadingThreading
DiagnosticsDiagnostics
ADO.NETADO.NET
SqlServerCeSqlServerCe
SqlClientSqlClient XmlDocumentXmlDocument
common languagecommon languageruntimeruntime
InteropServicesInteropServices
RemotingRemoting
SerializationSerialization
SecuritySecurity
ServicesServices
DescriptionDescription
DiscoveryDiscovery
ProtocolsProtocols System.DrawingSystem.Drawing
Drawing2DDrawing2D
TextText
System.Windows.FormsSystem.Windows.Forms
DesignDesign ComponentModelComponentModel
Reader/WritersReader/Writers
Supported ControlsSupported ControlsSystem.Windows.FormsSystem.Windows.Forms
ButtonButton
CheckBoxCheckBox
ComboBoxComboBox
ContextMenuContextMenu
DataGridDataGrid
DomainUpDownDomainUpDown
FileOpenDialogFileOpenDialog
Supported controls Supported controls FileSaveDialog FileSaveDialog
HScrollBarHScrollBar
ImageListImageList
Input PanelInput Panel
LabelLabel
ListBoxListBox
ListViewListView
MainMenuMainMenu
NumericUpDownNumericUpDown
PanelPanel
PictureBoxPictureBox
ProgressBarProgressBar
RadioButtonRadioButton
StatusBarStatusBar
TabControlTabControl
TextBoxTextBox
TimerTimer
ToolBarToolBar
Track BarTrack Bar
TreeViewTreeView
VScrollBarVScrollBar
Unavailable controlsUnavailable controls
CheckedListBoxCheckedListBox
ColorDialogColorDialog
ErrorProviderErrorProvider
HelpProviderHelpProvider
LinkLabelLinkLabel
NotifyIconNotifyIcon
ToolTipToolTip
SplitterSplitter
FontDialogFontDialog
Control ExtensibilityControl ExtensibilitySystem.Windows.FormsSystem.Windows.Forms
Add functionality to existing controlsAdd functionality to existing controls Create a text box that only supports numeric text Create a text box that only supports numeric text
entryentry Add additional properties specific to your Add additional properties specific to your
applicationapplication Create your own new controlsCreate your own new controls
Many 3Many 3rdrd party examples, such as a signature party examples, such as a signature capture controlcapture control
Article with source code:Article with source code: Microsoft® .NET Compact Framework-based Microsoft® .NET Compact Framework-based
DateTimePicker Control DateTimePicker Control http://msdn.microsoft.com/mobility/understanding/articles/default.aspx?http://msdn.microsoft.com/mobility/understanding/articles/default.aspx?pull=/library/en-us/dnnetcomp/html/netcfdatetimepicker.asppull=/library/en-us/dnnetcomp/html/netcfdatetimepicker.asp
Windows FormsWindows FormsBest PracticesBest Practices
Load and cache Forms in the backgroundLoad and cache Forms in the background Populate data separate from Form.Show()Populate data separate from Form.Show()
Pre-populate data, orPre-populate data, or Load data async to Form.Show()Load data async to Form.Show()
Parent controls top-downParent controls top-down e.g. Form e.g. Form panels panels controls controls
Use BeginUpdate/EndUpdate when it is availableUse BeginUpdate/EndUpdate when it is available e.g. ListView, TreeViewe.g. ListView, TreeView
Use SuspendLayout/ResumeLayout when Use SuspendLayout/ResumeLayout when repositioning controlsrepositioning controls
Keep event handling code tightKeep event handling code tight Process bigger operations asynchronouslyProcess bigger operations asynchronously BlockingBlocking in event handlers will affect UI responsiveness in event handlers will affect UI responsiveness
Form ManagementForm Management
The Form Flow ChallengeThe Form Flow Challenge No Multiple Document InterfaceNo Multiple Document Interface Multi form input more commonMulti form input more common Which form to display next?Which form to display next? Hide or destroy current form?Hide or destroy current form?
SolutionsSolutions Dynamic form constructionDynamic form construction Forms managerForms manager Wizard based input (e.g. tight scripting of forms)Wizard based input (e.g. tight scripting of forms)
Form ManagementForm Management
Application Kernel
Web Service Interface Local Store (SQL CE )
Main Form Collect Form
InspectForm
Truck Form
Form Manager
Main
Identifying The Top PitfallsIdentifying The Top PitfallsThe most common problemsThe most common problems
Putting synchronous code in Form_LoadPutting synchronous code in Form_Load Putting too much code in Form_LoadPutting too much code in Form_Load Assuming connectivity (implicitly)Assuming connectivity (implicitly) Mixing user interface code and processing Mixing user interface code and processing Architecting based on incomplete or non-Architecting based on incomplete or non-
representative testsrepresentative tests Accepting default timeoutsAccepting default timeouts Misapplying UI metaphors (desktop to mobile)Misapplying UI metaphors (desktop to mobile)
CRM Mobile ArchitectureCRM Mobile Architecture
DynamicOfflineStore
SQL CE Store
Metadata driven
Data AccessDatasets and Data ReadersWrapped with our Metadata APIs
MetadataDriven
Biz Logic
C# Code forOfflineBusiness Logic
MetadataDriven UI
Dynamic WinForms
Metadata andData Sync
Metadata changes aredownloaded on the flySQL CE schemas arealtered on the flyData is downloaded without replication usingStandard XML messages
MetadataDriven
Wire Formats
Dataset to messagetransforms are metadata driven
Web Services forConnected Scenarios
SQL CE RDA for async reliable messaging
InteroperabilityInteroperability
Platform Invocation (P/Invoke)Platform Invocation (P/Invoke) Allows users to call custom native code and Windows APIsAllows users to call custom native code and Windows APIs Declare statement in Visual BasicDeclare statement in Visual Basic DLLImport Attribute in C#DLLImport Attribute in C#
CallbacksCallbacks No support for direct native to managed function callsNo support for direct native to managed function calls Use MessageWindowUse MessageWindow
Part of Microsoft.WindowsCE.FormsPart of Microsoft.WindowsCE.Forms
COM InteroperabilityCOM Interoperability Not directly supported in this versionNot directly supported in this version Need to create native wrapperNeed to create native wrapper Partner solutions available (Odyssey Software)Partner solutions available (Odyssey Software)
InteroperabilityInteroperabilityGet More Information!Get More Information!
ArticlesArticles An Introduction to P/Invoke and An Introduction to P/Invoke and
Marshaling on the Microsoft .NET Marshaling on the Microsoft .NET Compact FrameworkCompact Frameworkhttp://msdn.microsoft.com/mobility/understanding/articles/default.aspx?http://msdn.microsoft.com/mobility/understanding/articles/default.aspx?pull=/library/en-us/dnnetcomp/html/netcfintrointerp.asppull=/library/en-us/dnnetcomp/html/netcfintrointerp.asp
Advanced P/Invoke on the Microsoft .NET Advanced P/Invoke on the Microsoft .NET Compact FrameworkCompact Frameworkhttp://msdn.microsoft.com/mobility/understanding/articles/default.aspx?http://msdn.microsoft.com/mobility/understanding/articles/default.aspx?pull=/library/en-us/dnnetcomp/html/netcfadvinterop.asppull=/library/en-us/dnnetcomp/html/netcfadvinterop.asp
Performance PrinciplesPerformance PrinciplesIn general…In general…
Less code is faster codeLess code is faster code Fewer objects are better for performanceFewer objects are better for performance Recycle and re-use expensive resourcesRecycle and re-use expensive resources Batch work where possibleBatch work where possible Initialize lazilyInitialize lazily Do work in the background to affect Do work in the background to affect
“perceived” performance“perceived” performance Use threads and async calls Use threads and async calls
Understand what the APIs are doingUnderstand what the APIs are doing
Application deploymentApplication deployment
A mobile Smart Client exampleA mobile Smart Client example
Application DeploymentApplication Deployment
Visual Studio .NET provides auto-generation Visual Studio .NET provides auto-generation of simple CAB files for ActiveSyncof simple CAB files for ActiveSync Include application and dependant referencesInclude application and dependant references Does not include the runtimeDoes not include the runtime Does not include other products that the app Does not include other products that the app
requires (e.g. SQL Server CE)requires (e.g. SQL Server CE)
Temporary files are kept if user wants to Temporary files are kept if user wants to customize the cab file contentscustomize the cab file contents
Self-updating applicationsSelf-updating applications
Application event triggers update Application event triggers update enquiryenquiry
Updater applet calls web service with Updater applet calls web service with version and platform dataversion and platform data
Web service indicates new version and Web service indicates new version and locationlocation
Updater asynchronously acquires cabUpdater asynchronously acquires cab Updater executes cab causing installUpdater executes cab causing install New application version installedNew application version installed
Self-updating architectureSelf-updating architecture
ApplicationV1.0
Updater
Web S
ervice
XMLSpec
CAB
CAB
CAB
CAB
CAB
CAB
\downloads
CAB
ApplicationV1.1
Async dow
nload
CAB executed
New version
http://msdn.microsoft.com/library/default.asp
Creating Self-Updating Applications With the .NET Compact Framework By Alex FeinmanOpenNETCF.org
Windows Mobile 2003 2Windows Mobile 2003 2ndnd Edition Edition
Windows Mobile 2003 2Windows Mobile 2003 2ndnd edition edition
Screen orientationScreen orientation High DPI supportHigh DPI support ActiveSync programming modelActiveSync programming model Today screen selection APIToday screen selection API .Net Compact Framework SP2 in ROM.Net Compact Framework SP2 in ROM
Developer resourcesDeveloper resources
Windows Mobile developer downloadsWindows Mobile developer downloads http://www.microsoft.com/windowsmobile/resourcehttp://www.microsoft.com/windowsmobile/resource
s/downloads/developer/default.mspxs/downloads/developer/default.mspx
Developer Resource kitDeveloper Resource kit White papersWhite papers SamplesSamples
Windows Mobile 2003 2Windows Mobile 2003 2ndnd Edition emulators for PPC Edition emulators for PPC and Smartphoneand Smartphone
eVC V4 SP3eVC V4 SP3
Types Of Orientations & ScreensTypes Of Orientations & Screens
Portrait Portrait 240x320240x320
LandscapeLandscape320x240320x240
Square Square 240x240240x240
Application ImpactApplication Impact
Fit content to the windowFit content to the window Change the contentChange the content Change layoutChange layout Design for squareDesign for square
Fit Content To WindowFit Content To Window
PortraitPortraitLandscapeLandscape
Change The ContentChange The Content Content may need to change when orientation Content may need to change when orientation
changeschanges
PortraitPortraitLandscapeLandscape
Change The LayoutChange The Layout
PortraitPortraitLandscapeLandscape
Design For Design For SquareSquare
PortraitPortrait
LandscapeLandscape
SquareSquare
What Happens?What Happens?
Pocket PC OS actions:Pocket PC OS actions: Call to ChangeDisplaySettingsEx() Call to ChangeDisplaySettingsEx()
occursoccurs The display driver and touch screen The display driver and touch screen
driver are notified of the orientation driver are notified of the orientation changechange
The shell is notified of the orientation The shell is notified of the orientation changechange
Supporting Orientation ChangeSupporting Orientation Change Full Screen applicationFull Screen application
Resize done by the shellResize done by the shell Respond to Resize event (WM_SIZE) and Respond to Resize event (WM_SIZE) and
resize child windowsresize child windows DialogsDialogs
Design new dialogs for square screenDesign new dialogs for square screen Consider using property pagesConsider using property pages Re-layout content Re-layout content Use Replacement controlsUse Replacement controls
MenusMenus Design for square screen Design for square screen Fit without scrolling in all orientationsFit without scrolling in all orientations
Future DeviceFuture Device OrientationsOrientations ResolutionsResolutions
Displays And LayoutDisplays And Layout
.NET Compact Framework 1.0 Service Pack 2 (.NET Compact Framework 1.0 Service Pack 2 (todaytoday)) Automatically provides scrolling Form contents for non-portrait Automatically provides scrolling Form contents for non-portrait
displaysdisplays Form.Resize eventForm.Resize event Automatically provides pixel doubling for high resolutionAutomatically provides pixel doubling for high resolution White paper on MSDN:White paper on MSDN:
Developing Screen Orientation-Aware ApplicationsDeveloping Screen Orientation-Aware Applications
Re-layout contentRe-layout content
Create layout Classes from DesignerCreate layout Classes from Designer Design Portrait -> capture Design Portrait -> capture
InitializeComponentInitializeComponent Design Landscape - > capture Design Landscape - > capture
InitializeComponentInitializeComponent
Handle orientation in methodsHandle orientation in methods Keep designer forms for future Keep designer forms for future
modificationmodification Full designer support in VS 2005Full designer support in VS 2005
Auto Scrollbars In DialogsAuto Scrollbars In Dialogs Existing apps (version <=4.20) Existing apps (version <=4.20)
automatic vertical scroll bar for Landscape and automatic vertical scroll bar for Landscape and SquareSquare
New apps (version >=4.21) New apps (version >=4.21) Call SHInitDialog() with Call SHInitDialog() with
SHIDIF_WANTSCROLLBARSHIDIF_WANTSCROLLBAR
80 pixels80 pixels
Layout TipsLayout Tips Re-layout is expensiveRe-layout is expensive
relayout only when the width changes relayout only when the width changes (not all WM_SIZE)(not all WM_SIZE)
Use DeferWindowPos for child windowsUse DeferWindowPos for child windows Off-screen controlsOff-screen controls
To the left or above the windowTo the left or above the window Hide them!Hide them!
Ensure select item is visibleEnsure select item is visible Scroll into view if necessaryScroll into view if necessary
Hardware buttons move!Hardware buttons move! May not lie where you expect May not lie where you expect
Update Your Install ScriptUpdate Your Install Script
Subsystem .EXE version <=4.20Subsystem .EXE version <=4.20
Update .INF file:Update .INF file:
[CEDevice][CEDevice]
BuildMax=0xE0000000 ; support for BuildMax=0xE0000000 ; support for square screens and screen rotationsquare screens and screen rotation
Resolution aware appsResolution aware apps What’s new?What’s new?
ExistingExisting NewNew
Pocket PCPocket PC 240 x 320 240 x 320
96 dots per inch96 dots per inch
480 x 640480 x 640
192 DPI192 DPI
SmartphoneSmartphone 172 x 240172 x 240
96 DPI96 DPI
240 x 320240 x 320
131 DPI131 DPI
NOTE: this is a DPI change, NOT a NOTE: this is a DPI change, NOT a screen size change!screen size change! Same physical sizeSame physical size Designed to enable high quality screensDesigned to enable high quality screens
GoalsGoals
Keep one app for both DPI settingsKeep one app for both DPI settings Support existing applicationsSupport existing applications
Provide DPI “emulation” for existing appsProvide DPI “emulation” for existing apps Best effort experienceBest effort experience Pocket PC onlyPocket PC only
Allow new applications to be DPI awareAllow new applications to be DPI aware Use hires graphicsUse hires graphics Better customer experienceBetter customer experience
What Is DPI Awareness?What Is DPI Awareness?
More detail per elementMore detail per element
NOT tiny textNOT tiny text
Migrating to HiDPIMigrating to HiDPI
Run your app on 96DPIRun your app on 96DPI Take a screen snapshotTake a screen snapshot
Run your app on 192DPIRun your app on 192DPI Take a screen snapshotTake a screen snapshot
Compare the output:Compare the output:
pWord, 96 DPIpWord, 96 DPI pWord, 192 DPIpWord, 192 DPI
Migrating to HiDPIMigrating to HiDPI Why so similar?Why so similar?
Legacy emulation layerLegacy emulation layer App believes it is running on 96 DPIApp believes it is running on 96 DPI Layer stretches app to screen pixelsLayer stretches app to screen pixels
Main Difference:Main Difference: Text looks sharper/betterText looks sharper/better
96 DPI 192 DPI96 DPI 192 DPI
So, Are We Done?So, Are We Done?
No – true Hi-DPI support means:No – true Hi-DPI support means: Better imagesBetter images Better performanceBetter performance
96 DPI96 DPI 192 DPI192 DPI
Disabling Emulation LayerDisabling Emulation Layer
Creating “manifest” resource:Creating “manifest” resource: Resource type: CEUX (custom data)Resource type: CEUX (custom data) Resource Name: “HI_RES_AWARE”Resource Name: “HI_RES_AWARE”
Quotes important (or will be defined as Quotes important (or will be defined as numeric)numeric)
Value: 01 00Value: 01 00 In .rc file:In .rc file:
HI_RES_AWARE CEUX HI_RES_AWARE CEUX BEGINBEGIN 0x0001 0x0001ENDEND
Now app will see the real DPINow app will see the real DPI
Looking For ProblemsLooking For Problems Compare screenshotsCompare screenshots
Obvious bugsObvious bugs Subtle bugsSubtle bugs
LoDPILoDPI
HiDPIHiDPI
.NET Compact Framework.NET Compact Framework
Emulation layer worksEmulation layer works No designer supportNo designer support Manifest resourceManifest resource
Res2exe –c –r hidpi.res MyApp.exeRes2exe –c –r hidpi.res MyApp.exe
SummarySummary
Visual Studio .NET 2003 is the development Visual Studio .NET 2003 is the development environmentenvironment
Add on a Pocket PC or Smartphone SDKAdd on a Pocket PC or Smartphone SDK .NET Compact Framework is in ROM! .NET Compact Framework is in ROM!
Get Tools & Resources:Get Tools & Resources:Windows Mobile Windows Mobile Developer PortalDeveloper Portal
More Support:More Support:Windows Mobile Windows Mobile Solution Partner Solution Partner ProgramProgram
Go To Market:Go To Market:Mobile2Market Mobile2Market andandCertificationCertificationTechnical Support:Technical Support:
Tools and SDKs with Tools and SDKs with emulatorsemulators
Technical articles and Technical articles and whitepaperswhitepapers
Marketing Support:Marketing Support: Monthly newslettersMonthly newsletters Case studiesCase studies
Technical Support:Technical Support: Exclusive expert columnsExclusive expert columns Early access to SDKsEarly access to SDKs Access to beta programsAccess to beta programs
Marketing Support:Marketing Support: PR supportPR support Ongoing promotionsOngoing promotions
for devicesfor devices
Technical Support:Technical Support: ““Designed for Windows Designed for Windows
Mobile” certification testingMobile” certification testing Free technical support Free technical support
incidentincident
Marketing Support:Marketing Support: ““Designed for Windows Designed for Windows
Mobile” logo on packaging & Mobile” logo on packaging & promotionspromotions
Increased promotion to Increased promotion to retailers and distribution retailers and distribution partnerspartners
Go to: Go to: http://www.microsoft.com/windowsmobile/developer
Windows Mobile Windows Mobile
Developer ResourcesDeveloper Resources
Questions?Questions?
© 2004 Microsoft Corporation. All rights reserved.© 2004 Microsoft Corporation. All rights reserved.