RSS
 

Posts Tagged ‘Windows Mobile’

MEAP + Mobile Merge Replication Performance and Scalability Cheat Sheet

22 Apr

If your Mobile Enterprise Application Platform (MEAP) is using SQL Server Merge Replication to provide the mobile middleware and reliable wireless wire protocol for SQL Server Compact (SSCE) running on Windows Mobile 5/6.x devices + Windows XP/Vista/7 laptops, desktops and tablets; below is a guide to help you build the fastest, most scalable systems:

Active Directory

  • Since your clients will be passing in their Domain\username + password credentials when they sync, both IIS and SQL Server will make auth requests of the Domain Controller. Ensure that you have at least a primary and backup Domain Controller, that the NTDS.dit disk drives are big enough to handle the creation of a large number of new AD DS objects (mobile users and groups), and that your servers have enough RAM to cache all those objects in memory.

 

Database Schema

  • Ensure your schema is sufficiently de-normalized so that you never have to perform more than a 4-way JOIN across tables. This affects server-side JOIN filters as well as SSCE performance.
  • To ensure uniqueness across all nodes participating in the sync infrastructure, use GUIDs for your primary keys so that SQL Server doesn’t have to deal with the overhead of managing Identity ranges. Make sure to mark your GUIDs as ROWGUIDCOL for that table so that Merge won’t try to add an additional Uniqueidentifier column to the table.
  • Not only create clustered indexes for your primary keys, but ensure that every column in every table that participates in a WHERE clause is indexed.

 

Distributor

  • If your network connection is fast and reliable like Wi-Fi or Ethernet, your SSCE client has more than 32 MB of free RAM, and SQL Server isn’t experiencing any deadlocks due to contention with ETL operations or too many concurrent Merge Agents, create a new Merge Agent Profile based on the High Volume Server-to-Server Profile so that SQL Server will perform more work per round-trip and speed up your synchronizations.
  • If you’re using a 2G/3G Wireless Wide Area Network connection, create a Merge Agent Profile based on the Default Profile so that SQL Server will perform less work and use fewer threads per round-trip during synchronization than the High Volume Server to Server Profile which will help to reduce server locking contention and perform less work per round trip which will make your synchronizations more likely to succeed. 
  • In order to prevent SQL Server from performing Metadata Cleanup every time a Subscriber synchronizes, set the –MetadataRetentionCleanup parameter to 0.
  • As SQL Server has to scale up to handle a higher number of concurrent users in the future, locking contention will increase due to more Merge Agents trying to perform work at the same time.  When this happens, adjust the parameters of the Default Profile so that both  –SrcThreads and –DestThreads are equal to 1.

 

Publication

  • When defining the Articles you’re going to sync, only check the minimum tables and columns needed by the Subscriber to successfully perform its work.
  • For Lookup/Reference tables that aren’t modified by the Subscriber, mark those as Download-only to prevent change-tracking metadata from being sent to the Subscriber.
  • Despite the fact the column-level tracking sends less data over the air, stick with row-level tracking so SQL Server won’t have to do as much work to track the changes.
  • Use the default conflict resolver where the “Server wins” unless you absolutely need a different manner of picking a winner during a conflict.
  • Use Static Filters to reduce the amount of server data going out to all Subscribers.
  • Make limited use of Parameterized Filters which are designed to reduce and further specify the subset of data going out to a particular Subscriber based on a HOST_NAME() which creates data partitions.  This powerful feature slows performance and reduces scalability with each additional filter so it must be used sparingly.
  • Keep filter queries simple and don’t use IN clauses, sub-selects or any kind of circular logic.
  • When using Parameterized Filters, always create non-overlapping data partitions where a row from a filtered table only goes to a single Subscriber instead of more than one.  This will boost performance and increase scalability by avoiding the use of certain Merge metadata tables.
  • When extending a filter to an additional table in a one-to-many fashion via a foreign key, make sure to always check the Unique key check box of the Add Join dialog to optimize the performance of the join.
  • Never extend a filter out to more than 4 joined tables.
  • Do not filter tables that are primarily lookup/reference tables, small tables, and tables with data that does not change.
  • Schedule the Snapshot Agent to run once per day to create an unfiltered schema Snapshot.
  • Set your Subscriptions to expire as soon as possible to keep the amount change-tracking metadata SQL Server has to manage to an absolute minimum. Normally, set the value to 2 to accommodate 3-day weekends since 24 hours are automatically added to the time to account for multiple time zones. If server-side change tracking isn’t needed and Subscribers are pulling down a new database every day and aren’t uploading data, then set the expiration value to 1.
  • Set Allow parameterized filters equal to True.
  • Set Validate Subscribers equal to HOST_NAME().
  • Set Precompute partitions equal to True to allow SQL Server to optimize synchronization by computing in advance which data rows belong in which partitions.
  • Set Optimize synchronization equal to False if Precompute partitions is equal to True.  Otherwise set it to True to optimize filtered Subscriptions by storing more metadata at the Publisher.
  • Set Limit concurrent processes equal to True.
  • Set Maximum concurrent processes equal to the number of SQL Server processor cores.  If exceesive locking contention occurs, reduce the number of concurrent processes until the problem is fixed.
  • Set Replicate schema changes equal to True.
  • Check Automatically define a partition and generate a snapshot if needed when a new Subscriber tries to synchronize. This will reduce Initialization times since SQL Server creates and applies snapshots using the fast BCP utility instead of a series of slower SELECT and INSERT statements.
  • Add data partitions based on unique HOST_NAMEs and schedule the Snapshot Agent to create those filtered Snapshots nightly or on the weekend so they’ll be built using the fast BCP utility and waiting for new Subscribers to download in the morning.
  • Ensure that SQL Server has 1 processor core and 2 GB of RAM for every 100 concurrent Subscribers utilizing bi-directional sync. Add 1 core and 2 GB of RAM server for every additional 100 concurrent Subscribers you want to add to the system.  Never add more Subscribers and/or IIS servers without also adding new cores and RAM to the Publisher.
  • Turn off Hyperthreading in the BIOS of the SQL Server as it has been known to degrade SQL Server performance.
  • Do not add your own user-defined triggers to tables on a Published database since Merge places 3 triggers on each table already.
  • Add one or more Filegroups to your database to contain multiple, secondary database files spread out across many physical disks.
  • Limit use of large object types such as text, ntext, image, varchar(max), nvarchar(max) or varbinary(max) as they require a significant memory allocation and will negatively impact performance.
  • Set SQL Servers’s minimum and maximum memory usage to within 2 GB of total system memory so it doesn’t have to allocate more memory on-demand.
  • Always use SQL Server 2008 R2 and Windows Server 2008 R2 since they work better together because they take advantage of the next generation networking stack which dramatically increases network throughput. They can also scale up as high as 256 cores.
  • Due to how Merge Replication tracks changes with triggers, Merge Agents, and tracking tables, it will create locking contention withDML/ ETL operations.  This contention degrades server performance which negatively impacts sync times with devices.  This contention should be mitgated by performing large INSERT/UPDATE/DELETE DML/ETL operations during a nightly maintenance window when Subscribers aren’t synchronizing.
  • Since Published databases result in slower DML/ETL operations, perform changes in bulk by using XML Stored Procedures to boost performance.
  • To improve the performance of pre-computed partitions when DML/ETL operations result in lots of data changes, ensure that changes to a Parent table in a join filter are made before corresponding changes in the child tables.  This means that when DML/ETL operations are pushing new data into SQL Server, they must add master data to the parent filter table first, and then add detail data to all the related child tables second, in order for that data to be pre-computed and optimized for sync.
  • Create filter partitions based on things that don’t change every day.  Partitions that are added and deleted from SQL Server and Subscribers that move from one partition to another is very disruptive to the performance of Merge Replication. 
  • Always perform initializations and re-initializations over Wi-Fi or Ethernet when the device is docked because this is the slowest operation where the entire database must be downloaded instead of just deltas.  To determine rough estimates for initialization, multiply the size of the resulting SSCE .sdf file x the bandwidth speed available to the device.  A file copy over the expected network will also yield estimates for mininum sync times.  These times don’t include the work SQL Server and IIS must perform to provide the data or data INSERT times on SSCE.
  • If your SQL Server Publisher hits a saturation point with too many concurrent mobile Subscribers, you can scale it out creating a Server/Push Republishing hierarchy. Put the primary SQL Server Publisher at the top of the pyramid and have two or more SQL Servers subscribe to it. These can be unfiltered Subscriptions where all SQL Servers get the same data or the Subscribers can filter their data feeds by region for example. Then have the Subscribing SQL Servers Publish their Subscription for consumption by mobile SSCE clients.

 

