/// <summary>
        /// Returns a collection of active <see cref="Rock.Model.PrayerRequest">PrayerRequests</see> that
        /// are in a specified <see cref="Rock.Model.Category"/> or any of its subcategories.
        /// </summary>
        /// <param name="categoryIds">A <see cref="System.Collections.Generic.List{Int32}"/> of
        /// the <see cref="Rock.Model.Category"/> IDs to retrieve PrayerRequests for.</param>
        /// <param name="onlyApproved">set false to include un-approved requests.</param>
        /// <param name="onlyUnexpired">set false to include expired requests.</param>
        /// <returns>An enumerable collection of <see cref="Rock.Model.PrayerRequest"/> that
        /// are in the specified <see cref="Rock.Model.Category"/> or any of its subcategories.</returns>
        public IEnumerable<PrayerRequest> GetByCategoryIds( List<int> categoryIds, bool onlyApproved = true, bool onlyUnexpired = true )
        {
            PrayerRequest prayerRequest = new PrayerRequest();
            Type type = prayerRequest.GetType();

            var prayerRequestEntityTypeId = Rock.Web.Cache.EntityTypeCache.GetId( type );

            // Get all PrayerRequest category Ids that are the **parent or child** of the given categoryIds.
            CategoryService categoryService = new CategoryService( (RockContext)Context );
            IEnumerable<int> expandedCategoryIds = categoryService.GetByEntityTypeId( prayerRequestEntityTypeId )
                .Where( c => categoryIds.Contains( c.Id ) || categoryIds.Contains( c.ParentCategoryId ?? -1 ) )
                .Select( a => a.Id );

            // Now find the active PrayerRequests that have any of those category Ids.
            var list = Queryable( "RequestedByPersonAlias.Person" ).Where( p => p.IsActive == true && expandedCategoryIds.Contains( p.CategoryId ?? -1 ) );

            if ( onlyApproved )
            {
                list = list.Where( p => p.IsApproved == true );
            }

            if ( onlyUnexpired )
            {
                list = list.Where( p => RockDateTime.Today <= p.ExpirationDate );
            }

            return list;
        }
        public JsonResult Index(PrayerRequest prayerRequest)
        {
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(m => m.ErrorMessage);

                return Json(new
                {
                    success = false,
                    text = "Sorry your email was not sent because: " + string.Join(", ", errors)
                });
            }

            try
            {
                // Get email content
                var text = _mailer.ReadTextFromFile(_props.PrayerResponseEmailFilePathText);
                var html = _mailer.ReadTextFromFile(_props.PrayerResponseEmailFilePathHtml);

                // Send prayer request email
                _mailer.SendMail(_props.SmtpClientHost, _props.SmtpClientPort, _props.SmtpUserName, _props.SmtpPassword,
                    fromEmail: prayerRequest.email,
                    toEmail: _props.PrayerRequestEmailAddress,
                    subject: _props.PrayerRequestEmailSubject,
                    text: System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(prayerRequest.prayFor, true));

                // Send prayer response email
                _mailer.SendMail(_props.SmtpClientHost, _props.SmtpClientPort, _props.SmtpUserName, _props.SmtpPassword,
                    fromEmail: _props.PrayerRequestEmailAddress,
                    toEmail: prayerRequest.email,
                    subject: _props.PrayerResponseEmailSubject,
                    text: text,
                    html: html);
            }
            catch (Exception ex)
            {
                Trace.TraceError("{0}\r\n\r\nStack Trace:\r\n\r\n{1}", ex.Message, ex.StackTrace);

                return Json(new
                {
                    success = false,
                    text = "Your prayer request has not been sent - please try mailing: " + _props.PrayerRequestEmailAddress
                });
            }

            return Json(new
            {
                success = true,
                text = "Thanks for sending your prayer request - we will pray."
            });
        }
        /// <summary>
        /// Shows the prayer request's detail.
        /// </summary>
        /// <param name="prayerId">The prayer identifier.</param>
        public void ShowDetail( int prayerId )
        {
            PrayerRequest prayerRequest = null;

            if ( prayerId != 0 )
            {
                prayerRequest = new PrayerRequestService( new RockContext() ).Get( prayerId );
            }

            if ( prayerRequest == null )
            {
                prayerRequest = new PrayerRequest { Id = 0, IsActive = true, IsApproved = true, AllowComments = true };
            }

            hfPrayerRequestId.Value = prayerRequest.Id.ToString();

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !IsUserAuthorized( Authorization.EDIT ) )
            {
                readOnly = true;
                nbEditModeMessage.Title = "Information";
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( PrayerRequest.FriendlyTypeName );
            }

            if ( readOnly )
            {
                lbEdit.Visible = false;
                ShowReadonlyDetails( prayerRequest );
            }
            else
            {
                if ( prayerRequest.Id > 0 )
                {
                    ShowReadonlyDetails( prayerRequest );
                }
                else
                {
                    ShowEditDetails( prayerRequest );
                }
            }
        }
        /// <summary>
        /// Handles the SaveClick event of the mdFlag control and flags the prayer request and moves to the next.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void mdFlag_SaveClick(object sender, EventArgs e)
        {
            int prayerRequestId = hfIdValue.ValueAsInt();

            var rockContext = new RockContext();
            var service     = new PrayerRequestService(rockContext);

            PrayerRequest request = service.Get(prayerRequestId);

            if (request != null)
            {
                request.FlagCount = (request.FlagCount ?? 0) + 1;
                if (request.FlagCount >= _flagLimit)
                {
                    request.IsApproved = false;
                }

                rockContext.SaveChanges();
            }

            mdFlag.Hide();
            lbNext_Click(sender, e);
        }
        /// <summary>
        /// Handles the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            Int32.TryParse(GetAttributeValue("GroupCategoryId"), out _blockInstanceGroupCategoryId);
            PrayerRequest prayerRequest = new PrayerRequest();
            Type          type          = prayerRequest.GetType();

            _prayerRequestEntityTypeId = Rock.Web.Cache.EntityTypeCache.GetId(type.FullName);

            BindFilter();

            // Block Security and special attributes (RockPage takes care of "View")
            canAddEditDelete = IsUserAuthorized("Edit");
            canApprove       = IsUserAuthorized("Approve");

            // grid stuff...
            gPrayerComments.Actions.ShowAdd = false;
            gPrayerComments.IsDeleteEnabled = canAddEditDelete;

            gPrayerComments.DataKeyNames = new string[] { "id", "entityid" };
            gPrayerComments.GridRebind  += gPrayerComments_GridRebind;
        }
