コード例 #1
0
        /// <summary>
        /// Prays for the specified request and optionally launches a workflow
        /// and/or records an interaction.
        /// </summary>
        /// <param name="prayerRequestGuid">The prayer request unique identifier that is being prayed for.</param>
        /// <param name="currentPerson">The current person whom is performing the action.</param>
        /// <param name="launchWorkflowGuid">The workflow type unique identifier to be launched.</param>
        /// <param name="recordInteraction">If set to <c>true</c> then an interaction will be recorded.</param>
        /// <param name="interactionSummary">The interaction summary text.</param>
        /// <param name="userAgent">The user agent for the interaction.</param>
        /// <param name="clientIpAddress">The client IP address for the interaction.</param>
        /// <param name="sessionGuid">The session unique identifier for the interaction.</param>
        /// <exception cref="System.ArgumentNullException">prayerRequest</exception>
        private static bool PrayForRequest(Guid prayerRequestGuid, Person currentPerson, Guid?launchWorkflowGuid, bool recordInteraction, string interactionSummary, string userAgent, string clientIpAddress, Guid?sessionGuid)
        {
            using (var rockContext = new RockContext())
            {
                var prayerRequestService = new PrayerRequestService(rockContext);
                var prayerRequest        = prayerRequestService.Get(prayerRequestGuid);

                if (prayerRequest == null)
                {
                    return(false);
                }

                prayerRequest.PrayerCount = (prayerRequest.PrayerCount ?? 0) + 1;

                rockContext.SaveChanges();

                if (launchWorkflowGuid.HasValue)
                {
                    PrayerRequestService.LaunchPrayedForWorkflow(prayerRequest, launchWorkflowGuid.Value, currentPerson);
                }

                if (recordInteraction)
                {
                    PrayerRequestService.EnqueuePrayerInteraction(prayerRequest, currentPerson, interactionSummary, userAgent, clientIpAddress, sessionGuid);
                }

                return(true);
            }
        }
コード例 #2
0
        /// <summary>
        /// Handles the Click event of the lbPrevious 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 lbBack_Click(object sender, EventArgs e)
        {
            int index = hfPrayerIndex.ValueAsInt();

            index--;

            List <int> prayerRequestIds = (List <int>)Session[_sessionKey];
            int        currentNumber    = index + 1;

            if (currentNumber > 0)
            {
                UpdateSessionCountLabel(currentNumber, prayerRequestIds.Count);

                hfPrayerIndex.Value = index.ToString();
                var rockContext = new RockContext();
                PrayerRequestService service  = new PrayerRequestService(rockContext);
                int           prayerRequestId = prayerRequestIds[index];
                PrayerRequest request         = service.Queryable("RequestedByPersonAlias.Person").FirstOrDefault(p => p.Id == prayerRequestId);
                ShowPrayerRequest(request, rockContext);
            }
            else
            {
                lbBack.Visible = false;
            }
        }
コード例 #3
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)
        {
            if (!Page.IsPostBack)
            {
                ShowDetail(PageParameter("PrayerRequestId").AsInteger());
            }
            else
            {
                if (pnlEditDetails.Visible)
                {
                    var           rockContext = new RockContext();
                    PrayerRequest prayerRequest;
                    int?          prayerRequestId = PageParameter("PrayerRequestId").AsIntegerOrNull();
                    if (prayerRequestId.HasValue && prayerRequestId.Value > 0)
                    {
                        prayerRequest = new PrayerRequestService(rockContext).Get(prayerRequestId.Value);
                    }
                    else
                    {
                        prayerRequest = new PrayerRequest {
                            Id = 0
                        };
                    }

                    prayerRequest.LoadAttributes();
                    phAttributes.Controls.Clear();
                    var excludeForEdit = prayerRequest.Attributes.Where(a => !a.Value.IsAuthorized(Authorization.EDIT, this.CurrentPerson)).Select(a => a.Key).ToList();
                    Rock.Attribute.Helper.AddEditControls(prayerRequest, phAttributes, false, BlockValidationGroup, excludeForEdit);
                }
            }

            base.OnLoad(e);
        }
