-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainPage.xaml.cs
278 lines (254 loc) · 12 KB
/
MainPage.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
using System;
using System.Net;
using Microsoft.Phone.Controls;
using RestSharp;
using System.Runtime.Serialization.Json;
using System.Text;
using System.IO;
using System.IO.IsolatedStorage;
using System.Device.Location;
using System.Device;
using Microsoft.Phone.Controls.Maps;
using System.Windows;
using System.Linq;
using Microsoft.Phone.Shell;
namespace LatitudeGap
{
public partial class MainPage : PhoneApplicationPage
{
IsolatedStorageSettings isoSettings = IsolatedStorageSettings.ApplicationSettings;
GeoCoordinateWatcher watcher;
private const String CURRENT_LOCATION = "https://www.googleapis.com/latitude/v1/currentLocation";
private const String DEVICE_URL = "https://accounts.google.com/o/oauth2/device/code";
private const String TOKEN_URL = "https://accounts.google.com/o/oauth2/token";
private const String CLIENT_ID = "<your_client_id>";
private const String CLIENT_SECRET = "<your_client_secret>";
private const String SCOPE = "https://www.googleapis.com/auth/latitude.all.best";
private const String APPROVAL_URL = "https://accounts.google.com/o/oauth2/device/approval";
// Constructor
public MainPage()
{
if (!isoSettings.Contains("Enablelocation"))
isoSettings.Add("Enablelocation", true);
InitializeComponent();
if (watcher == null)
{
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
watcher.MovementThreshold = 10;
watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
}
if ((bool)isoSettings["Enablelocation"])
{
watcher.Start();
}
else
{
map.Visibility = System.Windows.Visibility.Collapsed;
MessageBox.Show("Please enable Location services from settings to view and report location");
}
}
void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
switch (e.Status)
{
case GeoPositionStatus.Disabled:
MessageBox.Show("Location Service is not enabled on the device. Please enable to use application");
break;
case GeoPositionStatus.NoData:
MessageBox.Show(" The Location Service is working, but it cannot get location data.");
break;
}
}
void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (e.Position.Location.IsUnknown)
{
MessageBox.Show("Please wait while your position is determined....");
return;
}
this.map.Center = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);
if (this.map.Children.Count != 0)
{
var pushpin = map.Children.OfType<Pushpin>().FirstOrDefault(p => "locationPushpin".Equals(p.Tag));
if (pushpin != null)
{
this.map.Children.Remove(pushpin);
}
}
Pushpin locationPushpin = new Pushpin();
locationPushpin.Tag = "locationPushpin";
locationPushpin.Content = "You are here!";
locationPushpin.Location = watcher.Position.Location;
this.map.Children.Add(locationPushpin);
this.map.SetView(watcher.Position.Location, 15.0);
object access_token;
if (isoSettings.TryGetValue("access_token", out access_token))
{
string latitude = e.Position.Location.Latitude.ToString("0.0000");
string longitude = e.Position.Location.Longitude.ToString("0.0000");
string altitude = e.Position.Location.Altitude.ToString("0.0000");
submitToLatitude(latitude, longitude);
}
else
{
System.Diagnostics.Debug.WriteLine("NO ACCESS TOKEN TO START WITH");
}
}
private Boolean submitToLatitude(string latitude, string longitude)
{
string latitudeData = "{ \"data\": { \"kind\":\"latitude#location\", \"latitude\":" + latitude + ", \"longitude\":" + longitude + "}}";
object access_token;
if (isoSettings.TryGetValue("access_token", out access_token))
{
RestClient client = new RestClient(CURRENT_LOCATION);
RestRequest request = new RestRequest(Method.POST);
request.Resource = "?access_token="+ access_token;
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", latitudeData, ParameterType.RequestBody);
var asyncHandle = client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
System.Diagnostics.Debug.WriteLine("Submitted Fine... Latitude Response -->> " + response.Content);
}
else if (response.StatusCode == HttpStatusCode.Unauthorized)
{
object refresh_token;
if (isoSettings.TryGetValue("refresh_token", out refresh_token))
{
RestClient tokenClient = new RestClient(TOKEN_URL);
RestRequest req = new RestRequest(Method.POST);
request.AddParameter("client_id", CLIENT_ID);
request.AddParameter("client_secret", CLIENT_SECRET);
request.AddParameter("refresh_token", refresh_token);
request.AddParameter("grant_type", "refresh_token");
var asyncHandler = client.ExecuteAsync(req, resp =>
{
if (resp.StatusCode == HttpStatusCode.OK)
{
using (var ms2 = new MemoryStream(Encoding.Unicode.GetBytes(resp.Content)))
{
var ser = new DataContractJsonSerializer(typeof(TokenResponse));
TokenResponse obj = (TokenResponse)ser.ReadObject(ms2);
isoSettings["access_token"] = obj.access_token;
isoSettings["refresh_token"] = obj.refresh_token;
isoSettings.Save();
}
}
});
}
}
});
}
else
{
MessageBox.Show("Please authorize application with Google");
}
return true;
}
private void loginButton_Click(object sender, EventArgs e)
{
RestClient client = new RestClient(DEVICE_URL);
RestRequest request = new RestRequest(Method.POST);
request.AddParameter("client_id", CLIENT_ID);
request.AddParameter("scope", SCOPE);
var asyncHandle = client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
map.Visibility = System.Windows.Visibility.Collapsed;
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(response.Content)))
{
var ser = new DataContractJsonSerializer(typeof(DeviceResponse));
DeviceResponse obj = (DeviceResponse)ser.ReadObject(ms);
isoSettings["device_code"] = obj.device_code;
isoSettings.Save();
userCodeField.Visibility = System.Windows.Visibility.Visible;
userCodeField.Text = obj.user_code;
userCodeLabel.Visibility = System.Windows.Visibility.Visible;
webBrowser.Visibility = System.Windows.Visibility.Visible;
webBrowser.Navigate(new Uri(obj.verification_url));
}
}
});
}
private void tokenButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
object deviceCode;
if (isoSettings.TryGetValue("device_code", out deviceCode))
{
webBrowser.Visibility = System.Windows.Visibility.Collapsed;
map.Visibility = System.Windows.Visibility.Visible;
RestClient client = new RestClient(TOKEN_URL);
RestRequest request = new RestRequest(Method.POST);
request.AddParameter("client_id", CLIENT_ID);
request.AddParameter("client_secret", CLIENT_SECRET);
request.AddParameter("code", deviceCode);
request.AddParameter("grant_type", "http://oauth.net/grant_type/device/1.0");
var asyncHandle = client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(response.Content)))
{
var ser = new DataContractJsonSerializer(typeof(TokenResponse));
TokenResponse obj = (TokenResponse)ser.ReadObject(ms);
isoSettings["access_token"] = obj.access_token;
isoSettings["refresh_token"] = obj.refresh_token;
isoSettings.Save();
}
}
});
}
}
private void webBrowser_Navigating(object sender, NavigatingEventArgs e)
{
String url = e.Uri.AbsoluteUri;
if (url.Contains("?"))
{
if (url.Substring(0, url.IndexOf("?")).Equals(APPROVAL_URL))
{
TokenButton.Visibility = System.Windows.Visibility.Visible;
userCodeField.Visibility = System.Windows.Visibility.Collapsed;
userCodeLabel.Visibility = System.Windows.Visibility.Collapsed;
}
}
}
private void refreshButton_Click(object sender, EventArgs e)
{
if ((bool)isoSettings["Enablelocation"])
{
map.Visibility = System.Windows.Visibility.Visible;
((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;
watcher.Stop();
watcher.Start();
((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = true;
}
else
{
map.Visibility = System.Windows.Visibility.Collapsed;
MessageBox.Show("Please enable Location services from settings to view and report location");
}
}
private void settingsButton_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.Relative));
}
}
public class DeviceResponse
{
public string device_code { get; set; }
public string user_code { get; set; }
public string verification_url { get; set; }
public int expires_in { get; set; }
public int interval { get; set; }
}
public class TokenResponse
{
public string access_token { get; set; }
public string token_type { get; set; }
public string refresh_token { get; set; }
public int expires_in { get; set; }
}
}