Sunday, March 29, 2009

lobal Positioning System (GPS) is a world-wide navigational system that can tell you with pinpoint accuracy your exact current location. GPS has been around for many years and has many applications both in the commercial sector as well as in the military. The best part of GPS is that it is free to use—simply purchase a GPS receiver (prices range from $100 to $10,000+ for complex devices) and equip it with the necessary software and you will soon be using it to help you navigate unfamiliar territory.
While route navigation is one of the most popular uses of GPS, another good use is helping you track the whereabouts of your inventory, such as delivery trucks and goods. In this article, I will build a GPS tracking system that allows you to track the whereabouts of your delivery trucks, using a Windows Mobile 5.0 Pocket PC device and a Bluetooth-enabled GPS receiver.
The tracking system comprises:
A Windows Mobile 5.0 Pocket PC mounted in a truck; it is also connected to the Internet via GPRS (General Packet Radio Services)
A Bluetooth-enabled GPS receiver that is paired with the Pocket PC
A Pocket PC application that displays the latitude and longitude of its current position; it also shows the speed at which the truck is moving
A back end server hosted on a Web server that collects the positional data
A server-side application that receives the data and displays the map of the location the truck is currently at, thereby allowing real-time monitoring.shows what the server application will look like. As you can see, it can monitor two trucks at the same time and it uses Microsoft Virtual Earth for mapping.
The server application you will build in this article monitors two trucks at the same time in side-by-side maps.
I chose the iMate JasJar as my Pocket PC device and the Holux GPSlim 236 as my GPS receiver.There are two main components you will build in this article:
A Pocket PC application that retrieves and displays GPS data from the GPS receiver
A server that receives the positional data sent by the Pocket PC application and then displays the map of the corresponding location What you needTo create this application you'll need:
A Windows Mobile 5.0 Pocket PC (Phone Edition) that supports Bluetooth connectivity; in addition, the device must be connected to the Internet via GPRS
A Bluetooth-enabled GPS receiver shows the hardware I selected for my implementation: The iMate JasJar Pocket PC and the Holux GPSlim 236 GPS receiver.
You need to pair up the Windows Mobile device with the GPS receiver using Bluetooth. Once they are paired, remember to establish a serial connection between the two devices. For my device, I selected COM4 as the serial port.
Author's Note: Due to the different setup procedures for different devices, I will not attempt to show the steps to set up the serial port. Check the documentation of your device for more information.
Creating the Pocket PC ApplicationUsing Visual Studio 2005, create a Windows Mobile 5.0 Pocket PC application and name it C:\GPSTracking Author's Note: In order to select the Windows Mobile 5.0 Pocket PC item in the Project types listview, you need to make sure you've downloaded the Windows Mobile 5.0 SDK for Pocket PC ().
Populate the default Form1 with the following
Label
TextBox (set the Multiline property to True and the ScrollBars property to Both)
MainMenu
Create a Windows Mobile 5.0 Pocket PC project using Visual Studio.
opulate the default Form1 with the various controls as shown.Switch to the code-behind of Form1 and declare the following member variables:
serialPort to connect to the GPS receiver via the serial connection
ServerIP to store the IP address of the server
ID to store the ID of the user
Public Class Form1
'---serial port to connect to the GPS receiver---
Private WithEvents serialPort As New IO.Ports.SerialPort
'---IP address of the server---
Private ServerIP As String = "10.0.1.4"
'---the ID of the user---
Private ID As String = "1"
In the event handler for the "Connect GPS" menu item, configure the serial port variable with the necessary parameters and then open the connection:
'---Connect GPS---
Private Sub MenuItem1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MenuItem1.Click
'---close the port if it is already open---
If serialPort.IsOpen Then
serialPort.Close()
End If
'---set the parameters and open the port---
Try
With serialPort
.PortName = "COM4"
.BaudRate = 9600
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
End With
serialPort.Open()
'---disable the Connect GPS menu item---
MenuItem1.Enabled = False
'---enable the Disconnect menu item---
MenuItem3.Enabled = True
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
To receive incoming data from the GPS receiver, you need to service the DataReceived event of the SerialPort class:
Private Sub DataReceived( _
ByVal sender As Object, _
ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
Handles serialPort.DataReceived
TextBox1.BeginInvoke(New _
myDelegate(AddressOf updateTextBox), _
New Object() {})
End Sub
Here, I have used a delegate (myDelegate) to update the TextBox controls using the received data from the GPS receiver:
Public Delegate Sub myDelegate()
Public Sub updateTextBox()
TextBox1.Text += serialPort.ReadExisting()
Dim lines() As String = TextBox1.Text.Split(vbLf)
If lines.Length <>= 500 Then
'---clear until the last $---
TextBox1.Text = _
TextBox1.Text.Substring(TextBox1.Text.LastIndexOf("$"))
End If
If lines(lines.Length - 2).StartsWith("$GPGGA") Or _
lines(lines.Length - 2).StartsWith("$GPRMC") Then
processGPSData(lines(lines.Length - 2))
End If
End Sub
One tricky issue with the GPS receiver is that data is not received in discrete blocks. For example, instead of receiving the following two lines of data in two discrete blocks:
$GPGGA,001431.092,0118.2653,N,10351.1359,E,0,00,,-19.6,M,4.1,M,,0000*5B
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
The data may arrive in four separate blocks (the end of each of the two lines will be appended with characters 13 and 10 (new-line characters)):
$GPGGA,001431.092,0118.2653,N,
10351.1359,E,0,00,,-19.6,
M,4.1,M,,0000*5B
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
Tip: Using the ReadLine() method of the SerialPort class seems like it will do the trick. However, in practice it does not work and often chokes on the receiving data.
Append all received GPS data to the TextBox control.A good workaround is to append all incoming data to a TextBox control and manually retrieve the necessary data that you want to process. As illustrated in the latest data is always located at the bottom of the TextBox control. As the last line may contain incomplete GPS data, you should only examine the second-to-last line. You will do so by splitting the entire contents of the TextBox control into a string array (using the vbLf character as delimiter) and then examining the penultimate element in the array.
As the TextBox has a maximum limit on the number of characters it can store, you need to constantly clear it after a certain number of characters. To improve performance, ideally you should not leave too much data in the TextBox control as the splitting of its content into an array requires additional processing time.

n two of my earlier articles for DevX, "Teach Your Old Web Cam New Tricks: Use Video Captures in Your .NET Applications" and "Building an Enhanced Security System with a Web Cam and a Servo," I showed how to incorporate your web cam into your .NET applications and use it for surveillance purposes. However, using those solutions, the videos can only be viewed locally on the computer running the web cam. An interesting enhancement would be to extend the applications so that the video can be viewed remotely over the Internet.
And so, in this article I will show you how to use socket communication to send a live video image from a server to remote clients. The sample applications built in this article consists of:
A server that displays the video captured by a web cam
A client that receives the live video image from the server
The server will allow multiple clients to connect to it at the same time. Among other things, it is a useful application for the home environment where you can use it in your office to monitor your home or kids.
Creating the ServerI'll first create the server. Using Visual Studio 2005, create a new Windows application and name it RemoteMonitoring. In the default Form1, add a PictureBox control and set its properties as follows:
Size—449, 253
SizeMode—StretchImage

With the release of Visual Studio 2008, Microsoft has also updated the VB language to the latest version, 9.0. VB 9.0 boasts several key language enhancements that have been made to support the new Language Integrated Query (LINQ) feature that Microsoft has announced earlier. Part 2 of this series picks up where Part 1 left off, walking you through VB 9.0's new LINQ support features and providing code examples that illustrate how to use them.
LINQOne of the key additions to the .NET Framework v3.5 is the support for Language Integrated Query (LINQ). LINQ allows you to manipulate data just like you manipulate database records—using a query language, like SQL. So, whereas before you had to write complex iterative loops to retrieve data, you can now just specify data declaratively using LINQ and the compiler does all the work for you.
LINQ to ObjectsLINQ to Objects allows you to use LINQ to query any IEnumerable or IEnumerable(Of t) collections directly. For example, suppose you have a collection of data stored in an array and you want to retrieve a subset of the data quickly. In the old days, you'd write a loop and iteratively retrieve all the data matching your criteria. This is time-consuming because you'd have to write all the logic to perform the comparison, etc. Using LINQ, you can declaratively write the condition using an SQL-like statement and the compiler will do the job for you. Let's use a real-life example. Suppose you have an array of type String that contains a list of names:
Dim AllNames As String() = _
{"Jeffrey", "Kirby", "Gabriel", "Philip", "Ross", "Adam", _
"Alston", "Warren"}
Now suppose you need to print out all the names in this array that start with the letter "G." In this case, you can set up a loop and iteratively perform a comparison on each name. Things start to get more complex when you have more complicated filtering rules. Using LINQ, you could specify the filter using the From clause, like this:
Dim FoundNames As IEnumerable(Of String) = _
From Name In AllNames Where Name.StartsWith("G")
When this statement has been executed, FoundNames will now contain a collection of names that starts with the letter "G." It this case, it returns "Gabriel." You can now add the names to a ListBox control:
For Each PeopleName In FoundNames
ListBox1.Items.Add(PeopleName)
Next
You can also use a more complex filter:
Dim FoundNames As IEnumerable(Of String) = _
From Name In AllNames Where Name.StartsWith("G") Or _
Name.Contains("by") Order By Name
In this case, FoundNames will now contain "Gabriel, Kirby." Note that the result is also sorted. Another useful application of LINQ is to manipulate Windows Forms controls. Suppose you have a large number of controls on your form and you want to uncheck all the CheckBox controls without setting each one individually. You can use the following code with LINQ:
'---retrieve all the checkbox controls in the current form---
Dim checkboxes As IEnumerable = _
From ctrl In Me.Controls Where TypeOf ctrl Is CheckBox
For Each c As CheckBox In checkboxes
c.Checked = False
Next

Companies providing Internet-based applications are facing many challenges today. Users increasingly expect access to rapidly expanding amounts of data from anywhere, at any time, and from any device. The size, scale of use, and variety of forms of data are expanding rapidly. Developers need to rapidly build and deploy applications to keep up with these growing demands. Using the traditional on-premise data management model, meeting these needs demands constant investment in and management of servers, operating systems, storage, and networking. IT and operational staff must constantly monitor the infrastructure to ensure that capacity, performance, and availability are maintained as data volumes and user loads increase.
Cloud database services, such as SDS, provide an improved way to respond to these challenges. SDS is built on three key tenets: storage for all data types from birth to archiving, rich data processing services, and operational excellence.
From a developer's perspective, SDS offers a simple programming model, using standard Internet protocols, and simple deployment options. SDS simplifies the process of creating, prototyping, and deploying applications that integrate data across the enterprise. SDS removes infrastructure obstacles, thereby giving developers more freedom to innovate and experiment with new ways of sharing data.
From the IT management perspective, SDS offers a systematic and secure cloud-deployed solution that integrates with your on-premise assets and gives the IT organization oversight and control of distributed data assets. SDS is built on the same SQL Server technologies already used and proven in on-premise deployments to provide high availability, reliability, and security.
From the business perspective, SDS offers a cost-effective approach for managing data, with a flexible consumption based pricing plan, near zero capital and operational expenditures, and the ability to quickly and easily scale up or down as your needs change.
If you are planning to build applications on large or shared data sets, provide on-demand scalable data storage, or augment your on-premise data infrastructure with low cost, rapidly provisioned cloud-based storage, SDS can provide a robust and cost-effective solution.
SQL Data Services are an essential part of Microsoft's Cloud Services strategy and architecture, as illustrated

SDS offers a valuable supplement to on-premise data management models in the areas of flexibility and scalability, reliability and security, and developer agility. Let's begin by looking at some of these features.
Fast provisioning
When you use the traditional on-premise data infrastructure, your ability to prototype or roll out new data-driven solutions can be slowed by the time it takes to deploy and secure servers, network components, and software. With a cloud-deployed solution such as SDS, you can provision your data storage needs in minutes.
Flexible development model
SDS exposes Web services that you can use to create, modify, query, and delete data entities. The SDS Web services currently support the two primary standards-based communications protocols, SOAP (Simple Object Access Protocol) and REST (Representational State Transfer). This ensures that you can interact with SDS from almost any programming environment, not just Microsoft-based tools, and provides cross-platform compatibility to support existing solutions and mashups. Data retrieval is accomplished through a simple, text-based query syntax using the Language Integrated Query (LINQ) style. SDS is also compatible with ADO.NET Data Services, and exposes an ADO.NET Data Services interface.
Flexible data model
SDS provides a flexible data model that does not require schemas or fixed data types. Rather than creating database tables with fixed columns, in SDS you can create data containers that can store either homogeneous or heterogeneous data entities. This flexibility gives you the ability to handle any data scenario, regardless of whether you're storing schematized relational data or totally unstructured collections of properties. This model is especially useful when you design applications in which many different users will be providing data (such as content management or collaboration), or when you create applications that many different people will use, each of whom will have somewhat different data needs (such as customer relationship management).
Unlimited scalability
SDS enables you to store any amount of data, from kilobytes to terabytes. The service scales with your data, so you can allow your data to grow without worrying about capacity limitations. A pay as you grow pricing model ensures that you only pay for the storage you use, so you can also scale down the service when you don't need it. When compared to a hosted or on-premise solution, this means that your utilization is always optimal (never over-utilized so you can't meet demand, and never under-utilized so you are paying for inefficiency).
You can harness this scalability to build the next generation of Internet-scale applications with worldwide reach, but without the infrastructure costs and management overhead.
High availability
SDS is built on robust and proven Microsoft Windows Server® and SQL Server technologies, and is flexible enough to cope with any variations in usage and load. The service stores multiple copies of your data to ensure data availability and business continuity. Published service level agreements (SLAs) will guarantee a business-ready service.
Secure data access
SDS offers secure data storage, together with secure access over Secure Sockets Layer (SSL) channels, thereby enabling you to meet business and regulatory requirements for confidentiality and privacy.
Synchronization and offline scenarios
SDS integrates with the Microsoft Sync Framework to support occasionally-connected synchronization scenarios. For example, using SDS and the Sync Framework, on-premise applications and client devices can synchronize with each other via a common data hub in the cloud.

