/
MainPage.xaml.cs
414 lines (341 loc) · 13.6 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using System.Threading;
using System.ComponentModel;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Shell;
using System.Net.NetworkInformation;
namespace mockup
{
public partial class MainPage : PhoneApplicationPage
{
private string postString;
private string username;
private string password;
private string domain;
private string[] domains = { "NUSSTU", "NUSSTF", "NUSEXT", "GUEST" };
// Constructor
public MainPage()
{
InitializeComponent();
LoadCredentials();
// if token exists in isolated storage
if (LoadToken())
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
MessageBox.Show("No internet connection is available. Make sure you have either Wi-Fi or data connection.");
}
else
{
DisableControls();
loginProgressBar.IsIndeterminate = true;
UpdateToken();
}
}
// upload application tile with the latest to-dos
(Application.Current as App).UpdateAppTile();
}
// load token from isolated storage if existing
// return false if not
private bool LoadToken()
{
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("token"))
{
LAPI.token = settings["token"].ToString();
return true;
}
else
{
return false;
}
}
// validate token and update it if
// expiration is soon
private void UpdateToken()
{
HttpWebRequest request = HttpWebRequest.CreateHttp(LAPI.validateTokenURL());
request.BeginGetResponse(new AsyncCallback(HandleTokenResponse), request);
}
// disable all controls
private void DisableControls()
{
UsernameInput.IsEnabled = false;
PasswordInput.IsEnabled = false;
DomainInput.IsEnabled = false;
}
// enable all controls
private void EnableControls()
{
UsernameInput.IsEnabled = true;
PasswordInput.IsEnabled = true;
DomainInput.IsEnabled = true;
}
// handle the response and get the json string
public void HandleTokenResponse(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.EndGetResponse(result);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// returned JSON string for validation
string responseString = reader.ReadToEnd();
Token newToken = (Token)Deserialize(responseString, typeof(Token));
if (newToken != null && newToken.TokenSuccess.Equals(true))
{
LAPI.token = newToken.TokenContent;
Dispatcher.BeginInvoke(() =>
{
(Application.Current as App).online = true;
SaveCredentials();
SaveToken();
loginProgressBar.IsIndeterminate = false;
NavigationService.Navigate(new Uri(("/MenuPage.xaml"), UriKind.Relative));
});
}
else
{
Dispatcher.BeginInvoke(() =>
{
EnableControls();
loginProgressBar.IsIndeterminate = false;
});
}
}
}
catch (WebException ex)
{
}
}
// log in event by pressing the log in button
private void login_Click(object sender, RoutedEventArgs e)
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
MessageBox.Show("No internet connection is available. Make sure you have either Wi-Fi or data connection.");
}
else
{
loginProgressBar.IsIndeterminate = true;
// getting user credentials from input
username = UsernameInput.Text;
password = PasswordInput.Password;
// cast the selected listpickeritem and extract the content
domain = domains[DomainInput.SelectedIndex];
postString = LAPI.GeneratePostString(username, password, domain);
string authenticationURL = "https://ivle.nus.edu.sg/api/Lapi.svc/Login_JSON";
// Create a new HttpWebRequest object.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(authenticationURL);
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
}
private void Login()
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
MessageBox.Show("No internet connection is available. Make sure you have either Wi-Fi or data connection.");
}
else
{
loginProgressBar.IsIndeterminate = true;
// getting user credentials from input
username = UsernameInput.Text;
password = PasswordInput.Password;
// cast the selected listpickeritem and extract the content
domain = domains[DomainInput.SelectedIndex];
postString = LAPI.GeneratePostString(username, password, domain);
string authenticationURL = "https://ivle.nus.edu.sg/api/Lapi.svc/Login_JSON";
// Create a new HttpWebRequest object.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(authenticationURL);
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
}
public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
byte[] byteArray = Encoding.UTF8.GetBytes(postString);
postStream.Write(byteArray, 0, postString.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
// returned JSON string for validation
string responseString = streamRead.ReadToEnd();
// remove the last "}"
responseString = responseString.Remove(responseString.Length - 1);
// remove the first "{" and its associated header
responseString = responseString.Substring(responseString.IndexOf(":") + 1);
Token token = (Token)Deserialize(responseString, typeof(Token));
if (token != null && token.TokenSuccess.Equals(true))
{
LAPI.token = token.TokenContent;
Dispatcher.BeginInvoke(() =>
{
(Application.Current as App).online = true;
SaveCredentials();
SaveToken();
loginProgressBar.IsIndeterminate = false;
NavigationService.Navigate(new Uri(("/MenuPage.xaml"), UriKind.Relative));
});
}
else
{
Dispatcher.BeginInvoke(() =>
{
loginProgressBar.IsIndeterminate = false;
MessageBox.Show("Log in failed");
});
}
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
catch(WebException ex)
{
if (ex.Status == WebExceptionStatus.RequestCanceled)
{
Dispatcher.BeginInvoke(() =>
{
Login();
});
}
}
}
public static object Deserialize(String input, Type objectType)
{
if (objectType == null || input == null)
return null;
JsonSerializer ser = new JsonSerializer();
JsonReader jr = new JsonTextReader(new StringReader(input));
return ser.Deserialize(jr, objectType);
}
private void SaveCredentials()
{
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("username"))
{
settings["username"] = username;
}
else
{
settings.Add("username", username);
}
if (settings.Contains("password"))
{
settings["password"] = password;
}
else
{
settings.Add("password", password);
}
if (settings.Contains("domain"))
{
settings["domain"] = domain;
}
else
{
settings.Add("domain", domain);
}
settings.Save();
}
// save token into isolated storage
private void SaveToken()
{
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("token"))
{
settings["token"] = LAPI.token;
}
else
{
settings.Add("token", LAPI.token);
}
settings.Save();
}
private void LoadCredentials()
{
// if credential is memorized before
// load credentials
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("username") && settings.Contains("password") && settings.Contains("domain"))
{
username = settings["username"].ToString();
password = settings["password"].ToString();
domain = settings["domain"].ToString();
DomainInput.SelectedItem = DomainInput.FindName(domain);
UsernameInput.Text = username;
PasswordInput.Password = password;
}
}
//public void UpdateApplicationTile()
//{
// string backTitle = null;
// string backContent = null;
// if ((Application.Current as App).todos.Count > 0)
// {
// backTitle = (Application.Current as App).todos[0].todoName;
// if ((Application.Current as App).todos[0].todoDetail.Length > 50)
// {
// backContent = (Application.Current as App).todos[0].todoDetail.Substring(0,50);
// }
// else
// {
// backContent = (Application.Current as App).todos[0].todoDetail;
// }
// }
// var appTile = ShellTile.ActiveTiles.First();
// if(appTile != null)
// {
// var standardTile = new StandardTileData
// {
// Title = "IVLE Metro",
// BackTitle = backTitle,
// BackContent = backContent,
// BackgroundImage = new Uri("NUS_Logo.png", UriKind.Relative),
// BackBackgroundImage = null
// };
// appTile.Update(standardTile);
// }
//}
private void offlineMode_Click(object sender, RoutedEventArgs e)
{
// navigate to panaroma menu page immediately without downloading data
(Application.Current as App).online = false;
NavigationService.Navigate(new Uri(("/MenuPage.xaml"), UriKind.Relative));
}
}
}