Ejemplo n.º 1
0
        public IHttpActionResult GetRecurringGifts([FromUri(Name = "impersonateDonorId")] int?impersonateDonorId = null)
        {
            return(Authorized(token =>
            {
                var impersonateUserId = impersonateDonorId == null ? string.Empty : _mpDonorService.GetEmailViaDonorId(impersonateDonorId.Value).Email;

                try
                {
                    var recurringGifts = (impersonateDonorId != null)
                        ? _impersonationService.WithImpersonation(token,
                                                                  impersonateUserId,
                                                                  () =>
                                                                  _donorService.GetRecurringGiftsForAuthenticatedUser(token))
                        : _donorService.GetRecurringGiftsForAuthenticatedUser(token);

                    if (recurringGifts == null || !recurringGifts.Any())
                    {
                        return (RestHttpActionResult <ApiErrorDto> .WithStatus(HttpStatusCode.NotFound, new ApiErrorDto("No matching donations found")));
                    }

                    return (Ok(recurringGifts));
                }
                catch (UserImpersonationException e)
                {
                    return (e.GetRestHttpActionResult());
                }
            }));
        }
Ejemplo n.º 2
0
        public void TestClientError()
        {
            var result = RestHttpActionResult <JsonModel> .ClientError(_jsonModel);

            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);
            Assert.AreSame(_jsonModel, result.Content);
        }
Ejemplo n.º 3
0
        public IHttpActionResult SearchGroups([FromUri] int[] groupTypeIds,
                                              [FromUri(Name = "s")] string keywords   = null,
                                              [FromUri(Name = "loc")] string location = null,
                                              [FromUri(Name = "id")] int?groupId      = null)
        {
            try
            {
                var result = _groupToolService.SearchGroups(groupTypeIds, keywords, location, groupId);
                if (result == null || !result.Any())
                {
                    return(RestHttpActionResult <List <GroupDTO> > .WithStatus(HttpStatusCode.NotFound, new List <GroupDTO>()));
                }
                // Analytics call
                var props = new EventProperties();
                props.Add("Keywords", keywords);
                props.Add("Location", location);
                _analyticsService.Track("Anonymous", "SearchedForGroup", props);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                var apiError = new ApiErrorDto("Error searching for group", ex);
                throw new HttpResponseException(apiError.HttpResponseMessage);
            }
        }
Ejemplo n.º 4
0
        public void TestWithStatus()
        {
            var result = RestHttpActionResult <JsonModel> .WithStatus(HttpStatusCode.Conflict, _jsonModel);

            Assert.AreEqual(HttpStatusCode.Conflict, result.StatusCode);
            Assert.AreSame(_jsonModel, result.Content);
        }
Ejemplo n.º 5
0
        public IHttpActionResult GetDonations(string donationYear = null,
                                              int?limit           = null,
                                              [FromUri(Name = "softCredit")] bool?softCredit = null,
                                              [FromUri(Name = "impersonateDonorId")] int?impersonateDonorId = null,
                                              bool?includeRecurring = true)
        {
            return(Authorized(token =>
            {
                var impersonateUserId = impersonateDonorId == null ? string.Empty : _mpDonorService.GetEmailViaDonorId(impersonateDonorId.Value).Email;
                try
                {
                    var donations = (impersonateDonorId != null)
                        ? _impersonationService.WithImpersonation(token,
                                                                  impersonateUserId,
                                                                  () =>
                                                                  _gatewayDonationService.GetDonationsForAuthenticatedUser(token, donationYear, limit, softCredit, includeRecurring))
                        : _gatewayDonationService.GetDonationsForAuthenticatedUser(token, donationYear, limit, softCredit, includeRecurring);
                    if (donations == null || !donations.HasDonations)
                    {
                        return (RestHttpActionResult <ApiErrorDto> .WithStatus(HttpStatusCode.NotFound, new ApiErrorDto("No matching donations found")));
                    }

                    return (Ok(donations));
                }
                catch (UserImpersonationException e)
                {
                    return (e.GetRestHttpActionResult());
                }
            }));
        }
Ejemplo n.º 6
0
        public void TestServerError()
        {
            var result = RestHttpActionResult <JsonModel> .ServerError(_jsonModel);

            Assert.AreEqual(HttpStatusCode.InternalServerError, result.StatusCode);
            Assert.AreSame(_jsonModel, result.Content);
        }
