0% found this document useful (0 votes)
36 views71 pages

Full Download SQL Server CE Database Development With The NET Compact Framework 1st Edition Rob Tiffany (Auth.) PDF

Development

Uploaded by

mausaphytos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views71 pages

Full Download SQL Server CE Database Development With The NET Compact Framework 1st Edition Rob Tiffany (Auth.) PDF

Development

Uploaded by

mausaphytos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Download the full version of the ebook at

https://ebookultra.com

SQL Server CE Database Development with the


NET Compact Framework 1st Edition Rob Tiffany
(Auth.)

https://ebookultra.com/download/sql-server-ce-
database-development-with-the-net-compact-
framework-1st-edition-rob-tiffany-auth/

Explore and download more ebook at https://ebookultra.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

The Definitive Guide to the NET Compact Framework 1st


Edition Larry Roof

https://ebookultra.com/download/the-definitive-guide-to-the-net-
compact-framework-1st-edition-larry-roof/

ebookultra.com

Programming Microsoft SQL Server 2000 with Microsoft


Visual Basic NET 1st edition Edition Rick Dobson

https://ebookultra.com/download/programming-microsoft-sql-
server-2000-with-microsoft-visual-basic-net-1st-edition-edition-rick-
dobson/
ebookultra.com

Designing SQL Server 2000 Databases for Net Enterprise


Servers 1st Edition Robert A. Patton

https://ebookultra.com/download/designing-sql-server-2000-databases-
for-net-enterprise-servers-1st-edition-robert-a-patton/

ebookultra.com

Microsoft SQL Server 2012 T SQL 1st Edition Tom Coffing

https://ebookultra.com/download/microsoft-sql-server-2012-t-sql-1st-
edition-tom-coffing/

ebookultra.com
Microsoft SQL Server 2008 Administration with Windows
PowerShell 1st Edition Ananthakumar Muthusamy

https://ebookultra.com/download/microsoft-sql-
server-2008-administration-with-windows-powershell-1st-edition-
ananthakumar-muthusamy/
ebookultra.com

SQL Server T SQL Recipes 4th Edition Jason Brimhall

https://ebookultra.com/download/sql-server-t-sql-recipes-4th-edition-
jason-brimhall/

ebookultra.com

Practical Database Programming with Visual Basic NET


Second Edition Ying Bai(Auth.)

https://ebookultra.com/download/practical-database-programming-with-
visual-basic-net-second-edition-ying-baiauth/

ebookultra.com

Essential SQL on SQL Server 2008 1st Edition Dr. Sikha


Bagui

https://ebookultra.com/download/essential-sql-on-sql-server-2008-1st-
edition-dr-sikha-bagui/

ebookultra.com

MCTS Self Paced Training Kit Exam 70 511 Windows


Application Development with Microsoft NET Framework 4
Matthew A. Stoecker
https://ebookultra.com/download/mcts-self-paced-training-kit-
exam-70-511-windows-application-development-with-microsoft-net-
framework-4-matthew-a-stoecker/
ebookultra.com
SQL Server CE Database Development with the NET
Compact Framework 1st Edition Rob Tiffany (Auth.)
Digital Instant Download
Author(s): Rob Tiffany (auth.)
ISBN(s): 9781590591192, 1590591194
Edition: 1
File Details: PDF, 12.51 MB
Year: 2003
Language: english
-
SQL Server CE
Development
Database
with the
.NET Compact Framework
ROB TIFFANY

APress Media, LLC


SQL Server CE Database Development with the .NET Compact Framework
Copyright ©2003 by Rob Tiffany
Originally published by Apress in 2003

All rights reserved. No part of this work may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including photocopying, recording, or by any information
storage or retrieval system, without the prior written permission of the copyright owner and the
publisher.
ISBN 978-1-59059-119-2 ISBN 978-1-4302-0785-6 (eBook)
DOI 10.1007/978-1-4302-0785-6

Trademarked names may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, we use the names only in an editorial fashion and to the
benefit of the trademark owner, with no intention of infringement of the trademark.

Technical Reviewer: Darren Flatt


Editorial Board: Dan Appleman, Craig Berry, Gary Cornell, Tony Davis, Steven Rycroft, Julian
Skinner, Martin Streicher, Jim Sumser, Karen Watterson, Gavin Wray, John Zukowski
Assistant Publisher: Grace Wong
Project Manager: Nate McFadden
Copy Editor: Ami Knox
Production Manager: Kari Brooks
Production Editor: Lori Bring
Proofreader: Lori Bring
Compositor: Argosy Publishing
Indexer: Ron Strauss
Cover Designer: Kurt Krames
Manufacturing Manager: Tom Debolski

The information in this book is distributed on an "as is" basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall
have any liability to any person or entity with respect to any loss or damage caused or alleged to
be caused directly or indirectly by the information contained in this work.
To Cathy, Caroline, Nicholas, and Michael.
You're everything I've ever wanted or needed in this world.
Contents at a Glance
Foreword ................................................................................................................. xvii
About the Author ............................................................................................... xxi
About the Technical Reviewer .................................................................. xxiii
Acknowledgments ................................................................................................... xxv
Introduction .................................................................................................... xxvii
Chapter 1 Getting Started ...................................................................... 1
Chapter 2 ADO.NET .....................................................................................29
Chapter 3 Query Analyzer .................................................................. ,...51
Chapter 4 SQL Server CE Data Definition Language ................... 69
Chapter 5 Metadata ................................................................................. 107
Chapter 6 Data Manipulation Language .......................................... 139
Chapter 7 Operator Reference ........................................................... 181
Chapter 8 Function Reference ........................................................... 227
Chapter 9 Remote Data Access ...........................................................311
Chapter 10 Replication ...........................................................................361
Appendix The •NET Compact Framework Class Libraries ....... 395
Index .........................................................................................................................433

v
Contents
Foreword .......................................................................................... xvii
About the Author ........................................................................ xxi
About the Technical Reviewer ........................................... xxiii
Acknowledgments ............................................................................xxv
Introduction ............................................................................. xxvii

Chapter 1 Getting Started ....................................... 1

What This Book Is All About ................................................... 1


System Requirements .................................................................... 2
Development ................................................................................. 3
Deployn1ent .................................................................................. 4
ActiveSync All Over Again ....................................................... 5
Installation .................................................................................... 5
Get Connected .............................................................................. 6
Smart Device Extensions Walkthrough ................................. 9
Smart Device Application Wizard ............................................. 10
Forms Designer ........................................................................... 13
References ................................................................................... 16
Project Properties ....................................................................... 17
Sending Extra Files ..................................................................... 18
Let's Run It .................................................................................. 19
Security Considerations ......................................................... 22
Device Security ........................................................................... 23
Database Security ....................................................................... 24
Future Issues ............................................................................... 25
Deployment ...................................................................................... 25
Deploying the .NET Compact Framework and
SQL Server CE ...................................................................... 25
Deploying Your Application ...................................................... 26
Deployn1ent Options .................................................................. 26
Conclusion ...................................................................................... 27

vii
Contents

Chapter 2 ADO.NET ..........................................................29

Namespaces ......................................................................................30
System.Data ................................................................................. 30
System.Data.Common ............................................................... 30
System.Data.SqlClient ................................................................ 30
System.Data.SqlServerCe ........................................................... 31
The SqlCeConnection Class .....................................................31
Error Handling ............................................................................ 34
The SqlCeCommand Class ............................................................36
Parameterized Queries ............................................................... 38
Transactions ................................................................................ 40
The SqlCeDataReader Class .....................................................43
The SqlCeDataAdapter Class ...................................................46
Conclusion ......................................................................................49

Chapter 3 Query Analyzer ........................................ 51

Installation ........................ ,......................................................... 51


Overview ,......................................................................................... 52
The Objects Tab ..............................................................,............ 53
Connecting to an Unmanaged Database .................................. 53
Disconnecting from a Database ................................................ 55
Compacting a Database ................................................... ,......... 55
Deleting Databases ..................................................................... 55
Connecting to a Managed Database ......................................... 56
Showing and Hiding System Tables .......................................... 56
Retrieving Table Data .......................................... ,...................... 56
Removing Managed Databases ................................................. 57
Creating Databases ,.................................................................... 57
Creating Tables ......................................................................... ,.58
Adding Columns ......................................................................... 60
Creating Indexes ......................................................................... 61
Deleting Database Objects ......................................................... 63
The SQL Tab ....................................................................................63
Creating a New SQL Script File .................................................. 63
Saving a SQL Script File .............................................................. 65
Opening a SQL Script File .......................................................... 65
Saving Frequently Used SQL Statements .................................. 66
Opening a Saved SQL Statement ............................................... 67
Conclusion ......................................................................................67

viii
Contents

Chapter 4 SQL Server CE Data Definition


Language ........................................................ 69
Creating a Database .................................................................. 69
Example ....................................................................................... 70
Compacting a Database .............................................................. 72
Example ....................................................................................... 72
Deleting a Database .................................................................. 75
Example ....................................................................................... 75
Creating a Table ......................................................................... 76
Example 1 .................................................................................... 78
CREATE TABLE Syntax ............................................................... 81
Example 2 .................................................................................... 83
Example 3 .................................................................................... 85
Example 4 .................................................................................... 88
Modifying a Table ....................................................................... 90
Modify .......................................................................................... 92
Example 1 .................................................................................... 92
Add ............................................................................................... 94
Example 2 .................................................................................... 94
Delete ........................................................................................... 95
Example 3 .................................................................................... 96
Deleting a Table ......................................................................... 97
Example ....................................................................................... 98
Creating an Index ....................................................................... 99
The Dark Side ............................................................................ 100
Example ..................................................................................... 101
Deleting an Index ..................................................................... 103
Example ..................................................................................... 103
Conclusion .................................................................................... 105

Chapter 5 Metadata ...................................................... 107


Information Schema .................................................................. 107
Building a Metadata Viewer ................................................. 108
Building the Form ..................................................................... 109
Connection .................................................................................... 114
Example ..................................................................................... 114
Tables ............................................................................................. 116
Example ..................................................................................... 116
Table Constraints ..................................................................... 119
Example ..................................................................................... 120
Columns .......................................................................................... 122
Example ..................................................................................... 123

ix
Contents

Indexes ........................................................................................... 128


Example ..................................................................................... 128
Key Column Usage ....................................................................... 132
Example ..................................................................................... 132
Provider Types ........................................................................... 135
Example ..................................................................................... 136
Conclusion .................................................................................... 138

Chapter 6 Data Manipulation Language ....... 139


Inserting Data ........................................................................... 139
Syntax ......................................................................................... 140
Par8.Illeters ................•................................................................140
Ex8.II1ple ..................................................................................... 141
Retrieving Data ......................................................................... 144
Syntax ......................................................................................... 144
Par8.Illeters ................................................................................. 144
Example 1 .................................................................................. 145
Ex8.II1ple 2 .................................................................................. 148
Example 3 .................................................................................. 149
Joining Tables ........................................................................... 150
Syntax ......................................................................................... 150
Par8.Illeters ................................................................................. 150
Ex8.II1ple 1 .................................................................................. 151
Example 2 .................................................................................. 154
Ex8.II1ple 3 .................................................................................. 154
Filtering Data ........................................................................... 155
Syntax ......................................................................................... 155
Par8.Illeters ........•........................................................................ 155
Example ..................................................................................... 156
Joining Query Results ............................................................ 158
Syntax ......................................................................................... 158
Par8.Illeters ................................................................................. 158
Ex8.II1ple ..................................................................................... 159
Grouping Data ............................................................................. 161
Syntax ......................................................................................... 162
Par8.Illeters .................................................................................162
Example ..................................................................................... 162
Filtering Grouped Data .......................................................... 164
Syntax ......................................................................................... 165
Par8.Illeters .................................................................................165
Example ..................................................................................... 165

