protected async Task CreateBuildEngineProjectAsync(Project project)
        {
            var buildEngineProject = new BuildEngineProject
            {
                UserId        = project.Owner.Email,
                GroupId       = project.Group.Abbreviation,
                AppId         = project.Type.Name,
                LanguageCode  = project.Language,
                PublishingKey = project.Owner.PublishingKey,
                ProjectName   = project.Name
            };
            ProjectResponse projectResponse = null;

            if (SetBuildEngineEndpoint(project.Organization))
            {
                projectResponse = BuildEngineApi.CreateProject(buildEngineProject);
            }
            if ((projectResponse != null) && (projectResponse.Id != 0))
            {
                // Set state to active?
                project.WorkflowProjectId = projectResponse.Id;
                await ProjectRepository.UpdateAsync(project);

                var monitorJob = Job.FromExpression <BuildEngineProjectService>(service => service.ManageProject(project.Id));
                RecurringJobManager.AddOrUpdate(GetHangfireToken(project.Id), monitorJob, "* * * * *");
            }
            else
            {
                // TODO: Send Notification
                // Throw Exception to force retry
                throw new Exception("Create project failed");
            }
        }
예제 #2
0
        public async Task <IActionResult> UpdateProjectAsync(int projectId, [FromBody] UpdateProjectRequest request, [FromServices] IUpdateProjectCommand command, [FromServices] IGetProjectQuery query)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            string user    = User.Identity.Name;
            var    project = await query.RunAsync(projectId);

            try
            {
                var authorizationResult = await _authorizationService.AuthorizeAsync(User, project, Operations.Update);

                if (authorizationResult.Succeeded)
                {
                    ProjectResponse response = await command.ExecuteAsync(projectId, request, user);

                    return(response == null
                        ? (IActionResult)NotFound("Project Not Found")
                        : Ok(response));
                }
                return(StatusCode(403, "Вы не можете изменить этот проект!"));
            }
            catch (ProjectLockedException)
            {
                return(BadRequest("В данный момент изменение проекта невозможно!"));
            }
            catch (DbUpdateConcurrencyException)
            {
                return(BadRequest("Ошибка параллелизма!"));
            }
        }
        protected async Task ProjectCompletedAsync(Project project, ProjectResponse projectResponse)
        {
            project.WorkflowProjectUrl = projectResponse.Url;
            await ProjectRepository.UpdateAsync(project);

            ClearAndExit(project.Id);
        }
        public async Task Project_Failed()
        {
            BuildTestData();
            var buildProjectService = _fixture.GetService <BuildEngineProjectService>();
            var mockBuildEngine     = Mock.Get(buildProjectService.BuildEngineApi);

            mockBuildEngine.Reset();
            var projectResponse = new ProjectResponse
            {
                Id     = 4,
                Status = "completed",
                Result = "FAILURE",
                Error  = "",
                Url    = "ssh://[email protected]/v1/repos/scriptureappbuilder-DEM-LSDEV-eng-US-Test-Project8"
            };

            mockBuildEngine.Setup(x => x.GetProject(It.IsAny <int>())).Returns(projectResponse);
            await buildProjectService.ManageProjectAsync(project3.Id);

            mockBuildEngine.Verify(x => x.SetEndpoint(
                                       It.Is <String>(u => u == org1.BuildEngineUrl),
                                       It.Is <String>(t => t == org1.BuildEngineApiAccessToken)
                                       ));
            mockBuildEngine.Verify(x => x.GetProject(
                                       It.Is <int>(b => b == project3.WorkflowProjectId)
                                       ));
            var projects        = ReadTestData <AppDbContext, Project>();
            var modifiedProject = projects.First(p => p.Id == project1.Id);

            Assert.Null(modifiedProject.WorkflowProjectUrl);
        }
