/// <summary> /// Initialises the panel object. /// </summary> /// <param name="comm">Messenger object to communicate with other view models.</param> /// <param name="svc">The bug tracker web service.</param> /// <param name="activeProj">The currently active project.</param> public BugAddPanelViewModel(IMessenger comm, ITrackerService svc, ProjectViewModel activeProj, IGrowlNotifiactions notifier) : base(comm, svc, activeProj) { InitialiseBugViewModel(); _Notifier = notifier; }
public ICommandPanelViewModel CreateCommandPanel(ProjectViewModel project) { if (project == null) return _Container.Resolve<ICommandPanelViewModel>(); return _Container.Resolve<ICommandPanelViewModel>(new ParameterOverride("activeProj", project)); }
public ProjectPanelViewModel(ITrackerService svc, IMessenger mess) { _Messenger = mess; _Service = svc; Project = new ProjectViewModel(); }
public void Init() { var messengerMock = new Mock<IMessenger>(); var serviceMock = new Mock<ITrackerService>(); _Messenger = messengerMock.Object; _MockPriorityList = new List<string>() { "High", "Low" }; _MockStatusList = new List<string>() { "In Progress", "Closed" }; _MockActiveProject = new ProjectViewModel(new Project { Id = 1, Code = "GGGGG", Description = "", Name = "TestProject" }); _AssignedUserMock = new User() { Id = 5, FirstName = "Adam", Username = "******", Password = "******" }; _MockProjectUsersList = new List<User>() { _AssignedUserMock}; serviceMock.Setup<List<string>>(p => p.GetBugPriorityList()).Returns(_MockPriorityList); serviceMock.Setup<List<string>>(p => p.GetBugStatusList()).Returns(_MockStatusList); serviceMock.Setup<List<User>>(p => p.GetUsersByProject(_MockActiveProject.ToProjectModel())).Returns(_MockProjectUsersList); serviceMock.Setup<User>(p => p.GetMyUser()).Returns(_AssignedUserMock); var _MockNotifier = new Mock<IGrowlNotifiactions>(); _ServiceMock = serviceMock.Object; _ActiveProjectStub = new ProjectViewModel(new Project { Id = 5, Description = "Stub Project", Name = "Stub Title" }); _AddPanel = new BugAddPanelViewModel(_Messenger, _ServiceMock, _MockActiveProject, _MockNotifier.Object); }
public void OnLoadProject() { LoadProjectDataEvent loadProjectDataEvent = new LoadProjectDataEvent(); ProjectViewModel newProjectViewModel = new ProjectViewModel(project); eventAggregator.GetEvent<LoadProjectDataEvent>().Publish(newProjectViewModel); Assert.AreEqual(newProjectViewModel, viewModel.Project[0]); }
public ProjectUsersPanelViewModel(ITrackerService svc, IMessenger messenger, ProjectViewModel proj) { this._Service = svc; this._Messenger = messenger; this._Project = proj; ListenForMessages(); }
public void TestInitialize() { ProjectBase project = TestHelper.CreateTestProject(); Experiment experiment = project.Experiments.First() as Experiment; experiment.Results.Add(new Result("result", experiment)); viewModel = new ProjectViewModel(project); }
public WestSideBarViewModel(ITrackerService svc, IMessenger mess, ProjectViewModel activeProj) { _Service = svc; _Messenger = mess; _ActiveProject = activeProj; ListenForMessages(); }
// // GET: /Admin/Project/Details/5 public ActionResult Details(int id = 0) { ProjectViewModel project = new ProjectViewModel(ProjectDAL.FindProject(id)); if (project == null) { return HttpNotFound(); } return View(project); }
public BugPanelViewModel CreateBugViewPanel(ProjectViewModel project, BugViewModel bug) { ParameterOverrides parameters = new ParameterOverrides() { { "activeProj", project }, { "selectedBug", bug } }; return _Container.Resolve<BugPanelViewModel>("ViewPanel", parameters); }
public DeleteProjectDialogViewModel(IMessenger mess, ProjectViewModel proj) { _Messenger = mess; ProjectToDelete = proj; DeleteMessage = "Are you sure you want to delete project " + proj.Name + " and all of it's associated bugs?"; IsVisible = true; }
public ActionResult Details(int id) { var project = dataContext.Projects .Include(p => p.Tasks) .First(p => p.Id == id); var model = new ProjectViewModel(project); return View(model); }
public ProjectPropertiesViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator; _project = DocumentCache.ProjectViewModel as ProjectViewModel; _samples = _project.Children.First().Samples; AddRunData = new DelegateCommand<IList>(OnAddRunData); _selectedDataPath = Properties.Settings.Default.LastBrowseDataPath; LoadFiles(); }
public ProjectViewPanelViewModel(ITrackerService svc, IMessenger mess, ProjectViewModel selectedProj, IGrowlNotifiactions notifier) : base(svc, mess) { Project = selectedProj.Clone(); _Notifier = notifier; ButtonName = "Save & Close"; PanelTitle = "Edit Project"; }
public void TestInitialize() { project = TestHelper.CreateTestProject(); mockRegionManager = new Mock<IRegionManager>(); eventAggregator = new EventAggregator(); viewModel = new ProjectExplorerViewModel(mockRegionManager.Object, eventAggregator); projectViewModel = new ProjectViewModel(project); viewModel.Project.Add(projectViewModel); }
public ActionResult EditProject(ProjectViewModel project) { if (ModelState.IsValid) { projectService.Edit(project); return RedirectToAction("ShowProjects"); } return View("EditProject", project); }
public ActionResult CreateProject(ProjectViewModel project) { if (ModelState.IsValid) { projectService.Add(project); return RedirectToAction("ShowProjects"); } return View(); }
/// <summary> /// Initialises the bug view panel and de-references the selected bug to /// ensure updates to the edited bug do not reflect in the bug table. /// Also initialises a message listener to monitor changes in selected bug. /// </summary> /// <param name="comm">The mediator object for communication between view models.</param> /// <param name="svc">The bug tracker web service.</param> /// <param name="activeProj">The currently active project.</param> /// <param name="selectedBug">The currently selected bug</param> public BugViewPanelViewModel(IMessenger comm, ITrackerService svc, ProjectViewModel activeProj, BugViewModel selectedBug, IGrowlNotifiactions notifier) : base(comm, svc, activeProj) { if (selectedBug == null) throw new ArgumentNullException("The selected bug cannot be null."); _Notifier = notifier; UpdateBugView(selectedBug); ListenForMessages(); }
/// <summary> /// Stores references to dependencies and listens for incoming messages. /// </summary> /// <param name="comm">The mediator which allows communication between view models.</param> /// <param name="svc">The bug tracker web service.</param> /// <param name="activeProj"></param> public CommandPanelViewModel(IMessenger comm, ITrackerService svc, ProjectViewModel activeProj) { if (comm == null) throw new ArgumentNullException("The messenger cannot be null."); if (svc == null) throw new ArgumentNullException("Web service cannot be null."); _Messenger = comm; _Service = svc; if (!IsProjectNull(activeProj)) _ActiveProject = activeProj; ListenForMessages(); }
public ExtendedProjectViewModel(ICollection<EmployeeViewModel> employees, ProjectViewModel project) { Employed = new List<ExtendedEmployeeViewModel>(); Unemployed = new List<ExtendedEmployeeViewModel>(); Project = project; IEnumerable<EmployeeViewModel> employeeModels = employees.Where(x => (!project.CurrentEmployees.Contains(x))); foreach (EmployeeViewModel e in employeeModels) { Unemployed.Add(new ExtendedEmployeeViewModel(e)); } foreach (EmployeeViewModel e in project.CurrentEmployees) { Employed.Add(new ExtendedEmployeeViewModel(e)); } }
protected override void SaveProject(ProjectViewModel proj) { if (IsProjectValid) { Project savedProject = _Service.AddProject(proj.ToProjectModel()); _Notifier.AddNotification(new Notification { ImageUrl = Notification.ICON_ADD, Title = "Project Added", Message = "The project " + savedProject.Name + " has been added." }); _Messenger.NotifyColleagues(Messages.AddedProject, new ProjectViewModel(savedProject)); IsVisible = false; } }
public override async Task<InitializationResult> Initialize() { Log.Information("=> InputSelectorViewModel.Initialize"); string projectsXml; try { projectsXml = await connection.GetProjects(); } catch (WebException ex) { Log.Error("Could not get projects: " + ex.Message); HasBadConfiguration = true; return InitializationResult.Failed; } var projectsElement = XElement.Parse(projectsXml); foreach (var projectElement in projectsElement.Elements()) { var project = new ProjectViewModel(); project.Name = projectElement.GetAttributeString("name"); var projectId = projectElement.GetAttributeString("id"); var buildXml = await connection.GetProject(projectId); var buildRoot = XElement.Parse(buildXml); var buildElements = from buildTypesElement in buildRoot.Elements("buildTypes") from buildElement in buildTypesElement.Elements("buildType") select buildElement; foreach (var buildElement in buildElements) { var configuration = new ProjectConfigurationViewModel(project); configuration.Id = buildElement.GetAttributeString("id"); configuration.Name = buildElement.GetAttributeString("name"); project.Configurations.Add(configuration); } Projects.Add(project); } return InitializationResult.Succeeded; }
public override async Task<InitializationResult> Initialize() { Log.Information("=> InputSelectorViewModel.Initialize"); ProjectCollection projectCollection; try { projectCollection = await connection.GetProjects(); } catch (WebException ex) { Log.Error("Could not get projects: " + ex.Message); HasBadConfiguration = true; return InitializationResult.Failed; } foreach (var project in projectCollection.Value) { var projectVm = new ProjectViewModel(project); BuildDefinitionCollection buildDefinitionCollection; try { buildDefinitionCollection = await connection.GetBuildDefinitions(projectVm.Id); } catch (Exception ex) { Log.Error("Could not get build definitions: " + ex.Message); HasBadConfiguration = true; return InitializationResult.Failed; } foreach (var buildDefinition in buildDefinitionCollection.Value) { var configuration = new ProjectConfigurationViewModel(projectVm, buildDefinition); projectVm.Configurations.Add(configuration); } Projects.Add(projectVm); } return InitializationResult.Succeeded; }
public IActionResult UpdateProject(string projectName, [FromBody] ProjectViewModel newProjectObject) { if (newProjectObject == null) { return(BadRequest("Please provide details to update a project.")); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // replace the project with the new info above bool projectIsUpdated = _manager.ReplaceProject(projectName, newProjectObject); if (!projectIsUpdated) { return(NotFound($"Project with name '{projectName}' was not found. No update was executed.")); } return(NoContent()); }
public ProjectListViewModel GetUserAllProject(string account, string token) { ProjectListViewModel mlvm = new ProjectListViewModel(); var mm = _mr.FindMenuByType(token); foreach (var item in mm) { //验证用户是否有权限查看 bool bRet = new UserService().IsAuthProject(account, token, item.Id, 0); if (bRet) { ProjectViewModel mvm = new ProjectViewModel() { Id = item.Id, ClientId = item.ClientId, ProjectType = (int)item.ProjectType, ParentId = item.ParentId, Name = item.ProjectName, Token = item.Token }; mlvm.list.Add(mvm); } } mlvm.Success = true; mlvm.Message = "获取项目成功"; return(mlvm); }
public ProjectListViewModel FindUserProject(string account, string token) { var mm = _mr.FindMainMenu(token); ProjectListViewModel mlvm = new ProjectListViewModel(); foreach (var item in mm) { //验证用户是否有此主项目的查看权限 bool bRet = new UserService().IsAuthProject(account, token, item.Id, 0); if (bRet) { ProjectViewModel mvm = new ProjectViewModel() { Id = item.Id, ProjectType = (int)item.ProjectType, Name = item.ProjectName, Token = item.Token }; mlvm.list.Add(mvm); } } mlvm.Success = true; mlvm.Message = "获取用户项目成功"; return(mlvm); }
private ProjectViewModel ConfigureProjectViewModel(ConfigurableSectionController section, Uri serverUri, string projectKey) { if (serverUri == null) { FluentAssertions.Execution.Execute.Assertion.FailWith("Test setup: the server uri is not valid"); } if (string.IsNullOrWhiteSpace(projectKey)) { FluentAssertions.Execution.Execute.Assertion.FailWith("Test setup: the project key is not valid"); } section.ViewModel.State.ConnectedServers.Clear(); var serverVM = new ServerViewModel(new ConnectionInformation(serverUri)); section.ViewModel.State.ConnectedServers.Add(serverVM); var projectVM = new ProjectViewModel(serverVM, new SonarQubeProject(projectKey, "")); serverVM.Projects.Add(projectVM); return(projectVM); }
public ActionResult Create(ProjectViewModel collection) { Project pro = new Project(); pro.state = collection.state; pro.numberResource = collection.numberResource; pro.description = collection.description; pro.price = collection.price; pro.duration = collection.duration; pro.startDay = collection.startDay; pro.endDay = collection.endDay; // pro.userId = 5; serviceP.Add(pro); serviceP.Commit(); return(View()); }
public void TestRepositories_AfterRepositoriesUpdated_ContainsOneViewModelPerModel() { var tfProject = Substitute.For <ITfProject>(); var repositoryNames = new[] { "these", "names", "must", "be", "unique", "for", "this", "test", "to", "work" }; var repositoryModels = new List <ITfGitRepository>(); foreach (var repositoryName in repositoryNames) { var repoModel = Substitute.For <ITfGitRepository>(); repoModel.Name.Returns(repositoryName); repositoryModels.Add(repoModel); } tfProject.Repositories.Returns(repositoryModels); var systemUnderTest = new ProjectViewModel(tfProject); tfProject.RepositoriesUpdated += Raise.Event(); foreach (var repoModel in repositoryModels) { Assert.That(systemUnderTest.Repositories.Count(repoVm => repoVm.Name == repoModel.Name), Is.EqualTo(1)); } }
private void DeleteProject(ProjectViewModel project) { try { _Service.DeleteProject(project.ToProjectModel()); ManagedProjects.Remove(project); _Notifier.AddNotification(new Notification { ImageUrl = Notification.ICON_DELETE, Title = "Project Deleted", Message = "The project " + project.Name + " has been deleted." }); _Messenger.NotifyColleagues(Messages.DeletedProject, project); } catch (Exception e) { MessageBox.Show(e.Message); } }
public ActionResult GetAllProjectsWithUnfinishedTasks() { List <Project> projects = p.GetAllProjectsWithUnfinishedTasks(); List <ProjectViewModel> ProjectForView = new List <ProjectViewModel>(); projects.ForEach(proj => { ProjectViewModel projectView = new ProjectViewModel(); projectView.Id = proj.Id; projectView.Title = proj.Title; projectView.Discription = proj.Discription; projectView.DeadLine = proj.DeadLine; projectView.priority = proj.priority; if (proj.tasks != null && proj.tasks.Count != 0) { projectView.Tasks = new List <TaskWithUser>(); proj.tasks.ToList().ForEach(t => { TaskWithUser taskWithUser = new TaskWithUser(); taskWithUser.Id = t.Id; taskWithUser.notes = t.notes; taskWithUser.priority = t.priority; taskWithUser.ProjectId = t.ProjectId; taskWithUser.TaskDetails = t.TaskDetails; taskWithUser.TaskTitle = t.TaskTitle; taskWithUser.userId = t.userId; taskWithUser.developer = p.GetUserEmail(t.userId); projectView.Tasks.Add(taskWithUser); }); } else { projectView.Tasks = new List <TaskWithUser>(); } ProjectForView.Add(projectView); }); return(View(ProjectForView)); }
public void ErrorListInfoBarController_InfoBar_ClickButton_HasConnectedActiveSection_IsBusy() { // Arrange this.SetBindingMode(SonarLintMode.LegacyConnected); var testSubject = new ErrorListInfoBarController(this.host, this.unboundProjectFinder); this.ConfigureLoadedSolution(); int executed = 0; ProjectViewModel project = null; ConfigurableSectionController section = this.ConfigureActiveSectionWithBindCommand(args => { executed++; args.ProjectKey.Should().Be(project.Key); }); project = this.ConfigureProjectViewModel(section); testSubject.Refresh(); RunAsyncAction(); this.stateManager.SetAndInvokeBusyChanged(true); // Sanity ConfigurableInfoBar infoBar = this.infoBarManager.AssertHasAttachedInfoBar(ErrorListInfoBarController.ErrorListToolWindowGuid); VerifyInfoBar(infoBar); // Act (command enabled) infoBar.SimulateButtonClickEvent(); // Assert executed.Should().Be(0, "Busy, should not be executed"); // Act this.stateManager.SetAndInvokeBusyChanged(false); // Assert executed.Should().Be(1, "Update was expected to be executed"); this.infoBarManager.AssertHasNoAttachedInfoBar(ErrorListInfoBarController.ErrorListToolWindowGuid); infoBar.VerifyAllEventsUnregistered(); }
public ActionResult Create(ProjectViewModel model) { if (ModelState.IsValid) { if (ProjectDAL.ProjectExists(model.ProjectName)) { ViewBag.Error = "A project with that name already exists"; return View(model); } ProjectDAL.AddProject(model.ProjectName, model.Description); InfoCardDAL.UpdateInfoCardDescription( WebSecurity.CurrentUserId, "Added new project: \"" + model.ProjectName + "\"" ); return RedirectToAction("Details", new { id = ProjectDAL.GetProjectId(model.ProjectName) }); } return View(model); }
private void ConvertProject(ProjectViewModel projectViewModel) { try { Logger.Log.Debug("Converting"); var project = projectViewModel; if (project.Document.Blocks.Count < 1) { Logger.Log.Debug("Compiling Cancelled[InsufficientBlockCount]"); return; } Brush _DefaultForeground = ColorUtility.ConvertBrushFromString(Settings.Default.Foreground.ToString()); Brush _DefaultBackground = ColorUtility.ConvertBrushFromString(Settings.Default.Background.ToString()); Brush _LastForeground; Brush _LastBackground; _LastForeground = _DefaultForeground; _LastBackground = _DefaultBackground; string result = ProcessBlocks(project.Document.Blocks, _DefaultForeground, _DefaultBackground, _LastForeground, _LastBackground); project.Project.Document.Blocks.Clear(); project.Project.Document.Blocks.Add(new Paragraph(new Run(result) { Foreground = _DefaultForeground, Background = _DefaultBackground })); Logger.Log.DebugFormat("Converted ID[{0}] Name[{1}]", projectViewModel.Id, projectViewModel.Name); } catch (Exception ex) { Logger.Log.Error("Convert Exception", ex); } }
public async Task <ProjectViewModel> ReadProject(int projectId) { var queryFactory = _dataAccess.GetQueryFactory(_connectionString); var projects = (await queryFactory .Query() .From(ProjectTable) .Join(UserTable, $"{UserTable}.{UserConstants.UserId}", $"{ProjectTable}.{ProjectConstants.ProjectManagerId}") .Join(ClientTable, $"{ClientTable}.{ClientConstants.ClientId}", $"{ ProjectTable}.{ProjectConstants.ClientId}") .Select($"{ProjectTable}.{ProjectConstants.ProjectId}") .Select(ProjectConstants.ProjectCode) .Select(ProjectConstants.ProjectName) .Select(ProjectConstants.ProjectManagerId) .Select(UserConstants.EmailBmining) .Select(ClientConstants.ClientName) .Select(ProjectConstants.CodProjectType) .Select(ProjectConstants.StatusId) .Select(ProjectConstants.Level) .Select(ProjectConstants.ParentId) .Select($"{ClientTable}.{ClientConstants.ClientId}") .Where($"{ProjectTable}.{ProjectConstants.ProjectId}", projectId) .GetAsync <ProjectModel>()).First(); var projectViewModel = new ProjectViewModel() { MyLevel = projects.Level, MyParentId = projects.ParentId, MyId = projectId, MyProjectCode = projects.CodProject, MyProjectName = projects.ProjectName, MyProjectStatus = (ProjectStatusEnum)projects.StatusId, MyProjectType = (ProjectTypeEnum)projects.CodProjectType, MyClientId = projects.ClientId, MyClientName = projects.ClientName, MyProjectManager = new UserViewModel { MyId = projects.ProjectManagerId, MyEmail = projects.EmailBmining }, }; return(projectViewModel); }
public void AddEntryNeedsCurrentProject() { // Arrange var projectListMock = new Mock <IProjectListViewModel>(); ProjectViewModel currentProject = null; projectListMock.SetupSet(x => x.CurrentProject = It.IsAny <ProjectViewModel>()).Callback <ProjectViewModel>(v => currentProject = v); projectListMock.SetupGet(x => x.CurrentProject).Returns(() => currentProject); var vm = new MainViewModel(ConnectorMock.Object, null, TaskRunnerMock.Object, null, null, projectListMock.Object); // Act vm.ProjectList.CurrentProject = null; bool noSelection = vm.AddEntryCommand.CanExecute(null); vm.ProjectList.CurrentProject = new ProjectViewModel(new GSD.Models.Project()); bool selection = vm.AddEntryCommand.CanExecute(null); // Assert Assert.IsFalse(noSelection); Assert.IsTrue(selection); }
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { String projectIDParameter = ""; if (NavigationContext.QueryString.TryGetValue("projectIDParam", out projectIDParameter)) { String customerID = ""; if (NavigationContext.QueryString.TryGetValue("customerID", out customerID)) { projectViewModel = App.AppViewModel.GetProjectViewModel(projectIDParameter, customerID); } else { projectViewModel = App.AppViewModel.GetProjectViewModel(projectIDParameter, customerID); } projectViewModel.LoadAndCalsInitial(); } this.DataContext = projectViewModel; // Call the base method, to execute the rest of the navigation event base.OnNavigatedTo(e); }
public ActionResult Save(ProjectViewModel viewModel) { if (ModelState.IsValid) { if (viewModel.Id == Guid.Empty) { var model = new Project(); model.Id = Guid.NewGuid(); model.Name = viewModel.Name; projectRepository.Create(model); } else { var model = projectRepository.GetById(x => x.Id == viewModel.Id); model.Name = viewModel.Name; projectRepository.Update(model); } return(RedirectToAction("Index")); } return(View("Create", viewModel)); }
public ActionResult View(Guid id) { try { var dbProject = ProjectService.Get(id); if (dbProject == null) { return(RedirectToAction("Index")); } ProjectViewModel project = new ProjectViewModel(); project.Data = dbProject; project.Users = new SelectList(UserService.All(), "SID", "DisplayName", null); return(View(project)); } catch (Exception ex) { } return(RedirectToAction("Index")); }
public async Task <IActionResult> Index(int?id) { if (id == null) { return(NotFound()); } Project project = await _projectService.GetProject(new ServiceContext(), (int)id); Sprint currentSprint = project.Sprints.FirstOrDefault(); project.Sprints.Remove(currentSprint); var projectViewModel = new ProjectViewModel { ProjectName = project.Name, CurrentSprint = currentSprint, Sprints = new List <Sprint>(project.Sprints), }; return(View(projectViewModel)); }
public IActionResult Post([FromBody] Project project) { project.ClientLocation = null; db.Projects.Add(project); db.SaveChanges(); Project existingProject = db.Projects.Include("ClientLocation").Where(temp => temp.ProjectID == project.ProjectID).FirstOrDefault(); ProjectViewModel projectViewModel = new ProjectViewModel() { ProjectID = existingProject.ProjectID, ProjectName = existingProject.ProjectName, TeamSize = existingProject.TeamSize, DateOfStart = existingProject.DateOfStart.ToString("dd/MM/yyyy"), Active = existingProject.Active, ClientLocation = existingProject.ClientLocation, ClientLocationID = existingProject.ClientLocationID, Status = existingProject.Status }; return(Ok(projectViewModel)); }
/// <summary> /// /// </summary> /// <param name="model"></param> /// <returns></returns> internal int AddProject(ProjectViewModel model) { if (model != null) { var tblLists = db.Projects.Count(x => x.Name == model.Name); if (tblLists > 0) { return(2); // Project is already present in the database. } var project = new Project { Name = model.Name, ListId = model.ListId, Priority = model.Priority, ProjectCode = model.ProjectCode, ProjectBrief = model.ProjectBrief, LinkdinLink = model.LinkdinLink, Requester = model.Requester, ApprovalDate = model.ApprovalDate, DatesInformedToClient = model.DatesInformedToClient, NumberOfCompaniesApproved = model.NumberOfCompaniesApproved, JobTitlesPerCompany = model.JobTitlesPerCompany, RecordsToBeResearched = model.RecordsToBeResearched, ExpectedDeliveryDate = model.ExpectedDeliveryDate, ProjectStatus = 1, IsActive = model.IsActive, AllotedTo = model.AllotedTo, Names = model.Names, CreatedBy = model.CreatedBy, CreatedOn = model.CreatedOn, EditedOn = model.CreatedOn }; db.Projects.Add(project); db.SaveChanges(); return(0); } return(1); //Null object }
// GET: Project/Edit/5 public ActionResult Edit(int id) { ProjectViewModel projectModel = new ProjectViewModel(); DataTable dtblProject = new DataTable(); DataTable dtblProjectUser = new DataTable(); using (SqlConnection sqlCon = new SqlConnection(connectionString)) { sqlCon.Open(); string query = "SELECT * FROM Projects WHERE Id = @Id"; SqlDataAdapter sqlDa = new SqlDataAdapter(query, sqlCon); sqlDa.SelectCommand.Parameters.AddWithValue("@Id", id); sqlDa.Fill(dtblProject); query = "SELECT * FROM ProjectUser WHERE ProjectId = @Id"; sqlDa = new SqlDataAdapter(query, sqlCon); sqlDa.SelectCommand.Parameters.AddWithValue("@Id", id); sqlDa.Fill(dtblProjectUser); } if (dtblProject.Rows.Count == 1) { projectModel.Id = Convert.ToInt32(dtblProject.Rows[0][0].ToString()); projectModel.Name = dtblProject.Rows[0][1].ToString(); projectModel.Description = dtblProject.Rows[0][2].ToString(); var context = new ApplicationDbContext(); var allUsers = context.Users.ToList(); string[] user = new string[allUsers.Count]; for (int i = 0; i < allUsers.Count; i++) { projectModel.Member.Add(allUsers[i].UserName); } return(View(projectModel)); } else { return(RedirectToAction("Index")); } }
public ActionResult Edit(ProjectViewModel projectVM) { if (projectVM == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } if (ModelState.IsValid) { //db.Entry(project).State = EntityState.Modified; var projectToUpdate = db.Projects .Include(i => i.Users).First(i => i.Id == projectVM.Project.Id); if (TryUpdateModel(projectToUpdate, "Project", new string[] { "ID", "Name" })) { var newUsers = db.Users.Where( m => projectVM.SelectedProjectUsers.Contains(m.Id)).ToList(); var updatedUsers = new HashSet <string>(projectVM.SelectedProjectUsers); foreach (ApplicationUser user in db.Users) { if (!updatedUsers.Contains(user.Id)) { projectToUpdate.Users.Remove(user); } else { projectToUpdate.Users.Add((user)); } } db.Entry(projectToUpdate).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } } return(View(projectVM)); }
public ActionResult AddProject(ProjectViewModel projectView) { List <Image> imgs = new List <Image>(); if (projectView.FileMain != null) { var fileName = Path.GetFileName(projectView.FileMain.FileName); var path = Path.Combine(Server.MapPath("/Images"), fileName); projectView.project.ImageLink = "/Images/" + fileName; projectView.FileMain.SaveAs(path); } if (projectView.Files != null) { foreach (HttpPostedFileBase file in projectView.Files) { Image img = new Image(); var InputFileName = Path.GetFileName(file.FileName); var ServerSavePath = Path.Combine(Server.MapPath("/Images"), InputFileName); //Save file to server folder img.Name = InputFileName; img.Path = "/Images/" + InputFileName; file.SaveAs(ServerSavePath); imgs.Add(img); } } projectView.project.CarouselImages = imgs; database.Projects.Add(projectView.project); database.SaveChanges(); if (database.SaveChanges() < 0) { ViewBag.Message = "Success"; } else { ViewBag.Message = "Failed"; } return(RedirectToAction("addProject", "admin")); }
public void SectionController_ToggleShowAllProjectsCommand() { // Arrange var testSubject = this.CreateTestSubject(); var connInfo = new ConnectionInformation(new Uri("http://localhost")); var projectInfo = new SonarQubeProject("p1", "proj1"); var server = new ServerViewModel(connInfo); var project = new ProjectViewModel(server, projectInfo); server.Projects.Add(project); // Case 1: No bound projects project.IsBound = false; // Act + Assert CanExecute testSubject.ToggleShowAllProjectsCommand.CanExecute(server).Should().BeFalse(); // Case 2: Bound project.IsBound = true; // Act + Assert testSubject.ToggleShowAllProjectsCommand.CanExecute(server).Should().BeTrue(); // Assert execution bool original = server.ShowAllProjects; // Act testSubject.ToggleShowAllProjectsCommand.Execute(server); // Assert server.ShowAllProjects.Should().Be(!original); // Act testSubject.ToggleShowAllProjectsCommand.Execute(server); // Assert server.ShowAllProjects.Should().Be(original); }
public async Task <IActionResult> Edit(Guid id, ProjectViewModel projectViewModel) { if (id != projectViewModel.Id) { return(NotFound()); } // Update image if (projectViewModel.ImageUpload != null) { // Delete Old image UploadFile.Delete(projectViewModel.MainImage); string fileName = null; try { fileName = await UploadFile.Add(projectViewModel.ImageUpload); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message); } if (fileName == null) { return(View(projectViewModel)); } projectViewModel.MainImage = fileName; } var project = _mapper.Map <Project>(projectViewModel); await _projectRep.Update(project); await _projectRep.SaveChanges(); return(RedirectToAction(nameof(Index))); }
public ActionResult Create(ProjectViewModel model, HttpPostedFileBase upload) { var user = _userManager.FindById(User.Identity.GetUserId()); var myUser = db.Users.Where(x => x.AspNetUsersId.Equals(user.Id)).FirstOrDefault(); Project dbProject = null; var imageFile = _uploadFileManager.UploadFile(upload); if (ModelState.IsValid) { dbProject = new Project() { CategoryId = model.SelectedCategoryId, CreatorId = myUser.Id, DateInserted = DateTime.Now, CurrentFundAmount = model.Project.CurrentFundAmount, Description = model.Project.Description, Ratio = model.Project.Ratio, StatusId = 1, DueDate = model.Project.DueDate, TargetAmount = model.Project.TargetAmount, Title = model.Project.Title, PhotoUrl = imageFile != null ? imageFile.FileName : null, Image = imageFile != null ? imageFile.Content : null }; dbProject = db.Projects.Add(dbProject); db.SaveChanges(); return(RedirectToAction("Edit", new { id = dbProject.Id })); } var viewModel = new Models.ProjectViewModel() { Categories = db.Categories.ToList(), Statuses = db.ProjectStatus.ToList(), Project = dbProject, MyProjects = CreatorProjects(myUser.Id) }; return(View(viewModel)); }
public ActionResult Create(ProjectViewModel PVM) { if (!Request.IsAuthenticated) { return(RedirectToAction("Login", "Account")); } //redirect to nowhere if not admin if (!(User.IsInRole("Team Leader"))) { return(RedirectToAction("Nowhere", "Account")); } Project P = new Project(); var currentUserId = User.Identity.GetUserId(); int myInt = int.Parse(currentUserId); User u = us.GetById(myInt); if (PVM.Start_Date >= DateTime.Now.Date) { P.ProjectId = PVM.ProjectId; P.ProjectName = PVM.ProjectName; P.Description = PVM.Description; P.etat = Domain.Entities.Etat.Pending; P.Duration = (PVM.End_Date - PVM.Start_Date).TotalDays.ToString(); P.Start_Date = PVM.Start_Date; P.End_Date = PVM.End_Date; P.TeamFK = u.TeamFK; ps.Add(P); ps.Commit(); return(RedirectToAction("index")); } else { ViewBag.Message = "Start date must be greater than Today !"; } return(View("Create")); }
public void BindingController_SetBindingInProgress_Notifications() { // Arrange ServerViewModel serverVM = CreateServerViewModel(); serverVM.SetProjects(new[] { new SonarQubeProject("key1", "") }); ProjectViewModel projectVM = serverVM.Projects.ToArray()[0]; BindingController testSubject = this.PrepareCommandForExecution(); var section = ConfigurableSectionController.CreateDefault(); this.host.SetActiveSection(section); var progressEvents = new ConfigurableProgressEvents(); this.host.ActiveSection.UserNotifications.ShowNotificationError("Need to make sure that this is clear once started", NotificationIds.FailedToBindId, new RelayCommand(() => { })); ConfigurableUserNotification userNotifications = (ConfigurableUserNotification)section.UserNotifications; foreach (ProgressControllerResult result in Enum.GetValues(typeof(ProgressControllerResult)).OfType <ProgressControllerResult>()) { // Act - start testSubject.SetBindingInProgress(progressEvents, projectVM.Project); // Assert userNotifications.AssertNoNotification(NotificationIds.FailedToBindId); // Act - finish progressEvents.SimulateFinished(result); // Assert if (result == ProgressControllerResult.Succeeded) { userNotifications.AssertNoNotification(NotificationIds.FailedToBindId); } else { userNotifications.AssertNotification(NotificationIds.FailedToBindId, Strings.FailedToToBindSolution); } } }
public HttpResponseMessage Register(HttpRequestMessage request, ProjectViewModel project) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { if (_projectsRepository.UserExists(project.Email)) { ModelState.AddModelError("Invalid user", "Email already exists"); response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Keys.SelectMany(k => ModelState[k].Errors) .Select(m => m.ErrorMessage).ToArray()); } else { Project newProject = new Project(); newProject.UpdateProject(project); _projectsRepository.Add(newProject); _unitOfWork.Commit(); // Update view model project = Mapper.Map <Project, ProjectViewModel>(newProject); response = request.CreateResponse <ProjectViewModel>(HttpStatusCode.Created, project); } } return response; })); }
public ActionResult ProjectDetail(int id) { using (var assetRepoContext = new AssetRepoContext()) { var project = assetRepoContext.Projects.SingleOrDefault(p => p.ProjectId == id); if (project != null) { var projectViewModel = new ProjectViewModel { ProjectId = project.ProjectId, Title = project.Title, Category = new ProjectCategoryViewModel { ProjectCategoryId = project.ProjectCategoryId, Name = project.ProjectCategory.Name }, Creator = new ContributorPopulatedViewModel { ContributorId = project.CreatorId, Name = project.Creator.Name }, CreationDateTime = project.CreationDateTime, LastUpdater = new ContributorPopulatedViewModel { ContributorId = project.LastUpdaterId, Name = project.LastUpdater.Name }, LastUpdateDateTime = project.LastUpdateDateTime, Description = project.Description, IsActive = project.IsActive }; return(View(projectViewModel)); } } return(new HttpNotFoundResult()); }
// GET: Projects/Edit/5 public ActionResult p_Edit(int?id) { if (id == null) { return(NotFound()); } var project = _context.Projects.Find(id); if (project == null) { return(NotFound()); } var Results = from c in _context.Coders select new { c.CoderID, c.Name, Checked = ((from cp in _context.CoderProjects where (cp.ProjectID == id) & (cp.CoderID == c.CoderID) select cp).Count() > 0) }; var MyViewModel = new ProjectViewModel(); MyViewModel.ProjectID = id.Value; MyViewModel.Title = project.Title; MyViewModel.Description = project.Description; var MyCheckBoxList = new List <CBVeiwModel>(); foreach (var cod in Results) { MyCheckBoxList.Add(new CBVeiwModel { Id = cod.CoderID, Name = cod.Name, Checked = cod.Checked }); } MyViewModel.Coders = MyCheckBoxList; return(PartialView(MyViewModel)); }
private bool ExcuteBat(string sourceDir, ProjectViewModel item) { //获取当前运行目录下的所有文件,更新到指定地方 try { var root = GetTargetRoot(item); var targetDir = System.IO.Path.Combine(root, item.Name); if (Directory.Exists(targetDir)) { var bakDir = System.IO.Path.Combine(root, "bak", $"{item.Name}_bak_{DateTime.Now.ToString("yyyyMMddHHmmss")}"); //备份 FileOper.CopyDir(targetDir, bakDir); var files = Directory.GetFiles(sourceDir); foreach (var sourceFile in files) { var fileName = System.IO.Path.GetFileName(sourceFile); var extension = System.IO.Path.GetExtension(sourceFile); var targetPath = System.IO.Path.Combine(targetDir, fileName); if (extension == ".pdb" || extension == ".config") { continue; } System.IO.File.Copy(sourceFile, targetPath, true); } } } catch (Exception ex) { throw ex; } return(true); }
public ProjectView(string projectName) { InitializeComponent(); DataContext = new ProjectViewModel(Token, projectName); }
public ProjectView() { InitializeComponent(); DataContext = new ProjectViewModel(Token); }
protected abstract void SaveProject(ProjectViewModel project);
public ExtendedProjectViewModel() { Employed = new List<ExtendedEmployeeViewModel>(); Unemployed = new List<ExtendedEmployeeViewModel>(); Project = new ProjectViewModel(); }
public void TestInitialize() { project = TestHelper.CreateTestProject(); viewModel = new ProjectViewModel(project); samplesViewModel = viewModel.Children.First().Children.First() as SamplesViewModel; experiment = (Experiment)project.Experiments.First(); }
public ICollection<ProjectViewModel> Search(ProjectViewModel project) { ICollection<ProjectViewModel> projects = GetAllViewModels(); ICollection<ProjectViewModel> toTransfer = new List<ProjectViewModel>(); toTransfer = projects.Where(x => (x.Name.Equals(project.Name) || x.StartDate.Equals(project.StartDate) || x.EndDate.Equals(project.EndDate))).ToList(); return toTransfer; }