public ActionResult Login(ProjectProfile objUser)
        {
            if (!String.IsNullOrEmpty(objUser.Name) && !String.IsNullOrEmpty(objUser.Key))
            {
                Session["ID"]  = objUser.Name.ToString();
                Session["Key"] = objUser.Key.ToString();

                try
                {
                    HttpClient client = new HttpClient();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Add("x-api-key", objUser.Key.ToString());
                    var req = "https://api.applicationinsights.io/beta/apps/" + objUser.Name.ToString() + "/metrics/requests/count";
                    HttpResponseMessage response = client.GetAsync(req).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        ViewBag.Error = string.Empty;
                        return(RedirectToAction("Events"));
                    }
                    else
                    {
                        ViewBag.Error = "Invalid ID or Key";
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.Error = "Server Down! Try later.";
                }
            }
            return(View(objUser));
        }
 public ActionResult DeleteConfirmed(int id)
 {
     ProjectProfile ProjectProfile = db.ProjectProfiles.Find(id);
     db.ProjectProfiles.Remove(ProjectProfile);
     db.SaveChanges();
     return RedirectToAction("Index");
 }
      public static bool EditProjectProfile(ProjectProfile ptb)
         
        {
            try
            {
                db = new UcasProEntities();
                db.Configuration.LazyLoadingEnabled = false;
                db.Configuration.ProxyCreationEnabled = false;
                var q = db.ProjectProfiles.Where(p => p.ID == ptb.ID).SingleOrDefault();
                q.ProjectName = ptb.ProjectName;
                q.ProjectDescription = ptb.ProjectDescription;
                q.StartDate = ptb.StartDate;
                q.EndDate = ptb.EndDate;
                q.Status = ptb.Status;
                q.Coin = ptb.Coin;
                q.TotalCost = ptb.TotalCost;
               
                db.SaveChanges();
                return true;

            }
            catch (Exception ex)
            {


                Xprema.XpremaException e = new Xprema.XpremaException();
                e.CodeNumber = 6;
                e.OtherDescription = ex.InnerException.InnerException.Message;
                e.UserDescription = "Error in Add";
                e.UserDescriptionArabic = "خطاء في اضافة البيانات";
                throw e;
            }
        }
 public ActionResult Create([Bind(Prefix = "Item1", Include = "ProjectProfileID,FunctionID,ProgramID,AccountCodeID,OfficialCodeID,LineNumber,SectorID,ProjectTitle,ProjectDescription,ImpDeptID,ProjStartDate,ProjEndDate,ProjStatusID,ProjExpectedOutput,SourceFundID,BDIPID,ProjCatID,ProjReferenceOutput,ProjItemWork,MunicipalityID,barangayID,ProjPurok,Remarks,ProjPS,ProjMOOE,ProjCapitalOutlay,StrategicPriorityID,StrategicPriorityAreaID,MitigationTypologyID,AdaptationTypologyID")] ProjectProfile ProjectProfile)
 {
     try
     {
         var check2     = ProjectProfile.ProjectTitle;
         var IsExisting = db.ProjectProfiles.FirstOrDefault(user => user.ProjectTitle == check2);
         if (IsExisting == null)
         {
             if (ModelState.IsValid)
             {
                 db.ProjectProfiles.Add(ProjectProfile);
                 db.SaveChanges();
                 return(RedirectToAction("Create"));
             }
         }
         else
         {
             return(View(ProjectProfile));
         }
     }
     catch
     {
         ModelState.AddModelError("", "Project already exists.");
     }
     return(View(ProjectProfile));
 }
Example #5
0
        public async void CreateAProject_NullLocationCheck_ReturnBadRequestException()
        {
            var errMessage            = "Bad Request";
            LocationResource location = null;
            var summary = new ProjectSummary {
                Title            = "",
                Location         = location,
                ProjectStartDate = new System.DateTime(),
                ProjectEndDate   = new System.DateTime(),
                ProjectNumber    = "test"
            };
            var manager = new ProjectManager {
                UserID    = "1",
                FirstName = "",
                LastName  = ""
            };
            var profile = new ProjectProfile {
                ProjectSummary = summary,
                ProjectManager = manager,
                UsersSummary   = Enumerable.Empty <UserSummary>(),
                Openings       = Enumerable.Empty <OpeningPositionsSummary>()
            };

            var result = (await _controller.CreateAProject(profile)) as ObjectResult;

            Assert.Equal(StatusCodes.Status400BadRequest, result.StatusCode);
            Assert.IsType <BadRequestException>(result.Value);
            var response = result.Value as BadRequestException;

            Assert.Equal(errMessage, response.status);
        }