예제 #5
0
        public void ReadImageFileIndexReturnsOnlyFilesNotAlreadyImported()
        {
            var indexedLocation = "indexedLocation";
            var id           = "1";
            var importedFile = new ImageFileIndexStructure()
            {
                Id = "1"
            };

            var moqImageResponse = new ImageFileIndexResponse()
            {
            };

            moqImageResponse.Files.Add(importedFile);
            var moqProjectResponse = new ProjectResponse()
            {
                Project = new ProjectStructure()
                {
                    Id = ObjectId.GenerateNewId().ToString()
                }
            };

            moqProjectResponse.Project.SmallFileIds.Add(importedFile.Id);

            MockMakerClient.Setup(x => x.ReadImageFileIndex(It.IsAny <string>())).Returns(moqImageResponse);
            MockMakerClient.Setup(x => x.ReadProject(It.IsAny <string>())).Returns(moqProjectResponse);

            var model = new ImageFileIndexModel();

            model.ReadImageFileIndex(MockMakerClient.Object, indexedLocation, id);
            Assert.AreEqual(0, model.Files.Count);
        }
예제 #6
0
        public void ReadImageFileIndexReturnsOneFilesIfOneInCollection()
        {
            var indexedLocation = "indexedLocation";
            var id           = "1";
            var importedFile = new ImageFileIndexStructure()
            {
                Id = "1"
            };

            var moqImageResponse   = new ImageFileIndexResponse();
            var moqProjectResponse = new ProjectResponse()
            {
                Project = new ProjectStructure()
            };

            moqImageResponse.Files.Add(importedFile);

            MockMakerClient.Setup(x => x.ReadImageFileIndex(It.IsAny <string>())).Returns(moqImageResponse);
            MockMakerClient.Setup(x => x.ReadProject(It.IsAny <string>())).Returns(moqProjectResponse);

            var model = new ImageFileIndexModel();

            model.ReadImageFileIndex(MockMakerClient.Object, indexedLocation, id);
            Assert.AreEqual(1, model.Files.Count);
        }
예제 #7
0
        public void GenerateReturnsErrorIfReadAllImageFilesReturnsError()
        {
            var id    = ObjectId.GenerateNewId().ToString();
            var model = new GenerateMosaicModel();

            var projectResponse = new ProjectResponse()
            {
                Project = new ProjectStructure()
                {
                    Id = id, LargeFileId = ObjectId.GenerateNewId().ToString()
                }
            };

            projectResponse.Project.SmallFileIds.Add("1");

            MockMakerClient.Setup(x => x.ReadProject(It.Is <string>(y => y.Equals(id)))).Returns(projectResponse);
            MockMakerClient.Setup(x => x.ReadAllImageFiles(It.IsAny <IList <string> >())).Returns(new ImageFileIndexResponse()
            {
                Error = "Error"
            });
            MockMakerClient.Setup(x => x.ReadImageFile(It.IsAny <string>())).Returns(new ImageFileResponse()
            {
            });

            var response = model.Generate(MockMakerClient.Object, id);

            Assert.IsFalse(String.IsNullOrEmpty(response.Error));
        }
예제 #8
0
        public async Task <IActionResult> Create([FromBody] CreateProjectRequest postRequest)
        {
            var newProjectId = Guid.NewGuid();

            var project = new Project
            {
                Id          = newProjectId,
                Name        = postRequest.Name,
                Description = postRequest.Description,
                CreatedOn   = DateTime.Now,
                Completion  = postRequest.Completion
            };

            var projectResponse = new ProjectResponse
            {
                Id          = project.Id,
                Name        = project.Name,
                Description = project.Description,
                CreatedOn   = project.CreatedOn.ToString(),
                Completion  = project.Completion.ToString()
            };

            await _projectService.CreateAsync(project);

            var locationUri = _uriService.GetProjectUri(project.Id.ToString());

            return(Created(locationUri, projectResponse));
        }
