/// <summary>
        /// Gets all notifications stored in a collection as an 'object'.
        /// These notifications must NOT be mistaken as the Model class Notification.
        /// The objects can be of either Job or Project
        ///
        /// Examples on how to use this list:
        /// List<object> notifications = GetNotificationList();
        /// for (n in notifications) {
        ///     if (n is Job) {
        ///         // DO spesific Job code
        ///         Job job = (Job)n;
        ///         string date = job.expiryDate; // Will work
        ///     }
        ///     else if (n is Project) {
        ///         // Do spesific Project  code.
        ///         Project p = (Project)n;
        ///     }
        /// }
        /// </summary>
        /// <returns>A list of objects suitable for to be dislayed to the user as notifications</returns>
        public List <Advert> GetNotificationList()
        {
            DbJob                      dbJob         = new DbJob();
            DbNotification             db            = new DbNotification();
            JobsController             jc            = new JobsController();
            DbProject                  dbProject     = new DbProject();
            IEnumerable <Notification> notifications = db.GetNotifications();

            List <Advert> notificationList = new List <Advert>();

            foreach (var n in notifications)
            {
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.id = " + n.id);
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.jobUuid = " + n.jobUuid);
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.projectUuid = " + n.projectUuid);

                if (!string.IsNullOrWhiteSpace(n.jobUuid))
                {
                    Job job = dbJob.GetJobByUuid(n.jobUuid);
                    job.companies = dbJob.GetAllCompaniesRelatedToJob(job);
                    notificationList.Add(job);
                }
                else
                {
                    Project project = dbProject.GetProjectByUuid(n.projectUuid);
                    project.companies = dbProject.GetAllCompaniesRelatedToProject(project);
                    notificationList.Add(project);
                }
            }
            return(notificationList.OrderByDescending(a => a.published).ToList());
        }
Example #2
0
        public static Project ToModel(this DbProject dbProject, DbWorkflow dbWorkflow)
        {
            var model = dbProject.ToModel();

            // TODO: Uncomment after workflow extensions have been written.
            // model.Workflow = dbWorkflow.ToModel();
            return(model);
        }
Example #3
0
        public ActionResult ProjectResume(int Id)
        {
            DbProject     ProjectOperations;
            OperationBase dbOperation = new DbProject();

            ProjectOperations = (DbProject)dbOperation;
            var model = ProjectOperations.GetProjectResumeById(Id);

            return(View(model));
        }
Example #4
0
            public async Task <Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                var project = new DbProject {
                    ProjectId = request.ProjectId, ProjectCode = request.ProjectCode, RowVersion = request.RowVersion
                };

                _context.Set <DbProject>().Attach(project);
                _context.Set <DbProject>().Remove(project);
                await _context.SaveChangesAsync(cancellationToken);

                return(Unit.Value);
            }
Example #5
0
 public static Project ToModel(this DbProject dbProject)
 {
     return(new Project {
         Id = dbProject.Id,
         Code = dbProject.Code,
         Name = dbProject.Name,
         WorkflowId = dbProject.WorkflowId.ToString(),
         StartTime = dbProject.StartTime,
         EndTime = dbProject.EndTime,
         Settings = dbProject.Settings
     });
 }
Example #6
0
 private void OnBtnClick(object sender, RoutedEventArgs e)
 {
     if ((sender as Button).DataContext.GetType() == typeof(DbDocument))
     {
         PickedDocument = (sender as Button).DataContext as DbDocument;
     }
     if ((sender as Button).DataContext.GetType() == typeof(DbProject))
     {
         PickedProject = (sender as Button).DataContext as DbProject;
     }
     Close();
 }
Example #7
0
        private async Task PatchDbProject(DbProject dbProject, JsonProject gitlabProject)
        {
            var lastUpdatedUnixTime = gitlabProject.LastActivityAt.ToUnixTimestamp();

            dbProject.LastUpdated       = lastUpdatedUnixTime;
            dbProject.Description       = gitlabProject.Description;
            dbProject.NameWithNamespace = gitlabProject.NameWithNamespace;
            dbProject.TagList           = gitlabProject.TagList.ToArray();

            var projectId = await _databaseService.UpdateProject(dbProject);

            _jsonCache.WriteProject(projectId, gitlabProject);
        }