Exemple #6
0
        /// <summary>
        /// Handles the Delete event of the gPrayerRequests control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gPrayerRequests_Delete(object sender, RowEventArgs e)
        {
            var rockContext = new RockContext();
            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);
            PrayerRequest        prayerRequest        = prayerRequestService.Get(e.RowKeyId);

            if (prayerRequest != null)
            {
                DeleteAllRelatedNotes(prayerRequest, rockContext);

                string errorMessage;
                if (!prayerRequestService.CanDelete(prayerRequest, out errorMessage))
                {
                    maGridWarning.Show(errorMessage, ModalAlertType.Information);
                    return;
                }

                prayerRequestService.Delete(prayerRequest);
                rockContext.SaveChanges();
            }

            BindGrid();
        }
        /// <summary>
        /// Shows the approval.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void ShowApproval(PrayerRequest prayerRequest)
        {
            if (prayerRequest != null)
            {
                pnlStatus.Visible      = true;
                PendingCss             = prayerRequest.IsApproved == false ? "btn-warning active" : "btn-default";
                ApprovedCss            = prayerRequest.IsApproved == true ? "btn-success active" : "btn-default";
                hfApprovedStatus.Value = prayerRequest.IsApproved.ToString();
            }
            else
            {
                hfApprovedStatus.Value = true.ToString();
                pnlStatus.Visible      = false;
                divStatus.Visible      = false;
            }

            hlStatus.Text = (prayerRequest.IsApproved ?? false) ? "Approved" : "Pending";

            hlStatus.LabelType = (prayerRequest.IsApproved ?? false) ? LabelType.Success : LabelType.Warning;

            var statusDetail = new System.Text.StringBuilder();

            if (prayerRequest.ApprovedByPersonAlias != null && prayerRequest.ApprovedByPersonAlias.Person != null)
            {
                statusDetail.AppendFormat("by {0} ", prayerRequest.ApprovedByPersonAlias.Person.FullName);
            }

            if (prayerRequest.ApprovedOnDateTime.HasValue)
            {
                statusDetail.AppendFormat(
                    "on {0} at {1}",
                    prayerRequest.ApprovedOnDateTime.Value.ToShortDateString(),
                    prayerRequest.ApprovedOnDateTime.Value.ToShortTimeString());
            }

            hlStatus.ToolTip = statusDetail.ToString();
        }
        /// <summary>
        /// Handles the Click event of the lbDelete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void lbDelete_Click(object sender, EventArgs e)
        {
            int prayerRequestId = hfPrayerRequestId.ValueAsInt();

            if (!IsUserAuthorized(Authorization.EDIT))
            {
                maWarning.Show("You are not authorized to delete this request.", ModalAlertType.Information);
                return;
            }

            var rockContext = new RockContext();
            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);
            PrayerRequest        prayerRequest        = prayerRequestService.Get(prayerRequestId);

            if (prayerRequest != null)
            {
                DeleteAllRelatedNotes(prayerRequest, rockContext);

                string errorMessage;
                if (!prayerRequestService.CanDelete(prayerRequest, out errorMessage))
                {
                    maWarning.Show(errorMessage, ModalAlertType.Information);
                    return;
                }

                prayerRequestService.Delete(prayerRequest);
                rockContext.SaveChanges();

                var queryParms = new Dictionary <string, string>();
                if (!string.IsNullOrWhiteSpace(PageParameter("PersonId")))
                {
                    queryParms.Add("PersonId", PageParameter("PersonId"));
                }
                NavigateToParentPage(queryParms);
            }
        }
        /// <summary>
        /// Starts the workflow if one was defined in the block setting.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        /// <param name="rockContext">The rock context.</param>
        private void StartWorkflow(PrayerRequest prayerRequest, RockContext rockContext)
        {
            if (Workflow.HasValue)
            {
                var workflowType = WorkflowTypeCache.Get(Workflow.Value);
                if (workflowType != null && (workflowType.IsActive ?? true))
                {
                    try
                    {
                        //
                        // Reload the request to make sure all navigation properties are correct.
                        //
                        prayerRequest = new PrayerRequestService(rockContext).Get(prayerRequest.Id);

                        var workflow = Model.Workflow.Activate(workflowType, prayerRequest.Name);
                        new WorkflowService(rockContext).Process(workflow, prayerRequest, out var workflowErrors);
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogService.LogException(ex);
                    }
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// Starts the workflow if one was defined in the block setting.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        /// <param name="rockContext">The rock context.</param>
        private void StartWorkflow(PrayerRequest prayerRequest, RockContext rockContext)
        {
            WorkflowType workflowType     = null;
            Guid?        workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();

            if (workflowTypeGuid.HasValue)
            {
                var workflowTypeService = new WorkflowTypeService(rockContext);
                workflowType = workflowTypeService.Get(workflowTypeGuid.Value);
                if (workflowType != null)
                {
                    try
                    {
                        var           workflow = Workflow.Activate(workflowType, prayerRequest.Name);
                        List <string> workflowErrors;
                        new WorkflowService(rockContext).Process(workflow, prayerRequest, out workflowErrors);
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogService.LogException(ex, this.Context);
                    }
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Handles the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Page.IsPostBack)
            {
                if (CurrentPerson != null)
                {
                    tbFirstName.Text = CurrentPerson.FirstName;
                    tbLastName.Text  = CurrentPerson.LastName;
                    tbEmail.Text     = CurrentPerson.Email;
                }

                dtbRequest.Text = PageParameter("Request");
            }

            var prayerRequest = new PrayerRequest {
                Id = 0
            };

            prayerRequest.LoadAttributes();
            phAttributes.Controls.Clear();
            Rock.Attribute.Helper.AddEditControls(prayerRequest, phAttributes, false, BlockValidationGroup);
        }
        public void SendPrayerRequest_should_encode_prayFor_to_prevent_XSS_attacks()
        {
            // Arrange
            SendPrayerRequest_shared_setup();

            // Act
            var prayerRequest = new PrayerRequest {
                Email = "fds@fdsfs", PrayFor = "<script>alert()</script>"
            };
            var result = _controller.SendPrayerRequest(prayerRequest) as OkNegotiatedContentResult <PrayerRequestResponse>;

            // Assert
            _mailerMock.Verify(x =>
                               x.SendMail(_smtpClientHost, _smtpClientPort, _smtpUserName, _smtpPassword, prayerRequest.Email,
                                          _prayerRequestEmailAddress, _prayerRequestEmailSubject, prayerRequest.PrayFor, null),
                               Times.Never
                               );
            _mailerMock.Verify(x =>
                               x.SendMail(_smtpClientHost, _smtpClientPort, _smtpUserName, _smtpPassword, prayerRequest.Email,
                                          _prayerRequestEmailAddress, _prayerRequestEmailSubject,
                                          System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(prayerRequest.PrayFor, true), null),
                               Times.Once
                               );
        }
        /// <summary>
        /// Handles the Click event to save the prayer request.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            if ( ! IsValid() )
            {
                return;
            }

            bool isAutoApproved = GetAttributeValue( "EnableAutoApprove" ).AsBoolean();
            bool defaultAllowComments = GetAttributeValue( "DefaultAllowCommentsSetting" ).AsBoolean();

            PrayerRequest prayerRequest = new PrayerRequest { Id = 0, IsActive = true, IsApproved = isAutoApproved, AllowComments = defaultAllowComments };

            var rockContext = new RockContext();
            PrayerRequestService prayerRequestService = new PrayerRequestService( rockContext );
            prayerRequestService.Add( prayerRequest );
            prayerRequest.EnteredDateTime = RockDateTime.Now;

            if ( isAutoApproved )
            {
                prayerRequest.ApprovedByPersonAliasId = CurrentPersonAliasId;
                prayerRequest.ApprovedOnDateTime = RockDateTime.Now;
                var expireDays = Convert.ToDouble( GetAttributeValue( "ExpireDays" ) );
                prayerRequest.ExpirationDate = RockDateTime.Now.AddDays( expireDays );
            }

            // Now record all the bits...
            int? categoryId = bddlCategory.SelectedValueAsInt();
            Guid defaultCategoryGuid = GetAttributeValue( "DefaultCategory" ).AsGuid();
            if ( categoryId == null && !defaultCategoryGuid.IsEmpty() )
            {
                var category = new CategoryService( rockContext ).Get( defaultCategoryGuid );
                categoryId = category.Id;
            }

            prayerRequest.CategoryId = categoryId;
            prayerRequest.RequestedByPersonAliasId = CurrentPersonAliasId;
            prayerRequest.FirstName = dtbFirstName.Text;
            prayerRequest.LastName = dtbLastName.Text;
            prayerRequest.Email = dtbEmail.Text;
            prayerRequest.Text = dtbRequest.Text;

            if ( this.EnableUrgentFlag )
            {
                prayerRequest.IsUrgent = cbIsUrgent.Checked;
            }
            else
            {
                prayerRequest.IsUrgent = false;
            }

            if ( this.EnableCommentsFlag )
            {
                prayerRequest.AllowComments = cbAllowComments.Checked;
            }

            if ( this.EnablePublicDisplayFlag )
            {
                prayerRequest.IsPublic = cbAllowPublicDisplay.Checked;
            }
            else
            {
                prayerRequest.IsPublic = false;
            }

            if ( !Page.IsValid )
            {
                return;
            }

            if ( !prayerRequest.IsValid )
            {
                // field controls render error messages
                return;
            }

            rockContext.SaveChanges();

            bool isNavigateToParent = GetAttributeValue( "NavigateToParentOnSave" ).AsBoolean();

            if ( isNavigateToParent )
            {
                NavigateToParentPage();
            }
            else
            {
                pnlForm.Visible = false;
                pnlReceipt.Visible = true;
            }
        }
        /// <summary>
        /// Saves the prayer request.
        /// </summary>
        private void SaveRequest()
        {
            var rockContext = new RockContext();
            PrayerRequest prayerRequest;
            PrayerRequestService prayerRequestService = new PrayerRequestService( rockContext );

            int prayerRequestId = int.Parse( hfPrayerRequestId.Value );

            // Fetch the prayer request or create a new one if needed
            if ( prayerRequestId == 0 )
            {
                prayerRequest = new PrayerRequest();
                prayerRequestService.Add( prayerRequest );
                prayerRequest.EnteredDateTime = RockDateTime.Now;
            }
            else
            {
                prayerRequest = prayerRequestService.Get( prayerRequestId );
            }

            // If changing from NOT-approved to approved, record who and when
            if ( !( prayerRequest.IsApproved ?? false ) && cbApproved.Checked )
            {
                prayerRequest.ApprovedByPersonId = CurrentPerson.Id;
                prayerRequest.ApprovedOnDateTime = RockDateTime.Now;

                // reset the flag count only to zero ONLY if it had a value previously.
                if ( prayerRequest.FlagCount.HasValue && prayerRequest.FlagCount > 0 )
                {
                    prayerRequest.FlagCount = 0;
                }
            }

            // If no expiration date was manually set, then use the default setting.
            if ( !dpExpirationDate.SelectedDate.HasValue )
            {
                var expireDays = Convert.ToDouble( GetAttributeValue( "ExpireDays" ) );
                prayerRequest.ExpirationDate = RockDateTime.Now.AddDays( expireDays );
            }
            else
            {
                prayerRequest.ExpirationDate = dpExpirationDate.SelectedDate;
            }

            // If no category was selected, then use the default category if there is one.
            int? categoryId = catpCategory.SelectedValueAsInt();
            Guid defaultCategoryGuid = GetAttributeValue( "DefaultCategory" ).AsGuid();
            if ( categoryId == null && !defaultCategoryGuid.IsEmpty() )
            {
                var category = new CategoryService( rockContext ).Get( defaultCategoryGuid );
                categoryId = category.Id;
            }

            prayerRequest.CategoryId = categoryId;

            // Now record all the bits...
            prayerRequest.IsApproved = cbApproved.Checked;
            prayerRequest.IsActive = cbIsActive.Checked;
            prayerRequest.IsUrgent = cbIsUrgent.Checked;
            prayerRequest.AllowComments = cbAllowComments.Checked;
            prayerRequest.IsPublic = cbIsPublic.Checked;
            prayerRequest.FirstName = dtbFirstName.Text;
            prayerRequest.LastName = dtbLastName.Text;
            prayerRequest.Text = dtbText.Text.Trim();
            prayerRequest.Answer = dtbAnswer.Text.Trim();

            if ( !Page.IsValid )
            {
                return;
            }

            if ( !prayerRequest.IsValid )
            {
                // field controls render error messages
                return;
            }

            rockContext.SaveChanges();

            NavigateToParentPage();
        }
        /// <summary>
        /// Shows the prayer count.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void ShowPrayerCount( PrayerRequest prayerRequest )
        {
            if ( prayerRequest.PrayerCount > 10 )
            {
                badgePrayerCount.BadgeType = "success";
            }

            if ( prayerRequest.PrayerCount > 0 )
            {
                badgePrayerCount.Text = string.Format( "{0} prayers", prayerRequest.PrayerCount ?? 0 );
            }

            badgePrayerCount.ToolTip = string.Format( "{0} prayers offered by the team for this request.", prayerRequest.PrayerCount ?? 0 );
        }
        /// <summary>
        /// Shows the readonly details.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void ShowReadonlyDetails( PrayerRequest prayerRequest )
        {
            SetEditMode( false );
            lActionTitle.Text = string.Format( "{0} Prayer Request", prayerRequest.FullName ).FormatAsHtmlTitle();

            DescriptionList descriptionList = new DescriptionList();
            descriptionList.Add( "Name", prayerRequest.FullName.SanitizeHtml() );
            descriptionList.Add( "Category", prayerRequest.Category != null ? prayerRequest.Category.Name : string.Empty );
            descriptionList.Add( "Request", prayerRequest.Text.ScrubHtmlAndConvertCrLfToBr() );
            descriptionList.Add( "Answer", prayerRequest.Answer.ScrubHtmlAndConvertCrLfToBr() );
            lMainDetails.Text = descriptionList.Html;

            ShowStatus( prayerRequest, this.CurrentPerson, hlblFlaggedMessageRO );
            ShowPrayerCount( prayerRequest );

            if ( !prayerRequest.IsApproved.HasValue )
            {
                hlblStatus.Visible = true;
                hlblStatus.Text = "Pending Approval";
            }
            else if ( prayerRequest.IsApproved.HasValue && ( !prayerRequest.IsApproved ?? false ) )
            {
                hlblStatus.Visible = true;
                hlblStatus.Text = "Unapproved";
            }

            hlblUrgent.Visible = prayerRequest.IsUrgent ?? false;
        }
        //public void AddNewDogPhoto(string name, string furColor)
        //{
        //  sqliteConnection.Insert(new Dog
        //  {
        //      Name = name,
        //      FurColor = furColor,
        //      //a default dog image for entries via the text only field
        //      DogPictureSource = "https://s-media-cache-ak0.pinimg.com/736x/4b/c2/ac/4bc2acd1af5130a668a4c391805f3f29--teacup-poodle-puppies-teacup-poodles.jpg"
        //  });
        //}

        public void DeletePrayerRequest(PrayerRequest prayerRequest)
        {
            sqliteConnection.Delete(prayerRequest);
        }
        /// <summary>
        /// Handles the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            _blockInstanceGroupCategoryId = GetAttributeValue( "GroupCategoryId" ).AsInteger() ?? 0;
            PrayerRequest prayerRequest = new PrayerRequest();
            Type type = prayerRequest.GetType();
            _prayerRequestEntityTypeId = Rock.Web.Cache.EntityTypeCache.GetId( type.FullName );

            BindFilter();

            // Block Security and special attributes (RockPage takes care of View)
            _canAddEditDelete = IsUserAuthorized( Authorization.EDIT );
            _canApprove = IsUserAuthorized( "Approve" );

            // grid stuff...
            gPrayerComments.Actions.ShowAdd = false;
            gPrayerComments.IsDeleteEnabled = _canAddEditDelete;

            gPrayerComments.DataKeyNames = new string[] { "id", "entityid" };
            gPrayerComments.GridRebind += gPrayerComments_GridRebind;
        }
 public async Task <PrayerRequest> CreatePrayerRequest([Body] PrayerRequest prayerRequest)
 {
     return(await _client.CreatePrayerRequest(prayerRequest, token));
 }
        /// <summary>
        /// Builds the common fields.
        /// </summary>
        /// <param name="request">The prayer request.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns>A string containing the XAML that represents the common Group fields.</returns>
        private string BuildCommonFields(PrayerRequest request, Dictionary <string, string> parameters)
        {
            var    sb = new StringBuilder();
            string field;

            string firstName = request != null ? request.FirstName : RequestContext.CurrentPerson?.FirstName;
            string lastName  = request != null ? request.LastName : RequestContext.CurrentPerson?.LastName;
            string email     = request != null ? request.Email : RequestContext.CurrentPerson?.Email;

            field = MobileHelper.GetTextEditFieldXaml("firstName", "First Name", firstName, true);
            sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
            parameters.Add("firstName", "Text");

            field = MobileHelper.GetTextEditFieldXaml("lastName", "Last Name", lastName, RequireLastName);
            sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
            parameters.Add("lastName", "Text");

            field = MobileHelper.GetEmailEditFieldXaml("email", "Email", email, false);
            sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
            parameters.Add("email", "Text");

            if (ShowCampus && CampusCache.All().Where(a => a.IsActive ?? false).Count() > 1)
            {
                field = $"<Rock:CampusPicker x:Name=\"campus\" Label=\"Campus\" IsRequired=\"{RequireCampus}\" SelectedValue=\"{request?.Campus?.Guid.ToStringSafe()}\" />";
                sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
                parameters.Add("campus", "SelectedValue");
            }

            if (ShowCategory && ParentCategory.HasValue)
            {
                var items = CategoryCache.Get(ParentCategory.Value)
                            .Categories
                            .Select(a => new KeyValuePair <string, string>(a.Guid.ToString(), a.Name));

                var categoryGuid = request?.Category?.Guid;
                if (!categoryGuid.HasValue && DefaultCategory.HasValue)
                {
                    categoryGuid = CategoryCache.Get(DefaultCategory.Value).Guid;
                }

                field = MobileHelper.GetDropDownFieldXaml("category", "Category", categoryGuid.ToStringSafe(), true, items);
                sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
                parameters.Add("category", "SelectedValue");
            }

            field = MobileHelper.GetTextEditFieldXaml("request", "Request", request?.Text, true, true, CharacterLimit);
            sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
            parameters.Add("request", "Text");

            if (ShowPublicDisplayFlag)
            {
                field = MobileHelper.GetCheckBoxFieldXaml("allowPublication", "Allow Publication", request?.IsPublic ?? DefaultToPublic);
                sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
                parameters.Add("allowPublication", "IsChecked");
            }

            if (ShowUrgentFlag)
            {
                field = MobileHelper.GetCheckBoxFieldXaml("urgent", "Urgent", request?.IsUrgent ?? false);
                sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
                parameters.Add("urgent", "IsChecked");
            }

            return(sb.ToString());
        }
        /// <summary>
        /// Builds the content to be displayed on the block.
        /// </summary>
        /// <returns>A string containing the XAML content to be displayed.</returns>
        private string BuildContent()
        {
            string content;
            string fieldsContent;
            var    parameters = new Dictionary <string, string>();

            using (var rockContext = new RockContext())
            {
                Guid?         requestGuid = RequestContext.GetPageParameter(PageParameterKeys.RequestGuid).AsGuidOrNull();
                PrayerRequest request     = null;

                if (requestGuid.HasValue)
                {
                    if (!BlockCache.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson))
                    {
                        return("<Rock:NotificationBox HeaderText=\"Error\" Text=\"You are not authorized to edit prayer requests.\" NotificationType=\"Error\" />");
                    }

                    request = new PrayerRequestService(rockContext).Get(requestGuid.Value);

                    if (request == null)
                    {
                        return("<Rock:NotificationBox HeaderText=\"Error\" Text=\"We couldn't find that prayer request.\" NotificationType=\"Error\" />");
                    }
                }

                content = $@"
<StackLayout StyleClass=""prayerdetail"">
    ##HEADER##

    ##FIELDS##
    
    <Rock:Validator x:Name=""vForm"">
        ##VALIDATORS##
    </Rock:Validator>
    
    <Rock:NotificationBox x:Name=""nbError"" NotificationType=""Error"" />
    
    <Button StyleClass=""btn,btn-primary"" Text=""Save"" Margin=""24 0 0 0"" Command=""{{Binding Callback}}"">
        <Button.CommandParameter>
            <Rock:CallbackParameters Name=""Save"" Validator=""{{x:Reference vForm}}"" Notification=""{{x:Reference nbError}}"">
                ##PARAMETERS##
            </Rock:CallbackParameters>
        </Button.CommandParameter>
    </Button>

    <Button StyleClass=""btn,btn-link"" Text=""Cancel"" ##CANCEL## />
</StackLayout>";

                if (ShowHeader)
                {
                    content = content.Replace("##HEADER##", $@"<Label StyleClass=""h2"" Text=""{( request == null ? "Add" : "Edit" )} Prayer Request"" />
    <Rock:Divider />");
                }
                else
                {
                    content = content.Replace("##HEADER##", "");
                }

                fieldsContent = BuildCommonFields(request, parameters);
            }

            var validatorsContent = parameters.Keys.Select(a => $"<x:Reference>{a}</x:Reference>");
            var parametersContent = parameters.Select(a => $"<Rock:Parameter Name=\"{a.Key}\" Value=\"{{Binding {a.Value}, Source={{x:Reference {a.Key}}}}}\" />");

            //
            // On cancel, pop to the parent page.
            //
            content = content.Replace("##CANCEL##", "Command=\"{Binding PopPage}\"");

            return(content.Replace("##FIELDS##", fieldsContent)
                   .Replace("##VALIDATORS##", string.Join(string.Empty, validatorsContent))
                   .Replace("##PARAMETERS##", string.Join(string.Empty, parametersContent)));
        }
 /// <summary>
 /// Starts the workflow if one was defined in the block setting.
 /// </summary>
 /// <param name="prayerRequest">The prayer request.</param>
 /// <param name="rockContext">The rock context.</param>
 private void StartWorkflow( PrayerRequest prayerRequest, RockContext rockContext )
 {
     WorkflowType workflowType = null;
     Guid? workflowTypeGuid = GetAttributeValue( "Workflow" ).AsGuidOrNull();
     if ( workflowTypeGuid.HasValue )
     {
         var workflowTypeService = new WorkflowTypeService( rockContext );
         workflowType = workflowTypeService.Get( workflowTypeGuid.Value );
         if ( workflowType != null )
         {
             try
             {
                 var workflow = Workflow.Activate( workflowType, prayerRequest.Name );
                 List<string> workflowErrors;
                 new WorkflowService( rockContext ).Process( workflow, prayerRequest, out workflowErrors );
             }
             catch ( Exception ex )
             {
                 ExceptionLogService.LogException( ex, this.Context );
             }
         }
     }
 }
        /// <summary>
        /// Handles the Click event to save the prayer request.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            if ( ! IsValid() )
            {
                return;
            }

            bool isAutoApproved = GetAttributeValue( "EnableAutoApprove" ).AsBoolean();
            bool defaultAllowComments = GetAttributeValue( "DefaultAllowCommentsSetting" ).AsBoolean();

            PrayerRequest prayerRequest = new PrayerRequest { Id = 0, IsActive = true, IsApproved = isAutoApproved, AllowComments = defaultAllowComments };

            var rockContext = new RockContext();
            PrayerRequestService prayerRequestService = new PrayerRequestService( rockContext );
            prayerRequestService.Add( prayerRequest );
            prayerRequest.EnteredDateTime = RockDateTime.Now;

            if ( isAutoApproved )
            {
                prayerRequest.ApprovedByPersonAliasId = CurrentPersonAliasId;
                prayerRequest.ApprovedOnDateTime = RockDateTime.Now;
                var expireDays = Convert.ToDouble( GetAttributeValue( "ExpireDays" ) );
                prayerRequest.ExpirationDate = RockDateTime.Now.AddDays( expireDays );
            }

            // Now record all the bits...
            // Make sure the Category is hydrated so it's included for any Lava processing
            Category category;
            int? categoryId = bddlCategory.SelectedValueAsInt();
            Guid defaultCategoryGuid = GetAttributeValue( "DefaultCategory" ).AsGuid();
            if ( categoryId == null && !defaultCategoryGuid.IsEmpty() )
            {
                category = new CategoryService( rockContext ).Get( defaultCategoryGuid );
                categoryId = category.Id;
            }
            else
            {
                category = new CategoryService( rockContext ).Get( categoryId.Value );
            }

            prayerRequest.CategoryId = categoryId;
            prayerRequest.Category = category;
            prayerRequest.RequestedByPersonAliasId = CurrentPersonAliasId;
            prayerRequest.FirstName = tbFirstName.Text;
            prayerRequest.LastName = tbLastName.Text;
            prayerRequest.Email = tbEmail.Text;
            prayerRequest.Text = dtbRequest.Text;

            if ( this.EnableUrgentFlag )
            {
                prayerRequest.IsUrgent = cbIsUrgent.Checked;
            }
            else
            {
                prayerRequest.IsUrgent = false;
            }

            if ( this.EnableCommentsFlag )
            {
                prayerRequest.AllowComments = cbAllowComments.Checked;
            }

            if ( this.EnablePublicDisplayFlag )
            {
                prayerRequest.IsPublic = cbAllowPublicDisplay.Checked;
            }
            else
            {
                prayerRequest.IsPublic = false;
            }

            if ( !Page.IsValid )
            {
                return;
            }

            if ( !prayerRequest.IsValid )
            {
                // field controls render error messages
                return;
            }

            rockContext.SaveChanges();

            StartWorkflow( prayerRequest, rockContext );

            bool isNavigateToParent = GetAttributeValue( "NavigateToParentOnSave" ).AsBoolean();

            if ( isNavigateToParent )
            {
                NavigateToParentPage();
            }
            else
            {
                pnlForm.Visible = false;
                pnlReceipt.Visible = true;

                // Build success text that is Lava capable
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson );
                mergeFields.Add( "PrayerRequest", prayerRequest );
                nbMessage.Text = GetAttributeValue( "SaveSuccessText" ).ResolveMergeFields( mergeFields );

                // Resolve any dynamic url references
                string appRoot = ResolveRockUrl( "~/" );
                string themeRoot = ResolveRockUrl( "~~/" );
                nbMessage.Text = nbMessage.Text.Replace( "~~/", themeRoot ).Replace( "~/", appRoot );

                // show liquid help for debug
                if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
                {
                    nbMessage.Text += mergeFields.lavaDebugInfo();
                }
            }
        }
 private void DeleteAllRelatedNotes( PrayerRequest prayerRequest )
 {
     var noteTypeService = new NoteTypeService();
     var noteType = noteTypeService.Get( (int)_prayerRequestEntityTypeId, "Prayer Comment" );
     var noteService = new NoteService();
     var prayerComments = noteService.Get( noteType.Id, prayerRequest.Id );
     foreach ( Note prayerComment in prayerComments )
     {
         noteService.Delete( prayerComment, CurrentPersonId );
         noteService.Save( prayerComment, CurrentPersonId );
     }
 }