Example #6
0
        public async Task <string> CreateAProject(ProjectProfile projectProfile, int locationId)
        {
            using var connection = new SqlConnection(connectionString);

            var createdProjectId = await this.CreateAProject(connection, locationId, projectProfile.ProjectSummary, projectProfile.ProjectManager);

            if (createdProjectId != 0)
            {
                if (projectProfile.Openings != null)
                {
                    foreach (var opening in projectProfile.Openings)
                    {
                        var newOpeningId = await this.CreateAnOpeningPosition(connection, opening, createdProjectId);

                        if (opening.Skills.Count != 0)
                        {
                            foreach (var skill in opening.Skills)
                            {
                                await this.CreatePositionSkill(connection, newOpeningId, skill);
                            }
                        }
                    }
                }
            }

            return(projectProfile.ProjectSummary.ProjectNumber);
        }
        // GET: NewProjects/Edit/5
        public ActionResult Edit(int?id)
        {
            SectoralCodeDD();
            OfficialCodeDD();
            ClimateChangeAdaptationDD();
            ClimateChangeMitigationDD();
            AccountCodeDD();
            BDIPperMunicipalityDD();
            ImplementingDepartmentDD();
            MunicipalityDD();
            PriorityAreaDD();
            ProgramCodeDD();
            ProjectCategoryDD();
            ProjectStatusDD();
            SectorDD();
            SourceOfFundDD();
            TypologyCodeDD();

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ProjectProfile projectProfile = db.ProjectProfiles.Find(id);

            if (projectProfile == null)
            {
                return(HttpNotFound());
            }
            return(View(projectProfile));
        }
Example #8
0
        public async Task GetProjectByIdActionResult_ReturnsAProjectDto()
        {
            IEnumerable <Project> projects = new List <Project> {
                new Project
                {
                    Id      = 1,
                    Name    = "value 101",
                    Version = 1.0
                }
            };

            var mockProjectService = new Mock <IProjectService>();

            mockProjectService.Setup(x => x.GetProjects(false)).Returns(Task.FromResult(projects));
            var profile      = new ProjectProfile();
            var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile(profile));
            var mockMapper   = new Mock <Mapper>(mapperConfig);
            var mockLinkGen  = new Mock <LinkGenerator>();

            var controller = new ProjectsController(mockProjectService.Object, mockMapper.Object, mockLinkGen.Object);

            // Act
            var result = await controller.GetProjectById(1);

            // Assert
            var actionResult = Assert.IsType <ActionResult <ProjectDto> >(result);

            Assert.IsType <NotFoundObjectResult>(actionResult.Result);
        }
Example #9
0
        public async Task <IActionResult> UpdateAProject([FromBody] ProjectProfile projectProfile, string projectNumber)
        {
            if (projectProfile == null)
            {
                var error = new BadRequestException("The given project profile is null / Request Body cannot be read");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (
                projectProfile.ProjectManager == null || String.IsNullOrEmpty(projectProfile.ProjectManager.UserID) ||
                projectProfile.ProjectSummary == null ||
                String.IsNullOrEmpty(projectProfile.ProjectSummary.ProjectNumber) || String.IsNullOrEmpty(projectNumber) ||
                projectProfile.ProjectSummary.Location == null
                )
            {
                var error = new BadRequestException("The Project (Manager(ID) / Summary / Number / Location) cannot be null or empty string!");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (projectProfile.ProjectSummary.ProjectNumber != projectNumber)
            {
                var errMessage = $"The project number on URL '{projectNumber}'" +
                                 $" does not match with '{projectProfile.ProjectSummary.ProjectNumber}' in Request Body's Project Summary";
                var error = new BadRequestException(errMessage);
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                var location = await locationsRepository.GetALocation(projectProfile.ProjectSummary.Location.City);

                var updatedProjectNumber = await projectsRepository.UpdateAProject(projectProfile, location.Id);

                var response = new UpdatedResponse <string>(updatedProjectNumber, "Successfully updated");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                if (err is CustomException <InternalServerException> )
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, ((CustomException <InternalServerException>)err).GetException()));
                }
                else
                {
                    var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                    if (err is SqlException)
                    {
                        var error = new InternalServerException(errMessage);
                        return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                    }
                    else
                    {
                        var error = new BadRequestException(errMessage);
                        return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                    }
                }
            }
        }
