Device Development with Visual Studio Device Development with Visual Studio 2005 and Future Windows Mobile 2005 and Future Windows Mobile PlatformPlatformPer AhlbergDeveloper EvangelistMicrosoft AB
AgendaAgenda Introduction .NET Compact Framework 2.0 Visual Studio for Devices Future Windows Mobile Platform
Richer Platform Capabilities
.NET CF 2.0MFC 8.0, ATL 8.0Broad managed code support Notifications Broker, Location, Camera, Watson, D3DM
.NET CF SP2
VGA (PPC)QVGA (SP)SquareLandscape
ATL 4.2, .NET CF Enhanced Emulator Configuration Mgr,Bluetooth, SMS
MFC, ATL
Active SyncConnection MgrMAPIOBEXTelephony
MFC
Win32, POOM
BetterDevelopment
Visual Studio 2005(C#, VB.NET, C++)
eVC 3 (C++)eVC 4 (C++)VS.NET 2003 (C#, VB.NET)
eVC 3 (C++)eVC 4 (C++)VS.NET 2003(C#, VB.NET)
eVC 3 (C++)eVB 3 (VB)
eVC 3 (C++)eVB 3 (VB)
Core OS WinCE 5.0WinCE 4.2WinCE 4.2WinCE 3.0 WinCE 3.0
MoreDevice Choices
FutureWindows Mobile
Platform2003Second Edition
200320022000
IntroductionIntroductionWindows Mobile RoadmapWindows Mobile Roadmap
DisplayDisplayUSB or SerialUSB or Serial
ProcessorProcessorMemoryMemory
GSM/GPRSGSM/GPRSCDMA/1xRTTCDMA/1xRTT
Device Device HardwareHardware
WiFiWiFiBluetoothBluetooth
RadioRadioDriversDrivers
Windows MobileWindows Mobile CE DBCE DBActiveSyncActiveSyncSQL MobileSQL Mobile
Pocket OutlookPocket OutlookPocket Internet ExplorerPocket Internet ExplorerWindows Media PlayerWindows Media Player
WindowsWindows CECE
NativeNative
Win32Win32
MFCMFC ATLATLManagedManaged
.NET Compact.NET CompactFramework 2.0Framework 2.0
Server sideServer sideASP .NETASP .NET
Mobile ControlsMobile Controls
** = Managed wrappers = Managed wrappers
Visual Studio 2005Visual Studio 2005
Home ScreenHome ScreenUser Interface/ShellUser Interface/ShellHTML ControlHTML ControlDOMDOM
GAPIGAPICameraCameraD3DMD3DM
Remote APIRemote APIConfiguration*Configuration*BluetoothBluetoothNot. BrokerNot. BrokerPocket WatsonPocket Watson
Connection ManagerConnection Manager TAPI*TAPI*SMS* SMS* MAPI* MAPI* POOM*POOM*
MultimediaMultimediaCommunicatioCommunicationn
Device ManagementDevice Management PresentationPresentationSQL MobileSQL MobileADO CEADO CEXMLXMLCE DBCE DBOLE DBOLE DB
Data AccessData Access
Software Platform (APIs)Software Platform (APIs)
IntroductionIntroductionWindows Mobile PlatformWindows Mobile PlatformIntroductionIntroduction.NET Compact Framework 2.0.NET Compact Framework 2.0IntroductionIntroductionCore Platform APIsCore Platform APIs
IntroductionIntroductionManaged Code on WM PlatformManaged Code on WM Platform .NET Compact Framework 2.0
A subset of the full .NET Framework 2.0 Ships as part of Visual Studio 2005 Will be in ROM on future devices
Future Windows Mobile platform Managed interfaces for specific operating
system features Distributed via a forthcoming SDK
AgendaAgenda Introduction .NET Compact Framework 2.0 Visual Studio for Devices Future Windows Mobile Platform
.NET CF 2.0.NET CF 2.0Compatibility and PerformanceCompatibility and Performance Compatible with full .NET Framework
Interoperability, protocols Compatible with .NET CF 1.0
Side-by-side execution Application compatibility
Enhanced performance Unified JIT Improved string handling XML improvements Improved ADO.NET with SQL Mobile
.NET CF 1.0.NET CF 1.0
.NET CF .NET CF 2.02.0
.NET Compact Framework 2.0.NET Compact Framework 2.0Displays and LayoutDisplays and Layout Orientation support
Docking and anchoring AutoScroll property – forms, panels SuspendLayout and ResumeLayout ChangeOrientation – portrait or
landscape Resolution support
Automatic scaling Graphics
DpiX DpiY
.NET Compact Framework 2.0.NET Compact Framework 2.0New Windows Forms ControlsNew Windows Forms Controls DateTimePicker MonthCalendar DocumentList LinkLabel Notification Help WebBrowser
Clipboard support Additional properties, methods
and events Control.DoubleClick ToolBarButton tooltips More Treeview events
Keyboard support Form.KeyPreview TabIndex, TabStop
.NET Compact Framework 2.0 .NET Compact Framework 2.0 Windows Forms FeaturesWindows Forms Features
HPHP43004300
IntegrateIntegrated d
keyboarkeyboardsds
.NET Compact Framework 2.0 .NET Compact Framework 2.0 System.Drawing NamespaceSystem.Drawing Namespace Bitmaps
Bitmap.LockBits(…) Image.Save(…)
png, jpg, bmp, tif, gif Bitmap pattern brushes Create font from
LOGFONT structure Custom pens
Rotated text Rotated text using LOGFONT using LOGFONT
.NET Compact Framework 2.0 .NET Compact Framework 2.0 Smartphone SupportSmartphone Support Data access
SQL Mobile DataGridView
Textbox IME switching InputModeEditor
Enable multiple menu items on left softkey
.NET Compact Framework 2.0 .NET Compact Framework 2.0 System.Xml NamespaceSystem.Xml Namespace Improved performance Schema validation support
No DTD Support Static creation methods for
XmlTextReader and XmlTextWriter XML processing through XPath XmlSerialization
.NET Compact Framework 2.0 .NET Compact Framework 2.0 System.Messaging NamespaceSystem.Messaging Namespace Support for message queuing
Send and receive messages Inter-application communication without a
live connection Communication using unreliable connections Administer, connect, and monitor network
message queues
.NET Compact Framework 2.0 .NET Compact Framework 2.0 Language and Runtime SupportLanguage and Runtime Support Enhanced VB.NET features
"My" namespace support Enhanced C# features
Iterators Anonymous methods
Cross language features Generics Partial classes
AgendaAgenda Introduction .NET Compact Framework 2.0 Visual Studio for Devices Future Windows Mobile Platform
Visual Studio 2005 for DevicesVisual Studio 2005 for DevicesVisual Studio 2005Visual Studio 2005 Enhanced project wizard
Target Pocket PC or Smartphone Enhanced designers Emulator support
Based on ARM processor Save multiple states
CAB and Setup projects Integrated device and emulator
debugging Remote tools
Process viewer, file viewer, heap walker, and more…
Visual Studio 2005 for DevicesVisual Studio 2005 for DevicesEmulatorsEmulators Build and test applications without a
device Requires a network connection or loopback
adapter Smart device applications use a variety of
Windows Mobile based emulators Visual Studio 2005 automates debugging
and deployment
Visual Studio 2005 for DevicesVisual Studio 2005 for DevicesNative Language SupportNative Language Support First-class native C++ support
MFC 8.0 ATL 8.0
One IDE for developing both Managed and Native components of an application Debug mixed Native/Managed application at
the same time
AgendaAgenda Introduction .NET Compact Framework 2.0 Visual Studio for Devices Future Windows Mobile Platform
Future Windows Mobile PlatformFuture Windows Mobile PlatformKey FeaturesKey Features Enhanced services and device support
Messaging – SMS, POOM, and telephony Notifications – signal, battery, connections Location and Camera APIs
Peripherals support Microdrives, cameras, keyboards, secondary
displays Not part of the core .NET CF 2.0 APIs embedded in operating system Accessed through forthcoming SDK
Future Windows Mobile Platform Future Windows Mobile Platform Managed APIsManaged APIs Pocket Outlook Object Model (POOM)
Managed access to PIM objects Contacts, tasks, appointments
MAPI and SMS Sending and receiving email and SMS Receiving SMS is a filter based system
Telephony Make phone calls Display call log
Pocket OutlookPocket OutlookListing AppointmentsListing Appointments
using Microsoft.WindowsMobile.PocketOutlook
private void ListAppointments(){
myItemStore = new ItemStore();
private System.Windows.Forms.ListBox AppointmentListBox;
AppointmentListBox.DataSource = myItemStore.Appointments.Items;
AppointmentListBox.DisplayMember = "Subject";}
private void button1_Click( object sender, System.EventArgs e){ SmsMessage sms = new SmsMessage(); sms.To.Add(new Recipient(sendTo.Text)); sms.Body = msg.Text; sms.Send();}
SMS MessagingSMS MessagingSending a MessageSending a Message Easier than before Similar to Winsock API Just create SMS object and send
TelephonyTelephonyManaged Access to Phone FunctionalityManaged Access to Phone Functionality Does not replace or map directly to TAPI or
exTAPI Instead, provides a managed interface to
crucial, commonly used telephony services Make phone calls
Easily implement a phone dialer UI Access the call log
Display missed, incoming and outgoing calls
SummarySummary The .NET Compact Framework 2.0
represents significant gains in performance and compatibility
Visual Studio 2005 tools and managed APIs offer a simplified development model
Support for next generation hardware will have you building state-of-the-art mobile applications
Data Access with SQL Server 2005 Data Access with SQL Server 2005 Mobile Edition and the .NET Compact Mobile Edition and the .NET Compact Framework v2.0Framework v2.0
AgendaAgenda
Overview SQL Server 2005 Integration Visual Studio 2005 Integration Merge Replication
OverviewOverviewDeviceDevice DataData AccessAccess
Native Stack Managed Stack
SQL Server Mobile Edition
CLR / .NET CFCLR / .NET CF
SQL Server CE SQL Server CE Data ProviderData Provider
ADO.NETADO.NET
VB .NET / C#VB .NET / C#VS 2005 C++VS 2005 C++
OLEDB CEOLEDB CE
OLEDB OLEDB ProviderProvider
QP / Cursor Engine / ESQP / Cursor Engine / ES
Storage Engine / Replication TrackingStorage Engine / Replication Tracking
OverviewOverviewHighlyHighly IntegratedIntegrated intointo DevelopmentDevelopment ToolsTools
Integration with SQL Server 2005 DTS Support Show Plan and Hints SQL Server Management Studio
Integration with Visual Studio 2005 Ships with Visual Studio 2005 Database management functionality Easy code upgrades from SQL Server CE 2.0
OverviewOverviewArchitecture ImprovementsArchitecture Improvements Storage engine
Multiconnection support Row level locking of data Shares common memory pool Auto-shrink support
Improved query processor Cost-based optimization Show plan and query hints Scrollable, updatable cursor – SqlCeResultSet
OverviewOverviewSynchronization ImprovementsSynchronization Improvements Improved synchronization control
Multiuser synchronization Progress notifications Multiple subscriptions in the same database
Synchronization performance (w/SQL 2005) Partitioned groups Download-only tables
OverviewOverviewIntroducing the SqlCeResultSetIntroducing the SqlCeResultSet Development Features
Included in SQL Mobile, ships with: Visual Studio 2005 SQL Server 2005
Takes full advantage of SQL Server 2005 Mobile Edition local capabilities
Extended Features Scrolling access Update in place Random access
SQL Server 2005 IntegrationSQL Server 2005 IntegrationSQL Server 2005 ToolsSQL Server 2005 Tools
Business Intelligence Development Studio Visual Tools for creating Data Transformation Data Visualization Enhanced Debugging
SQL Server 2005 IntegrationSQL Server 2005 IntegrationSQL Server 2005 ToolsSQL Server 2005 Tools
SQL Server Management Studio Create SQL Mobile Databases Show Plan and Hints Faster Optimization Enhanced Publication Subscription Wizard
Visual Studio 2005 IntegrationVisual Studio 2005 IntegrationVisual Studio ToolsVisual Studio Tools
Library Evolution SqlCeEngine,
SqlCeConnection, SqlCeCommand, SqlCeDataReader
SqlCeResultSet (new updatable scrollable cursor)
SynchronizationSynchronizationGoals of SynchronizationGoals of Synchronization Simplify development of synchronization logic
Sync becomes a single line of code Conflict resolution happens on the server through SQL
Server model Share a common data source
Allow multiuser access to the same data source Improve performance and data concurrency
More end-user versatility Allows end users to change devices and still access the
data source
OLE D
B
SQL Mobile Client SQL Mobile Client AgentAgent
SynchronizationSynchronizationOverallOverall ArchitectureArchitecture
HTTP OLE DB
ApplicationApplication
SQL Mobile Engine
DatabaseDatabaseSQL ServerSQL ServerDatabaseDatabase
SQL Server SQL Server OLE DBOLE DBProviderProvider
SQL Mobile ServerSQL Mobile ServerAgentAgent
Internet Information Internet Information Services (IIS)Services (IIS)
SynchronizationSynchronizationOutliningOutlining YourYour OptionsOptions SQL Server Mobile Edition provides two
synchronization solutions Remote data access Merge replication
Both require server components that are on IIS.
Remote Data Access Remote Data Access OverviewOverview Loosely coupled connectivity between SQL Server
Mobile Edition and SQL Server Talks to SQL Server without being “connected” Stores SQL Server query results directly in SQL Server
2005 Mobile Edition Optionally tracks changes locally
Sends locally changed records back to SQL Server The .NET Compact Framework provides managed
wrapper SqlCeRemoteDataAccess
Remote Data AccessRemote Data AccessUsingUsing SqlCeRemoteDataAccessSqlCeRemoteDataAccess Each program must specify RDA
connectivity Local database information (SQL Mobile Edition
OLE DB connection string) Web server information
URL – must include sqlcesa30.dll Login and password
Proxy server login and password information Remote DB info sent with each command
(SQL Connection String)
Remote Data AccessRemote Data AccessPullPull OperationOperation Local table created including data and
schema Optionally includes primary key Optionally includes indexes
Values may come from a table or stored procedure
Can retrieve all data to be more robust Can filter data to reduce data size Tracking of tables must be turned off View/stored procedure can reference only one table with a primary key
Remote Data AccessRemote Data AccessPullPull OperationOperation Optionally track local changes
Changes can be later applied Uses optimistic concurrency (no server data
locked) Local table must not exist before pull
Created during pull operation Error thrown if table exists
Remote Data AccessRemote Data AccessUsingUsing RDARDA PullPull
Public Sub RDAPull() Dim rda as New SqlCeRemoteDataAccess Dim ServerOledbStr as String = “Provider=sqloledb; Data Source=dataserver;” _ “Initial Catalog=Pubs;User Id=sa;Password=;”
rda.LocalConnectionString = ”Provider=Data Source=\My Documents\test.sdf” ‘ Set URL and IIS login/password.
rda.Pull( “Authors”, _ “Select * from authors where state = ‘CA’”, _ ServerOledbStr, _ RdaTrackOption.TrackingOn)End Sub
Remote Data AccessRemote Data AccessPushPush OperationOperation Sends changes back to server
All changes since last pull or push are applied Changes applied to server indiscriminately
Table tracking must have been “on” during pull
Exception thrown if any portion of update fails Changes are rolled back
Remote Data AccessRemote Data AccessUsingUsing RDARDA PushPush
Public Sub RDAPush()Public Sub RDAPush() Dim rda = New SqlCeRemoteDataAccess()Dim rda = New SqlCeRemoteDataAccess()
Dim ServerOledbStr as String = Dim ServerOledbStr as String = “ “Provider=sqloledb; Data Source=dataserver;” _Provider=sqloledb; Data Source=dataserver;” _ “ “Initial Catalog=Pubs;User Id=sa;Password=;”Initial Catalog=Pubs;User Id=sa;Password=;”
rda.LocalConnectionString = _rda.LocalConnectionString = _””Data Source=\My Documents\test.sdf”Data Source=\My Documents\test.sdf”
‘ Set URL and IIS login/password. rda.Push(rda.Push( “ “Authors”,Authors”, ServerOledbStr,ServerOledbStr, RdaBatchOption.BatchingOn)RdaBatchOption.BatchingOn)End SubEnd Sub
Merge ReplicationMerge ReplicationOverviewOverview Provides data synchronization between
SQL Server 2005 Mobile Edition and SQL Server SQL Server is the publisher SQL Server 2005 Mobile Edition is the
subscriber SQL Server 2005 Mobile Edition receives
initial snapshot from SQL Server Both SQL Server 2005 Mobile Edition and
SQL Server can modify the data Conflict resolution can be customized
Merge ReplicationMerge ReplicationOverviewOverview Changes reconciled on next
synchronization Local SQL Server 2005 Mobile Edition changes
sent to SQL Server SQL Server changes sent to SQL Server 2005
Mobile Edition SQL Server Management Studio wizards
Publishers created in studio Subscribers create in studio
.NET Compact Framework managed wrapper SqlCeReplication
Merge ReplicationMerge ReplicationExaminingExamining thethe CodeCode
Public Sub SyncSubscription()Public Sub SyncSubscription() Dim repl as New SqlCeReplication()Dim repl as New SqlCeReplication() repl.InternetUrl = repl.InternetUrl = "http://Server1/SQLServerCE/sqlcesa30.dll""http://Server1/SQLServerCE/sqlcesa30.dll" repl.Publisher = “SERVER1"repl.Publisher = “SERVER1" repl.PublisherDatabase = "RDA_DeNormalize"repl.PublisherDatabase = "RDA_DeNormalize" repl.PublisherLogin = "sa"repl.PublisherLogin = "sa" repl.PublisherPassword = ""repl.PublisherPassword = "" repl.Publication = "RDA_DeNormalize_CustomerInfo"repl.Publication = "RDA_DeNormalize_CustomerInfo" repl.SubscriberConnectionString = _repl.SubscriberConnectionString = _
””Data Source=\My Documents\MyLocalDB.sdf“Data Source=\My Documents\MyLocalDB.sdf“
repl.Subscriber = “User1"repl.Subscriber = “User1" repl.AddSubscription(AddOption.CreateDatabase)repl.AddSubscription(AddOption.CreateDatabase) repl.Synchronize()repl.Synchronize()End SubEnd Sub
Merge ReplicationMerge ReplicationWeighingWeighing thethe CostsCosts Several triggers and stored procedures added
Added to system tables Adds more overhead
Replicated tables must have a ROWGUIDCOL Ensures that rows are unique Can avoid if rowguid column is added prior
Database must track all modifications Additional tables added to system database Tables used to track modifications Can grow significantly
Merge ReplicationMerge ReplicationMinimizingMinimizing thethe CostsCosts forfor DeviceDevice ApplicationsApplications
Key to success for device apps is minimizing communication Take only what you need Apply filters
Reduce the amount of data sent between devices and server Reduces time Improves responsiveness
Making The Replication ChoiceMaking The Replication ChoiceRecommendationsRecommendations Remote Data Access
Greater scalability on server Choose merge replication
Greater optimization over the wire Bi-direction synchronization
For more on making the choice http://msdn.microsoft.com/library/en-us/dnppcgen/html/
eff_arch_sql_servr_ce_rep.asp
SummarySummary
SQL Server 2005 Mobile Edition functionality is greatly enhanced for developers
Integration with SQL Server 2005 makes generation and maintenance of SQL Mobile databases better
Integration with Visual Studio 2005 makes developing of SQL Mobile applications easier and faster
Remote data access vs. merge replication
.NET Compact Framework Performance .NET Compact Framework Performance and Best Practicesand Best Practices
AgendaAgenda General Principles Performance in the .NET Compact
Framework Common Language Runtime Base Class Library Framework
Summary
General PrinciplesGeneral PrinciplesGolden Rules of PerformanceGolden Rules of Performance
Make performance a functional requirement Set performance goals as early as possible Revise performance goals at each milestone Design, code and test for performance
throughout application development life-cycle
General PrinciplesGeneral PrinciplesIn general…In 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
AgendaAgenda General Principles Performance in the .NET Compact
Framework Common Language Runtime Base Class Library Framework
Summary
Common Language RuntimeCommon Language RuntimeExecution EngineExecution Engine
JIT compilers Two JIT compiler architectures today
Emulator and ARM device performance experience may be different
Optimizations (ARM) Method inlining for simple methods
Optimizations are unavailable while debugging from Microsoft Visual Studio®
Some optimizations are unavailable when assemblies are compiled as ‘debug’
Call path Properties are calls Virtual calls are more expensive Platform Invokes are more expensive
Floating Point Pocket PC and Smartphone platforms don’t have FPUs
Common Language RuntimeCommon Language RuntimeGarbage CollectorGarbage Collector
What triggers a GC? Memory allocation failure 750KB of GC objects allocated Application going to background GC.Collect()
Avoid “helping” the GC, don’t call GC.Collect() What happens at GC time?
Freezes all threads at safe point Finds all live objects and marks them
An object is live if it is reachable from root location Unmarked objects are freed and added to finalizer queue
Finalizers are run on a separate thread GC pools are compacted if required Return free memory to the system heap
In general, if you don’t allocate objects, GC won’t occur Beware of side-effects of calls that may allocate objects
Common Language RuntimeCommon Language RuntimeFinalization and DisposeFinalization and Dispose
Cost of finalizers Non-deterministic cleanup Extends lifetime of object
In general, rely on GC for automatic memory cleanup The exceptions to the rule…
If your object contains an unmanaged resource that the GC is unaware of, you need to implement a finalizer Also implement Dispose pattern to release unmanaged resource in deterministic manner Dispose method should suppress finalization
If the object you are using implements Dispose, call it when you are done with the object Assumes an unmanaged resource in the object chain
Common Language RuntimeCommon Language RuntimeValue TypesValue Types
Value types allocated on the stack .NET Framework primitive types are value
types (for optimal performance) Keep value types small and simple Useful for items like Point (x,y coords) Avoid frequent boxing and unboxing
Boxing causes a heap allocation and a copy Can negate performance gains
Override Equals and GetHashCode Prevents boxing Correctness
Common Language RuntimeCommon Language RuntimeExceptionsExceptions
Exceptions are cheap…until you throw Throw exceptions in exceptional
circumstances Do not use exceptions for normal flow
control Use performance counters to track the
number of exceptions thrown Replace “On Error/Goto” with
“Try/Catch/Finally” in Microsoft Visual Basic® .NET
Common Language RuntimeCommon Language RuntimeReflectionReflection
Reflection can be expensive Reflection performance cost
Type comparisons (for example: typeof() ) Member enumerations
(for example: Type.GetFields() ) Member access
(for example: Type.InvokeMember() ) Should be avoided for performance sensitive
code paths Be aware of APIs that use reflection as a side
effect (for example: Object.ToString() ) Avoid using Type.InvokeMember()
Common Language RuntimeCommon Language Runtime.NET Compact Framework 2.0 Performance.NET Compact Framework 2.0 Performance
Substantial improvements in CLR JIT Compiler
All platforms have same optimized JIT Better code generation
More inlining Enregistration
Improved call path Improved p/invoke
Beware of cost of marshaling complex types Improved virtual method dispatch
Garbage Collector Less overhead per object Faster allocator
Improved heap management (reduce heap fragmentation)
Common Language RuntimeCommon Language Runtime.NET Compact Framework 2.0 Performance.NET Compact Framework 2.0 Performance
(Pocket PC 2003, XScale 400MHz)
1.0 1.0 SP2
2.0
Method Calls(Calls/sec)
3.7M 7.1M
Virtual Calls(Calls/sec)
2.4M 2.7M
Simple P/Invoke(Calls/sec)
733K 1.7M
Primes (to 1500)(iterations/sec)
562 832
GC Small (8 bytes)(Bytes/sec)
1M 7M
GC Array (100 int’s)(Bytes/sec)
25M 43M
XML Text Reader 200KB (seconds)
1.7 1.2 0.72
DataSet (static data) 4 tables, 1000 records (seconds)
13.1 6.6 7.3
DataSet (ReadXml) 3 tables, 100 records (seconds)
12.3 6.5 5.2
Bigger #is better
Smaller #is better
AgendaAgenda General Principles .NET Compact Framework Overview Performance in the .NET Compact
Framework Common Language Runtime Base Class Library Framework
Summary
Base Class LibraryBase Class LibraryArrays and CollectionsArrays and Collections
Use strongly typed arrays where possible Use jagged (foo[][]), instead of
multidimensional arrays (foo[,]) Jagged arrays give better performance
Pre-size collection classes appropriately Resizing creates unnecessary copies
Base Class LibraryBase Class LibraryStringsStrings
Use StringBuilder class for complex string concatenation and manipulation Strings are immutable String.Concat() causes unnecessary copies Perf Blog
http://weblogs.asp.net/ricom/archive/2003/12/02/40778.aspx Do not use foreach() to enumerate
characters in strings:foreach(char c in str){ //use c }
Use array index:for(int i=0;i < str.Length;i++){//use str[i]}
AgendaAgenda General Principles .NET Compact Framework Overview Performance in the .NET Compact
Framework Common Language Runtime Base Class Library Framework
Summary
Windows FormsWindows FormsBest PracticesBest 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
XMLXMLBest Practices for Managing Large XML Data FilesBest 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
XMLXMLBest Practices for SerializationBest 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
DataDataBest PracticesBest 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
XML and DataXML and Data.NET Compact Framework 2.0 Performance.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
AgendaAgenda General Principles .NET Compact Framework Overview Performance in the .NET Compact
Framework Common Language Runtime Base Class Library Framework
Summary
SummarySummary Make performance a
requirement Understand the APIs Less code is faster code
.NET Compact Framework Tips & Tricks.NET Compact Framework Tips & Tricks
AgendaAgenda Coding Tips & Tricks Testing/Deploying Tips & Tricks Other Tips & Tricks
Test Your Internet ConnectionTest Your Internet Connection
ISSUE: Windows Mobile device applications are often
created with “occasionally-connected” computing in mind. You need to test to see if a Windows Mobile device is connected to the Internet before attempting communication.
SOLUTION: Create a simple method to attempt to
connect using WebRequest and WebResponse.
Replacing Smart Minimize Button with Close Replacing Smart Minimize Button with Close ButtonButton ISSUE:
The default behavior of forms in the .NET Compact Framework is to display the “X” symbol and “Smart Minimize”. You would like your application to close completely.
SOLUTION: The MinimizeBox property of a Form can be
set to False at either design- or run-time, changing the button to “OK” and closing the application when tapped.
Call a Function in a Native DLL From the Call a Function in a Native DLL From the Compact FrameworkCompact Framework ISSUE:
Lower-level functionalities are often not directly exposed directly through classes of the .NET Compact Framework. These functionalities may be desired or needed, however.
SOLUTION: Using Process Invocation (“P/Invoke”)
techniques will expose the functionalities for use in C# or VB.NET.
Determine the Root Directory of an Determine the Root Directory of an ApplicationApplication ISSUE:
It is often desirable to determine the root directory for an application in order to determine where other files should be created and/or accessed.
SOLUTION: Use reflection to find the root directory of the
assesmbly.
Stop an Application From ClosingStop an Application From Closing
ISSUE: There are times where an application should
not be closed until certain conditions are met. As a result, it is necessary to programmatically stop the application from closing.
SOLUTION: Overriding the OnClosing event for the
application.
Determining the Current Version of the .NET Determining the Current Version of the .NET CF on a DeviceCF on a Device ISSUE:
Your user/customer base may be running differing versions of the .NET Compact Framework. Your application may need to know which version is installed for supporting functionality.
SOLUTION: Use System.Environment.Version to evaluate
the current .NET CF version.
Get the OpenNETCF Smart Device Get the OpenNETCF Smart Device FrameworkFramework ISSUE:
There are a number of features in the Windows Mobile environment not directly supported by the .NET Compact Framework. This causes a lot of additional coding.
SOLUTION: Look at the Smart Device Framework (“SDF”)
from the OpenNETCF group.
Get the OpenNETCF Smart Device Get the OpenNETCF Smart Device FrameworkFramework
AgendaAgenda Coding Tips & Tricks Testing/Deploying Tips & Tricks Other Tips & Tricks
Tip: Creating a .NET CF Setup ApplicationTip: Creating a .NET CF Setup Application
ISSUE: You would like to create a standard
installation for deployment of your Windows Mobile application.
SOLUTIONS: Basic CAB file deployment “Do it yourself” http://msdn.microsoft.com/library/default.asp
?url=/library/en-us/dnnetcomp/html/netcfdeployment.asp
Third-Party Solutions InstalllShield Wise
AgendaAgenda Coding Tips & Tricks Testing/Deploying Tips & Tricks Other Tips & Tricks
Additional Invaluable ToolsAdditional Invaluable Tools Windows Mobile Developer Power Toys
http://www.microsoft.com/downloads/details.aspx?FamilyId=74473FD6-1DCC-47AA-AB28-6A2B006EDFE9&displaylang=en
SOTI Pocket Controller For developing, testing and supporting http://www.soti.net
Sprite Clone Image a device for cloning in large-scale deployments http://www.spritesoftware.com
Sprite Backup Complete Windows Mobile backup solution http://www.spritesoftware.com
Additional ResourcesAdditional Resources Mobile and Embedded Developer Center
http://msdn.microsoft.com/mobility/ Microsoft .NET Compact Framework Newsgroups
microsoft.public.dotnet.framework.compactframework WindowsForms.com
http://www.windowsforms.com/ deVBuzz.com
http://www.devbuzz.com/ Club Pocket PC – Boston
http://www.bostonpocketpc.com/
© 2004 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.