Exemple #25
0
        public override MobileBlockResponse HandleRequest(string request, Dictionary <string, string> Body)
        {
            body = Body;
            RockContext          rockContext          = new RockContext();
            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);
            PrayerRequest        prayerRequest        = new PrayerRequest();

            prayerRequest.EnteredDateTime          = RockDateTime.Now;
            prayerRequest.FirstName                = GetItem("firstName");
            prayerRequest.LastName                 = GetItem("lastName");
            prayerRequest.Text                     = GetItem("request");
            prayerRequest.RequestedByPersonAliasId = CurrentPersonAliasId;

            if (!string.IsNullOrWhiteSpace(GetItem("campus")))
            {
                prayerRequest.CampusId = GetItem("campus").AsInteger();
            }

            bool isAutoApproved = GetAttributeValue("EnableAutoApprove").AsBoolean();

            if (isAutoApproved)
            {
                prayerRequest.ApprovedByPersonAliasId = CurrentPersonAliasId;
                prayerRequest.ApprovedOnDateTime      = RockDateTime.Now;
                var expireDays = GetAttributeValue("ExpireDays").AsDouble();
                prayerRequest.ExpirationDate = RockDateTime.Now.AddDays(expireDays);
            }

            //Category
            if (GetItem("category").AsInteger() != 0)
            {
                prayerRequest.CategoryId = GetItem("category").AsInteger();
            }
            else
            {
                Guid defaultCategoryGuid = GetAttributeValue("DefaultCategory").AsGuid();
                var  defaultCategory     = CategoryCache.Read(defaultCategoryGuid);
                if (defaultCategory != null)
                {
                    prayerRequest.CategoryId = defaultCategory.Id;
                }
            }

            if (GetItem("urgent").AsBoolean())
            {
                prayerRequest.IsUrgent = true;
            }
            else
            {
                prayerRequest.IsUrgent = false;
            }

            if (GetItem("allowComments").AsBoolean())
            {
                prayerRequest.AllowComments = true;
            }
            else
            {
                prayerRequest.AllowComments = false;
            }

            if (GetItem("allowPublication").AsBoolean())
            {
                prayerRequest.IsPublic = true;
            }
            else
            {
                prayerRequest.IsPublic = false;
            }
            prayerRequestService.Add(prayerRequest);
            rockContext.SaveChanges();

            Guid?workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();

            if (workflowTypeGuid.HasValue)
            {
                prayerRequest.LaunchWorkflow(workflowTypeGuid, prayerRequest.Name);
            }

            AvalancheUtilities.SetActionItems(GetAttributeValue("ActionItem"),
                                              CustomAttributes,
                                              CurrentPerson,
                                              AvalancheUtilities.GetMergeFields(CurrentPerson));

            var response = new FormResponse
            {
                Success = true,
                Message = GetAttributeValue("SaveSuccessText")
            };

            if (CustomAttributes.ContainsKey("ActionType") && CustomAttributes["ActionType"] != "0")
            {
                response.ActionType = CustomAttributes["ActionType"];
            }

            if (CustomAttributes.ContainsKey("Resource"))
            {
                response.Resource = CustomAttributes["Resource"];
            }

            if (CustomAttributes.ContainsKey("Parameter"))
            {
                response.Parameter = CustomAttributes["Parameter"];
            }


            return(new MobileBlockResponse()
            {
                Request = request,
                Response = JsonConvert.SerializeObject(response),
                TTL = 0
            });
        }
Exemple #26
0
        public AddTapPage()
        {
            this.Title = "Add a Prayer Request";

            mySharedText.Text      = "Hey guys, this is what's going on...";
            mySharedText.TextColor = Color.Gray;

            mySharedText.Focused   += myQuestion_Focused;
            mySharedText.Unfocused += myQuestion_Unfocused;

            //BUTTON
            Button submitButton = new StyledButton(StyledButton.Borders.Thin, 1);

            submitButton.Text = "Submit";
            submitButton.HorizontalOptions = LayoutOptions.FillAndExpand;

            submitButton.Clicked += (sender, e) => {
                Device.BeginInvokeOnMainThread(() => {
                    System.Random random = new Random();
                    int randomId         = random.Next(1, 1000000000);
                    string randomNumber  = string.Join(string.Empty, Enumerable.Range(0, 10).Select(number => random.Next(0, 5).ToString()));

                    PrayerRequest newPrayerRequest = new PrayerRequest()
                    {
                        Id = randomId,
                        CreatedDateTimeString = DateTime.Now.ToString("MMM d h:mm tt", new CultureInfo("en-US")),
                        CreatedDateTime       = DateTimeOffset.UtcNow,
                        StringOnlyDateTime    = "March 1, 2018",
                        FirstName             = "Andrew",
                        LastName        = "Kim",
                        FullName        = "Andrew Kim",
                        FullNameAndDate = "Andrew Kim\r\nMarch 1, 2018",
                        //FBProfileUrl = "http://loremflickr.com/600/600/nature?filename=simple.jpg",
                        FBProfileUrl             = "http://graph.facebook.com/450/picture?type=normal",
                        PrayerRequestText        = mySharedText.Text,
                        NumberOfThoughts         = 0,
                        NumberOfPrayers          = 0,
                        StringTheNumberOfPrayers = "first test string"
                    };

                    ParentViewModel.MyObservableCollectionOfUnderlyingData.Add(newPrayerRequest);
                    ParentViewModel.ResetDataSource();

                    Navigation.PopModalAsync();
                });
            };

            Button cancelButton = new StyledButton(StyledButton.Borders.Thin, 1);

            cancelButton.Text = "Cancel";
            cancelButton.HorizontalOptions = LayoutOptions.FillAndExpand;

            cancelButton.Clicked += (sender, e) => {
                Device.BeginInvokeOnMainThread(() => {
                    Navigation.PopModalAsync();
                });
            };

            StackLayout myEnterTextStacklayout = new StackLayout
            {
                BackgroundColor   = Color.Transparent,
                VerticalOptions   = LayoutOptions.Start,
                HorizontalOptions = LayoutOptions.FillAndExpand,

                Children =
                {
                    mST, mySharedText
                }
            };


            StackLayout myButtonStacklayout = new StackLayout
            {
                Padding           = new Thickness(10, 10, 10, 10),
                Orientation       = StackOrientation.Horizontal,
                VerticalOptions   = LayoutOptions.Start,
                HorizontalOptions = LayoutOptions.FillAndExpand,

                Children =
                {
                    cancelButton, submitButton
                }
            };

            StackLayout combinedLayout = new StackLayout
            {
                BackgroundColor   = Color.White,
                Padding           = new Thickness(10, 50, 10, 10),
                VerticalOptions   = LayoutOptions.Start,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                Children          =
                {
                    myEnterTextStacklayout, myButtonStacklayout
                }
            };


            #region GRID DEFINITION
            var grid = new Grid()
            {
                //Padding = new Thickness(10, 10, 10, 10),
                Padding = new Thickness(10, 10, 10, 10),
                //BackgroundColor = MyColors.DarkGray
                BackgroundColor = MyColors.LighterGray
            };

            grid.RowDefinitions.Add(new RowDefinition {
                Height = new GridLength(.5, GridUnitType.Star)
            });
            grid.RowDefinitions.Add(new RowDefinition {
                Height = GridLength.Auto
            });
            grid.RowDefinitions.Add(new RowDefinition {
                Height = new GridLength(1, GridUnitType.Star)
            });
            grid.RowDefinitions.Add(new RowDefinition {
                Height = new GridLength(1, GridUnitType.Star)
            });

            grid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(1, GridUnitType.Star)
            });

            grid.Children.Add(combinedLayout, 0, 1);
            //Grid.SetRowSpan(cachedImage, 2);
            //Grid.SetColumnSpan(cachedImage, 2);

            Content = grid;
            #endregion



            //Content = new StackLayout
            //{
            //    Padding = new Thickness(10, 50, 10, 10),
            //    VerticalOptions = LayoutOptions.Start,
            //    HorizontalOptions = LayoutOptions.FillAndExpand,
            //    Children = {
            //        myEnterTextStacklayout, myButtonStacklayout

            //    }
            //};
        }
        /// <summary>
        /// Saves the prayer request.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <returns>The response to send back to the client.</returns>
        private CallbackResponse SaveRequest(Dictionary <string, object> parameters)
        {
            using (var rockContext = new RockContext())
            {
                var           prayerRequestService = new PrayerRequestService(rockContext);
                PrayerRequest prayerRequest;
                var           requestGuid = RequestContext.GetPageParameter(PageParameterKeys.RequestGuid).AsGuidOrNull();

                if (requestGuid.HasValue)
                {
                    prayerRequest = prayerRequestService.Get(requestGuid.Value);

                    if (prayerRequest == null || !BlockCache.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson))
                    {
                        return(new CallbackResponse
                        {
                            Error = "You are not authorized to edit prayer requests."
                        });
                    }
                }
                else
                {
                    int?categoryId = null;

                    if (DefaultCategory.HasValue)
                    {
                        categoryId = CategoryCache.Get(DefaultCategory.Value).Id;
                    }

                    prayerRequest = new PrayerRequest
                    {
                        Id              = 0,
                        IsActive        = true,
                        IsApproved      = EnableAutoApprove,
                        AllowComments   = false,
                        EnteredDateTime = RockDateTime.Now,
                        CategoryId      = categoryId
                    };
                    prayerRequestService.Add(prayerRequest);

                    if (EnableAutoApprove)
                    {
                        prayerRequest.ApprovedByPersonAliasId = RequestContext.CurrentPerson?.PrimaryAliasId;
                        prayerRequest.ApprovedOnDateTime      = RockDateTime.Now;
                        prayerRequest.ExpirationDate          = RockDateTime.Now.AddDays(ExpiresAfterDays);
                    }
                }

                prayerRequest.FirstName = ( string )parameters["firstName"];
                prayerRequest.LastName  = ( string )parameters["lastName"];
                prayerRequest.Email     = ( string )parameters["email"];
                prayerRequest.Text      = ( string )parameters["request"];

                if (ShowCampus)
                {
                    if (parameters.ContainsKey("campus"))
                    {
                        var campusGuid = (( string )parameters["campus"]).AsGuidOrNull();

                        if (campusGuid.HasValue)
                        {
                            prayerRequest.CampusId = CampusCache.Get(campusGuid.Value).Id;
                        }
                    }
                    else
                    {
                        prayerRequest.CampusId = CampusCache.All().FirstOrDefault(a => a.IsActive ?? false)?.Id;
                    }
                }

                if (ShowCategory && parameters.ContainsKey("category"))
                {
                    var categoryGuid = (( string )parameters["category"]).AsGuidOrNull();

                    if (categoryGuid.HasValue)
                    {
                        prayerRequest.CategoryId = CategoryCache.Get(categoryGuid.Value).Id;
                    }
                    else if (prayerRequest.Id > 0)
                    {
                        prayerRequest.CategoryId = null;
                    }
                }

                if (ShowPublicDisplayFlag)
                {
                    prayerRequest.IsPublic = ( bool )parameters["allowPublication"];
                }

                if (ShowUrgentFlag)
                {
                    prayerRequest.IsUrgent = ( bool )parameters["urgent"];
                }

                if (RequestContext.CurrentPerson != null)
                {
                    //
                    // If there is a logged in person and the names still match, meaning they are not
                    // entering a prayer request for somebody else, then set the requested by property.
                    //
                    var person = RequestContext.CurrentPerson;
                    if (prayerRequest.FirstName == person.FirstName && prayerRequest.LastName == person.LastName)
                    {
                        prayerRequest.RequestedByPersonAliasId = person.PrimaryAliasId;
                    }
                }
                else
                {
                    //
                    // If there is not a logged in person, try to match to an existing person.
                    //
                    var person = MatchPerson(prayerRequest, rockContext);

                    if (person != null)
                    {
                        prayerRequest.RequestedByPersonAliasId = person.PrimaryAliasId;
                    }
                }

                //
                // Save all changes to database.
                //
                rockContext.SaveChanges();

                StartWorkflow(prayerRequest, rockContext);
            }

            if (CompletionAction == 0)
            {
                return(new CallbackResponse
                {
                    Content = CompletionXaml ?? string.Empty
                });
            }
            else if (CompletionAction == 1)
            {
                return(new CallbackResponse
                {
                    Command = "PopPage",
                    CommandParameter = "true"
                });
            }
            else
            {
                return(new CallbackResponse
                {
                    Content = AttributeDefaults.CompletionXaml
                });
            }
        }
