/// <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);
        }
Пример #2
0
        /// <summary>
        /// Peter ikke se på denne metoden, den er kun for å teste databasen :D
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void TestProjectsFilterDb_OnClicked(object sender, EventArgs e)
        {
            List <string> studyGroups   = new List <string>();
            string        helse         = Hasher.Base64Encode("helse");
            string        datateknologi = Hasher.Base64Encode("datateknologi");

            studyGroups.Add(helse);
            studyGroups.Add(datateknologi);
            //LEGG FAGOMRÅDER TIL AKTIVT FILTER HER MED EN SWITCH ELLER LIGNENDE


            Dictionary <string, string> filter = new Dictionary <string, string>();
            string DAT304     = Hasher.Base64Encode("DAT-304");
            string virksomhet = Hasher.Base64Encode("virksomhet");

            filter.Add("courses", DAT304);
            filter.Add("types", virksomhet);

            DbProject pc       = new DbProject();
            var       projects = pc.GetProjectsFromDbBasedOnFilter(null, filter);

            if (projects == null)
            {
                System.Diagnostics.Debug.WriteLine("TestProjectsFilterDb:  was null aka failed!");
            }

            else
            {
                System.Diagnostics.Debug.WriteLine("TestProjectsFilterDb: projects.Count(): " +
                                                   projects.Count());

                foreach (var project in projects)
                {
                    System.Diagnostics.Debug.WriteLine("projects title: " + project.title);
                    if (project.companies != null)
                    {
                        System.Diagnostics.Debug.WriteLine("Companies is not null: " + project.companies[0].id);
                    }
                }
            }

            var projects2 = pc.GetProjectsFromDbBasedOnFilter(studyGroups);

            if (projects2 == null)
            {
                System.Diagnostics.Debug.WriteLine("TestProjectsFilterDb:  was null aka failed!");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("GetProjectsFromDbBasedOnFilter: projects2.Count(): " +
                                                   projects2.Count());

                foreach (var project in projects2)
                {
                    System.Diagnostics.Debug.WriteLine("project2 title: " + project.title);
                    if (project.companies != null)
                    {
                        System.Diagnostics.Debug.WriteLine("Companies is not null: " + project.companies[0].id);
                        System.Diagnostics.Debug.WriteLine("Companies is not null: " + project.companies[0].name);
                        System.Diagnostics.Debug.WriteLine("Companies is not null: " + project.companies[0].logo);
                    }
                }
            }

            var projects3 = pc.GetProjectsFromDbBasedOnFilter(studyGroups, filter);

            if (projects3 == null)
            {
                System.Diagnostics.Debug.WriteLine("TestProjectsFilterDb:  was null aka failed!");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("GetProjectsFromDbBasedOnFilter: projects3.Count(): " +
                                                   projects3.Count());

                foreach (var project in projects3)
                {
                    System.Diagnostics.Debug.WriteLine("projects3 title: " + project.title);
                    if (project.companies != null)
                    {
                        System.Diagnostics.Debug.WriteLine("Companies is not null: " + project.companies[0].id);
                    }
                }
            }

            Dictionary <string, string> filter2 = new Dictionary <string, string>();

            //string titles = Hasher.Base64Encode("Strømavleser vha gammel mobil");
            filter2.Add("titles", "Strømavleser vha gammel mobil");
            Dictionary <string, string> filter3 = new Dictionary <string, string>();

            filter3.Add("titles", "vha");

            var projects4 = pc.GetProjectsFromDbBasedOnFilter(studyGroups, filter2);
            var projects5 = pc.GetProjectsFromDbBasedOnFilter(null, filter3);

            if (projects4 == null || projects5 == null)
            {
                System.Diagnostics.Debug.WriteLine("TestProjectsFilterDb:  was null aka failed!");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("GetProjectsFromDbBasedOnFilter: projects4.Count(): " +
                                                   projects4.Count());

                System.Diagnostics.Debug.WriteLine("GetProjectsFromDbBasedOnFilter: projects5.Count(): " +
                                                   projects5.Count());
                foreach (var project in projects4)
                {
                    System.Diagnostics.Debug.WriteLine("projects4 title: " + project.title);
                    if (project.companies != null)
                    {
                        System.Diagnostics.Debug.WriteLine("Companies is not null: " + project.companies[0].id);
                    }
                }
            }
        }
        /// <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);
                }
            }
        }