Click here to Skip to main content
15,880,972 members
Articles / Database Development / SQL Server

GPS Tracer Extension: storing the path on SQL2005 via Web Services

Rate me:
Please Sign up or sign in to vote.
4.53/5 (9 votes)
7 Sep 20075 min read 33.6K   427   33  
This article extends Leonardo Salvatore's project "A GPS tracer application for Windows Mobile CE 5" using the Web Service Software Factory. It shows how to create a robust solution for storing the path on a DB server, using Web Services and SQL
<!--------------------------------------------------------------------------->  
<!--                           INTRODUCTION                                

 The Code Project article submission template (HTML version)

Using this template will help us post your article sooner. To use, just 
follow the 3 easy steps below:
 
     1. Fill in the article description details
     2. Add links to your images and downloads
     3. Include the main article text

That's all there is to it! All formatting will be done by our submission
scripts and style sheets. 

-->  
<!--------------------------------------------------------------------------->  
<!--                        IGNORE THIS SECTION                            -->
<html>
<head>
<title>The Code Project</title>
<Style>
BODY, P, TD { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt }
H2,H3,H4,H5 { color: #ff9900; font-weight: bold; }
H2 { font-size: 13pt; }
H3 { font-size: 12pt; }
H4 { font-size: 10pt; color: black; }
PRE { BACKGROUND-COLOR: #FBEDBB; FONT-FAMILY: "Courier New", Courier, mono; WHITE-SPACE: pre; }
CODE { COLOR: #990000; FONT-FAMILY: "Courier New", Courier, mono; }
</style>
<link rel="stylesheet" type=text/css href="http://www.codeproject.com/styles/global.css">
</head>
<body bgcolor="#FFFFFF" color=#000000>
<!--------------------------------------------------------------------------->  


<!-------------------------------     STEP 1      --------------------------->
<!--  Fill in the details (CodeProject will reformat this section for you) -->

<pre>
Title:       GPS Tracer Extension: storing the path on SQL2005 via Web Services
Author:      Lorenzo Consegni
Email:       lorenzo.consegni@giuneco.it
Member ID:   3760874 
Language:    C# 2.0
Platform:    Windows, .NET 2.0 
Technology:  Web Service Software Factory, .NET Guidance, SQL Server 2005
Level:       Intermediate
Description: This article extends, using the Web Service Software Factory, the Leonardo Salvatore's project "A GPS tracer application for Windows Mobile CE 5". It shows how to create a robust solution for storing the path on a DB server, using Web Services and SQL Server 2005 (in a very fast way).
Section      General C#
SubSection   C# Data Base, C# Web Services
</pre>

<!-------------------------------     STEP 2      --------------------------->
<!--  Include download and sample image information.                       --> 

<ul class=download>
<li><a href="GpsTracerServer.zip">Download source - 70 Kb</a></li>
</ul>

<p><img src="Article.gif" alt="Sample Image - maximum width is 600 pixels" width=400 height=200></p>


<!-------------------------------     STEP 3      --------------------------->
<!--  Add the article text. Please use simple formatting (<h2>, <p> etc)   --> 

<h2>Introduction</h2>

<p>In this article we want to add a simple extension to the project seen in the CodeProject article �A GPS tracer application for Windows Mobile CE 5�. We want to create a Web Service which can be invoked by the mobile application to store, on a remote SQL2005 Data Base, the path followed by different GPS devices. The easiest and fastest way to achieve this result is represented by the Web Service Software Factory (next WSSF for short). This strategy is, at the same time, the best way to build higher quality service using well known pattern and practices.

<h2>Background (optional)</h2>

<p>A GPS tracer application for Windows Mobile CE 5; Web Services Software Factory

<h2>Using the code</h2>

<p>Our goal is incredibly simple: we just want to store an ordered collection of GPS coordinates (a path) sent by a mobile device. Obviously we desire to distinguish between different devices, and respective paths, which can send information contemporarily.

<p>First of all I created two tables in a DB named <code>GpsTracer</code>: the tables are <code>Device</code> and <code>LocationEntry</code> and are defined by the following sql statements

<pre>
CREATE TABLE [dbo].[Device](
	[ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Device_ID]  DEFAULT (newid()),
	[CreationDate] [datetime] NOT NULL,
	[LastLoginDate] [datetime] NOT NULL,
 CONSTRAINT [PK_Device] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

GO

CREATE TABLE [dbo].[LocationEntry](
	[ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_LocationEntry_ID]  DEFAULT (newid()),
	[IDDevice] [uniqueidentifier] NOT NULL,
	[Latitude] [float] NULL,
	[Longitude] [float] NULL,
	[WhenInserted] [datetime] NULL,
	[Speed] [float] NULL,
	[Quote] [float] NULL,
	[Heading] [float] NULL,
 CONSTRAINT [PK_LocationEntry] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]GO
ALTER TABLE [dbo].[LocationEntry]  WITH CHECK ADD  CONSTRAINT [FK_LocationEntry_Device] FOREIGN KEY([IDDevice])
</pre>

<p>This structure is quite simple but it�s enough powerful for our purpose: we just want to collect the devices connected (identified by their Guid) and their first and last connection to the system (device table); we want to know the paths they have ever followed (LocationEntry table).  Please note that structure and tables of the DB are the foundation of the solution built with the WSSF (and not only with that! ;)) so we suggest thinking them carefully before starting with the code generation: of course, due to the nature of this �demo-project�, we can go on.
<p>After the DB definition the biggest part of the rough work is done by the WSSF. Once we created, in Visual Studio, a new project of type �Web Service Software Factory (ASMX)�, we should follow these steps (please refer to the Visual Studio Guidance Navigator window and it�s �recipes� for more details; please remember to rebuild solution between the steps):
<p>-	Connect the infrastructure to the DB in the Service project: a connection string is added to the web.config file
<p>-	Create The CRUD Stored Procedure for the DB tables in the Data Access Project: a sql statement file is generated (see GpsTracerStoredCreation.sql)
<p>-	Create the Business Entities based on the DB tables in the Business Entity project: the classes Device and LocationEntry are created
<p>-	Create the Data Repository Classes from Business Entities in the Data Access Project: the classes for connecting the entities and the DB are created.
<p>-	Create a Data Type accepted by the Web Service: the objects of this type will be the ones sent by the mobile application to the web server and they will contain all the information needed for the insertion of a �footstep� (a single step in the gps path) in the DB. In our case the type �DeviceAndLocation� contains the fields of both the DB tables: deviceID, deviceCreationDate, deviceLastLoginDate, locationEntryLatitude, locationEntryLongitude and so on.
<p>-	Create a Service Contract in the corresponding project: this is the signature of the Web Method that will be created. In our example it is named SendDeviceAndLocation, it returns a Boolean and has one input parameter of type DeviceAndLocation.
<p>-	Create the Service Contract Translators from the data type to the Business Entities. In our example this direction is enough because our application just receives data from the mobile devices. We define two translators: one from the data type to the device BE and one from the data type to the location BE. 
<p>-	Add business logic to our solution: in our simple solution we add the class DeviceAndLocationBLL with the single method AcquireDeviceAndLocation (see code described below).
<p>-	Generate the Service Implementation:  here we can finally implement our service (see code described below).
<p>-	Expose the service: the asmx file is generated.
<p>-	Add web reference and implement a test, in the windows form test project, to check if insertion goes well!

<h2>Points of Interest</h2>

<p>The few lines of code that we have to write are related to the method in the business logic and the service method. Let�s start with the BLL. 
<p>This method checks if the device that sends informations is already in the Device table: if it�s present then we update its last login date, else we insert it into the table.
<p>Its peculiarity consists in the use of the GetAllFromDevice (automatically created as Data Repository Classes from the CRUD stored procedures) which result is filtered with the find method of a �generics list�. The Predicate of the find method is an anonimous delegate that checks if the ID of the input device parameter �fits� to an element of the list. Please note that the method is STATIC: a class method is prefereble for the performances and we don�t need to mind to atomicity of operations due to the use of the DB.
<pre>
    public class DeviceLocationBll
    {
        public static bool AcquireDevice(Device inDev, LocationEntry inLoc)
        {
            DeviceRepository devRep = new DeviceRepository("GpsTracer"); 
		//"GpsTracer" is the name of the connection string in web.config

            List<Device> listDev = devRep.GetAllFromDevice();


            Device devResult = listDev.Find(
                new Predicate<Device>(
                    delegate(Device devv)
                    {
                        return devv.ID == inDev.ID;
                    }
                )
            );
            if (devResult == null)
            {
                devRep.Add(inDev);
            }
	    Else
	    {
		devResult.LastLoginDate = DateTime.Now();
	    }

            LocationEntryRepository locRep = new LocationEntryRepository("GpsTracer");
            locRep.Add(inLoc);
            
            return true;
        }
    }

</pre>

<p>The service implementation is quite easy: we just need to translate the object received from the web and pass the results to the AcquireDevice method.
<pre>
public bool SendDeviceAndLocationInfos(GpsTracerServer.DataTypes.DevicePlusLocationType SendDeviceAndLocationInfosRequest)
        {
            BusinessEntities.Device dev = TranslateBetweenDevicePlusLocationTypeAndDevice.TranslateDevicePlusLocationTypeToDevice(SendDeviceAndLocationInfosRequest);
            BusinessEntities.LocationEntry loc = TranslateBetweenDevicePlusLocationTypeAndLocationEntry.TranslateDevicePlusLocationTypeToLocationEntry(SendDeviceAndLocationInfosRequest);

            return DeviceLocationBll.AcquireDevice(dev,loc);
        }
</pre>

<p>A very simple test implementation in the windows form is the following: we instantiate the proxy class which is needed to translate our DeviceAndLocation to the corresponding soap packet.

<pre>
private void ExecuteButton_Click(object sender, EventArgs e)
{
	//TODO: Call proxy method
	GpsTracerServiceContract ws = new GpsTracerServiceContract();

	DeviceAndLocation testDev = new DeviceAndLocation ();
	testDev.DeviceID = new Guid().ToString();
	testDev.DeviceCreationDate = DateTime.Now;
	testDev.DeviceLastLoginDate = DateTime.Now;
	testDev.LocationHeading = 10;
	testDev.LocationLatitude = 11;
	testDev.LocationLongitude = 12;
	testDev.LocationQuote = 13;
	testDev.LocationSpeed = 14;
	testDev.LocationWhenInserted = DateTime.Now;

	ws.SendDeviceAndLocationInfos(testDev);
}
</pre>

<p>
In this article we put the hands on the Web Service Software Factory and the result is a simple web service based on a robust, extensible, well engineered foundation. We just emphasize that the all solution can be built in 15 minutes and with a few lines of code.


<h2>History</h2>

<p>Nothing to add... at this moment! :)


<!-------------------------------    That's it!   --------------------------->
</body>
</html>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions