예제 #1
0
        private void Seed()
        {
            var projectSkill1 = new ProjectSkill {
                ProjectId = 1, SkillId = 1
            };
            var projectSkill2 = new ProjectSkill {
                ProjectId = 2, SkillId = 2
            };

            this._projectSkillRepository.Insert(projectSkill1);
            this._projectSkillRepository.Insert(projectSkill2);


            var userSkill1 = new UserSkill {
                UserId = "1", SkillId = 1
            };
            var userSkill2 = new UserSkill {
                UserId = "2", SkillId = 2
            };

            this._userSkillRepository.Insert(userSkill1);
            this._userSkillRepository.Insert(userSkill2);


            this._skillRepository.Insert(new Skill {
                Id = 1, SkillName = "Java", Users = new List <UserSkill> {
                    userSkill1
                }
            });
            this._skillRepository.Insert(new Skill {
                Id = 2, SkillName = "C++", Projects = new List <ProjectSkill> {
                    projectSkill1
                }
            });
        }
예제 #2
0
파일: Alpha.cs 프로젝트: harisbr/School
        static void getProjectSkills()
        {
            Console.Write("PROJECTSKILLS: ");
            DataTable rawData = Utility.OpenExcel(sourceData, "ProjectSkill");
            int       N       = 0;

            foreach (DataRow row in rawData.Rows)
            {
                string teamName = Utility.getString(row, 2);
                Team   team     = context.Teams.Where(x => x.Name == teamName).FirstOrDefault();

                string toolName = Utility.getString(row, 1);
                Tool   tool     = context.Tools.Where(x => x.Name == toolName).FirstOrDefault();

                ProjectSkill projectSkill = new ProjectSkill()
                {
                    Level = (Level)Utility.getInteger(row, 0),
                    Team  = team,
                    Tool  = tool
                };

                N++;
                context.ProjectSkills.Add(projectSkill);
            }
            context.SaveChanges();
            Console.WriteLine(N);
        }
예제 #3
0
    public void RenderBossSkillNotice(ProjectSkill skill)
    {
        StopAllCoroutines();

        PlayerNoticeText.gameObject.SetActive(false);
        PlayerNoticeText.text = string.Empty;
        BossSkillText.text    = string.Empty;

        SetBossSkillNoticeActiveState(true);

        if (skill is ProjectBurfSkill)
        {
            RenderBossSkillNotice(skill as ProjectBurfSkill);
        }
        else if (skill is ProjectSingleDeburfSkill)
        {
            RenderBossSkillNotice(skill as ProjectSingleDeburfSkill);
        }
        else if (skill is ProjectMultiDeburfSkill)
        {
            RenderBossSkillNotice(skill as ProjectMultiDeburfSkill);
        }
        else if (skill is ProjectSingleAttackSkill)
        {
            RenderBossSkillNotice(skill as ProjectSingleAttackSkill);
        }
        else if (skill is ProjectMultiAttackSkill)
        {
            RenderBossSkillNotice(skill as ProjectMultiAttackSkill);
        }

        StartCoroutine(AutomaticTurnOffText(BossSkillText, 2.5f));
    }
예제 #4
0
        public bool UpdateProjectSkills(int projectId, int[] skills)
        {
            try
            {
                Project project = _projectRepository.Get(projectId);

                if (skills != null)
                {
                    List <ProjectSkill> prefferedSkills = new List <ProjectSkill>();
                    foreach (int x in skills)
                    {
                        var cur = new ProjectSkill();
                        cur.ProjectId = project.Id;
                        cur.SkillId   = x;
                        prefferedSkills.Add(cur);
                    }

                    project.PrefferedSkills = prefferedSkills;
                }

                this._projectRepository.Update(project);

                var result = this._projectRepository.Save();

                if (result == 0)
                {
                    return(false);
                }
                return(true);
            }
            catch (Exception e)
            {
                throw new Exception("Failed to update the project: " + e.Message);
            }
        }
예제 #5
0
        public bool PostProject(Project project, int[] skills)
        {
            try
            {
                if (skills != null)
                {
                    List <ProjectSkill> prefferedSkills = new List <ProjectSkill>();
                    foreach (int x in skills)
                    {
                        var cur = new ProjectSkill();
                        cur.ProjectId = project.Id;
                        cur.SkillId   = x;
                        prefferedSkills.Add(cur);
                    }
                    project.PrefferedSkills = prefferedSkills;
                }

                if (this._projectRepository.Insert(project) == null)
                {
                    return(false);
                }

                if (this._projectRepository.Save() == 0)
                {
                    return(false);
                }

                return(true);
            }catch (Exception e)
            {
                throw new Exception("Failed to create a new project: " + e.Message);
            }
        }