Internet Information Services

  • Use the x64 version of the SQL Server Compact 3.5 SP2 Server Tools with Windows Server 2008 R2 running inside IIS 7.5.
  • Ensure the IIS Virtual Directory where the Server Agent resides is on a fast hard drive that’s separate from the disk where Windows Server is installed to better support file I/O.
  • Use a server with 4 processor cores and 4 GB of RAM to support 400 concurrent Subscribers queued at the same time.
  • Set the MAX_THREADS_PER_POOL Server Agent registry key equal to 4 to match the IIS processor cores and RAM. Do not set this value to a higher number than the number of cores.
  • Set the MAX_PENDING_REQUEST Server Agent registry key equal to 400 which means the Server Agent will queue up to 400 concurrent Subscribers waiting for one of the 4 worker threads to become available to sync with SQL Server.
  • Set the IIS Connection Limits property to 400 to prevent an unlimited number of connections reaching the Server Agent.
  • Add a new load-balanced IIS server for every additional 400 concurrent Subscribers you want to add to the system. 

 

Subscriber

  • Use the appropriate x64, x86 or ARM version of SQL Server Compact 3.5 SP2 to take advantage of the PostSyncCleanup property of the SqlCeReplication object that can reduce the time it takes to perform an initial synchronization. Set the PostSyncCleanup property equal to 3 where neither UpdateStats nor CleanByRetention are performed.
  • Increase the Max Buffer Size connection string parameter to 1024 on a phone and 4096 on a PC to boost both replication and SQL query processing performance. If you have more RAM available, set those values even higher until you reach the law of diminishing returns.
  • Keep your SSCE database compact and fast by setting the Autoshrink Threshold connection string parameter to 10 so it starts reclaiming empty data pages once the database has become 10% fragmented.
  • Replication performance testing must be performed using actual PDAs to observe how available RAM, storage space and CPU speed affect moving data into the device’s memory area and how quickly this data is inserted into the SSCE database tables.  Since the SSCE database doubles in size during replication, the device must have enough storage available or the operation will fail.  Having plenty of available RAM is important so that SSCE can utilize its memory buffer to complete a Merge Replication operation more quickly.  With plenty of available RAM and storage, a fast CPU will make all operations faster.
  • The PDA must have at least an extra 32 MB of available free RAM that can be used by the .NET Compact Framework (NETCF) application.  If additional applications are running on the device at the same time, even more RAM is needed.  If a NETCF application has insufficient RAM is will discard its compiled code and run in interpreted mode which will slow the application down.  If the NETCF app is still under memory pressure after discarding compiled code, Windows Mobile will first tell the application to return free memory to the operating system and then will terminate the app if needed.
  • Set the CompressionLevel property of the SqlCeReplication object to 0 for fast connections and increment it from 1 to 6 on slower connections like GPRS to increase speed and reduce bandwidth consumption.
  • Tune the ConnectionRetryTimeout, ConnectTimeout, ReceiveTimeout and SendTimeout properties of the SqlCeReplication object based on expected bandwidth speeds:

 

Property High Bandwidth Medium Bandwidth Low Bandwidth
ConnectionRetryTimeout 30 60 120
ConnectTimeout 3000 6000 12000
ReceiveTimeout 1000 3000 6000
SendTimeout 1000 3000 6000
  • You can decrease potentially slow SSCE file I/O by adjusting the Flush Interval connection string parameter to write committed transactions to disk less often than the default of every 10 seconds.  Test longer intervals between flushes like 20 or 30 seconds. Keep in mind that these transactions can be lost if the disk or system fails before flushing occurs so be careful.
  • When replicating data that has been captured in the field by the device, perform Upload-only syncs to shorten the duration.

 