X
Contents

Sorting Data ............................................................................... 167


Syntax ........................................................................................ 168
Parameters ................................................................................ 168
Example 1 .................................................................................. 168
Example 2 .................................................................................. 171
Updating Data ............................................................................. 172
Syntax ........................................................................................ 172
Parameters ................................................................................ 172
Example ..................................................................................... 173
Deleting Data ............................................................................. 176
Syntax ........................................................................................ 176
Parameters ................................................................................ 176
Example ..................................................................................... 176
Conclusion .................................................................................... 179

Chapter 7 Operator Reference ............................ 181


Arithmetic .................................................................................... 181
+(Add) ....................................................................................... 182
- (Subtract) ................................................................................ 184
* (Multiply) ................................................................................ 186
I (Divide) ................................................................................... 187
% (Modulo) ................................................................................ 189
Bitwise .......................................................................................... 190
& (AND) ..................................................................................... 190
I (OR) .......................................................................................... 192
"(Exclusive OR) ........................................................................ 193
-(NOT) ...................................................................................... 195
Comparison .................................................................................... 196
=(Equals) ................................................................................... 196
> (Greater Than) ........................................................................ 198
< (Less Than) ............................................................................. 199
>= (Greater Than or Equal To) ................................................. 201
<= (Less Than or Equal To) ...................................................... 202
<>(Not Equal To) ...................................................................... 204
!=(Not Equal To) ....................................................................... 205
!<(Not Less Than) ..................................................................... 207
!> (Nat Greater Than) ............................................................... 208
Logical .......................................................................................... 210
ALL ............................................................................................. 210
AND ............................................................................................ 211
SOME/ANY ................................................................................ 213
BE1WEEN .................................................................................. 215
EXISTS ....................................................................................... 216

xi
Contents

IN ................................................................................................ 218
LIKE ............................................................................................ 219
NOT ............................................................................................ 221
OR ............................................................................................... 222
Unary ............................................................................................... 224
+ (Positive) ................................................................................. 224
-(Negative) ................................................................................ 225

Chapter 8 Function Reference ............................ 227


Aggregate Functions ................................................................ 227
AVG ............................................................................................. 227
COUNT ...................................................................................... 230
MAX ............................................................................................ 232
MIN ............................................................................................ 233
SUM ........................................................................................... 235
Date/Time Manipulation .......................................................... 236
DATEADD .................................................................................. 236
DATEDIFF ................................................................................. 238
DATENAME ............................................................................... 240
DATEPART ................................................................................. 241
GETDATE ................................................................................... 243
Mathematical Functions .......................................................... 244
ABS ............................................................................................. 244
ACOS .......................................................................................... 246
ASIN ........................................................................................... 247
ATAN .......................................................................................... 249
ATN2 .......................................................................................... 250
CEIUNG ..................................................................................... 252
cos ............................................................................................. 253
COT ............................................................................................ 255
DEGREES ................................................................................... 256
EXP ............................................................................................. 257
FLOOR ........................................................................................ 259
LOG ............................................................................................ 260
LOG10 ........................................................................................ 262
PI ................................................................................................. 263
POWER ....................................................................................... 264
RADIANS .................................................................................... 266
RAND ......................................................................................... 267
ROUND ...................................................................................... 269
SIGN ........................................................................................... 270
SIN .............................................................................................. 272

xii
Contents

SQRT .......................................................................................... 273


TAN ............................................................................................ 274
String Manipulation ................................................................ 276
NCHAR ...................................................................................... 276
CHARINDEX .............................................................................. 277
LEN ............................................................................................ 279
LOWER ....................................................................................... 280
LTRIM ........................................................................................ 282
PATINDEX ................................................................................. 283
REPLACE ................................................................................... 285
REPUCATE ................................................................................ 286
RTRIM ........................................................................................ 288
SPACE ........................................................................................ 289
STR ............................................................................................. 291
STUFF ........................................................................................ 292
SUBSTRING ............................................................................... 294
UNICODE .................................................................................. 295
UPPER ........................................................................................ 297
System Functions and Variables ........................................ 298
@@IDENTITY ............................................................................ 298
CASE ........................................................................................... 300
COALESCE ................................................................................. 302
CONVERT .................................................................................. 303
DATALENGTH .......................................................................... 307
NEWID ....................................................................................... 308

Chapter 9 Remote Data Access ............................ 311


RDA Architecture ....................................................................... 311
ClientAgent ............................................................................... 312
Database Engine ....................................................................... 312
Server Agent .............................................................................. 313
Security Considerations ....................................................... 313
liS Security ................................................................................ 313
SQLServerSecurity .................................................................. 314
Conclusions ............................................................................... 314
Installing the Server Tools ............................................... 315
Securing Your Connection ..................................................... 325
Generating a CSR ...................................................................... 325
Submit Your CSR ...................................................................... 334
Creating the Field Memo Database .................................... 340
A Table, Columns, and Indexes ............................................... 341
Creating the RDA Client ....................................................... 343
Time to Code ............................................................................. 345
Conclusion .................................................................................... 359
xiii
Contents

Chapter 10 Replication ..............................................361


Merge Replication Architecture ........................................ 361
ClientAgent ............................................................................... 362
Database Engine ....................................................................... 362
Server Agent ............................................................................... 363
SQL Server Reconciler .............................................................. 363
Creating a Publication .......................................................... 363
Making the Connection ............................................................ 375
Creating the Replication Client ...................................... 375
Your Last Chance to Code ........................................................ 377
Conclusion .................................................................................... 392

Appendix The .NET Compact Framework


Class Libraries .................................... 395
Microsoft. VisualBasic ............................................................ 395
Microsoft. VisualBasic. CompilerServices ....................... 396
Microsoft. WindowsCE. Forms ................................................... 398
System ............................................................................................. 398
System. Collections ................................................................... 402
System. Collections. Specialized ....................................... .403
System. ComponentModel ............................................................ 403
System. Configuration.Assemblies ..................................... .405
System.Data .................................................................................. 405
System.Data.Common ................................................................... 408
System.Data.SqlClient ........................................................... .409
System.Data.SqlServerCe ....................................................... .409
System.Data.SqlTypes ............................................................. .411
System.Diagnostics ................................................................... 412
System.Drawing ........................................................................... 412
System.Drawing2D ....................................................................... 413
System.Drawing.Imaging ......................................................... .413
System. Globalization .............................................................. 413
System. IO ...................................................................................... 414
System.Net .................................................................................... 415
System. Net. Sockets ................................................................... 417
System. Reflection ..................................................................... 418
System. Resources ....................................................................... 420
System. Runtime. CompilerServices ..................................... .420
System. RuntimeinteropServices .......................................... 421
System. Security ......................................................................... 421
System. Cryptography. X509Certi ficates .......................... .422

xiv
Contents

System.Security.Policy .......................................................... 422


System. Text .................................................................................. 422
System. Text.RegularExpressions ........................................ 423
System. Threading ....................................................................... 423
System.Web.Services ................................................................ 424
System. Web. Services. Description ...................................... 424
System. Web. Services. Protocols .......................................... 424
System.Windows. Forms .............................................................. 425
System.Xml .................................................................................... 430
System.Xml.Schema .................................................................... 431
System.Xml. Serialization ..................................................... 432

Index ............................................................................... 433

XV
Foreword
WELCOME TO SQL Server CE Database Development with the .NET Compact
Framework! Back in 1998, I moved off of working on the Jet database engine and
started investigating what was to become Microsoft SQL Server Windows CE
Edition. There was a lot of excitement behind working on a Vl product and
building a new team that was to tackle an area that Microsoft had not yet
embraced. Of course, with all of this came some incredible challenges to create a
robust database to work in the confines of a different OS that had very limited CPU
and RAM resources. I distinctly remember waking up at night, worrying how we
would ever get a database engine to initialize, let alone have good performance on
a MIPS 48 MHz CPU with 16MB total RAM! On top of that, we still had to get man-
agement approval and contend with the fact that we were the last of the "big"
database vendors to come to market for the mobile space.
For the Vl product, we had some design goals that would differentiate us from
the competition in the mobile database arena. First, we decided that being an in-
process DLL would be a competitive advantage over the embedded database and
server model in terms of having tight integration with eMbedded Visual Tools.
Second, we decided that we had to have a very strong sync model, as we believed
our customer base was primarily disconnected. Third, we knew that we had to be
very competitive in performance against our competitors, even though we would
provide more features in a larger footprint. Finally, we knew that we had to have a
very efficient QP that could come up with good query plans, even with limited
CPU power.
As part of any Microsoft project, the team needed to investigate all possibil-
ities before starting on the project and doing the Bill G review. This meant
investigating all angles on how to create a small but still feature-rich database
engine. We looked at everything from buying technology, to porting native SQL
Server, to using existing technology, to starting from scratch. Amazingly, the first
release was a combination of everything that eventually made the SQL Server CE
product.
As is the case with any Vl product, there was a lot of blood, sweat, and tears.
Big features had to be cut because of time constraints (having a componentized
engine was one feature that was hard to cut), and there were a host of inner team
dependencies. It certainly didn't help that the tools (eMbedded Visual Tools) were
in Vl mode and SQL Server 2000 was in beta. Nothing is as challenging as having
every component that the product relies on also be in beta. This led to many inter-
esting challenges, one being when a group of us stayed up for three straight days
trying to get a demo to work for the Windows DNA 2000 Readiness Conference. It's
amazing, when an objective needs to be achieved, how sleep can become irrel-
evant and one can watch cars come and go from the adjacent parking garage three
times straight! Even with all the all-nighters and 14+-hourwork days, the team

xvii
Foreword

pulled together and launched the Vl.O version of the product in October 2000 with
Nabisco for their "cookies and crackers" direct store delivery application.
Amazingly, the Vl.O project didn't have an internal code name, something that
never happens at Microsoft. We got with the times for our Vl.l release and formed
an official committee to come up with a set of code names that would define the
product future releases. We determined that beaches should be the theme, and
Vl.l was christened "Pebble."
We then focused our sights on V2.0, code-named Daytona, and concentrated
primarily on improving the developer experience from eMbedded Visual Tools to
VS .NET and integration with the super cool functionality that came with .NET CE
Again, the whole dependency of other products caused us some strain and forced
us to ship the product twice, once for eMbedded Visual Tools on Sept 19, 2002, and
then again with VS .NET 2003 onAprill9, 2003.
Currently we are working on our next release of SQL Server CE, code named
Laguna, and we have an incredibly valuable set of features and functionality.
Even working at a technology company, I am still amazed at how fast tech-
nology improves. Since the inception of SQL Server CE, the CPU speeds have
dramatically increased from the days of the MIPS 48 MHz PPC device to the latest
Intel XScale PXA255 running at 400 MHz, with a data bus that runs twice the speed
of the previous XScale device. The OS in Pocket PC 2003 has moved from the 3.0
code base ofWindows CE .NET to a 4.2 code base, which among many things has
introduced significant performance improvements and the removal of the 64MB
RAM limitation. Most importantly has been the widespread adoption and stan-
dardization of wireless data protocols. GPRS has finally caught on with Europe and
has widespread deployment in the U.S., and the latest generation of COMA, pro-
viding over lOOKB throughput speeds, has dramatically increased the options
available to developers to deploy truly interesting mobile applications. The
exciting mobile applications that come from this and tight integration of wireless
data into the device is something I still find amazing.
What all of these technology advances have done is increased the widespread
adoption of mobile databases, especially SQL Server CE. We now have a large
number of successful corporate rollouts, with many customers rolling out large
deployments of devices. For example, one customer will have a 90,000-device
deployment.
With all of this technology and large deployments, one of the things that I do
hear from customers is "When is a book on SQL Server CE coming out?" I'm very
happy to say that SQL Server CE Database Development with the .NET Compact
Framework is the first book of its kind to focus on SQL Server CE, data access to
SQL Server CE, and synchronization with SQL Server 2000. This lends credence to
the increased growth of mobile devices in both the consumer and corporate space.
Rob's book does a great job of covering all the basics that a developer would need