예제 #6
0
    public ProjectSkill Invoke()
    {
        ProjectSkill ret = Ability.InvokedSkill;

        anim.Play(ret.Information.Animation);
        ret.ResetCoolDown();
        return(ret);
    }
예제 #7
0
        public async Task <Result <Unit> > Handle(Command request, CancellationToken cancellationToken)
        {
            if (request.Project.PhotoFiles.Count <= 0)
            {
                return(Result <Unit> .Failure("File Missing"));
            }
            foreach (IFormFile item in request.Project.PhotoFiles)
            {
                var photoResult = await _photoAccessor.AddPhoto(item);

                if (photoResult == null)
                {
                    return(Result <Unit> .Failure("Failed to upload photo"));
                }

                var photo = new Photo
                {
                    Id     = photoResult.PublicId,
                    Url    = photoResult.Url,
                    IsMain = request.Project.Photos.Count <= 0 ? true : false,
                };
                request.Project.Photos.Add(photo);
            }

            if (request.Project.SkillId.Count <= 0)
            {
                return(Result <Unit> .Failure("No Skill ID added here"));
            }
            foreach (Guid item in request.Project.SkillId)
            {
                var SkillResult = await _context.Skills.FindAsync(item);

                if (SkillResult == null)
                {
                    return(Result <Unit> .Failure("Failed find skill"));
                }

                var projectSkill = new ProjectSkill
                {
                    SKill   = SkillResult,
                    Project = request.Project
                };

                request.Project.Skills.Add(projectSkill);
            }

            _context.Projects.Add(request.Project);

            var result = await _context.SaveChangesAsync() > 0;

            if (result)
            {
                return(Result <Unit> .Success(Unit.Value));
            }
            return(Result <Unit> .Failure("Failed to add Project"));
        }
        public ActionResult AddAndEditProject(FormProject model)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Account"));
            }
            var accID   = int.Parse(User.Identity.Name);
            var acc     = new AccountDao().FindAccountById(accID);
            var project = new Project();

            if (model.typeAction == "add")
            {
                project.CreateDate = DateTime.Now;
                project.MasterID   = acc.UserId;
            }
            else
            {
                project.ProjectID = model.saveID;
            }
            project.ProjectMajor = model.major;
            project.Title        = model.title;
            project.Amount       = model.amount;
            project.Apply        = 1;
            project.Description  = model.description;
            var check = -1;

            if (model.typeAction == "add")
            {
                check = new ProjectDao().Insert(project);
                var projectMember = new ProjectMember();
                projectMember.ProjectID  = check;
                projectMember.MemberID   = acc.UserId;
                projectMember.CreateDate = DateTime.Now;
                projectMember.Status     = "master";
                var checkSecond = new ProjectMemberDao().Insert(projectMember);
            }
            else
            {
                var edit = new ProjectDao().Edit(project);
            }
            if (model.skill != null && model.skill.Count != 0)
            {
                var prSkillDao = new ProjectSkillDao();
                foreach (var item in model.skill)
                {
                    var prk = new ProjectSkill();
                    prk.ProjectSkill1 = item;
                    prk.ProjectID     = check != -1 ? check : model.saveID;
                    var echInsert = prSkillDao.Insert(prk);
                }
            }
            return(RedirectToAction("ListProject"));
        }
예제 #9
0
 public bool Insert(ProjectSkill ps)
 {
     try
     {
         db.ProjectSkills.Add(ps);
         db.SaveChanges();
         return(true);
     }
     catch (Exception e)
     {
         return(false);
     }
 }