Storage

  • Use a Fibre Channel SAN with 15k RPM or solid-state disks for best I/O performance.
  • Databases should reside on a RAID 10, unshared LUN comprised of at least 6 disks.
  • Database logs should reside on a RAID 10, unshared LUN comprised of at least 6 disks.
  • Tempdb should reside on a RAID 10, unshared LUN comprised of at least 6 disks.
  • The Tempdb log should reside on a RAID 10, unshared LUN comprised of at least 6 disks.
  • The Snapshot share should reside on a RAID 10, unshared LUN comprised of at least 6 disks.  This disk array should be large enough to accommodate a growing number of filtered Snapshots. Snapshot folders for Subscribers that no longer use the system must be manually deleted. 
  • Merge Replication metadata tables should reside on a RAID 10, unshared LUN comprised of at least 6 disks.
  • Increase your Host Bus Adapter (HBA) queue depths to 64.
  • Your Publication database should be broken up into half the number of files as the SQL Server has processor cores. Each file must be the same size.
  • Tempdb should be pre-sized with an auto-growth increment of 10%. It should be broken up into the same number of files as the SQL Server has processor cores. Each file must be the same size.

 

High Availability

  • Load-balance the IIS servers to scale them out. Enable Server Affinity (stickiness) since the Replication Session Control Blocks that transmit data between the Server Agent and SSCE are stateful. Test to ensure that your load-balancer is actually sending equal amounts of Subscriber sync traffic to each IIS server.  Some load-balancers can erroneously send all traffic to a single IIS server if not properly configured.
  • Implement Windows Clustering so that SQL Server can failover to a second node.
  • Using SQL Server Mirroring so that your Published database will failover to a standby server.
  • Make a second SQL Server into an unfiltered Subscriber to your Publisher so that it can take over Merge Replication duties for mobile clients as a Republisher if the primary SQL Server fails. SSCE clients would just have to reinitialize their Subscriptions to begin synchronizing with the new Republisher.

 

Ongoing Maintenance

  • Use the Replication Monitor to have a real-time view of the synchronization performance of all your Subscribers.
  • Use the web-based SQL Server Compact Server Agent Statistics and Diagnostics tools to monitor the health and activity of the Server Agent running on IIS.
  • Create a SQL Job to execute the sp_MSmakegeneration stored procedure after large DML operations. Regular execution after INSERTING/UPDATING/DELETING data from either DML/ETL operations or after receiving lots of changes from Subscribers will maintain subsequent sync performance. Executing this stored procedure from the server-side is preferable to having it executed as a result of a Subscriber sync which would block all other Subscribers.
  • During your nightly maintenance window, rebuild the indexes and update the statistics of the following Merge Replication metadata tables:
    • MSmerge_contents
    • MSmerge_tombstone
    • MSmerge_genhistory
    • MSmerge_current_partition_mappings
    • MSmerge_past_partition_mappings
    • MSmerge_generation_partition_mappings
  • If you notice performance degradation during the day due to a large number of Subscribers making large changes to the database, you can updates the statistics (with fullscan) of the Merge Replication metadata tables more frequently throughout the day to force stored proc recompiles to get a better query plan.
    • UPDATE STATISTICS MSmerge_generation_partition_mappings WITH FULLSCAN
    • UPDATE STATISTICS MSmerge_genhistory WITH FULLSCAN
  • Rebuild/defrag indexes on your database tables and Merge Replication metadata tables throughout the day to reduce locking contention and maintain performance.
  • Use the Missing Indexes feature of SQL Server to tell you which indexes you could add that would give your system a performance boost. Do not add recommended indexes to Merge system tables.
  • Use the Database Engine Tuning Advisor to give you comprehensive performance tuning recommendations that cover every aspect of SQL Server.
  • Monitor the performance of the following counters:
    • Processor Object: % Processor Time: This counter represents the percentage of processor utilization. A value over 80% is a CPU bottleneck.
    • System Object: Processor Queue Length: This counter represents the number of threads that are delayed in the processor Ready Queue and waiting to be scheduled for execution. A value over 2 is bottleneck and shows that there is more work available than the processor can handle. Remember to divide the value by the number of processor cores on your server.
    • Memory Object: Available Mbytes: This counter represents the amount of physical memory available for allocation to a process or for system use. Values below 10% of total system RAM indicate that you need to add additional RAM to your server.
    • PhysicalDisk Object: % Disk Time: This counter represents the percentage of time that the selected disk is busy responding to read or write requests. A value greater than 50% is an I/O bottleneck.
    • PhysicalDisk Object: Average Disk Queue Length: This counter represents the average number of read/write requests that are queued on a given physical disk. If your disk queue length is greater than 2, you’ve got an I/O bottleneck with too many read/write operations waiting to be performed.
    • PhysicalDisk Object: Average Disk Seconds/Read and Disk Seconds/Write: These counters represent the average time in seconds of a read or write of data to and from a disk. A value of less than 10 ms is what you’re shooting for in terms of best performance. You can get by with subpar values between 10 – 20 ms but anything above that is considered slow. Times above 50 ms represent a very serious I/O bottleneck.
    • PhysicalDisk Object: Average Disk Reads/Second and Disk Writes/Second: These counters represent the rate of read and write operations against a given disk. You need to ensure that these values stay below 85% of a disk’s capacity by adding disks or reducing the load from SQL Server. Disk access times will increase exponentially when you get beyond 85% capacity.
  • A limited number of database schema changes can be made and synchronized down to SSCE Subscribers without any code changes which makes it easier to update your system as it evolves over time.
  • Use a Merge Replication Test Harness to stress test the entire system.  The ability to simulate hundreds or thousands of concurrent synchronizing Subscribers allows you to monitor performance and the load on the system.  This is helpful in properly configuring and tuning SQL Server, IIS, and the Windows Mobile devices.  It will tell you where you’re having problems and it will let you predict how much server hardware you will need to support growing numbers of Subscribers over time.  It’s also very important to simulate worst-case scenarios that you never expect to happen. 

 