xviii
Foreword

to know to start developing an application and moving forward to a final product,


while still keeping everything interesting to read.
I know I can speak for the entire SQL Server CE team that we are very pleased
to see a book finally come out that is focused on SQL Server CE.
Kevin Collins
Microsoft Senior Program Manager for SQL Server CE

xix
About the Author
Rob Tiffany is cofounder and chief technology officer of Hood
Canal Systems, where he's focused on providing exceptional
wireless and handheld products and solutions for his clients.
In addition, Rob is also a speaker, editor, columnist, and
author of articles that have appeared in a variety of trade mag-
azines, including Java Developer's Journal and Visual Basic
Developer, on topics ranging from PersonalJava to wireless
development. SQL Server CE Database Development with the
.NET Compact Framework is Rob's second book to be pub-
lished by Apress. Rob's first book, Pocket PC Database Development with eMbedded
Visual Basic, is still popular with eVB programmers. You can contact Rob at
[email protected].

xxi
About the
Technical Reviewer
Darren Flatt is the cofounder and chief operating officer of Hood Canal Systems.
Darren's current focus is determining how to best leverage mobile technology in
the enterprise. Darren has participated in startup ventures with focuses ranging
from enterprise network management software to consulting services. While
Darren has a business degree, he can code with the best of them. You can contact
Darren at darren. flatt@hoodcanalsystems. com.

xxiii
Acknowledgments
To THE DREAM TEAM atApress, Gary Cornell, Dan Appleman, and Karen Watterson,
thanks for all your support over the years. Back when you gave me the opportunity
to write my first book, Apress was the little publishing company that could. Apress
isn't little anymore.
To the .NET Compact Framework and SQL Server CE teams at Microsoft, the
next phase of the Information Age belongs to you. The wires are gone and the com-
puters have gotten a lot smaller.

XXV
Introduction
Remembering 9/11
THE TRAGIC EVENTS of September 11, 2001, have affected everyone very deeply.
Seeing those airplanes fly into the '!Win Towers was almost surreal. In utter shock,
I watched the World Trade Center collapse and witnessed thousands of people
running and screaming. Until that moment, I thought something of this mag-
nitude only happened in science fiction movies, when Earth found herself on the
verge of extinction at the hands of an alien race. I remember thinking that this
couldn't be happening; my denial was probably coming from that part of the
human psyche that prevents the brain from being overwhelmed when faced with a
previously unimaginable horror. Like many people, I was at the office, in a sky-
scraper, with my coworkers, watching the events unfold on television. I remember
a strange silence in the office; I remember a common look of disbelief on the faces
of my friends; I remember looking out the window and noticing an eerily empty
sky once the president had cleared the U.S. airspace of commercial aircraft.

How Can I Help?


Later that day, I received an e-mail from my former boss on the USSAlaska, Senior
Chief Sexton. The subject line of the e-mail read, "Get Ready." I served my country
during the GulfWar in the Naval Submarine Service, first on a SEAL team delivery
vehicle, and later on a Trident submarine. I assumed that I'd be getting a phone call
from the United States Navy within the next few weeks recalling me to submarine
duty to go fight World War III. Well, the call never came, so I kept going to work,
kept writing software, and spent as much time as possible with my family. Pres-
ident Bush launched the War on Terrorism and invaded Afghanistan. I seem to
recall a Sunday football game being interrupted to announce the beginning of this
new conflict. There were lots of football fans cheering the soldiers on to war. Since
the call to once again serve my country didn't come, I felt like I was sitting on the
sidelines, unable to contribute. How could I help? I can navigate oceans and evade
torpedoes. I can keep a submarine perfectly level at launch depth in order to fire
her ICBMs. I even used to have a pretty high security clearance.

Getting Ready for This Book


In the meantime, I'd been planning to write a book that taught programmers how
to create database applications on the Pocket PC using the .NET Compact
Framework and SQL Server CE 2.0. You know, something that would allow
employees working in the field to enter relevant data into their handheld and then

xxvii
Introduction

replicate it back to corporate headquarters. I'd previously written a book with


similar goals that taught developers to how to build Pocket PC database applica-
tions using eMbedded Visual Basic and Pocket Access. This new technology from
Microsoft looked to be a giant leap forward, so I knew it was time to teach readers
a new technology to help them solve problems and streamline business processes.
While making the corporate world run more efficiently is an important goal, with
all that was going on in the world, I couldn't help but wonder if there was a higher
purpose for this new technology.

Not Connecting the Dots


In the spring of 2002, I started hearing news reports of FBI agents working in
Phoenix and Minneapolis who seemed to know something about the terrorists
who hijacked those airplanes on 9 I 11. These agents had picked up on the fact that
several young foreign men with expired visas were taking flying lessons all around
the country, paying with cash. They noted their suspicions in field memos, which
they sent to their superiors in Washington D.C. Some memos were rejected by
mid-level bureaucrats, while others were lost in mounds of paperwork. Con-
gressmen and senators started pointing fingers and wondering why senior FBI
officials didn't connect the dots. Why wasn't data shared amongst the various gov-
ernment agencies? Why weren't the FBI and CIA working together? Some time
later, reports surfaced that the CIA had two of the terrorists who flew the plane into
the Pentagon under surveillance when they were attending an al-Qaida meeting
overseas. The CIA had plenty of information on these two guys in their databases,
and yet the two terrorists entered the United States without incident. Why didn't
the INS get this information so they could stop these terrorists from entering the
U.S.? Is the company you work for made up of a bunch of departments that don't
talk to each other?

We Have the Technology


When President Bush addressed the nation to announce his desire to form a
cabinet-level homeland security department to coordinate this tangled web of
government agencies, people, and data, I knew what I had to do. I had to harness
my knowledge of the Pocket PC, wireless data networks, security, the .NET
Compact Framework, and both SQL Server 2000 and CE to help solve the problems
faced by those FBI field agents. In the future, field agents will be able to use a
secure Pocket PC to rapidly enter their intelligence data into a Visual Basic .NET or
C# application. That data will then be safely stored in an encrypted SQL Server CE
database until it is replicated back to a master SQL Server 2000 database via an SSL
tunnel. This multi-petabyte SQL Server 2000 database of electronic field memos
will contain the combined data of the FBI, CIA, and the Department of Homeland

xxviii
Introduction

Security. Intelligent software agents can then mine this data in order to connect
the dots and present the president with a more accurate daily threat assessment.

What to Expect from This Book


Readers of this book will learn about the technologies necessary to build the
important system I just described. If you're thinking I'm crazy, and that this line of
thinking is a little "out there" for a computer book, go take a look at the new HP
iPAQ, which has a biometric fingerprint reader. Who do you think HP made that
Pocket PC for? Anyone with highly sensitive data who can't afford to have that
information fall into the wrong hands. That applies to federal agents, military per-
sonnel, government scientists, defense contractors, and yes, corporate executives.
Who knows, maybe this kind of security will become mainstream one day.
Don't worry, you don't have to build software designed to save the world from
terrorism in order to benefit from what you're about to read. In a nutshell, you'll
learn what it takes to build powerful Pocket PC database applications that utilize
SQL Server CE 2.0. Remember all those stand -alone desktop applications you built
with Visual Basic andAccess?You'll be able to build those same applications on the
Pocket PC. Need to have your Pocket PC application synchronize with SQL Server
2000 over a wired or wireless network? I'll show you how to do that as well. I'll even
show you how to make those network data connections secure. You'll have the
tools needed to empower a mobile workforce. Whether you need to provide your
sales force with freshly updated information at their fingertips or you need to give
your insurance claims adjusters a way to capture data, this book has you covered.
Probably much like yourself, I am a business software developer. Sometimes,
problems can be solved and efficiencies can be gained through the use of tech-
nology. Technology for technology's sake doesn't fly in the corporate world. When
you're on a project, you're expected to work quickly, and in many cases you're fig-
uring out the appropriate technology on the fly. That's where I'm coming from, and
that's what you'll get from this book. My style is very succinct, so you get your
questions answered without a lot of fluff. This book will serve as both a tutorial and
a reference for you to keep on hand whenever a solution requires a Pocket PC
database application. At no time when you read this book will you ever get the
impression that I'm a computer scientist. I will not spend a single sentence
teaching you "what's under the hood" or "the low-level guts" of the .NET Compact
Framework technology. If you're looking for volumes of information on how to
build Pocket PC applications using just the Microsoft Intermediate Language,
Notepad, and a command -line compiler, you'll be extremely disappointed. On the
other hand, if you're looking for a book that will make you productive in the
shortest amount of time possible, then you've come to the right place. The chapter
summaries later in this introduction will give you a better feel for what to expect
from this book.

xxix
Introduction

Who This Book Is For


Normally, this is the part where you find out if you're qualified to read this book.
I certainly don't want to come off sounding like a stock analyst who's in the back
pocket of an investment bank by throwing out erroneous buy, sell, or hold recom-
mendations. So instead of telling you that this book targets either beginner,
intermediate, or advanced developers, I'm going to throw you a little curve. In
today's .NET Compact Framework environment, there's no requirement for
advanced embedded C++ coding experience to build powerful Pocket PC applica-
tions. In fact, those advanced embedded C++ developers are going to find that life
has gotten a lot easier for them in this arena. By the same token, beginning .NET
developers are going to find out how straightforward Pocket PC database devel-
opment truly is with the .NET Compact Framework. I will make the most complex
topics appear simple so that this book doesn't go over the head of a single
developer. All.NET developers who have a need to build Pocket PC database appli-
cations are invited to this party.

Chapter Summaries
In order to get a quick glimpse of what's to come in this book, I've included brief
summaries of each chapter. As you will see, this book takes you from the ground
floor of learning how to use the Smart Device Extensions, to teaching you about
ADO.NET, and then diving into the inner workings of SQL Server CE 2.0.

Chapter 1: Getting Started


In this chapter, I'll give you an overview of the new Smart Device Extensions for
Visual Studio .NET 2003 as well as what to expect in SQL Server CE 2.0. You'll be
taken from start to finish with a visual walkthrough of building your first Pocket PC
application with the .NET Compact Framework.

Chapter 2: ADO.NET
In this chapter, you'll see which .NET Compact Framework classes are needed to
connect to and manipulate SQL Server CE databases. You'll examine data pro-
viders as well as all the nuances of both connected and disconnected database
access.

XXX
Introduction

Chapter 3: Query Analyzer


In this chapter, I'll give you a visual tour of a useful tool that lets you work with SQL
Server CE databases in a graphical manner. You'll learn how to point-and -click
your way through data retrieval as well as database and table creation and
manipulation.

Chapter 4: SQL Server CE Data Definition Language


In this chapter, I'll teach you how to create and manipulate SQL Server CE
database objects using a combination ofSQL and .NET code. Through extensive
examples, you'll gain the skills necessary to construct any of kind of SQL Server CE
data structure.

Chapter 5: Metadata
In this chapter, you'll learn how to view database objects and their metadata using
the SQL Server CE Information Schema views. Once you've completed this
chapter, you'll no longer need to use Query Analyzer to view the data structures
you've created with DOL.

Chapter 6: Data Manipulation Language


In this chapter, I'll show you how to add, modify, retrieve, and remove data from
SQL Server CE databases. You'll learn the ins and outs of filtering, grouping, and
ordering data in your queries. Additionally, I'll describe the various types of table
joins that are now available to you in SQL Server CE 2.0.

Chapter 7: Operator Reference


