Пример #1
0
        protected override void OnStart()
        {
            DbStudent dbStudent = new DbStudent();
            Student student = dbStudent.GetStudent();

            // Comment out the 4 lines under to deactive the GoToLogin at 
            if (student == null || student.accessToken == null)
            {
                Authenticater.Authorized = false;
            }

            NavPage = new NavigationPage(new MainPage());
            //NavPage = new NavigationPage(new LoginPage());
            MainPage = NavPage;
            
            //NavPage.BarBackgroundColor = Color.FromHex("ec7a08");
            //NavPage.BarTextColor = Color.White;

            if (student != null)
            {
                DeleteOutdatedData();
                UpdateAllFilters();
                DbDevice dbDevice = new DbDevice();
                if (dbDevice.GetDevice() != null && !dbDevice.GetDevice().tokenSent)
                {
                    DevicesController dc = new DevicesController();
                    dc.UpdateServersDb();
                }
            }
        }
        /// <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>
 /// Active to logout.
 /// </summary>
 async void Logout(object sender, EventArgs e)
 {
     var logout = await DisplayAlert("Logg ut", "Ønsker du å logge ut?", "Ja", "Nei");
     if (logout == true)
     {
         DbStudent dbStudent = new DbStudent();
         dbStudent.DeleteAllStudents();
         GoToLogin();
     }
 }
Пример #4
0
 /// <summary>
 /// Gets the students accessToken.
 /// Warning, check for Null
 /// </summary>
 /// <returns></returns>
 public string GetStudentAccessToken()
 {
     DbStudent db = new DbStudent();
     Student student = db.GetStudent();
     string accessToken = null;
     if (student != null)
     {
         accessToken = student.accessToken;
     }
     return accessToken;
 }