I hope this information sufficiently empowers you to take on the largest MEAP solutions that involve SQL Server Merge Replication and SQL Server Compact.  If you need a deeper dive, go check out my book on Enterprise Data Synchronization http://www.amazon.com/Enterprise-Synchronization-Microsoft-Compact-Replication/dp/0979891213/ref=sr_1_1?ie=UTF8&s=books&qid=1271964573&sr=1-1 over at Amazon.  Now go build a fast and scalable solution for your company or your customers.

Best Regards,

Rob

 

Making MEAP Real

01 Feb

After all the logical diagrams of Microsoft MEAP and spelling out how it meets Gartner’s critical capabilities, I thought I’d show you a picture that provides a more concrete view of what our MEAP offering looks like. Hopefully, this will better crystallize how Microsoft lines up with those critical capabilities and how our reusable mobile application platform plugs into a customer’s enterprise. I think we have a great story here that shows customers how we can save them money on a platform that:

1. Works the same across laptops, tablets, Netbooks and phones.
2. Gives them reusable mobile middleware that can support multiple simultaneous applications rather than needing something different for each point solution
3. Lowers risk to their projects by reducing the amount of custom code needed to build any given solution.
4. Gives them adapters that plug into the existing enterprise packages they use to run their business.

MEAP Physical Diagram

Regards,
Rob

 

Finding your Windows phone on the CBS Early Show

27 Dec

Microsoft’s My Phone service got its first public showing on the CBS Early Show when CNET’s Senior Editor Natali Del Conte put the system through its paces in New York.  Natali tossed her HTC Pure running Windows Mobile 6.5 into a taxi to simulate a real-world scenario where a passenger loses her phone. 

While you probably knew that My Phone backs up your photos, contacts, text messages, music, documents and IE favorites to the cloud, you might not have known that My Phone can be used to locate and secure a lost phone.  You can ring, lock, erase, and locate your lost phone on a map.  On the CBS Early Show, Natali was able to display a message on her lost Windows phone instructing whoever found it to contact her and return it.  Pretty cool stuff and a great example of Microsoft tying the cloud to the third screen.

Best Regards,

Rob

 
 

Interview with Rob @ Tech Ed Europe 2009

23 Dec

Check out the interview I did with David Goon at Tech Ed Europe 2009 in Berlin.  I discuss Microsoft’s Mobile Enterprise Application Platform and talk about how it aligns with Gartner’s MEAP critical capabilities and how it can save money for companies.

With the tidal wave of mobile and wireless technologies sweeping across both the consumer and enterprise landscapes, I believe MEAP offerings give us a glimpse of a new standard for designing all future infrastructures.

-Rob

 

Yes, Microsoft does have a Mobile Enterprise Application Platform (MEAP)

28 Oct
Gartner says that the Mobile Enterprise Application Platform (MEAP) market will top $1 Billion by the end of 2010 and that more than 95% of organizations will choose MEAP instead of point solutions through 2012.  The big takeaway here is that companies have been building tactical mobile application silos that support only one application and now they want to save money by going with a reusable platform capable of supporting multiple applications.  Oh and along the way it needs to support multiple device and OS platforms while providing security, device management, and a single IDE to build apps and logic to integrate with back end systems.
Gartner has a “rule of three” that states that a MEAP offers significant advantages in three situations:
  1. When there are 3 or more mobile applications
  2. When there are 3 or more targeted operating systems or platforms
  3. When they involve the integration of 3 or more back-end systems

Leaders in this space have included Sybase iAnywhere, Antenna, Dexterra, Syclo and Spring Wireless.  Microsoft goes from a large Mobile General Store with myriad solutions to a player in this space with a MEAP solution of our own:  Microsoft Mobile Enterprise Application PlatformVisual Studio is used to build the mobile logic and UI.  Merge Replication provides occasionally-connected data synchronization between SQL Server Compact on the mobile device and SQL Server in the data center.  SQL Server Business Intelligence Development Studio is used to visually create connections to back-end systems like SAP or databases like Oracle.  Data in transit is secured via SSL or VPN, data at rest is encrypted via device encryption, SQL Server Compact, BitLocker or programmatically through the Crypto API.  Integration packages that communicate with back-end systems are encrypted and digitally signed. 

We already have the best mobile email, calendaring, and contacts product in the business where Exchange Active Sync keeps Outlook and Outlook Mobile always up to date with Exchange Server.  Server-to-device as well as peer-to-peer device notifications are facilitated through WCF Store and Forward on Exchange.  Software and patch distribution along with device settings and policy management is accompished via System Center Configuration Manager.  ISA Server provides both VPN and Reverse Proxy access to roaming applications on the Internet on any platform.

When you put this stack in place and resuse it for multiple mobile applications instead of going with point solutions, ROI savings increase as the need for POCs, Pilots and training are reduced and the need for extra client access licenses is eliminated.  That’s Gartner’s first requirement.  We hit Gartner’s second requirement by uniformly supporting 3 mobile operating systems in the form of Windows, Windows CE, and Windows Mobile.  Last but not least, our SQL Server Integration Services technology combined with dozens of connectors mean we can connect your mobile devices with almost any back-end package or database.

Yes, Microsoft does have a Mobile Enterprise Application Platform that’s already proven to scale to tens of thousands of devices and it will definitely save you time and money.

- Rob

 

Enterprise Data Synchronization with Microsoft SQL Server 2008 and SQL Server Compact 3.5 Mobile Merge Replication

23 Oct

I’m happy to say that my latest book is now available on Amazon.

With the world’s largest organizations rolling out tens of thousands of Windows® phones, laptops, tablets and Netbooks to empower their respective mobile workforces, the ability to create mobile line of business solutions that support large numbers of users is absolutely critical. In my fourth book on mobile infrastructure and development, I show you how to take the SQL Server data you use to run your organization and make it available to all of your mobile employees.