Exemple #28
0
        /// <summary>
        /// Saves the prayer request.
        /// </summary>
        private void SaveRequest()
        {
            var                  rockContext = new RockContext();
            PrayerRequest        prayerRequest;
            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);

            int prayerRequestId = int.Parse(hfPrayerRequestId.Value);

            // Fetch the prayer request or create a new one if needed
            if (prayerRequestId == 0)
            {
                prayerRequest = new PrayerRequest();
                prayerRequestService.Add(prayerRequest);
                prayerRequest.EnteredDateTime = RockDateTime.Now;
            }
            else
            {
                prayerRequest = prayerRequestService.Get(prayerRequestId);
            }

            // If changing from NOT-approved to approved, record who and when
            if (!(prayerRequest.IsApproved ?? false) && cbApproved.Checked)
            {
                prayerRequest.ApprovedByPersonId = CurrentPerson.Id;
                prayerRequest.ApprovedOnDateTime = RockDateTime.Now;

                // reset the flag count only to zero ONLY if it had a value previously.
                if (prayerRequest.FlagCount.HasValue && prayerRequest.FlagCount > 0)
                {
                    prayerRequest.FlagCount = 0;
                }
            }

            // If no expiration date was manually set, then use the default setting.
            if (!dpExpirationDate.SelectedDate.HasValue)
            {
                var expireDays = Convert.ToDouble(GetAttributeValue("ExpireDays"));
                prayerRequest.ExpirationDate = RockDateTime.Now.AddDays(expireDays);
            }
            else
            {
                prayerRequest.ExpirationDate = dpExpirationDate.SelectedDate;
            }

            // If no category was selected, then use the default category if there is one.
            int? categoryId          = catpCategory.SelectedValueAsInt();
            Guid defaultCategoryGuid = GetAttributeValue("DefaultCategory").AsGuid();

            if (categoryId == null && !defaultCategoryGuid.IsEmpty())
            {
                var category = new CategoryService(rockContext).Get(defaultCategoryGuid);
                categoryId = category.Id;
            }

            prayerRequest.CategoryId = categoryId;

            // Now record all the bits...
            prayerRequest.IsApproved    = cbApproved.Checked;
            prayerRequest.IsActive      = cbIsActive.Checked;
            prayerRequest.IsUrgent      = cbIsUrgent.Checked;
            prayerRequest.AllowComments = cbAllowComments.Checked;
            prayerRequest.IsPublic      = cbIsPublic.Checked;
            prayerRequest.FirstName     = dtbFirstName.Text;
            prayerRequest.LastName      = dtbLastName.Text;
            prayerRequest.Text          = dtbText.Text.Trim();
            prayerRequest.Answer        = dtbAnswer.Text.Trim();

            if (!Page.IsValid)
            {
                return;
            }

            if (!prayerRequest.IsValid)
            {
                // field controls render error messages
                return;
            }

            rockContext.SaveChanges();

            NavigateToParentPage();
        }
 /// <summary>
 /// Deletes all related notes.
 /// </summary>
 /// <param name="prayerRequest">The prayer request.</param>
 private void DeleteAllRelatedNotes( PrayerRequest prayerRequest )
 {
     var rockContext = new RockContext();
     var noteTypeService = new NoteTypeService( rockContext );
     var noteType = noteTypeService.Get( _prayerRequestEntityTypeId.Value, "Prayer Comment" );
     var noteService = new NoteService( rockContext );
     var prayerComments = noteService.Get( noteType.Id, prayerRequest.Id );
     foreach ( Note prayerComment in prayerComments )
     {
         noteService.Delete( prayerComment );
         rockContext.SaveChanges();
     }
 }
        /// <summary>
        /// Displays the details for a single, given prayer request.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        /// <param name="rockContext">The rock context.</param>
        private void ShowPrayerRequest( PrayerRequest prayerRequest, RockContext rockContext )
        {
            pnlPrayer.Visible = true;
            divPrayerAnswer.Visible = false;

            prayerRequest.PrayerCount = ( prayerRequest.PrayerCount ?? 0 ) + 1;
            hlblPrayerCountTotal.Text = prayerRequest.PrayerCount.ToString() + " team prayers";
            hlblUrgent.Visible = prayerRequest.IsUrgent ?? false;
            lTitle.Text = prayerRequest.FullName.FormatAsHtmlTitle();

            lPrayerText.Text = prayerRequest.Text.ScrubHtmlAndConvertCrLfToBr();

            if ( prayerRequest.EnteredDateTime != null )
            {
                lPrayerRequestDate.Text = string.Format( "Date Entered: {0}", prayerRequest.EnteredDateTime.ToShortDateString() );
            }

            hlblCategory.Text = prayerRequest.Category.Name;

            // Show their answer if there is one on the request.
            if ( !string.IsNullOrWhiteSpace( prayerRequest.Answer ) )
            {
                divPrayerAnswer.Visible = true;
                lPrayerAnswerText.Text = prayerRequest.Answer.EncodeHtml().ConvertCrLfToHtmlBr();
            }

            // put the request's id in the hidden field in case it needs to be flagged.
            hfIdValue.SetValue( prayerRequest.Id );

            if ( prayerRequest.RequestedByPersonAlias != null )
            {
                lPersonIconHtml.Text = Person.GetPersonPhotoImageTag( prayerRequest.RequestedByPersonAlias, 50, 50, "pull-left margin-r-md img-thumbnail" );
            }
            else
            {
                lPersonIconHtml.Text = string.Empty;
            }

            pnlPrayerComments.Visible = prayerRequest.AllowComments ?? false;
            if ( notesComments.Visible )
            {
                notesComments.EntityId = prayerRequest.Id;
                notesComments.RebuildNotes( true );
            }

            CurrentPrayerRequestId = prayerRequest.Id;

            try
            {
                // save because the prayer count was just modified.
                rockContext.SaveChanges();
            }
            catch ( Exception ex )
            {
                ExceptionLogService.LogException( ex, Context, this.RockPage.PageId, this.RockPage.Site.Id, CurrentPersonAlias );
            }
        }
        /// <summary>
        /// Shows the prayer request's detail.
        /// </summary>
        /// <param name="prayerId">The prayer identifier.</param>
        public void ShowDetail( int prayerId )
        {
            PrayerRequest prayerRequest = null;

            if ( prayerId != 0 )
            {
                prayerRequest = new PrayerRequestService( new RockContext() )
                    .Queryable( "RequestedByPersonAlias.Person,ApprovedByPersonAlias.Person" )
                    .FirstOrDefault( p => p.Id == prayerId );
                pdAuditDetails.SetEntity( prayerRequest, ResolveRockUrl( "~" ) );
            }

            if ( prayerRequest == null )
            {
                prayerRequest = new PrayerRequest { Id = 0, IsActive = true, IsApproved = true, AllowComments = true };
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            hfPrayerRequestId.Value = prayerRequest.Id.ToString();

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !IsUserAuthorized( Authorization.EDIT ) )
            {
                readOnly = true;
                nbEditModeMessage.Title = "Information";
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( PrayerRequest.FriendlyTypeName );
            }

            hlCategory.Text = prayerRequest.Category != null ? prayerRequest.Category.Name : string.Empty;

            if ( readOnly )
            {
                lbEdit.Visible = false;
                ShowReadonlyDetails( prayerRequest );
            }
            else
            {
                if ( prayerRequest.Id > 0 )
                {
                    ShowReadonlyDetails( prayerRequest );
                }
                else
                {
                    ShowEditDetails( prayerRequest );
                }
            }
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // determine the person
            Person person          = null;
            var    personAliasGuid = GetAttributeValue(action, "Person", true).AsGuidOrNull();

            {
                person = new PersonAliasService(rockContext).Queryable()
                         .Where(a => a.Guid.Equals(personAliasGuid.Value))
                         .Select(a => a.Person)
                         .FirstOrDefault();
            }
            if (person == null || !person.PrimaryAliasId.HasValue)
            {
                errorMessages.Add("The Person for the prayer request could not be determined or found!");
            }

            // determine the contents of prayer request
            var requestText = GetAttributeValue(action, "PrayerRequestText", true);

            if (requestText.IsNullOrWhiteSpace())
            {
                errorMessages.Add("The contents of the prayer request could not be determined or found!");
            }

            // determine if public
            bool isPublic = GetAttributeValue(action, "Public", true).AsBoolean();

            // determine the campus
            CampusCache campus = CampusCache.Read(GetAttributeValue(action, "Campus", true).AsGuid());

            // Add request
            if (!errorMessages.Any())
            {
                var requestService = new PrayerRequestService(rockContext);

                PrayerRequest prayerRequest = new PrayerRequest {
                    Id = 0, IsActive = true, IsApproved = false, AllowComments = false
                };
                requestService.Add(prayerRequest);
                prayerRequest.EnteredDateTime          = RockDateTime.Now;
                prayerRequest.RequestedByPersonAliasId = person.PrimaryAliasId;
                prayerRequest.FirstName = person.NickName;
                prayerRequest.LastName  = person.LastName;
                prayerRequest.Email     = person.Email;
                prayerRequest.Text      = requestText;
                prayerRequest.IsPublic  = isPublic;
                prayerRequest.CampusId  = campus != null ? campus.Id : (int?)null;

                var categoryGuid = GetAttributeValue(action, "Category").AsGuidOrNull();
                if (categoryGuid.HasValue)
                {
                    prayerRequest.CategoryId = new CategoryService(rockContext).Get(categoryGuid.Value)?.Id;
                }

                rockContext.SaveChanges();

                if (prayerRequest.Id > 0)
                {
                    string resultValue = prayerRequest.Id.ToString();
                    var    attribute   = SetWorkflowAttributeValue(action, "ResultAttribute", resultValue);
                    if (attribute != null)
                    {
                        action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, resultValue));
                    }
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(!errorMessages.Any());
        }
        /// <summary>
        /// Saves the prayer request.
        /// </summary>
        private void SaveRequest()
        {
            bool isAutoApproved       = GetAttributeValue("EnableAutoApprove").AsBoolean();
            bool defaultAllowComments = GetAttributeValue("DefaultAllowCommentsSetting").AsBoolean();

            PrayerRequest prayerRequest = new PrayerRequest {
                Id = 0, IsActive = true, IsApproved = isAutoApproved, AllowComments = defaultAllowComments
            };

            PrayerRequestService prayerRequestService = new PrayerRequestService();

            prayerRequestService.Add(prayerRequest, CurrentPersonId);
            prayerRequest.EnteredDate = DateTime.Now;

            // If changing from NOT approved to approved, record who and when
            if (isAutoApproved)
            {
                prayerRequest.ApprovedByPersonId = CurrentPerson.Id;
                prayerRequest.ApprovedOnDate     = DateTime.Now;
            }

            // Now record all the bits...
            prayerRequest.CategoryId = rblCategory.SelectedValueAsInt();
            prayerRequest.FirstName  = tbFirstName.Text;
            prayerRequest.LastName   = tbLastName.Text;
            prayerRequest.Text       = txtRequest.Text;

            if (enableUrgentFlag)
            {
                prayerRequest.IsUrgent = cbIsUrgent.Checked;
            }

            if (enableCommentsFlag)
            {
                prayerRequest.AllowComments = cbAllowComments.Checked;
            }

            if (enablePublicDisplayFlag)
            {
                prayerRequest.IsPublic = cbAllowPublicDisplay.Checked;
            }

            if (!Page.IsValid)
            {
                return;
            }

            if (!prayerRequest.IsValid)
            {
                // field controls render error messages
                return;
            }

            prayerRequestService.Save(prayerRequest, CurrentPersonId);

            bool isNavigateToParent = GetAttributeValue("NavigateToParentOnSave").AsBoolean();

            if (isNavigateToParent)
            {
                NavigateToParentPage();
            }
            else
            {
                pnlForm.Visible    = false;
                pnlReceipt.Visible = true;
            }
        }
        /// <summary>
        /// Shows the approval.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void ShowApproval( PrayerRequest prayerRequest )
        {
            if ( prayerRequest != null )
            {
                pnlStatus.Visible = true;
                PendingCss = prayerRequest.IsApproved == false ? "btn-warning active" : "btn-default";
                ApprovedCss = prayerRequest.IsApproved == true ? "btn-success active" : "btn-default";
                hfApprovedStatus.Value = prayerRequest.IsApproved.ToString();
            }
            else
            {
                hfApprovedStatus.Value = true.ToString();
                pnlStatus.Visible = false;
                divStatus.Visible = false;
            }

            hlStatus.Text = ( prayerRequest.IsApproved ?? false ) ? "Approved" : "Pending";

            hlStatus.LabelType = ( prayerRequest.IsApproved ?? false ) ? LabelType.Success : LabelType.Warning;

            var statusDetail = new System.Text.StringBuilder();
            if ( prayerRequest.ApprovedByPersonAlias != null && prayerRequest.ApprovedByPersonAlias.Person != null )
            {
                statusDetail.AppendFormat( "by {0} ", prayerRequest.ApprovedByPersonAlias.Person.FullName );
            }

            if ( prayerRequest.ApprovedOnDateTime.HasValue )
            {
                statusDetail.AppendFormat(
                    "on {0} at {1}",
                    prayerRequest.ApprovedOnDateTime.Value.ToShortDateString(),
                    prayerRequest.ApprovedOnDateTime.Value.ToShortTimeString() );
            }

            hlStatus.ToolTip = statusDetail.ToString();
        }
        /// <summary>
        /// Deletes all related notes.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void DeleteAllRelatedNotes( PrayerRequest prayerRequest, RockContext rockContext )
        {
            var noteTypeService = new NoteTypeService( rockContext );
            var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid() );
            var noteService = new NoteService( rockContext );
            var prayerComments = noteService.Get( noteType.Id, prayerRequest.Id );
            foreach ( Note prayerComment in prayerComments )
            {
                noteService.Delete( prayerComment );
            }

            rockContext.SaveChanges();
        }
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void ShowEditDetails( PrayerRequest prayerRequest )
        {
            SetEditMode( true );

            if ( prayerRequest.Id > 0 )
            {
                lActionTitle.Text = ActionTitle.Edit( PrayerRequest.FriendlyTypeName ).FormatAsHtmlTitle();
            }
            else
            {
                lActionTitle.Text = ActionTitle.Add( PrayerRequest.FriendlyTypeName ).FormatAsHtmlTitle();
                if ( CurrentPersonAlias != null && CurrentPerson != null && GetAttributeValue( "SetCurrentPersonToRequester" ).AsBoolean() )
                {
                    prayerRequest.RequestedByPersonAlias = CurrentPersonAlias;
                    prayerRequest.FirstName = CurrentPerson.NickName;
                    prayerRequest.LastName = CurrentPerson.LastName;
                }
            }

            pnlDetails.Visible = true;

            catpCategory.SetValue( prayerRequest.Category );

            tbFirstName.Text = prayerRequest.FirstName;
            tbLastName.Text = prayerRequest.LastName;
            dtbText.Text = prayerRequest.Text;
            dtbAnswer.Text = prayerRequest.Answer;

            if ( prayerRequest.RequestedByPersonAlias != null )
            {
                ppRequestor.SetValue( prayerRequest.RequestedByPersonAlias.Person );
            }
            else
            {
                ppRequestor.SetValue( null );
            }

            // If no expiration date is set, then use the default setting.
            if ( !prayerRequest.ExpirationDate.HasValue )
            {
                var expireDays = Convert.ToDouble( GetAttributeValue( "ExpireDays" ) );
                dpExpirationDate.SelectedDate = RockDateTime.Now.AddDays( expireDays );
            }
            else
            {
                dpExpirationDate.SelectedDate = prayerRequest.ExpirationDate;
            }

            ShowStatus( prayerRequest, this.CurrentPerson, hlblFlaggedMessage );

            cbIsPublic.Checked = prayerRequest.IsPublic ?? false;
            cbIsUrgent.Checked = prayerRequest.IsUrgent ?? false;
            cbIsActive.Checked = prayerRequest.IsActive ?? false;
            cbAllowComments.Checked = prayerRequest.AllowComments ?? false;
        }
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void ShowEditDetails( PrayerRequest prayerRequest )
        {
            SetEditMode( true );

            lActionTitle.Text = ( prayerRequest.Id > 0 ) ?
                ActionTitle.Edit( PrayerRequest.FriendlyTypeName ).FormatAsHtmlTitle() :
                ActionTitle.Add( PrayerRequest.FriendlyTypeName ).FormatAsHtmlTitle();

            pnlDetails.Visible = true;

            catpCategory.SetValue( prayerRequest.Category );

            dtbFirstName.Text = prayerRequest.FirstName;
            dtbLastName.Text = prayerRequest.LastName;
            dtbText.Text = prayerRequest.Text;
            dtbAnswer.Text = prayerRequest.Answer;

            // If no expiration date is set, then use the default setting.
            if ( !prayerRequest.ExpirationDate.HasValue )
            {
                var expireDays = Convert.ToDouble( GetAttributeValue( "ExpireDays" ) );
                dpExpirationDate.SelectedDate = RockDateTime.Now.AddDays( expireDays );
            }
            else
            {
                dpExpirationDate.SelectedDate = prayerRequest.ExpirationDate;
            }

            ShowStatus( prayerRequest, this.CurrentPerson, hlblFlaggedMessage );

            cbIsPublic.Checked = prayerRequest.IsPublic ?? false;
            cbIsUrgent.Checked = prayerRequest.IsUrgent ?? false;
            cbIsActive.Checked = prayerRequest.IsActive ?? false;
            cbAllowComments.Checked = prayerRequest.AllowComments ?? false;
        }
        /// <summary>
        /// Shows the readonly details.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void ShowReadonlyDetails( PrayerRequest prayerRequest )
        {
            SetEditMode( false );
            lActionTitle.Text = string.Format( "{0} Prayer Request", prayerRequest.FullName ).FormatAsHtmlTitle();

            DescriptionList descriptionList = new DescriptionList();
            if ( prayerRequest.RequestedByPersonAlias != null )
            {
                descriptionList.Add( "Requested By", prayerRequest.RequestedByPersonAlias.Person.FullName );
            }

            descriptionList.Add( "Name", prayerRequest.FullName );
            descriptionList.Add( "Request", prayerRequest.Text.ScrubHtmlAndConvertCrLfToBr() );
            descriptionList.Add( "Answer", prayerRequest.Answer.ScrubHtmlAndConvertCrLfToBr() );
            lMainDetails.Text = descriptionList.Html;

            ShowStatus( prayerRequest, this.CurrentPerson, hlblFlaggedMessageRO );
            ShowPrayerCount( prayerRequest );

            hlblUrgent.Visible = prayerRequest.IsUrgent ?? false;
        }
        /// <summary>
        /// Shows the status flags
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        /// <param name="person">The person.</param>
        /// <param name="lFlagged">The l flagged.</param>
        private void ShowStatus( PrayerRequest prayerRequest, Person person, HighlightLabel lFlagged )
        {
            int flagCount = prayerRequest.FlagCount ?? 0;
            if ( flagCount > 0 )
            {
                lFlagged.Visible = true;
                lFlagged.Text = string.Format( "flagged {0} times", flagCount );
            }

            cbApproved.Enabled = IsUserAuthorized( "Approve" );
            cbApproved.Checked = prayerRequest.IsApproved ?? false;

            if ( person != null && ( prayerRequest.IsApproved ?? false ) && prayerRequest.ApprovedByPersonId.HasValue )
            {
                lblApprovedByPerson.Visible = true;
                lblApprovedByPerson.Text = string.Format( "approved by {0}", prayerRequest.ApprovedByPerson.FullName );
            }
            else
            {
                lblApprovedByPerson.Visible = false;
            }
        }
        /// <summary>
        /// Shows the status flags
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        /// <param name="person">The person.</param>
        /// <param name="lFlagged">The l flagged.</param>
        private void ShowStatus( PrayerRequest prayerRequest, Person person, HighlightLabel lFlagged )
        {
            int flagCount = prayerRequest.FlagCount ?? 0;
            if ( flagCount > 0 )
            {
                lFlagged.Visible = true;
                lFlagged.Text = string.Format( "flagged {0} times", flagCount );
            }

            ShowApproval( prayerRequest );
        }
        /// <summary>
        /// Displays the details for a single, given prayer request.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        /// <param name="rockContext">The rock context.</param>
        private void ShowPrayerRequest( PrayerRequest prayerRequest, RockContext rockContext )
        {
            pnlPrayer.Visible = true;
            divPrayerAnswer.Visible = false;

            prayerRequest.PrayerCount = ( prayerRequest.PrayerCount ?? 0 ) + 1;
            hlblPrayerCountTotal.Text = prayerRequest.PrayerCount.ToString() + " team prayers";
            hlblUrgent.Visible = prayerRequest.IsUrgent ?? false;
            lTitle.Text = prayerRequest.FullName.FormatAsHtmlTitle();

            //lPrayerText.Text = prayerRequest.Text.EncodeHtmlThenConvertCrLfToHtmlBr();
            lPrayerText.Text = prayerRequest.Text.ScrubHtmlAndConvertCrLfToBr();
            hlblCategory.Text = prayerRequest.Category.Name;

            // Show their answer if there is one on the request.
            if ( !string.IsNullOrWhiteSpace( prayerRequest.Answer ) )
            {
                divPrayerAnswer.Visible = true;
                lPrayerAnswerText.Text = prayerRequest.Answer.EncodeHtml().ConvertCrLfToHtmlBr();
            }

            // put the request's id in the hidden field in case it needs to be flagged.
            hfIdValue.SetValue( prayerRequest.Id );

            lPersonIconHtml.Text = Person.GetPhotoImageTag( prayerRequest.RequestedByPersonAlias, 50, 50 );

            notesComments.Visible = prayerRequest.AllowComments ?? false;
            if ( notesComments.Visible )
            {
                notesComments.EntityId = prayerRequest.Id;
                notesComments.RebuildNotes( true );
            }

            CurrentPrayerRequestId = prayerRequest.Id;

            // save because the prayer count was just modified.
            rockContext.SaveChanges();
        }
        public ActionResult SubmitNewPrayerRequest(PrayerRequestModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    //Instantiate variables
                    IContentService contentService = Services.ContentService;
                    IContent        content        = contentService.CreateContent(name: model.PrayerTitle, parentId: (int)Common.siteNode.ThePrayerCorner, contentTypeAlias: docType.PrayerRequest);

                    content.SetValue(PrayerRequest.GetModelPropertyType(x => x.PrayerTitle).PropertyTypeAlias, model.PrayerTitle);
                    content.SetValue(PrayerRequest.GetModelPropertyType(x => x.Prayer).PropertyTypeAlias, model.Prayer);
                    content.SetValue(PrayerRequest.GetModelPropertyType(x => x.PrayerRequestMember).PropertyTypeAlias, model.UserId);
                    content.SetValue(PrayerRequest.GetModelPropertyType(x => x.RequestDate).PropertyTypeAlias, DateTime.Now);
                    content.SetValue(PrayerRequest.GetModelPropertyType(x => x.BaseCalculationDate).PropertyTypeAlias, DateTime.Now);

                    content.SetValue(PrayerRequest.GetModelPropertyType(x => x.TotalPrayersOffered).PropertyTypeAlias, 0);
                    content.SetValue(PrayerRequest.GetModelPropertyType(x => x.CurrentPercentage).PropertyTypeAlias, 0);

                    var result = contentService.SaveAndPublishWithStatus(content);
                    //contentService.RePublishAll(model.UserId);


                    if (result.Success)
                    {
                        //Add Prayer Request to member's records
                        IMember member = Services.MemberService.GetById(model.UserId);
                        if (member == null)
                        {
                            //Save error message to umbraco
                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine(@"Controllers/PrayerController.cs : SubmitNewPrayerRequest()");
                            sb.AppendLine(@"Member Id returned nothing.  Cannot add prayer request to member.");
                            sb.AppendLine("model:" + Newtonsoft.Json.JsonConvert.SerializeObject(model));
                            Exception ex = new Exception();
                            Common.SaveErrorMessage(ex, sb, typeof(PrayerController));
                        }
                        else
                        {
                            //Instantiate list
                            List <Models._prayerRequest> lstPrayerRequests = new List <Models._prayerRequest>();

                            //Populate list with any existing data
                            if (member.HasProperty(NodeProperties.prayerRequests) && member.GetValue(NodeProperties.prayerRequests) != null)
                            {
                                lstPrayerRequests = JsonConvert.DeserializeObject <List <Models._prayerRequest> >(member.GetValue(NodeProperties.prayerRequests).ToString());
                            }

                            //Add latest prayer request to
                            Models._prayerRequest newRequest = new Models._prayerRequest();
                            newRequest.prayer = content.Id.ToString();
                            newRequest.date   = DateTime.Now.ToString("yyyy-MM-dd");
                            lstPrayerRequests.Add(newRequest);

                            //Add data to member and save
                            member.SetValue(NodeProperties.prayerRequests, JsonConvert.SerializeObject(lstPrayerRequests));
                            Services.MemberService.Save(member);
                        }

                        //Return to page
                        TempData["NewPrayerCreatedSuccessfully"] = true;
                        return(RedirectToUmbracoPage((int)(Models.Common.siteNode.PrayerRequests)));
                    }
                    else
                    {
                        //Save error message to umbraco
                        StringBuilder sb = new StringBuilder();
                        sb.AppendLine(@"Controllers/PrayerController.cs : SubmitNewPrayerRequest()");
                        sb.AppendLine("model:" + Newtonsoft.Json.JsonConvert.SerializeObject(model));
                        sb.AppendLine("result:" + Newtonsoft.Json.JsonConvert.SerializeObject(result));
                        Exception ex = new Exception();
                        Common.SaveErrorMessage(ex, sb, typeof(PrayerController));

                        //Return with error
                        ModelState.AddModelError(string.Empty, "An error occured while creating your prayer request.");
                        return(CurrentUmbracoPage());
                    }
                }
                else
                {
                    return(CurrentUmbracoPage());
                }
            }
            catch (Exception ex)
            {
                //Save error message to umbraco
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(@"PrayerController.cs : SubmitNewPrayerRequest()");
                sb.AppendLine("model:" + Newtonsoft.Json.JsonConvert.SerializeObject(model));
                Common.SaveErrorMessage(ex, sb, typeof(PrayerController));

                ModelState.AddModelError(string.Empty, "An error occured while submitting your prayer request.");
                return(CurrentUmbracoPage());
            }
        }
        /// <summary>
        /// Handles the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            if ( !IsPostBack )
            {
                // hide cancel buttons if no homepage defined
                if ( string.IsNullOrWhiteSpace( GetAttributeValue( "Homepage" ) ) )
                {
                    lbPrayerCancel.Visible = false;
                }
            }

            this.EnableUrgentFlag = GetAttributeValue( "EnableUrgentFlag" ).AsBoolean();
            this.EnableCommentsFlag = GetAttributeValue( "EnableCommentsFlag" ).AsBoolean();
            this.EnablePublicDisplayFlag = GetAttributeValue( "EnablePublicDisplayFlag" ).AsBoolean();
            nbMessage.Text = GetAttributeValue( "SaveSuccessText" );

            RockPage.AddScriptLink( Page, ResolveUrl( "~/Scripts/bootstrap-limit.js" ) );
            var categoryGuid = GetAttributeValue( "GroupCategoryId" );
            if ( ! string.IsNullOrEmpty( categoryGuid ) )
            {
                BindCategories( categoryGuid );
            }
            else
            {
                bddlCategory.Visible = false;
            }

            Type type = new PrayerRequest().GetType();
            this.PrayerRequestEntityTypeId = Rock.Web.Cache.EntityTypeCache.GetId( type.FullName );

            int charLimit = GetAttributeValue( "CharacterLimit" ).AsInteger();
            if ( charLimit > 0 )
            {
                dtbRequest.Placeholder = string.Format( "Please pray that... (up to {0} characters)", charLimit );
                string scriptFormat = @"
            function SetCharacterLimit() {{
            $('#{0}').limit({{maxChars: {1}, counter:'#{2}', normalClass:'badge', warningClass:'badge-warning', overLimitClass: 'badge-danger'}});

            $('#{0}').on('cross', function(){{
            $('#{3}').prop('disabled', true);
            }});
            $('#{0}').on('uncross', function(){{
            $('#{3}').prop('disabled', false);
            }});
            }};
            $(document).ready(function () {{ SetCharacterLimit(); }});
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(SetCharacterLimit);
            ";
                string script = string.Format(scriptFormat , dtbRequest.ClientID, charLimit, lblCount.ClientID, lbSave.ClientID );
                ScriptManager.RegisterStartupScript( this.Page, this.GetType(), string.Format( "limit-{0}", this.ClientID ), script, true );
            }
        }
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void ShowEditDetails(PrayerRequest prayerRequest)
        {
            SetEditMode(true);

            if (prayerRequest.Id > 0)
            {
                lActionTitle.Text = ActionTitle.Edit(PrayerRequest.FriendlyTypeName).FormatAsHtmlTitle();
            }
            else
            {
                lActionTitle.Text = ActionTitle.Add(PrayerRequest.FriendlyTypeName).FormatAsHtmlTitle();
                if (CurrentPersonAlias != null && CurrentPerson != null && GetAttributeValue("SetCurrentPersonToRequester").AsBoolean())
                {
                    prayerRequest.RequestedByPersonAlias = CurrentPersonAlias;
                    prayerRequest.FirstName = CurrentPerson.NickName;
                    prayerRequest.LastName  = CurrentPerson.LastName;
                }
            }

            cpCampus.SelectedCampusId = prayerRequest.CampusId;

            pnlDetails.Visible = true;

            var prayRequestCategory = prayerRequest.Category;

            if (prayRequestCategory == null)
            {
                var defaultCategoryGuid = GetAttributeValue("DefaultCategory").AsGuidOrNull();
                if (defaultCategoryGuid.HasValue)
                {
                    prayRequestCategory = new CategoryService(new RockContext()).Get(defaultCategoryGuid.Value);
                }
            }
            catpCategory.SetValue(prayRequestCategory);

            tbFirstName.Text = prayerRequest.FirstName;
            tbLastName.Text  = prayerRequest.LastName;
            tbEmail.Text     = prayerRequest.Email;
            dtbText.Text     = prayerRequest.Text;
            dtbAnswer.Text   = prayerRequest.Answer;

            if (prayerRequest.RequestedByPersonAlias != null)
            {
                ppRequestor.SetValue(prayerRequest.RequestedByPersonAlias.Person);
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(PageParameter("PersonId")))
                {
                    var requestor = new PersonService(new RockContext()).Get(PageParameter("PersonId").AsInteger());
                    ppRequestor.SetValue(requestor);
                    tbFirstName.Text = requestor.NickName;
                    tbLastName.Text  = requestor.LastName;
                    tbEmail.Text     = requestor.Email;
                }
                else
                {
                    ppRequestor.SetValue(null);
                }
            }

            // If no expiration date is set, then use the default setting.
            if (!prayerRequest.ExpirationDate.HasValue)
            {
                var expireDays = Convert.ToDouble(GetAttributeValue("ExpireDays"));
                dpExpirationDate.SelectedDate = RockDateTime.Now.AddDays(expireDays);
            }
            else
            {
                dpExpirationDate.SelectedDate = prayerRequest.ExpirationDate;
            }

            ShowStatus(prayerRequest, this.CurrentPerson, hlblFlaggedMessage);

            cbIsPublic.Checked      = prayerRequest.IsPublic ?? false;
            cbIsUrgent.Checked      = prayerRequest.IsUrgent ?? false;
            cbIsActive.Checked      = prayerRequest.IsActive ?? false;
            cbAllowComments.Checked = prayerRequest.AllowComments ?? false;

            prayerRequest.LoadAttributes();
            phAttributes.Controls.Clear();
            // Filter to only include attribute / attribute values that the person is authorized to edit.
            var excludeForEdit = prayerRequest.Attributes.Where(a => !a.Value.IsAuthorized(Authorization.EDIT, this.CurrentPerson)).Select(a => a.Key).ToList();

            Rock.Attribute.Helper.AddEditControls(prayerRequest, phAttributes, true, BlockValidationGroup, excludeForEdit);
        }
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // stand up all the vars
            var      expireDays             = GetAttributeValue(action, "ExpireDays").AsDouble();
            int?     categoryId             = null;
            bool?    allowComments          = null;
            bool?    isUrgent               = null;
            bool?    isPublic               = null;
            Person   person                 = null;
            int?     requestorPersonAliasId = null;
            var      requestFirstName       = "Anonymous";
            var      requestLastName        = string.Empty;
            var      requestEmail           = string.Empty;
            int?     requestCampusId        = null;
            var      requestText            = string.Empty;
            var      isApproved             = GetAttributeValue(action, "Approved").AsBoolean();
            var      expirationDate         = RockDateTime.Now.AddDays(expireDays);
            DateTime?dateApproved           = null;
            int?     approvedPersonAliasId  = null;

            // get person
            Guid?personAttributeGuid = GetAttributeValue(action, "Person").AsGuidOrNull();

            if (personAttributeGuid.HasValue)
            {
                Guid?personAliasGuid = action.GetWorkflowAttributeValue(personAttributeGuid.Value).AsGuidOrNull();
                if (personAliasGuid.HasValue)
                {
                    var personAlias = new PersonAliasService(rockContext).Get(personAliasGuid.Value);
                    if (personAlias != null)
                    {
                        person = personAlias.Person;
                    }
                }
            }

            // get name and campus info
            if (person != null)
            {
                requestorPersonAliasId = person.PrimaryAliasId;
                requestFirstName       = (!string.IsNullOrWhiteSpace(person.NickName)) ? person.NickName : person.LastName; // in case it was a business
                requestLastName        = person.LastName;
                requestEmail           = person.Email;
                if (person.GetCampusIds().Any())
                {
                    requestCampusId = person.GetCampusIds().FirstOrDefault();
                }
            }
            else
            {
                Guid?firstNameAttributeGuid = GetAttributeValue(action, "FirstName").AsGuidOrNull();
                if (firstNameAttributeGuid.HasValue)
                {
                    var firstName = action.GetWorkflowAttributeValue(firstNameAttributeGuid.Value);
                    if (!string.IsNullOrWhiteSpace(firstName))
                    {
                        requestFirstName = firstName;
                    }
                }

                Guid?lastNameAttributeGuid = GetAttributeValue(action, "LastName").AsGuidOrNull();
                if (lastNameAttributeGuid.HasValue)
                {
                    var lastName = action.GetWorkflowAttributeValue(lastNameAttributeGuid.Value);
                    if (!string.IsNullOrWhiteSpace(lastName))
                    {
                        requestLastName = lastName;
                    }
                }

                Guid?emailAttributeGuid = GetAttributeValue(action, "Email").AsGuidOrNull();
                if (emailAttributeGuid.HasValue)
                {
                    var email = action.GetWorkflowAttributeValue(emailAttributeGuid.Value);
                    if (!string.IsNullOrWhiteSpace(email))
                    {
                        requestEmail = email;
                    }
                }

                Guid?campusAttributeGuid = GetAttributeValue(action, "Campus").AsGuidOrNull();
                if (campusAttributeGuid.HasValue)
                {
                    var campus = action.GetWorkflowAttributeValue(campusAttributeGuid.Value).AsGuidOrNull();
                    if (campus.HasValue)
                    {
                        requestCampusId = CampusCache.Get(campus.Value).Id;
                    }
                }
            }

            // get prayer request text
            Guid?requestTextAttributeGuid = GetAttributeValue(action, "Request").AsGuidOrNull();

            if (requestTextAttributeGuid.HasValue)
            {
                var requestAttributeText = action.GetWorkflowAttributeValue(requestTextAttributeGuid.Value);
                if (!string.IsNullOrWhiteSpace(requestAttributeText))
                {
                    requestText = requestAttributeText;
                }
            }

            // get category
            Guid?cateogryAttributeGuid = GetAttributeValue(action, "Category").AsGuidOrNull();

            if (cateogryAttributeGuid.HasValue)
            {
                var categoryGuid = action.GetWorkflowAttributeValue(cateogryAttributeGuid.Value).AsGuidOrNull();
                if (categoryGuid.HasValue)
                {
                    categoryId = CategoryCache.Get(categoryGuid.Value).Id;
                }
            }

            // get allow comments
            Guid?allowCommentsAttributeGuid = GetAttributeValue(action, "AllowComments").AsGuidOrNull();

            if (allowCommentsAttributeGuid.HasValue)
            {
                var commentsAllowed = action.GetWorkflowAttributeValue(allowCommentsAttributeGuid.Value).AsBooleanOrNull();
                if (commentsAllowed.HasValue)
                {
                    allowComments = commentsAllowed;
                }
            }

            // get is urgent
            Guid?isUrgentAttributeGuid = GetAttributeValue(action, "IsUrgent").AsGuidOrNull();

            if (isUrgentAttributeGuid.HasValue)
            {
                var urgent = action.GetWorkflowAttributeValue(isUrgentAttributeGuid.Value).AsBooleanOrNull();
                if (urgent.HasValue)
                {
                    isUrgent = urgent;
                }
            }

            // get is public
            Guid?isPublicAttributeGuid = GetAttributeValue(action, "IsPublic").AsGuidOrNull();

            if (isPublicAttributeGuid.HasValue)
            {
                var publicValue = action.GetWorkflowAttributeValue(isPublicAttributeGuid.Value).AsBooleanOrNull();
                if (publicValue.HasValue)
                {
                    isPublic = publicValue;
                }
            }

            // mark as approved if needed
            if (isApproved)
            {
                dateApproved          = RockDateTime.Now;
                approvedPersonAliasId = requestorPersonAliasId;
            }

            // test for possible errors and fail gracefully
            if (string.IsNullOrWhiteSpace(requestFirstName))
            {
                errorMessages.Add("A first name is required.");
                return(true);
            }

            if (string.IsNullOrWhiteSpace(requestText))
            {
                errorMessages.Add("The prayer request text is required.");
                return(true);
            }

            // create the request
            var request = new PrayerRequest
            {
                RequestedByPersonAliasId = requestorPersonAliasId,
                FirstName               = requestFirstName,
                LastName                = requestLastName,
                Email                   = requestEmail,
                CampusId                = requestCampusId,
                IsActive                = true,
                IsApproved              = isApproved,
                Text                    = requestText,
                EnteredDateTime         = RockDateTime.Now,
                ExpirationDate          = expirationDate,
                CreatedDateTime         = RockDateTime.Now,
                ApprovedOnDateTime      = dateApproved,
                CreatedByPersonAliasId  = requestorPersonAliasId,
                ApprovedByPersonAliasId = approvedPersonAliasId,
                CategoryId              = categoryId,
                AllowComments           = allowComments,
                IsUrgent                = isUrgent,
                IsPublic                = isPublic,
                Answer                  = string.Empty
            };

            // add the request
            var prayerRequestService = new PrayerRequestService(rockContext);

            prayerRequestService.Add(request);

            // save the request
            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();
            });

            if (request.Guid != null)
            {
                // get the attribute to store the request guid
                var prayerRequestAttributeGuid = GetAttributeValue(action, "PrayerRequest").AsGuidOrNull();
                if (prayerRequestAttributeGuid.HasValue)
                {
                    var prayerRequestAttribute = AttributeCache.Get(prayerRequestAttributeGuid.Value, rockContext);
                    if (prayerRequestAttribute != null)
                    {
                        if (prayerRequestAttribute.FieldTypeId == FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid(), rockContext).Id)
                        {
                            SetWorkflowAttributeValue(action, prayerRequestAttributeGuid.Value, request.Guid.ToString());
                        }
                    }
                }
            }

            return(true);
        }
        /// <summary>
        /// Saves the prayer request.
        /// </summary>
        private void SaveRequest()
        {
            var                  rockContext = new RockContext();
            PrayerRequest        prayerRequest;
            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);

            int prayerRequestId = hfPrayerRequestId.Value.AsInteger();

            // Fetch the prayer request or create a new one if needed
            if (prayerRequestId == 0)
            {
                prayerRequest = new PrayerRequest();
                prayerRequestService.Add(prayerRequest);
                prayerRequest.EnteredDateTime = RockDateTime.Now;
            }
            else
            {
                prayerRequest = prayerRequestService.Get(prayerRequestId);
            }

            if (ppRequestor.PersonId.HasValue)
            {
                prayerRequest.RequestedByPersonAliasId = ppRequestor.PersonAliasId;
            }

            // If changing from NOT-approved to approved, record who and when
            if (!(prayerRequest.IsApproved ?? false) && hfApprovedStatus.Value.AsBoolean())
            {
                prayerRequest.ApprovedByPersonAliasId = CurrentPersonAliasId;
                prayerRequest.ApprovedOnDateTime      = RockDateTime.Now;

                // reset the flag count only to zero ONLY if it had a value previously.
                if (prayerRequest.FlagCount.HasValue && prayerRequest.FlagCount > 0)
                {
                    prayerRequest.FlagCount = 0;
                }
            }

            // If no expiration date was manually set, then use the default setting.
            if (!dpExpirationDate.SelectedDate.HasValue)
            {
                var expireDays = Convert.ToDouble(GetAttributeValue("ExpireDays"));
                prayerRequest.ExpirationDate = RockDateTime.Now.AddDays(expireDays);
            }
            else
            {
                prayerRequest.ExpirationDate = dpExpirationDate.SelectedDate;
            }

            prayerRequest.CampusId   = cpCampus.SelectedCampusId;
            prayerRequest.CategoryId = catpCategory.SelectedValueAsInt();

            // Now record all the bits...
            prayerRequest.IsApproved    = hfApprovedStatus.Value.AsBoolean();
            prayerRequest.IsActive      = cbIsActive.Checked;
            prayerRequest.IsUrgent      = cbIsUrgent.Checked;
            prayerRequest.AllowComments = cbAllowComments.Checked;
            prayerRequest.IsPublic      = cbIsPublic.Checked;
            prayerRequest.FirstName     = tbFirstName.Text;
            prayerRequest.LastName      = tbLastName.Text;
            prayerRequest.Email         = tbEmail.Text;
            prayerRequest.Text          = dtbText.Text.Trim();
            prayerRequest.Answer        = dtbAnswer.Text.Trim();

            prayerRequest.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributes, prayerRequest);

            if (!Page.IsValid)
            {
                return;
            }

            if (!prayerRequest.IsValid)
            {
                // field controls render error messages
                return;
            }

            rockContext.SaveChanges();
            prayerRequest.SaveAttributeValues(rockContext);

            var queryParms = new Dictionary <string, string>();

            if (!string.IsNullOrWhiteSpace(PageParameter("PersonId")))
            {
                queryParms.Add("PersonId", PageParameter("PersonId"));
            }

            NavigateToParentPage(queryParms);
        }
        public ActionResult RenderForm_PrayerPledges(string userName)
        {
            //Intsantiate list
            List <PrayerRequestModel> lstPrayers = new List <PrayerRequestModel>();


            try
            {
                //
                IMember member = Services.MemberService.GetByUsername(userName);
                if (member != null)
                {
                    //Instantiate list
                    List <_prayerRequest> lstJsonPrayersOffered = new List <_prayerRequest>();

                    //Populate list with any existing data
                    if (member.HasProperty(Common.NodeProperties.prayersOfferedFor) && member.GetValue(Common.NodeProperties.prayersOfferedFor) != null)
                    {
                        lstJsonPrayersOffered = JsonConvert.DeserializeObject <List <_prayerRequest> >(member.GetValue(Common.NodeProperties.prayersOfferedFor).ToString());
                    }

                    //
                    foreach (_prayerRequest prayerOffered in lstJsonPrayersOffered)
                    {
                        PrayerRequestModel prayerRequest = new PrayerRequestModel();
                        IPublishedContent  ipPrayer      = Umbraco.TypedContent(prayerOffered.prayer);

                        prayerRequest.Id          = ipPrayer.Id;
                        prayerRequest.date        = Convert.ToDateTime(prayerOffered.date);
                        prayerRequest.PrayerTitle = ipPrayer.GetPropertyValue <String>(PrayerRequest.GetModelPropertyType(x => x.PrayerTitle).PropertyTypeAlias);
                        prayerRequest.Url         = ipPrayer.Url;

                        lstPrayers.Add(prayerRequest);
                    }
                }
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(@"PrayerController.cs : RenderForm_PrayerPledges()");
                sb.AppendLine("userName:"******"model:" + Newtonsoft.Json.JsonConvert.SerializeObject(lstPrayers));
                Common.SaveErrorMessage(ex, sb, typeof(PrayerController));


                ModelState.AddModelError("", "*An error occured while...");
                return(CurrentUmbracoPage());
            }


            return(PartialView("~/Views/Partials/PrayerCorner/_prayerPledges.cshtml", lstPrayers));
        }