예제 #10
0
        public async Task <IActionResult> SaveProject(Project Project, int[] skillList, Boolean check1, Boolean check2)
        {
            var _Project = new Project
            {
                Employer_ID          = (int)HttpContext.Session.GetInt32("Employer_ID"),
                ProjectName          = Project.ProjectName,
                Description          = Project.Description,
                TypeProject_ID       = Project.TypeProject_ID,
                Budget               = Project.Budget,
                Timelength           = Project.Timelength,
                StartingDate         = Project.StartingDate,
                EndDate              = Project.EndDate,
                ProjectStatus        = true,
                ProjectAuctionStatus = false,
                ProjectTimeOut       = DateTime.Now.AddDays(15),
                Date_Create          = DateTime.Now,
                Date_Update          = DateTime.Now,
                DelStatus            = false,
            };

            if (check1)
            {
                _Project.StartingDate         = DateTime.Now;
                _Project.ProjectAuctionStatus = true;
            }
            if (check2)
            {
                _Project.EndDate = DateTime.Now.AddDays(15);
            }
            _context.Project.Add(_Project);
            await _context.SaveChangesAsync();

            int id = _Project.Project_ID;

            foreach (var skillLists in skillList)
            {
                var _ProjectSkill = new ProjectSkill
                {
                    Skill_ID    = skillLists,
                    Project_ID  = id,
                    Date_Create = DateTime.Now,
                    Date_Update = DateTime.Now,
                    DelStatus   = false,
                };
                _context.ProjectSkill.Add(_ProjectSkill);
                _context.SaveChanges();
            }
            return(Json(new { _Project }));
        }
예제 #11
0
        private List <ProjectSkill> AddProjectSkillsBySkills(List <Skill> skills, Project project)
        {
            var projectSkills = new List <ProjectSkill>();

            foreach (var item in skills)
            {
                var projectSkill = new ProjectSkill
                {
                    ProjectSkillId = Guid.NewGuid().ToString(),
                    Project        = project,
                    Skill          = item
                };
                projectSkills.Add(projectSkill);
            }
            return(projectSkills);
        }
예제 #12
0
        public IActionResult UpdateSkillProject(int id, int[] skills)
        {
            var _Project = _context.ProjectSkill.Where(p => p.Project_ID == id).ToArray();

            if (_Project.Length == 0)
            {
                foreach (var skillLists in skills)
                {
                    var _ProjectSkill = new ProjectSkill
                    {
                        Skill_ID    = skillLists,
                        Project_ID  = id,
                        Date_Create = DateTime.Now,
                        Date_Update = DateTime.Now,
                        DelStatus   = false,
                    };
                    _context.ProjectSkill.Add(_ProjectSkill);
                    _context.SaveChanges();
                }
            }
            else
            {
                foreach (var _Projects in _Project)
                {
                    _context.ProjectSkill.Remove(_Projects);
                    _context.SaveChanges();
                }
                foreach (var skillLists in skills)
                {
                    var _ProjectSkill = new ProjectSkill
                    {
                        Skill_ID    = skillLists,
                        Project_ID  = id,
                        Date_Create = DateTime.Now,
                        Date_Update = DateTime.Now,
                        DelStatus   = false,
                    };
                    _context.ProjectSkill.Add(_ProjectSkill);
                    _context.SaveChanges();
                }
            }
            var Results = new { id, skills };

            return(Json(new { Result = _Project }));
        }
예제 #13
0
        }    // end public async Task<IActionResult> OnGet(int? id)

        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }     // endif (!ModelState.IsValid)

            ProjectSkill projectSkill = new ProjectSkill()
            {
                ProjectId = Project.ProjectId,
                SkillCode = SkillTitle.SkillCode
            };

            _context.ProjectSkills.Add(projectSkill);
            await _context.SaveChangesAsync();

            return(RedirectToPage("./CustomerProjectSkills", new { id = Project.ProjectId }));
        } // end public async Task<IActionResult> OnPostAsync()
예제 #14
0
        public IActionResult UpdateProjectSkill(int[] skillList)
        {
            var SessionProject_ID = HttpContext.Session.GetInt32("Project_ID");

            foreach (var skillLists in skillList)
            {
                var _ProjectSkill = new ProjectSkill
                {
                    Skill_ID    = skillLists,
                    Project_ID  = (int)SessionProject_ID,
                    Date_Create = DateTime.Now,
                    Date_Update = DateTime.Now,
                    DelStatus   = false,
                };
                _context.ProjectSkill.Add(_ProjectSkill);
                _context.SaveChanges();
            }

            return(Json(new { Result = "OK" }));
        }
        public JsonResult PostProjectSkill(string projectid, string skillid)
        {
            try
            {
                IDAL         dal             = (new DALFactory()).GetInstance();
                ProjectSkill objProjectSkill = dal.PostProjectSkill(projectid, skillid);
                return(new JsonResult {
                    Data = objProjectSkill
                });
            }
            catch (Exception ex)
            {
                UserManager user = (UserManager)Session["CurrentUser"];
                LogHelper.AddLog(new LogEntity(AppConstant.PartitionError, user.EmailID.ToString(), AppConstant.ApplicationName, "ProjectSkills, DeleteProjectSkill", ex.Message, ex.StackTrace));

                return(new JsonResult {
                    Data = null
                });
            }
        }