Step-by-step, I’ll walk you through the process of building a secure, performant, n-tier, mobile enterprise application platform architecture designed to scale to thousands of users. You’ll also learn how to create occasionally-connected .NET applications designed to thrive in unreliable wireless conditions.

Enterprise Data Synchronization with Microsoft SQL Server 2008 and SQL Server Compact=

  • Learn how to “Mobilize” your organization by making your enterprise data available to employees carrying Windows® phones, laptops, Netbooks and tablets in the field.
  • Learn how to build an N-Tier Mobile Sync infrastructure that will scale to thousands of users.
  • Learn how to create occasionally-connected .NET applications designed to thrive in unreliable wireless conditions.
  • Learn best practices in security, reliability, performance, load-balancing, reverse proxy and hardware configuration.
  • Learn how to implement this technology in real world scenarios like supply chain management, retail, sales force automation, healthcare and emergency management.

 

Keep in mind that the knowledge you gain from this book didn’t come from me dreaming this stuff up in an Ivory Tower.  It came from building some of the worlds largest and most complex data synchronization systems for the world’s largest companies.  In addition to the hands-on experience that went into this book, I’d also like to thank some of my colleagues for their invaluable contributions:

  • Liam Cavanagh is a Senior Lead Program Manager for Microsoft’s Sync Framework and Cloud Data Services and he wrote the forward.
  • Catherine Wyatt is the Managing Editor for Hood Canal Press who made the publishing of the book possible.
  • Darren Shaffer is the CEO of Handheld Logic and he wrote the Chapter on building the Mobile Subscriber. 
  • Michael Jimenez is a Mobility Architect at Microsoft and he wrote the Appendix that shows you how to create an ISA Server 2006 Reverse Proxy to publish your sync infrastructure to the Internet.

 

It’s my sincere hope that this book will encourage you to un-tether your workforce from their desktop computers and boost your organization’s agility by pushing out critical business functions to the point of activity where employees are empowered to make timely decisions and perform tasks that best serve the interests of their customers and their company.

This repudiation of the traditional “connected” software application model increases customer satisfaction, boosts worker efficiency, reduces “missed opportunities” and results in cost savings as “un-wired” employees get their jobs done wherever they happen to be.

Best Regards,

Rob

 

The Windows Phones have arrived!

06 Oct

I’m pleased to announce that today we’re launching a new line of Windows® phones around the world that are available in a broad range of styles and prices. With a Windows phone, you can navigate easily with the touch of a finger and browse the Internet on a great mobile browser. You can also connect to two new services that allow you to back up and share data from your phone to the Web and buy a variety of useful applications from the Windows Marketplace for Mobile. Microsoft expects partners to deliver more than 30 new phones in more than 20 countries by the end of 2009.

Windows phone

One Phone for Work and Play

With a Windows phone, people can rely on their phone to balance their lives, from work to home to play. Whether it’s editing a document or sharing several vacation updates through a social networking application, Windows phones help people stay connected to the people and information they care about most. Because people’s phones often match their personality and unique needs, Microsoft now offers the Windows phone Custom Theme Creator. People can create personalized themes for their Windows phone by choosing the color and design that suits their style at http://www.windowsphone.com/theme.

With a Windows phone, people will have familiar work and play experiences right from their Start button, including these:

• A new enhanced Windows Live experience with What’s New feeds and improved Windows Live photo sharing across major social networking sites (such as Twitter, Facebook, MySpace and Flickr)

• A best-in-class e-mail experience and the ability to manage multiple accounts right from their phone with Outlook Mobile and Exchange Server synchronization not to mention Hotmail

• The ability to use PowerPoint and open and edit Word and Excel documents from their phone with Microsoft Office Mobile

• The power to sync files on the phone through Windows Live Media Manager and play media files seamlessly with Windows Media Player

• A redesigned Windows Internet Explorer mobile browser with Adobe Flash Lite that brings the mobile Web browsing experience closer to what people have come to expect from their PC

Powerful Mobile Services

With the launch of these new Windows phones, Microsoft debuts new services that bring added value to people.

My Phone is a free service that helps people manage and back up the invaluable information stored on their phone and provides peace of mind and an easy restore option in the event of a lost or damaged phone. My Phone automatically synchronizes the specific types of a phone’s content the user chooses — from contacts and appointments to texts, photos and more — to a password-protected Web site. People can also publish their photos from the My Phone Web site or their phone directly to Windows Live, Facebook, MySpace and Flickr. As part of the free service, people can go online and map the last known location of their phone from when it was last synchronized. In addition, a set of more advanced “lost phone” features are being offered as a premium package that people can activate as needed. The My Phone Premium package includes the ability to immediately locate the phone’s current location on a map (in the U.S. only); remotely lock a phone and post an “if found” message to its screen; loudly ring the phone even if it is set to vibrate or silent mode; and ultimately, if needed, completely erase the phone to protect personal data from falling into the wrong hands. People using My Phone on their phone running either Windows Mobile 6.0, 6.1 or 6.5 can access the premium package free of charge until Nov. 30, 2009. After that date, seven-day access to the premium package will be available for purchase for $4.99 in the U.S.

Also launching today is Windows Marketplace for Mobile, which offers people an easy way to find and purchase high-quality mobile applications for both work and play, while creating a new opportunity for developers to reach millions of people using Windows phones worldwide. Microsoft is pleased today to introduce 246 quality mobile applications initially in Windows Marketplace for work and play, with more than 753 ISVs worldwide on board to continue building out the catalog. People will have access to not only important line-of-business applications for work, but also popular mobile applications for play such as Facebook, MySpace, Netflix, Twikini, WunderRadio and ZAGAT, as well as leading game titles including Sudoku, “Guitar Hero World Tour” and the “PAC-MAN” series, all of which can be easily purchased and installed directly on a Windows phone. All purchased applications are certified by Microsoft to run on Windows phones and are backed by a simple return policy. Over the next few months, Microsoft will continue to evolve Windows Marketplace for Mobile to bring to market a fresh take on the app store that delivers strong value for developers and a great shopping experience for people.

Choice and Availability: A Phone for Everyone

Windows phones give people the power to choose the phone that best fits their style and budget by offering phones with a full physical QWERTY keyboard, others with just a large touch screen, and some with both touch screen and keyboard.

So what’s new for Developers?

Web developers can now target Internet Explorer Mobile for their applications.  Not only does this browser provide full desktop fidelity, but it also includes the fast IE8 Javascript engine to speed up code execution, DOM manipulation and Ajax calls.  Don’t take my word for it, test it out over at http://asp.net and watch it accurately render all the Ajax controls.

Both Native and Managed code developers get to take advantage of the new Gesture API to add panning and flicking to their apps.  The built-in physics engine allows developers to add smooth, finger-friendly scrolling.

For developers that are more at home with Cascading Style Sheets, HTML, Javascript and Ajax, Windows Mobile 6.5 introduces Widgets as an alternative to C++ or .NET.  These programs take advantage of the new Internet Explorer Mobile to render Rich Internet Applications that run outside the browser but take advantage of the power of the Web.

Any changes under the Hood?

Yes, since the launch of Windows Mobile 6, we’ve been progressively enhancing the Windows CE 5 kernel that powers the Windows Mobile platform.  You should expect better application stability, much more virtual memory available to running apps, and faster execution.

Have fun with your new phones!

- Rob

 
 

The Hidden Message Queue on your Windows phone

02 Oct

The ability to be “offline” and “occasionally-connected” is a critical component of successful mobile apps.  Wireless data networks lack complete coverage and exhibit a level of unreliability that immediately disqualify permanently-connected apps like you might see on a corporate LAN.  For a mobile app to be successful, it must allow the user to keep working in the absence of a data network.  It must also be able to transparently sync data changes from the mobile client to the server whenever a wireless data network is detected.  The primary means of accomplishing that today is via one of Microsoft’s sync technologies that allows SQL Server Compact on the mobile client to replicate data to and from SQL Server in the data center or the cloud.  Since SQL Server Compact runs almost anywhere, your mobile client could be a Windows phone, a laptop, a desktop or even a Netbook.

Besides synchronizing the tables, rows and columns of a complete database between mobile clients and servers, the use of message queuing should be considered for many scenarios due to its high-reliability by ensuring that a critical message arrives at its destination.  Products like MSMQ, MQ Series, Tibco and JMS are used all over the world in the most mission-critical environments to ensure a high level of availability and reliability.  They’re asynchronous by nature and use store and forward mechanisms so that messages get from point A to B to C.  A typical queue message includes the Destination which tells the messge where to go, a Label which describes the message, a Body which contains the message, and a Body Length so the receiver can verify that it received everything.

So how does any of this relate to Windows phones?  A number of years ago, an MSMQ client was made available for download and installation on Windows phones.  Additionally, the .NET Compact Framework 2.0 included classes to work with MSMQ.  Unfortunately, the installation of MSMQ was far from seamless which inhibited its adoption by customers.  More recently, functionality was included in the .NET Compact Framework 3.5 that facilitated store and forward messaging using Exchange 2007 as a transport.  This is a good solution for customers running the newest version of Exchange, have an unlimited data plan for their phones, and don’t mind running line of business applications over their email infrastructure.

So what do we do for customers that have found the Windows Mobile MSMQ client too much of a hassle, don’t have Exchange 2007 or don’t want to use it as a mobile message queue server?  I think the answer has been under our noses all along.  Burned in the ROM of every Windows Mobile 6.x device is SQL Server Compact + a lightweight data sync solution called Remote Data Access (RDA).  For those of you running Windows Mobile 5, XP, Vista or 7, you can easily download these bits to your mobile client.  SQL Server Compact is you local queue, RDA is your transport and SQL Server in the cloud or data center is your message queue server.  So let’s break this down and see how it will work.

A mobile application that captures data in the field would want to drop that info in a local queue.  SQL Server Compact becomes that local queue and the message format is actually a table with the following structure:

Table name Message
MessageId Uniqueidentifier
Destination NVarchar(whatever)
Label NVarchar(whatever)
Body NVarchar(4000)
BodyLength int

This table would be created inside a MessgeQueue database in SQL Server and RDA would pull it down to SQL Server Compact.  In the Pull method you call from .NET on the client, you would add “WHERE 1=0” to the SQL statement.  This filter has the effect of pulling down an empty shell of the table without retrieving any data to the client since that’s all you want.  It also means that when you insert local data into the table and call the Push method, the data will be removed from the client at the completion of a successful sync.

So you’re probably wondering, what makes this so special and message queue-like vs. anything else?  The secret is that unlike other sync technologies, RDA can wrap the upload of data into a transaction.  As the data is being uploaded over wireless, if any of the INSERTs into SQL Server fail for whatever reason, everything gets rolled-back and the original data remains in the local SQL Server Compact queue.  This is the kind of guaranteed commit that you expect from a message queuing system.  It’s an “all or nothing” success or rollback. 

It actually gets better.  A property of both RDA and Merge Replication is called ConnectionRetryTimeout.  This feature is designed to help you with unreliable wireless coverage where you have signal one minute and then lose it the next.  Let’s say you have this timeout value set to 2 minutes and you begin your Push upload of queued data.  Everything is working fine for the first few seconds but then you lose wireless coverage from your mobile operator.  If you regain coverage before the 2 minute time-out, the upload will resume where it left off.  Since both RDA and Merge send and receive data between the SQL Server Compact and IIS in tiny blocks, you never have to worry about running out of memory and you can pick up where you left off in case of a network dropout.

So the big takeaway here is that we do in fact have a Mobile Message Queue solution hidden on our Windows phones.  We have a message format that lets us drop text/xml/whatever data into the body, a label that a server process or SQL trigger can key off of to perform an action, and a transactional upload mechanism that ensures your critical data will cross the wireless chasm and make it to the other side intact.

