Inheritance: DelegatingHandler
Example #1
0
        public Task WriteAsync(Response response)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            var wrapper = new ResponseWrapper(response);
            Message message = wrapper.GetMessage();

            byte[] responsePayload = null;
            using (var ms = new MemoryStream())
            {
                Serializer.Serialize(ms, message);
                responsePayload = ms.ToArray();
            }

            int payloadLen = responsePayload.Length;
            var payloadLenBytes = Encoding.ASCII.GetBytes(payloadLen.ToString());

            byte[] responseBytes = null;
            using (var ms = new MemoryStream())
            {
                ms.Write(payloadLenBytes, 0, payloadLenBytes.Length);
                ms.WriteByte(Constants.CR);
                ms.WriteByte(Constants.LF);
                ms.Write(responsePayload, 0, responsePayload.Length);
                ms.WriteByte(Constants.CR);
                ms.WriteByte(Constants.LF);
                responseBytes = ms.ToArray();
            }
            return destination.WriteAsync(responseBytes, 0, responseBytes.Length);
        }
Example #2
0
 public static new BooleanResult fromResponse(ResponseWrapper responseWrapper)
 {
     BooleanResult tagListResult = new BooleanResult();
      if (responseWrapper.isServerResponse())
      {
          tagListResult = JsonConvert.DeserializeObject<BooleanResult>(responseWrapper.responseContent);
      }
      tagListResult.ResponseResult = responseWrapper;
      return tagListResult;
 }
        /// <summary>
        /// Wrapper for returning a BadRequest - so we can centrally change the structure of standard responses
        /// </summary>
        /// <param name="errorMessage">Message to send back</param>
        /// <param name="content">Anything that needs to be returned to client</param>
        /// <returns>ResponseWrapper</returns>
        protected OkNegotiatedContentResult<ResponseWrapper<object>> processBadRequest(string errorMessage, object content = null)
        {
            ResponseWrapper<object> response = new ResponseWrapper<object>
            {
                Status = Constants.Api.ResponseStatus.Fail,
                ErrorMessage = errorMessage,
                Content = content
            };

            return this.Ok(response);
        }
        /// <summary>
        /// Wrapper for returning an OK - so we can centrally change the structure of standard responses
        /// </summary>
        /// <param name="content">Anything that needs to be returned to client</param>
        /// <returns>ResponseWrapper</returns>
        protected OkNegotiatedContentResult<ResponseWrapper<object>> processOk(object content)
        {
            ResponseWrapper<object> response = new ResponseWrapper<object>
            {
                Content = content,
                Status = Constants.Api.ResponseStatus.Ok
            };

            // this.addTimingTelemetry(response);

            return this.Ok(response);
        }
        public static DefaultResult fromResponse(ResponseWrapper responseWrapper)
        {
            DefaultResult result = null;

            if (responseWrapper.isServerResponse())
            {
                result = new DefaultResult();
            }

            result.ResponseResult=responseWrapper;

            return result;
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            [RequestBodyType(typeof(GetPostcodesRequest), "Get Postcodes")] GetPostcodesRequest req,
            CancellationToken cancellationToken)
        {
            try
            {
                NewRelic.Api.Agent.NewRelic.SetTransactionName("AddressService", "GetPostcodes");
                _logger.LogInformation("C# HTTP trigger function processed a request.");

                GetPostcodesResponse response = await _mediator.Send(req, cancellationToken);

                return(new OkObjectResult(ResponseWrapper <GetPostcodesResponse, AddressServiceErrorCode> .CreateSuccessfulResponse(response)));
            }
            catch (Exception ex)
            {
                _logger.LogErrorAndNotifyNewRelic($"Unhandled error in GetPostcodes", ex, req);
                return(new ObjectResult(ResponseWrapper <GetPostcodesResponse, AddressServiceErrorCode> .CreateUnsuccessfulResponse(AddressServiceErrorCode.UnhandledError, "Internal Error"))
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
Example #7
0
        public ResponseWrapper <string> GetAccount(string clientId)
        {
            ResponseWrapper <string> response = new ResponseWrapper <string>();

            if (CacheUtil.Exists(clientId) == false)
            {
                response.ReturnCode   = 0;
                response.Message      = "Login Failed";
                response.InnerMessage = "The client id is expired or does not exists.";
                response.Result       = null;

                return(response);
            }

            var MyQQEntity = (MyQQEntity)CacheUtil.Get(clientId);

            response.ReturnCode   = 1;
            response.Message      = "";
            response.InnerMessage = "";
            response.Result       = MyQQEntity.QQAccount;

            return(response);
        }
Example #8
0
        public ResponseWrapper <List <DicussionGroupMemberEntity> > GetDiscussionMemberList(string clientId, string groupId)
        {
            ResponseWrapper <List <DicussionGroupMemberEntity> > response = new ResponseWrapper <List <DicussionGroupMemberEntity> >();

            if (CacheUtil.Exists(clientId) == false)
            {
                response.ReturnCode   = 0;
                response.Message      = "Login Failed";
                response.InnerMessage = "The client id is expired or does not exists.";
                response.Result       = null;

                return(response);
            }

            List <DicussionGroupMemberEntity> members = myQQDAL.GetQQDicusstionGroupMembersByGroupId(groupId);

            response.ReturnCode   = 1;
            response.Message      = "";
            response.InnerMessage = "";
            response.Result       = members;

            return(response);
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
            [RequestBodyType(typeof(GetShiftRequestsByFilterRequest), "Get Shift Requests By Filter request")] GetShiftRequestsByFilterRequest req,
            CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("GetShiftRequestsByFilter started");
                GetShiftRequestsByFilterResponse response = await _mediator.Send(req, cancellationToken);

                return(new OkObjectResult(ResponseWrapper <GetShiftRequestsByFilterResponse, RequestServiceErrorCode> .CreateSuccessfulResponse(response)));
            }
            catch (Exception exc)
            {
                _logger.LogError("Exception occured in GetShiftRequestsByFilter", exc);
                _logger.LogError(exc.ToString(), exc);
                _logger.LogErrorAndNotifyNewRelic("Exception occured in GetShiftRequestsByFilter", exc);
                return(new ObjectResult(ResponseWrapper <GetShiftRequestsByFilterResponse, RequestServiceErrorCode> .CreateUnsuccessfulResponse(RequestServiceErrorCode.InternalServerError, "Internal Error"))
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            [RequestBodyType(typeof(SendEmailToUserRequest), "Send Email To User")] SendEmailToUserRequest req,
            ILogger log)
        {
            try
            {
                NewRelic.Api.Agent.NewRelic.SetTransactionName("CommunicationService", "SendEmailToUser");
                log.LogInformation("C# HTTP trigger function processed a request.");

                SendEmailResponse response = await _mediator.Send(req);

                return(new OkObjectResult(ResponseWrapper <SendEmailResponse, CommunicationServiceErrorCode> .CreateSuccessfulResponse(response)));
            }
            catch (Exception exc)
            {
                LogError.Log(log, exc, req);
                return(new ObjectResult(ResponseWrapper <SendEmailResponse, CommunicationServiceErrorCode> .CreateUnsuccessfulResponse(CommunicationServiceErrorCode.InternalServerError, "Internal Error"))
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
        public HttpResponseMessage GetPagingApplicationReviewCommentList(int projectTypeId, int year, int page)
        {
            try
            {
                /*
                 * year = year <= 0 ? SystemConfig.ApplicationStartYear : year;
                 * var userInfo = UserHelper.GetCurrentUser();
                 * Func<Application, bool> predicate = a => userInfo.ProjectTypeIds.Contains(a.ProjectTypeId) //院管理员只能看到他分管的类型
                 *                                   && ((instId == 0) || a.InstituteId == instId)//单位筛选
                 *                                   && ((projectTypeId == 0) || a.ProjectTypeId == projectTypeId)//项目类型筛选
                 *                                   && (a.CurrentYear >= year);//年份筛选
                 */

                var userInfo  = UserHelper.GetCurrentUser();
                var predicate = RetrievalConditions(userInfo.InstId, projectTypeId, 0, a => a.HasReview());
                var res       = repository.GetPagingApplicationReviewCommentList(predicate, page);
                return(ResponseWrapper.SuccessResponse(res));
            }
            catch (Exception e)
            {
                return(ResponseWrapper.ExceptionResponse(e));
            }
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]
            [RequestBodyType(typeof(GetVolunteersByPostcodeAndActivityRequest), "Get Volunteers By Postcode And Activity")] GetVolunteersByPostcodeAndActivityRequest req,
            ILogger log)
        {
            try
            {
                NewRelic.Api.Agent.NewRelic.SetTransactionName("UserService", "GetHelpersContactInformationByPostcode");
                log.LogInformation("C# HTTP trigger function processed a request.");

                GetVolunteersByPostcodeAndActivityResponse response = await _mediator.Send(req);

                return(new OkObjectResult(ResponseWrapper <GetVolunteersByPostcodeAndActivityResponse, UserServiceErrorCode> .CreateSuccessfulResponse(response)));
            }
            catch (Exception exc)
            {
                LogError.Log(log, exc, req);
                return(new ObjectResult(ResponseWrapper <GetVolunteersByPostcodeAndActivityResponse, UserServiceErrorCode> .CreateUnsuccessfulResponse(UserServiceErrorCode.UnhandledError, "Internal Error"))
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
Example #13
0
        public async Task <GroupResult> GetWithGroupByAsync <T>(IRequestContext context, IList <QueryPhrase> queryPhrases, string groupBy) where T : BaseEntity
        {
            string collectionName = EntityTypeRegistry.GetInstance().GetCollectionName(typeof(T));
            string url            = context.GetPath() + "/" + collectionName + "/groups";

            // Octane group API now return logical name by default as ID field,
            // this parameter change this to return numeric ID.
            var serviceArgs = new Dictionary <string, string>();

            serviceArgs.Add("use_numeric_id", "true");

            string queryString = QueryBuilder.Create().SetQueryPhrases(queryPhrases).SetGroupBy(groupBy).SetServiceArguments(serviceArgs).Build();


            ResponseWrapper response = await rc.ExecuteGetAsync(url, queryString).ConfigureAwait(RestConnector.AwaitContinueOnCapturedContext);

            if (response.Data != null)
            {
                GroupResult result = jsonSerializer.Deserialize <GroupResult>(response.Data);
                return(result);
            }
            return(null);
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            [RequestBodyType(typeof(GetDistanceBetweenPostcodesRequest), "Get Distance Between Postcodes")] GetDistanceBetweenPostcodesRequest req,
            CancellationToken cancellationToken)
        {
            try
            {
                var input = JsonConvert.SerializeObject(req);
                _logger.LogInformation(input);
                GetDistanceBetweenPostcodesResponse response = await _mediator.Send(req, cancellationToken);

                return(new OkObjectResult(ResponseWrapper <GetDistanceBetweenPostcodesResponse, AddressServiceErrorCode> .CreateSuccessfulResponse(response)));
            }
            catch (Exception exc)
            {
                _logger.LogErrorAndNotifyNewRelic("Exception occured in GetDistanceBetweenPostcodes", exc);
                _logger.LogError(exc.ToString(), exc);
                return(new ObjectResult(ResponseWrapper <GetDistanceBetweenPostcodesResponse, AddressServiceErrorCode> .CreateUnsuccessfulResponse(AddressServiceErrorCode.UnhandledError, "Internal Error"))
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
Example #15
0
        public GroupResult GetWithGroupBy <T>(IRequestContext context, IList <QueryPhrase> queryPhrases, String groupBy)
            where T : BaseEntity
        {
            String collectionName = GetCollectionName <T>();
            string url            = context.GetPath() + "/" + collectionName + "/groups";


            String queryString = QueryStringBuilder.BuildQueryString(queryPhrases, null, null, null, null, groupBy);

            if (!String.IsNullOrEmpty(queryString))
            {
                url = url + "?" + queryString;
            }

            ResponseWrapper response = rc.ExecuteGet(url);

            if (response.Data != null)
            {
                GroupResult result = jsonSerializer.Deserialize <GroupResult>(response.Data);
                return(result);
            }
            return(null);
        }
        public HttpResponseMessage RefuseRecommendation(int recommendationId)
        {
            try
            {
                var result = repository.RefuseRecommendation(recommendationId);

                //院管理员驳回专家的推荐
                //通知打点:发给单位管理员
                //_noticeService.AddNoticeList(
                //    _noticeService.GetInstMListByAdoptRecommendation(recommendationId), 113,
                //    new Dictionary<string, string>
                //    { {"UserName", _noticeService.GetCandidateNameByRecommendation(recommendationId)} });
                //通知打点:发给用户
                //_noticeService.AddNotice(
                //    _noticeService.GetCandidateIdByRecommendation(recommendationId), 106);

                return(ResponseWrapper.SuccessResponse(result));
            }
            catch (Exception e)
            {
                return(ResponseWrapper.ExceptionResponse(e));
            }
        }
Example #17
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ActionArguments.Any(kv => kv.Value == null))
            {
                actionContext.Response = ResponseWrapper.ExceptionResponse(new OtherException("参数不能为NULL"));
            }

            if (actionContext.ModelState.IsValid == false)
            {
                StringBuilder msg = new StringBuilder();
                foreach (var key in actionContext.ModelState.Keys)
                {
                    var state = actionContext.ModelState[key];
                    foreach (var error in state.Errors)
                    {
                        msg.Append(error.ErrorMessage);
                        msg.Append("<br/>");
                    }
                }

                actionContext.Response = ResponseWrapper.ExceptionResponse(new OtherException(msg.ToString()));
            }
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            [RequestBodyType(typeof(RequestCommunicationRequest), "Request Communication")] RequestCommunicationRequest req,
            ILogger log)
        {
            try
            {
                var request = JsonConvert.SerializeObject(req);
                log.LogInformation($"RequestCommunicationRequest {request}");

                RequestCommunicationResponse response = await _mediator.Send(req);

                return(new OkObjectResult(ResponseWrapper <RequestCommunicationResponse, CommunicationServiceErrorCode> .CreateSuccessfulResponse(response)));
            }
            catch (Exception exc)
            {
                log.LogError("Exception occured in Request Communication", exc);
                return(new ObjectResult(ResponseWrapper <RequestCommunicationResponse, CommunicationServiceErrorCode> .CreateUnsuccessfulResponse(CommunicationServiceErrorCode.InternalServerError, "Internal Error"))
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
            public async Task <ResponseWrapper <SetActive> > Handle(Command request, CancellationToken cancellationToken)
            {
                try
                {
                    var dish = await _context.Get(request.Id);

                    if (dish == null)
                    {
                        throw new RestException(HttpStatusCode.NotFound, "No dish found with this Id");
                    }

                    await _context.ChangeActiveState(request.Id, request.Active);

                    var responseWrapper = ResponseWrapper <SetActive> .GetInstance((int)HttpStatusCode.OK, null, true, null);

                    return(responseWrapper);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Problem setting the active status of the dish");
                    throw new Exception("Problem setting the active status of the dish");
                }
            }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
            GetAllJobsByFilterRequest req,
            CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("GetAllJobsByFilter started");
                GetAllJobsByFilterResponse response = await _mediator.Send(req, cancellationToken);

                return(new OkObjectResult(ResponseWrapper <GetAllJobsByFilterResponse, RequestServiceErrorCode> .CreateSuccessfulResponse(response)));
            }
            catch (PostCodeException exc)
            {
                _logger.LogErrorAndNotifyNewRelic($"{req.Postcode} is an invalid postcode", exc);
                return(new ObjectResult(ResponseWrapper <GetAllJobsByFilterResponse, RequestServiceErrorCode> .CreateUnsuccessfulResponse(RequestServiceErrorCode.ValidationError, "Invalid Postcode"))
                {
                    StatusCode = StatusCodes.Status400BadRequest
                });
            }
            catch (InvalidFilterException exc)
            {
                _logger.LogErrorAndNotifyNewRelic($"invalid filter", exc);
                return(new ObjectResult(ResponseWrapper <GetAllJobsByFilterResponse, RequestServiceErrorCode> .CreateUnsuccessfulResponse(RequestServiceErrorCode.ValidationError, "Invalid filter combination"))
                {
                    StatusCode = StatusCodes.Status400BadRequest
                });
            }
            catch (Exception exc)
            {
                _logger.LogErrorAndNotifyNewRelic("Exception occured in GetAllJobsByFilter", exc);
                return(new ObjectResult(ResponseWrapper <GetAllJobsByFilterResponse, RequestServiceErrorCode> .CreateUnsuccessfulResponse(RequestServiceErrorCode.InternalServerError, "Internal Error"))
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
        public async Task <IActionResult> GetVisitsTicketTariffAsync(string visitTariffId, string ticketTariffId)
        {
            if (string.IsNullOrEmpty(visitTariffId) || string.IsNullOrEmpty(ticketTariffId))
            {
                return(OnInvalidParameterError($"Parameters '{nameof(visitTariffId)}' and '{nameof(ticketTariffId)}' cannot be null or empty."));
            }

            VisitTariff visitTariff = null;

            try
            {
                visitTariff = await _visitTariffDbService.GetAsync(visitTariffId);

                var ticketTariff    = visitTariff.TicketTariffs.Single(x => x.Id.Equals(ticketTariffId));
                var ticketTariffDto = MapToDto(ticketTariff);
                var response        = new ResponseWrapper(ticketTariffDto);
                return(Ok(response));
            }
            catch (InvalidOperationException ex) when(visitTariff is null)
            {
                return(OnNotFoundError($"Cannot found '{typeof(VisitTariff).Name}' with specified id: '{visitTariffId}'.", ex));
            }
            catch (InvalidOperationException ex)
            {
                return(OnNotFoundError($"Cannot found '{typeof(TicketTariff).Name}' with specified id: '{ticketTariffId}'.", ex));
            }
            catch (InternalDbServiceException ex)
            {
                LogInternalDbServiceException(ex);
                throw;
            }
            catch (Exception ex)
            {
                LogUnexpectedException(ex);
                throw;
            }
        }
Example #22
0
        public async Task <IActionResult> GetCustomerTicketsAsync(string customerId)
        {
            _logger.LogInformation($"Starting method '{nameof(GetCustomerTicketsAsync)}'.");

            if (string.IsNullOrEmpty(customerId))
            {
                return(OnInvalidParameterError($"Parameter '{customerId}' cannot be null or empty."));
            }

            try
            {
                var allCustomerTickets = await _ticketDbService.GetByAsync(x => x.Customer.Id.Equals(customerId));

                if (allCustomerTickets.Count() == 0)
                {
                    // The customer must have at least one ticket because it is created if it has ordered at least one ticket.
                    // If none ticket found then customer with passed id doesn't exist.
                    return(OnNotFoundError($"Element '{nameof(Customer)}' with specified id: '{customerId}' not found."));
                }

                _logger.LogDebug("Data retrieved succeeded");
                var allCustomerTicketsDto = MapToDtoEnumerable(allCustomerTickets);
                var response = new ResponseWrapper(allCustomerTicketsDto);
                _logger.LogInformation($"Finished method '{nameof(GetCustomerTicketsAsync)}'.");
                return(Ok(response));
            }
            catch (InternalDbServiceException ex)
            {
                LogInternalDbServiceException(ex, _ticketDbService.GetType());
                throw;
            }
            catch (Exception ex)
            {
                LogUnexpectedException(ex);
                throw;
            }
        }
Example #23
0
        public User GetUserByLoginAndPassword(string login, string pass)
        {
            User user = new User()
            {
                Login    = login,
                Password = pass
            };

            RequestWrapper request = new RequestWrapper()
            {
                Command = RequestWrapper.CommandEnum.UsersAuthByLoginAndPassword, Parameters = JsonConvert.SerializeObject(user)
            };

            apiCore.SendRequestToServer(request);

            ResponseWrapper response = apiCore.GetResponseFromServer();

            switch (response.Status)
            {
            case ResponseWrapper.StatusEnum.Ok:
                return(JsonConvert.DeserializeObject <User>(response.Message));

                break;

            case ResponseWrapper.StatusEnum.LogicError:
                return(null);

                break;

            case ResponseWrapper.StatusEnum.SystemError:
                throw new Exception(response.Message);
                break;
            }

            return(null);
        }
        public async Task <string> GetWorkspaceUser()
        {
            if (octaneUserValue != null && !octaneUserValue.Equals(""))
            {
                return(octaneUserValue);
            }

            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(host + "/api/current_user/");

                httpWebRequest.Method      = RestConnector.METHOD_GET;
                httpWebRequest.ContentType = RestConnector.CONTENT_TYPE_JSON;

                PrepareRequest(httpWebRequest);

                httpWebRequest.Headers.Add("HPECLIENTTYPE", "HPE_CI_CLIENT");

                ResponseWrapper responseWrapper = new ResponseWrapper();

                using (var httpResponse = await httpWebRequest.GetResponseAsync().ConfigureAwait(RestConnector.AwaitContinueOnCapturedContext))
                {
                    using (var reader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        responseWrapper.Data = reader.ReadToEnd();
                    }
                }
                WorkspaceUser result = jSerialiser.Deserialize <WorkspaceUser>(responseWrapper.Data);
                octaneUserValue = result.Name;
                return(result.Name);
            }
            catch (Exception)
            {
                return(null);
            }
        }
        public async Task <ResponseWrapper> MakePostAPICall(PostObject postData)
        {
            ResponseWrapper responseWrapper = new ResponseWrapper();

            responseWrapper.Code = -1;

            try
            {
                SetHeader(postData.HeadersList);
                var builder = new UriBuilder(postData.RequestUrl);
                builder.Port = -1;
                string url      = builder.ToString();
                var    response = await _client.PostAsync(url, GetPostJson(postData.JsonData));

                responseWrapper.Code = 1;
                responseWrapper.Data = response.Content.ReadAsStringAsync().Result;
            }
            catch (Exception ex)
            {
                responseWrapper.Data = ex.Message;
            }

            return(responseWrapper);
        }
Example #26
0
        public async Task <IActionResult> GetGroupAsync(string id)
        {
            _logger.LogInformation($"Starting method '{nameof(GetGroupAsync)}'.");

            if (string.IsNullOrEmpty(id))
            {
                return(OnInvalidParameterError($"Parameter '{nameof(id)}' cannot be null or empty."));
            }

            ISightseeingGroupDbService groupDbService = null;

            try
            {
                groupDbService = _dbServiceFactory[nameof(ISightseeingGroupDbService)] as ISightseeingGroupDbService;
                var group = await groupDbService.GetAsync(id);

                var groupDto = MapToDto(group);
                var response = new ResponseWrapper(groupDto);
                _logger.LogInformation($"Finished method '{nameof(GetGroupAsync)}'.");
                return(Ok(response));
            }
            catch (InvalidOperationException ex)
            {
                return(OnNotFoundError($"Cannot found element '{typeof(SightseeingGroup).Name}' with specified id: '{id}'.", ex));
            }
            catch (InternalDbServiceException ex)
            {
                LogInternalDbServiceException(ex, groupDbService.GetType());
                throw;
            }
            catch (Exception ex)
            {
                LogUnexpectedException(ex);
                throw;
            }
        }
Example #27
0
 public HttpResponseMessage IsSubmitProjectFinish(string ProjectId)
 {
     try
     {
         var projectDTO = Mapper.Map <GetProjectDTO>(_repository.GetProjectDetailList(ProjectId));
         if (projectDTO.Docs.Count(d => d.Type == ProjectDocType.FINISH_REPORT) == 0)
         {
             projectDTO.IsSubmit = false;
         }
         else if (projectDTO.AnnualTasks.Count(a => a.Status == AnnualTaskStatus.FINISH) != projectDTO.Period)
         {
             projectDTO.IsSubmit = false;
         }
         else
         {
             projectDTO.IsSubmit = true;
         }
         return(ResponseWrapper.SuccessResponse(projectDTO));
     }
     catch (Exception e)
     {
         return(ResponseWrapper.ExceptionResponse(e));
     }
 }
Example #28
0
        public HttpResponseMessage GetProjectAnnualTaskList(string projectId)
        {
            try
            {
                GetProjectAnnualTaskDTO projectTaskDTO = new GetProjectAnnualTaskDTO();
                var projectTasks = _repository
                                   .GetAnnualTaskList()
                                   .Where(at => at.ProjectId == projectId)
                                   .Select(Mapper.Map <GetAnnualTaskVO>);

                projectTaskDTO.Previous = projectTasks.ToList();
                var current = projectTaskDTO.Previous.FirstOrDefault();
                if (current != null && current.Status < AnnualTaskStatus.FINISH)
                {
                    projectTaskDTO.Previous.Remove(current);
                    projectTaskDTO.Current = current;
                }
                return(ResponseWrapper.SuccessResponse(projectTaskDTO));
            }
            catch (Exception e)
            {
                return(ResponseWrapper.ExceptionResponse(e));
            }
        }
Example #29
0
        public async Task <ResponseWrapper <Activity> > LikeActivity(ApplicationUser user, int activityId)
        {
            var response = new ResponseWrapper <Activity>
            {
                Success = true,
                Status  = "",
            };

            var activity = await _UserRepo.GetActivityById(activityId);

            if (activity == null)
            {
                response.Success = false;
                response.Status  = "Activity does not exist with id.";
                return(response);
            }

            var activityLike = new ActivityLike()
            {
                Activity = activity,
                User     = user
            };

            var updatedActivity = await _UserRepo.LikeActivity(activity, activityLike);

            if (updatedActivity == null)
            {
                response.Success = false;
                response.Status  = "Like activity action failed.";
                return(response);
            }

            response.Data = updatedActivity;

            return(response);
        }
Example #30
0
            public async Task <ResponseWrapper <Delete> > Handle(Command request, CancellationToken cancellationToken)
            {
                try
                {
                    var category = await _context.Get(request.Id);

                    if (category == null)
                    {
                        throw new RestException(HttpStatusCode.NotFound, "No category found with this Id");
                    }

                    await _context.Delete(request.Id);

                    _logger.LogInformation("Successfully deleted the category");
                    var responseWrapper = ResponseWrapper <Delete> .GetInstance((int)HttpStatusCode.OK, null, true, null);

                    return(responseWrapper);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Problem deleting the category");
                    throw new Exception("Problem deleting the category");
                }
            }
Example #31
0
 public HttpResponseMessage PostPartners(int id)
 {
     try
     {
         //检查专家研究领域完整性
         //if (PersonRepository.ExpertFieldComplete(id))
         //{
         //    PersonRepository.GrantRole(id, 5, p => true);
         //    return ResponseWrapper.SuccessResponse();
         //}
         //else
         //{
         //    return ResponseWrapper.ExceptionResponse(new OtherException("请完善研究领域信息"));
         //}
         //完善校外专家信息
         PersonRepository.ExpertFieldCompletePartners(id);
         PersonRepository.GrantRole(id, 5, p => true);
         return(ResponseWrapper.SuccessResponse());
     }
     catch (Exception e)
     {
         return(ResponseWrapper.ExceptionResponse(e));
     }
 }
Example #32
0
        public async Task <IActionResult> GetAllCustomersAsync()
        {
            _logger.LogInformation($"Starting method '{nameof(GetAllCustomersAsync)}'.");

            try
            {
                var customers = await _customerDbService.GetAllAsync();

                var customersDto = MapToDtoEnumerable(customers);
                var response     = new ResponseWrapper(customersDto);
                _logger.LogInformation($"Finished method '{nameof(GetAllCustomersAsync)}'.");
                return(Ok(response));
            }
            catch (InternalDbServiceException ex)
            {
                LogInternalDbServiceException(ex, _customerDbService.GetType());
                throw;
            }
            catch (Exception ex)
            {
                LogUnexpectedException(ex);
                throw;
            }
        }
Example #33
0
        public void CheckQRCodeStatus(object source, System.Timers.ElapsedEventArgs e)
        {
            // If the timer is paused, skip other request
            if (this.LoginStatusTimer.Enabled == false || String.IsNullOrEmpty(ClientID))
            {
                return;
            }

            String strSvcURI = "http://localhost:4788/" + "login/qrcode/status/" + ClientID;

            HttpClient client = new HttpClient();

            HttpResponseMessage responseMsg = client.Get(strSvcURI);

            responseMsg.EnsureStatusIsSuccessful();

            String strJson = responseMsg.Content.ReadAsString();

            ResponseWrapper <LoginEntity> loginStatusResult = JsonConvert.DeserializeObject <ResponseWrapper <LoginEntity> >(strJson);

            if (loginStatusResult.ReturnCode == 1)
            {
                // Pause the timer
                this.LoginStatusTimer.Enabled = false;
                MessageBox.Show("Login Successfully.");
            }
            else
            {
                if (loginStatusResult.Result != null && loginStatusResult.Result.StatusCode == "65")
                {
                    // Pause the timer
                    this.LoginStatusTimer.Enabled = false;
                    MessageBox.Show(loginStatusResult.Result.StatusText);
                }
            }
        }
Example #34
0
        public HttpResponseMessage GetManualAssignmentList(int instId, int page)
        {
            try
            {
                var userInfo = UserHelper.GetCurrentUser();

                Func <Application, bool> predicate = a => a.CurrentYear == SystemConfig.ApplicationStartYear &&
                                                     a.Status == ApplicationStatus.MANUAL_ASSIGNMENT &&
                                                     userInfo.ProjectTypeIds.Contains(a.ProjectTypeId) &&
                                                     ((instId == 0) || a.InstituteId == instId);

                string fieldId    = Request.GetQueryNameValuePairs().FirstOrDefault(p => p.Key == "fieldId").Value;
                string subFieldId = Request.GetQueryNameValuePairs().FirstOrDefault(p => p.Key == "subFieldId").Value;

                fieldId    = fieldId == null ? "all" : fieldId;
                subFieldId = subFieldId == null ? "all" : subFieldId;

                return(ResponseWrapper.SuccessResponse(repository.GetPagingReviewAssignmentList(fieldId, subFieldId, predicate, page)));
            }
            catch (Exception e)
            {
                return(ResponseWrapper.ExceptionResponse(e));
            }
        }
Example #35
0
        public HttpResponseMessage PostAssignments(int id, List <ApplicationAssignmentDTO> AssignmentList)
        {
            //var request = HttpContext.Current.Request;
            //var id = request.Params["id"];
            //if (null == id || string.IsNullOrEmpty(id))
            //{
            //    return Response.CreateParameterErrorResponse("id不能为空!");
            //}
            try
            {
                var result = repository.UpdateUserApplicationAssignment(id, AssignmentList);

                //系统管理员更改某院管理员的分管类型
                //通知打点:发给用户
                //_noticeService.AddNotice(
                //    _noticeService.GetUserIdByPersonId(id), 110);

                return(ResponseWrapper.SuccessResponse(result));
            }
            catch (Exception e)
            {
                return(ResponseWrapper.ExceptionResponse(e));
            }
        }
Example #36
0
        public ResponseWrapper Send(string restRelativeUri, RequestType requestType, string data)
        {
            if (!IsConnected())
            {
                throw new NotConnectedException();
            }

            HttpWebRequest request = CreateRequest(restRelativeUri, requestType);
            ResponseWrapper responseWrapper = new ResponseWrapper();

            try
            {
                if ((requestType == RequestType.Post || requestType == RequestType.Update) && !String.IsNullOrEmpty(data))
                {
                    byte[] byteData = Encoding.UTF8.GetBytes(data);
                    request.ContentLength = byteData.Length;
                    using (Stream postStream = request.GetRequestStream())
                    {
                        postStream.Write(byteData, 0, byteData.Length);
                    }
                }

                var response = (HttpWebResponse)request.GetResponse();
                using (var streamReader = new StreamReader(response.GetResponseStream()))
                {
                    responseWrapper.Data = streamReader.ReadToEnd();
                }

                responseWrapper.StatusCode = response.StatusCode;
                UpdateLwssoTokenFromResponse(response);

            }
            catch (WebException ex)
            {
                var response = (HttpWebResponse)ex.Response;
                if (response == null)
                {
                    throw new ServerUnavailableException();
                }
                else
                {
                    String body = null;
                    using (var streamReader = new StreamReader(response.GetResponseStream()))
                    {
                        body = streamReader.ReadToEnd();
                    }
                    JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
                    RestExceptionInfo exceptionInfo = jsSerializer.Deserialize<RestExceptionInfo>(body);
                    throw new MqmRestException(exceptionInfo, response.StatusCode);
                }

            }

            return responseWrapper;
        }