Example #10
0
        public ProjectServiceTest()
        {
            // https://stackoverflow.com/questions/40275195/how-to-setup-automapper-in-asp-net-core
            var profile = new ProjectProfile();

            var config = new MapperConfiguration(ex => ex.AddProfile(profile));

            _mapper = new Mapper(config);

            (_mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid();
        }
Example #11
0
        public async void CreateAProject_NullProfileCheck_ReturnBadRequestException()
        {
            var            errMessage = "Bad Request";
            ProjectProfile profile    = null;

            var result = (await _controller.CreateAProject(profile)) as ObjectResult;

            Assert.Equal(StatusCodes.Status400BadRequest, result.StatusCode);
            Assert.IsType <BadRequestException>(result.Value);
            var response = result.Value as BadRequestException;

            Assert.Equal(errMessage, response.status);
        }
 // GET: ProjectProfile/Delete/5
 public ActionResult Delete(int? id)
 {
     if (id == null)
     {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }
     ProjectProfile ProjectProfile = db.ProjectProfiles.Find(id);
     if (ProjectProfile == null)
     {
         return HttpNotFound();
     }
     return View(ProjectProfile);
 }
        // GET: NewProjects/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ProjectProfile projectProfile = db.ProjectProfiles.Find(id);

            if (projectProfile == null)
            {
                return(HttpNotFound());
            }
            return(View(projectProfile));
        }
Example #14
0
        public async Task GetProjectByIdActionResult_ReturnsNotFound()
        {
            var mockProjectService = new Mock <IProjectService>();
            var profile            = new ProjectProfile();
            var mapperConfig       = new MapperConfiguration(cfg => cfg.AddProfile(profile));
            var mockMapper         = new Mock <Mapper>(mapperConfig);
            var mockLinkGen        = new Mock <LinkGenerator>();

            var controller = new ProjectsController(mockProjectService.Object, mockMapper.Object, mockLinkGen.Object);

            // Act
            var result = await controller.GetProjectById(-1);

            // Assert
            var actionResult = Assert.IsType <ActionResult <ProjectDto> >(result);

            Assert.IsType <NotFoundObjectResult>(actionResult.Result);
        }
Example #15
0
        public async Task GetProjectById_Returns_A_Project()
        {
            // Arrange
            Guid projectId          = Guid.NewGuid();
            var  fakeProjectService = A.Fake <IProjectService>();
            var  fakeResult         = A.Dummy <Task_Management_System.Models.Project>();

            A.CallTo(() => fakeProjectService.GetByIdAsync(projectId)).Returns(Task.FromResult(fakeResult));
            var     myProfile     = new ProjectProfile();
            var     configuration = new MapperConfiguration(cfg => cfg.AddProfile(myProfile));
            IMapper mapper        = new Mapper(configuration);
            var     controller    = new ProjectsController(fakeProjectService, mapper);

            // Act
            var actionResult = await controller.GetProjectById(projectId);

            // Assert
            //var result = actionResult.
        }
Example #16
0
 public static bool AddNewProject(ProjectProfile tb)
   {
       try
       {
            db = new UcasProEntities();
       db.ProjectProfiles.Add(tb);
       db.SaveChanges();
       return true;
       }
       catch (Exception ex)
       {
           
             Xprema.XpremaException e = new Xprema.XpremaException();
           e.CodeNumber = 6;
           e.OtherDescription = ex.InnerException.InnerException.Message;
           e.UserDescription = "Error in Add";
           e.UserDescriptionArabic = "خطاء في اضافة البيانات";
           throw e;
       }
      
   }
