Source Code SilverlightEdition ProjectTemplates VehicleTracking CS.zip
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MapSuiteVehicleTracking.Web.Default" %>
<%@ Register Assembly="SilverlightMapConnector" Namespace="ThinkGeo.MapSuite.SilverlightEdition"
TagPrefix="cc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Vehicle Tracking</title>
<style type="text/css">
html, body, form
{
height: 100%;
}
body
{
margin: 0px;
overflow: hidden;
}
</style>
<script type="text/javascript">
var updateSize = function (withTree) {
var sw = parseInt(document.body.scrollWidth);
var sh = parseInt(document.body.scrollHeight);
var sourceDiv = $get('sourceDiv');
if (withTree) {
sw -= 253;
sh -= 125;
sourceDiv.style.left = 253;
} else {
sourceDiv.style.left = 4;
}
sourceDiv.style.width = sw + 'px';
sourceDiv.style.height = sh + 'px';
}
var hide = function () {
var sourceDiv = $get('sourceDiv');
sourceDiv.style.display = 'none';
}
var show = function (srcUri) {
var div = $get('sourceDiv');
var iframe = $get('sourceFrame');
iframe.src = srcUri;
div.style.display = 'block';
}
</script>
<script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript">
function onSilverlightError(sender, args) {
var appSource = "";
if (sender != null && sender != 0) {
appSource = sender.getHost().Source;
}
var errorType = args.ErrorType;
var iErrorCode = args.ErrorCode;
if (errorType == "ImageError" || errorType == "MediaError") {
return;
}
var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n";
errMsg += "Code: " + iErrorCode + " \n";
errMsg += "Category: " + errorType + " \n";
errMsg += "Message: " + args.ErrorMessage + " \n";
if (errorType == "ParserError") {
errMsg += "File: " + args.xamlFile + " \n";
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
else if (errorType == "RuntimeError") {
if (args.lineNumber != 0) {
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
errMsg += "MethodName: " + args.methodName + " \n";
}
throw new Error(errMsg);
}
</script>
</head>
<body onload="updateSize(true)">
<form id="form1" runat="server" style="height: 100%">
<div id="silverlightControlHost" style="height: 100%">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<cc1:SilverlightMapConnector ID="SilverlightMapConnector1" runat="server" Windowless="true"
Width="100%" Height="100%" Source="~/ClientBin/MapSuiteVehicleTracking.xap">
</cc1:SilverlightMapConnector>
<div id="sourceDiv" style="position: absolute; left: 253px; top: 119px; display: none;">
<iframe id="sourceFrame" width="100%" height="100%"></iframe>
</div>
</div>
</form>
</body>
</html>
default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using System.IO;
namespace MapSuiteVehicleTracking.Web
{
public partial class Default : System.Web.UI.Page
{
public static string AccessFilePath;
private static readonly string acessFileName = @"VehicleTrackingDb.mdb";
protected void Page_Load(object sender, EventArgs e)
{
AccessFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), acessFileName);
if (!File.Exists(AccessFilePath))
{
File.WriteAllBytes(AccessFilePath, Properties.Resources.VehicleTrackingDb);
}
}
}
}
Location.cs
using System;
using System.Runtime.Serialization;
using ThinkGeo.MapSuite.Core;
namespace ThinkGeo.MapSuite.VehicleTracking
{
/// <summary>
/// This class specify the basic information for a location.
/// </summary>
[DataContract]
public class Location
{
private double speed;
private double latitude;
private double longitude;
private DateTime dateTime;
public Location()
: this(0, 0, 0, DateTime.Now)
{ }
public Location(double longitude, double latitude, double speed, DateTime dateTime)
{
Longitude = longitude;
Latitude = latitude;
Speed = speed;
DateTime = dateTime;
}
[DataMember]
public double Longitude
{
get { return longitude; }
set { longitude = value; }
}
[DataMember]
public double Latitude
{
get { return latitude; }
set { latitude = value; }
}
[DataMember]
public double Speed
{
get { return speed; }
set { speed = value; }
}
[DataMember]
public DateTime DateTime
{
get { return dateTime; }
set { dateTime = value; }
}
}
}
TrackingAccessProvider.cs
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.OleDb;
using System.Globalization;
using System.Text;
namespace ThinkGeo.MapSuite.VehicleTracking
{
public class TrackingAccessProvider : TrackingDataProvider
{
private OleDbConnection dataConnection;
public TrackingAccessProvider(string databaseFilePath)
{
string connectionString = string.Format(CultureInfo.InvariantCulture, "Provider=Microsoft.Jet.OLEDB.4.0; Data Source='{0}'", databaseFilePath);
dataConnection = new OleDbConnection(connectionString);
}
public override Dictionary<int, Vehicle> GetCurrentVehicles(DateTime currentTime)
{
Dictionary<int, Vehicle> vehiclesList = new Dictionary<int, Vehicle>();
DataSet vehiclesDataSet = ExecuteQuery("Select * from Vehicle");
TimeSpan trackHistoryVehicleTimeSpan = TimeSpan.FromHours(8);
foreach (DataRow row in vehiclesDataSet.Tables[0].Rows)
{
int vehicleId = Convert.ToInt32(row["VehicleId"], CultureInfo.InvariantCulture);
Vehicle vehicle = GetCurrentVehicle(vehicleId, currentTime, trackHistoryVehicleTimeSpan);
vehiclesList.Add(vehicle.Id, vehicle);
}
return vehiclesList;
}
private Vehicle GetCurrentVehicle(int vehicleId, DateTime currentTime, TimeSpan trackHistoryVehicleTimeSpan)
{
string sql = "SELECT A.VehicleName, A.VehicleID, A.VehicleIconVirtualPath, B.Longitude, B.Latitude, B.[Date], B.Speed FROM (Vehicle A LEFT OUTER JOIN Location B ON A.VehicleID = B.VehicleID) WHERE (A.VehicleID = {0}) AND (B.[Date] <= #{1}# and B.[Date]>=#{2}#) ORDER BY A.VehicleID, B.[Date] DESC";
DateTime trackStartTime = currentTime.AddTicks(-trackHistoryVehicleTimeSpan.Ticks);
sql = String.Format(CultureInfo.InvariantCulture, sql, vehicleId, currentTime.ToString(CultureInfo.InvariantCulture), trackStartTime.ToString(CultureInfo.InvariantCulture));
Vehicle currentVechicle = new Vehicle(vehicleId);
DataSet currentLocations = null;
try
{
// Get the locations from current time back to the passed time span
currentLocations = ExecuteQuery(sql);
Collection<double> historySpeeds = new Collection<double>();
for (int rowIndex = 0; rowIndex < currentLocations.Tables[0].Rows.Count; rowIndex++)
{
DataRow dataRow = currentLocations.Tables[0].Rows[rowIndex];
currentVechicle.VehicleIconVirtualPath = dataRow["VehicleIconVirtualPath"].ToString();
double latitude = Convert.ToDouble(dataRow["Latitude"], CultureInfo.InvariantCulture);
double longitude = Convert.ToDouble(dataRow["Longitude"], CultureInfo.InvariantCulture);
double speed = Convert.ToDouble(dataRow["Speed"], CultureInfo.InvariantCulture);
DateTime dateTime = Convert.ToDateTime(dataRow["Date"], CultureInfo.InvariantCulture);
Location currentLocation = new Location(longitude, latitude, speed, dateTime);
historySpeeds.Add(speed);
if (rowIndex == 0)
{
string vehicleName = dataRow["VehicleName"].ToString();
currentVechicle.Location = currentLocation;
currentVechicle.Id = vehicleId;
currentVechicle.VehicleName = vehicleName;
}
else
{
currentVechicle.HistoryLocations.Add(currentLocation);
}
}
}
finally
{
if (currentLocations != null) currentLocations.Dispose();
}
return currentVechicle;
}
public override Collection<string> GetSpatialFences()
{
Collection<string> spatialFences = new Collection<string>();
DataSet dataSet = ExecuteQuery("Select * from SpatialFence");
foreach (DataRow row in dataSet.Tables[0].Rows)
{
string wkt = row["FenceGeometry"].ToString();
string id = row["FeatureID"].ToString();
spatialFences.Add(wkt + "|" + id);
}
return spatialFences;
}
public void DeleteAndUpdateAndInsertSpatialFences(IEnumerable<string> excludeFeatureWktIds)
{
Dictionary<string, string> featureWktIds = new Dictionary<string, string>();
foreach (var item in excludeFeatureWktIds)
{
var array = item.Split('|');
if (array.Length == 2)
{
featureWktIds.Add(array[0], array[1]);
}
}
DeleteSpatialFencesExcluding(featureWktIds.Values.ToList());
foreach (var item in featureWktIds)
{
int result = UpdateSpatialFenceByFeature(item.Key, item.Value);
if (result == 0)
{
InsertSpatialFence(item.Key, item.Value);
}
}
}
public override void DeleteSpatialFencesExcluding(IEnumerable<string> excludeFeatureIds)
{
StringBuilder undeleteFeatureIds = new StringBuilder();
foreach (string undeleteFeatureId in excludeFeatureIds)
{
undeleteFeatureIds.AppendFormat(CultureInfo.InvariantCulture, "'{0}',", undeleteFeatureId);
}
string sql = String.Format(CultureInfo.InvariantCulture,
"DELETE FROM SpatialFence WHERE (FeatureID NOT IN ({0}))", undeleteFeatureIds.ToString().TrimEnd(','));
ExecuteNonQuery(sql);
}
public override int UpdateSpatialFenceByFeature(string wkt, string featureId)
{
int updatedSpatialFenceCount =
ExecuteNonQuery(String.Format(CultureInfo.InvariantCulture,
"UPDATE SpatialFence SET FenceGeometry = '{0}' WHERE (FeatureID = '{1}')", wkt, featureId));
return updatedSpatialFenceCount;
}
public override void InsertSpatialFence(string wkt, string featureId)
{
ExecuteNonQuery(String.Format(CultureInfo.InvariantCulture,
"Insert into SpatialFence(FenceGeometry,FeatureID) values('{0}','{1}')", wkt, featureId));
}
private DataSet ExecuteQuery(string selectCommandText)
{
OleDbDataAdapter dataAdapter = null;
try
{
dataAdapter = new OleDbDataAdapter(selectCommandText, dataConnection);
dataConnection.Open();
DataSet dataSet = new DataSet();
dataSet.Locale = CultureInfo.InvariantCulture;
dataAdapter.Fill(dataSet);
return dataSet;
}
finally
{
if (dataAdapter != null)
{
dataAdapter.Dispose();
}
if (dataConnection != null)
{
dataConnection.Close();
}
}
}
private int ExecuteNonQuery(string cmdText)
{
OleDbCommand dataCommand = null;
int affectedRowNumber = 0;
try
{
dataCommand = new OleDbCommand(cmdText, dataConnection);
dataConnection.Open();
affectedRowNumber = dataCommand.ExecuteNonQuery();
}
finally
{
if (dataCommand != null) dataCommand.Dispose();
if (dataConnection != null) dataConnection.Close();
}
return affectedRowNumber;
}
~TrackingAccessProvider()
{
Dispose(false);
}
public override void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool flag)
{
if (flag)
{
if (dataConnection != null)
{
dataConnection.Close();
dataConnection.Dispose();
dataConnection = null;
}
}
}
}
}
TrackingDataProvider.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace ThinkGeo.MapSuite.VehicleTracking
{
public abstract class TrackingDataProvider : IDisposable
{
public abstract Dictionary<int, Vehicle> GetCurrentVehicles(DateTime currentTime);
public abstract Collection<string> GetSpatialFences();
public abstract void DeleteSpatialFencesExcluding(IEnumerable<string> excludeFeatureIds);
public abstract int UpdateSpatialFenceByFeature(string wkt, string featureId);
public abstract void InsertSpatialFence(string wkt, string featureId);
public abstract void Dispose();
}
}
Vehicle.cs
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
namespace ThinkGeo.MapSuite.VehicleTracking
{
/// <summary>
/// This class stands for a vehicle.
/// </summary>
[DataContract]
public class Vehicle
{
private int id;
private string name;
private string iconPath;
private Location location;
private Collection<Location> historyLocations;
private Vehicle()
: this(0)
{ }
public Vehicle(int id)
{
Id = id;
name = string.Empty;
Location = new Location();
historyLocations = new Collection<Location>();
}
[DataMember]
public int Id
{
get { return id; }
set { id = value; }
}
[DataMember]
public Location Location
{
get { return location; }
set { location = value; }
}
[DataMember]
public Collection<Location> HistoryLocations
{
get { return historyLocations; }
}
[DataMember]
public string VehicleName
{
get { return name; }
set { name = value; }
}
[DataMember]
public string VehicleIconVirtualPath
{
get { return iconPath; }
set { iconPath = value; }
}
public int GetSpeedDuration()
{
int speedDuration = 0;
double lastSpeed = Location.Speed;
foreach (Location tempLocation in HistoryLocations)
{
if (tempLocation.Speed == lastSpeed)
{
speedDuration++;
}
else
{
break;
}
}
return speedDuration;
}
/// <summary>
/// If the Vehicle's speed is not 0 in the passed 4 minutes, we say it is in Motion.
/// </summary>
/// <returns>State of current vehicle.</returns>
public VehicleMotionState GetCurrentState()
{
VehicleMotionState vehicleState = VehicleMotionState.Idle;
if (Location.Speed != 0)
{
vehicleState = VehicleMotionState.Motion;
}
else
{
int locationIndex = 0;
foreach (Location historyLocation in HistoryLocations)
{
if (locationIndex > 3)
{
break;
}
if (historyLocation.Speed != 0)
{
vehicleState = VehicleMotionState.Motion;
break;
}
locationIndex++;
}
}
return vehicleState;
}
}
}
VehicleMotionState.cs
using System.Runtime.Serialization;
namespace ThinkGeo.MapSuite.VehicleTracking
{
/// <summary>
/// This enumeration specifies the Possible states for Vehicles.
/// </summary>
[DataContract]
public enum VehicleMotionState
{
[DataMember]
Motion = 0,
[DataMember]
Idle = 1,
}
}
BooleanToBorderStyleConverter.cs
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows;
using System.Windows.Controls;
namespace ThinkGeo.MapSuite.VehicleTracking
{
public class BooleanToBorderStyleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool)
{
bool result = (bool)value;
Style checkedStyle = new Style(typeof(Border));
checkedStyle.Setters.Add(new Setter(Border.BackgroundProperty, new SolidColorBrush(Color.FromArgb(51, 222, 81, 11))));
checkedStyle.Setters.Add(new Setter(Border.BorderBrushProperty, new SolidColorBrush(Color.FromArgb(136, 136, 136, 136))));
checkedStyle.Setters.Add(new Setter(Border.BorderThicknessProperty, new Thickness(1)));
Style unCheckedStyle = new Style(typeof(Border));
unCheckedStyle.Setters.Add(new Setter(Border.BackgroundProperty, new SolidColorBrush(Colors.Transparent)));
unCheckedStyle.Setters.Add(new Setter(Border.BorderBrushProperty, new SolidColorBrush(Colors.Transparent)));
unCheckedStyle.Setters.Add(new Setter(Border.BorderThicknessProperty, new Thickness(0)));
return result ? checkedStyle : unCheckedStyle;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
}
MapSuiteSampleHelper.cs
using ThinkGeo.MapSuite.SilverlightCore;
using ThinkGeo.MapSuite.VehicleTracking.ServiceReference;
namespace ThinkGeo.MapSuite.VehicleTracking
{
public static class MapSuiteSampleHelper
{
public static int GetSpeedDuration(Vehicle vehicle)
{
int speedDuration = 0;
double lastSpeed = vehicle.Location.Speed;
foreach (Location location in vehicle.HistoryLocations)
{
if (location.Speed == lastSpeed)
{
speedDuration++;
}
else
{
break;
}
}
return speedDuration;
}
/// <summary>
/// If the Vehicle's speed is not 0 in the passed 4 minutes, we say it is in Motion.
/// </summary>
/// <returns>State of current vehicle.</returns>
public static string GetCurrentState(Vehicle vehicle)
{
string result = "Idle";// "In Motion";
if (vehicle.Location.Speed != 0)
{
result = "In Motion";
}
else
{
int locationIndex = 0;
foreach (Location historyLocation in vehicle.HistoryLocations)
{
if (locationIndex > 3)
{
break;
}
if (historyLocation.Speed != 0)
{
result = "In Motion";
break;
}
locationIndex++;
}
}
return result;
}
public static PointShape GetLocationPointShape(Location location)
{
return new PointShape(location.Longitude, location.Latitude);
}
}
}
ViewModelBase.cs
using System;
using System.ComponentModel;
using System.Linq.Expressions;
namespace ThinkGeo.MapSuite.VehicleTracking
{
public class ViewModelBase : INotifyPropertyChanged
{
public ViewModelBase()
{
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
protected virtual void RaisePropertyChanged<T>(Expression<Func<T>> expreesion)
{
RaisePropertyChanged(((MemberExpression)expreesion.Body).Member.Name);
}
}
}
VehicleTrackingViewModel.cs
using System.Collections.ObjectModel;
using System.Linq;
namespace ThinkGeo.MapSuite.VehicleTracking
{
public class VehicleTrackingViewModel : ViewModelBase
{
private string defaultOverlayName;
private UnitSystem selectedUnitSystem;
private Collection<string> overlayNames;
private Collection<UnitSystem> unitSystems;
private ObservableCollection<VehicleViewModel> vehicles;
public VehicleTrackingViewModel()
{
overlayNames = new Collection<string>();
vehicles = new ObservableCollection<VehicleViewModel>();
unitSystems = new Collection<UnitSystem> { UnitSystem.Imperial, UnitSystem.Metric };
selectedUnitSystem = unitSystems[0];
}
public ObservableCollection<VehicleViewModel> Vehicles
{
get { return vehicles; }
}
public Collection<UnitSystem> UnitSystems
{
get { return unitSystems; }
}
public UnitSystem SelectedUnitSystem
{
get { return selectedUnitSystem; }
set { selectedUnitSystem = value; }
}
public Collection<string> OverlayNames
{
get { return overlayNames; }
}
public string DefaultOverlayName
{
get { return string.IsNullOrEmpty(defaultOverlayName) ? overlayNames.FirstOrDefault() : defaultOverlayName; }
set { defaultOverlayName = value; }
}
}
public enum UnitSystem
{
Imperial = 0,
Metric = 1,
}
}
VehicleViewModel.cs
using System.Globalization;
using ThinkGeo.MapSuite.VehicleTracking.ServiceReference;
namespace ThinkGeo.MapSuite.VehicleTracking
{
public class VehicleViewModel : ViewModelBase
{
private string area;
private string speed;
private string status;
private string iconUri;
private string duration;
private string ownerName;
private Vehicle vehicle;
public VehicleViewModel()
: this(null)
{ }
public VehicleViewModel(Vehicle vehicle)
{
ownerName = vehicle.VehicleName;
iconUri = "Image/" + vehicle.VehicleIconVirtualPath;
Vehicle = vehicle;
Load();
}
public Vehicle Vehicle
{
get { return vehicle; }
set { vehicle = value; }
}
public void Load()
{
Status = MapSuiteSampleHelper.GetCurrentState(vehicle);
Speed = vehicle.Location.Speed.ToString(CultureInfo.InvariantCulture) + " mph";
Duration = MapSuiteSampleHelper.GetSpeedDuration(vehicle).ToString(CultureInfo.InvariantCulture) + " min";
}
public string Status
{
get { return status; }
set
{
status = value;
RaisePropertyChanged(() => Status);
}
}
public string IconUri
{
get { return iconUri; }
set
{
iconUri = value;
RaisePropertyChanged(() => IconUri);
}
}
public string Area
{
get { return area; }
set
{
area = value;
RaisePropertyChanged(() => Area);
}
}
public string OwnerName
{
get { return ownerName; }
set
{
ownerName = value;
RaisePropertyChanged(() => OwnerName);
}
}
public string Speed
{
get { return speed; }
set
{
speed = value;
RaisePropertyChanged(() => Speed);
}
}
public string Duration
{
get { return duration; }
set
{
duration = value;
RaisePropertyChanged(() => Duration);
}
}
}
}