Example #8
0
        public bool UpdateSecure(DbProject dbProject, Guid userId)
        {
            dbProject.CreatorId = userId;
            var isAdmin = IsAdmin(dbProject.Id, userId);

            if (isAdmin)
            {
                _dbSet.Update(dbProject);
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #9
0
        public Picker(List <DbDocument> documents)
        {
#if Revit2020
            Owner = ModuleData.RevitWindow;
#endif
#if Revit2018
            WindowInteropHelper helper = new WindowInteropHelper(this);
            helper.Owner = ModuleData.MainWindowHandle;
#endif
            PickedProject  = null;
            PickedDocument = null;
            InitializeComponent();
            this.Projects.ItemsSource = documents;
            tbHeader.Text             = "Документы:";
            Title = "KPLN: Выбрать документ";
        }
Example #10
0
        private async Task CreateDbProject(DbAccount account, JsonProject gitlabProject)
        {
            var lastUpdatedUnixTime = gitlabProject.LastActivityAt.ToUnixTimestamp();

            var dbProject = new DbProject
            {
                Account           = account,
                GitlabProjectId   = gitlabProject.Id,
                Description       = gitlabProject.Description,
                LastUpdated       = lastUpdatedUnixTime,
                NameWithNamespace = gitlabProject.NameWithNamespace,
                TagList           = gitlabProject.TagList.ToArray()
            };
            var projectId = await _databaseService.InsertProject(dbProject);

            _jsonCache.WriteProject(projectId, gitlabProject);
        }
Example #11
0
        /// <summary>
        /// Init ViewModel for projectId
        /// </summary>
        /// <param name="projectId">Internal ProjectId (Database) that should be opened</param>
        public async void Init(int projectId)
        {
            // get project info from database
            _dbProject = _gitlabProjectManager.GetProject(projectId);

            // get json project meta data
            _jsonProject = await _gitlabProjectManager.GetCachedProjectMeta(_dbProject);

            // init download for specific gitlab account
            _gitlabProjectDownloader.InitForClient(
                new GitlabAccountClientImpl(_dbProject.Account.HostUrl, _dbProject.Account.AuthenticationToken)
                );
            // delete local folder in database if folder not present on client
            if (!string.IsNullOrEmpty(_dbProject.LocalFolder) && !Directory.Exists(_dbProject.LocalFolder))
            {
                _databaseService.UpdateLocalFolderForProject(_dbProject, "");
            }

            RaiseUpdateProject();
        }
        public List <object> GetNotificationListProjectOnly()
        {
            DbNotification             db               = new DbNotification();
            DbProject                  dbProject        = new DbProject();
            IEnumerable <Notification> notifications    = db.GetNotifications();
            List <object>              notificationList = new List <object>();

            foreach (var n in notifications)
            {
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.id = " + n.id);
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.jobUuid = " + n.jobUuid);
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.projectUuid = " + n.projectUuid);

                if (!string.IsNullOrWhiteSpace(n.projectUuid))
                {
                    Project project = dbProject.GetProjectByUuid(n.projectUuid);
                    project.companies = dbProject.GetAllCompaniesRelatedToProject(project);
                    notificationList.Add(project);
                }
            }
            return(notificationList);
        }
Example #13
0
        /// <summary>
        /// Get cached metadata (json serialization of gitlab project-endpoint)
        /// </summary>
        /// <param name="project">Database project object</param>
        /// <returns>JsonProject with all project metadata</returns>
        public async Task <JsonProject> GetCachedProjectMeta(DbProject project)
        {
            var globalProjectId = project.Id;

            // read from cache
            var cachedProjectMeta = _jsonCache.ReadProject(globalProjectId);

            // return if in cache
            if (cachedProjectMeta != null)
            {
                return(cachedProjectMeta);
            }

            // write into cache
            var account      = project.Account;
            var gitlabClient = _gitlabService.GetGitlabClient(account.HostUrl, account.AuthenticationToken);

            var gitlabProject = await gitlabClient.GetProjectById(project.GitlabProjectId);

            _jsonCache.WriteProject(globalProjectId, gitlabProject);

            return(gitlabProject);
        }
 private bool ProjectIsChecked(DbDocument doc)
 {
     if (doc.Project == null)
     {
         return(false);
     }
     foreach (UIWPFElement e in this.lbProjects.ItemsSource as ObservableCollection <UIWPFElement> )
     {
         DbProject project = e.Element as DbProject;
         if (project.Id == doc.Project.Id)
         {
             if (e.IsChecked)
             {
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
     }
     return(false);
 }
Example #15
0
 /// <summary>
 /// Async method to update project in database
 /// </summary>
 /// <param name="project">Project to save</param>
 /// <returns></returns>
 public async Task <int> UpdateProject(DbProject project)
 {
     _context.Update(project);
     return(await _context.SaveChangesAsync());
 }
Example #16
0
 /// <summary>
 /// Async method to insert project into database
 /// </summary>
 /// <param name="project">Project to save</param>
 /// <returns></returns>
 public async Task <int> InsertProject(DbProject project)
 {
     _context.Add(project);
     return(await _context.SaveChangesAsync());
 }
Example #17
0
 /// <summary>
 /// Update local project folder
 /// </summary>
 /// <param name="project">Project that should be updated</param>
 /// <param name="folderName">Local name of folder</param>
 public void UpdateLocalFolderForProject(DbProject project, string folderName)
 {
     project.LocalFolder = folderName;
     _context.Update(project);
     _context.SaveChanges();
 }
        /// <summary>
        /// Deserializes a singular Project with children objects.
        /// </summary>
        /// <param name="jsonString">Serialized data contain information about project and its children</param>
        /// <returns>A deserialized Project object</returns>
        private Project Deserialize(string jsonString)
        {
            DbProject db = new DbProject();
            Dictionary <string, object> dict = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonString);

            System.Diagnostics.Debug.WriteLine("DeserializeApiData. Printing Key Value:");
            string[] keys = dict.Keys.ToArray();
            Project  p    = new Project();

            p.companies   = new List <Company>();
            p.courses     = new List <Course>();
            p.studyGroups = new List <StudyGroup>();
            p.jobTypes    = new List <JobType>();

            foreach (var key in keys)
            {
                System.Diagnostics.Debug.WriteLine("key: " + key);
                System.Diagnostics.Debug.WriteLine("value: " + dict[key].ToString());

                /*
                 * if (!key.Equals("companies") || !key.Equals("courses") || !key.Equals("degrees")
                 || !key.Equals("jobTypes") || !key.Equals("studyGroup")) {} */
                if (key.Equals("uuid"))
                {
                    p.uuid = dict[key].ToString();
                }
                if (key.Equals("title"))
                {
                    p.title = dict[key].ToString();
                }

                /*
                 * if (key.Equals("description"))
                 * {
                 *  p.description = dict[key].ToString();
                 * }
                 */

                if (key.Equals("webpage"))
                {
                    p.webpage = dict[key].ToString();
                }
                if (key.Equals("published"))
                {
                    DateTime dateTime = (DateTime)dict[key];
                    p.published = long.Parse(dateTime.ToString("yyyyMMddHHmmss"));
                }

                if (key.Equals("modified"))
                {
                    DateTime dateTime = (DateTime)dict[key];
                    p.modified = long.Parse(dateTime.ToString("yyyyMMddHHmmss"));
                }

                if (key.Equals("companies"))
                {
                    // if not true then company already exist and needs to be updated.
                    CompaniesController cc        = new CompaniesController();
                    DbCompany           dbCompany = new DbCompany();
                    IEnumerable         companies = (IEnumerable)dict[key];
                    //`Newtonsoft.Json.Linq.JArray'
                    System.Diagnostics.Debug.WriteLine("companies created");
                    foreach (var comp in companies)
                    {
                        System.Diagnostics.Debug.WriteLine("foreach initiated");
                        Dictionary <string, object> companyDict = JsonConvert.DeserializeObject <Dictionary <string, object> >(comp.ToString());
                        Company company = cc.DeserializeCompany(companyDict);
                        System.Diagnostics.Debug.WriteLine("Deserialize: company.id: " + company.id);
                        p.companies.Add(company);
                        dbCompany.UpdateCompany(company);
                        System.Diagnostics.Debug.WriteLine("Deserialize: After j.companies.Add(company)");
                        string projectUuid = dict["uuid"].ToString();
                        dbCompany.InsertCompanyProject(company.id, projectUuid);
                    }
                }

                if (key.Equals("courses"))
                {
                    DbCourse    dbCourse = new DbCourse();
                    IEnumerable courses  = (IEnumerable)dict[key];
                    //Newtonsoft.Json.Linq.JArray'
                    System.Diagnostics.Debug.WriteLine("location created");
                    foreach (var course in courses)
                    {
                        System.Diagnostics.Debug.WriteLine("foreach initiated");
                        Dictionary <string, object> courseDict =
                            JsonConvert.DeserializeObject <Dictionary <string, object> >(course.ToString());

                        Course co = new Course();
                        if (courseDict.ContainsKey("id"))
                        {
                            co.id = courseDict["id"].ToString();
                            System.Diagnostics.Debug.WriteLine("Course id: " + co.id);
                        }

                        if (courseDict.ContainsKey("name"))
                        {
                            co.name = courseDict["name"].ToString();
                        }

                        dbCourse.InsertCourse(co);
                        p.courses.Add(co);
                        string projectUuid = dict["uuid"].ToString();
                        dbCourse.InsertCourseProject(co.id, projectUuid);
                    }
                }

                if (key.Equals("studyGroups"))
                {
                    DbStudyGroup dbStudyGroup = new DbStudyGroup();
                    IEnumerable  studyGroups  = (IEnumerable)dict[key];
                    //Newtonsoft.Json.Linq.JArray'
                    System.Diagnostics.Debug.WriteLine("studyGroups created");
                    foreach (var studyGroup in studyGroups)
                    {
                        System.Diagnostics.Debug.WriteLine("foreach initiated");
                        Dictionary <string, object> studyGroupDict = JsonConvert.DeserializeObject <Dictionary <string, object> >(studyGroup.ToString());


                        StudyGroup sg = new StudyGroup();
                        if (studyGroupDict.ContainsKey("id"))
                        {
                            sg.id = studyGroupDict["id"].ToString();
                        }

                        if (studyGroupDict.ContainsKey("name"))
                        {
                            sg.name = studyGroupDict["name"].ToString();
                        }

                        p.studyGroups.Add(sg);

                        string projectUuid = dict["uuid"].ToString();
                        dbStudyGroup.InsertStudyGroupProject(sg.id, projectUuid);
                    }
                }

                /*
                 * if (key.Equals("approvedCourses"))
                 * {
                 *
                 *  Same as companies implementation
                 *
                 * }
                 *
                 * if (key.Equals("degrees"))
                 * {
                 *
                 *  Same as companies implementation
                 *
                 * }
                 */
                if (key.Equals("jobTypes"))
                {
                    DbJobType   dbJobType = new DbJobType();
                    IEnumerable jobTypes  = (IEnumerable)dict[key];
                    //Newtonsoft.Json.Linq.JArray'
                    System.Diagnostics.Debug.WriteLine("jobTypes created");
                    foreach (var jobType in jobTypes)
                    {
                        System.Diagnostics.Debug.WriteLine("foreach initiated");
                        Dictionary <string, object> jtDict = JsonConvert.DeserializeObject <Dictionary <string, object> >(jobType.ToString());

                        JobType jt = new JobType();
                        if (jtDict.ContainsKey("id"))
                        {
                            jt.id = jtDict["id"].ToString();
                        }

                        if (jtDict.ContainsKey("name"))
                        {
                            jt.name = jtDict["name"].ToString();
                        }

                        dbJobType.InsertJobType(jt);
                        System.Diagnostics.Debug.WriteLine("before p.jobTypes.Add(jt);");
                        p.jobTypes.Add(jt);

                        string projectUuid = dict["uuid"].ToString();
                        dbJobType.InsertJobTypeProject(jt.id, projectUuid);
                    }
                }
            }
            db.UpdateProject(p);
            return(p);
        }
        /// <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>
        /// 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);
                }
            }
        }
Example #21
0
 public void Create(DbProject dbProject, Guid creatorId)
 {
     dbProject.Admins.Add(_context.Users.Find(creatorId));
     dbProject.CreatorId = creatorId;
     _dbSet.Add(dbProject);
 }
Example #22
0
 public ProjectsController()
 {
     dbOperation       = new DbProject();
     ProjectOperations = (DbProject)dbOperation;
 }
Example #23
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);
                    }
                }
            }
        }
 private Maybe <Project> MaybeProject(DbProject project)
 {
     return(project != null
             ? new Maybe <Project>(project.ToModel())
             : Maybe <Project> .Fail);
 }