Exemplo n.º 1
0
        /// <summary>
        /// Delete an EventAttendee from the database
        /// </summary>
        /// <param name="id">EventAttendee id the object to be deleted from the database</param>
        /// <returns>success or failure</returns>
        public override ServiceResultEnum Delete(Guid id)
        {
            // Number of changes as a result of the database change
            NumberChanges = 0;
            try
            {
                // Perform data access using the context
                using (var context = new HuskyRescueEntities())
                {
                    // convert to database object
                    var dbObj = context.Event_Attendee.Find(id);

                    if (dbObj != null)
                    {
                        // remove associated person first
                        if (dbObj.PersonID != null)
                        {
                            var personHandler = new PersonHandler();
                            personHandler.Delete(dbObj.PersonID.Value);
                        }

                        context.Event_Attendee.Remove(dbObj);

                        // commit changes to the database
                        NumberChanges = context.SaveChanges();
                    }
                }
            }
            catch (InvalidOperationException ex)
            {
                Trace.WriteLine(ex.Message);
                Messages.Add("Error deleting person - " + ex.Message);
            }
            catch (ValidationException ex)
            {
                Trace.WriteLine(ex.Message);
                Messages.Add("Error deleting person - " + ex.Message);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
                Messages.Add("Error deleting person - " + ex.Message);
            }

            return(NumberChanges > 0 ? ServiceResultEnum.Success : ServiceResultEnum.Failure);
        }