Exemple #48
0
        /// <summary>
        /// Handles the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            pnlRequester.Visible = this.ContextEntity <Rock.Model.Person>() == null;

            RockContext rockContext = new RockContext();

            this.EnableUrgentFlag        = GetAttributeValue("EnableUrgentFlag").AsBoolean();
            this.EnableCommentsFlag      = GetAttributeValue("EnableCommentsFlag").AsBoolean();
            this.EnablePublicDisplayFlag = GetAttributeValue("EnablePublicDisplayFlag").AsBoolean();
            tbLastName.Required          = GetAttributeValue("RequireLastName").AsBooleanOrNull() ?? true;

            RockPage.AddScriptLink(Page, ResolveUrl("~/Scripts/bootstrap-limit.js"));
            var categoryGuid = GetAttributeValue("GroupCategoryId");

            if (!string.IsNullOrEmpty(categoryGuid))
            {
                BindCategories(categoryGuid);

                // set the default category
                if (!string.IsNullOrWhiteSpace(GetAttributeValue("DefaultCategory")))
                {
                    Guid defaultCategoryGuid = GetAttributeValue("DefaultCategory").AsGuid();
                    var  defaultCategoryId   = CategoryCache.Read(defaultCategoryGuid, rockContext).Id;

                    bddlCategory.SetValue(defaultCategoryId);
                }
            }
            else
            {
                bddlCategory.Visible = false;
            }

            Type type = new PrayerRequest().GetType();

            this.PrayerRequestEntityTypeId = Rock.Web.Cache.EntityTypeCache.GetId(type.FullName);

            int charLimit = GetAttributeValue("CharacterLimit").AsInteger();

            if (charLimit > 0)
            {
                dtbRequest.Placeholder = string.Format("Please pray that... (up to {0} characters)", charLimit);
                string scriptFormat = @"
    function SetCharacterLimit() {{
        $('#{0}').limit({{maxChars: {1}, counter:'#{2}', normalClass:'badge', warningClass:'badge-warning', overLimitClass: 'badge-danger'}});

        $('#{0}').on('cross', function(){{
            $('#{3}').prop('disabled', true);
        }});
        $('#{0}').on('uncross', function(){{
            $('#{3}').prop('disabled', false);
        }});
    }};
    $(document).ready(function () {{ SetCharacterLimit(); }});
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(SetCharacterLimit);
";
                string script       = string.Format(scriptFormat, dtbRequest.ClientID, charLimit, lblCount.ClientID, lbSave.ClientID);
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), string.Format("limit-{0}", this.ClientID), script, true);
            }
        }
        /// <summary>
        /// Handles the Click event to save the prayer request.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!IsValid())
            {
                return;
            }

            bool isAutoApproved          = GetAttributeValue("EnableAutoApprove").AsBoolean();
            bool defaultAllowComments    = GetAttributeValue("DefaultAllowCommentsSetting").AsBoolean();
            bool isPersonMatchingEnabled = GetAttributeValue("EnablePersonMatching").AsBoolean();

            PrayerRequest prayerRequest = new PrayerRequest {
                Id = 0, IsActive = true, IsApproved = isAutoApproved, AllowComments = defaultAllowComments
            };

            var rockContext = new RockContext();

            prayerRequest.EnteredDateTime = RockDateTime.Now;

            if (isAutoApproved)
            {
                prayerRequest.ApprovedByPersonAliasId = CurrentPersonAliasId;
                prayerRequest.ApprovedOnDateTime      = RockDateTime.Now;
                var expireDays = Convert.ToDouble(GetAttributeValue("ExpireDays"));
                prayerRequest.ExpirationDate = RockDateTime.Now.AddDays(expireDays);
            }

            // Now record all the bits...
            // Make sure the Category is hydrated so it's included for any Lava processing
            Category category;
            int?     categoryId          = bddlCategory.SelectedValueAsInt();
            Guid     defaultCategoryGuid = GetAttributeValue("DefaultCategory").AsGuid();

            if (categoryId == null && !defaultCategoryGuid.IsEmpty())
            {
                category   = new CategoryService(rockContext).Get(defaultCategoryGuid);
                categoryId = category.Id;
            }
            else
            {
                category = new CategoryService(rockContext).Get(categoryId.Value);
            }

            prayerRequest.CategoryId = categoryId;
            prayerRequest.Category   = category;

            var personContext = this.ContextEntity <Person>();

            if (personContext == null)
            {
                Person person = null;
                if (isPersonMatchingEnabled)
                {
                    var personService = new PersonService(new RockContext());
                    person = personService.FindPerson(new PersonService.PersonMatchQuery(tbFirstName.Text, tbLastName.Text, tbEmail.Text, pnbPhone.Number), false, true, false);

                    if (person == null && (!string.IsNullOrWhiteSpace(tbEmail.Text) || !string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number))))
                    {
                        var personRecordTypeId  = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                        var personStatusPending = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id;

                        person                     = new Person();
                        person.IsSystem            = false;
                        person.RecordTypeValueId   = personRecordTypeId;
                        person.RecordStatusValueId = personStatusPending;
                        person.FirstName           = tbFirstName.Text;
                        person.LastName            = tbLastName.Text;
                        person.Gender              = Gender.Unknown;

                        if (!string.IsNullOrWhiteSpace(tbEmail.Text))
                        {
                            person.Email           = tbEmail.Text;
                            person.IsEmailActive   = true;
                            person.EmailPreference = EmailPreference.EmailAllowed;
                        }

                        PersonService.SaveNewPerson(person, rockContext, cpCampus.SelectedCampusId);

                        if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                        {
                            var mobilePhoneType = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE));

                            var phoneNumber = new PhoneNumber {
                                NumberTypeValueId = mobilePhoneType.Id
                            };
                            phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                            phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);
                            person.PhoneNumbers.Add(phoneNumber);
                        }
                    }
                }

                prayerRequest.FirstName = tbFirstName.Text;
                prayerRequest.LastName  = tbLastName.Text;
                prayerRequest.Email     = tbEmail.Text;
                if (person != null)
                {
                    prayerRequest.RequestedByPersonAliasId = person.PrimaryAliasId;
                }
                else
                {
                    prayerRequest.RequestedByPersonAliasId = CurrentPersonAliasId;
                }
            }
            else
            {
                prayerRequest.RequestedByPersonAliasId = personContext.PrimaryAliasId;
                prayerRequest.FirstName = string.IsNullOrEmpty(personContext.NickName) ? personContext.FirstName : personContext.NickName;
                prayerRequest.LastName  = personContext.LastName;
                prayerRequest.Email     = personContext.Email;
            }

            prayerRequest.CampusId = cpCampus.SelectedCampusId;

            prayerRequest.Text = dtbRequest.Text;

            if (this.EnableUrgentFlag)
            {
                prayerRequest.IsUrgent = cbIsUrgent.Checked;
            }
            else
            {
                prayerRequest.IsUrgent = false;
            }

            if (this.EnableCommentsFlag)
            {
                prayerRequest.AllowComments = cbAllowComments.Checked;
            }

            if (this.EnablePublicDisplayFlag)
            {
                prayerRequest.IsPublic = cbAllowPublicDisplay.Checked;
            }
            else
            {
                prayerRequest.IsPublic = this.DefaultToPublic;
            }

            if (!Page.IsValid)
            {
                return;
            }

            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);

            prayerRequestService.Add(prayerRequest);
            prayerRequest.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributes, prayerRequest);

            if (!prayerRequest.IsValid)
            {
                // field controls render error messages
                return;
            }

            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();
                prayerRequest.SaveAttributeValues(rockContext);
            });


            StartWorkflow(prayerRequest, rockContext);

            bool isNavigateToParent = GetAttributeValue("NavigateToParentOnSave").AsBoolean();

            if (isNavigateToParent)
            {
                NavigateToParentPage();
            }
            else if (GetAttributeValue("RefreshPageOnSave").AsBoolean())
            {
                NavigateToCurrentPage(this.PageParameters().Where(a => a.Value is string).ToDictionary(k => k.Key, v => v.Value.ToString()));
            }
            else
            {
                pnlForm.Visible    = false;
                pnlReceipt.Visible = true;

                // Build success text that is Lava capable
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                mergeFields.Add("PrayerRequest", prayerRequest);
                nbMessage.Text = GetAttributeValue("SaveSuccessText").ResolveMergeFields(mergeFields);

                // Resolve any dynamic url references
                string appRoot   = ResolveRockUrl("~/");
                string themeRoot = ResolveRockUrl("~~/");
                nbMessage.Text = nbMessage.Text.Replace("~~/", themeRoot).Replace("~/", appRoot);
            }
        }
        /// <summary>
        /// Shows the prayer request's detail.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        public void ShowDetail( string itemKey, int itemKeyValue )
        {
            if ( !itemKey.Equals( _prayerRequestKeyParameter ) )
            {
                return;
            }

            PrayerRequest prayerRequest;

            if ( !itemKeyValue.Equals( 0 ) )
            {
                prayerRequest = new PrayerRequestService().Get( itemKeyValue );
            }
            else
            {
                prayerRequest = new PrayerRequest { Id = 0, IsActive = true, IsApproved = true, AllowComments = true };
            }

            if ( prayerRequest == null )
                return;

            hfPrayerRequestId.Value = prayerRequest.Id.ToString();

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !IsUserAuthorized( "Edit" ) )
            {
                readOnly = true;
                nbEditModeMessage.Title = "Information";
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( PrayerRequest.FriendlyTypeName );
            }

            if ( readOnly )
            {
                lbEdit.Visible = false;
                ShowReadonlyDetails( prayerRequest );
            }
            else
            {
                if ( prayerRequest.Id > 0 )
                {
                    ShowReadonlyDetails( prayerRequest );
                }
                else
                {
                    ShowEditDetails( prayerRequest );
                }
            }
        }
        /// <summary>
        /// Handles the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            PrayerRequest prayerRequest = new PrayerRequest();
            Type type = prayerRequest.GetType();
            _prayerRequestEntityTypeId = Rock.Web.Cache.EntityTypeCache.GetId( type.FullName );

            BindFilter();

            gPrayerRequests.DataKeyNames = new string[] { "id" };
            gPrayerRequests.Actions.AddClick += gPrayerRequests_Add;
            gPrayerRequests.GridRebind += gPrayerRequests_GridRebind;

            // Block Security and special attributes (RockPage takes care of View)
            _canApprove = IsUserAuthorized( "Approve" );
            _canAddEditDelete = IsUserAuthorized( Authorization.EDIT );
            gPrayerRequests.Actions.ShowAdd = _canAddEditDelete;
            gPrayerRequests.IsDeleteEnabled = _canAddEditDelete;
        }