Ejemplo n.º 7
0
        public IHttpActionResult GetDonationYears([FromUri(Name = "impersonateDonorId")] int?impersonateDonorId = null)
        {
            return(Authorized(token =>
            {
                var impersonateUserId = impersonateDonorId == null ? string.Empty : _mpDonorService.GetEmailViaDonorId(impersonateDonorId.Value).Email;
                try
                {
                    var donationYears = (impersonateDonorId != null)
                        ? _impersonationService.WithImpersonation(token, impersonateUserId, () => _gatewayDonationService.GetDonationYearsForAuthenticatedUser(token))
                        : _gatewayDonationService.GetDonationYearsForAuthenticatedUser(token);

                    if (donationYears == null || !donationYears.HasYears)
                    {
                        return (RestHttpActionResult <ApiErrorDto> .WithStatus(HttpStatusCode.NotFound, new ApiErrorDto("No donation years found")));
                    }

                    return (Ok(donationYears));
                }
                catch (UserImpersonationException e)
                {
                    return (e.GetRestHttpActionResult());
                }
                catch (Exception e)
                {
                    var msg = "DonationController: GetDonationYears " + impersonateDonorId;
                    _logger.Error(msg, e);
                    return (RestHttpActionResult <ApiErrorDto> .WithStatus(HttpStatusCode.InternalServerError, new ApiErrorDto("Unexpected exception happens at server side")));
                }
            }));
        }
Ejemplo n.º 8
0
        public void TestOk()
        {
            var result = RestHttpActionResult <JsonModel> .Ok(_jsonModel);

            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.AreSame(_jsonModel, result.Content);
        }
Ejemplo n.º 9
0
        public IHttpActionResult GetProfileImage(Int32 contactId)
        {
            var token = _apiUserService.GetToken();
            var files = _mpService.GetFileDescriptions("Contacts", contactId, token);
            var file  = files.FirstOrDefault(f => f.IsDefaultImage);

            return(file != null?
                   GetImage(file.FileId, file.FileName, token) :
                       (RestHttpActionResult <ApiErrorDto> .WithStatus(HttpStatusCode.NotFound, new ApiErrorDto("No matching image found"))));
        }
Ejemplo n.º 10
0
        public IHttpActionResult GetCampaignImage(Int32 recordId)
        {
            var token = _apiUserService.GetToken();
            var files = _mpService.GetFileDescriptions("Pledge_Campaigns", recordId, token);
            var file  = files.FirstOrDefault(f => f.IsDefaultImage);

            return(file != null?
                   GetImage(file.FileId, file.FileName, token) :
                       (RestHttpActionResult <ApiErrorDto> .WithStatus(HttpStatusCode.NotFound, new ApiErrorDto("No campaign image found"))));
        }
Ejemplo n.º 11
0
        private IHttpActionResult GetImage(Int32 fileId, String fileName, String token)
        {
            var imageStream = _mpService.GetFile(fileId, token);

            if (imageStream == null)
            {
                return(RestHttpActionResult <ApiErrorDto> .WithStatus(HttpStatusCode.NotFound, new ApiErrorDto("No matching image found")));
            }

            HttpContext.Current.Response.Buffer = true;
            return(new FileResult(imageStream, fileName, null, false));
        }
 private RestHttpActionResult <ApiErrorDto> CheckToken(string token)
 {
     try
     {
         _authenticationService.GetContactId(token);
         return(null);
     }
     catch (Exception e)
     {
         return(RestHttpActionResult <ApiErrorDto> .WithStatus(HttpStatusCode.Unauthorized, new ApiErrorDto("Could not authenticate to MinistryPlatform", e)));
     }
 }
        public IHttpActionResult ProcessStripeEvent([FromBody] StripeEvent stripeEvent)
        {
            if (stripeEvent == null || !ModelState.IsValid)
            {
                if (_logger.IsDebugEnabled)
                {
                    _logger.Debug("Received invalid Stripe event " + stripeEvent);
                }
                return(BadRequest(ModelState));
            }

            _logger.Debug("Received Stripe Event " + stripeEvent.Type);
            if (_liveMode != stripeEvent.LiveMode)
            {
                _logger.Debug("Dropping Stripe Event " + stripeEvent.Type + " because LiveMode was " + stripeEvent.LiveMode);
                return(Ok());
            }

            StripeEventResponseDTO response = null;

            try
            {
                if (_asynchronous)
                {
                    _logger.Debug("Enqueueing Stripe event " + stripeEvent.Type + " because AsynchronousProcessingMode was true");
                    var message = _messageFactory.CreateMessage(stripeEvent);
                    _eventQueue.Send(message, MessageQueueTransactionType.None);
                    response = new StripeEventResponseDTO
                    {
                        Message = "Queued event for asynchronous processing"
                    };
                }
                else
                {
                    _logger.Debug("Processing Stripe event " + stripeEvent.Type + " because AsynchronousProcessingMode was false");
                    response = _stripeEventService.ProcessStripeEvent(stripeEvent);
                }
            }
            catch (Exception e)
            {
                var msg = "Unexpected error processing Stripe Event " + stripeEvent.Type;
                _logger.Error(msg, e);
                var responseDto = new StripeEventResponseDTO()
                {
                    Exception = new ApplicationException(msg, e),
                    Message   = msg
                };
                return(RestHttpActionResult <StripeEventResponseDTO> .ServerError(responseDto));
            }

            return(response == null ? Ok() : (IHttpActionResult)RestHttpActionResult <StripeEventResponseDTO> .Ok(response));
        }
