public async Task <long> Handle(CreateProjectCmd request, CancellationToken cancellationToken)
        {
            var project = new Project(request.Name, request.SelfHostSettings, request.DefaultAdminSettings);

            _projectRepository.Add(project);
            _projectRepository.Add(new UserProjectRights(request.UserId, project.Id, ProjectRight.Creator));
            await _projectRepository.UnitOfWork.SaveChangesAsync(cancellationToken);

            return(project.Id);
        }
Example #2
0
        public ActionResult ProjectAdd([FromBody] Project project)
        {
            var student = _appRepository.GetStudentByID(project.StudentID);

            project.UniversityID     = student.UniversityID;
            project.Status           = 1;
            project.ProjectStartDate = DateTime.Now;
            _appRepository.Add(project);
            _appRepository.SaveAll();
            return(Ok(project));
        }
Example #3
0
        public void CreateProject(Project project)
        {
            if (ProjectCodeIsNotUnique(project.Code))
            {
                throw new ProjectCodeIsInUseException();
            }

            project.Id        = Guid.NewGuid();
            project.Code      = project.Code.ToUpper();
            project.CreatedAt = DateTime.Now;
            addProjectOwnerToProjectUsers(project);
            project.Users = _userRepo.FindBy(u => project.SelectedUsers.Contains(u.Id)).ToList();

            _projectRepo.Add(project);
        }
 /// <exception cref="UnableToAddObjectException">Thrown when we're unable to add the new project</exception>
 public void AddProject(Project project)
 {
     try
     {
         var projectDto = Mapper.Map <ProjectDto>(project);
         projectRepository.Add(projectDto);
     }
     catch (UnableToPersistToMongoDbException exception)
     {
         var sex = new UnableToAddObjectException(ObjectType.Project, "ProjectService: AddProject", exception);
         sex.AddData("Project", project);
         logger.Log(ExceptionType.ExceptionizerApi, "ProjectService: AddProject", sex);
     }
     catch (UnableToPersistToElasticSearchException exception)
     {
         var sex = new UnableToAddObjectException(ObjectType.Project, "ProjectService: AddProject", exception);
         sex.AddData("Project", project);
         logger.Log(ExceptionType.ExceptionizerApi, "ProjectService: AddProject", sex);
     }
     catch (Exception exception)
     {
         var sex = new UnableToAddObjectException(ObjectType.Project, "ProjectService: AddProject", exception);
         sex.AddData("Project", project);
         logger.Log(ExceptionType.Unhandled, "ProjectService: AddProject", sex);
     }
 }
Example #5
0
        public ProjectViewModel Add(ProjectViewModel viewModel)
        {
            var model = _repository.Add(viewModel.ToProjectEntity());

            _repository.Save();
            return(new ProjectViewModel(model));
        }
Example #6
0
        public void Storer(ProjectDto projectDto)
        {
            var dataOrcamento = new DateTime();

            RuleValidator.New()
            .When(!Enum.TryParse <Status>(projectDto.Status, out var status), Resource.InvalidStatus)
            .When(!string.IsNullOrEmpty(projectDto.DataOrcamento) && !DateTime.TryParseExact(projectDto.DataOrcamento, "ddMMyyyy", CultureInfo.InvariantCulture,
                                                                                             System.Globalization.DateTimeStyles.None, out dataOrcamento), Resource.InvalidDataOrcamentoProjeto)
            .ThrowExceptionIfExists();

            if (projectDto.Id == 0)
            {
                var project = new Project(projectDto.Descricao, projectDto.Largura, projectDto.Comprimento,
                                          dataOrcamento, status);

                _projectRepository.Add(project);
            }
            else
            {
                var project = _projectRepository.GetById(projectDto.Id);

                RuleValidator.New()
                .When(project == null, Resource.ProjectNotFound)
                .ThrowExceptionIfExists();

                project.ChangeDataOrcamento(dataOrcamento);
                project.ChangeDescricao(projectDto.Descricao);
                project.ChangeStatus(status);
            }
        }
Example #7
0
        public async Task <IActionResult> Create(ProjectViewModel projectViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(projectViewModel));
            }

            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.Add(project);

            await _projectRep.SaveChanges();

            return(RedirectToAction(nameof(Index)));
        }
