790 likes | 937 Views
Introduction to managed code development for Windows Mobile. Paul Foster paulfo@microsoft.com. Event agenda. 18.00 Registration 18:30 Introduction to managed code application development for Windows Mobile 19:30 Break / Refreshments 20:00 Session continued 20:50 Q&A 21:00 Close. Agenda.
E N D
Introduction to managed code development for Windows Mobile Paul Foster paulfo@microsoft.com
Event agenda 18.00 Registration 18:30 Introduction to managed code application development for Windows Mobile 19:30 Break / Refreshments 20:00 Session continued 20:50 Q&A 21:00 Close
Agenda • Smart Client design • Introduction to managed code • .Net Compact Framework – overview • Design and performance tips • Deployment • Windows Mobile 2003 2nd Edition • Orientation support • DPI support
Mobile Device Shipments 600 500 400 300 200 100 PC Shipments Unit Shipments (M) 2001 2002 2003 2004 2005 2006 2007 Source: Gartner Dataquest (Dec. 2003) For Mobile Applications: • $5.8 billion market for ISVs by 2006 (source: Forrester, 2002) • Customers demand more mobile applications(source: Handango, 2003) • Mobile Operators report monthly ARPU increases of 25% on Windows Mobile-based devices • 700 applications added to Mobile Application Catalog since launch of Mobile2Market program last year 58% want more Personal productivity apps58% want more Business and professional apps54% want more Games44% want more Utilities Momentum Continues To Build… For Mobile Devices: • Mobile device adoption continues to grow • Growing Pocket PC market share • Smartphones launching, 37+ leading OEMs and 50+ Mobile Operators partners • New form factors for landscape, high DPI
MoreDevice Choices 2000 2002 2003 2003Second Edition FutureWindows Mobile Core OS WinCE 3.0 WinCE 3.0 WinCE 4.2 WinCE 4.2 WinCE “Macallan” BetterDevelopment eVC 3 (C++)eVB 3 (VB) eVC 3 (C++)eVB 3 (VB) eVC 3 (C++)eVC 4 (C++) VS.NET 2003(C#, VB.NET) eVC 3 (C++)eVC 4 (C++) VS.NET 2003 (C#, VB.NET) VS “Whidbey”(C#, VB.NET, C++) MFC Win32, POOM MFC, ATL Active SyncConnection MgrMAPIOBEXTelephony ATL 4.2, .NET CFEnhanced Emulator Configuration Mgr,Bluetooth, SMS .NET CF SP2VGA (PPC)QVGA (SP)SquareLandscape .NET CF “Whidbey”MFC 8.0, ATL 8.0 Broad managed code support Notification broker, Location, Camera, Watson, D3DM, Richer Platform Capabilities Windows Mobile Roadmap
Smart Client design For .Net Compact Framework
The Mobile Device Universe Clients User Experiences & Solutions Web services Tools Authentication SMS Voice CallsSubscriber DB MMS Data CallsPersonalization Billing etc… Infrastructure Servers, e.g. Network Operators
Police Force case study • Business driver • Need to improve officer productivity • Goal • Improve productivity to eqv. 100 additional officers • Very public project • Council tax contribution to fund project • Results • PNC search results ~4 seconds back on device
The need for a Smart Client • Application supports key business activities • User needs to ‘fire and forget’ tasks • Device security requires code on the client
What is a Smart Client design? • Client installed app using local CPU • Works in both connect and disconnected network states • In-built application change management
Smart Client architecture • Why consciously factor code? • Increased abstraction • Decreased complexity • Increase reusability • How to factor code? • Move code (functions, classes, assemblies) • Change code visibility • Share or Split implementations
Specific Factoring Opportunities • The .NET Compact Framework has additional opportunities to gain value by factoring • Divide them into two key sub-groups: • Cross-tier factoring • Intra-tier (on-device) factoring
Multi-tier Factoring • How much can you put on a server? • How will you handle being unable to reach the server? • Duplication of sending (idempotence) • Mobile apps must be able to continue running while mobile • Client data stores: XML, SQLCE, flat files…
Cross-tier factoring Device application functionality Unreliable wireless connectivity Server application functionality
Intra-tier Factoring • Strict separation of UI and client-side logic (UI Processing code) • User interface code handles the specifics of the screen drawing • All logic associated with client validation, logic, rules, etc., should be considered UI Processing • Allows reuse of the maximum possible subset of code
Device Variety • .NET Compact Framework allows for unified API for many devices • The underlying form factors can be quite diverse, though. • This means input methods may be different • Consider factoring to allow for additional devices to be supported later.
N-tier application architecture Users Communication Operational Management Security UI Components UI Process Components Service Interfaces Business Workflows Business Components Business Entities Data Access Logic Components Service Agents Data Sources Services
Managed Managed Server side Server side Native Native ASP .NETMobile Controls ASP .NETMobile Controls MFC MFC ATL ATL .NET Compact Framework .NET Compact Framework Win32 Win32 Software Platform (APIs) Data Access Device Management Communication Presentation Multimedia Remote APIConfigurationBluetooth Security Connection ManagerTAPISMS MAPI POOM ActiveSync ADO CEXMLCE DBOLE DB Home ScreenUser Interface/ShellHTML Control GAPI Windows Mobile CE DBActiveSync Pocket OutlookPocket Internet ExplorerWindows Media Player Windows CE Device Hardware Radio ProcessorMemory GSM/GPRSCDMA/1xRTT WiFiBluetooth DisplayUSB or Serial Windows Mobile Development Platform:Today Visual Studio .NET Embedded VC++ Drivers
Managed Server side Native ASP .NETMobile Controls MFC ATL .NET Compact Framework Win32 Software Platform (APIs) Data Access Device Management Communication Presentation Multimedia Remote APIConfiguration*Bluetooth Statsor* Pocket Watson Connection ManagerTAPI*SMS*MAPI*POOM* SQL CEADO CEXMLCE DBOLE DB Home ScreenUser Interface/ShellHTML ControlDOM GAPICameraD3DMLocation* Windows Mobile CE DBActiveSync SQL CE Pocket OutlookPocket Internet ExplorerWindows Media Player Windows CE Device Hardware Radio ProcessorMemory GSM/GPRSCDMA/1xRTT WiFiBluetooth DisplayUSB or Serial This Session Will Focus On … Visual Studio “Whidbey” Drivers Orange = Added/Enhanced in Future Windows Mobile Platform* = Managed wrappers
.NET Compact Framework Today… • Service Pack 2 Improvements • Download it today from MSDN • Performance Gains over RTM • ~ 40% faster XML • ~ 20% faster ADO.NET • ForeColor and BackColor!!! • Keyboard Events • Support for Future Devices • Developer Adoption • Fourth most active .NET newsgroup • Developer Focused Web sites like • http://www.OpenNetCF.org • http://www.dotnetdn.com/ • http://www.pocketPCDN.com • http://msdn.microsoft.com/mobility/ • Information direct from product team members
.NET Compact Framework Today…Third Party Controls and Libraries • ComponentOne Studio for Mobile Devices • /n Software’s IP*Works for .NET Compact Framework • InstallShield Developer Mobile Edition • Odyssey CFCom • Preemptive Dotfuscator • And More!
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
The .NET Compact Framework System.Web System.Windows.Forms Services Design ComponentModel Description Discovery System.Drawing Protocols Drawing2D Security Text System.Data System.Xml ADO.NET SqlClient XmlDocument Reader/Writers SqlServerCe System Collections IO common languageruntime Security Net InteropServices Text Reflection Diagnostics Globalization Resources Threading
The .NET Common Language Runtime System.Web System.Windows.Forms Services Design ComponentModel Description Discovery System.Drawing Protocols Drawing2D Security Text System.Data System.Xml ADO.NET SqlClient XmlDocument SqlServerCe Reader/Writers System Collections IO common languageruntime • Core functionality for execution • No worries about initialized pointers! • Provides garbage collection services • Good performance through JIT compilation • Straightforward error handling with exceptions • Support for Win32 APIs through platform invocation • All these benefits, and you can pick your development favourite language too! Security Net InteropServices Text Reflection Diagnostics Remoting Serialization Globalization Resources Threading
Compiler Assembly Common Language Runtime DEVELOPMENT 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 code C# J# VB Cobol … MSIL Metadata Resources
DEVELOPMENT DEVELOPMENT 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()); } } GlobalAssemblyCache (GAC) 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()); } } Compiler Assembly Assembly Source code C# J# VB Cobol … MSIL Metadata Resources ApplicationDirectory Download Cache Install Common Language Runtime DEPLOYMENT Setup Copy Browser
DEVELOPMENT Assemblyon Target Machine GlobalAssemblyCache (GAC) Assembly Setup Copy Browser ApplicationDirectory Class Loader Security Assembly Loader IL to NativeCompiler Download Cache Garbage Collection Code Manager Exception Manager Native .exe + GC table Thread Support COM Interop Install Debug Engine Common Language Runtime DEPLOYMENT 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" EXECUTION
Networking SupportSystem.Net System.Web System.Windows.Forms Services Design ComponentModel Description Discovery System.Drawing Protocols Drawing2D Security Text System.Data System.Xml ADO.NET SqlClient XmlDocument SqlServerCe Reader/Writers System • Sockets • Provides synchronous and asynchronous • Multiple protocols • Streams • Built on top of sockets • Synchronous and asynchronous • HTTP request and response • Use stream model • Requires no user knowledge of HTTP Collections IO common languageruntime Security Net InteropServices Text Reflection Diagnostics Remoting Serialization Globalization Resources Threading
System.Web System.Windows.Forms Web Service SupportSystem.Web Services Design ComponentModel Description Discovery System.Drawing Protocols Drawing2D Security Text System.Data System.Xml ADO.NET SqlClient XmlDocument SqlServerCe Reader/Writers System Collections IO common languageruntime • Calling Web services • All encoding types • Synchronous and asynchronous invocation • Basic and Digest authentication • Secure Sockets Layer support for encryption (SSL) • Custom SOAP headers • Read more about it! • Consuming XML Web Services with the Microsoft .NET Compact Framework http://msdn.microsoft.com/mobility/understanding/articles/default.aspx?pull=/library/en-us/dnnetcomp/html/netcfwebservices.asp Security Net InteropServices Text Reflection Diagnostics Remoting Serialization Globalization Resources Threading
System.Web System.Windows.Forms Data SupportSystem.Data Services Design ComponentModel Description Discovery System.Drawing Protocols Drawing2D Security Text System.Data System.Xml ADO.NET SqlClient XmlDocument SqlServerCe Reader/Writers System Collections IO common languageruntime • Handling data offline with DataSet • Common data model from server to PC to device • Extensible ADO.NET provider model • SQL Server (System.Data.SqlClient) • SQL Server CE (System.Data.SqlServerCe) • Managed access to rich, robust device database • Efficient, complex querying • Enables online/offline applications • Data synchronization to SQL Server with server and client tracking Security Net InteropServices Text Reflection Diagnostics Remoting Serialization Globalization Resources Threading
DataBest Practices • If data is local…instead of DataSet… • Leverage SQL Server CE native in-proc database • Query data using DataReader • Use TableDirect command type for fast index searches • Equivalent to “SELECT * FROM foo WHERE bar > 3” • Limit open SqlCeCommand/DataReaders • Dispose when complete • If data is remote… • Use SQL Server CE replication • When using Web Services • Use DiffGrams to read and write DataSets to limit data transfer • Save data locally in SQL Server CE for faster access and storage • Don’t save remote DataSets as XML to device • If you do, save Schema as well
XMLBest Practices for Managing Large XML Data Files • Use XmlTextReader and XmlTextWriter • Smaller memory footprint than using XmlDocument • XmlTextReader is a pull model parser which only reads a “window” of the data • Design XML schema first, then code • Understand the structure of your XML document • Use elements to group • Allows use of Skip() in XmlTextReader • Use attributes to reduce size
XMLBest Practices for Serialization • Use XmlTextReader and XmlTextWriter • XmlDocument builds a generic, untyped object model using a tree • Type stored as string • Use XmlConvert to convert each element to appropriate managed type for efficiency • e.g. Int32 • Design XML schema first, then code • Use elements for objects and arrays • Use attributes for simple properties and fields
XML And Data.NET Compact Framework 2.0 Performance • Vastly improved XmlTextReader (SP2) and XmlTextWriter • XmlSerializer • Improved ADO.NET performance with SQL Server CE 3.0 • SqlCeResultSet • Direct access to scrollable, updatable cursor
System.Web System.Windows.Forms User Interface Design Services Design ComponentModel Description Discovery System.Drawing Protocols Drawing2D Security Text System.Data System.Xml ADO.NET SqlClient XmlDocument SqlServerCe Reader/Writers System Collections IO common languageruntime • Wide range of controls • Supported controls are tailored to each device • Rich designer support in Visual Studio .NET • Some desktop functionality isn’t supported • ActiveX Controls • Printing • Drag and Drop • GDI+ (transparency) Security Net InteropServices Text Reflection Diagnostics Remoting Serialization Globalization Resources Threading
Button CheckBox ComboBox ContextMenu DataGrid DomainUpDown FileOpenDialog Supported ControlsSystem.Windows.Forms • Supported controls FileSaveDialog HScrollBar ImageList Input Panel Label ListBox ListView MainMenu NumericUpDown Panel PictureBox ProgressBar RadioButton StatusBar TabControl TextBox Timer ToolBar Track Bar TreeView VScrollBar • Unavailable controls ToolTip Splitter FontDialog HelpProvider LinkLabel NotifyIcon CheckedListBox ColorDialog ErrorProvider
Control ExtensibilitySystem.Windows.Forms • Add functionality to existing controls • Create a text box that only supports numeric text entry • Add additional properties specific to your application • Create your own new controls • Many 3rd party examples, such as a signature capture control • Article with source code: • Microsoft® .NET Compact Framework-based DateTimePicker Control http://msdn.microsoft.com/mobility/understanding/articles/default.aspx?pull=/library/en-us/dnnetcomp/html/netcfdatetimepicker.asp
Windows FormsBest Practices • Load and cache Forms in the background • Populate data separate from Form.Show() • Pre-populate data, or • Load data async to Form.Show() • Parent controls top-down • e.g. Form panels controls • Use BeginUpdate/EndUpdate when it is available • e.g. ListView, TreeView • Use SuspendLayout/ResumeLayout when repositioning controls • Keep event handling code tight • Process bigger operations asynchronously • Blocking in event handlers will affect UI responsiveness
Form Management • The Form Flow Challenge • No Multiple Document Interface • Multi form input more common • Which form to display next? • Hide or destroy current form? • Solutions • Dynamic form construction • Forms manager • Wizard based input (e.g. tight scripting of forms)
Form Management Main Form Collect Form Inspect Form Truck Form Form Manager Application Kernel Main Web Service Interface Local Store (SQL CE )
Identifying The Top PitfallsThe most common problems • Putting synchronous code in Form_Load • Putting too much code in Form_Load • Assuming connectivity (implicitly) • Mixing user interface code and processing • Architecting based on incomplete or non-representative tests • Accepting default timeouts • Misapplying UI metaphors (desktop to mobile)
Web Services for Connected Scenarios SQL CE RDA for async reliable messaging Metadata Driven UI Dynamic WinForms Metadata Driven Biz Logic Metadata Driven Wire Formats Dataset to message transforms are metadata driven C# Code for Offline Business Logic Metadata driven Data Access Metadata and Data Sync Metadata changes are downloaded on the fly SQL CE schemas are altered on the fly Data is downloaded without replication using Standard XML messages Datasets and Data Readers Wrapped with our Metadata APIs Dynamic Offline Store SQL CE Store CRM Mobile Architecture
Interoperability • Platform Invocation (P/Invoke) • Allows users to call custom native code and Windows APIs • Declare statement in Visual Basic • DLLImport Attribute in C# • Callbacks • No support for direct native to managed function calls • Use MessageWindow • Part of Microsoft.WindowsCE.Forms • COM Interoperability • Not directly supported in this version • Need to create native wrapper • Partner solutions available (Odyssey Software)
InteroperabilityGet More Information! • Articles • An Introduction to P/Invoke and Marshaling on the Microsoft .NET Compact Frameworkhttp://msdn.microsoft.com/mobility/understanding/articles/default.aspx?pull=/library/en-us/dnnetcomp/html/netcfintrointerp.asp • Advanced P/Invoke on the Microsoft .NET Compact Frameworkhttp://msdn.microsoft.com/mobility/understanding/articles/default.aspx?pull=/library/en-us/dnnetcomp/html/netcfadvinterop.asp
Performance PrinciplesIn general… • Less code is faster code • Fewer objects are better for performance • Recycle and re-use expensive resources • Batch work where possible • Initialize lazily • Do work in the background to affect “perceived” performance • Use threads and async calls • Understand what the APIs are doing
Application deployment A mobile Smart Client example
Application Deployment • Visual Studio .NET provides auto-generation of simple CAB files for ActiveSync • Include application and dependant references • Does not include the runtime • Does not include other products that the app requires (e.g. SQL Server CE) • Temporary files are kept if user wants to customize the cab file contents
Self-updating applications • Application event triggers update enquiry • Updater applet calls web service with version and platform data • Web service indicates new version and location • Updater asynchronously acquires cab • Updater executes cab causing install • New application version installed
Self-updating architecture Web Service XML Spec Application V1.0 Updater CAB CAB CAB executed CAB CAB \downloads Async download CAB Application V1.1 New version CAB CAB http://msdn.microsoft.com/library/default.asp Creating Self-Updating Applications With the .NET Compact Framework By Alex FeinmanOpenNETCF.org