So what’s next?  Now that you can capture data in a local queue and safely upload it, you might be wondering how queued messages from someone else can be pushed to your device.  Don’t worry, that will be in my next post.  Also, this isn’t just an article on how to solve a big problem in the mobile space, I’m actually building the necessary client and server pieces as well.  We’re all looking for a reliable and unified way to connect mobile devices to corporate assets and this just might be the simple answer we’re looking for.

- Rob

 

What ever happened to RDA?

22 Sep

Who remembers using Remote Data Access to synchronize data between SQL Server and SQL Server Compact?  I certainly do!

Before I dove head first into the world of Merge Replication, I always used RDA to get my customers up and running quickly.  Mobilizing an organization’s workforce quickly and easily is what it’s all about so they can start reaping the benefits.  In addition to a speedy time to market, there’s no faster or more scalable mobile sync technology on the market anywhere. 

So why wouldn’t I always use RDA?  Here’s a quick list:

  1. You’re using Identity columns.
  2. You want to replicate schema changes to the client.
  3. You want change tracking on both the client and server to perform diffs of each of the tables during a sync instead of re-downloading the entire table.
  4. You want to automatically resolve conflicts that arise when 2 people update the same data.
  5. You want referential integrity constraints to be pushed down to the client database from SQL Server.
  6. You don’t want to write code to perform synchronization or filter data.

If anything on the above list applied to you, you would shift to Merge Replication because it could manage ranges of Identity columns, push down schema changes, only sync data differences, resolve conflicts and push down a database’s referential integrity constraints.  Merge requires almost no code to get started and tables and columns are filtered visually via a wizard.

So why might you choose to use RDA?  Here’s another list:

  1. Your Primary Keys use GUIDs instead of Identity columns.
  2. Users don’t overwrite each other’s data so you don’t need conflict resolution.  The rule of “Last in Wins” works for you.
  3. While you want indexes to be pushed down, you don’t care if your local SSCE database has referential integrity constraints applied.
  4. You want to wrap the changes you upload to SQL Server in a transaction so that all changes are applied or none of them are.
  5. Change tracking on the client is good enough and re-downloading updated server tables doesn’t take too long.
  6. You developers don’t mind writing some sync code.
  7. Be able to execute SQL and Stored Procedures directly against SQL Server via IIS.
  8. You’re downloading read-only data.

If your solution meets the criteria in the list above, you’re probably a good candidate for using RDA instead of Merge.  Are there any other choices out there?

Back at MEDC 2007, we announced a new data replication technology for devices called Occasionally Connected Sync that would sit somewhere between RDA and Merge.  OCS as it used to be called was renamed Sync Services for ADO.NET and then was eventually merged into the Sync Framework. 

The Sync Framework is a developer-focused technology:

  1. Supports conflict resolution.
  2. Change tracking on the server as well as the client so that only data differences are exchanged.
  3. Peer to Peer sync in the forthcoming v2 of Sync Framework.
  4. Sync with databases other than SQL Server.
  5. Best suited for SSCE running on a desktop or laptop.

The clearest differentiation that the Sync Framework has over Merge is its provider model which allows it to sync with other ADO.NET databases like Oracle or DB2.  SQL Server supports built-in P2P Transactional replication and v2 of the Sync Framework will allow you to do this via WCF.  If you development team doesn’t mind writing lots of sync code and needs to support scenarios like synchronizing with other databases from SSCE on the desktop, then the Sync Framework might be the way to go for you.  I wouldn’t yet recommend the Sync Framework for device sync since its wire protocol is currently based on the DataSet which may cause out of memory errors on Windows phones with limited working sets.

So where does this leave RDA?

The reason I’m writing this blog post is because time and time again I run into customer sync scenarios that don’t always need the power of Merge or the extra flexibility of the Sync Framework.  Most field service applications follow the same kind of pattern:

  1. Lots of download-only lookup/reference tables that aren’t changed by the user.
  2. Tables that are pushed down to the device that tell a user where to go and what to do.
  3. Tables (sometimes empty) that are used to capture data from the user in the field that are upload-only.

These kinds of schemas don’t require conflict resolvers or server change tracking and are therefore well suited for RDA. 

What’s the big benefit of using RDA if a sync scenario meets its criteria?

  1. You won’t modify SQL Server’s schema with GUIDs and Triggers.
  2. You won’t degrade the performance of SQL Server by having it track changes and maintain extra metadata.
  3. You will have the fastest and most scalable sync solution with least amount of hardware.
  4. Time to market is shorter.

The big takeaway here is that I want you to consider your sync solution carefully before choosing a technology.  If your customer’s needs are met by RDA, then you should use it and reap the benefits of developing and deploying a simpler solution with fewer moving parts.

Remember Occam’s Razor.

-Rob

 
1 Comment

Posted in Sync

 

MemMaker for the .NET Compact Framework

23 Apr

Does everyone remember the good old days of DOS when we used to spend our time making more of the 640 KB memory space available for our drivers, programs, TSRs and even Windows?  Things like QEMM, HIMEM.SYS and EMM386.EXE bring back fond memories for me.  We had this one slot and Billg said we’d never need more than 640 KB.

DOS Memory Map

Some of us even switched to OS/2 which could give us 740 KB to our DOS sessions while providing them with preemptive multitasking.  Yes, I could run multiple DOS games in multiple windows simultaneously with no degradation.  Wow, now I had a bunch of crash-protected slots each with 740 KB of memory.

OS/2

If you fast forward to today, you’ll see that Windows CE 5.0 and Windows Mobile 6.x shares some commonalities with their forefathers from the 80’s and 90’s.  The 32-bit embedded operating system that we rely on to power our Windows phones is made up of a bunch of slots.  The mobile applications that you build run inside one of these slots and unlike DOS with its 640 KB memory space, your app gets 32 MB of virtual memory space.  But just like with DOS, you don’t get access to the whole space because other things like system DLLs are already eating into your free virtual memory. 

Many of you might not care because you build simple apps that use very little memory.  On the other hand, most of the people and organizations I work with build the largest, most memory-intensive applications ever seen on the mobile device.  Needless to say, these folks aren’t too pleased that they don’t get the whole 32 MB of virtual memory that’s coming to them.  They probably wish they a utility like QEMM or MemMaker to put things in high memory.