예제 #9
0
        public async Task <ActionResult <ProjectResponse> > GetProject(int id)
        {
            try
            {
                var project = await projectClass.GetProject(id);

                if (project.Name == null)
                {
                    projectResponse = new ProjectResponse
                    {
                        StatusCode = 400,
                        Message    = "Invalid Id",
                    };
                    return(Ok(projectResponse));
                }
                else
                {
                    projectResponse = new ProjectResponse
                    {
                        StatusCode   = 200,
                        Message      = "Successfully Executed",
                        ResponseData = project
                    };
                    return(Ok(projectResponse));
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #10
0
        public async Task <IActionResult> PutProject(int id, ProjectRequest projectRequest)
        {
            var project = await projectClass.EditProject(id, projectRequest);

            if (project.Name == null)
            {
                projectResponse = new ProjectResponse
                {
                    StatusCode = 400,
                    Message    = "Invalid Id",
                };
                return(Ok(projectResponse));
            }
            else
            {
                projectResponse = new ProjectResponse
                {
                    StatusCode   = 200,
                    Message      = "Successfully Updated",
                    ResponseData = project
                };

                return(Ok(projectResponse));
            }
        }
        public async Task Project_Update_ProjectAsync()
        {
            BuildTestData();
            var buildProjectService = _fixture.GetService <BuildEngineProjectService>();
            var mockBuildEngine     = Mock.Get(buildProjectService.BuildEngineApi);

            mockBuildEngine.Reset();
            var projectResponse = new ProjectResponse
            {
                Id     = 3,
                Status = "completed",
                Result = "SUCCESS",
                Error  = "",
                Url    = "ssh://[email protected]/v1/repos/scriptureappbuilder-DEM-LSDEV-eng-US-Test-Project8"
            };

            mockBuildEngine.Setup(x => x.UpdateProject(It.IsAny <int>(), It.IsAny <BuildEngineProject>())).Returns(projectResponse);
            await buildProjectService.UpdateProjectAsync(project2.Id);

            mockBuildEngine.Verify(x => x.SetEndpoint(
                                       It.Is <String>(u => u == org1.BuildEngineUrl),
                                       It.Is <String>(t => t == org1.BuildEngineApiAccessToken)
                                       ));
            mockBuildEngine.Verify(x => x.UpdateProject(
                                       It.Is <int>(i => i == project2.WorkflowProjectId),
                                       It.Is <BuildEngineProject>(b => b.UserId == user1.Email)
                                       ));
        }
예제 #12
0
        public async Task <IActionResult> GetAsync([FromQuery] QueryProjectsRequest request)
        {
            if (request.IsPrivate == true && !User.IsInRole(nameof(RoleType.Admin)))
            {
                return(Unauthorized());
            }

            var projectsQuery = new ProjectsQuery(
                request.Offset,
                request.Count,
                request.IsPrivate,
                request.OnlyScored,
                request.SearchString,
                request.Stage,
                request.CountryCode,
                request.Category,
                request.MinimumScore,
                request.MaximumScore,
                request.OrderBy,
                request.SortDirection,
                request.ScoringStatuses ?? new List <ScoringStatus>(),
                request.ProjectIds ?? new List <long>()
                );

            var projects = await _projectService.GetAsync(projectsQuery);

            var scoringsApplications = await _scoringApplicationRepository.GetByProjectIdsAsync(projects.Select(i => i.Id).ToArray());

            return(Ok(projects.ToPartialCollectionResponse(p => ProjectResponse.Create(p, scoringsApplications.FirstOrDefault(s => s.ProjectId == p.Id)))));
        }
예제 #13
0
 public List <ActivityResponse> Activities(OrganizationResponse organization, ProjectResponse project)
 {
     try
     {
         if (project == null || organization == null)
         {
             return(new List <ActivityResponse>());
         }
         var response = OrgApi.GetOrgApi().ListProjectActivitiesWithHttpInfo(organization.Id, project.Id);
         if (response.StatusCode == 200)
         {
             return(response.Data);
         }
         else
         {
             throw new ApiException();
         }
     }
     catch (ApiException ex)
     {
         Popup.ShowPopupError(ex.Message);
         return(new List <ActivityResponse>());
     }
     catch (Exception ex)
     {
         Popup.ShowPopupError(ex.Message);
         return(new List <ActivityResponse>());
     }
 }
예제 #14
0
        public async Task <IActionResult> ImportProject([FromServices] IImportProjectCommand command, [FromBody] ImportProjectRequest request)
        {
            var             userId = getUserId();
            ProjectResponse result = await command.ExecuteAsync(request, userId);

            return(Ok(result));
        }
예제 #15
0
        public async Task <ActionResult> GetAllMenu(int role, int pageNo = 1, int pageSize = 5)
        {
            using (var db = new EFWorkContext())
            {
                //var d =  from m in db.Project where m.ParentId == null && m.RoleProject.Any(a => a.RoleId == role) select m;
                var d         = db.Menu.Where(a => a.Parent == null && a.Roles.Any(b => b.Id == role));
                int dataCount = d.Count();
                //var p = await d.OrderBy(a => a.Id).Skip((pageNo - 1) * pageSize).Take(pageSize).ToListAsync();

                //var orderExpression = string.Format("{0} {1}", sortName, sortType); //sortName排序的名称 sortType排序类型 (desc asc)
                var orderExpression = string.Format("{0} {1}", "id", "desc"); //sortName排序的名称 sortType排序类型 (desc asc)
                var p = await d.OrderBy(orderExpression).Skip((pageNo - 1) * pageSize).Take(pageSize).ToListAsync();

                ProjectResponse pr = new ProjectResponse();
                pr.PageNo    = pageNo;
                pr.PageSize  = pageSize;
                pr.DataCount = dataCount;
                pr.PageCount = (int)Math.Ceiling((decimal)dataCount / pageSize);
                foreach (var item in p)
                {
                    pr.Projects.Add(new Project()
                    {
                        Id = item.Id, Name = item.Name, ParentId = item.ParentId
                    });
                }
                return(Json(pr, JsonRequestBehavior.AllowGet));
            }
        }
예제 #16
0
        public async Task <ProjectResponse> RunAsync(int projectId)
        {
            //var project = await Uow.Projects.FindAsync(projectId);
            //if (project != null)
            //{
            //    return new ProjectResponse
            //    {
            //        Id = project.Id,
            //        Name = project.Name,
            //        Description = project.Description,
            //        OpenTasksCount = project.Tasks.Count(t => t.Status != Entities.TaskStatus.Completed)
            //    };
            //}
            //return null;

            ProjectResponse response = await Uow.Projects
                                       .Select(p => new ProjectResponse
            {
                Id             = p.Id,
                Name           = p.Name,
                Description    = p.Description,
                OpenTasksCount = p.Tasks.Count(t => t.Status != Entities.TaskStatus.Completed)
            })
                                       .FirstOrDefaultAsync(pr => pr.Id == projectId);

            return(response);
        }
예제 #17
0
        public JsonResult CreateProject(string repo, string projectName)
        {
            //  projectName = "mind";
            APIServicecs ApiObject;

            //  ProjectDetails projectDetails = new ProjectDetails();
            try
            {
                string templatesPath = Server.MapPath("~") + @"\JSON Template\";
                ApiObject = new APIServicecs(Session["PAT"].ToString());
                var    userDetails = JsonConvert.DeserializeObject <UserDetails>(ApiObject.ApiService("https://api.github.com/user"));
                string ownername   = userDetails.login;//"ashwin9627";//;
                string url         = "https://api.github.com/repos/" + ownername + "/" + repo + "/projects";
                string RqstBody    = "";
                //if (System.IO.File.Exists(templatesPath + @"\projectDetails.json"))
                //{
                //    RqstBody = projectDetails.ReadJsonFile(templatesPath + @"\projectDetails.json");
                //}
                string RequestBody = System.IO.File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath("~") + @"\Jsons\Repo.json");
                RequestBody = RequestBody.Replace("$name$", projectName);
                string responseString = ApiObject.ApiService(url, "POST", RequestBody);
                //  var responseString = response.Content.ReadAsStringAsync().Result;
                ProjectResponse pro = JsonConvert.DeserializeObject <ProjectResponse>(responseString);
                CreateColumn(pro.id.ToString());
                return(Json(pro, JsonRequestBehavior.AllowGet));

                //projectDetails = JsonConvert.DeserializeObject<ProjectDetails>(ApiObject.ApiService(url, "POST", RqstBody));
            }
            catch (Exception ex)
            {
                ProjectResponse pro1 = new ProjectResponse();
                return(Json(pro1, JsonRequestBehavior.AllowGet));
            }
        }
예제 #18
0
        public async Task <IActionResult> GetProjectAsync(int projectId, [FromServices] IProjectQuery query)
        {
            ProjectResponse response = await query.RunAsync(projectId);

            return(response == null
                ? (IActionResult)NotFound("Project Not Found")
                : Ok(response));
        }
예제 #19
0
        /// <summary>
        /// Deletes the project.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <returns></returns>
        public ProjectResponse DeleteProject(string projectId)
        {
            var response = new ProjectResponse {
                Acknowledge = AcknowledgeType.Success
            };

            try
            {
                var project  = ProjectDao.GetProject(projectId);
                var projects = ProjectDao.GetProjects().Where(x => x.ParentID == projectId).ToList();

                if (projects.Count != 0)
                {
                    response.Acknowledge = AcknowledgeType.Failure;

                    switch (project.ObjectType)
                    {
                    case 1:
                        response.Message = @"Bạn phải xóa tất cả các CTMT con trước khi xóa CTMT cha";
                        break;

                    case 2:
                        response.Message = @"Bạn phải xóa tất cả các dự án con trước khi xóa dự án cha";
                        break;

                    case 3:
                        response.Message = @"Bạn phải xóa tất cả các HMCT con trước khi xóa HMCT cha";
                        break;
                    }
                    return(response);
                }

                response.Message = ProjectDao.DeleteProject(projectId);
                if (!string.IsNullOrEmpty(response.Message))
                {
                    if (response.Message.Contains("FK")
                        )
                    {
                        response.Message = @"Bạn không thể xóa dự án,CTMT,HMCT " + project.ProjectCode + " , vì đã có phát sinh trong chứng từ hoặc danh mục liên quan!";
                    }
                    response.Acknowledge = AcknowledgeType.Failure;
                    return(response);
                }
                if (!string.IsNullOrEmpty(response.Message))
                {
                    response.Acknowledge = AcknowledgeType.Failure;
                    return(response);
                }
                response.ProjectId = projectId;
                return(response);
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                return(response);
            }
        }
예제 #20
0
        public HttpResponseMessage Login(LoginInModel lim)
        {
            StringContent   stringContent;
            ProjectResponse response = new ProjectResponse();
            var             result   = new UserModel();
            var             sps      = new SignUpService();

            try
            {
                result = sps.Login(lim);
            }
            catch (DataException de)
            {
                response.internalcode = de.Info;
                if (de.Info == "21")
                {
                    response.status = "IOerror";
                    stringContent   = new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json");
                }
                else if (de.Info == "3")
                {
                    response.status = "Passworderror";
                    stringContent   = new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json");
                }
                else if (de.Info == "2")
                {
                    response.status = "UserNotexist";
                    stringContent   = new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json");
                }
                else
                {
                    response.status = "Unknownerror";
                    stringContent   = new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json");
                }
                HttpResponseMessage hrm = new HttpResponseMessage();
                hrm.Content = stringContent;
                return(hrm);
            }

            var resp = new HttpResponseMessage();

            var nv = new NameValueCollection();

            nv["user"]     = result.Name;
            nv["username"] = result.UserName;
            nv["id"]       = result.Id;
            var cookie = new CookieHeaderValue("session", nv);

            response.internalcode = "1";
            response.status       = "success";
            resp.Content          = new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json");
            resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });



            return(resp);
        }
        /// <summary>
        /// Initialize the module loader.
        /// </summary>
        public void Initialize()
        {
            if (_isInitialized)
            {
                throw new ModuleLoaderInternalException("the loader is already initialized");
            }

            _modulePath = Environment.GetEnvironmentVariable(ENV_NAME);
            if (string.IsNullOrWhiteSpace(_modulePath))
            {
                throw new ModuleLoaderConfigurationException($"The {ENV_NAME} environment variable must be set");
            }

            if (!Directory.Exists(_modulePath))
            {
                throw new ModuleLoaderConfigurationException($"The directory specified in the {ENV_NAME} environment variable doesn't exist");
            }

            AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;
            if (_options.NugetSources == null || !_options.NugetSources.Any())
            {
                throw new ModuleLoaderConfigurationException("At least one nuget sources must be specified");
            }

            if (string.IsNullOrWhiteSpace(_options.ProjectName))
            {
                throw new ModuleLoaderConfigurationException("The project name must be specified");
            }

            if (_options.ModuleFeedUri == null)
            {
                throw new ModuleLoaderConfigurationException("The ModuleFeedUri parameter must be specified");
            }

            var currentDirectory      = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var configurationFilePath = Path.Combine(currentDirectory, _configFile);

            if (!File.Exists(configurationFilePath))
            {
                throw new FileNotFoundException(configurationFilePath);
            }

            var json = File.ReadAllText(configurationFilePath);

            _projectConfiguration = JsonConvert.DeserializeObject <ProjectResponse>(json);
            if (_projectConfiguration == null)
            {
                throw new ModuleLoaderConfigurationException($"{configurationFilePath} is not a valid configuration file");
            }

            _isInitialized = true;
            if (Initialized != null)
            {
                Initialized(this, EventArgs.Empty);
            }
        }