예제 #16
0
        public async Task <Project> AddProjectAsync(AddProjectViewModel model,
                                                    CancellationToken cancellationToken = default(CancellationToken))
        {
            //Check exists project in database
            var isExists = await _dbContext.Projects.AnyAsync(c => c.Name == model.Name, cancellationToken);

            if (isExists)
            {
                throw new Exception();
            }

            var transaction = _dbContext.Database.BeginTransaction();

            try
            {
                //Inial Project object
                var project = new Project();

                project.UserId       = model.UserId;
                project.Name         = model.Name;
                project.Description  = model.Description;
                project.FinishedTime = model.FinishedTime;
                project.StartedTime  = model.StatedTime;

                //Add project to database
                project = _dbContext.Projects.Add(project);
                if (model.SkillIds != null)
                {
                    #region add project skill

                    //check exists skill
                    var countSkills = await _dbContext.Skills.Where(c => model.SkillIds.Contains(c.Id)).CountAsync();

                    var isExistSkills = countSkills == model.SkillIds.Count;

                    if (!isExistSkills)
                    {
                        throw new Exception();
                    }

                    //Insert to projectSkill table
                    foreach (var skillId in model.SkillIds)
                    {
                        var projectSkill = new ProjectSkill();

                        projectSkill.ProjectId = project.Id;
                        projectSkill.SkillId   = skillId;

                        //Add to db context
                        _dbContext.ProjectSkills.Add(projectSkill);
                    }

                    #endregion
                }

                if (model.ResponsibilityIds != null)
                {
                    #region Project responsibilitis

                    // check exists responsibilities
                    var countRespon = await _dbContext.Responsibilities
                                      .Where(c => model.ResponsibilityIds.Contains(c.Id)).CountAsync();

                    var isExistsRespon = countRespon == model.ResponsibilityIds.Count;

                    if (!isExistsRespon)
                    {
                        throw new Exception();
                    }

                    //Insert project responsibility to db context
                    foreach (var responsibilityId in model.ResponsibilityIds)
                    {
                        var projectResponsibility = new ProjectResponsibility();

                        projectResponsibility.ProjectId        = project.Id;
                        projectResponsibility.ResponsibilityId = responsibilityId;
                        projectResponsibility.CreatedTime      = DateTime.UtcNow.ToOADate();

                        //Add to db context
                        _dbContext.ProjectResponsibilities.Add(projectResponsibility);
                    }

                    #endregion
                }


                //Save changes to database
                await _dbContext.SaveChangesAsync(cancellationToken);

                //Commit transaction
                transaction.Commit();
                return(project);
            }
            catch (Exception e)
            {
                transaction.Rollback();
                throw new Exception(e.Message);
            }
        }
예제 #17
0
        public async Task <IHttpActionResult> AddProject([FromBody] AddProjectViewModel model)
        {
            if (model == null)
            {
                model = new AddProjectViewModel();
                Validate(model);
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //Check exists project in database
            var projects = _unitOfWork.Projects.Search();

            projects = projects.Where(x => x.Name.Contains(model.Name));

            var project = await projects.FirstOrDefaultAsync();

            if (project != null)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Conflict, "EXISTS_CODE_ERROR")));
            }

            var transaction = _unitOfWork.BeginTransactionScope();

            try
            {
                //Inial Project object
                project = new Project();

                project.UserId       = model.UserId;
                project.Name         = model.Name;
                project.Description  = model.Description;
                project.FinishedTime = model.FinishedTime;
                project.StartedTime  = model.StatedTime;

                //Add project to database
                _unitOfWork.Projects.Insert(project);
                if (model.SkillIds != null)
                {
                    #region add project skill

                    //check exists skill
                    var skills          = _unitOfWork.Skills.Search();
                    var availableSkills = await skills.Where(x => model.SkillIds.Contains(x.Id)).ToListAsync();

                    // Insert to projectSkill table
                    foreach (var skill in availableSkills)
                    {
                        var projectSkill = new ProjectSkill();

                        projectSkill.ProjectId = project.Id;
                        projectSkill.SkillId   = skill.Id;

                        //Add to db context
                        _unitOfWork.ProjectSkills.Insert(projectSkill);
                    }

                    #endregion
                }

                if (model.ResponsibilityIds != null)
                {
                    #region Project responsibilitis

                    // Find available responsibilities.
                    var responsibilities          = _unitOfWork.Responsibilities.Search();
                    var availableResponsibilities = await responsibilities.Where(x => model.ResponsibilityIds.Contains(x.Id)).ToListAsync();

                    //Insert project responsibility to db context
                    foreach (var responsibility in availableResponsibilities)
                    {
                        var projectResponsibility = new ProjectResponsibility();

                        projectResponsibility.ProjectId        = project.Id;
                        projectResponsibility.ResponsibilityId = responsibility.Id;
                        projectResponsibility.CreatedTime      = DateTime.UtcNow.ToOADate();

                        //Add to db context
                        _unitOfWork.ProjectResponsibilities.Insert(projectResponsibility);
                    }

                    #endregion
                }

                //Save changes to database
                await _unitOfWork.CommitAsync();

                //Commit transaction
                transaction.Commit();

                //Success
                return(Ok(project));
            }
            catch (Exception e)
            {
                transaction.Rollback();
                return(Conflict());
            }
        }
