예제 #1
0
        /// <summary>
        /// Inserts the project and its respective children (only Company and CompanyProject) 
        /// into the database.
        /// </summary>
        /// <param name="student"></param>
        /// <returns>Returns true if the project was inserted, returns false if a project with the same 
        ///  uuid (primary key) already exists in the table.</returns>
        public bool InsertStudent(Student student)
        {
            if (CheckIfStudentExist(student.username))
            {
                System.Diagnostics.Debug.WriteLine("DbStudent - InsertStudent: Student not inserted, already exist");
                return false;
            }

            System.Diagnostics.Debug.WriteLine("DbStudent - InsertStudent: Student not inserted");
            //Student did not exist, safe to insert.
            DbDevice dbDevice = new DbDevice();

            lock (DbContext.locker)
            {
                Db.Insert(student);
            }

            if (student.devices != null)
            {
                foreach (Device d in student.devices)
                {
                    dbDevice.InsertDevice(d);
                }
            }

            else
            {
                dbDevice.FixStudentForeignKey(student.username);
            }

            return true;
        }
예제 #2
0
        /// <summary>
        /// Inserts the project and its respective children (only Company and CompanyProject)
        /// into the database.
        /// </summary>
        /// <param name="student"></param>
        /// <returns>Returns true if the project was inserted, returns false if a project with the same
        ///  uuid (primary key) already exists in the table.</returns>
        public bool InsertStudent(Student student)
        {
            if (CheckIfStudentExist(student.username))
            {
                System.Diagnostics.Debug.WriteLine("DbStudent - InsertStudent: Student not inserted, already exist");
                return(false);
            }

            System.Diagnostics.Debug.WriteLine("DbStudent - InsertStudent: Student not inserted");
            //Student did not exist, safe to insert.
            DbDevice dbDevice = new DbDevice();

            lock (DbContext.locker)
            {
                Db.Insert(student);
            }

            if (student.devices != null)
            {
                foreach (Device d in student.devices)
                {
                    dbDevice.InsertDevice(d);
                }
            }

            else
            {
                dbDevice.FixStudentForeignKey(student.username);
            }

            return(true);
        }
예제 #3
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>
        /// 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();
            }
        }
예제 #5
0
        /// <summary>
        /// Deletes a student and its related devices.
        /// </summary>
        /// <param name="student"></param>
        public void DeleteStudentWithChilds(Student student)
        {
            if (CheckIfStudentExist(student.username))
            {
                DbDevice dbDevice = new DbDevice();
                foreach (Device d in student.devices)
                {
                    dbDevice.DeleteDevice(d);
                }

                lock (DbContext.locker)
                {
                    System.Diagnostics.Debug.WriteLine("DbStudent - DeleteStudentWithChilds: Before delete.");
                    Db.Delete <Student>(student.username);
                    System.Diagnostics.Debug.WriteLine("DbStudent - DeleteStudentWithChilds: After delete.");
                }
            }
        }
예제 #6
0
        /// <summary>
        /// Gets the student with the specified username
        /// </summary>
        /// <returns></returns>
        public void UpdateStudentWithChilds(Student student)
        {
            if (!CheckIfStudentExist(student.username))
            {
                System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: There was no stored record of Student.");
                InsertStudent(student);
            }
            System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: There was a record of project in the database.");
            if (student.devices != null)
            {
                DbDevice dbDevice = new DbDevice();
                foreach (Device d in student.devices)
                {
                    if (!dbDevice.InsertDevice(d))
                    {
                        System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: Device already exists: Calling UpdateDevice.");

                        dbDevice.UpdateDevice(d);
                    }
                }
            }

            try
            {
                lock (DbContext.locker)
                {
                    System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: Before Updating project.");

                    Db.Update(student);
                    System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: After Updating project.");

                    // Db.InsertOrReplaceWithChildren(project, recursive: true);
                    //Db.UpdateWithChildren(project);
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: Project update failed");
                System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: Exception msg: " + e.Message);
                System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: Stack Trace: \n" + e.StackTrace);
                System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: End Of Stack Trace");
            }
        }
예제 #7
0
        /// <summary>
        /// Deletes a student and its related devices.
        /// </summary>
        /// <param name="student"></param>
        public void DeleteStudentWithChilds(Student student)
        {
            if (CheckIfStudentExist(student.username))
            {
                DbDevice dbDevice = new DbDevice();
                foreach (Device d in student.devices)
                {
                    dbDevice.DeleteDevice(d);
                }

                lock (DbContext.locker)
                {
                    System.Diagnostics.Debug.WriteLine("DbStudent - DeleteStudentWithChilds: Before delete.");
                    Db.Delete<Student>(student.username);
                    System.Diagnostics.Debug.WriteLine("DbStudent - DeleteStudentWithChilds: After delete.");
                }
            }
        }
예제 #8
0
        /// <summary>
        /// Gets the student with the specified username
        /// </summary>
        /// <returns></returns>
        public void UpdateStudentWithChilds(Student student)
        {
            if (!CheckIfStudentExist(student.username))
            {
                System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: There was no stored record of Student.");
                InsertStudent(student);
            }
            System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: There was a record of project in the database.");
            if (student.devices != null)
            {
                DbDevice dbDevice = new DbDevice();
                foreach (Device d in student.devices)
                {
                    if (!dbDevice.InsertDevice(d))
                    {
                        System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: Device already exists: Calling UpdateDevice.");

                        dbDevice.UpdateDevice(d);
                    }
                }
            }

            try
            {
                lock (DbContext.locker)
                {
                    System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: Before Updating project.");

                    Db.Update(student);
                    System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: After Updating project.");

                    // Db.InsertOrReplaceWithChildren(project, recursive: true);
                    //Db.UpdateWithChildren(project);
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: Project update failed");
                System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: Exception msg: " + e.Message);
                System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: Stack Trace: \n" + e.StackTrace);
                System.Diagnostics.Debug.WriteLine("DbStudent - UpdateStudentWithChilds: End Of Stack Trace");
            }
        }
        /// <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;
            }
        }