Exemple #52
0
 /// <summary>
 /// Binds all comments for the given prayer request.
 /// </summary>
 /// <param name="prayerRequest">a prayer request</param>
 private void ShowComments( PrayerRequest prayerRequest )
 {
     var notes = new List<Note>();
     notes = new NoteService().Get( (int)PrayerCommentNoteTypeId, prayerRequest.Id ).OrderBy( n => n.CreationDateTime ).ToList();
     lMeIconHtml.Text = GetPhotoUrl( CurrentPerson, cssClassName: "media-object" );
     rptComments.DataSource = notes;
     rptComments.DataBind();
 }
Exemple #53
0
 /// <summary>
 /// Shows the readonly details.
 /// </summary>
 /// <param name="prayerRequest">The prayer request.</param>
 private void ShowReadonlyDetails(PrayerRequest prayerRequest)
 {
     SetEditMode(false);
 }
 private void ShowReadonlyDetails( PrayerRequest prayerRequest )
 {
     SetEditMode( false );
 }
        /// <summary>
        /// Handles the Click event to save the prayer request.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!IsValid())
            {
                return;
            }

            bool isAutoApproved       = GetAttributeValue("EnableAutoApprove").AsBoolean();
            bool defaultAllowComments = GetAttributeValue("DefaultAllowCommentsSetting").AsBoolean();

            PrayerRequest prayerRequest = new PrayerRequest {
                Id = 0, IsActive = true, IsApproved = isAutoApproved, AllowComments = defaultAllowComments
            };

            var rockContext = new RockContext();
            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);

            prayerRequestService.Add(prayerRequest);
            prayerRequest.EnteredDateTime = RockDateTime.Now;

            if (isAutoApproved)
            {
                prayerRequest.ApprovedByPersonAliasId = CurrentPersonAliasId;
                prayerRequest.ApprovedOnDateTime      = RockDateTime.Now;
                var expireDays = Convert.ToDouble(GetAttributeValue("ExpireDays"));
                prayerRequest.ExpirationDate = RockDateTime.Now.AddDays(expireDays);
            }

            // Now record all the bits...
            int? categoryId          = bddlCategory.SelectedValueAsInt();
            Guid defaultCategoryGuid = GetAttributeValue("DefaultCategory").AsGuid();

            if (categoryId == null && !defaultCategoryGuid.IsEmpty())
            {
                var category = new CategoryService(rockContext).Get(defaultCategoryGuid);
                categoryId = category.Id;
            }

            prayerRequest.CategoryId = categoryId;
            prayerRequest.RequestedByPersonAliasId = CurrentPersonAliasId;
            prayerRequest.FirstName = dtbFirstName.Text;
            prayerRequest.LastName  = dtbLastName.Text;
            prayerRequest.Email     = dtbEmail.Text;
            prayerRequest.Text      = dtbRequest.Text;

            if (this.EnableUrgentFlag)
            {
                prayerRequest.IsUrgent = cbIsUrgent.Checked;
            }
            else
            {
                prayerRequest.IsUrgent = false;
            }

            if (this.EnableCommentsFlag)
            {
                prayerRequest.AllowComments = cbAllowComments.Checked;
            }

            if (this.EnablePublicDisplayFlag)
            {
                prayerRequest.IsPublic = cbAllowPublicDisplay.Checked;
            }
            else
            {
                prayerRequest.IsPublic = false;
            }

            if (!Page.IsValid)
            {
                return;
            }

            if (!prayerRequest.IsValid)
            {
                // field controls render error messages
                return;
            }

            rockContext.SaveChanges();

            bool isNavigateToParent = GetAttributeValue("NavigateToParentOnSave").AsBoolean();

            if (isNavigateToParent)
            {
                NavigateToParentPage();
            }
            else
            {
                pnlForm.Visible    = false;
                pnlReceipt.Visible = true;
            }
        }