コード例 #4
0
        /// <summary>
        /// Creates a Linq Expression that can be applied to an IQueryable to filter the result set.
        /// </summary>
        /// <param name="entityType">The type of entity in the result set.</param>
        /// <param name="serviceInstance">A service instance that can be queried to obtain the result set.</param>
        /// <param name="parameterExpression">The input parameter that will be injected into the filter expression.</param>
        /// <param name="selection">A formatted string representing the filter settings.</param>
        /// <returns>
        /// A Linq Expression that can be used to filter an IQueryable.
        /// </returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            var settings = new FilterSettings(selection);

            var context = (RockContext)serviceInstance.Context;

            //
            // Define Candidate People.
            //

            var dataView = DataComponentSettingsHelper.GetDataViewForFilterComponent(settings.PersonDataViewGuid, context);

            var personService = new PersonService(context);

            var personQuery = personService.Queryable();

            if (dataView != null)
            {
                personQuery = DataComponentSettingsHelper.FilterByDataView(personQuery, dataView, personService);
            }

            var personKeys = personQuery.Select(x => x.Id);

            //
            // Construct the Query to return the list of Prayer Requests matching the filter conditions.
            //
            var prayerRequestQuery = new PrayerRequestService(context).Queryable();

            prayerRequestQuery = prayerRequestQuery.Where(p => personKeys.Contains(p.RequestedByPersonAlias.PersonId));

            var result = FilterExpressionExtractor.Extract <Rock.Model.PrayerRequest>(prayerRequestQuery, parameterExpression, "p");

            return(result);
        }
コード例 #5
0
        /// <summary>
        /// Handles the edit Click event of the lbEdit 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 lbEdit_Click(object sender, EventArgs e)
        {
            PrayerRequestService service = new PrayerRequestService(new RockContext());
            PrayerRequest        item    = service.Get(hfPrayerRequestId.ValueAsInt());

            ShowEditDetails(item);
        }
コード例 #6
0
        /// <summary>
        /// Binds all comments for the given prayer request Id.
        /// </summary>
        /// <param name="prayerRequestId">the id of a prayer request</param>
        private void ShowComments(int prayerRequestId)
        {
            PrayerRequestService prayerRequestService = new PrayerRequestService();
            var prayerRequest = prayerRequestService.Get(prayerRequestId);

            ShowComments(prayerRequest);
        }
コード例 #7
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)
        {
            RockTransactionScope.WrapTransaction(() =>
            {
                PrayerRequestService prayerRequestService = new PrayerRequestService();
                PrayerRequest prayerRequest = prayerRequestService.Get((int)e.RowKeyValue);

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

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

                    prayerRequestService.Delete(prayerRequest, CurrentPersonId);
                    prayerRequestService.Save(prayerRequest, CurrentPersonId);
                }
            });

            BindGrid();
        }
コード例 #8
0
        /// <summary>
        /// Finds all approved prayer requests for the given selected categories and orders them by least prayed-for.
        /// Also updates the prayer count for the first item in the list.
        /// </summary>
        /// <param name="categoriesList"></param>
        private void SetAndDisplayPrayerRequests(RockCheckBoxList categoriesList)
        {
            RockContext          rockContext = new RockContext();
            PrayerRequestService service     = new PrayerRequestService(rockContext);
            var prayerRequestQuery           = service.GetByCategoryIds(categoriesList.SelectedValuesAsInt);

            var campusId = cpCampus.SelectedValueAsInt();

            if (campusId.HasValue)
            {
                prayerRequestQuery = prayerRequestQuery.Where(a => a.CampusId == campusId);
            }

            var limitToPublic = GetAttributeValue(PUBLIC_ONLY).AsBoolean();

            if (limitToPublic)
            {
                prayerRequestQuery = prayerRequestQuery.Where(a => a.IsPublic.HasValue && a.IsPublic.Value);
            }

            var        prayerRequests = prayerRequestQuery.OrderByDescending(p => p.IsUrgent).ThenBy(p => p.PrayerCount).ToList();
            List <int> list           = prayerRequests.Select(p => p.Id).ToList <int>();

            PrayerRequestIds = list;
            if (list.Count > 0)
            {
                UpdateSessionCountLabel(1, list.Count);
                hfPrayerIndex.Value = "0";
                PrayerRequest request = prayerRequests.First();
                ShowPrayerRequest(request, rockContext);
            }
        }