In this chapter, you'll see how to use SQL Server CE's operators to build powerful
queries. This example-filled chapter will serve as an indispensable reference for
the use oflogical, unary, mathematical, bitwise, and comparison operators.

xxxi
Introduction

Chapter 8: Function Reference


In this chapter, you'll explore the dozens of built-in functions supported by SQL
Server CE. Whether you're looking for mathematical, aggregate, date/time, system,
or string functions, this chapter will answer all your questions with detailed
examples.

Chapter 9: Remote Data Access


In this chapter, you'll learn about the easy way to connect your .NET Compact
Framework/SQL Server CE applications to SQL Server 2000.1'll show you how to
pull data down to your Pocket PC, where you can manipulate it, track the changes
you made, and then push those changes back to SQL Server. You'll also learn how
to submit INSERT, UPDATE, and DELETE statements against a remote SQL Server.

Chapter 10: Replication


In this chapter, you'll learn how to work with the powerful merge replication
feature of SQL Server 2000. I'll show you how to subscribe and synchronize with a
SQL Server 2000 publication containing a collection of articles.

Appendix: The .NET Compact Framework Class Libraries


This appendix provides you with a complete reference to all the .NET Compact
Framework class libraries. This reference includes all namespaces, classes, struc-
tures, enumerations, delegates, and interfaces.

Hood Canal Systems


To keep up with what's going on in the world of handheld and wireless devel-
opment, frequent trips to http: I /www. hoodcanalsystems. com will keep you current.
This site provides you with resources such as the latest handheld and wireless
news, training courses, articles, newsgroups, and links to other important Web
sites. Additionally, Hood Canal Systems sells commercial applications, compo-
nents, and consulting services to make your wireless, handheld, barcoding, and
RFID projects a success. Feel free to contact me about these services at
[email protected].

xxxii
CHAPTER 1

Getting Started
IN OUR LAST EPISODE, back in the 2000-2001 time frame, I described how we
were entering a new phase of computing that would be dominated by small,
handheld devices designed to make your life easier. The dynamic duo of
eMbedded Visual Basic (eVB) and Pocket Access seemed like a godsend to the
millions ofVisual Basic and Access programmers who would be instantly pro-
ductive in this familiar environment. With old friends like ActiveX controls and
ADO along for the ride, a new wave of powerful Pocket PC 2000 applications would
storm onto the scene. With handheld devices containing 32MB of RAM running at
speeds of over 200 MHz, I always found it amusing when Microsoft told us eVB
programmers that we were working in a severely constrained environment. Did
everybody forget that in the early '90s we were building similar Windows applica-
tions using Visual Basic 3.0 and Access 2.0 with only 4MB of RAM available to us?
As we fast-forward to 2003, handheld devices are everywhere, and they're more
powerful than ever. That being said, your 400 MHz XScale Pocket PC with 64MB of
RAM, a 256MB SD card, and an 802.llx compact flash card is still considered a
resource-constrained device <g>. I hope the true embedded programmers who
are slinging just a few KBs of C code and burning EPROMs don't feel slighted. Oh
well, memory and processors are now small and cheap and that's why smart
devices of all kinds are taking over the market and even outselling PCs.

What This Book Is All About


The decision by Microsoft to introduce a subset of the .NET Framework to
run on these devices could not have come at a better time. The .NET Compact
Framework takes the eMbedded Visual Basic, PersonalJava, or eMbedded Visual
C++ developer to the next level with built-in support for things like networking,
custom controls, ADO. NET, Visual Basic .NET, C#, threading, compiled code, Web
services, and structured error handling. Not bad for something that weighs in at
just under 1.5MB. This power is only matched by the ease with which you can
build .NET Compact Framework applications in Visual Studio .NET 2003 utilizing
the Smart Device Extensions (SDE). SDE empowers the developer to build Pocket
PC, and Windows CE applications using the same IDE, forms designer, and
wizards that desktop and server .NET Framework developers use. You're even pro-
vided with an emulator to aid in debugging your applications. Sharing the stage

1
Chapter 1

with the .NET Compact Framework is SQL Server CE 2.0. Just when you thought
you were going to get an upgrade to the Pocket Access (cdb) database you've been
using all these years, Microsoft decides to cram their server database into a con-
strained device and allows it to work with the .NET Compact Framework via
ADO.NET. SQL Server CE is an amazing database that runs in-process as a DLL
with your .NET Compact Framework application and is a giant leap forward over
Pocket Access. Believe it or not, SQL Server CE shares many of the same features as
SQL Server 2000. Some of these features include the following:

• 249 indexes per table (same as SQL Server 2000)

• Both inner and outer joins

• Query Analyzer

• The union operator (plus 30 more operators where that came from)

• Support for parameterized queries

• 128-bit file-level encryption

• Full referential integrity including cascading updates and deletes

• Merge replication and remote data access

• Over 50 built-in functions

SQL Server CE packs an unbelievable amount of functionality for a product


that takes up no more than 1.33MB of memory on your handheld. Of course, don't
let its small size fool you, as it supports databases up to 2GB in size. As you make
your way through this book, you'll see lots ofVisual Basic .NET and C# code
examples. Since the primary focus of this book is to describe all the aspects of SQL
Server CE 2.0, keep in mind that this .NET Compact Framework code is there only
to demonstrate what can be done with SQL Server CE.

System Requirements
As I mentioned previously, .NET Compact Framework applications are created
with Visual Studio .NET 2003. This is possible through the use of a Visual Studio
Integration Package (VSIP) that plugs into Visual Studio. This VSIP is called Smart
Device Extensions and allows you to target Pocket PC and Windows CE .NET
devices.

2
Getting Started

Development
The requirements to create .NET Compact Framework applications are the same
as the requirements to run Visual Studio .NET 2003. You need one of the following:

• Windows Server 2003

• Windows XP Professional

• Windows XP Home

• Windows 2000 Server

• Windows 2000 Professional

One interesting caveat is that you won't be able to debug your applications in
the included emulator unless your computer is on a network with an active con-
nection. If you find yourself without a network, you'll need to install the Microsoft
LoopbackAdapter in order to fool the emulator into believing that you're on a
network. The following steps will get you up and running with the Loop back
Adapter.

Windows Server 2003/Windows XP


Follow these steps to install the Microsoft Loop back Adapter on a Windows Server
2003 or Windows XP system:

1. Go to the Control Panel and double-click the Add Hardware applet.

2. Click Next until you get to the Is the hardware connected? screen. Select
Yes and then click Next.

3. Select Add a new hardware device from the Installed hardware list and
then click Next.

4. Select the Install the hardware that I manually select from a list
(Advanced) radio button and then click Next.

5. Select Network Adapters from the Common hardware types list and then
click Next.

3
Chapter 1

6. Select Microsoft from the Manufacturer list, select Microsoft Loop back
Adapter from the Network Adapter list, and then click Next.

7. Click Next to initiate the installation process and then click Finish.

Windows 2000
If you have a Windows 2000 system, follow these steps to install the Microsoft
Loop back Adapter:

1. Go to the Control Panel and double-click the Add/Remove Hardware


applet.

2. Click Next until you get to the Choose a Hardware Task screen. Select Add/
Troubleshoot a device and then click Next.

3. Select Add a new device from the Devices list and then click Next.

4. Select the No, I want to select the hardware from a list radio button and
then click Next.

5. Select Network adapters from the Hardware types list and then click Next.

6. Select Microsoft from the Manufacturers list, select Microsoft Loop back
Adapter from the Network Adapter list, and then click Next.

7. Click Next to initiate the installation process and then click Finish.

Deployment
Your .NET Compact Framework applications can be targeted at a number of dif-
ferent devices:

• Pocket PC 2000

• Pocket PC 2002

• Pocket PC 2002 Phone Edition

• Windows CE 4.x

4
Getting Started

Later on in 2003, you'll get a few other devices to choose from,


including Pocket PC 2003 and Smartphone 2003, based on the latest
version ofWindows CE 4.x. Support for these forthcoming devices will
come from Web downloadable SDKs. By the time you read this, the Pocket
PC 2003 SDK should be available for download at http: I /microsoft. com/downloads/
details.aspx?Familyid=9996B314-0364-4623-9EDE-OBSFBB133652&displaylang=en.
The future looks bright for the Pocket PC, but you may have to look for other
database alternatives on the forthcoming version of Smartphone, since it won't
support SQL Server CE.

ActiveSync All Over Again


Now that the Pocket PC is a first -class, enterprise network client, you're probably
thinking that Active Sync is now a thing of the past. After all, your device has vir-
tually all of the capabilities that a laptop does, and can connect directly to Internet
and intranet resources like databases and Web services. Don't forget, consumers
who don't know what the enterprise is and just want to keep track of their everyday
life purchase millions of Pocket PCs. The reason you still need to care about
ActiveSync is for debugging and deploying your .NET Compact Framework
applications.

Installation
Based on my experience over the years working with the eMbedded Visual Tools
and now the Smart Device Extensions in Visual Studio .NET 2003, it's important to
have ActiveSync installed and working on a machine before installing the devel-
opment environment. Don't ask me why, it's just a chicken-and-egg thing. I've
tried it the other way around, and the result was that I had to reinstall Visual Studio
in order to get anything to work. Microsoft Knowledge Base article 813579
describes the inability to deploy a Smart Device Application once ActiveSync is
uninstalled and then reinstalled. In fact, our esteemed technical editor validated
just this situation the hard way and lost a day of editing in the process. Therefore,
I'm going to walk you through the ActiveSync Setup Wizard to ensure that you get
it installed properly. To get the latest and greatest version of ActiveSync, surf on
over to the Pocket PC downloads page at http: I /www. microsoft. com/mobile/
pocketpc/ downloads/. As of the writing of this book, the latest version is 3. 7.
Double-clicking msasync.exe will get things installed and shouldn't require a
reboot.

5
Chapter 1

Get Connected
Once ActiveSync is installed, it's time to get your device connected. Plug the USB
cable that came with your Pocket PC into your computer's USB port as well as the
Pocket PC itself. Most likely, you should hear a musical chime from both your Pocket
PC and your desktop computer when the two connect. Once the connection is
made, you'll be prompted to create a new partnership as shown in Figure 1-1.

This wizard helps you establish a partnership between your


mobile device and this computer. You can set up either a
standard partnership to synchronize data between your
device and this computer, or a guest partnership to simply
transfer data between your device and this computer.

What kind of partnership would you like to establish between


your device and this computer?

r. Standard partnership
I want to synchronize data between my device and
this computer, keeping data such as e-mail and
calendar items up-to-date in both places.
i Guest partnership
I want to only copy and move information between my
device and this computer, or add and remove
programs. I do not want to synchronize data.

<Back Next> Cancel Help

Figure 1-1. Setting up a partnership

Creating a Partnership
As you can see in Figure 1-1, you need to choose between setting up a Standard or
Guest partnership. A Standard partnership allows you to move data between the
desktop and device, debug with Visual Studio .NET, and synchronize items such as
Outlook calendars, Pocket Access databases, and e-mail. This is the most widely
used type of partnership, and it creates a permanent relationship between your
computer and your device. On the other hand, a Guest partnership is more of a
transient type of relationship. An example would be where many different devices
need to connect to a single computer. A Guest partnership allows you to debug
with Visual Studio .NET and move data back and forth between the desktop and
device, but it doesn't allow any kind of synching.
6
Getting Started

Data Synchronization
It used to be that the only thing you had to worry about synching with was your
desktop computer. Now you have some other options to concern yourself with. As
shown in Figure 1-2, you can choose to synchronize either with your desktop com-
puter and/ or with the Microsoft Mobile Information Server. Very shortly, the
technology found in the Mobile Information Server will be merged into Microsoft
Exchange 2003 to give you even more choices when synchronizing your data.