예제 #18
0
        /// <summary>
        /// <inheritdoc />
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task <Project> EditProjectAsync(int id, EditProjectViewModel model,
                                                             CancellationToken cancellationToken = default(CancellationToken))
        {
            var loadProjectCondition = new SearchProjectViewModel();

            loadProjectCondition.Ids = new HashSet <int>();
            loadProjectCondition.Ids.Add(id);

            var profile = _profileService.GetProfile(_httpRequestMessage);

            if (profile == null)
            {
                throw new HttpException((int)HttpStatusCode.Forbidden, HttpMessages.ActionIsForbidden);
            }

            // Non admin user can only edit his/her project.
            if (profile.Role != UserRoles.Admin)
            {
                loadProjectCondition.UserIds = new HashSet <int>();
                loadProjectCondition.UserIds.Add(profile.Id);
            }

            var project = await GetProjects(loadProjectCondition).FirstOrDefaultAsync(cancellationToken);

            if (project == null)
            {
                throw new HttpException((int)HttpStatusCode.NotFound, HttpMessages.ProjectNotFound);
            }

            // Transaction begin.
            var transaction = _unitOfWork.BeginTransactionScope();

            //Update information
            project.UserId       = model.UserId;
            project.Name         = model.Name;
            project.Description  = model.Description;
            project.FinishedTime = model.FinishedTime;
            project.StartedTime  = model.StatedTime;

            // Update skills
            if (model.SkillIds != null)
            {
                // Get the list of available skills.
                var skills          = _unitOfWork.Skills.Search();
                var availableSkills = await skills.Where(x => model.SkillIds.Contains(x.Id)).ToListAsync(cancellationToken);

                var projectSkills = _unitOfWork.ProjectSkills.Search();
                projectSkills = projectSkills.Where(x => x.ProjectId == id);
                _unitOfWork.ProjectSkills.Remove(projectSkills);

                foreach (var availableSkill in availableSkills)
                {
                    var projectSkill = new ProjectSkill();
                    projectSkill.ProjectId = id;
                    projectSkill.SkillId   = availableSkill.Id;

                    _unitOfWork.ProjectSkills.Insert(projectSkill);
                }
            }

            // Update responsibilities
            if (model.ResponsibilityIds != null)
            {
                // Get the list of available skills.
                var responsibilities          = _unitOfWork.Responsibilities.Search();
                var availableResponsibilities = await responsibilities.Where(x => model.ResponsibilityIds.Contains(x.Id)).ToListAsync(cancellationToken);

                var projectResponsibilities = _unitOfWork.ProjectResponsibilities.Search();
                projectResponsibilities = projectResponsibilities.Where(x => x.ProjectId == id);
                _unitOfWork.ProjectResponsibilities.Remove(projectResponsibilities);

                foreach (var availableResponsibility in availableResponsibilities)
                {
                    var projectResponsibility = new ProjectResponsibility();
                    projectResponsibility.ProjectId        = id;
                    projectResponsibility.ResponsibilityId = availableResponsibility.Id;

                    _unitOfWork.ProjectResponsibilities.Insert(projectResponsibility);
                }
            }

            await _unitOfWork.CommitAsync();

            transaction.Commit();
            return(project);
        }