예제 #22
0
        public async Task <IActionResult> UpdateProjectAsync([FromBody] UpdateProjectRequest request, [FromServices] IUpdateProjectCommand command)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            ProjectResponse response = await command.ExecuteAsync(request);

            return(response == null ? (IActionResult)NotFound() : Ok(response));
        }
예제 #23
0
        protected ProjectResponse ConvertToProjectResponse(UserProject convertedProject)
        {
            var projectResponse = new ProjectResponse()
            {
                Id = convertedProject.Id, Title = convertedProject.Title
            };

            projectResponse.Cards = ConvertCardResponses(convertedProject.Cards);
            return(projectResponse);
        }
예제 #24
0
        public async Task <IActionResult> CreateProjectAsync([FromBody] CreateProjectRequest request, [FromServices] ICreateProjectCommand command)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            ProjectResponse response = await command.ExecuteAsync(request);

            return(Ok(response)); // This is wrong, it should return 401
        }
예제 #25
0
        public async Task <IActionResult> CreateProjectAsync([FromBody] CreateProjectRequest request, [FromServices] ICreateProjectCommand command)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            string          user     = User.Identity.Name;
            ProjectResponse response = await command.ExecuteAsync(request, user);

            return(Created(Url.RouteUrl(new { response.Id }), response));
        }