New Partnership .. -~ll:

Specify how to synchronize data


Choose to synchronize with your desktop and/or a server

You can synchronize data, such as e·mail messages and calendar items, between your
device and this desktop computer. However, if you have access to a Microsoft Mobile
Information Server with Microsoft Server ActiveSync, you can also choose some information
types to synchronize directly with a server, getting the most up·to·date information, even when
your desktop computer is turned off.

How do you want to synchronize with your device?

r. Synchronize with this desktop computer

r Synchronize with Microsoft Mobile Information Server and/or this desktop computer
(Note: You must have access to a Microsoft Mobile Information Server with Server
ActiveSync to synchronize with a server. You will also need to have the necessary
information to configure your connection with the server.)

<Back Ne~t > Cancel Help

Figure 1-2. Specifying how to synchronize data

How Many Partnerships?


At this point, you need to decide if you want to create a partnership with just one
or two computers. If you don't have a partnership in place with another computer
that you want to keep and you only want to sync with a single desktop, select Yes as
shown in Figure 1-3. Otherwise, select No to maintain an existing partnership
while still being able to sync with the current computer you're installing
ActiveSync on. It's very common to have partnerships set up at both your home
and office computers.

7
Chapter 1

New Partnership ··,::'/:'

Select Number of Partnerships


Select whether you want to synchronize with just this computer.

Your device can have up to two partnerships or a partnership w~h only this computer. Do
you want your device to have a partne~ship and synchronize with only this computer?

r. Yes. I want to synchronize with only this computer

R~move any e~isting partnerships on my device and set up a new partnership with just
thrs computer.

r No, I want to synchronize with two computers


Set up a partnership with this computer, but do not remove any existing partnerships on
my device.

<Back Next> Cancel Help

Figure 1-3. Selecting the number of partnerships

Synchronization Settings
Now that you've decided on one or two partnerships, you need to choose which
programs you want to synchronize with between your Pocket PC and your desktop
computer as shown in Figure 1-4. These choices are completely up to you and will
have no impact on your ability to debug and deploy .NET Compact Framework
applications from Visual Studio .NET. Alas, we've moved on from Pocket Access, so
you won't have to select it this time around.
With your synchronization setting decided upon, the creation of your
ActiveSync partnership is now complete, and the ActiveSync setup is finished. The
ActiveSync software now serves as the primary conduit between your Pocket PC
and your desktop computer. In addition to USB, ActiveSync can also communicate
with your Pocket PC via serial cable, infrared, Ethernet, and wireless 802.llx. Some
notable features found in ActiveSync include the following:

• A File Explorer that allows you to drag and drop files between your desktop
computer and your Pocket PC

• A Backup and Restore program to keep your Pocket PC data safe

8
Getting Started

• The ability to add and remove Pocket PC programs in the same manner as
Windows on the desktop

• The ability to import and export databases and tables

• The ability to synchronize with various desktop and Internet applications

New Partnership ~':.1l

Select Synchronization Settings


Select the type of information you want to synchronize.

To synchronize a particular type of information, select its check boK To stop


synchronization of that information, clear its check boK

Mobile Device
0 . .A.vantGo ,A:.,-antGo Channels
~~Calendar Microsoft Outlook
~~ Contacts Microsoft Outlook
~ *
Favorites Internet Explorer
D @ Files Synchronized Files
~ ~ l nbox Microsoft 0 utlook
D ~Notes
_....., Microsoft 0 utlook
l:J
To find out more about and to customize what gets synchronized, click
on that information type in the list and then click Settings.
Settings.. I

<Back Next> ) Cancel Help

Figure 1-4. Selecting synchronization settings

I personally think the most important element of ActiveSync is the pass-


through feature that allows your device to connect to either the Internet or
network resources in the enterprise when it's in the cradle. This allows you to test
applications that utilize TCP /IP networks even if your device doesn't have a
wireless network card. This feature will be very important later in the book when I
show you how to replicate data across the network with SQL Server 2000.

Smart Device Extensions Walkthrough


By now, you're probably anxious to build your first .NET Compact Framework
application with Visual Studio .NET 2003 and the Smart Device Extensions. To get
started with your first Smart Device Application project, you'll need to click the

9
Chapter 1

New Project button on the Start Page. Alternatively, you can go to the File menu,
and select New I Project to achieve the same result. Either way, you'll be presented
with the New Project dialog box as shown in Figure 1-5. In the Project Types pane,
you can choose which language you'd like to use. In the Templates pane, you get to
select a particular project template based on whether you want to build a Windows
or Web application among other things. In this case, you're going to choose a
Visual Basic Project and a Smart Device Application, specify a clever name for your
project, and then click OK.

29
I9'Q ::::I
Project Types: Templates: p~g ..::::.J

Windows Class Library Windows


Visual C++ Projects Application Control Library
Setup and Deployment Projects
Other Projects
Visual Studio Solutions ~ 'Ve Ve
Smart Device ASP .NET Web ASP.NET Web
Application Application Service

A project for creating an application for Pocket PC and resource-constrained devices

Name: ISmartDeviceApplicationl
Location: JC:\Documents and Settings\rtiffany\My Documents\Vis• :::J Browse ...

Project will be created at C:\ ... \rtiffany\My Oocuments\Visual Studio Projects\SmartDeviceApplicationl.

~ Mor~ OK

Figure 1-5. New Project dialog box

Smart Device Application Wizard


You are now presented with a dialog box that allows you to choose the platform
you wish to target as well as the type of project you want to create as shown in
Figure 1-6. As you can see, you're currently allowed to target Pocket PCs and
Windows CE .NET devices. In the near future, you'll be able to target the Smart-
phone as well.

10
Getting Started

Smart Dev1ce Apphcat10n W1 zard- CleverApphcat10n < ;;:;~~

II
Welcome to the Smart Device Application Wizard
This wizard creates a project to develop an application to run on a smart device.

~at platfonn do you want to target?


Vou currently have the following devices
PQd et PC
instaled that wll run an application targeting
WindowsCE
this platform.
Pocket PC Device
Pocket PC 2002 Emulator (Default:)

What ptojo!ct type do you want to create?

Class Library
Non·<;~raphical Application
Empty Project

Figure 1-6. Smart Device Application Wizard

The four project types listed in Table 1-1 are available to the Pocket PC 2000
and Pocket PC 2002.

Table 1-1. Pocket PC 2000/2002 Project Types

PROJECT TYPE DESCRIPTION


Windows Application An application that utilizes Windows Forms

Class Ubrary A DLL containing classes and methods that may be


used by other applications
Non-graphical Application An application that has no user interface and doesn't
require user interaction

Empty Project A project without any files

ll
Chapter 1

Likewise, Table 1-2 describes the four project types that are available for
Windows CE .NET.

Table 1-2. Windows CE .NET Project Types

PROJECT TYPE DESCRIPTION


Windows Application An application that utilizes Windows Forms

Class Library A DLL containing classes and methods that may be


used by other applications
Console Application A command-line application like DOS
Empty Project A project without any files

Despite the fact that you get all these great choices, I want you to select a
Pocket PC Windows Application and then click OK. Mter your computer thinks for
a moment, you'll be presented with your Pocket PC Windows project as shown in
Figure 1-7. It's time to start dragging, dropping, referencing, and coding.

Eilo~~fr•O<t .... llol>.>o_l... -~


~ - ~101" l!Qf!. 0 ·-ll-~ '"""" • ~l:li' ~ :R'l'J ·.
I !' t ~ • •~. ~ lb ;::::> [ljJ .

.,c "
6 -F<2002 ........ (00fd) -
1
~~~-·-
~- lliL X Sttd P'"9" Forml.vb(OcJign) J

I ;:::::-::::- :::·.:: :.
:·::::::::::·:::·.::: : ......
p-.,_,
loll .... _
CO'ft~ton

D•...,
(;JOotoGm
!Jju.tfiO):
II""""""' . .. .... ' ..
........
=~~lbM$w ...... - ................
... . . . ... . . ' .
" ....... .
' . ' .. . .' . ' . .
f:}:ltwn.w

··-
'

..::.1'"""""' a..tom Toof NlmeSf


='I'Saclear B

o-

RJ.._._

-.,---;;,;- J. a,.,.._,,
........
~~ . g~~r~------------------------~~--~----~~~~---=-----J
P-r~i·:~::::::::::::~~~==:::::::::r::::::::=:======·=x~
~d -

-
~~ I loc«m
ltl ••"'''" 'eJ"""' 1ll...,,..._.,r1---------------------------------- ·llli'~- ... lo.,.,._..,, ·

Figure 1-7. Smart Device Project running inside Visual Studio .NET

12
Getting Started

Forms Designer
As you can see, your Pocket PC project looks just like a standard Windows Forms
project that you'd expect to see on the desktop. The only difference is that your
form is only 295 pixels high by 246 pixels wide. On the left side of the IDE, you can
see the familiar Toolbox containing almost 30 different controls to help you build
rich graphical user interfaces. These controls can be added to your form either by
double-clicking the control or by clicking and drawing the control on your form's
surface. Controls with a runtime user interface include the following:

• Button

• CheckBox

• ComboBox

• DataGrid

• DomainUpDown

• HscrollBar

• Label

• ListBox

• ListView

• NumericUpDown

• Panel

• PictureBox

• ProgressBar

• RadioButton

• StatusBar

• TabControl

• TextBox

13
Chapter 1

• ToolBar

• TrackBar

• TreeView

• VscrollBar

You also have a number of controls without any kind of runtime or design-
time user interface. Instead, these controls display themselves in the panel below
your form:

• ContextMenu

• ImageList

• InputPanel

• MainMenu

• OpenFileDialog

• SaveFileDialog

• Timer

Thinking back in time, I don't recall either Visual Basic 3 or 4 having this
many controls. Since the purpose of this walkthrough is to get you up and
running with the Smart Device Extensions, go ahead and drop a Button control
anywhere on the form you like. Normally, you might be asked to display "Hello
World" when you click on the button. Since this book targets SQL Server CE specif-
ically, I'll have you do things a little differently. Double-click the Button control to
bring up the code window for the button's click event. Inside that click event, type
MessageBox.Show("Hello SQL") as shown in Figure 1-8.

14
Getting Started

~~ -

•I I•
~])J .j ... l ~ < .. lilJ rn ... l
Pr~ f)()
''"'""·"" " ' - ::J
E.Jt~
e:::;: c~---:=
Cl.8tclmToal

s ~ .

ftiNIIM ~- l ...tl
1'\t~ C\Doc..,_....t..r.:IS.

~~ ~ ·
.,.
~- ·- - _·---- --· =- ·- 4 X

- o ...-.... 1

Figure 1-8. Visual Studio .NET code window

Before you move on, I have one little adjustment I'd like you to make while
you're working with the Forms Designer. One of my personal pet peeves deals with
the familiar circle with an X or OK in the middle that you find in the upper-right
corner of your application. Presumably, you tap on this to close your application.
You might be surprised to know that this is actually a minimize button. Under
normal circumstances, when you tap on this button, your program disappears,
but it's actually still running in the background, taking up resources. This behavior
might be fine for some applications, but it's not a good idea when your application
has an open connection to a SQL Server CE database. Luckily, there is a way to fix
this problem. With your form displayed in the Forms Designer, go to the Minimi-
zeBox property and set it to False. Problem solved. Tapping on the X or OK will now
close your application and return its resources back to the operating system.

15
Chapter 1

References
On the right side of the IDE in the Solution Explorer, you've probably noticed a
folder labeled References. The items beneath the References folder signify that
special functionality has been added to your application. For instance, the fact
that you see System.XML beneath the References folder means that the ability to
work with XML has been added to your application. If you need to give your
program more capabilities, doing so is as easy as adding a new reference. Since
this book is about SQL Server CE, you'll find yourself needing to add additional ref-
erences to get the job done. Practice this task by right -clicking the References
folder and then selecting Add Reference. The Add Reference dialog box will pop
up, displaying a list of .NET components as shown in Figure 1-9 .