예제 #19
0
        public async Task <IHttpActionResult> Update([FromUri] int id, [FromBody] EditProjectViewModel model)
        {
            if (model == null)
            {
                model = new EditProjectViewModel();
                Validate(model);
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //Find  Project
            var projects = _unitOfWork.Projects.Search();
            var project  = await projects.FirstOrDefaultAsync(x => x.Id == id);

            if (project == null)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound,
                                                                   HttpMessages.ProjectNotFound)));
            }

            //Update information
            project.UserId       = model.UserId;
            project.Name         = model.Name;
            project.Description  = model.Description;
            project.FinishedTime = model.FinishedTime;
            project.StartedTime  = model.StatedTime;

            #region  Update skills

            // Update skills
            if (model.SkillIds != null)
            {
                // Get the list of available skills.
                var skills          = _unitOfWork.Skills.Search();
                var availableSkills = await skills.Where(x => model.SkillIds.Contains(x.Id)).ToListAsync();

                var projectSkills = _unitOfWork.ProjectSkills.Search();
                projectSkills = projectSkills.Where(x => x.ProjectId == id);
                _unitOfWork.ProjectSkills.Remove(projectSkills);

                foreach (var availableSkill in availableSkills)
                {
                    var projectSkill = new ProjectSkill();
                    projectSkill.ProjectId = id;
                    projectSkill.SkillId   = availableSkill.Id;

                    _unitOfWork.ProjectSkills.Insert(projectSkill);
                }
            }

            // Update responsibilities
            if (model.ResponsibilityIds != null)
            {
                // Get the list of available skills.
                var responsibilities          = _unitOfWork.Responsibilities.Search();
                var availableResponsibilities = await responsibilities.Where(x => model.ResponsibilityIds.Contains(x.Id)).ToListAsync();

                var projectResponsibilities = _unitOfWork.ProjectResponsibilities.Search();
                projectResponsibilities = projectResponsibilities.Where(x => x.ProjectId == id);
                _unitOfWork.ProjectResponsibilities.Remove(projectResponsibilities);

                foreach (var availableResponsibility in availableResponsibilities)
                {
                    var projectResponsibility = new ProjectResponsibility();
                    projectResponsibility.ProjectId        = id;
                    projectResponsibility.ResponsibilityId = availableResponsibility.Id;

                    _unitOfWork.ProjectResponsibilities.Insert(projectResponsibility);
                }
            }

            #endregion

            //Save changes to database
            await _unitOfWork.CommitAsync();

            return(Ok(project));
        }
예제 #20
0
 public void RenderBossSkillNotice(ProjectSkill skill)
 {
     stageNoticeUiPresenter.RenderBossSkillNotice(skill);
 }