Example #8
0
        public async Task <Infrastructure.Database.Query.Model.Project.Project> Handle(AddProjectCommand request, CancellationToken cancellationToken)
        {
            var projectDomain = new Project(request.Description, request.LongDescription);

            projectDomain.Validate();

            #region Persistence

            var project = projectDomain.ToModel <Command.Project>(_Mapper);

            await _ProjectRepository.Add(project);

            await _UnitOfWork.Commit();

            #endregion

            #region Bus

            var publishMessage = new Message();
            publishMessage.MessageType = "AddProject";
            var response = projectDomain.ToQueryModel <Query.Project>(_Mapper);
            publishMessage.SetData(response);

            await _Bus.SendMessage(publishMessage);

            #endregion

            return(response);
        }
Example #9
0
    public static void GenerateDemoData(
      IIssueRepository issueRepository, 
      IProjectRepository projectRepository, 
      IAttachmentRepository attachmentRepository)
    {
      Project p = new Project("SHOP", "Webshop", "All issues related to the webshop.");
      projectRepository.Add(p);

      Issue i = new Issue(p, "Crash after payment", @"I have justed paid for two pairs of shoes - or rather I tried to. When I clicked 'Pay' all I got was a yellow error screen.", 3);

      issueRepository.Add(i);

      string errorReport = "This is an error report ...";
      Attachment att = new Attachment(i, "Error report", "Error report from end user", Encoding.UTF8.GetBytes(errorReport), "text/plain");
      attachmentRepository.Add(att);

      string logFile = "DEBUG 2014-01-22 15:45:07,610 166033ms  [9] Log4NetTraceListener   WriteLine          - Executing OperationResult OperationResult: type=OK, statusCode=200.";
      att = new Attachment(i, "Logfile", "Logfile with server stack trace", Encoding.UTF8.GetBytes(logFile), "text/plain");
      attachmentRepository.Add(att);

      i = new Issue(p, "Not calculating VAT correctly", @"When I add both shoes and socks it fails to calculate the VAT correctly.", 3);

      issueRepository.Add(i);

      i = new Issue(p, "General Failure?", @"When I press ctrl-P it says 'General failure reading harddisk'! Who is that General and why is he reading my hard disk?", 5);

      issueRepository.Add(i);
    }
Example #10
0
        private Project CreateNewProject()
        {
            var project = new Project();

            _projectRepository.Add(project);
            return(project);
        }
Example #11
0
        private async void OnSaveDetailExecute()
        {
            if (!InEditMode)
            {
                _projectRepository.Add(SelectedProject.Model);
            }
            else
            {
            }

            await _projectRepository.SaveAsync();

            HasChanges = _projectRepository.HasChanges();



            //TODO - FIX CACHING ISSUE
            var localRefreshProject = _projectRepository.GetByIdAsync(SelectedProject.Id);

            //SelectedProject =


            InEditMode = false;



            _eventAggregator.GetEvent <AfterDetailSavedEvent>().Publish();
            _eventAggregator.GetEvent <RefreshListEvent>().Publish();
        }
Example #12
0
        public static void GenerateDemoData(
            IIssueRepository issueRepository,
            IProjectRepository projectRepository,
            IAttachmentRepository attachmentRepository)
        {
            Project p = new Project("SHOP", "Webshop", "All issues related to the webshop.");

            projectRepository.Add(p);

            Issue i = new Issue(p, "Crash after payment", @"I have justed paid for two pairs of shoes - or rather I tried to. When I clicked 'Pay' all I got was a yellow error screen.", 3);

            issueRepository.Add(i);

            string     errorReport = "This is an error report ...";
            Attachment att         = new Attachment(i, "Error report", "Error report from end user", Encoding.UTF8.GetBytes(errorReport), "text/plain");

            attachmentRepository.Add(att);

            string logFile = "DEBUG 2014-01-22 15:45:07,610 166033ms  [9] Log4NetTraceListener   WriteLine          - Executing OperationResult OperationResult: type=OK, statusCode=200.";

            att = new Attachment(i, "Logfile", "Logfile with server stack trace", Encoding.UTF8.GetBytes(logFile), "text/plain");
            attachmentRepository.Add(att);

            i = new Issue(p, "Not calculating VAT correctly", @"When I add both shoes and socks it fails to calculate the VAT correctly.", 3);

            issueRepository.Add(i);

            i = new Issue(p, "General Failure?", @"When I press ctrl-P it says 'General failure reading harddisk'! Who is that General and why is he reading my hard disk?", 5);

            issueRepository.Add(i);
        }
