Click here to Skip to main content
15,885,244 members
Articles / Hosted Services / Azure

GPS Runner Maps: My First Windows Azure Application

Rate me:
Please Sign up or sign in to vote.
4.90/5 (12 votes)
20 Dec 2009CPOL3 min read 55.1K   3.1K   63  
It is "cloud" Web application to display GPS tracks on Google or Bing maps
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PS.GpsRunnerMaps;
using System.Globalization;
using System.Threading;
using System.Web.Security;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Configuration;
using System.Data.Services.Client;

namespace GpsRunnerMaps_WebRole
{
  public partial class Tracks : System.Web.UI.Page
  {
    GpsRunnerDisplay _gpsDisplay;
    int _pageSize = 4;

    protected override void OnInit(EventArgs e)
    {
      base.OnInit(e);
      _gpsDisplay = new GpsRunnerDisplay(this.Master.GoogleMapUC, this.Master.VEMap);
    }

    protected override void InitializeCulture()
    {
      base.InitializeCulture();
      UserProfile p = (UserProfile)Context.Profile;
      Thread.CurrentThread.CurrentUICulture = new CultureInfo(p.Language);
      Thread.CurrentThread.CurrentCulture = new CultureInfo(p.Language);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      if (_users.Items.Count == 0)
      {
        _users.Items.Add(new ListItem(Resources.Res.allUsers));
        foreach (MembershipUser user in Membership.GetAllUsers().OfType<MembershipUser>().OrderBy(u => u.UserName))
        {
          if (!string.IsNullOrEmpty(user.UserName))
          { _users.Items.Add(new ListItem(user.UserName, user.UserName)); }
        }
      }
      if (!this.IsPostBack)
      {
        this.TrackId = null;
        if (RoleEnvironment.IsAvailable)
        { _pageSize = int.Parse(RoleEnvironment.GetConfigurationSettingValue("PageSize")); }
        else
        { _pageSize = int.Parse(ConfigurationManager.AppSettings["PageSize"]); }
        DataBindTracks();
      }
      if (!string.IsNullOrEmpty(this.TrackId))
      { FillMap(); }
    }

    public int PageSize
    {
      get { return _pageSize; }
      set { _pageSize = value; }
    }

    /// <summary>
    /// Datas the bind tracks.
    /// </summary>
    private void DataBindTracks()
    {
      try
      {
        DataServiceQuery<TrackRow> tracksQuery = this.GetTracks(this.PageSize);
        // int tt = tracksQuery.Count(); --> unfortunately count is not supported
        var continuation = Request["ct"];
        if (continuation != null)
        {
          string[] tokens = continuation.Split('/');
          string partitionToken = tokens[0];
          string rowToken = tokens[1];
          tracksQuery.AddQueryOption("NextPartitionKey", partitionToken).
            AddQueryOption("NextRowKey", rowToken);
        }
        QueryOperationResponse res = (QueryOperationResponse)tracksQuery.Execute();
        string nextPartition = null;
        string nextRow = null;
        res.Headers.TryGetValue("x-ms-continuation-NextPartitionKey", out nextPartition);
        res.Headers.TryGetValue("x-ms-continuation-NextRowKey", out nextRow);
        dtlTracks.DataKeyField = "TrackId";
        dtlTracks.DataSource = res;
        // bind data list
        dtlTracks.DataBind();
        if (nextPartition != null && nextRow != null)
        {
          navNext.NavigateUrl = string.Format("?ct={0}/{1}", nextPartition, nextRow);
        }
        else
        {
          navNext.Enabled = false;
        }
        if (continuation == null)
        { navPrev.Enabled = false; }

      }
      catch (Exception ex)
      {
        System.Diagnostics.Debug.WriteLine(ex.Message);
        throw ex;
      }
      //Checking for enabling/disabling next/prev buttons.
      //Next/prev buton will be disabled when is the last/first page of the pageobject.
    }

    /// <summary>
    /// Manage links visible.
    /// </summary>
    protected bool EvalManageVisible(object userId)
    { return HttpContext.Current.User.Identity.Name.Equals(userId); }