Exemple #56
0
        /// <summary>
        /// Handles the Click event to save the prayer request.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!IsValid())
            {
                return;
            }

            bool isAutoApproved       = GetAttributeValue("EnableAutoApprove").AsBoolean();
            bool defaultAllowComments = GetAttributeValue("DefaultAllowCommentsSetting").AsBoolean();

            PrayerRequest prayerRequest = new PrayerRequest {
                Id = 0, IsActive = true, IsApproved = isAutoApproved, AllowComments = defaultAllowComments
            };

            var rockContext = new RockContext();
            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);

            prayerRequestService.Add(prayerRequest);
            prayerRequest.EnteredDateTime = RockDateTime.Now;

            if (isAutoApproved)
            {
                prayerRequest.ApprovedByPersonAliasId = CurrentPersonAliasId;
                prayerRequest.ApprovedOnDateTime      = RockDateTime.Now;
                var expireDays = Convert.ToDouble(GetAttributeValue("ExpireDays"));
                prayerRequest.ExpirationDate = RockDateTime.Now.AddDays(expireDays);
            }

            // Now record all the bits...
            // Make sure the Category is hydrated so it's included for any Lava processing
            Category category;
            int?     categoryId          = bddlCategory.SelectedValueAsInt();
            Guid     defaultCategoryGuid = GetAttributeValue("DefaultCategory").AsGuid();

            if (categoryId == null && !defaultCategoryGuid.IsEmpty())
            {
                category   = new CategoryService(rockContext).Get(defaultCategoryGuid);
                categoryId = category.Id;
            }
            else
            {
                category = new CategoryService(rockContext).Get(categoryId.Value);
            }

            prayerRequest.CategoryId = categoryId;
            prayerRequest.Category   = category;

            var personContext = this.ContextEntity <Person>();

            if (personContext == null)
            {
                prayerRequest.RequestedByPersonAliasId = CurrentPersonAliasId;
                prayerRequest.FirstName = tbFirstName.Text;
                prayerRequest.LastName  = tbLastName.Text;
                prayerRequest.Email     = tbEmail.Text;
            }
            else
            {
                prayerRequest.RequestedByPersonAliasId = personContext.PrimaryAliasId;
                prayerRequest.FirstName = string.IsNullOrEmpty(personContext.NickName) ? personContext.FirstName : personContext.NickName;
                prayerRequest.LastName  = personContext.LastName;
                prayerRequest.Email     = personContext.Email;
            }

            prayerRequest.Text = dtbRequest.Text;

            if (this.EnableUrgentFlag)
            {
                prayerRequest.IsUrgent = cbIsUrgent.Checked;
            }
            else
            {
                prayerRequest.IsUrgent = false;
            }

            if (this.EnableCommentsFlag)
            {
                prayerRequest.AllowComments = cbAllowComments.Checked;
            }

            if (this.EnablePublicDisplayFlag)
            {
                prayerRequest.IsPublic = cbAllowPublicDisplay.Checked;
            }
            else
            {
                prayerRequest.IsPublic = false;
            }

            if (!Page.IsValid)
            {
                return;
            }

            if (!prayerRequest.IsValid)
            {
                // field controls render error messages
                return;
            }

            rockContext.SaveChanges();

            StartWorkflow(prayerRequest, rockContext);

            bool isNavigateToParent = GetAttributeValue("NavigateToParentOnSave").AsBoolean();

            if (isNavigateToParent)
            {
                NavigateToParentPage();
            }
            else if (GetAttributeValue("RefreshPageOnSave").AsBoolean())
            {
                NavigateToCurrentPage(this.PageParameters().Where(a => a.Value is string).ToDictionary(k => k.Key, v => v.Value.ToString()));
            }
            else
            {
                pnlForm.Visible    = false;
                pnlReceipt.Visible = true;

                // Build success text that is Lava capable
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                mergeFields.Add("PrayerRequest", prayerRequest);
                nbMessage.Text = GetAttributeValue("SaveSuccessText").ResolveMergeFields(mergeFields);

                // Resolve any dynamic url references
                string appRoot   = ResolveRockUrl("~/");
                string themeRoot = ResolveRockUrl("~~/");
                nbMessage.Text = nbMessage.Text.Replace("~~/", themeRoot).Replace("~/", appRoot);

                // show liquid help for debug
                if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
                {
                    nbMessage.Text += mergeFields.lavaDebugInfo();
                }
            }
        }
        /// <summary>
        /// Handles the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
            this.BlockUpdated += PrayerRequestEntry_BlockUpdated;
            this.AddConfigurationUpdateTrigger(upAdd);

            pnlRequester.Visible = this.ContextEntity <Rock.Model.Person>() == null;

            RockContext rockContext = new RockContext();

            this.EnableUrgentFlag        = GetAttributeValue("EnableUrgentFlag").AsBoolean();
            this.EnableCommentsFlag      = GetAttributeValue("EnableCommentsFlag").AsBoolean();
            this.EnablePublicDisplayFlag = GetAttributeValue("EnablePublicDisplayFlag").AsBoolean();
            this.DefaultToPublic         = GetAttributeValue("DefaultToPublic").AsBoolean();
            tbLastName.Required          = GetAttributeValue("RequireLastName").AsBooleanOrNull() ?? true;
            cpCampus.Visible             = GetAttributeValue("ShowCampus").AsBoolean();
            cpCampus.Required            = GetAttributeValue("RequireCampus").AsBoolean();
            pnbPhone.Visible             = GetAttributeValue("EnablePersonMatching").AsBoolean();

            if (cpCampus.Visible)
            {
                cpCampus.Campuses = CampusCache.All(false);
            }

            var categoryGuid = GetAttributeValue("GroupCategoryId");

            if (!string.IsNullOrEmpty(categoryGuid))
            {
                BindCategories(categoryGuid);

                // set the default category
                if (!string.IsNullOrWhiteSpace(GetAttributeValue("DefaultCategory")))
                {
                    Guid defaultCategoryGuid = GetAttributeValue("DefaultCategory").AsGuid();
                    var  defaultCategoryId   = CategoryCache.Get(defaultCategoryGuid, rockContext).Id;

                    bddlCategory.SetValue(defaultCategoryId);
                }
            }
            else
            {
                bddlCategory.Visible = false;
            }

            Type type = new PrayerRequest().GetType();

            this.PrayerRequestEntityTypeId = EntityTypeCache.GetId(type.FullName);

            int charLimit = GetAttributeValue("CharacterLimit").AsInteger();

            if (charLimit > 0)
            {
                dtbRequest.Placeholder = string.Format("Please pray that... (up to {0} characters)", charLimit);
                string scriptFormat = @"
    function SetCharacterLimit() {{
        $('#{0}').limit({{maxChars: {1}, counter:'#{2}', normalClass:'badge', warningClass:'badge-warning', overLimitClass: 'badge-danger'}});

        $('#{0}').on('cross', function(){{
            $('#{3}').prop('disabled', true);
        }});
        $('#{0}').on('uncross', function(){{
            $('#{3}').prop('disabled', false);
        }});
    }};
    $(document).ready(function () {{ SetCharacterLimit(); }});
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(SetCharacterLimit);
";
                string script       = string.Format(scriptFormat, dtbRequest.ClientID, charLimit, lblCount.ClientID, lbSave.ClientID);
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), string.Format("limit-{0}", this.ClientID), script, true);
            }
        }