.NET IProjects J
Browse ...
Component Name 1 Version I Path
Microsoft. Visu.aiBasic 7.0.5000.0 C:\Program Files\Microsoft Vi .. . Select
Microsoft. WindowsCE.Forms 1.0.5000.0 C:\Program Files\Microsoft Vi .. .
mscorlib 1.0.5000.0 C:\Program Files\Microsoft Vi .. .
System 1.0.5000.0 C:\Program Files\Microsoft Vi .. .
System.Data 1.0.5000.0 C:\Program Files\Microsoft Vi .. .
System.Data. Common 1.0.5000.0 C: \Program Files\Microsoft Vi .. .
System.Data. SqiClient I .0.5000.0 C:\Program Files\Microsoft Vi .. .
System. Data. SqiServerCe I .0.5000.0 C:\Program Files\Microsoft Vi... -
System .Drawing 1.0.5000.0 C:\Program Files\Microsoft Vi ...
System.Net.IrDA 1.0.5000.0 C:\Program Files\Microsoft Vi. ..
System.SR I .0.5000.0 C: \Program Files\Microsoft Vi. . . '= 1
'iv<tP.m .WP.h . "i"rvirP.< 1.n.~nnn . n 1:\Prnnrnm FiiP.<IMirrn<nft Vi... ..!.I