예제 #26
0
        public async Task <IActionResult> CreateProjectAsync([FromBody] CreateProjectRequest request, [FromServices] ICreateProjectCommand command)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var             userId   = HttpContext.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier).Value;
            ProjectResponse response = await command.ExecuteAsync(request, userId);

            return(CreatedAtRoute("GetSingleProject", new { projectId = response.Id }, response));
        }
예제 #27
0
        public ProjectResponse InsertProject([FromBody] ProjectsRequest request)
        {
            ProjectResponse response = new ProjectResponse();

            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    if (!BAplication.ValidateAplicationToken(request.ApplicationToken))
                    {
                        response.Code    = "2";
                        response.Message = Messages.ApplicationTokenNoAutorize;
                        return(response);
                    }

                    string webRoot     = _env.ContentRootPath;
                    string rootPath    = _appSettings.Value.rootPath;
                    string ProjectPath = _appSettings.Value.ProjectPath;

                    BaseRequest baseRequest = new BaseRequest();

                    foreach (MProject model in request.Projects)
                    {
                        MProject project = new MProject();

                        project.ProjectCode = model.ProjectCode;
                        project.Description = model.Description;
                        project.Type        = model.Type;
                        project.Status      = model.Status;
                        project.StartDate   = model.StartDate;
                        project.EndDate     = model.EndDate;
                        project.Title       = model.Title;
                        project.AwardId     = model.AwardId;
                        project.AwardStatus = model.AwardStatus;

                        BProject.Insert(project);
                    }

                    response.Code    = "0";
                    response.Message = "Success";

                    scope.Complete();
                }
                catch (Exception ex)
                {
                    response.Code    = "2";
                    response.Message = ex.Message;

                    scope.Dispose();
                }
            }

            return(response);
        }