コード例 #9
0
ファイル: CampusesFilter.cs プロジェクト: ewin66/rockrms
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            var rockContext = (RockContext)serviceInstance.Context;

            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 1)
            {
                var        campusGuidList = selectionValues[0].Split(',').AsGuidList();
                List <int> campusIds      = new List <int>();
                foreach (var campusGuid in campusGuidList)
                {
                    var campus = CampusCache.Get(campusGuid);
                    if (campus != null)
                    {
                        campusIds.Add(campus.Id);
                    }
                }

                if (!campusIds.Any())
                {
                    return(null);
                }

                var qry = new PrayerRequestService((RockContext)serviceInstance.Context).Queryable()
                          .Where(p => campusIds.Contains(p.CampusId ?? 0));

                Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.PrayerRequest>(qry, parameterExpression, "p");

                return(extractedFilterExpression);
            }

            return(null);
        }
コード例 #10
0
        /// <summary>
        /// Creates the prayer request.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="person">The person.</param>
        private void CreatePrayerRequest(RockContext rockContext, Person person)
        {
            if (person != null && !tbPrayerRequests.Text.IsNullOrWhiteSpace())
            {
                PrayerRequest prayerRequest = new PrayerRequest();
                prayerRequest.RequestedByPersonAliasId = person.PrimaryAliasId;
                prayerRequest.FirstName = person.NickName;
                prayerRequest.LastName  = person.LastName;
                prayerRequest.Text      = tbPrayerRequests.Text;
                prayerRequest.Email     = person.Email;

                Category category;
                Guid     defaultCategoryGuid = GetAttributeValue("PrayerCategory").AsGuid();
                if (!defaultCategoryGuid.IsEmpty())
                {
                    category = new CategoryService(rockContext).Get(defaultCategoryGuid);
                    prayerRequest.CategoryId = category.Id;
                    prayerRequest.Category   = category;
                }

                prayerRequest.IsPublic = false;

                PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);
                prayerRequestService.Add(prayerRequest);
                prayerRequest.EnteredDateTime = RockDateTime.Now;
                rockContext.SaveChanges();
            }
        }
コード例 #11
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);
        }
コード例 #12
0
        //private DateTime _TestPeriodEndDate = new DateTime( 2019, 3, 31 );

        /// <summary>
        /// Performs the initialization required for tests in this class to execute.
        /// </summary>
        /// <param name="context"></param>
        //[ClassInitialize]
        //public static void Initialize( TestContext context )
        //{
        //}

        protected override void OnValidateTestData(out bool isValid, out string stateMessage)
        {
            try
            {
                // Verify that the necessary test data exists by retrieving a well-known test record.
                var dataContext = GetNewDataContext();

                var prayerRequestService = new PrayerRequestService(dataContext);

                var testEntryId = prayerRequestService.GetId(TestGuids.PrayerRequestGuid.AllChurchForEmployment.AsGuid());

                if (testEntryId == null)
                {
                    throw new Exception("Prayer Request test data is either incomplete or does not exist in this database.");
                }

                isValid      = true;
                stateMessage = null;
            }
            catch (Exception ex)
            {
                isValid      = false;
                stateMessage = ex.Message;
            }
        }