VB
isual Basic 9 has a new set of language features that allows developers to work with XML in a much more productive way using a new API called "LINQ to XML."LINQ stands for "Language Integrated Query," and it lets you write queries for objects, databases, and XML in a standard way. Visual Basic provides deep support for LINQ to XML through XML literals and XML axis properties. These features let you use a familiar, convenient syntax for working with XML in your Visual Basic code. LINQ to XML is a new, in-memory XML programming API specifically designed to leverage the LINQ framework. Even though you can call the LINQ APIs directly, only Visual Basic allows you to declare XML literals and directly access XML axis properties. This article will help you master these new Visual Basic XML features.XML Literals and Embedded ExpressionsTraditionally, when working with XML in code you would use the XML Document Object Model (XML DOM), and call its API to manipulate objects representing the structure of your XML. This API is document-centric, which does not lend itself well to creating XML with LINQ. In addition it uses the XPath language, which is unnecessary when using LINQ—as you will soon see. Another way to work with XML would be to drop out of Visual Basic code altogether and manipulate XML using XSLT, XQuery, or XPath directly.With the release of the .NET Framework 3.5, the LINQ to XML API allows developers to work with XML in a much more intuitive way, taking a top-down, element-centric approach. Additionally, in Visual Basic 9 (VB9) you can use XML literals to embed XML directly into your code and bring an even more WYSIWYG approach to XML programming. For example, the following code is perfectly legal in VB9: Dim myXml =