Ejemplo n.º 14
0
        public IHttpActionResult Save([FromBody] TripApplicationDto dto)
        {
            if (!ModelState.IsValid)
            {
                var errors    = ModelState.Values.SelectMany(val => val.Errors).Aggregate("", (current, err) => current + err.Exception.Message);
                var dataError = new ApiErrorDto("Save Trip Application Data Invalid", new InvalidOperationException("Invalid Save Data" + errors));
                throw new HttpResponseException(dataError.HttpResponseMessage);
            }

            TripApplicationResponseDto response;

            try
            {
                var participantPledgeInfo = _tripService.CreateTripParticipant(dto.ContactId, dto.PledgeCampaignId);
                var message = _messageFactory.CreateMessage(dto);
                _eventQueue.Send(message, MessageQueueTransactionType.None);
                response = new TripApplicationResponseDto
                {
                    Message       = "Queued event for asynchronous processing",
                    DepositAmount = participantPledgeInfo.Deposit,
                    DonorId       = participantPledgeInfo.DonorId,
                    ProgramId     = participantPledgeInfo.ProgramId,
                    ProgramName   = participantPledgeInfo.ProgramName
                };

                new Task(() => { _tripService.SendTripIsFullMessage(dto.PledgeCampaignId); }).Start();
            }
            catch (TripFullException e)
            {
                var json    = JsonConvert.SerializeObject(e.Message, Formatting.None);
                var message = new HttpResponseMessage(HttpStatusCode.Conflict);
                message.Content = new StringContent(json);
                throw new HttpResponseException(message);
            }
            catch (Exception e)
            {
                const string msg         = "Unexpected error processing Trip Application Save";
                var          responseDto = new TripApplicationResponseDto()
                {
                    Exception = new ApplicationException(msg, e),
                    Message   = msg
                };
                return(RestHttpActionResult <TripApplicationResponseDto> .ServerError(responseDto));
            }
            return((IHttpActionResult)RestHttpActionResult <TripApplicationResponseDto> .Ok(response));
        }
Ejemplo n.º 15
0
        public RestHttpActionResult <PaymentProcessorErrorResponse> GetStripeResult()
        {
            var stripeError = new PaymentProcessorErrorResponse
            {
                Error = new PaymentProcessorError
                {
                    DeclineCode   = DeclineCode,
                    Code          = Code,
                    Message       = DetailMessage,
                    Type          = Type,
                    Param         = Param,
                    GlobalMessage = GlobalMessage
                }
            };

            return(RestHttpActionResult <PaymentProcessorErrorResponse> .WithStatus(StatusCode, stripeError));
        }
        public IHttpActionResult GetPageSelectionRecordIds(int selectionId)
        {
            var response = Authorized(token =>
            {
                var selected = _selectionService.GetSelectionRecordIds(token, selectionId);
                if (selected == null || !selected.Any())
                {
                    return(RestHttpActionResult <SelectedRecords> .WithStatus(HttpStatusCode.NotFound, new SelectedRecords()));
                }
                var selectedRecords = new SelectedRecords
                {
                    RecordIds = selected
                };

                return(Ok(selectedRecords));
            });

            return(response);
        }
 public IHttpActionResult IsParticipantValid(int contactId, int eventId)
 {
     return(Authorized((token) =>
     {
         try
         {
             var participant = _eventParticipantService.GetEventParticipantByContactAndEvent(contactId, eventId);
             if (_eventParticipantService.IsParticipantInvalid(participant))
             {
                 return NotFound();
             }
             return Ok();
         }
         catch (Exception e)
         {
             var apiError = new ApiErrorDto("Error determining if participant is interested", e);
             return (RestHttpActionResult <ApiErrorDto> .WithStatus(HttpStatusCode.InternalServerError, apiError));
         }
     }));
 }
Ejemplo n.º 18
0
        public void TestExecuteAsync()
        {
            var result = RestHttpActionResult <JsonModel> .Ok(_jsonModel);

            var task = result.ExecuteAsync(new CancellationToken());

            task.Wait();
            var response = task.Result;

            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            var content = response.Content;

            Assert.AreEqual(MediaTypeHeaderValue.Parse("application/json"), response.Content.Headers.ContentType);
            Assert.IsInstanceOf <StringContent>(content);
            var stringContentTask = content.ReadAsStringAsync();

            stringContentTask.Wait();
            Assert.AreEqual(JsonConvert.SerializeObject(_jsonModel), stringContentTask.Result);
        }