コード例 #13
0
        /// <summary>
        /// Creates a Linq Expression that can be applied to an IQueryable to filter the result set.
        /// </summary>
        /// <param name="entityType">The type of entity in the result set.</param>
        /// <param name="serviceInstance">A service instance that can be queried to obtain the result set.</param>
        /// <param name="parameterExpression">The input parameter that will be injected into the filter expression.</param>
        /// <param name="selection">A formatted string representing the filter settings.</param>
        /// <returns>
        /// A Linq Expression that can be used to filter an IQueryable.
        /// </returns>
        /// <exception cref="System.Exception">Filter issue(s):  + errorMessages.AsDelimited( ;  )</exception>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            var settings = new FilterSettings(selection);

            var context = (RockContext)serviceInstance.Context;

            // Get the Prayer Request Data View.
            var dataView = DataComponentSettingsHelper.GetDataViewForFilterComponent(settings.DataViewGuid, context);

            // Evaluate the Data View that defines the Person's Prayer Request.
            var prayerRequestService = new PrayerRequestService(context);

            var prayerRequestQuery = prayerRequestService.Queryable();

            if (dataView != null)
            {
                prayerRequestQuery = DataComponentSettingsHelper.FilterByDataView(prayerRequestQuery, dataView, prayerRequestService);
            }

            var prayerRequestPersonsKey = prayerRequestQuery.Select(a => a.RequestedByPersonAliasId);
            // Get all of the Person corresponding to the qualifying Prayer Requests.
            var qry = new PersonService(context).Queryable()
                      .Where(g => g.Aliases.Any(k => prayerRequestPersonsKey.Contains(k.Id)));

            // Retrieve the Filter Expression.
            var extractedFilterExpression = FilterExpressionExtractor.Extract <Model.Person>(qry, parameterExpression, "g");

            return(extractedFilterExpression);
        }
コード例 #14
0
        /// <summary>
        /// Handler that gets the next prayer request and updates its prayer count.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbNext_Click(object sender, EventArgs e)
        {
            int index = hfPrayerIndex.ValueAsInt();

            index++;

            List <int> prayerRequestIds = (List <int>)Session[_sessionKey];
            int        currentNumber    = index + 1;

            if (currentNumber <= prayerRequestIds.Count)
            {
                UpdateSessionCountLabel(currentNumber, prayerRequestIds.Count);

                hfPrayerIndex.Value = index.ToString();
                PrayerRequestService service = new PrayerRequestService();
                PrayerRequest        request = service.Get(prayerRequestIds[index]);
                ShowPrayerRequest(request, service);
            }
            else
            {
                pnlFinished.Visible = true;
                pnlPrayer.Visible   = false;
                lbStartAgain.Focus();
            }
        }
コード例 #15
0
        /// <summary>
        /// Handler that gets the next prayer request and updates its prayer count.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbNext_Click(object sender, EventArgs e)
        {
            int index = hfPrayerIndex.ValueAsInt();

            index++;

            List <int> prayerRequestIds = this.PrayerRequestIds;
            int        currentNumber    = index + 1;

            if ((prayerRequestIds != null) && (currentNumber <= prayerRequestIds.Count))
            {
                UpdateSessionCountLabel(currentNumber, prayerRequestIds.Count);

                hfPrayerIndex.Value = index.ToString();
                var rockContext = new RockContext();
                PrayerRequestService service  = new PrayerRequestService(rockContext);
                int           prayerRequestId = prayerRequestIds[index];
                PrayerRequest request         = service.Queryable("RequestedByPersonAlias.Person").FirstOrDefault(p => p.Id == prayerRequestId);
                ShowPrayerRequest(request, rockContext);
            }
            else
            {
                pnlFinished.Visible = true;
                pnlPrayer.Visible   = false;
                lbStartAgain.Focus();
            }

            lbBack.Visible = true;
        }
コード例 #16
0
ファイル: PrayerSession.cs プロジェクト: waldo2590/Rock
        /// <summary>
        /// Gets the prayer requests for the new session.
        /// </summary>
        /// <returns>An enumerable of <see cref="PrayerRequest"/> objects.</returns>
        protected virtual IEnumerable <PrayerRequest> GetPrayerRequests(RockContext rockContext)
        {
            var prayerRequestService = new PrayerRequestService(rockContext);
            var category             = CategoryCache.Get(PrayerCategory);

            if (category == null)
            {
                return(null);
            }

            var query = prayerRequestService.GetByCategoryIds(new List <int> {
                category.Id
            });

            if (PublicOnly)
            {
                query = query.Where(a => a.IsPublic.HasValue && a.IsPublic.Value);
            }

            if (MyCampus)
            {
                var campusId = RequestContext.CurrentPerson?.PrimaryCampusId;

                if (campusId.HasValue)
                {
                    query = query.Where(a => a.CampusId.HasValue && a.CampusId == campusId);
                }
            }

            query = query.OrderByDescending(a => a.IsUrgent)
                    .ThenBy(a => a.PrayerCount);

            return(query);
        }