    /// <summary>
    /// Manage links visible.
    /// </summary>
    protected bool EvalIsAdministrator()
    { return string.Compare(HttpContext.Current.User.Identity.Name, "Administrator", true) == 0; }
    /// <summary>
    /// Gets the tracks.
    /// <para>Warning: Skip, Count not implemented</para>
    /// </summary>
    /// <param name="page">The page.</param>
    /// <param name="pagecount">The pagecount.</param>
    /// <returns></returns>
    public DataServiceQuery<TrackRow> GetTracks(int? pagesize)
    {
      IQueryable<TrackRow> q;
      if (this._users.SelectedIndex == 0)
      { q = GpsRunnerDataStore.GetPublicTracks(_countries.SelectedValue); }
      else
      { q = GpsRunnerDataStore.GetTracksByUser(_users.SelectedValue, _countries.SelectedValue); }
      if (pagesize.HasValue)
      { q = q.Take(pagesize.Value); }
      return (DataServiceQuery<TrackRow>)q;
    }

    protected void _countries_SelectedIndexChanged(object sender, EventArgs e)
    {
      this.CenterToCountry();
      this.DataBindTracks();
    }

    protected string EvalCountryName(object ccode)
    { return _countries.GetCountryName(ccode.ToString()); }

    protected void _users_SelectedIndexChanged(object sender, EventArgs e)
    {
      this._countries.SelectedIndex = 0;
      this.DataBindTracks();
    }

    private void CenterToCountry()
    {
      if (_countries.SelectedIndex > 0)
      {
        _gpsDisplay.Clear();
        GooglePoint p = GooglePoint.FromLatLong(_gpsDisplay.CenterPoint);
        p.Address = _countries.SelectedText;
        p.GeocodeAddress(_gpsDisplay.Google.GoogleMap.APIKey);
        _gpsDisplay.ZoomLevel = 7;
        _gpsDisplay.CenterPoint = p.ToLatLong();
      }
    }

    internal string TrackId
    {
      get { return ViewState["trackId"] as string; }
      set { ViewState["trackId"] = value; }
    }

    protected void _viewLink_Click(object sender, EventArgs e)
    {
      this.TrackId = GetTrackIdFromDataKeys(((IButtonControl)sender).CommandArgument);
      //Response.Redirect("Tracks.aspx?trackId=" + trackId);
      DataBindTracks();
      FillMap();
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
      string trackId = GetTrackIdFromDataKeys(((IButtonControl)sender).CommandArgument);
      GpsRunnerDataStore.DeleteTrack(trackId);
      this.DataBindTracks();
    }

    protected void btnDeleteAll_Click(object sender, EventArgs e)
    {
      GpsRunnerDataStore.DeleteAllTracks();
      this.DataBindTracks();
    }

    internal string GetTrackIdFromDataKeys(string sIndex)
    {
      int index = int.Parse(sIndex);
      string trackId = dtlTracks.DataKeys[index].ToString();
      return trackId;
    }

    protected void _detailsLink_Click(object sender, EventArgs e)
    {
      string trackId = GetTrackIdFromDataKeys(((IButtonControl)sender).CommandArgument);
      Response.Redirect("TrackDetails.aspx?trackId=" + trackId);
    }

    private void FillMap()
    {
      this._gpsDisplay.MapType = this.Master.SelectedMapType;
      this._gpsDisplay.Clear();
      string trackId = this.TrackId;
      this._gpsDisplay.TrackId = trackId;
      if (trackId == string.Empty)
      {
        return; // -->no track selected
      }
      _gpsDisplay.FillMap(false, true);
      _updatePanel.Update();
    }


    //moves to Previous  record 
    protected void btnPrev_Click(object sender, EventArgs e)
    {
      DataBindTracks();
    }

    //moves to next  record 
    protected void btnNext_Click(object sender, EventArgs e)
    {
      DataBindTracks();
    }

   } // end class
}

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Forthnet
Greece Greece
Software developer and Microsoft Trainer, Athens, Greece (MCT, MCSD.net, MCSE 2003, MCDBA 2000,MCTS, MCITP, MCIPD).

Comments and Discussions