Пример #5
0
        /// <summary>
        /// Gets the students accessToken.
        /// Warning, check for Null
        /// </summary>
        /// <returns></returns>
        public string GetStudentAccessToken()
        {
            DbStudent db          = new DbStudent();
            Student   student     = db.GetStudent();
            string    accessToken = null;

            if (student != null)
            {
                accessToken = student.accessToken;
            }
            return(accessToken);
        }
        /// <summary>
        /// Inserts or update the device with the given fields.
        /// </summary>
        /// <param name="gcmToken"></param>
        /// <param name="deviceId"></param>
        /// <param name="deviceType"></param>
        /// <returns></returns>
        public async Task InsertOrUpdateDevice(string gcmToken, string deviceId, string deviceType)
        {
            DbDevice db = new DbDevice();
            DbStudent dbStudent = new DbStudent();
            Student student = dbStudent.GetStudent();
            Device device = db.GetDevice();
            if (device == null)
            {
                device = new Device();
                device.id = deviceId;
                device.token = gcmToken;
                device.tokenSent = false;
                device.deviceType = deviceType;

                if (student != null)
                {
                    device.username = student.username;
                }
                db.InsertDevice(device);
                if (student != null)
                {
                    UpdateServersDb();
                }
                return;
            }

            if (device.token != gcmToken)
            {
                device.token = gcmToken;
                device.tokenSent = false;
                if (student != null)
                {
                    device.username = student.username;
                }
                db.UpdateDevice(device);
                if (student != null)
                {
                    UpdateServersDb();
                }
                return;
            }

            if (!device.tokenSent && student != null)
            {
                if (device.username != student.username)
                {
                    device.username = student.username;
                    db.UpdateDevice(device);
                }
                UpdateServersDb();
            }
        }
        /// <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>
        /// Receives a Message from GCM. The method exctracts a message from the Bundle data,
        /// and calls SendNotification.
        /// 
        /// If the students have enabled receiveNotifications, but
        /// disabled receiveProjectNotifications and receiveJobNotifications
        /// The student can still receive more general messages sent as push notifications
        /// however these notifications will only be displayed once and won't be displayed in the
        /// notification list.
        /// </summary>
        public override async void OnMessageReceived(string from, Bundle data)
        {
            DbStudent dbStudent = new DbStudent();
            var message = data.GetString("message");
            Log.Debug("MyGcmListenerService", "From:    " + from);
            Log.Debug("MyGcmListenerService", "Message: " + message);
            var type = data.GetString("type");
            var uuid = data.GetString("uuid");
            Student student = dbStudent.GetStudent();
            if (student != null && student.receiveNotifications)
            {
                DbNotification dbNotification = new DbNotification();
                if (type == "project")
                {    
                    if (student.receiveProjectNotifications)  
                    { 
                        SendNotification(message);
                        Log.Debug("MyGcmListenerService", "type: " + type);
                        Log.Debug("MyGcmListenerService", "uuid: " + uuid);
                        // type = job or project          
            
                        Log.Debug("MyGcmListenerService", "After New NotificationController, but before use of method.");
                        dbNotification.InsertNotification(type, uuid);         
                    }
                }
                else if (type == "job")
                {
                    if (student.receiveJobNotifications)
                    {
                        SendNotification(message);
                        Log.Debug("MyGcmListenerService", "type: " + type);
                        Log.Debug("MyGcmListenerService", "uuid: " + uuid);
                        // type = job or project          

                        Log.Debug("MyGcmListenerService", "After New NotificationController, but before use of method.");
                        dbNotification.InsertNotification(type, uuid);
                    }
                }
                else
                {
                    SendNotification(message);
                }
            }
        }
        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("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("CompareServerHash response " + response.StatusCode.ToString());
                    string json = await response.Content.ReadAsStringAsync();
                    string hash = ExtractServersHash(json);
                    string localHash = CreateLocalHash();
                    if (hash != localHash)
                    {
                        await UpdateCoursesFromServer();
                    }

                }
                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    Authenticater.Authorized = false;
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("CoursesController - CompareServerHash: await client.GetAsync(\"url\") Failed");
                System.Diagnostics.Debug.WriteLine("CoursesController - CompareServerHash: Exception msg: " + e.Message);
                System.Diagnostics.Debug.WriteLine("CoursesController - CompareServerHash: Stack Trace: \n" + e.StackTrace);
                System.Diagnostics.Debug.WriteLine("CoursesController - CompareServerHash: 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");
            }
        }
 void GetStudentNotificationsPref()
 {
     DbStudent dbStudent = new DbStudent();
     Student student = dbStudent.GetStudent();
     if (student != null)
     {
         oppgaveSwitch.IsToggled = student.receiveProjectNotifications;
         stillingSwitch.IsToggled = student.receiveJobNotifications;
         varselSwitch.IsToggled = student.receiveNotifications;
     }
     else {
         oppgaveSwitch.IsToggled = false;
         stillingSwitch.IsToggled = false;
         varselSwitch.IsToggled = false;
     }
 }
        /// <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;
            }     
        }
        /// <summary>
        /// Can return 3 different values:
        /// 1. "exists": No new project on the server. 
        /// 2. "incorrectCache": If the cache indicates that local database got data that the server doesnt have. 
        /// 3. "newData": There are new projects 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.
        /// </summary>
        /// <returns></returns>
        private async Task<String> CheckServerForNewData(List<string> studyGroups = null, Dictionary<string, string> filter = null)
        {
            string queryParams = CreateQueryParams(studyGroups, null, filter);
            //"api/v1/jobs/lastmodifed"
            string adress = Adress + "/" + "lastmodified" + queryParams;
            System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData - adress: " + adress);
            Uri url = new Uri(adress);
            System.Diagnostics.Debug.WriteLine("ProjectController - 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("ProjectController - 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("ProjectController - 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("ProjectController - CheckServerForNewData: await client.GetAsync(\"url\") Failed");
                System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: Exception msg: " + e.Message);
                System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: Stack Trace: \n" + e.StackTrace);
                System.Diagnostics.Debug.WriteLine("ProjectController - 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("amountOfProjects"))
                {
                    string uuid = dict["uuid"].ToString();
                    DateTime dateTime = (DateTime)dict["modified"];
                    long modified = long.Parse(dateTime.ToString("yyyyMMddHHmmss"));
                    string uuids = dict["hash"].ToString();
                    int amountOfProjects = 0;
                    try
                    {
                        amountOfProjects = Int32.Parse(dict["amountOfProjects"].ToString());
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: await client.GetAsync(\"url\") Failed");
                        System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: Exception msg: " + ex.Message);
                        System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: Stack Trace: \n" + ex.StackTrace);
                        System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: End Of Stack Trace");
                        return null;
                    }

                    DbProject dbProject = new DbProject();
                    bool existInDb = dbProject.ExistsInDb(uuid, modified);
                    if (!existInDb)
                    {
                        return "newData";
                        //return existInDb;
                    }
                    var localProjects = dbProject.GetProjectsFromDbBasedOnFilter(studyGroups, filter, true);
                    int localDbCount = localProjects.Count();

                    StringBuilder sb = new StringBuilder();
                    foreach (var project in localProjects)
                    {
                        sb.Append(project.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 (amountOfProjects > localDbCount)
                        {
                            return "newData";
                            //return !existInDb;
                        }

                        return "incorrectCache";
                    }
                    return "exists";
                    //return existInDb;
                }
            }
            return null;
        }
        /// <summary>
        /// Updates the Project 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 UpdateProjectFromServer(string uuid)
        {
            System.Diagnostics.Debug.WriteLine("ProjectController - UpdateProjectFromServer(string uuid): initiated");
            string adress = Adress + "/" + uuid;
            System.Diagnostics.Debug.WriteLine("UpdateProjectFromServer: var url = " + adress);

            DbStudent dbStudent = new DbStudent();
            string accessToken = dbStudent.GetStudentAccessToken();
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                Authenticater.Authorized = false;
                return;
            }

            Uri url = new Uri(adress);
            var client = new HttpClient();
            System.Diagnostics.Debug.WriteLine("ProjectController - UpdateProjectFromServer: HttpClient created");
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
            string jsonString = null;
            try
            {
                var response = await client.GetAsync(url);
                System.Diagnostics.Debug.WriteLine("UpdateProjectFromServer response " + response.StatusCode.ToString());
                //results = await response.Content.ReadAsAsync<IEnumerable<Project>>();
                jsonString = await response.Content.ReadAsStringAsync();

            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("ProjectController - UpdateProjectFromServer: await client.GetAsync(\"url\") Failed");
                System.Diagnostics.Debug.WriteLine("ProjectController - UpdateProjectFromServer: Exception msg: " + e.Message);
                System.Diagnostics.Debug.WriteLine("ProjectController - UpdateProjectFromServer: Stack Trace: \n" + e.StackTrace);
                System.Diagnostics.Debug.WriteLine("ProjectController - UpdateProjectFromServer: End Of Stack Trace");
                return;
            }
            Deserialize(jsonString);

        }
        /// <summary>
        /// Gets a project based on optional filters.
        /// </summary>
        /// <param name="studyGroups">studyGroups can be a list of numerous studygroups ex: helse, idrettsfag, datateknologi </param>>
        /// <param name="filter">A dictionary where key can be: titles (values:title of the project), types (values: virksomhet, faglærer, etc...),
        ///                      courses (values: "IS-304" "DAT-304" osv). 
        ///                      Supports only 1 key at this current implementation!</param>
        /// <returns></returns>
        public async Task<IEnumerable<Project>> GetProjectsBasedOnFilter(List<string> studyGroups = null,
            Dictionary<string, string> filter = null)
        {
            DbProject db = new DbProject();
            //string adress = "http://kompetansetorgetserver1.azurewebsites.net/api/v1/projects";

            string instructions = await CheckServerForNewData(studyGroups, filter);
            if (!Authenticater.Authorized)
            {
                return null;
            }
            if (instructions != null)
            {
                System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter - instructions" + instructions);
                if (instructions == "exists")
                {
                    IEnumerable<Project> filteredProjects = db.GetProjectsFromDbBasedOnFilter(studyGroups, filter);
                    filteredProjects = db.GetAllCompaniesRelatedToProjects(filteredProjects.ToList());
                    return filteredProjects;
                }
            }

            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("GetProjectsBasedOnFilter - url: " + url.ToString());

            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

            string jsonString = null;
            IEnumerable<Project> projects = null;
            try
            {
                var response = await client.GetAsync(url).ConfigureAwait(false);
                System.Diagnostics.Debug.WriteLine("GetProjectsBasedOnFilter 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();
                    if (instructions != null && instructions == "incorrectCache")
                    {
                        var cachedProjects = db.GetProjectsFromDbBasedOnFilter(studyGroups, filter);
                        projects = DeserializeMany(jsonString);
                        // Get all jobs from that local dataset that was not in the dataset provided by the server
                        // These are manually deleted projects and have to be cleared from cache.
                        // linear search is ok because of small data set
                        var manuallyDeletedProjects = cachedProjects.Where(p => !projects.Any(cp2 => cp2.uuid == p.uuid));
                        db.DeleteObsoleteProjects(manuallyDeletedProjects.ToList());
                    }
                    else
                    {
                        projects = DeserializeMany(jsonString);
                    }
                }

                else
                {
                    System.Diagnostics.Debug.WriteLine("GetProjectsBasedOnFilter - Using the local database");
                    projects = db.GetProjectsFromDbBasedOnFilter(studyGroups, filter);
                    projects = db.GetAllCompaniesRelatedToProjects(projects.ToList());
                }
                return projects;
            }
            catch (Exception e)
            {
                // Hack workaround if mobil data and wifi is turned off
                try
                {
                    System.Diagnostics.Debug.WriteLine("GetProjectsBasedOnFilter - Using the local database");
                    projects = db.GetProjectsFromDbBasedOnFilter(studyGroups, filter);
                    projects = db.GetAllCompaniesRelatedToProjects(projects.ToList());
                    return projects;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("ProjectsController - GetProjectsBasedOnFilter: await client.GetAsync(\"url\") Failed");
                    System.Diagnostics.Debug.WriteLine("ProjectsController - GetProjectsBasedOnFilter: Exception msg: " + e.Message);
                    System.Diagnostics.Debug.WriteLine("ProjectsController - GetProjectsBasedOnFilter: Stack Trace: \n" + e.StackTrace);
                    System.Diagnostics.Debug.WriteLine("ProjectsController - GetProjectsBasedOnFilter: End Of Stack Trace");
                    return null;
                }
            }
        }
        /// <summary>
        /// This method is called after authentication is successfull.
        /// Implement functionality that is useful as initial server communication. 
        /// </summary>
        /// <param name="account"></param>
        async void PerformAuth2TestRequests(Account account)
        {
            Authorized = true;
            App.SuccessfulLoginAction();

            try
            {

                /*
                System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests before looop");


                foreach (KeyValuePair<string, string> p in account.Properties)
                {
                    System.Diagnostics.Debug.WriteLine("Property: Key:" + p.Key + " Value:" + p.Value);
                }
                System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests before looop");

                System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests: Url:" + AuthProvider.ApiRequests);
                System.Diagnostics.Debug.WriteLine("Request Url:" + AuthProvider.ApiRequests);
                */
                Uri requestLocalToken = new Uri(AuthProvider.ApiRequests + account.Properties["access_token"]);
                System.Diagnostics.Debug.WriteLine("Requesting local token");
                System.Diagnostics.Debug.WriteLine("Using access_token: " + account.Properties["access_token"]);
                OAuth2Request request1 = new OAuth2Request("GET", requestLocalToken, null, account);
                //OAuth2Request request1 = new OAuth2Request("GET", requestLocalToken, null, null);

                IResponse response1 = await request1.GetResponseAsync();
                System.Diagnostics.Debug.WriteLine("After Response");


                Dictionary<string, string> responseDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(response1.GetResponseText());


                string localToken = "";
                string username = "";

                if (response1.StatusCode == 200)
                {
                    System.Diagnostics.Debug.WriteLine("Response code from backend: 200");
                    localToken = responseDict["access_token"];
                    username = responseDict["userName"];
                    System.Diagnostics.Debug.WriteLine("username: "******"localToken: " + localToken);

                    StudentsController sc = new StudentsController();
                    DbStudent dbStudent = new DbStudent();
                    if (dbStudent.CheckIfStudentExist(username))
                    {
                        System.Diagnostics.Debug.WriteLine("Student did exist");
                        Student student = dbStudent.GetStudent(username);
                        student.accessToken = localToken;
                        dbStudent.UpdateStudent(student);
                        DevicesController dc = new DevicesController();
                        dc.UpdateServersDb();
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Student did not exist");
                        dbStudent.DeleteAllStudents();
                        Student student = new Student();
                        student.username = username;
                        student.accessToken = localToken;
                        student.receiveNotifications = true;
                        student.receiveJobNotifications = true;
                        student.receiveProjectNotifications = true;
                        dbStudent.InsertStudent(student);
                        DevicesController dc = new DevicesController();
                        DbDevice dbDevice = new DbDevice();
                        dbDevice.FixStudentForeignKey(username);
                        dc.UpdateServersDb();
                    }
                }
                /*
                string studentEndpoint = "http://kompetansetorgetserver1.azurewebsites.net/api/v1/students";
                Uri testAuthorize = new Uri(studentEndpoint);


                //authorization: bearer b2Dvqzi9Ux_FAjbBYat6PE-LgNGKL_HDBWbnJ3Fb9cwfjaE8NQdqcvC8jwSB5QJUIVRog_gQQPjaRI0DT7ahu7TEpqP28URtPr1LjgaV - liCqgIuTdSHW_NqD3qh - 5shVh - h7TCin7XNHq8GSkGg5qtOlcHeFPSZ4xMwMbw5_1rBfKYJr3w0_D5R9jk0hJPEfJldCTYcawatz7wVfbmz0qKHAkrKxZyaqum6IHJWdczWz5K26RCfZWMwEmK1uLN5

                var client = new HttpClient();
                System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests before Setting AuthenticationHeaderValue");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", localToken);
                System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests after Setting AuthenticationHeaderValue");
            System.Diagnostics.Debug.WriteLine(client.DefaultRequestHeaders.Authorization.Parameter);


                var response = await client.GetAsync(testAuthorize);


                System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests: StatusCode:" + response.StatusCode);
                                                 // + " ResponseUri:" + response.ResponseUri);
                //System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests: Headers:");


                foreach (KeyValuePair<string, string> h in response.Headers)
                {
                    System.Diagnostics.Debug.WriteLine("Header: Key:" + h.Key + " Value:" + h.Value);
                } 
                System.Diagnostics.Debug.WriteLine("Response(" + response.StatusCode);
                string jsonString = await response.Content.ReadAsStringAsync();
                System.Diagnostics.Debug.WriteLine(jsonString);
                */
                // TODO Implement relevant GET, PUT or POST Requests
                // Notifies the app that the login was successful and that its safe to shift page.
                Authorized = true;
                App.SuccessfulLoginAction();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception: PerformAuth2TestRequests: Message:" + ex.Message);
                foreach (KeyValuePair<string, string> p in account.Properties)
                {
                    System.Diagnostics.Debug.WriteLine("Key:" + p.Key + " Value:" + p.Value);
                }
            }

        }
        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;
            }
        }
 /// <summary>
 /// Updates the students notification preferances.
 /// </summary>
 /// <param name="receiveNotifications"></param>
 /// <param name="receiveProjectNotifications"></param>
 /// <param name="receiveJobNotifications"></param>
 public void UpdateStudentsNotificationsPref(bool receiveNotifications,
     bool receiveProjectNotifications, bool receiveJobNotifications)
 {
     DbStudent db = new DbStudent();
     Student student = db.GetStudent();
     student.receiveNotifications = receiveNotifications;
     student.receiveProjectNotifications = receiveProjectNotifications;
     student.receiveJobNotifications = receiveJobNotifications;
     db.UpdateStudent(student);
 }
Пример #19
0
        public void SetNavPageToNotificationList()
        {
            DbStudent dbStudent = new DbStudent();
            Student student = dbStudent.GetStudent();

            if (student == null || student.accessToken == null)
            {
                Authenticater.Authorized = false;
            }
            UpdateAllFilters();
            NavPage = new NavigationPage(new CarouselVarsler());
        }