/// <summary> /// Gets the Students StudyGroups used for push notifications from the server. /// </summary> /// <returns></returns> public async Task <List <StudyGroup> > GetStudentsStudyGroupFromServer() { DbStudent db = new DbStudent(); Student student = db.GetStudent(); if (student == null) { Authenticater.Authorized = false; return(null); } string encodedUsername = Hasher.Base64Encode(student.username); Uri url = new Uri(Adress + "/" + encodedUsername); System.Diagnostics.Debug.WriteLine("StudentsController - UpdateStudyGroupStudent uri: " + url.ToString()); string accessToken = db.GetStudentAccessToken(); if (accessToken == null) { Authenticater.Authorized = false; return(null); } var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken); string jsonString = null; try { var response = await client.GetAsync(url).ConfigureAwait(false); if (response.StatusCode == HttpStatusCode.Unauthorized) { System.Diagnostics.Debug.WriteLine("StudentsController - UpdateStudyGroupStudent failed due to lack of Authorization"); Authenticater.Authorized = false; return(null); } System.Diagnostics.Debug.WriteLine("UpdateStudyGroupStudent response " + response.StatusCode.ToString()); jsonString = await response.Content.ReadAsStringAsync(); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("StudentsController - UpdateStudyGroupStudent: await client.GetAsync(\"url\") Failed"); System.Diagnostics.Debug.WriteLine("StudentsController - UpdateStudyGroupStudent: Exception msg: " + e.Message); System.Diagnostics.Debug.WriteLine("StudentsController - UpdateStudyGroupStudent: Stack Trace: \n" + e.StackTrace); System.Diagnostics.Debug.WriteLine("StudentsController - UpdateStudyGroupStudent: End Of Stack Trace"); return(null); } if (jsonString != null) { return(ExtractStudyGroupsFromJson(jsonString)); //DeleteAllStudyGroupStudent(); //CreateStudyGroupStudents(student.username, studyGroupIds); } return(null); }
/// <summary> /// Gets all StudyGroups from the servers REST Api. /// </summary> public async Task UpdateStudyGroupsFromServer() { DbStudyGroup db = new DbStudyGroup(); System.Diagnostics.Debug.WriteLine("StudyGroupsController - GetStudyGroupsFromServer: initiated"); DbStudent dbStudent = new DbStudent(); string accessToken = dbStudent.GetStudentAccessToken(); if (accessToken == null) { Authenticater.Authorized = false; return; } Uri url = new Uri(Adress); System.Diagnostics.Debug.WriteLine("StudyGroupsController - url " + url.ToString()); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken); try { var response = await client.GetAsync(url); if (response.StatusCode == HttpStatusCode.OK) { System.Diagnostics.Debug.WriteLine("GetStudyGroupsFromServer response " + response.StatusCode.ToString()); var results = await response.Content.ReadAsAsync <IEnumerable <StudyGroup> >(); db.DeleteAllStudyGroups(); foreach (var studygroup in results) { // ugly gui filter hack studygroup.filterChecked = false; db.InsertStudyGroup(studygroup); } } if (response.StatusCode == HttpStatusCode.Unauthorized) { Authenticater.Authorized = false; } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("StudyGroupsController - GetStudyGroupsFromServer: await client.GetAsync(\"url\") Failed"); System.Diagnostics.Debug.WriteLine("StudyGroupsController - GetStudyGroupsFromServer: Exception msg: " + e.Message); System.Diagnostics.Debug.WriteLine("StudyGroupsController - GetStudyGroupsFromServer: Stack Trace: \n" + e.StackTrace); System.Diagnostics.Debug.WriteLine("StudyGroupsController - GetStudyGroupsFromServer: End Of Stack Trace"); } }
/// <summary> /// Gets all Courses from the servers REST Api. /// </summary> public async Task UpdateCoursesFromServer() { DbCourse db = new DbCourse(); System.Diagnostics.Debug.WriteLine("CoursesController - UpdateCoursesFromServer: initiated"); DbStudent dbStudent = new DbStudent(); string accessToken = dbStudent.GetStudentAccessToken(); if (accessToken == null) { Authenticater.Authorized = false; return; } Uri url = new Uri(Adress); System.Diagnostics.Debug.WriteLine("CoursesController - url " + url.ToString()); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken); try { var response = await client.GetAsync(url); if (response.StatusCode == HttpStatusCode.OK) { System.Diagnostics.Debug.WriteLine("UpdateCoursesFromServer response " + response.StatusCode.ToString()); var newCourses = await response.Content.ReadAsAsync <IEnumerable <Course> >(); db.DeleteAllCourses(); db.InsertCourses(newCourses); } if (response.StatusCode == HttpStatusCode.Unauthorized) { Authenticater.Authorized = false; } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("CoursesController - UpdateCoursesFromServer: await client.GetAsync(\"url\") Failed"); System.Diagnostics.Debug.WriteLine("CoursesController - UpdateCoursesFromServer: Exception msg: " + e.Message); System.Diagnostics.Debug.WriteLine("CoursesController - UpdateCoursesFromServer: Stack Trace: \n" + e.StackTrace); System.Diagnostics.Debug.WriteLine("CoursesController - UpdateCoursesFromServer: End Of Stack Trace"); } }
public async Task CompareServerHash() { DbStudent dbStudent = new DbStudent(); string accessToken = dbStudent.GetStudentAccessToken(); if (accessToken == null) { Authenticater.Authorized = false; return; } Uri url = new Uri(Adress + "/hash"); System.Diagnostics.Debug.WriteLine("JobTypesController - url " + url.ToString()); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken); try { var response = await client.GetAsync(url); if (response.StatusCode == HttpStatusCode.OK) { System.Diagnostics.Debug.WriteLine("CompareServerHash response " + response.StatusCode.ToString()); string json = await response.Content.ReadAsStringAsync(); string hash = ExtractServersHash(json); string localHash = CreateLocalHash(); if (hash != localHash) { await UpdateJobTypesFromServer(); } } if (response.StatusCode == HttpStatusCode.Unauthorized) { Authenticater.Authorized = false; } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("JobTypesController - CompareServerHash: await client.GetAsync(\"url\") Failed"); System.Diagnostics.Debug.WriteLine("JobTypesController - CompareServerHash: Exception msg: " + e.Message); System.Diagnostics.Debug.WriteLine("JobTypesController - CompareServerHash: Stack Trace: \n" + e.StackTrace); System.Diagnostics.Debug.WriteLine("JobTypesController - CompareServerHash: End Of Stack Trace"); } }
/// <summary> /// Updates the Job from the servers REST Api. /// /// This implementation also get the minimum data from the related /// Companies to build a proper notification list. /// </summary> /// <param name="uuid"></param> public async Task UpdateJobFromServer(string uuid) { System.Diagnostics.Debug.WriteLine("JobController - UpdateJobFromServer(string uuid): initiated"); string adress = Adress + "/" + uuid; System.Diagnostics.Debug.WriteLine("UpdateJobFromServer: var url = " + adress); Uri url = new Uri(adress); var client = new HttpClient(); System.Diagnostics.Debug.WriteLine("JobController - UpdateJobFromServer: HttpClient created"); DbStudent dbStudent = new DbStudent(); string accessToken = dbStudent.GetStudentAccessToken(); if (string.IsNullOrWhiteSpace(accessToken)) { Authenticater.Authorized = false; return; } client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken); string jsonString = null; try { var response = await client.GetAsync(url); System.Diagnostics.Debug.WriteLine("UpdateJobFromServer response " + response.StatusCode.ToString()); //results = await response.Content.ReadAsAsync<IEnumerable<Job>>(); jsonString = await response.Content.ReadAsStringAsync(); } catch (Exception e) { System.Diagnostics.Debug.WriteLine( "JobController - UpdateJobFromServer: await client.GetAsync(\"url\") Failed"); System.Diagnostics.Debug.WriteLine("JobController - UpdateJobFromServer: Exception msg: " + e.Message); System.Diagnostics.Debug.WriteLine("JobController - UpdateJobFromServer: Stack Trace: \n" + e.StackTrace); System.Diagnostics.Debug.WriteLine("JobController - UpdateJobFromServer: End Of Stack Trace"); return; } Deserialize(jsonString); }
/// <summary> /// Can return 3 different values: /// 1. "exists": No new jobs on the server. /// 2. "incorrectCache": If the cache indicates that local database got data that the server doesnt have. /// 3. "newData": There are new jobs available on the server. /// 4. null: Check if Authenticater.Authorized has been set to false, if not the app could most likely not reach the server. /// TODO Way to complicated logic, simplify this method if theres time /// </summary> /// <returns></returns> private async Task <string> CheckServerForNewData(List <string> studyGroups = null, Dictionary <string, string> filter = null) { //"api/v1/jobs/lastmodifed" string queryParams = CreateQueryParams(studyGroups, null, filter); string adress = Adress + "/" + "lastmodified" + queryParams; System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData - adress: " + adress); Uri url = new Uri(adress); System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData - url.ToString: " + url.ToString()); var client = new HttpClient(); DbStudent dbStudent = new DbStudent(); string accessToken = dbStudent.GetStudentAccessToken(); if (string.IsNullOrWhiteSpace(accessToken)) { Authenticater.Authorized = false; return(null); } System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData - bearer: " + accessToken); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken); string jsonString = null; try { var response = await client.GetAsync(url); System.Diagnostics.Debug.WriteLine("CheckServerForNewData response " + response.StatusCode.ToString()); if (response.StatusCode == HttpStatusCode.Unauthorized) { System.Diagnostics.Debug.WriteLine("JobsController - CheckServerForNewData failed due to lack of Authorization"); Authenticater.Authorized = false; } else if (response.StatusCode == HttpStatusCode.OK) { //results = await response.Content.ReadAsAsync<IEnumerable<Job>>(); jsonString = await response.Content.ReadAsStringAsync(); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: await client.GetAsync(\"url\") Failed"); System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: Exception msg: " + e.Message); System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: Stack Trace: \n" + e.StackTrace); System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: End Of Stack Trace"); return(null); } if (jsonString != null) { // using <string, object> instead of <string, string> makes the date be stored in the right format when using .ToString() Dictionary <string, object> dict = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonString); if (dict.ContainsKey("uuid") && dict.ContainsKey("modified") && dict.ContainsKey("hash") && dict.ContainsKey("amountOfJobs")) { string uuid = dict["uuid"].ToString(); DateTime dateTime = (DateTime)dict["modified"]; long modified = long.Parse(dateTime.ToString("yyyyMMddHHmmss")); string uuids = dict["hash"].ToString(); int amountOfJobs = 0; try { amountOfJobs = Int32.Parse(dict["amountOfJobs"].ToString()); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: await client.GetAsync(\"url\") Failed"); System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: Exception msg: " + ex.Message); System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: Stack Trace: \n" + ex.StackTrace); System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: End Of Stack Trace"); return(null); } DbJob db = new DbJob(); bool existInDb = db.ExistsInDb(uuid, modified); if (!existInDb) { return("newData"); //return existInDb; } var localJobs = db.GetJobsFromDbBasedOnFilter(studyGroups, filter, true); int localDbCount = localJobs.Count(); StringBuilder sb = new StringBuilder(); foreach (var job in localJobs) { sb.Append(job.uuid); } string localUuids = Hasher.CalculateMd5Hash(sb.ToString()); // if there is a greater amount of jobs on that search filter then the job that exist // in the database has been inserted throught another search filter if (uuids != localUuids) { if (amountOfJobs > localDbCount) { return("newData"); //return !existInDb; } return("incorrectCache"); } return("exists"); //return existInDb; } } return(null); }
/// <summary> /// Gets a job based on optional filters. /// </summary> /// <param name="studyGroups">studyGroups can be a list of numerous studygroups ex: helse, idrettsfag, datateknologi </param> /// </param> /// <param name="filter">A dictionary where key can be: titles (values:title of the job), types (values: deltid, heltid, etc...), /// locations (values: vestagder, austagder), . /// Supports only 1 key at this current implementation!</param> /// <returns></returns> public async Task <IEnumerable <Job> > GetJobsBasedOnFilter(List <string> studyGroups = null, Dictionary <string, string> filter = null) { DbJob db = new DbJob(); //string adress = "http://kompetansetorgetserver1.azurewebsites.net/api/v1/jobs"; string instructions = await CheckServerForNewData(studyGroups, filter); if (!Authenticater.Authorized) { return(null); } if (instructions != null) { System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter - instructions: " + instructions); if (instructions == "exists") // "newData"; incorrectCache exists { IEnumerable <Job> filteredJobs = db.GetJobsFromDbBasedOnFilter(studyGroups, filter); filteredJobs = db.GetAllCompaniesRelatedToJobs(filteredJobs.ToList()); return(filteredJobs); } } DbStudent dbStudent = new DbStudent(); string accessToken = dbStudent.GetStudentAccessToken(); if (string.IsNullOrWhiteSpace(accessToken)) { Authenticater.Authorized = false; return(null); } string sortBy = "publish"; string queryParams = CreateQueryParams(studyGroups, sortBy, filter); Uri url = new Uri(Adress + queryParams); System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter - url: " + url.ToString()); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken); string jsonString = null; IEnumerable <Job> jobs = null; try { var response = await client.GetAsync(url).ConfigureAwait(false); System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter response " + response.StatusCode.ToString()); if (response.StatusCode == HttpStatusCode.Unauthorized) { System.Diagnostics.Debug.WriteLine("StudentsController - UpdateStudyGroupStudent failed due to lack of Authorization"); Authenticater.Authorized = false; } else if (response.StatusCode == HttpStatusCode.OK) { jsonString = await response.Content.ReadAsStringAsync(); //DeleteJobs(GetJobsFromDbBasedOnFilter(studyGroups, filter)); if (instructions != null && instructions == "incorrectCache") { var cachedJobs = db.GetJobsFromDbBasedOnFilter(studyGroups, filter); jobs = DeserializeMany(jsonString); // Get all jobs from that local dataset that was not in the data set provided by the server // These are manually deleted jobs and have to be cleared from cache. // linear search is ok because of small data set var manuallyDeletedJobs = cachedJobs.Where(j => !jobs.Any(cj2 => cj2.uuid == j.uuid)); db.DeleteObsoleteJobs(manuallyDeletedJobs.ToList()); } else { jobs = DeserializeMany(jsonString); } } else { System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter - Using the local database"); jobs = db.GetJobsFromDbBasedOnFilter(studyGroups, filter); jobs = db.GetAllCompaniesRelatedToJobs(jobs.ToList()); } return(jobs); } catch (Exception e) { // Hack workaround if mobil data and wifi is turned off try { jobs = db.GetJobsFromDbBasedOnFilter(studyGroups, filter); jobs = db.GetAllCompaniesRelatedToJobs(jobs.ToList()); return(jobs); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("JobsController - GetJobsBasedOnFilter: await client.GetAsync(\"url\") Failed"); System.Diagnostics.Debug.WriteLine("JobsController - GetJobsBasedOnFilter: Exception msg: " + ex.Message); System.Diagnostics.Debug.WriteLine("JobsController - GetJobsBasedOnFilter: Stack Trace: \n" + ex.StackTrace); System.Diagnostics.Debug.WriteLine("JobsController - GetJobsBasedOnFilter: End Of Stack Trace"); System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter - Using the local database"); return(null); } } }
/// <summary> /// Posts the Students StudyGroups used for push notifications to the server. /// </summary> /// <returns></returns> public async Task <bool> PostStudentsStudyGroupToServer(List <string> studyGroups) { DbStudent db = new DbStudent(); Student student = db.GetStudent(); string accessToken = db.GetStudentAccessToken(); if (student == null || accessToken == null) { Authenticater.Authorized = false; return(false); } string jsonString = ""; if (studyGroups.Count == 0) { string id = Hasher.Base64Encode("none"); studyGroups.Add(id); } foreach (var studyGroup in studyGroups) { string id = Hasher.Base64Decode(studyGroup); if (string.IsNullOrWhiteSpace(jsonString)) { jsonString = "{\"StudyGroup\":[{\"id\":\"" + id + "\"}"; } else { jsonString += ",{\"id\":\"" + id + "\"}"; } } jsonString += "]}"; // {"StudyGroup":[{"id":"idrettsfag"},{"id":"datateknologi"}]} // {"studyGroups":[{"id":"helse"},{"id":"ingeniør"},{"id":"samfunnsfag"}]} System.Diagnostics.Debug.WriteLine("StudentsController - PostStudentsStudyGroupToServer jsonString: " + jsonString); string encodedUsername = Hasher.Base64Encode(student.username); Uri url = new Uri(Adress + "/" + encodedUsername); System.Diagnostics.Debug.WriteLine("StudentsController - PostStudentsStudyGroupToServer uri: " + url.ToString()); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken); var content = new StringContent(jsonString, Encoding.UTF8, "application/json"); try { var response = await client.PostAsync(url, content); System.Diagnostics.Debug.WriteLine("PostStudentsStudyGroupToServer response " + response.StatusCode.ToString()); if (response.StatusCode == HttpStatusCode.OK) { return(true); } if (response.StatusCode == HttpStatusCode.Unauthorized) { System.Diagnostics.Debug.WriteLine("StudentsController - PostStudentsStudyGroupToServer failed due to lack of Authorization"); Authenticater.Authorized = false; } // response.StatusCode is either unauthorized or another failed status. return(false); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("StudentsController - PostStudentsStudyGroupToServer: await client.PostAsJsonAsync(url, jsonString) Failed"); System.Diagnostics.Debug.WriteLine("StudentsController - PostStudentsStudyGroupToServer: Exception msg: " + e.Message); System.Diagnostics.Debug.WriteLine("StudentsController - PostStudentsStudyGroupToServer: Stack Trace: \n" + e.StackTrace); System.Diagnostics.Debug.WriteLine("StudentsController - PostStudentsStudyGroupToServer: End Of Stack Trace"); return(false); } }
public async Task UpdateServersDb() { DbDevice db = new DbDevice(); DbStudent dbStudent = new DbStudent(); Student student = dbStudent.GetStudent(); Device device = db.GetDevice(); string accessToken = dbStudent.GetStudentAccessToken(); if (student == null || accessToken == null || device == null || student.username != device.username) { Authenticater.Authorized = false; return; } if (device.tokenSent) { return; } System.Diagnostics.Debug.WriteLine("DevicesController - UpdateServersDb - bearer: " + accessToken); string serializedJson = "{\"Device\":[{\"id\":\"" + device.id + "\"," + "\"token\":\"" + device.token + "\"," + "\"deviceType\":\"" + device.deviceType + "\"}]}"; // {"Device":[{"id":"HT451WM08832","token":"longGCMToken","deviceType":"android"}]} System.Diagnostics.Debug.WriteLine("DevicesController - UpdateServersDb serializedJson: " + serializedJson); string encodedUsername = Hasher.Base64Encode(student.username); //"api/v1/students/{id}" string updateAdress = studentAdress + "/" + encodedUsername; System.Diagnostics.Debug.WriteLine("DevicesController - UpdateServersDb - adress: " + updateAdress); Uri url = new Uri(updateAdress); System.Diagnostics.Debug.WriteLine("DevicesController - UpdateServersDb - url.ToString: " + url.ToString()); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken); var content = new StringContent(serializedJson, Encoding.UTF8, "application/json"); try { var response = await client.PostAsync(url, content); System.Diagnostics.Debug.WriteLine("UpdateServersDb response " + response.StatusCode.ToString()); if (response.StatusCode == HttpStatusCode.OK) { device.tokenSent = true; db.UpdateDevice(device); return; } if (response.StatusCode == HttpStatusCode.Unauthorized) { System.Diagnostics.Debug.WriteLine("DevicesController - UpdateServersDb failed due to lack of Authorization"); Authenticater.Authorized = false; } // response.StatusCode is either unauthorized or another failed status. return; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("StudentsController - PostStudentsStudyGroupToServer: await client.PostAsJsonAsync(url, jsonString) Failed"); System.Diagnostics.Debug.WriteLine("StudentsController - PostStudentsStudyGroupToServer: Exception msg: " + e.Message); System.Diagnostics.Debug.WriteLine("StudentsController - PostStudentsStudyGroupToServer: Stack Trace: \n" + e.StackTrace); System.Diagnostics.Debug.WriteLine("StudentsController - PostStudentsStudyGroupToServer: End Of Stack Trace"); return; } }