예제 #21
0
        public async Task <Result <Unit> > Handle(Command request, CancellationToken cancellationToken)
        {
            Project project = await _context.Projects
                              .Include(p => p.Skills)
                              .Include(p => p.Photos)
                              .Where(p => p.Id == request.Project.Id)
                              .FirstOrDefaultAsync();

            if (project == null)
            {
                return(null);
            }

            if (request.Project.SkillId != null)
            {
                List <Guid> existingSkills = project.Skills.Select(s => s.SkillId).ToList();
                List <Guid> newSkillIds    = new List <Guid>();

                if (existingSkills != null)
                {
                    newSkillIds = request.Project.SkillId.Where(id => !existingSkills.Contains(id)).ToList();
                }

                foreach (Guid id in newSkillIds)
                {
                    Skill skill = await _context.Skills.FindAsync(id);

                    if (skill == null)
                    {
                        return(Result <Unit> .Failure("Coudln't find the Skill in Database"));
                    }

                    var newProjectSkill = new ProjectSkill {
                        ProjectId = project.Id, SkillId = skill.Id
                    };
                    project.Skills.Add(newProjectSkill);
                }
            }

            if (request.Project.PhotoFiles != null)
            {
                foreach (IFormFile item in request.Project.PhotoFiles)
                {
                    var photoResult = await _photoAccessor.AddPhoto(item);

                    if (photoResult == null)
                    {
                        return(Result <Unit> .Failure("Failed to upload photo"));
                    }

                    var photo = new Photo
                    {
                        Id     = photoResult.PublicId,
                        Url    = photoResult.Url,
                        IsMain = request.Project.Photos.Count <= 0 ? true : false,
                    };
                    project.Photos.Add(photo);
                }
            }

            project.Title       = request.Project.Title ?? project.Title;
            project.Details     = request.Project.Details ?? project.Details;
            project.Project_Url = request.Project.Project_Url ?? project.Project_Url;
            project.IsLive      = request.Project.IsLive;
            project.Rating      = request.Project.Rating;

            var result = await _context.SaveChangesAsync() > 0;

            if (result)
            {
                return(Result <Unit> .Success(Unit.Value));
            }

            return(Result <Unit> .Failure("Failed save changes while editing Project"));
        }
        public JsonResult UploadProjectDataFile(HttpPostedFileBase uploadedFile)
        {
            IDAL dal = (new DALFactory()).GetInstance();

            bool          isProjectInserted = false;
            StringBuilder logText           = new StringBuilder();

            try
            {
                logText.Append("<table border = '1'> <tr><th>Result</th></tr>");

                if (uploadedFile != null && uploadedFile.ContentLength > 0)
                {
                    #region Read file data
                    if ((uploadedFile.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || uploadedFile.ContentType == "application/octet-stream") &&
                        (uploadedFile.FileName.EndsWith(".xls") || uploadedFile.FileName.EndsWith(".xlsx")))
                    {
                        string            url             = ConfigurationManager.AppSettings["URL"].ToString();
                        List <Skill>      allSkills       = null;
                        List <Competence> allCompetencies = null;
                        List <Project>    allProjects     = null;

                        try
                        {
                            allSkills       = dal.GetAllSkills();
                            allCompetencies = dal.GetAllCompetenceList();
                            allProjects     = dal.GetAllProjects();
                        }
                        catch (Exception ex)
                        {
                            UserManager user = (UserManager)Session["CurrentUser"];
                            LogHelper.AddLog(new LogEntity(AppConstant.PartitionError, user.EmailID.ToString(), AppConstant.ApplicationName, "ImportProject,UploadProjectDataFile", ex.Message, ex.StackTrace));
                        }

                        List <DataTable> listDataTable  = new List <DataTable>();
                        ProjectData      objProjectData = new ProjectData();
                        using (SpreadsheetDocument doc = SpreadsheetDocument.Open(uploadedFile.InputStream, false))
                        {
                            Sheet sheet        = doc.WorkbookPart.Workbook.Sheets.GetFirstChild <Sheet>();
                            var   listOfSheets = Utilities.GetAllWorksheets(doc);
                            foreach (Sheet sheetItem in listOfSheets)
                            {
                                string            sheetName = sheetItem.Name;
                                string            sheetId   = sheetItem.Id.Value;
                                Worksheet         worksheet = (doc.WorkbookPart.GetPartById(sheetId) as WorksheetPart).Worksheet;
                                IEnumerable <Row> rows      = worksheet.GetFirstChild <SheetData>().Descendants <Row>();
                                DataTable         dt        = new DataTable();
                                int rowcount = rows.Count();

                                foreach (Row row in rows)
                                {
                                    if (row != null)
                                    {
                                        if (row.RowIndex.Value == 1)
                                        {
                                            foreach (Cell cell in row.Descendants <Cell>())
                                            {
                                                dt.Columns.Add(Utilities.GetSpreadsheetCellValue(doc, cell));
                                            }
                                        }
                                        else
                                        {
                                            dt.Rows.Add();
                                            int i = 0;
                                            foreach (Cell cell in row.Descendants <Cell>())
                                            {
                                                dt.Rows[dt.Rows.Count - 1][i] = Utilities.GetSpreadsheetCellValue(doc, cell);
                                                i++;
                                            }
                                        }
                                    }
                                }
                                listDataTable.Add(dt);
                            }
                        }

                        objProjectData.projects = new List <Project>();
                        Project objProject = null;
                        foreach (DataRow item in listDataTable[0].Rows)
                        {
                            objProject             = new Project();
                            objProject.ProjectName = Convert.ToString(item.ItemArray[0]);
                            List <Project> itemProject = allProjects.Where(project => (project.ProjectName).ToLower() == (objProject.ProjectName).ToLower()).ToList();
                            if (itemProject != null && itemProject.Count() > 0)
                            {
                                string duplicateProject = itemProject.FirstOrDefault().ProjectName;
                                logText.Append("<tr><td class='error'>The Project <span class='bold'>" + duplicateProject + "</span>already present.<td><tr>");
                            }
                            else
                            {
                                objProjectData.projects.Add(objProject);
                            }
                        }

                        objProjectData.projectSkills = new List <ProjectSkill>();
                        ProjectSkill objProjectSkill = null;
                        logText.Append("<tr><td>&nbsp;</td></tr>");
                        foreach (DataRow item in listDataTable[1].Rows)
                        {
                            objProjectSkill         = new ProjectSkill();
                            objProjectSkill.Project = item.ItemArray[0] != null?Convert.ToString(item.ItemArray[0]) : "";

                            objProjectSkill.Skill = item.ItemArray[1] != null?Convert.ToString(item.ItemArray[1]) : "";

                            List <Skill> objSkill = allSkills.Where(i => i.SkillName == objProjectSkill.Skill).ToList();
                            objProjectSkill.SkillId = objSkill != null && objSkill.Count() > 0 ? Convert.ToInt32(objSkill.FirstOrDefault().SkillId) : -1;
                            if (objProjectSkill.SkillId == -1)
                            {
                                logText.Append("<tr><td class='error'>Project :<span class='bold'>" + objProjectSkill.Project + "</span>Skill : <span class='bold'>" + objProjectSkill.Skill + "</span> is not valid<td><tr>");
                            }
                            else
                            {
                                objProjectData.projectSkills.Add(objProjectSkill);
                            }
                        }

                        objProjectData.projectSkillResources = new List <ProjectSkillResource>();
                        ProjectSkillResource objProjectSkillResource = null;
                        logText.Append("<tr><td>&nbsp;</td></tr>");
                        foreach (DataRow item in listDataTable[2].Rows)
                        {
                            objProjectSkillResource                        = new ProjectSkillResource();
                            objProjectSkillResource.ProjectName            = Convert.ToString(item.ItemArray[0]);
                            objProjectSkillResource.Skill                  = Convert.ToString(item.ItemArray[1]);
                            objProjectSkillResource.CompetencyLevel        = Convert.ToString(item.ItemArray[2]);
                            objProjectSkillResource.ExpectedResourceCount  = Convert.ToString(item.ItemArray[3]);
                            objProjectSkillResource.AvailableResourceCount = Convert.ToString(item.ItemArray[4]);

                            List <Competence> itemSkillResource = allCompetencies.Where(i => i.SkillName == objProjectSkillResource.Skill && i.CompetenceName.ToUpper() == objProjectSkillResource.CompetencyLevel.ToUpper()).ToList();
                            if (itemSkillResource != null && itemSkillResource.Count() > 0)
                            {
                                objProjectSkillResource.CompetencyLevelId = itemSkillResource != null && itemSkillResource.Count() > 0 ? itemSkillResource.FirstOrDefault().CompetenceId : -1;
                                objProjectSkillResource.SkillId           = itemSkillResource != null && itemSkillResource.Count() > 0 ? itemSkillResource.FirstOrDefault().SkillId : -1;
                                objProjectData.projectSkillResources.Add(objProjectSkillResource);
                            }
                            else
                            {
                                logText.Append("<tr><td class='error'>" +
                                               "For Project : <span class='bold'>" + objProjectSkillResource.ProjectName + "</span>" +
                                               "Skill : <span class='bold'>" + objProjectSkillResource.Skill + "</span>" +
                                               ", Competency Level :  <span class='bold'>" + objProjectSkillResource.CompetencyLevel + "</span>" +
                                               " Combination doesn't exist. So it can't be added to ProjectSkillResource list<td><tr>"

                                               );
                            }
                        }
                        isProjectInserted = InsertProjectFromExcel(
                            objProjectData.projects, objProjectData.projectSkills, objProjectData.projectSkillResources, ref logText);
                    }
                    else
                    {
                        logText.Append("<tr><td>Please upload correct file format<td><tr>");
                    }
                    #endregion Read file data
                }
                else
                {
                    logText.Append("<tr><td>Please upload correct file format<td><tr>");
                }

                logText.Append("</table>");
            }
            catch (Exception ex)
            {
                UserManager user = (UserManager)Session["CurrentUser"];
                LogHelper.AddLog(new LogEntity(AppConstant.PartitionError, user.EmailID.ToString(), AppConstant.ApplicationName, "ImportProject,UploadProjectDataFile", ex.Message, ex.StackTrace));
            }
            return(Json(new
            {
                statusCode = 200,
                status = isProjectInserted,
                message = logText.ToString(),
            }, JsonRequestBehavior.AllowGet));
        }