I recently met with a good friend of mine who wanted to share some interesting findings with me.  Keep in mind, not only do I consider this person and his colleagues to be some of the top Compact Framework developers in the world, his team members designed and developed of one of the world’s largest, most complex managed apps running on a Windows Mobile device.  Like many organizations that have built very large Windows Mobile applications, free virtual memory issues and the “DLL Crunch” have deprived this app from of all the memory it would like to have.  One of the architects on this “Dream Team” noticed that by keeping their application’s EXE empty and putting all the forms, code, resources, and data in managed DLLs, he reduced the amount of virtual memory his app uses inside its slot while at the same time taking advantage of memory outside the slot in the 1 GB shared memory area.

To help you visualize this, I’m going to show you 2 pictures of the Windows Mobile process slots running a Compact Framework application two different ways.  The virtual memory viewer you see running in the emulators below shows the 32 slots in the User space of the OS.  Everything in Red is free virtual memory, Blue is committed memory and Green is reserved.  Slot 1 is crammed full of ROM DLLs and you can’t help but notice the area of Blue at the top of every other slot.  That’s space out of everyone’s slot being used by system and other native DLLs which means nobody’s going to get their fair share of their 32 MB slot space.

On the left you’ll see a NETCF app called StandardExe.exe running in slot 14 of the operating system.  This simple managed EXE has a 2.25 MB bitmap bound to it as a resource and a single form that compiles to the same size as the bitmap inside it.  If you look at the picture on the left, you’ll see a 2.25 MB Blue area coming up from the bottom of slot 14.  This represents the space being taken up by the EXE.

Standard Memory Map

Optimized Memory Map

On the right a NETCF app called OptimizedExe.exe running in slot 11 of the operating system.  This managed EXE is completely empty.  The Main function calls into a static class of a managed DLL and that’s it.  No mas.  This results in an EXE with a file size of 5 KB.  In the managed DLL we have the same 2.25 MB bitmap bound to it as well as a simple form.  This compiles into a 2.25 MB DLL called OptimizedDLL.dll.  When you look at the picture on the right, you’ll be hard-pressed to see any Blue area coming up from the bottom of slot 11.  A closer look reveals the 2.25 MB DLL is nowhere to be found either.

This is pretty cool and has the potential to unleash the largest, most powerful games and applications Windows phones have ever seen.  So the big question is, how is this happening?  Is it magic? 

Those of you who have read Steven Pratschner’s blog know that the Compact Framework memory maps your managed EXE and DLLs into the 1 GB shared memory area outside the slot your app is running which is cool.  What you may not know is that the OS automatically blocks out virtual memory at the bottom of your slot that’s the same size as your EXE.  So even though the CLR is in control of app execution and is giving you lots of love by putting your managed EXE up in the shared memory area, Windows CE takes away a valuable chunk of memory because it thinks that’s where your EXE is running.  Guess what, your app isn’t running there and it’s not native.  For those of you with giant managed EXEs, you’re losing out on a lot of virtual memory in your slot that could be put to good use.  So the first lesson here is to do what Brian did and make your EXE nothing but an empty stub used to launch your app which really lives inside managed DLLs.

Your empty EXE code should look like the following:

using System;

namespace OptimizedExe
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [MTAThread]
        static void Main()
        {
            OptimizedDLL.StartUp.Main();
        }
    }
}

Your DLL code should look like the following:

using System;
using System.Windows.Forms;

namespace OptimizedDLL
{
    public class StartUp
    {
        public static void Main()
        {
            Application.Run(new Main());
        }
    }
}

So now that you’ve learned how to instantly give your managed apps more memory by beating Windows CE at its own game, let’s talk about the curious case of your managed DLL.  If you’ve read Reed Robison’s blog discussion about Slaying the Virtual Memory Monster, you know that DLLs seem to take up everyone’s virtual memory from the top of the slot down which doesn’t sound too fair.  DLLs keep pushing their way down everyone’s slot causing something we call the “DLL Crunch” as free virtual memory get’s squeezed between the DLLs and EXEs.  I’ve got some good news for you.  Managed DLLs do not exhibit this same behavior.  In fact, not only do they not use up memory in all the other slots of your Windows phone, they don’t even push downward on the memory of your own slot.  How could this be?

Managed DLLs are not DLLs.  The CLR just treats them as files that it memory maps into the 1 GB shared memory area.  To the Compact Framework, managed EXE and DLL assemblies are just files full of IL that it maps outside your process slot.  So now you know where the 2.25 MB bitmap that we bound to OptimizedDLL.dll is.  It’s beyond the 32 MB barrier of your slot and therefore not using up your valuable memory. 

So if I follow this new pattern for NETCF development, will my slot ever have virtual memory allocated or do I get a free lunch?

While there’s no free lunch, you did get a buy one get one free discount.  The JIT compiler is running in your slot and it pulls in IL from the 1 GB space as needed to compile the current call stack.  Resources that aren’t designed to be compiled or executed will never be pulled down here.  The GC Heap is in your slot and that’s where your currently allocated Objects and instance variables are hanging out.  Your slot maintains a 64 KB Stack for every Thread your app spawns and the AppDomain Heap maintains a representation of the data structures found in your assembly’s IL.

Windows CE Memory Map

So what are the big takeaways here?

You can eliminate the erroneous and wasted allocation of EXE virtual memory in your slot by following the pattern of using an empty stub managed EXE to kick off your application.  Windows CE will now only block out 5 KB of memory.

You can take better advantage of the 1 GB shared memory area by putting your entire application inside managed DLLs.  This will make your app a good neighbor by not creating the dreaded “DLL Crunch” for all the other apps on your Windows phone.  It also reduces the amount of memory that has to be allocated inside your slot.

This new pattern of managed development on the Windows Mobile platform is a true breakthrough in memory management.  Come join me at Tech Ed 2009 this May in Los Angeles for a complete deep dive on this new way of building memory-intensive games and applications.

- Rob