Exemplo n.º 2
0
        public ServiceResultEnum Create(ref Donation obj)
        {
            // Number of changes as a result of the database change
            NumberChanges = 0;

            // only perform if payment section was shown to the user
            if (obj.ShowPaymentSection)
            {
                // send information to payment service
                var paymentResult = ServiceResultEnum.Failure;
                var payment       = obj.GetPaymentInformation();
                try
                {
                    var brainTreeHandler = new BrainTreeHandler();
                    paymentResult = brainTreeHandler.SendTransactionRequest(ref payment);
                    if (paymentResult == ServiceResultEnum.Success)
                    {
                        ServiceResult = paymentResult;
                        obj.DonationInformation.PaymentTransactionId = payment.TransactionResult.Target.Id;
                        Messages.Add("Payment processed successfully");
                    }
                }
                catch (Exception ex)
                {
                    Messages.Add(ex.Message);
                }

                // check if the payment was not processed
                if (paymentResult == ServiceResultEnum.Failure)
                {
                    Messages.Add(payment.TransactionResult.Message);
                    var errorMessage = payment.ErrorMessage();
                    if (errorMessage.IsNotNullOrEmpty())
                    {
                        Messages.Add(errorMessage);
                    }
                    ServiceResult = paymentResult;
                    return(ServiceResult);
                }
            }

            // payment is a success, save information to the database
            try
            {
                // Perform data access using the context
                using (var context = new HuskyRescueEntities())
                {
                    var personHandler = new PersonHandler();
                    var person        = obj.DonationInformation.Person;
                    if (personHandler.Create(ref person) == ServiceResultEnum.Success)
                    {
                        obj.DonationInformation.BaseId = person.BaseID;

                        // convert to database object
                        var dbObj = obj.DonationInformation.ToModel();

                        // add to the database and retrieve the updated object back (namely the GUID generated into the Id)
                        dbObj = context.Entity_Donation.Add(dbObj);

                        // commit changes to the database
                        NumberChanges = context.SaveChanges();

                        // convert the database object back to a presentation object with included changes from the database (if any)
                        obj.DonationInformation.Id = dbObj.Id;
                    }
                }
            }
            catch (InvalidOperationException ex)
            {
                Trace.WriteLine(ex.Message);
                Messages.Add(ex.Message);
            }
            catch (DbEntityValidationException ex)
            {
                Messages.AddRange(Common.FormatEntityValidationError(ex));
            }

            // check if database changes were a success
            ServiceResult = NumberChanges > 0 ? ServiceResultEnum.Success : ServiceResultEnum.Failure;
            if (ServiceResult == ServiceResultEnum.Success)
            {
                Messages.Add("Donation saved to database successfully");
            }
            // if the save to database didn't work then keep going as the payment already processed.
            // TODO: log registration information to database for manual entry

            // send emails
            var emailSendResult = ServiceResultEnum.Failure;

            try
            {
                const string signature = @" 
Texas Husky Rescue
1-877-TX-HUSKY (894-8759) (phone/fax)
PO Box 118891, Carrollton, TX 75011";

                var emailBodyToDonor = new StringBuilder();
                emailBodyToDonor.AppendFormat("Thank you, {0}, for your donation of {1} to Texas Husky Rescue.",
                                              obj.DonationInformation.Person.FullName, obj.DonationInformation.Amount.ToString("C"));
                emailBodyToDonor.AppendLine().Append(signature);

                var emailBodyToGroup = new StringBuilder();
                emailBodyToGroup.AppendFormat("Donation received from {0} for {1}", obj.DonationInformation.Person.FullName, obj.DonationInformation.Amount.ToString("C"));
                if (obj.DonationInformation.DonorComments.IsNotNullOrEmpty())
                {
                    emailBodyToGroup.AppendLine().Append("Notes from donor: ").AppendLine().Append(obj.DonationInformation.DonorComments);
                }

                var message = new EmailMessage
                {
                    BodyTextExternal     = emailBodyToDonor.ToString(),
                    BodyTextInternal     = emailBodyToGroup.ToString(),
                    Subject              = "Texas Husky Rescue Donation",
                    EmailAddressExternal = obj.DonationInformation.Person.Base.EmailAddresses[0].Address,
                    EmailAddressInternal = Settings.Default.ContactEmail,
                    NameInternal         = "Texas Husky Rescue",
                    NameExternal         = string.Empty
                };

                var emailMessageHandler = new EmailMessageHandler();
                emailSendResult = emailMessageHandler.SendMessage(ref message);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }

            if (emailSendResult == ServiceResultEnum.Success)
            {
                Messages.Add("Email confirmation sent");
            }

            return(ServiceResultEnum.Success);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Add new Applicant to the database
        /// </summary>
        /// <param name="obj">Applicant object to be saved to the database</param>
        /// <returns>success or failure</returns>
        public override ServiceResultEnum Create(ref Applicant obj)
        {
            // Number of changes as a result of the database change
            NumberChanges = 0;
            try
            {
                // Perform data access using the context
                using (var context = new HuskyRescueEntities())
                {
                    #region Save Application to Database
                    try
                    {
                        // Create ViewModel of adopter
                        var appPersonVm = new ViewModel.Entity.Person
                        {
                            Base =
                            {
                                EmailAddresses = new List <ViewModel.Entity.EmailAddress>(),
                                PhoneNumbers   = new List <ViewModel.Entity.PhoneNumber>()
                            }
                        };
                        if (!string.IsNullOrEmpty(obj.AppEmail))
                        {
                            appPersonVm.Base.EmailAddresses.Add(new ViewModel.Entity.EmailAddress
                            {
                                Address = obj.AppEmail,
                                Type    = "0"
                            });
                        }
                        if (!string.IsNullOrEmpty(obj.AppCellPhone))
                        {
                            appPersonVm.Base.PhoneNumbers.Add(
                                new ViewModel.Entity.PhoneNumber
                            {
                                Number = obj.AppCellPhone,
                                Type   = "3"
                            }
                                );
                        }
                        if (!string.IsNullOrEmpty(obj.AppHomePhone))
                        {
                            appPersonVm.Base.PhoneNumbers.Add(
                                new ViewModel.Entity.PhoneNumber
                            {
                                Number = obj.AppHomePhone,
                                Type   = "1"
                            }
                                );
                        }

                        appPersonVm.FirstName = obj.AppNameFirst;
                        appPersonVm.LastName  = obj.AppNameLast;
                        if (obj.DateSubmitted == null)
                        {
                            obj.DateSubmitted = DateTime.Now;
                        }
                        appPersonVm.Base.Comments = "applied for: " + obj.FilterAppDogsInterestedIn + " on " + obj.DateSubmitted.Value.ToShortDateString() + ". ";

                        // Save primary adopter to database
                        var personHandler = new PersonHandler();
                        personHandler.Create(ref appPersonVm);

                        // Associate the application with the adopter in the database
                        obj.PersonID = appPersonVm.ID;

                        // Remove "owned animals" that are blank (no name)
                        obj.ApplicantOwnedAnimal.RemoveAll(pet => pet.Name.IsNullOrEmpty());

                        // Associate the adopter's "owned animals" in the database to the adopter
                        foreach (var animalVm in obj.ApplicantOwnedAnimal)
                        {
                            animalVm.PersonID = obj.PersonID;
                            if (string.IsNullOrEmpty(animalVm.Breed))
                            {
                                animalVm.Breed = "n/a";
                            }
                        }

                        // convert to database object
                        var dbObj = obj.ToModel();

                        // StateId is only 2 char in database and will error if there is whitespace after that.
                        dbObj.AppAddressStateId = dbObj.AppAddressStateId.Trim();

                        // add to the database and retrieve the updated object back (namely the GUID generated into the Id)
                        dbObj = context.Applicants.Add(dbObj);

                        // commit changes to the database
                        NumberChanges = context.SaveChanges();

                        // convert the database object back to a presentation object with included changes from the database (if any)
                        obj = dbObj.ToViewModel();
                    }
                    catch (DbEntityValidationException dex)
                    {
                        _logger.Error("ApplicantError", dex);
                        var validationErrors = "";
                        foreach (var failure in dex.EntityValidationErrors)
                        {
                            validationErrors  = failure.ValidationErrors.Aggregate(validationErrors, (current, error) => current + (error.PropertyName + "  " + error.ErrorMessage));
                            validationErrors += Environment.NewLine + Environment.NewLine;
                        }
                        if (validationErrors != "")
                        {
                            _logger.Error("ApplicantError - Data Validation Errors " + Environment.NewLine + validationErrors, dex);
                        }
                        if (dex.InnerException != null)
                        {
                            _logger.Error("ApplicantError - Data Validation Inner", dex.InnerException);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("ApplicantError", ex);
                        if (ex.InnerException != null)
                        {
                            _logger.Error("ApplicantError Inner", ex.InnerException);
                        }
                    }
                    finally
                    {
                        _logger.Information("Application App Submitted" + Environment.NewLine + obj);
                    }
                    #endregion

                    #region generate application pdf
                    var newPdfPath = string.Empty;
                    try
                    {
                        // Generate the pdf of the application and email it
                        var genPdf = new GenerateAppPdf(_logger);
                        newPdfPath = genPdf.CreatePdf(obj, obj.ApplicantType);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(obj.ApplicantType + " App PDF Gen Ex", ex);
                        if (ex.InnerException != null)
                        {
                            _logger.Error(obj.ApplicantType + " App PDF Gen Inner Ex", ex.InnerException);
                        }
                    }
                    #endregion

                    #region Email Application

                    var appTypeDesc = (obj.ApplicantType.Equals("A")) ? "Adoption" : "Foster";

                    var          subject     = "Online " + appTypeDesc + " Application for " + obj.AppNameFirst + " " + obj.AppNameLast;
                    const string bodyAppHtml = @" Thank you for your application.
								See attachment for a copy of your application sent to Texas Husky Rescue, Inc.
								You can respond back to this email if you have any further questions or comments for us.
								We will get back to you within the next 5 days regarding your application."                                ;
                    var          bodyGroup   = @" Dogs interested in: " + obj.FilterAppDogsInterestedIn;

                    var message = new EmailMessage
                    {
                        BodyTextExternal     = bodyAppHtml,
                        BodyTextInternal     = bodyGroup,
                        Subject              = subject,
                        EmailAddressExternal = (string.IsNullOrEmpty(obj.AppEmail)) ? string.Empty : obj.AppEmail,
                        EmailAddressInternal = Settings.Default.ContactEmail,
                        NameInternal         = "Texas Husky Rescue",
                        NameExternal         = string.Empty
                    };

                    var newPdfFile = new FileInfo(newPdfPath);
                    if (newPdfFile.Exists)
                    {
                        var attachment  = new Attachment(newPdfFile.FullName, MediaTypeNames.Application.Octet);
                        var disposition = attachment.ContentDisposition;
                        disposition.CreationDate     = newPdfFile.CreationTime;
                        disposition.ModificationDate = newPdfFile.CreationTime;
                        disposition.ReadDate         = newPdfFile.CreationTime;
                        disposition.FileName         = newPdfFile.Name;
                        disposition.Size             = newPdfFile.Length;
                        disposition.DispositionType  = DispositionTypeNames.Attachment;
                        message.Attachments.Add(attachment);
                    }
                    message.SendMessage();
                    #endregion
                }
            }
            catch (InvalidOperationException ex)
            {
                Trace.WriteLine(ex.Message);
            }
            catch (ValidationException ex)
            {
                Trace.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }

            return(NumberChanges > 0 ? ServiceResultEnum.Success : ServiceResultEnum.Failure);
        }