コード例 #17
0
        /// <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();
                NavigateToParentPage();
            }
        }
コード例 #18
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)
        {
            if (!Page.IsPostBack)
            {
                ShowDetail(PageParameter("prayerRequestId").AsInteger());
            }
            else
            {
                if (pnlEditDetails.Visible)
                {
                    var           rockContext = new RockContext();
                    PrayerRequest prayerRequest;
                    int?          prayerRequestId = PageParameter("prayerRequestId").AsIntegerOrNull();
                    if (prayerRequestId.HasValue && prayerRequestId.Value > 0)
                    {
                        prayerRequest = new PrayerRequestService(rockContext).Get(prayerRequestId.Value);
                    }
                    else
                    {
                        prayerRequest = new PrayerRequest {
                            Id = 0
                        };
                    }

                    prayerRequest.LoadAttributes();
                    phAttributes.Controls.Clear();
                    Rock.Attribute.Helper.AddEditControls(prayerRequest, phAttributes, false, BlockValidationGroup);
                }
            }

            base.OnLoad(e);
        }
コード例 #19
0
        /// <summary>
        /// Gets the last prayed details.
        /// </summary>
        /// <param name="prayerRequests">The prayer requests.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns>A collection of last prayed details.</returns>
        private List <PrayerRequestLastPrayedDetail> GetLastPrayedDetails(List <PrayerRequest> prayerRequests, RockContext rockContext)
        {
            var prayerRequestService   = new PrayerRequestService(rockContext);
            var prayerRequestIds       = prayerRequests.Select(r => r.Id).ToList();
            var lastPrayedInteractions = prayerRequestService.GetLastPrayedDetails(prayerRequestIds);

            return(lastPrayedInteractions.ToList());
        }
コード例 #20
0
ファイル: CategorySelect.cs プロジェクト: waldo2590/Rock
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entityIdProperty">The entity identifier property.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(RockContext context, MemberExpression entityIdProperty, string selection)
        {
            var prayerRequestQuery = new PrayerRequestService(context).Queryable()
                                     .Select(p => p.Category.Name);

            var selectExpression = SelectExpressionExtractor.Extract(prayerRequestQuery, entityIdProperty, "p");

            return(selectExpression);
        }
コード例 #21
0
        /// <summary>
        /// Saves the prayer request.
        /// </summary>
        private void SaveRequest()
        {
            PrayerRequest        prayerRequest;
            PrayerRequestService prayerRequestService = new PrayerRequestService();

            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, CurrentPersonId);
                prayerRequest.EnteredDate = DateTime.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.ApprovedOnDate     = DateTime.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;
                }
            }
            // 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.CategoryId    = cpCategory.SelectedValueAsInt();
            prayerRequest.FirstName     = tbFirstName.Text;
            prayerRequest.LastName      = tbLastName.Text;
            prayerRequest.Text          = tbText.Text;
            prayerRequest.Answer        = tbAnswer.Text;

            if (!Page.IsValid)
            {
                return;
            }

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

            prayerRequestService.Save(prayerRequest, CurrentPersonId);

            NavigateToParentPage();
        }