This is XML

The runtime infers that the myXml variable is an XDocument object in this case (XDocument is a class in the LINQ to XML API that, in many cases, performs much better than the XML DOM). Type inference is another new feature of VB9 that supports LINQ. The compiler can infer the types of local variables by evaluating the right-hand side of the assignment. In previous versions of Visual Basic, the preceding statement would produce a type of Object; but with the new Option Infer flag set to ON in VB9, the statement above is now the same as declaring the XDocument type explicitly, so your code still benefits from compile-time checks. As you can see there is no conceptual barrier between the code you write and the XML you're trying to express when using XML literals in VB9.In the editor, you can see XML syntax coloring, which indicates that Visual Basic recognizes this XML literal as a supported data type. As you type the beginning tag of the element, Visual Basic will automatically insert the end tag and format the XML. If you change the name of the element's beginning tag, Visual Basic updates the end tag to match. Also note that underscores are not necessary in multiline XML literals.XML literals get much more interesting when you use them with embedded expressions. Embedded expressions let you write any Visual Basic expression and have it evaluated directly in the literal. These expressions are compiled code, not script, so you benefit from the same compile-time syntax checks and editor experience you're accustomed to when writing programs in Visual Basic. The syntax you use is <%= expression %>. For example, using the simple literal above you could embed an expression in the element to write out the current date and time inside the element instead: Dim myXml =
<%= Now() %>