Exemple #58
0
        /// <summary>
        /// Displays the details for a single, given prayer request.
        /// </summary>
        /// <param name="prayerRequest"></param>
        /// <param name="service"></param>
        private void ShowPrayerRequest( PrayerRequest prayerRequest, PrayerRequestService service )
        {
            pnlPrayer.Visible = true;
            pPrayerAnswer.Visible = false;

            prayerRequest.PrayerCount = ( prayerRequest.PrayerCount ?? 0 ) + 1;
            hlblPrayerCountTotal.Text = prayerRequest.PrayerCount.ToString() + " team prayers";
            hlblUrgent.Visible = prayerRequest.IsUrgent ?? false;
            lTitle.Text = prayerRequest.FullName.FormatAsHtmlTitle();

            //lPrayerText.Text = prayerRequest.Text.EncodeHtmlThenConvertCrLfToHtmlBr();
            lPrayerText.Text = ScrubHtmlAndConvertCrLfToBr( prayerRequest.Text );
            hlblCategory.Text = prayerRequest.Category.Name;

            // Show their answer if there is one on the request.
            if ( !string.IsNullOrWhiteSpace( prayerRequest.Answer ) )
            {
                pPrayerAnswer.Visible = true;
                lPrayerAnswerText.Text = prayerRequest.Answer.EncodeHtmlThenConvertCrLfToHtmlBr();
            }

            // put the request's id in the hidden field in case it needs to be flagged.
            hfIdValue.SetValue( prayerRequest.Id );

            lPersonIconHtml.Text = GetPhotoUrl( prayerRequest.RequestedByPerson );

            pnlComments.Visible = prayerRequest.AllowComments ?? false;
            if ( rptComments.Visible )
            {
                ShowComments( prayerRequest );
            }

            // save because the prayer count was just modified.
            service.Save( prayerRequest, this.CurrentPersonId );
        }