コード例 #22
0
        /// <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;

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

            if (CampusCache.All(false).Count() > 1)
            {
                hlblCampus.Text = prayerRequest.CampusId.HasValue ? prayerRequest.Campus.Name : string.Empty;
            }

            hlblCategory.Text = prayerRequest.Category.Name;
            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new Rock.Lava.CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            });

            // need to load attributes so that lava can loop thru PrayerRequest.Attributes
            prayerRequest.LoadAttributes();

            // Filter to only show attribute / attribute values that the person is authorized to view.
            var excludeForView = prayerRequest.Attributes.Where(a => !a.Value.IsAuthorized(Authorization.VIEW, this.CurrentPerson)).Select(a => a.Key).ToList();

            prayerRequest.Attributes      = prayerRequest.Attributes.Where(a => !excludeForView.Contains(a.Key)).ToDictionary(k => k.Key, k => k.Value);
            prayerRequest.AttributeValues = prayerRequest.AttributeValues.Where(av => !excludeForView.Contains(av.Key)).ToDictionary(k => k.Key, k => k.Value);

            mergeFields.Add("PrayerRequest", prayerRequest);
            string prayerPersonLava  = this.GetAttributeValue(AttributeKey.PrayerPersonLava);
            string prayerDisplayLava = this.GetAttributeValue(AttributeKey.PrayerDisplayLava);

            lPersonLavaOutput.Text = prayerPersonLava.ResolveMergeFields(mergeFields);
            lPrayerLavaOutput.Text = prayerDisplayLava.ResolveMergeFields(mergeFields);

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

            CurrentPrayerRequestId = prayerRequest.Id;

            if (GetAttributeValue(AttributeKey.CreateInteractionsForPrayers).AsBoolean())
            {
                PrayerRequestService.EnqueuePrayerInteraction(prayerRequest, CurrentPerson, PageCache.Layout.Site.Name, Request.UserAgent, RockPage.GetClientIpAddress(), RockPage.Session["RockSessionId"]?.ToString().AsGuidOrNull());
            }

            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);
            }
        }
コード例 #23
0
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var rockContext = new RockContext();

            var noteTypeService = new NoteTypeService(rockContext);
            var noteType        = noteTypeService.Get(Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid());

            // TODO log exception if noteType is null

            var noteService    = new NoteService(rockContext);
            var prayerComments = noteService.GetByNoteTypeId(noteType.Id);

            SortProperty sortProperty = gPrayerComments.SortProperty;

            if (_blockInstancePrayerRequestCategoryGuid.HasValue)
            {
                // if filtered by category, only show comments for prayer requests in that category or any of its decendent categories
                var categoryService = new CategoryService(rockContext);

                if (_blockInstancePrayerRequestCategoryGuid.HasValue)
                {
                    var categories = new CategoryService(rockContext).GetAllDescendents(_blockInstancePrayerRequestCategoryGuid.Value).Select(a => a.Id).ToList();

                    var prayerRequestQry = new PrayerRequestService(rockContext).Queryable().Where(a => a.CategoryId.HasValue &&
                                                                                                   (a.Category.Guid == _blockInstancePrayerRequestCategoryGuid.Value || categories.Contains(a.CategoryId.Value)))
                                           .Select(a => a.Id);

                    prayerComments = prayerComments.Where(a => a.EntityId.HasValue && prayerRequestQry.Contains(a.EntityId.Value));
                }
            }

            // Filter by Date Range
            if (drpDateRange.LowerValue.HasValue)
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerComments = prayerComments.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate);
            }

            if (drpDateRange.UpperValue.HasValue)
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays(1);
                prayerComments = prayerComments.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate);
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if (sortProperty != null)
            {
                gPrayerComments.DataSource = prayerComments.Sort(sortProperty).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderBy(n => n.CreatedDateTime).ToList();
            }

            gPrayerComments.DataBind();
        }
コード例 #24
0
        /// <summary>
        /// Handles the edit Click event of the lbEdit 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 lbEdit_Click(object sender, EventArgs e)
        {
            int           prayerRequestId = hfPrayerRequestId.ValueAsInt();
            PrayerRequest item            = new PrayerRequestService(new RockContext())
                                            .Queryable("RequestedByPersonAlias.Person,ApprovedByPersonAlias.Person")
                                            .FirstOrDefault(p => p.Id == prayerRequestId);

            ShowEditDetails(item);
        }