Ejemplo n.º 19
0
        public IHttpActionResult SearchGroups([FromUri] int[] groupTypeIds,
                                              [FromUri(Name = "s")] string keywords   = null,
                                              [FromUri(Name = "loc")] string location = null,
                                              [FromUri(Name = "id")] int?groupId      = null)
        {
            try
            {
                var result = _groupToolService.SearchGroups(groupTypeIds, keywords, location, groupId);
                if (result == null || !result.Any())
                {
                    return(RestHttpActionResult <List <GroupDTO> > .WithStatus(HttpStatusCode.NotFound, new List <GroupDTO>()));
                }

                return(Ok(result));
            }
            catch (Exception ex)
            {
                var apiError = new ApiErrorDto("Error searching for group", ex);
                throw new HttpResponseException(apiError.HttpResponseMessage);
            }
        }
        public IHttpActionResult CreateDonor([FromBody] CheckScannerCheck checkDetails)
        {
            return(Authorized(token =>
            {
                var authResult = CheckToken(token);
                if (authResult != null)
                {
                    return (authResult);
                }

                try
                {
                    var result = _checkScannerService.CreateDonor(checkDetails);
                    return (Ok(result));
                }
                catch (PaymentProcessorException e)
                {
                    return (RestHttpActionResult <ApiErrorDto> .WithStatus(HttpStatusCode.MethodNotAllowed, new ApiErrorDto("Could not create checking account at payment processor", e)));
                }
            }));
        }
Ejemplo n.º 21
0
        public IHttpActionResult GetPledges()
        {
            return(Authorized(token =>
            {
                try
                {
                    var pledges = _donorService.GetCapitalCampaignPledgesForAuthenticatedUser(token);

                    if (pledges == null || !pledges.Any())
                    {
                        return (RestHttpActionResult <ApiErrorDto> .WithStatus(HttpStatusCode.NotFound, new ApiErrorDto("No matching commitments found")));
                    }

                    return (Ok(pledges));
                }
                catch (UserImpersonationException e)
                {
                    return (e.GetRestHttpActionResult());
                }
            }));
        }
Ejemplo n.º 22
0
 public RestHttpActionResult <ApiErrorDto> GetRestHttpActionResult()
 {
     return(RestHttpActionResult <ApiErrorDto> .WithStatus(_httpStatusCode, new ApiErrorDto(Message)));
 }
Ejemplo n.º 23
0
        public IHttpActionResult ProcessStripeEvent([FromBody] StripeEvent stripeEvent)
        {
            if (stripeEvent == null || !ModelState.IsValid)
            {
                if (_logger.IsDebugEnabled)
                {
                    _logger.Debug("Received invalid Stripe event " + stripeEvent);
                }
                return(BadRequest(ModelState));
            }

            _logger.Debug("Received Stripe Event " + stripeEvent.Type);
            if (_liveMode != stripeEvent.LiveMode)
            {
                _logger.Debug("Dropping Stripe Event " + stripeEvent.Type + " because LiveMode was " + stripeEvent.LiveMode);
                return(Ok());
            }

            StripeEventResponseDTO response;

            try
            {
                if (_asynchronous)
                {
                    _logger.Debug("Enqueueing Stripe event " + stripeEvent.Type + " because AsynchronousProcessingMode was true");
                    var message = _messageFactory.CreateMessage(stripeEvent);
                    _eventQueue.Send(message, MessageQueueTransactionType.None);
                    response = new StripeEventResponseDTO
                    {
                        Message = "Queued event for asynchronous processing"
                    };
                }
                else
                {
                    _logger.Debug("Processing Stripe event " + stripeEvent.Type + " because AsynchronousProcessingMode was false");
                    response = _stripeEventService.ProcessStripeEvent(stripeEvent);
                }
            }
            catch (Exception e)
            {
                var msg = "Unexpected error processing Stripe Event " + stripeEvent.Type;

                if (e is DonationNotFoundException)
                {
                    // Sometimes we receive a webhook callback before the donation has been
                    // added to the database.  This is a known issue, so just do minimal
                    // logging without a full stack trace.
                    _logger.Error($"ProcessStripeEvent: Donation not found processing {stripeEvent.Type}: {e.Message}");
                }
                else
                {
                    _logger.Error(msg, e);
                }

                var responseDto = new StripeEventResponseDTO()
                {
                    Exception = new ApplicationException(msg, e),
                    Message   = msg
                };
                return(RestHttpActionResult <StripeEventResponseDTO> .ServerError(responseDto));
            }

            return(response == null ? Ok() : (IHttpActionResult)RestHttpActionResult <StripeEventResponseDTO> .Ok(response));
        }