예제 #28
0
        public bool PostWorklog(OrganizationResponse organization, ProjectResponse project, ActivityResponse activity, long minutes, string day)
        {
            try
            {
                if (project == null || organization == null || activity == null)
                {
                    Popup.ShowPopupError("Please fill in all the fields");
                    return(false);
                }
                var response = OrgApi.GetOrgApi().LogWorkForCurrentUserWithHttpInfo(organization.Id, project.Id, activity.Id, new NewWorklogRequest(day, minutes, true));
                if (response.StatusCode == 201)
                {
                    return(true);
                }
                else
                {
                    throw new ApiException();
                }
            }
            catch (ApiException ex)
            {
                if (ex.ErrorCode == 412)
                {
                    var    json         = JObject.Parse(ex.ErrorContent);
                    string errorMessage = json["message"];
                    Popup.ShowPopupError("User not assigned to project: " + errorMessage);
                    return(false);
                }
                if (ex.ErrorCode == 400)
                {
                    var    json      = JObject.Parse(ex.ErrorContent);
                    string errorCode = json["errorCode"];
                    if (errorCode == "3000")
                    {
                        Popup.ShowPopupError("No overtime allowed for project: " + project.Name);
                        return(false);
                    }
                    else
                    {
                        string message = json["message"];
                        Popup.ShowPopupError(message);
                        return(false);
                    }
                }

                Popup.ShowPopupError(ex.Message);
                return(false);
            }
            catch (Exception ex)
            {
                Popup.ShowPopupError(ex.Message);
                return(false);
            }
        }