コード例 #25
0
        /// <summary>
        /// Saves the prayer request.
        /// </summary>
        /// <param name="answer">The answer text.</param>
        /// <returns>
        /// The response to send back to the client.
        /// </returns>
        private CallbackResponse SaveRequest(string answer)
        {
            using (var rockContext = new RockContext())
            {
                var           prayerRequestService = new PrayerRequestService(rockContext);
                PrayerRequest prayerRequest        = null;
                var           requestGuid          = RequestContext.GetPageParameter(PageParameterKeys.RequestGuid).AsGuidOrNull();

                if (requestGuid.HasValue)
                {
                    prayerRequest = new PrayerRequestService(rockContext).Get(requestGuid.Value);
                }

                if (prayerRequest == null)
                {
                    return(new CallbackResponse
                    {
                        Error = "We couldn't find that prayer request."
                    });
                }

                var canEdit = prayerRequest.RequestedByPersonAlias != null && prayerRequest.RequestedByPersonAlias.PersonId == RequestContext.CurrentPerson?.Id;

                if (!BlockCache.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson) && !canEdit)
                {
                    return(new CallbackResponse
                    {
                        Error = "You are not authorized to edit prayer requests."
                    });
                }

                prayerRequest.Answer = answer;

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

            if (ReturnPageGuid.HasValue)
            {
                return(new CallbackResponse
                {
                    Command = "ReplacePage",
                    CommandParameter = ReturnPageGuid.Value.ToString()
                });
            }
            else
            {
                return(new CallbackResponse
                {
                    Command = "PopPage",
                    CommandParameter = "true"
                });
            }
        }
コード例 #26
0
ファイル: PrayerSession.cs プロジェクト: waldo2590/Rock
        /// <summary>
        /// Builds the content to be shown.
        /// </summary>
        /// <param name="context">The session context.</param>
        /// <returns>
        /// A string containing the XAML content.
        /// </returns>
        protected virtual string BuildContent(string context = null)
        {
            var            template    = Template;
            var            mergeFields = RequestContext.GetCommonMergeFields();
            SessionContext sessionContext;
            PrayerRequest  request;
            var            rockContext = new RockContext();

            if (context.IsNotNullOrWhiteSpace())
            {
                var prayerRequestService = new PrayerRequestService(rockContext);

                sessionContext = Security.Encryption.DecryptString(context).FromJsonOrNull <SessionContext>();

                //
                // Update the prayer count on the last prayer request.
                //
                var lastRequest = prayerRequestService.Get(sessionContext.RequestIds[sessionContext.Index]);
                lastRequest.PrayerCount = (lastRequest.PrayerCount ?? 0) + 1;
                rockContext.SaveChanges();

                //
                // Move to the next prayer request, or else indicate that we have
                // finished this session.
                //
                sessionContext.Index += 1;
                if (sessionContext.RequestIds.Count > sessionContext.Index)
                {
                    var requestId = sessionContext.RequestIds[sessionContext.Index];
                    request = prayerRequestService.Get(requestId);
                }
                else
                {
                    request = null;
                }
            }
            else
            {
                var query = GetPrayerRequests(rockContext);

                sessionContext = new SessionContext
                {
                    RequestIds = query.Select(a => a.Id).ToList()
                };

                request = query.FirstOrDefault();
            }

            mergeFields.Add("PrayedButtonText", PrayedButtonText);
            mergeFields.Add("ShowFollowButton", ShowFollowButton);
            mergeFields.Add("ShowInappropriateButton", ShowInappropriateButton);
            mergeFields.Add("SessionContext", Security.Encryption.EncryptString(sessionContext.ToJson()));
            mergeFields.Add("Request", request);

            return(template.ResolveMergeFields(mergeFields));
        }
コード例 #27
0
        /// <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)
            {
                bool isPublic = GetAttributeValue("DefaultToPublic").AsBoolean();
                prayerRequest = new PrayerRequest {
                    Id = 0, IsPublic = isPublic, IsActive = true, IsApproved = true, AllowComments = GetAttributeValue("DefaultAllowCommentsChecked").AsBooleanOrNull() ?? 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;
                lbDelete.Visible = false;
                ShowReadonlyDetails(prayerRequest);
            }
            else
            {
                if (prayerRequest.Id > 0)
                {
                    ShowReadonlyDetails(prayerRequest);
                }
                else
                {
                    ShowEditDetails(prayerRequest);
                }
            }
        }