Example #17
0
        public async void CreateAProject_CatchBlockProjectErr_ReturnsBadRequestException()
        {
            string errMessage          = "Bad Request";
            var    badRequestException = new CustomException <BadRequestException>(new BadRequestException(errMessage));

            Setup_LocationsRepo_GetALocation_Default(new Location());
            Setup_ProjectsRepo_CreateAProject_ThrowsException(badRequestException);
            var location = new LocationResource {
                LocationID = 1,
                Province   = "",
                City       = ""
            };
            var summary = new ProjectSummary {
                Title            = "",
                Location         = location,
                ProjectStartDate = new System.DateTime(),
                ProjectEndDate   = new System.DateTime(),
                ProjectNumber    = "test"
            };
            var manager = new ProjectManager {
                UserID    = "1",
                FirstName = "",
                LastName  = ""
            };
            var profile = new ProjectProfile {
                ProjectSummary = summary,
                ProjectManager = manager,
                UsersSummary   = Enumerable.Empty <UserSummary>(),
                Openings       = Enumerable.Empty <OpeningPositionsSummary>()
            };

            var result = (await _controller.CreateAProject(profile)) as ObjectResult;

            Assert.Equal(StatusCodes.Status400BadRequest, result.StatusCode);
            Assert.IsType <BadRequestException>(result.Value);
            var response = result.Value as BadRequestException;

            Assert.Equal(errMessage, response.status);
        }
Example #18
0
        public async void CreateAProject_CatchBlockProjectErr_ReturnsSqlException()
        {
            var errMessage   = "Internal Server Error";
            var sqlException = new SqlExceptionBuilder().WithErrorNumber(50000).WithErrorMessage(errMessage).Build();

            Setup_LocationsRepo_GetALocation_Default(new Location());
            Setup_ProjectsRepo_CreateAProject_ThrowsException(sqlException);
            var location = new LocationResource {
                LocationID = 1,
                Province   = "",
                City       = ""
            };
            var summary = new ProjectSummary {
                Title            = "",
                Location         = location,
                ProjectStartDate = new System.DateTime(),
                ProjectEndDate   = new System.DateTime(),
                ProjectNumber    = "test"
            };
            var manager = new ProjectManager {
                UserID    = "1",
                FirstName = "",
                LastName  = ""
            };
            var profile = new ProjectProfile {
                ProjectSummary = summary,
                ProjectManager = manager,
                UsersSummary   = Enumerable.Empty <UserSummary>(),
                Openings       = Enumerable.Empty <OpeningPositionsSummary>()
            };

            var result = (await _controller.CreateAProject(profile)) as ObjectResult;

            Assert.Equal(StatusCodes.Status500InternalServerError, result.StatusCode);
            var response = result.Value as InternalServerException;

            Assert.Equal(errMessage, response.status);
        }
Example #19
0
        public async void CreateAProject_TryBlock_ValidCreation()
        {
            Setup_LocationsRepo_GetALocation_Default(new Location());
            Setup_ProjectsRepo_CreateAProject_Default("1");
            var location = new LocationResource {
                LocationID = 1,
                Province   = "",
                City       = ""
            };
            var summary = new ProjectSummary {
                Title            = "",
                Location         = location,
                ProjectStartDate = new System.DateTime(),
                ProjectEndDate   = new System.DateTime(),
                ProjectNumber    = "test"
            };
            var manager = new ProjectManager {
                UserID    = "1",
                FirstName = "",
                LastName  = ""
            };
            var profile = new ProjectProfile {
                ProjectSummary = summary,
                ProjectManager = manager,
                UsersSummary   = Enumerable.Empty <UserSummary>(),
                Openings       = Enumerable.Empty <OpeningPositionsSummary>()
            };

            var result = (await _controller.CreateAProject(profile)) as ObjectResult;

            Assert.Equal(StatusCodes.Status201Created, result.StatusCode);
            Assert.IsType <CreatedResponse <string> >(result.Value);
            var response = result.Value as CreatedResponse <string>;

            Assert.IsType <string>(response.payload);
        }