Example #13
0
        public IActionResult Create(ProjectCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                Project newProject = new Project
                {
                    //Id = _projectRepository.GetAllProjects().Count() + 1,
                    ProjectID       = model.ProjectID,
                    Name            = model.Name,
                    Count           = model.Count,
                    Designer        = model.Designer,
                    Engineer        = model.Engineer,
                    Programmer      = model.Programmer,
                    Assembler       = model.Assembler,
                    DesignerScore   = model.DesignerScore,
                    EngineerScore   = model.EngineerScore,
                    ProgrammerScore = model.ProgrammerScore,
                    AssemblerScore  = model.AssemblerScore
                };

                _projectRepository.Add(newProject);
                return(RedirectToAction("Index"));
            }
            return(View());
        }
Example #14
0
        public int Add(Project project)
        {
            if (project.Id != 0)
            {
                return(0);
            }

            if (string.IsNullOrEmpty(project.Name) || string.IsNullOrEmpty(project.Area))
            {
                return(0);
            }

            if (project.Colaborators.Count != 0)
            {
                return(0);
            }

            bool UserNameExist = _dataRepo.Exist(project.Name);

            if (UserNameExist)
            {
                return(0);
            }

            int id = _dataRepo.Add(project);

            return(id);
        }
 public async Task <IActionResult> Post([FromBody] Project project)
 {
     return(await FunctionWrapper.ExecuteFunction(this, async() =>
     {
         return await _projectRepository.Add(project);
     }));
 }
Example #16
0
        public void CreateSampleOrganizationAndProject(string userId)
        {
            if (_projectRepository.GetByApiKey(SAMPLE_API_KEY) != null)
            {
                return;
            }

            User user         = _userRepository.GetById(userId, true);
            var  organization = new Organization {
                Id = "537650f3b77efe23a47914f3", Name = "Acme"
            };

            _billingManager.ApplyBillingPlan(organization, BillingManager.UnlimitedPlan, user);
            organization = _organizationRepository.Add(organization);

            var project = new Project {
                Id = "537650f3b77efe23a47914f4", Name = "Disintegrating Pistol", TimeZone = TimeZone.CurrentTimeZone.StandardName, OrganizationId = organization.Id
            };

            project.NextSummaryEndOfDayTicks = TimeZoneInfo.ConvertTime(DateTime.Today.AddDays(1), project.DefaultTimeZone()).ToUniversalTime().Ticks;
            project.ApiKeys.Add(SAMPLE_API_KEY);
            project.Configuration.Settings.Add("IncludeConditionalData", "true");
            project.AddDefaultOwnerNotificationSettings(userId);
            project = _projectRepository.Add(project);

            _organizationRepository.IncrementStats(project.OrganizationId, projectCount: 1);

            user.OrganizationIds.Add(organization.Id);
            _userRepository.Save(user);
        }
Example #17
0
        public IActionResult Post(ProjectDTO model)
        {
            Project item = new Project();

            model.UpdateFromModel(item);

            item.LastEdit = DateTime.Now;

            if (_projectRepo.NameExists(item.OwnerId, item.Name))
            {
                return(Conflict("A project with this name already exists for that owner"));
            }

            _projectRepo.Add(item);
            _projectRepo.SaveChanges();

            ProjectDTO dto = new ProjectDTO {
                Id            = item.Id,
                Name          = item.Name,
                TeamId        = item.TeamId,
                OwnerId       = item.OwnerId,
                LastEdit      = item.LastEdit,
                ContactPerson = item.ContactPerson
            };

            return(CreatedAtAction(nameof(GetAll), dto));
        }
Example #18
0
        public async Task <CreateProjectResponse?> Handle(CreateProjectRequest message)
        {
            if (string.IsNullOrWhiteSpace(message.ProjectName))
            {
                return(ReturnError(new FieldValidationError(nameof(message.ProjectName), "The project name must not be empty.")));
            }

            if (message.KeyStorage == KeyStorage.ServerEncrypted && (string.IsNullOrEmpty(message.KeyPassword) || message.KeyPassword !.Length < 6))
            {
                return(ReturnError(new FieldValidationError(nameof(message.KeyPassword), "The key password is required.")));
            }

            var key           = _asymmetricKeyFactory.Create();
            var asymmetricKey = CreateAsymmetricKey(key, message.KeyStorage, message.KeyPassword);

            var project = new Project(message.ProjectName, asymmetricKey);
            var result  = await _repository.Add(project);

            if (message.KeyStorage == KeyStorage.Locally)
            {
                return(new CreateProjectResponse(result.Id, key.PrivateKey));
            }
            else
            {
                return(new CreateProjectResponse(result.Id));
            }
        }
 public ActionResult <Project> Post([FromForm] Project project)
 {
     try
     {
         if (ModelState.IsValid)
         {
             var isAdded = repository.Add(project);
             if (isAdded)
             {
                 return(Created("Project", project));
             }
             else
             {
                 return(StatusCode(StatusCodes.Status500InternalServerError));
             }
         }
         else
         {
             return(BadRequest(ModelState));
         }
     }
     catch
     {
         return(StatusCode(StatusCodes.Status500InternalServerError));
     }
 }