예제 #29
0
        public async Task <IActionResult> GetAll(CancellationToken cancellationToken = default)
        {
            _logger.LogInformation("Getting all projects...");

            var projects = await _dbContext
                           .Projects
                           .ToListAsync(cancellationToken);

            _logger.LogInformation("Got all projects successfully");
            return(Ok(projects.Select(x => ProjectResponse.Map(x))));
        }
예제 #30
0
        public ProjectResponse InsertProjectConvert(ProjectEntity project)
        {
            var response = new ProjectResponse {
                Acknowledge = AcknowledgeType.Success
            };

            try
            {
                var projects = ProjectDao.GetProjectsByProjectCodeObjectType(project.ProjectCode, project.ObjectType);
                if (projects != null)
                {
                    response.Acknowledge = AcknowledgeType.Failure;
                    switch (project.ObjectType)
                    {
                    case 1:
                        response.Message = @"Mã CTMT " + project.ProjectCode + @" đã tồn tại!";
                        break;

                    case 2:
                        response.Message = @"Mã dự án " + project.ProjectCode + @" đã tồn tại!";
                        break;

                    case 3:
                        response.Message = @"Mã HMCT " + project.ProjectCode + @" đã tồn tại!";
                        break;
                    }

                    return(response);
                }
                if (!project.Validate())
                {
                    foreach (string error in project.ValidationErrors)
                    {
                        response.Message += error + Environment.NewLine;
                    }
                    response.Acknowledge = AcknowledgeType.Failure;
                    return(response);
                }
                response.Message = ProjectDao.InsertProject(project);
                if (!string.IsNullOrEmpty(response.Message))
                {
                    response.Acknowledge = AcknowledgeType.Failure;
                    return(response);
                }
                response.ProjectId = project.ProjectId;
                return(response);
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                return(response);
            }
        }