コード例 #28
0
        /// <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()
        {
            using (var rockContext = new RockContext())
            {
                Guid?         requestGuid = RequestContext.GetPageParameter(PageParameterKeys.RequestGuid).AsGuidOrNull();
                PrayerRequest request     = null;

                if (requestGuid.HasValue)
                {
                    request = new PrayerRequestService(rockContext).Get(requestGuid.Value);
                }

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

                var canEdit = request.RequestedByPersonAlias != null && request.RequestedByPersonAlias.PersonId == RequestContext.CurrentPerson?.Id;

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

                var mergeFields = RequestContext.GetCommonMergeFields();
                mergeFields.AddOrReplace("PrayerRequest", request);
                var prayerRequestXaml = Template.ResolveMergeFields(mergeFields, RequestContext.CurrentPerson);

                return($@"
<StackLayout StyleClass=""prayerdetail"">
    {prayerRequestXaml}

    <Rock:FieldContainer>
        <Rock:TextEditor x:Name=""tbAnswer"" IsRequired=""True"" MinimumHeightRequest=""80"" AutoSize=""TextChanges"" Placeholder=""My answer to prayer is...""
            Text=""{request.Answer.ToStringSafe().EncodeXml( true )}"" />
    </Rock:FieldContainer>

    <Rock:Validator x:Name=""vForm"">
        <x:Reference>tbAnswer</x:Reference>
    </Rock:Validator>
    
    <Rock:NotificationBox x:Name=""nbError"" NotificationType=""Warning"" />
    
    <Button StyleClass=""btn,btn-primary,save-button"" Text=""Save"" Command=""{{Binding Callback}}"">
        <Button.CommandParameter>
            <Rock:CallbackParameters Name="":SaveAnswer"" Validator=""{{x:Reference vForm}}"" Notification=""{{x:Reference nbError}}"">
                <Rock:Parameter Name=""answer"" Value=""{{Binding Text, Source={{x:Reference tbAnswer}}}}"" />
            </Rock:CallbackParameters>
        </Button.CommandParameter>
    </Button>

    <Button StyleClass=""btn,btn-link,cancel-button"" Text=""Cancel"" Command=""{{Binding PopPage}}"" />
</StackLayout>");
            }
        }
コード例 #29
0
        /// <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(new RockContext()).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(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);
                }
            }
        }
コード例 #30
0
        /// <summary>
        /// Binds the grid to a list of Prayer Requests.
        /// </summary>
        private void BindGrid()
        {
            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);
            SortProperty         sortProperty         = gPrayerRequests.SortProperty;

            var prayerRequests = prayerRequestService.Queryable().Select(a =>
                                                                         new
            {
                a.Id,
                Person       = a.RequestedByPersonAlias != null ? a.RequestedByPersonAlias.Person : null,
                CategoryName = a.CategoryId.HasValue ? a.Category.Name : null,
                EnteredDate  = a.EnteredDateTime,
                a.Text,
                a.CategoryId,
                CategoryParentCategoryId = a.CategoryId.HasValue ? a.Category.ParentCategoryId : null
            });

            // Filter by prayer category if one is selected...
            int selectedPrayerCategoryID = catpPrayerCategoryFilter.SelectedValue.AsIntegerOrNull() ?? All.Id;

            if (selectedPrayerCategoryID != All.Id && selectedPrayerCategoryID != None.Id)
            {
                prayerRequests = prayerRequests.Where(c => c.CategoryId == selectedPrayerCategoryID ||
                                                      c.CategoryParentCategoryId == selectedPrayerCategoryID);
            }

            // Filter by Date Range
            if (drpDateRange.LowerValue.HasValue)
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerRequests = prayerRequests.Where(a => a.EnteredDate >= startDate);
            }

            if (drpDateRange.UpperValue.HasValue)
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays(1);
                prayerRequests = prayerRequests.Where(a => a.EnteredDate < endDate);
            }


            if (sortProperty != null)
            {
                gPrayerRequests.SetLinqDataSource(prayerRequests.Sort(sortProperty));
            }
            else
            {
                gPrayerRequests.SetLinqDataSource(prayerRequests.OrderByDescending(p => p.EnteredDate).ThenByDescending(p => p.Id));
            }

            gPrayerRequests.EntityTypeId = EntityTypeCache.Read <PrayerRequest>().Id;
            gPrayerRequests.ExportSource = ExcelExportSource.ColumnOutput;
            gPrayerRequests.DataBind();
        }