Example #20
0
        private void CreateData()
        {
            foreach (Organization organization in OrganizationData.GenerateSampleOrganizations())
            {
                if (organization.Id == TestConstants.OrganizationId3)
                {
                    _billingManager.ApplyBillingPlan(organization, BillingManager.FreePlan, UserData.GenerateSampleUser());
                }
                else
                {
                    _billingManager.ApplyBillingPlan(organization, BillingManager.SmallPlan, UserData.GenerateSampleUser());
                }

                _organizationRepository.Add(organization);
            }

            foreach (Project project in ProjectData.GenerateSampleProjects())
            {
                var organization = _organizationRepository.GetById(project.OrganizationId);
                organization.ProjectCount += 1;
                _organizationRepository.Save(organization);

                _projectRepository.Add(project);
            }
        }
        public async Task <IActionResult> CreateMessage(int userId, MessageForCreateionDto messageForCreateionDto)
        {
            var sender = await _repo.GetUser(userId, false); //create sender variable to give auto mapper a hint to map messageToReturnDto

            if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            messageForCreateionDto.SenderId = userId;

            var recipient = await _repo.GetUser(messageForCreateionDto.RecipientId, true);

            if (recipient == null)
            {
                return(BadRequest("Could not find user"));
            }

            var message = _mapper.Map <Message>(messageForCreateionDto);

            _repo.Add(message);

            if (await _repo.SaveAll())
            {
                var messageToReturn = _mapper.Map <MessageToReturnDto>(message);
                return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn));
            }

            throw new Exception("Creating the message failed on save");
        }
Example #22
0
        public async Task <IActionResult> LikeUser(int id, int recipientId)
        {
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var like = await _repo.GetLike(id, recipientId);

            if (like != null)
            {
                return(BadRequest("You already liked the user"));
            }

            if (await _repo.GetUser(recipientId, false) == null)
            {
                return(NotFound());
            }

            like = new Like
            {
                LikerId = id,
                LikeeId = recipientId
            };

            _repo.Add <Like>(like); //not updated to database yet so no need to use async

            if (await _repo.SaveAll())
            {
                return(Ok());
            }

            return(BadRequest("Failed to like user"));
        }
        public async Task <Domain.AggregatesModel.Project> Handle(CreateProjectCommand request, CancellationToken cancellationToken)
        {
            _projectRepository.Add(request.Project);
            await _projectRepository.UnitOfWork.SaveEntitiesAsync();

            return(request.Project);
        }
Example #24
0
        public async Task <ProjectModel> Handle(CreateProjectCommands request, CancellationToken cancellationToken)
        {
            ProjectModel project = projectRepository.Add(request.Project);
            await projectRepository.UnitOfWork.SaveEntitiesAsync();

            return(project);
        }
Example #25
0
        private async Task <Project> AddProjectAsync(long userId, CreateProjectRequest request)
        {
            var country = await GetCountryAsync(request.CountryCode);

            var user = await _userRepository.GetByIdAsync(userId);

            var project = new Project
            {
                Name           = request.Name,
                CountryId      = country.Id,
                Category       = (Category)request.Category,
                Description    = request.Description,
                AuthorId       = userId,
                ExternalId     = Guid.NewGuid(),
                ContactEmail   = request.ContactEmail,
                IcoDate        = request.IcoDate,
                Website        = request.Website,
                WhitePaperLink = request.WhitePaperLink,
                Stage          = (Stage)request.Stage,
                Facebook       = request.Facebook,
                Reddit         = request.Reddit,
                BitcoinTalk    = request.BitcoinTalk,
                Telegram       = request.Telegram,
                Github         = request.Github,
                Medium         = request.Medium,
                Twitter        = request.Twitter,
                Linkedin       = request.Linkedin,
                IsPrivate      = user.CanCreatePrivateProjects
            };

            _projectRepository.Add(project);
            return(project);
        }