Icom.,.~
Sele(:ted Components:
I Source
"'••

OK Cancel Help

Figure 1-9. Add Reference dialog box

Double-click both System.Data.Common and System.Data.SqlServerCe and


then click OK, since those are the two most frequently needed references in this
book. The reference to System.Data.Common allows you to work with things like
DataSets. These XML-based structures will be utilized later in the book when you
want to bind the results of your queries to a DataGrid. Referencing

16
Getting Started

System.Data.SqlServerCe gives you the power to communicate with SQL Server CE


via ADO. NET. Any time you need to work with SQL Server CE, you must have this
reference added to your project if you want your applications to work. Addi-
tionally, having System.Data.SqlServerCe referenced tells Visual Studio .NET that
it needs to copy and install SQL Server CE to either the emulator or your device
when the time comes to debug or deploy.

Project Properties
As you might imagine, your Smart Device Extension applications have all kinds of
properties that can be set through the Project Property Pages dialog box. This
dialog box can be activated by clicking the Project menu and then selecting the
<Application Name> Properties menu item. As shown in Figure 1-10, you can set
properties to optimize your application, alter the assembly name, and modify how
the compiler performs type conversions.

CleverApphcatoon l'roperty Pages

Common Properties Asserrbly rwne:


+ General ICleverApplication
Build
OUtpU: type: Startup object:
Imports
Reference Path !windows Applic..tlon ::::J J.-Fo-r-ml---------~::J
Device Root Mme~e:
Confi~r ation Properties
ICleverApplic..tion

Inform..tlon

Project folder: C:\Dorunents and SettJn9s\rtffany\My Documenl:s\Viiuol Studio Pro~


Project file: CleverApplication,vbdproj
Output Mme: CleverApplication.exe

OK Cancel Help

Figure 1-10. Property Pages dialog box

For this walkthrough, I'm only interested in showing you how to control where
your application is deployed and how to give it an icon. If you click Device under
Common Properties, you'll see a textbox called Output file folder. This is the key to
making sure your application ends up where you intend it to go. If you want your
application to show up on the Start Menu, type\ Windows\Start Menu into the

17
Chapter 1

textbox. If, on the other hand, you want it to show up with all the other programs
like Pocket Word and Excel, type in \Windows \Start Menu \Programs. With your
output path set the way you want it, click Build under Common Properties in
Visual Basic .NET or General in C# to display the Application Icon combo box.
Click the ellipsis button to the right of the combo box in order to browse for an
icon. The icons included with Visual Studio .NET can be found at C: \Program
Files\MicrosoftVisual Studio .NET 2003\Common7\Graphics\icons. Once you've
chosen an icon, you'll see that its filename has been added to the Solution Explorer
if you're using Visual Basic .NET. In order to prevent the icon from being sent along
as just an additional file, you need to highlight the filename, drop down to the
Properties area below the Solution Explorer, and set the Build Action property to
Embedded Resource. InC#, you won't see the icon in the Solution Explorer.

Sending Extra Files


In the last section, I showed you how to prevent your icon from being deployed
with your application as an extra file. Sometimes, there is a good reason to send
along extra files with your application during debugging or deployment. Anyone
who's ever worked with Microsoft Access or SQL Server over the years has defi-
nitely heard of a database called Northwind. Well, SQL Server CE is no exception,
as a version of this database comes with your copy ofVisual Studio .NET.
In order to get this database deployed to your device or emulator, I'll have to
walk you through a few steps. First of all, go to the Solution Explorer, right-click
your application name (just below the Solution name), select Add, and then click
Add Existing Item. This brings up a file dialog box that will let you search your com-
puter for the desired file. Navigate to C:\Program Files\MicrosoftVisual Studio
.NET 2003\CompactFrameworkSDK\vl.O.SOOO\Windows CE\Samples\ VB\Pocket
PC\NorthwindCE and select NorthwindDemo.sdf. You may need to adjust the file
types of your file dialog box to (*. *) in order to find it. Once you've selected it,
NorthwindDemo.sdf should appear in the Solution Explorer. This time around,
highlight the filename and set the Build Action property to Content. Getting this
set properly will ensure that this new Northwind database for SQL Server CE gets
deployed to your device and/ or emulator. It's important to note that following
these steps to get NorthwindDemo.sdf deployed to your device or emulator is not
just a request. Most of the examples found throughout the book rely on the fact
that this database has been deployed. Without it, the rest of this book won't be
nearly as delightful.

18
Getting Started

LetJs Run It
The wait is now over. If you've followed my instructions carefully, then your new
.NET Compact Framework application is ready to go. Unfortunately, there are just
a few more steps to follow. First of all, you need to tell Visual Studio .NET where to
deploy your application when you run it. This is accomplished by going to the
Deployment Device combo box on the toolbar and selecting either Pocket PC
Device as shown in Figure 1-11 or Pocket PC 2002 Emulator as shown in
Figure 1-12. Remember, your device must be connected to your desktop via
ActiveSync in order to successfully deploy your application to your device.

Pocket PC Device
=====
· I P. ~
Figure 1-11. Deploying to a Pocket PC device

t:!l
Pocket PC 2002 Emulator (Default) ru •

Figure 1-12. Deploying to the emulator

One other choice you can make before running your program is to select
either Debug or Release from the Solution Configurations combo box found on the
toolbar. If you choose Debug, you'll be able to set breakpoints and utilize the full
debugging capabilities ofVisual Studio .NET regardless of whether you're
deploying to the emulator or to your Pocket PC. If you choose Release, Visual
Studio .NET will build an optimized executable for deployment. For our purposes,
select Pocket PC 2002 Emulator and Debug, and then click the Start button on the
toolbar as shown in Figure 1-13 in order to get things going.

._ Figure 1-13. Start button

A Deploy dialog box will pop up immediately after clicking the Start button, as
shown in Figure 1-14. This dialog box is somewhat redundant to the choices you've
already made, but it gives you a second chance to change your mind in regards to
your deployment target. It also reminds you that if your device doesn't already
have the .NET Compact Framework installed, it will take care of that task for you
automatically.

19
Exploring the Variety of Random
Documents with Different Content
The sides of this (Fig, 101, a, a), facing east and west are three
and a half feet long, two feet high on the south end, and two and a
half feet on the north. They are in one piece, which is secured by
nailing the boards which form them to cleats, which are one inch
from the ends. The north end (Fig, 101, b) is three feet by two and a
half feet, the south (Fig. 101, b), three feet by two, and made the
same as are the sides. The slanting top of the sides (Fig. 101, a, a)
is made by using for the upper board, the strip formed by sawing
diagonally from corner to corner a board six inches wide and three
feet long. The cover (Fig. 101, g), which is removed in the figure, is
large enough to cover the top and project one inch at both ends. It
should be battened, and held in one piece by cleats (Fig. 101, h) four
inches wide, nailed on to the ends. These will drop over the ends of
the box, and thus hold the cover in place, and prevent rain and snow
from driving in. When in place this slanting cover permits the rain to
run off easily, and will dry quickly after a storm. By a single nail at
each corner the four sides may be tacked together about the hives,
when they can be packed in with straw (Fig. 101), which should be
carefully done if the day is cold, so as not to disquiet the bees. At the
centre and bottom of the east side (Fig. 101, c), cut out a square
eight inches each way, and between this and the hive place a
bottomless tube (the top of this tube is represented as removed in
figure to show entrance to hive), before putting around the straw and
adding the cover. This box should be put in place before the bleak
cold days of November, and retained in position till the stormy winds
of April are passed by. This permits the bees to fly when very warm
weather comes in winter or spring, and requires no attention from the
apiarist. By placing two or three hives close together in autumn—yet
never move the colonies more than three or four feet at any one
time, as such removals involve the loss of many bees—one box may
be made to cover all, and at less expense. Late in April these may
be removed and packed away, and the straw carried away, or
removed a short distance and burned.

CHAFF HIVES.
Messrs. Townley, Butler, Root, and others, prefer chaff hives,
which are simply double-walled hives, with the four or five inch
chambers filled with chaff. The objection to these I take to be: First,
Danger that so limited a space would not answer in severe seasons;
Second, That such cumbrous hives would be inconvenient to handle
in summer; and, Third, A matter of expense. That they would in part
supply the place of shade, is, perhaps, in their favor, while Mr. A. I.
Root thinks they are not expensive.

WINTERING IN CELLAR OR HOUSE.


With large apiaries the above method is expensive, and
specialists may prefer a cellar or special depository, which I think are
quite as safe, though they demand attention and perhaps labor in
winter. After my experience in the winter of 1874 and 1875, losing all
my bees by keeping them in a house with double walls filled in with
sawdust, in which the thermometer indicated a temperature below
zero for several weeks, in which time my strongest colonies literally
starved to death in the manner already described, I hesitate to
recommend a house above ground for Michigan, though with very
numerous colonies it might do. Such a house must, if it answer the
purpose, keep an equable temperature, at least 3° and not more
than 10° above freezing, be perfectly dark, and ventilated with tubes
above and below, so arranged as to be closed or opened at
pleasure, and not admit a ray of light.
A cellar in which we are sure of our ability to control the
temperature, needs to be also dry, dark, and quiet, and ventilated as
described above. As already stated, the ventilator to bring air may
well be made of tile, and pass through the earth for some feet and
then open at the bottom of the cellar. If possible, the ventilator that
carries the foul air off should be connected with a stove pipe in a
room above, with its lower end reaching to the bottom of the cellar.
The College apiary cellar is grouted throughout, which makes it more
dry and neat. Of course it should be thoroughly drained.
The colonies should be put into the depository when the hives
are dry, before cold weather, and should remain till April; though in
January and March, if there are days that are warm, they should be
taken out and the bees permitted to fly, though not unless they seem
uneasy and soil the entrance to their hives. Always when taken out
they should be placed on their old stands, so that no bees may be
lost. Towards night, when all are quiet, return them to the cellar. I
would not remove bees till towards night, as it is better that they
have a good flight, and then become quiet. When moved out it is
very desirable to brush away all dead bees which is an argument in
favor of a movable bottom-board. In moving the hives, great care
should be exercised not to jar them. It were better if the bees should
not know that they were being moved at all.
That the moisture may be absorbed, I cover the bees with a quilt,
made of coarse factory cloth, enclosing a layer of cotton batting.
Above this I fill in with straw which is packed in so closely that the
cover may be removed without the straw falling out. If desirable the
straw may be cut—or chaff may be used—and may be confined in a
bag made of factory, so that it resembles a pillow. I now use these
and like them. This is not only an excellent absorbent, but preserves
the heat, and may well remain, till the following June.
I have found it advantageous, when preparing my bees for winter,
in October, to contract the chamber by use of a division board. This
is very desirable if wintered out doors, and with frames a foot square
is very easily accomplished. By use of eight frames the space (one
cubic foot) is very compact, and serves to economize the heat, not
only in winter, but in spring. By thus using a division board with only
three frames, I have been very successful in wintering nuclei. We
have only to guard against low temperature.
Perhaps I ought to say that all colonies should be strong in
autumn; but I have said before, never have weak colonies. Yet for
fear some have been negligent. I remark that weak colonies should
be united in preparing for winter. To do this, approximate the colonies
each day four or five feet till they are side by side. Now remove the
poorest queen, then smoke thoroughly, sprinkle both colonies with
sweetened water scented with essence of peppermint, putting a
sufficient number of the best frames and all the bees into one of the
hives, and then set this midway between the position of the hives at
the commencement of the uniting. The bees will unite peaceably,
and make a strong colony. Uniting colonies may pay at other
seasons. It may seem rash to some, yet I fully believe that if the
above suggestions are carried out in full, I may guarantee successful
wintering. But if we do lose our bees—with all our hives, combs and
honey, we can buy colonies in the spring, with a perfect certainty of
making 200 or 300 per cent, on our investment. Even with the worst
condition of things, we are still ahead, in way of profit, of most other
vocations.

BURYING BEES.
Another way to winter safely and very economically, is to bury the
bees. If this is practiced the ground should either be sandy or well
drained. If we can choose a side-hill it should be done. Beneath the
hives and around them, straw should be placed. I should advise
leaving the entrance well open, yet secure against mice. The hives
should all be placed beneath the surface level of the earth, then form
a mound above them sufficient to preserve against extreme warmth
or cold. A trench about the mound to carry the water off quickly is
desirable. In this arrangement the ground acts as a moderator. Five
colonies thus treated the past winter, (1877-8) lost all told less than
one-half gill of bees. As this method has not been so long tried, as
the others, I would suggest caution. Try it with a few colonies, till you
are assured as to the best arrangement, and of its efficacy. I am
inclined to think that it is next to a good snow-bank, as a winter
repository.

SPRING DWINDLING.
As already suggested, this is not to be feared if we keep our bees
breeding till late autumn. It may be further prevented by forbidding
late autumn flights, frequent flights in winter, when the weather is
warm, and too early flying in spring. These may all be curtailed or
prevented by the packing system as described above, as thus
prepared the bees will not feel the warmth, and so will remain quiet
in the hive. Nine colonies which I have packed have been
remarkably quiet, and are in excellent condition this, February 25th,
while two others unpacked have flown day after day, much, I fear, to
their injury. I would leave bees in the packing till near May, and in the
cellar or ground, till early flowers bloom, that we may secure against
too rapid demise of bees in spring.
CHAPTER XVIII.
THE HOUSE APIARY.

DESCRIPTION.
This is a double-walled house, which may be rectangular or
octagonal in form. The outer wall should be of brick, and made as
thin as possible. Inside of this there should be wooden strips two-
inches thick, which should receive a layer of paper-sheeting inside,
which may be held by nailing strips two-inches wide immediately
inside the first mentioned strips. These last strips should receive lath,
after which all should be plastered. This may cost more than a purely
wooden structure, but it will be more nearly frost-proof than any other
kind of wall, and in the end will be the cheapest. There will be two
dead air-chambers, each two inches deep, one between the paper
and brick, the other between the paper and the plaster. The entire
wall will be at least eight inches thick. If desired, it may be made less
thick by using one-inch strips, though for our very severe winters the
above is none too thick. The doors and windows should be double
and should all shut closely against rubber. The outer ones should
consist of glass, and should be so hung as to swing out, and in hot
weather should be replaced with door, and window-screens, of
coarse, painted, wire gauze. A small window just above each colony
of bees is quite desirable.
Somewhere in the walls there should be a ventilating tube—a
brick flue would be very good—which should open into the room just
above the floor. Above it might open into the attic, which should be
well aired. Ventilators such as are so common on barns might be
used.
The pipe for admitting air, should, as in the cellar before
described, pass through the ground and enter the floor from below. A
good cellar, well ventilated and thoroughly dry will be convenient,
and should not be neglected. I would have the building but one story,
with joists in ceiling above eight inches thick. Above these I would
sheet with building paper, fastened by nailing strips two inches deep
on top, above which I would ceil with matched boards. I should lath
and plaster below the joists. The hives, which are to be kept
constantly in this house, may rest on two rows of shelves, one at the
floor, the other three feet high, and should be arranged for both top
and side storing in the small section frames. Indeed, the hive need
only consist of the two rabbeted side-boards (Fig, 30, c), and a
division-board with quilt. The entrances of course pass through the
wall. An alighting-board, so hinged as to be let down in summer, but
tightly closed over the entrance during very severe winter weather, I
should think would be very desirable. Between the double windows,
which it will be remembered shut closely against rubber, sacks of
chaff may be placed in winter, if found necessary to keep the proper
temperature. With few colonies this might be very necessary. The
adjacent entrances should vary in color, so that young queens would
not go astray, when they returned from their "Marriage flight."

ARE THEY DESIRABLE?


As yet, I think this question cannot be answered. Some who have
tried them, among whom are Messrs. Russell and Heddon, of this
State, pronounce against them. Perhaps they have faulty houses,
perhaps they have had too brief an experience to judge correctly.
Others, among whom are Messrs. A. I. Root, Burch, and Nellis, have
tried them, and are loud in their favor. I think these first trials are
hardly conclusive, as perfection seldom comes in any system with
the first experience. That the early use of these houses has met with
so much favor, seems to argue that with more experience, and
greater perfection, they may become popular. Yet I would urge
people to be slow to adopt these costly houses, as enough will do so
to thoroughly test the matter; when, if they prove a desideratum, all
can build; whereas, if they prove worthless, we shall not have to
regret money squandered, in the adoption of what was of doubtful
value.

THE CASE AS IT NOW STANDS.


The desirable points as they now appear, are: First. The bees are
in condition to winter with no trouble or anxiety. Second. The bees
are handled in the house, and as they fly at once to the windows,
where they can be suffered to escape, they are very easily and
safely handled, even with little or no protection. Third. As we can
extract, manipulate honey boxes, etc., right in the same house, it is
desirable on the score of convenience. Fourth. As the bees are
protected from the sudden rise of the out-door temperature, they will
be kept from frequent flights during the cold, forbidding days of fall,
winter and spring, and will thus be more secure against spring
dwindling. Fifth. As the bees are so independent of out-door heat,
because of the thick walls, with intervening-air-spaces, they are
found less inclined to swarm. Sixth. We can lock our house, and
know that thieves cannot steal our hard-earned property.
The objections to them are: First. The bees leave the hives while
being handled, crawl about the house, from which it is difficult to
dislodge them, especially the young bees. This objection may
disappear with improved houses and practice. Second. In very
severe winters, like that of 1874 and 1875, they may not offer
sufficient protection, yet they would be much safer than chaff hives,
as there would be many colonies all mutually helping each other to
maintain the requisite temperature, and the walls might be even
thicker than specified above, without any serious inconvenience.
Third. Some think it pleasanter and more desirable to handle bees
out-doors, where all is unconfined. Fourth. The cost of the house; yet
this is only for once in a life-time, and saves providing shade,
sawdust, packing-boxes, complex hives, etc.
So, we see the question is too complex to be settled except by
careful experiment, and this, too, for a series of years. There are so
many now in use in the various States, that the question must soon
be settled. I predict that these structures will grow more and more
into favor.
CHAPTER XIX.
EVILS THAT CONFRONT THE APIARIST.

There are various dangers that are likely to vex the apiarist, and
even to stand in the way of successful apiculture.—Yet, with
knowledge, most, if not all of these evils may be wholly vanquished.
Among these are: Robbing among the bees, disease, and
depredations from other animals.

ROBBING.
This is a trouble that often very greatly annoys the inexperienced.
Bees only rob at such times as the general scarcity of nectar forbids
honest gains. When the question comes: Famine or theft, like many
another, they are not slow to choose the latter. It is often induced by
working with the bees at such times, especially if honey is scattered
about or left lying around the apiary. It is especially to be feared in
spring, when colonies are apt to be weak in both honey and bees,
and thus are unable to protect their own meager stores. The
remedies for this evil are not far to seek:
First. Strong colonies are very rarely molested, and are almost
sure to defend themselves against marauders; hence, it is only the
weaklings of the apiarist's flock that are in danger. Therefore, regard
for our motto, "Keep all colonies strong," will secure against harm
from this cause.
Second. Italians, as before stated, are fully able, and quite as
ready, to protect their rights against neighboring tramps. Woe be to
the thieving bee that dares to violate the sacred rights of the home of
our beautiful Italians. For such temerity is almost sure to cost the
intruder its life.
But weak colonies, like our nuclei, and those too of black bees,
are still easily kept from harm. Usually, the closing of the entrance so
that but a single bee can pass through, is all sufficient. With the hive
we have recommended, this is easily accomplished by simply
moving the hive back.
Another way to secure such colonies against robbing is to move
them into the cellar for a few days. This is a further advantage, as
less food is eaten, and the strength of the individual bees is
conserved by the quiet, and as there is no nectar in the fields no loss
is suffered.
In all the work of the apiary at times of no honey gathering, we
cannot be too careful to keep all honey from the bees unless placed
in the hives. The hives, too, should not be kept open long at a time.
Neat, quick work should be the watch-word. During times when
robbers are essaying to practice their nefarious designs, the bees
are likely to be more than usually irritable, and likely to resent
intrusion; hence the importance of more than usual caution, if it is
desired to introduce a queen.

DISEASE.
The common dysentery—indicated by the bees soiling their
hives, as they void their feces within instead of without—which has
been so free, of late, to work havoc in our apiaries, is, without doubt,
I think, consequent upon wrong management on the part of the
apiarist, as already suggested in Chapter XVII. As the methods to
prevent this have already been sufficiently considered, we pass to
the terrible

FOUL BROOD.
This disease, said to have been known to Aristotle—though this
is doubtful, as a stench attends common dysentery—though it has
occurred in our State as well as in States about us, is not familiar to
me, I having never seen but one case, and that on Kelly's Island, in
the summer of 1875, where I found it had reduced the colonies on
that Island to two. No bee malady can compare with this in
malignancy. By it Dzierzon once lost his whole apiary of 500
colonies.—Mr. E. Rood, first President of the Michigan Association,
has lost his bees two or three times by this same terrible plague.
The symptoms are as follows: Decline in the prosperity of the
colony, because of failure to rear brood. The brood seems to putrefy,
becomes "brown and salvy," and gives off a stench, which is by no
means agreeable, while later, the caps are concave instead of
convex, and have a little hole through them.
There is no longer any doubt as to the cause of this fearful
plague. Like the fell "Pebrine," which came so near exterminating the
"silk worm," and a most lucrative and extensive industry in Europe, it,
as conclusively shown by Drs. Preusz and Shönfeld, of Germany, is
the result of fungous or vegetable growth. Shönfeld not only infected
healthy bee larvæ, but those of other insects, both by means of the
putrescent foul brood, and by taking the spores.
Fungoid growths are very minute, and the spores are so
infinitesimally small as often to elude the sharp detection of the
expert microscopist. Most of the terrible, contagious diseases that
human flesh is heir to, like typhus, diphtheria, cholera, small pox,
&c., &c., are now thought to be due to microscopic germs, and
hence to be spread from home to home, and from hamlet to hamlet,
it is only necessary that the spores, the minute seeds, either by
contact or by some sustaining air current, be brought to new soil of
flesh blood or other tissue—their garden spot—when they at once
spring into growth, and thus lick up the very vitality of their victims.
The huge mushroom will grow in a night. So too, these other plants
—the disease germs—will develop with marvelous rapidity; and
hence the horrors of yellow fever, scarlatina, and cholera.
To cure such diseases, the fungi must be killed. To prevent their
spread, the spores must be destroyed, or else confined. But as these
are so small, so light, and so invisible—easily borne and wafted by
the slightest zephyr of summer, this is often a matter of the utmost
difficulty.
In "Foul Brood" these germs feed on the larvæ of the bees, and
thus convert life and vigor into death and decay. If we can kill this
miniature forest of the hive, and destroy the spores, we shall
extirpate the terrible plague.

REMEDIES.

If we can find a substance that will prove fatal to the fungi, and
yet not injure the bees, the problem is solved. Our German scientists
—those masters in scientific research and discovery, have found this
valuable fungicide in salicylic acid, an extract from the same willows
that give us pollen and nectar. This cheap white powder is easily
soluble in alcohol, and when mixed with borax in water.
Mr. Hilbert, one of the most thoughtful of German bee-keepers,
was the first to effect a radical cure of foul brood in his apiary by the
use of this substance. He dissolved fifty grains of the acid in five
hundred grains of pure spirits. One drop of this in a grain of distilled
water is the mixture he applied. Mr. C. F. Muth, from whom the above
facts as to Herr Hilbert are gathered, suggests a variation in the
mixture.
Mr. Muth suggests an improvement, which takes advantage of
the fact that the acid, which alone is very insoluble in water, is, when
mixed with borax, soluble. His recipe is as follows: One hundred and
twenty-eight grains of salicylic acid, one hundred and twenty-eight
grains of soda borax, and sixteen ounces distilled water. There is no
reason why water without distillation should not do as well.
This remedy is applied as follows: First uncap all the brood, then
throw the fluid over the comb in a fine spray. This will not injure the
bees, but will prove fatal to the fungi.
If the bees are removed to an empty hive, and given no comb for
three or four days, till they have digested all the honey in their
stomachs, and then prevented visiting the affected hive, they are
said to be out of danger. It would seem that the spores are in the
honey, and by taking that, the contagion is administered to the young
bees. The honey may be purified from these noxious germs, by
subjecting it to the boiling temperature, which is generally, if not
always, fatal to the spores of fungoid life. By immersing the combs in
a salicylic acid solution, or sprinkling them with the same, they would
be rendered sterile, and could be used without much fear of
spreading contagion. The disease is probably spread by robber bees
visiting affected hives, and carrying with them in the honey the fatal
germs.
I have found that a paste made of gum tragacanth and water is
very superior, and I much prefer it for either general or special use to
gum Arabic. Yet it soon sours—which means that it is nourishing
these fungoid plants—and thus becomes disagreeable. I have found
that a very little salicylic acid will render it sterile, and thus preserve it
indefinitely.

ENEMIES OF BEES.
Swift was no mean entomologist, as shown in the following
stanza:

"The little fleas that do us tease,


Have lesser fleas to bite them,
And these again have lesser fleas,
And so ad infinitum."

Bees are no exception to this law, as they have to brave the


attacks of reptiles, birds, and other insects. In fact, they are beset
with perils at home, and perils abroad, perils by night and perils by
day.

THE BEE MOTH—Galleria Cereana, Fabr.

This insect belongs to the family of snout moths, Pyralidæ. This


snout is not the tongue, but the palpi, which fact was not known by
Mr. Langstroth, who is usually so accurate, as he essayed to correct
Dr. Harris, who stated correctly, that the tongue, the ligula, was "very
short and hardly visible." This family includes the destructive hop
moth, and the noxious meal and clover moths, and its members are
very readily recognized by their unusually long palpi, the so-called
snouts.
Fig. 102.
Fig, 103.

The eggs of the bee moth are white, globular and very small.
These are usually pushed into crevices by the female moth as she
extrudes them, which she can easily do by aid of her spy-glass-like
ovipositor. They may be laid in the hive, in the crevice underneath it
or about the entrance.—Soon these eggs hatch, when the gray, dirty
looking caterpillars, with brown heads, seek the comb on which they
feed. To better protect themselves from the bees, they wrap
themselves in a silken tube (Fig, 102) which they have power to spin.
They remain in this tunnel of silk during all their growth, enlarging it
as they eat. By looking closely, the presence of these larvæ may be
known by this robe of glistening silk, as it extends in branching
outlines (Fig, 103) along the surface of the comb. A more speedy
detection, even, than the defaced comb, comes from the particles of
comb, intermingled with the powder-like droppings of the caterpillars,
which will always be seen on the bottom-board in case the moth-
larvæ are at work. Soon, in three or four weeks, the larvæ are full
grown (Fig, 104). Now the six jointed, and the ten prop-legs—making
sixteen in all, the usual number of caterpillars—are plainly visible.

Fig. 104. Fig. 105.

Fig. 106.

These larvæ are about an inch long, and show, by their plump
appearance, that they at least, can digest comb. They now spin their
cocoons, either in some crevice about the hive, or, if very numerous,
singly (Fig, 105, a) or in clusters (Fig, 105, b) on the comb, or even
in the drone-cells (Fig, 105, c) in which they become pupæ, and in
two weeks, even less, sometimes, during the extreme heat of
summer, the moths again appear. In winter, they may remain as
pupæ for months. The moths or millers—sometimes incorrectly
called moth-millers—are of an obscure gray color, and thus so mimic
old boards, that they are very readily passed unobserved by the
apiarist. They are about three-fourths of an inch long, and expand
(Fig, 106) nearly one and one-fourth inches. The females (Fig, 107)
are darker than the males (Fig, 107), possess a longer snout, and
are usually a little larger. The wings, when the moths are quiet (Fig,
107) are flat on the back for a narrow space, then slope very
abruptly. They rest by day, yet, when disturbed, will dart forth with
great swiftness, so Réaumur styled them "nimble-footed." They are
active by night, when they essay to enter the hive and deposit their
one or two hundred eggs. If the females are held in the hand they
will often extrude their eggs; in fact, they have been known to do this
even after the head and thorax were severed from the abdomen, and
still more strange, while the latter was being dissected.
Fig. 107.

Male. Female.

It is generally stated that these are two-brooded, the first moths


occurring in May, the second in August. Yet, as I have seen these
moths in every month from May to September, and as I have proved
by actual observation that they may pass from egg to moth in less
than six weeks, I think under favorable conditions there may be even
three broods a year. It is true that the varied conditions of
temperature—as the moth larvæ may grow in a deserted hive, in one
with few bees, or one crowded with bee life—will have much to do
with the rapidity of development. Circumstances may so retard
growth and development that there may not be more than two, and
possibly, in extreme cases, more than one brood in a season.
It is stated by Mr Quinby that a freezing temperature will kill these
insects in all stages, while Mr. Betsinger thinks that a deserted hive
is safe, neither of which assertions are correct. I have seen hives,
whose bees were killed by the severe winter, crowded with moth
pupæ or chrysalids the succeeding summer. I have subjected both
larvæ and pupæ to the freezing temperature without injuring them. I
believe, in very mild winters, the moth and the chrysalids might be so
protected as to escape unharmed, even outside the hive. It is
probable too, that the insects may pass the winter in any one of the
various stages.

HISTORY.

These moths were known to writers of antiquity, as even Aristotle


tells of their injuries. They are wholly of oriental origin, and are often
referred to by European writers as a terrible pest. Dr. Kirtland, the
able scientist, the first President of our American Bee Convention,
whose decease we have just had to mourn, once said in a letter to
Mr. Langstroth, that the moth was first introduced into America in
1805, though bees had been introduced long before. They first
seemed to be very destructive. It is quite probable, as has been
suggested, that the bees had to learn to fear and repel them; for,
unquestionably, bees do grow in wisdom.—In fact, may not the
whole of instinct be inherited knowledge, which once had to be
acquired by the animal. Surely bees and other animals learn to battle
new enemies, and vary their habits with changed conditions, and
they also transmit this knowledge and their acquired habits to their
offspring, as illustrated by setter and pointer dogs. In time, may not
this account for all those varied actions, usually ascribed to instinct?
At least, I believe the bee to be a creature of no small intelligence.

REMEDIES.

In Europe, late writers give very little space to this moth. Once a
serious pest, it has now ceased to alarm, or even disquiet the
intelligent apiarist. In fact, we may almost call it a blessed evil, as it
will destroy the bees of the heedless, and thus prevent injury to the
markets by their unsalable honey, while to the attentive bee-keeper it
will work no injury at all. Neglect and ignorance are the moth
breeders.
As already stated, Italian bees are rarely injured by moths, and
strong colonies never. As the enterprising apiarist will only possess
these, it is clear that he is free from danger. The intelligent apiarist
will also provide, not only against weak, but queenless colonies as
well, which from their abject discouragement, are the surest victims
to moth invasion. Knowing that destruction is sure, they seem, if not
to court death, to make no effort to delay it.
In working with bees, an occasional web will be seen glistening in
the comb, which should be picked out with a knife till the
manufacturer—the ruthless larva—is found, when it should be
crushed. Any larva seen about the bottom board, seeking a place to
spin its cocoon, or any pupæ, either on comb or in crack, should also
be killed. If, through carelessness, a colony has become hopelessly
victimized by these filthy, stinking, wax devourers, then the bees and
any combs not attacked should be transferred to another hive, after
which the old hive should be sulphured by use of the smoker, as
before described (page 216), then by giving one or two each of the
remaining combs to strong colonies, after killing any pupæ that may
be on them, they will be cleaned and used, while by giving the
enfeebled colony brood, if it has any vigor remaining, and if
necessary a good queen, it will soon be rejoicing in strength and
prosperity.
We have already spoken of caution as to comb honey and
frames of comb (page 216), and so need not speak further of them.

BEE KILLER—Asilus Missouriensis, Riley.

This is a two-winged fly, of the predacious family Asilidæ, which


attacks, and takes captive the bee and then feeds upon its fluids. It is
confined to the southern part of our country.
The fly (Fig, 108) has a long, pointed abdomen, strong wings,
and is very powerful. I have seen an allied species attack and
overcome the powerful tiger-beetle, whereupon I took them both with
my net, and now have them pinned, as they were captured, in our
College cabinet. These flies delight in the warm sunshine, are very
quick on the wing, and are thus not easily captured. It is to be hoped
that they will not become very numerous. If they should, I hardly
know how they could be kept from their evil work. Frightening them,
or catching with a net might be tried, yet these methods would irritate
the bees, and need to be tried before they are recommended. I have
received specimens of this fly from nearly every Southern State.
There are very similar flies North, belonging to the same genus, but
as yet we have no account of their attacking bees, though such a
habit might easily be acquired, and attacks here would not be
surprising.
Fig. 108.

BEE-LOUSE—Branla Cœca, Nitsch.

Fig. 109.

Larva.
Imago.
This louse (Fig, 109) is a wingless Dipteron, and one of the
uniques among insects. It is a blind, spider-like parasite, and serves
as a very good connecting link between insects and spiders, or, still
better, between the Diptera, where it belongs, and the Hemiptera,
which contains the bugs and most of the lice. It assumes the semi-
pupa state almost as soon as hatched, and strangest of all, is,
considering the size of the bee on which it lives, and from which it
sucks its nourishment, enormously large. Two or three, and
sometimes even more, (the new Encyclopedia Britannica says 50 or

You might also like