Notice that this example doesn't start with the XML declaration; instead VB9 infers this to be an XElement object, the fundamental class in the LINQ to XML API. XML trees are made up of these XElement objects. This is just a simple example; there's no practical limit to the number of embedded expressions you can include in XML literals. You can also nest embedded expressions any number of levels deep.Here's an example of a LINQ query that queries the files in the current directory and creates an XML output document using XML literals and embedded expressions. Dim myXml = _

<%= From FileName In _ My.Computer.FileSystem.GetFiles(CurDir()) _ Let File = _ My.Computer.FileSystem.GetFileInfo(FileName) _ Select _ >

<%= File.Name %>


<%= File.CreationTime %>


<%= File.LastWriteTime %>


<%= File.DirectoryName %>

%>

myXml.Save("MyFiles.xml")
The preceding code produces XML something like this:

customers.html

2007-10-07T15:57:00.2072384-08:00


2007-10-22T14:46:48.6157792-07:00

C:\temp


orders.xml

2007-10-07T15:57:00.2773392-08:00


2007-10-27T12:01:00.3549584-07:00

C:\temp


plants.xml

2007-10-07T15:57:00.147152-08:00


2007-10-18T18:25:07.2607664-07:00

C:\temp


Notice in the example that you first start writing an XML literal and then embed a LINQ query that selects a collection of XElements to create the document. You can nest embedded expressions this way to create very complex documents in a much more intuitive way. This example creates the XML from the top down—just as you would read it. This feature lets you be much more productive using the LINQ to XML API than its predecessor, the XML DOM, which forced you to think in terms of its API instead of the actual XML you're trying to express.