Example #26
0
        public string CreateDefaultOrganizationAndProject(User user)
        {
            string organizationId = user.OrganizationIds.FirstOrDefault();

            if (!String.IsNullOrEmpty(organizationId))
            {
                var defaultProject = _projectRepository.GetByOrganizationId(user.OrganizationIds.First(), useCache: true).FirstOrDefault();
                if (defaultProject != null)
                {
                    return(defaultProject.Id);
                }
            }
            else
            {
                var organization = new Organization {
                    Name = "Default Organization"
                };
                BillingManager.ApplyBillingPlan(organization, Settings.Current.EnableBilling ? BillingManager.FreePlan : BillingManager.UnlimitedPlan, user);
                _organizationRepository.Add(organization);
                organizationId = organization.Id;
            }

            var project = new Project {
                Name = "Default Project", OrganizationId = organizationId
            };

            project.NextSummaryEndOfDayTicks = DateTime.UtcNow.Date.AddDays(1).AddHours(1).Ticks;
            project.AddDefaultOwnerNotificationSettings(user.Id);
            project = _projectRepository.Add(project);

            _tokenRepository.Add(new Token {
                Id             = StringExtensions.GetNewToken(),
                OrganizationId = organizationId,
                ProjectId      = project.Id,
                CreatedUtc     = DateTime.UtcNow,
                ModifiedUtc    = DateTime.UtcNow,
                Type           = TokenType.Access
            });

            if (!user.OrganizationIds.Contains(organizationId))
            {
                user.OrganizationIds.Add(organizationId);
                _userRepository.Save(user, true);
            }

            return(project.Id);
        }
Example #27
0
 public static void AddProjects(this IProjectRepository projectRepository, int entryCount, string plant)
 {
     for (var i = 0; i < entryCount; i++)
     {
         var project = new Project(plant, $"Project-{i}", "Decription");
         projectRepository.Add(project);
     }
 }
Example #28
0
        public void Add(ProjectModel model)
        {
            var entity = ProjectFactory.Create(model);

            _projectRepository.Add(entity);

            model.Id = entity.Id;
        }
        public async Task <IActionResult> AddProject(Project project)
        {
            if (ModelState.IsValid)
            {
                var userId      = userManager.GetUserId(User);
                var currentUser = await userManager.FindByIdAsync(userId);

                var newProject = new Project();

                newProject.OwnerId            = userId;
                newProject.OwnerUserName      = currentUser.UserName;
                newProject.ProjectName        = project.ProjectName;
                newProject.ProjectDescription = project.ProjectDescription;
                newProject.ProjectStatus      = project.ProjectStatus;
                newProject.StartDate          = project.StartDate;
                newProject.EndDate            = project.EndDate;

                _projectRepository.Add(newProject);

                var claims = await userManager.GetClaimsAsync(currentUser);

                Console.WriteLine(claims.Count);
                var result = await userManager.RemoveClaimsAsync(currentUser, claims);

                var claimList = new List <Claim>();

                for (var i = 0; i < ClaimsPile.AllClaims.Count; i++)
                {
                    if (claims.Count == 4 && claims[i].Value != null)
                    {
                        claimList.Add(new Claim(ClaimsPile.AllClaims[i].Type, claims[i].Value + " " + newProject.ProjectId.ToString()));
                    }
                    else
                    {
                        claimList.Add(new Claim(ClaimsPile.AllClaims[i].Type, newProject.ProjectId.ToString()));
                    }
                }

                foreach (var claim in claimList)
                {
                    Console.WriteLine(claim.Issuer);
                    Console.WriteLine(claim.Type);
                    Console.WriteLine(claim.Value);
                    Console.WriteLine("----------");
                }


                Global.globalCurrentUserClaims = claimList;

                result = await userManager.AddClaimsAsync(currentUser, claimList);

                Global.ProjectId = newProject.ProjectId;

                return(RedirectToAction("ProjectDetails", new { projectId = newProject.ProjectId }));
            }

            return(View());
        }
Example #30
0
        /// <summary>
        /// Add new project
        /// </summary>
        /// <param name="name">Name of the project</param>
        /// <param name="description">Description of the project</param>
        /// <returns>Created project dto</returns>
        public async Task <ProjectDto> AddProjectAsync(string name, string description)
        {
            var project = new ProjectAggregate(name, description);

            _projectRepository.Add(project);
            await _projectRepository.SaveAsync();

            return(project.ToProjectDto());
        }
Example #31
0
 public IActionResult Add(ProjectAdd project)
 {
     if (!ModelState.IsValid)
     {
         return(View(project));
     }
     repository.Add(project);
     return(Redirect("~/"));
 }