Example #20
0
        public async Task <IActionResult> GetAProject(string projectNumber)
        {
            if (String.IsNullOrEmpty(projectNumber))
            {
                var error = new BadRequestException("The given project number is null/empty");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }
            try
            {
                var project = await projectsRepository.GetAProjectResource(projectNumber);

                if (project == null)
                {
                    var error = new NotFoundException($"No project at projectNumber '{projectNumber}' found");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }
                var projectSummary = mapper.Map <ProjectResource, ProjectSummary>(project);

                var projectManager = mapper.Map <ProjectResource, ProjectManager>(project);

                var users = await usersRepository.GetAllUserResourcesOnProject(project.Id, project.ManagerId);

                if (users == null || !users.Any())
                {
                    users = new UserResource[] { };
                }
                var usersSummary = mapper.Map <IEnumerable <UserResource>, IEnumerable <UserSummary> >(users);

                var openingPositions = await positionsRepository.GetAllUnassignedPositionsResourceOfProject(project.Id);

                if (openingPositions == null || !openingPositions.Any())
                {
                    openingPositions = new OpeningPositionsResource[] { };
                }
                var openingPositionsSummary = mapper.Map <IEnumerable <OpeningPositionsResource>, IEnumerable <OpeningPositionsSummary> >(openingPositions);

                var projectProfile = new ProjectProfile
                {
                    ProjectSummary = projectSummary,
                    ProjectManager = projectManager,
                    UsersSummary   = usersSummary,
                    Openings       = openingPositionsSummary
                };

                var response = new OkResponse <ProjectProfile>(projectProfile, "Everything is good");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Example #21
0
 /// <summary>
 /// Add new project to the TACS.NET database.
 /// </summary>
 /// <param name="project"></param>
 /// <param name="credentials"></param>
 public void AddProjectProfile(ProjectProfile project, Credentials credentials)
 {
     string result = String.Empty;
     ProjectServiceProxy.ProjectService projectService =
         new iCampaign.TACS.ProjectServiceProxy.ProjectService();
     try
     {
         result = projectService.AddProject(project, credentials);
     }
     catch (Exception ex)
     {
         throw ex;
     }
     if (result != "OK")
     {
         throw new System.SystemException(result);
     }
 }
Example #22
0
        public async Task <string> UpdateAProject(ProjectProfile projectProfile, int locationId)
        {
            using var connection = new SqlConnection(connectionString);

            var projectSummary = projectProfile.ProjectSummary;
            var projectManager = projectProfile.ProjectManager;
            var updatedCount   = await this.UpdateAProject(connection, locationId, projectSummary, projectManager);

            if (updatedCount != 1)
            {
                var errMessage = $"Query returns failure status on updating project number '{projectProfile.ProjectSummary.ProjectNumber}'";
                var error      = new InternalServerException(errMessage);
                throw new CustomException <InternalServerException>(error);
            }

            else
            {
                var projectId = await this.GetProjectId(connection, projectSummary.ProjectNumber);

                var currentOpeningIds = await this.GetCurrentOpeningIdsForProject(connection, projectId);

                if (
                    (currentOpeningIds != null && currentOpeningIds.Any()) &&
                    (projectProfile.Openings == null || !projectProfile.Openings.Any())
                    )
                {
                    var deletedCount = await this.DeleteAllOpeningPositions(connection, projectId);

                    if (deletedCount != currentOpeningIds.Count())
                    {
                        var error = new InternalServerException(
                            $@"Deleted opening counts ({deletedCount}) is not the same as Current opening counts ({currentOpeningIds.Count()})"
                            );
                        throw new CustomException <InternalServerException>(error);
                    }
                }
                else
                {
                    var request     = projectProfile.Openings.Select(opening => opening.PositionID);
                    var toDeleteIds = currentOpeningIds.Except(request);
                    if (toDeleteIds != null && toDeleteIds.Count() > 0)
                    {
                        var deletedCount = await this.DeleteOpeningPositions(connection, toDeleteIds);

                        if (deletedCount != toDeleteIds.Count())
                        {
                            var error = new InternalServerException(
                                $@"Deleted opening counts ({deletedCount}) is not the same as To Be Deleted opening counts ({toDeleteIds.Count()})"
                                );
                            throw new CustomException <InternalServerException>(error);
                        }
                    }

                    foreach (var opening in projectProfile.Openings)
                    {
                        if (!currentOpeningIds.Contains(opening.PositionID))
                        {
                            var newOpeningId = await this.CreateAnOpeningPosition(connection, opening, projectId);

                            if (opening.Skills.Count != 0)
                            {
                                foreach (var skill in opening.Skills)
                                {
                                    await this.CreatePositionSkill(connection, newOpeningId, skill);
                                }
                            }
                        }
                        else
                        {
                            var updateOpeningSuccess = await this.UpdateAnOpeningPosition(connection, opening, projectId);

                            if (updateOpeningSuccess == 1)
                            {
                                if (opening.Skills.Count != 0)
                                {
                                    var currentSkillIds = await GetCurrentPositionSkillIds(connection, opening.PositionID);

                                    var openingSkillIds = await GetSkillIds(connection, opening.Skills, opening.Discipline);

                                    foreach (var id in openingSkillIds)
                                    {
                                        if (!currentSkillIds.Contains(id))
                                        {
                                            await this.CreatePositionSkill(connection, opening.PositionID, id);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return(projectSummary.ProjectNumber);
            }
        }
Example #23
0
        public async Task <IActionResult> UpdateProject(Int16 ProjectId, [FromBody] Project item)
        {
            if (item == null || item.Id != ProjectId)
            {
                return(BadRequest());
            }

            var model = await ApplicationDbContext.Projects.Include(f => f.Financingforms).Include(p => p.Participants).ThenInclude(p => p.Participant).FirstOrDefaultAsync(o => o.Id == ProjectId);

            if (model == null)
            {
                var msg = String.Format(FAILGETENTITYBYID, ProjectId);
                return(NotFound(msg));
            }


            if (item.Title != null)
            {
                model.Title       = item.Title;
                model.Shorttitle  = item.Shorttitle;
                model.Subtitle    = item.Subtitle;
                model.Description = item.Description;
                model.Startdate   = item.Startdate;
                model.Enddate     = item.Enddate;
            }

            if (item.Abstract != null)
            {
                model.Abstract = item.Abstract;
            }

            // budget
            if (model.Budget != null)
            {
                Budget budget;
                if (model.BudgetId > 0)
                {
                    budget = ApplicationDbContext.Budgets.FirstOrDefault(m => m.Id == model.BudgetId);
                }
                else
                {
                    budget = new Budget();
                }

                budget.TotalBudget      = model.Budget.TotalBudget;
                budget.ArteveldeBudget  = model.Budget.ArteveldeBudget;
                budget.InvestmentBudget = model.Budget.InvestmentBudget;
                budget.OperatingBudget  = model.Budget.OperatingBudget;
                budget.StaffBudget      = model.Budget.StaffBudget;
                model.BudgetValidate    = item.BudgetValidate;

                model.Budget = budget;
            }

            if (item.Profiles != null)
            {
                foreach (var profile in item.Profiles.ToList())
                {
                    Profile profile1 = ApplicationDbContext.Profiles.FirstOrDefault(m => m.Id == profile.ProfileId);

                    var af = new ProjectProfile {
                        Project = item, Profile = profile1
                    };

                    ApplicationDbContext.ProjectProfile.Add(af);
                }
            }



            if (item.Financingforms != null || item.Participants != null || item.Tags != null || item.Partners != null || item.Links != null)
            {
                // many financingform; delete old + add new
                var oldProjectFinancingforms = ApplicationDbContext.ProjectFinancingform.Where(m => m.ProjectId == model.Id).ToList();

                foreach (var oldProjectFinancingform in oldProjectFinancingforms)
                {
                    //model.Financingforms.Remove(oldProjectFinancingform);
                    ApplicationDbContext.Entry(oldProjectFinancingform).State  =  EntityState.Deleted;
                    ApplicationDbContext.SaveChanges();
                }
                if (item.Financingforms != null)
                {
                    foreach (var financingform in item.Financingforms.ToList())
                    {
                        Financingform financingform1 = ApplicationDbContext.Financingforms.FirstOrDefault(m => m.Id == financingform.FinancingformId);

                        var af = new ProjectFinancingform {
                            Project = item, Financingform = financingform1
                        };

                        ApplicationDbContext.ProjectFinancingform.Add(af);
                    }
                }


                // many participants; delete old + add new
                var oldProjectParticipants = ApplicationDbContext.ProjectParticipant.Where(m => m.ProjectId == model.Id).ToList();

                foreach (var oldProjectParticipant in oldProjectParticipants)
                {
                    ApplicationDbContext.Entry(oldProjectParticipant).State  =  EntityState.Deleted;
                    ApplicationDbContext.SaveChanges();
                }

                if (item.Participants != null)
                {
                    foreach (var participant in item.Participants.ToList())
                    {
                        Participant participant1 = ApplicationDbContext.Participants.FirstOrDefault(m => m.Id == participant.ParticipantId);

                        var af = new ProjectParticipant {
                            Project = item, Participant = participant1
                        };

                        ApplicationDbContext.ProjectParticipant.Add(af);
                    }
                }



                //tags
                var oldTags = ApplicationDbContext.Tags.Where(m => m.ProjectId == model.Id).ToList();

                foreach (var oldTag in oldTags)
                {
                    ApplicationDbContext.Entry(oldTag).State  =  EntityState.Deleted;
                    ApplicationDbContext.SaveChanges();
                }

                List <Tag> tags = new List <Tag>();
                if (item.Tags != null)
                {
                    foreach (var tag in item.Tags.ToList())
                    {
                        var tag1 = new Tag();
                        tag1.Name = tag.Name;

                        tags.Add(tag1);
                        model.Tags = tags;
                    }
                }


                //partners
                var oldPartners = ApplicationDbContext.Partners.Where(m => m.ProjectId == model.Id).ToList();
                foreach (var oldPartner in oldPartners)
                {
                    ApplicationDbContext.Entry(oldPartner).State  =  EntityState.Deleted;
                    ApplicationDbContext.SaveChanges();
                }

                List <Partner> partners = new List <Partner>();
                if (item.Partners != null)
                {
                    foreach (var partner in item.Partners.ToList())
                    {
                        var partner1 = new Partner();
                        partner1.Name = partner.Name;

                        partners.Add(partner1);
                        model.Partners = partners;
                    }
                }


                //links
                var oldLinks = ApplicationDbContext.Links.Where(m => m.ProjectId == model.Id).ToList();

                foreach (var oldLink in oldLinks)
                {
                    ApplicationDbContext.Entry(oldLink).State  =  EntityState.Deleted;
                    ApplicationDbContext.SaveChanges();
                }

                List <Link> links = new List <Link>();
                if (item.Links != null)
                {
                    foreach (var link in item.Links.ToList())
                    {
                        var link1 = new Link();
                        link1.Name = link.Name;

                        links.Add(link1);
                        model.Links = links;
                    }
                }
            }

            //mediums
            if (item.Mediums != null)
            {
                var oldMediums = ApplicationDbContext.Mediums.Where(m => m.ProjectId == model.Id).ToList();

                foreach (var oldMedia in oldMediums)
                {
                    ApplicationDbContext.Entry(oldMedia).State  =  EntityState.Deleted;
                    ApplicationDbContext.SaveChanges();
                }

                List <Media> mediums = new List <Media>();
                foreach (var media in item.Mediums.ToList())
                {
                    var media1 = new Media();
                    media1.Image     = media.Image;
                    media1.TypeMedia = media.TypeMedia;

                    mediums.Add(media1);
                    model.Mediums = mediums;
                }
            }


            ApplicationDbContext.Projects.Attach(model);
            ApplicationDbContext.Entry(model).State = EntityState.Modified;
            await ApplicationDbContext.SaveChangesAsync();

            return(new NoContentResult());
        }
Example #24
0
      public static bool DeleteProjectProfile(int xid)
        {
            try
            {
                db = new UcasProEntities();
                ProjectProfile tb = new ProjectProfile();
                tb = db.ProjectProfiles.Where(prj => prj.ID == xid).Single();
                if (tb.ID != 0)
                {
                    db.ProjectProfiles.Remove(tb);
                    db.SaveChanges();
                    return true;
                }
                return false;
            }
            catch (Exception)
            {

                return false;
            }
        }