コード例 #1
0
        /// <summary>
        /// Raises 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);

            pCategory.EntityTypeId = EntityTypeCache.GetId(typeof(Rock.Model.Schedule)) ?? 0;

            rFilter.ApplyFilterClick   += rFilter_ApplyFilterClick;
            rFilter.DisplayFilterValue += rFilter_DisplayFilterValue;
            BindFilter();

            gGroupLocationSchedule.DataKeyNames    = new string[] { "GroupLocationId" };
            gGroupLocationSchedule.Actions.ShowAdd = false;
            gGroupLocationSchedule.IsDeleteEnabled = false;
            gGroupLocationSchedule.GridRebind     += gGroupLocationSchedule_GridRebind;

            //
            // First section of the script sets the default state of the header checkbox based
            // on if all item row checkboxes are checked. Second section handles toggling all
            // check boxes when the user clicks the header checkbox.
            //
            string script = string.Format(@"
    Sys.Application.add_load(function () {{
        var $table = $('#{0}');
        function updateHeaderCheckboxes()
        {{
            $table.find('thead > tr > th').each(function (columnIndex) {{
                if ($(this).find('a.fa').length > 0) {{
                    columnIndex += 1;
                    var $cbs = $table.find('tbody > tr > td:nth-child(' + columnIndex + ') input');
                    if ($cbs.length == $cbs.filter(':checked').length) {{
                        $(this).find('a.fa').addClass('fa-check-square-o').removeClass('fa-square-o');
                    }}
                    else {{
                        $(this).find('a.fa').addClass('fa-square-o').removeClass('fa-check-square-o');
                    }}
                }}
            }});
        }}
        updateHeaderCheckboxes();
        $table.find('tbody > tr > td input[type=""checkbox""]').click(function () {{ updateHeaderCheckboxes(); }});
        $('.js-sched-select-all').click(function (e) {{
            e.preventDefault();
            var $th = $(this).closest('th');
            var $table = $(this).closest('table');
            var columnIndex = $th.parent().children().index($th) + 1;
            var $cbs = $table.find('tbody > tr > td:nth-child(' + columnIndex + ') input');
            if ($(this).hasClass('fa-square-o')) {{
                $(this).addClass('fa-check-square-o').removeClass('fa-square-o');
                $cbs.prop('checked', true);
            }} else {{
                $(this).addClass('fa-square-o').removeClass('fa-check-square-o');
                $cbs.prop('checked', false);
            }}
        }});
    }});
", gGroupLocationSchedule.ClientID);

            ScriptManager.RegisterStartupScript(gGroupLocationSchedule, gGroupLocationSchedule.GetType(), "grid-sched-select-all", script, true);
        }
コード例 #2
0
        /// <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>();

            var personGuid = GetAttributeValue(action, "Person", true).AsGuidOrNull();

            if (personGuid == null)
            {
                errorMessages.Add("Person Add History requires a valid person");
                return(false);
            }

            var categoryGuid = GetAttributeValue(action, "Category").AsGuid();
            var category     = new CategoryService(rockContext).Get(categoryGuid);

            if (category == null)
            {
                errorMessages.Add("Person Add History requires a valid category");
                return(false);
            }

            PersonAliasService personAliasService = new PersonAliasService(rockContext);
            var personAlias = personAliasService.Get(personGuid.Value);

            if (personAlias != null)
            {
                var            person               = personAlias.Person;
                var            entityTypeId         = EntityTypeCache.GetId(typeof(Rock.Model.Person));
                var            workflowEntityTypeId = EntityTypeCache.GetId(typeof(Rock.Model.Workflow));
                var            mergeFields          = GetMergeFields(action);
                var            caption              = GetAttributeValue(action, "Caption").ResolveMergeFields(mergeFields);
                var            summary              = GetAttributeValue(action, "Summary").ResolveMergeFields(mergeFields);
                var            verb           = GetAttributeValue(action, "Verb").ResolveMergeFields(mergeFields);
                HistoryService historyService = new HistoryService(rockContext);
                History        history        = new History
                {
                    Caption      = caption,
                    Summary      = summary,
                    Verb         = verb,
                    EntityId     = person.Id,
                    EntityTypeId = entityTypeId.Value,
                    CategoryId   = category.Id
                };
                if (action?.Activity?.Workflow != null && action.Activity.WorkflowId != 0)
                {
                    history.RelatedEntityTypeId = workflowEntityTypeId;
                    history.RelatedEntityId     = action.Activity.WorkflowId;
                }
                historyService.Add(history);
                rockContext.SaveChanges();

                return(true);
            }
            else
            {
                errorMessages.Add("Person Add History requires a valid person");
                return(false);
            }
        }
コード例 #3
0
        /// <summary>
        /// Binds the group members grid.
        /// </summary>
        protected void BindGroupMembersGrid()
        {
            var rockContext = new RockContext();

            int groupId           = hfGroupId.Value.AsInteger();
            var groupMembersQuery = new GroupMemberService(rockContext).Queryable().Where(a => a.GroupId == groupId);
            var group             = new GroupService(rockContext).Get(groupId);

            group.LoadAttributes(rockContext);
            var defaultIndividualFundRaisingGoal = group.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull();

            groupMembersQuery = groupMembersQuery.Sort(gGroupMembers.SortProperty ?? new SortProperty {
                Property = "Person.LastName, Person.NickName"
            });

            var entityTypeIdGroupMember = EntityTypeCache.GetId <Rock.Model.GroupMember>();

            var groupMemberList = groupMembersQuery.ToList().Select(a =>
            {
                var groupMember = a;
                groupMember.LoadAttributes(rockContext);

                var contributionTotal = new FinancialTransactionDetailService(rockContext).Queryable()
                                        .Where(d => d.EntityTypeId == entityTypeIdGroupMember &&
                                               d.EntityId == groupMember.Id)
                                        .Sum(d => (decimal?)d.Amount) ?? 0.00M;

                var individualFundraisingGoal          = groupMember.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull();
                bool disablePublicContributionRequests = groupMember.GetAttributeValue("DisablePublicContributionRequests").AsBoolean();
                if (!individualFundraisingGoal.HasValue)
                {
                    individualFundraisingGoal = group.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull();
                }

                var fundingRemaining = individualFundraisingGoal - contributionTotal;
                if (disablePublicContributionRequests)
                {
                    fundingRemaining = null;
                }
                else if (fundingRemaining < 0)
                {
                    fundingRemaining = 0.00M;
                }

                return(new
                {
                    groupMember.Id,
                    PersonId = groupMember.PersonId,
                    DateTimeAdded = groupMember.DateTimeAdded,
                    groupMember.Person.FullName,
                    groupMember.Person.Gender,
                    FundingRemaining = fundingRemaining,
                    GroupRoleName = a.GroupRole.Name
                });
            }).ToList();

            gGroupMembers.DataSource = groupMemberList;
            gGroupMembers.DataBind();
        }
コード例 #4
0
        /// <summary>
        /// Deletes any related entities that reference the specified entity
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void DeleteRelatedEntities(T entity)
        {
            var relatedEntityService       = new RelatedEntityService(this.Context as RockContext);
            var sourceOrTargetEntityTypeId = EntityTypeCache.GetId <T>();
            var relatedEntityRecords       = relatedEntityService.Queryable().Where(a => (a.SourceEntityTypeId == sourceOrTargetEntityTypeId && a.SourceEntityId == entity.Id) || (a.TargetEntityTypeId == sourceOrTargetEntityTypeId && a.TargetEntityId == entity.Id)).ToList();

            relatedEntityService.DeleteRange(relatedEntityRecords);
        }
コード例 #5
0
ファイル: NoteTypeService.cs プロジェクト: waldo2590/Rock
        /// <summary>
        /// Gets the approvers.
        /// </summary>
        /// <param name="noteTypeId">The note type identifier.</param>
        /// <returns></returns>
        public List <Person> GetApprovers(int noteTypeId)
        {
            var rockContext        = this.Context as RockContext;
            var groupMemberService = new GroupMemberService(rockContext);

            var noteType             = NoteTypeCache.Get(noteTypeId);
            int?noteTypeEntityTypeId = EntityTypeCache.GetId <NoteType>();

            if (!noteTypeEntityTypeId.HasValue || noteType == null)
            {
                // shouldn't happen
                return(new List <Person>());
            }

            var authService = new AuthService(rockContext);

            var approvalAuths = authService.GetAuths(noteTypeEntityTypeId.Value, noteTypeId, Rock.Security.Authorization.APPROVE);

            // Get a list of all PersonIds that are allowed that are included in the Auths
            // Then, when we get a list of all the allowed people that are in the auth as a specific Person or part of a Role (Group), we'll run all those people thru NoteType.IsAuthorized
            // That way, we don't have to figure out all the logic of Allow/Deny based on Order, etc
            List <int> authPersonIdListAll  = new List <int>();
            var        approvalAuthsAllowed = approvalAuths.Where(a => a.AllowOrDeny == "A").ToList();

            foreach (var approvalAuth in approvalAuthsAllowed)
            {
                var personId = approvalAuth.PersonAlias?.PersonId;
                if (personId.HasValue)
                {
                    authPersonIdListAll.Add(personId.Value);
                }
                else if (approvalAuth.GroupId.HasValue)
                {
                    var groupPersonIdsQuery = groupMemberService.Queryable().Where(a => a.GroupId == approvalAuth.GroupId.Value && a.GroupMemberStatus == GroupMemberStatus.Active && a.Person.IsDeceased == false).Select(a => a.PersonId);
                    authPersonIdListAll.AddRange(groupPersonIdsQuery.ToList());
                }
                else if (approvalAuth.SpecialRole != SpecialRole.None)
                {
                    // Not Supported: Get people that belong to Special Roles like AllUsers, AllAuthenticatedUser, and AllUnAuthenicatedUsers doesn't really make sense, so ignore it
                }
            }

            authPersonIdListAll = authPersonIdListAll.Distinct().ToList();

            var authPersonsAll      = new PersonService(rockContext).Queryable().Where(a => authPersonIdListAll.Contains(a.Id)).ToList();
            var authorizedApprovers = new List <Person>();

            // now that we have a list of all people that have at least one Allow auth, run them thru noteType.IsAuthorized, to get rid of people that would have been excluded due to a Deny auth
            foreach (var authPerson in authPersonsAll)
            {
                if (noteType.IsAuthorized(Rock.Security.Authorization.APPROVE, authPerson))
                {
                    authorizedApprovers.Add(authPerson);
                }
            }

            return(authorizedApprovers);
        }
コード例 #6
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);

            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, "~/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 = 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);
            }
        }
コード例 #7
0
        /// <summary>
        /// Gets the <see cref="RelatedEntity.PurposeKey"/>s that are in the database where the SourceEntityType is T and has the specified Id.
        /// </summary>
        /// <param name="entityId">The entity identifier.</param>
        /// <returns>IQueryable&lt;System.String&gt;.</returns>
        public IQueryable <string> GetUsedPurposeKeys(int entityId)
        {
            var sourceEntityTypeId = EntityTypeCache.GetId <T>() ?? 0;

            var usedPurposeKeys = new RelatedEntityService(this.Context as RockContext).Queryable()
                                  .Where(a => a.SourceEntityId == entityId && a.SourceEntityTypeId == sourceEntityTypeId).Select(a => a.PurposeKey).Distinct();

            return(usedPurposeKeys);
        }
コード例 #8
0
        /// <summary>
        /// Binds the filter.
        /// </summary>
        private void BindFilter()
        {
            cpCategoryFilter.EntityTypeId = EntityTypeCache.GetId <Rock.Model.Schedule>() ?? 0;
            cpCategoryFilter.SetValue(fSchedules.GetUserPreference(GridUserPreferenceKey.Category).AsIntegerOrNull());
            cpCategoryFilter.Visible = !this.GetAttributeValue(AttributeKey.FilterCategoryFromQueryString).AsBoolean();
            var itemActiveStatus = fSchedules.GetUserPreference(GridUserPreferenceKey.ActiveStatus);

            ddlActiveFilter.SetValue(itemActiveStatus);
        }
コード例 #9
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext         = new RockContext();
            var mediaAccountService = new MediaAccountService(rockContext);

            // Use AsNoTracking() since these records won't be modified, and therefore don't need to be tracked by the EF change tracker
            var qry = mediaAccountService.Queryable().AsNoTracking();

            // name filter
            string nameFilter = gfAccounts.GetUserPreference(UserPreferenceKey.Name);

            if (!string.IsNullOrEmpty(nameFilter))
            {
                qry = qry.Where(account => account.Name.Contains(nameFilter));
            }

            Guid?accountTypeGuid = gfAccounts.GetUserPreference(UserPreferenceKey.AccountType).AsGuidOrNull();

            if (accountTypeGuid.HasValue)
            {
                qry = qry.Where(l => l.ComponentEntityType.Guid.Equals(accountTypeGuid.Value));
            }

            bool showInactiveAccounts = gfAccounts.GetUserPreference(UserPreferenceKey.IncludeInactive).AsBoolean();

            if (!showInactiveAccounts)
            {
                qry = qry.Where(s => s.IsActive == true);
            }

            var selectQry = qry
                            .Select(a => new
            {
                a.Id,
                a.Name,
                Type = a.ComponentEntityType,
                a.LastRefreshDateTime,
                Folders = a.MediaFolders.Count,
                Videos  = a.MediaFolders.SelectMany(b => b.MediaElements).Count()
            });

            var sortProperty = gAccountList.SortProperty;

            if (gAccountList.AllowSorting && sortProperty != null)
            {
                qry = qry.Sort(sortProperty);
            }
            else
            {
                qry = qry.OrderBy(a => a.Name);
            }

            gAccountList.EntityTypeId = EntityTypeCache.GetId <MediaAccount>();
            gAccountList.DataSource   = selectQry.ToList();
            gAccountList.DataBind();
        }
コード例 #10
0
        /// <summary>
        /// Binds the report grid.
        /// </summary>
        private void BindReportGrid()
        {
            var    rockContext   = new RockContext();
            var    reportService = new ReportService(rockContext);
            var    reportGuid    = this.GetAttributeValue("Report").AsGuidOrNull();
            var    personIdField = this.GetAttributeValue("PersonIdField");
            Report report        = null;

            if (reportGuid.HasValue)
            {
                report = reportService.Get(reportGuid.Value);
            }

            if (report == null)
            {
                nbConfigurationWarning.Visible = true;
                nbConfigurationWarning.Text    = "A report needs to be configured in block settings";
                pnlView.Visible = false;
            }
            else if (report.DataView == null)
            {
                nbConfigurationWarning.Visible = true;
                nbConfigurationWarning.Text    = string.Format("The {0} report does not have a dataview", report);
                pnlView.Visible = false;
            }
            else
            {
                nbConfigurationWarning.Visible = false;

                report.DataView.DataViewFilter = ReportingHelper.GetFilterFromControls(phFilters);

                string errorMessage;

                ReportingHelper.BindGrid(report, gReport, this.CurrentPerson, null, out errorMessage);

                if (report.EntityTypeId != EntityTypeCache.GetId <Rock.Model.Person>())
                {
                    var personColumn = gReport.ColumnsOfType <BoundField>().Where(a => a.HeaderText == personIdField).FirstOrDefault();
                    if (personColumn != null)
                    {
                        gReport.PersonIdField = personColumn.SortExpression;
                    }
                }

                if (!string.IsNullOrWhiteSpace(errorMessage))
                {
                    nbReportErrors.NotificationBoxType = NotificationBoxType.Warning;
                    nbReportErrors.Text    = errorMessage;
                    nbReportErrors.Visible = true;
                }
                else
                {
                    nbReportErrors.Visible = false;
                }
            }
        }
コード例 #11
0
        private void UpdateAttributes()
        {
            var type = this.GetType();

            using (var rockContext = new RockContext())
            {
                Rock.Attribute.Helper.UpdateAttributes(type, EntityTypeCache.GetId(type.FullName), rockContext);
                this.LoadAttributes(rockContext);
            }
        }
コード例 #12
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();

            gLinkList.EntityTypeId = EntityTypeCache.GetId <PersonalLink>();
            var dataList = GetDataGridList(rockContext);

            gLinkList.DataSource = dataList;
            gLinkList.DataBind();
        }
コード例 #13
0
        /// <summary>
        /// Deletes the relationship between the relatedEntity and the entity for the given QualifierValue.
        /// </summary>
        /// <typeparam name="TT">The type of the t.</typeparam>
        /// <param name="entityId">The entity identifier.</param>
        /// <param name="relatedEntity">The related entity.</param>
        /// <param name="purposeKey">The purpose key.</param>
        /// <param name="qualifierValue">The qualifier value.</param>
        public void DeleteRelatedToSourceEntity <TT>(int entityId, TT relatedEntity, string purposeKey, string qualifierValue) where TT : IEntity
        {
            var relatedEntityTypeId = EntityTypeCache.GetId <TT>();
            var sourceEntityTypeId  = EntityTypeCache.GetId <T>();

            var relatedEntityService = new Rock.Model.RelatedEntityService(this.Context as RockContext);
            var relatedEntityRecords = relatedEntityService.GetRelatedEntityRecordsToSource(entityId, sourceEntityTypeId.Value, relatedEntityTypeId.Value, purposeKey, qualifierValue);

            relatedEntityService.DeleteRange(relatedEntityRecords);
        }
コード例 #14
0
ファイル: DragDropPage.cs プロジェクト: secc/RockPlugins
 public override void ConfigureCoursePage(CoursePage coursePage, List <Control> controls)
 {
     if (controls.Count > 0)
     {
         var widgityControl = ( WidgityControl )controls[0];
         widgityControl.EntityTypeId = EntityTypeCache.GetId(typeof(CoursePage)).Value;
         widgityControl.EntityGuid   = coursePage.Guid;
         widgityControl.Publish();
     }
 }
コード例 #15
0
        /// <inheritdoc/>
        public override Dictionary <int, List <int> > GetAlternateEntityIdsByType(RockContext rockContext)
        {
            // Return all of the EventCalendarItems on which this event item occurs.
            var entitiesByType = new Dictionary <int, List <int> >
            {
                { EntityTypeCache.GetId(typeof(EventCalendarItem)) ?? 0, this.EventCalendarItems.Select(c => c.Id).ToList() }
            };

            return(entitiesByType);
        }
コード例 #16
0
        /// <summary>
        /// Shows the settings.
        /// </summary>
        protected override void ShowSettings()
        {
            pnlSettings.Visible = true;

            ddlTransactionType.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_TYPE.AsGuid()).Id;

            DefinedValueCache blockTransactionType = null;
            Guid?blockTransactionTypeGuid          = this.GetAttributeValue("TransactionTypeGuid").AsGuidOrNull();

            if (blockTransactionTypeGuid.HasValue)
            {
                blockTransactionType = DefinedValueCache.Get(blockTransactionTypeGuid.Value);
            }

            ddlTransactionType.SetValue(blockTransactionType != null ? blockTransactionType.Id : ( int? )null);

            var rockContext = new RockContext();

            gtpGroupType.GroupTypes = new GroupTypeService(rockContext).Queryable().OrderBy(a => a.Order).ThenBy(a => a.Name).AsNoTracking().ToList();
            ddlDefinedTypePicker.Items.Clear();
            ddlDefinedTypePicker.Items.Add(new ListItem());
            var definedTypesList = new DefinedTypeService(rockContext).Queryable().OrderBy(a => a.Name)
                                   .Select(a => new
            {
                a.Id,
                a.Name
            }).ToList();

            foreach (var definedType in definedTypesList)
            {
                ddlDefinedTypePicker.Items.Add(new ListItem(definedType.Name, definedType.Id.ToString()));
            }

            var entityTypeGuid          = this.GetAttributeValue("EntityTypeGuid").AsGuidOrNull();
            var entityTypeIdGroupMember = EntityTypeCache.GetId <GroupMember>();

            etpEntityType.EntityTypes = new EntityTypeService(rockContext).Queryable().Where(a => (a.IsEntity && a.SingleValueFieldTypeId.HasValue) || (a.Id == entityTypeIdGroupMember)).OrderBy(t => t.FriendlyName).AsNoTracking().ToList();

            if (entityTypeGuid.HasValue)
            {
                var entityType = EntityTypeCache.Get(entityTypeGuid.Value);
                etpEntityType.SetValue(entityType != null ? entityType.Id : ( int? )null);
            }

            UpdateControlsForEntityType();

            tbEntityTypeQualifierColumn.Text = this.GetAttributeValue("EntityTypeQualifierColumn");

            gtpGroupType.SetValue(this.GetAttributeValue("EntityTypeQualifierValue"));
            cbLimitToActiveGroups.Checked = this.GetAttributeValue("LimitToActiveGroups").AsBoolean();
            ddlDefinedTypePicker.SetValue(this.GetAttributeValue("EntityTypeQualifierValue"));
            tbEntityTypeQualifierValue.Text = this.GetAttributeValue("EntityTypeQualifierValue");

            mdSettings.Show();
        }
コード例 #17
0
        /// <summary>
        /// Handles the SelectedIndexChanged event of the contentChannelTypePicker control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        public void contentChannelTypePicker_SelectedIndexChanged(object sender, EventArgs e)
        {
            RockDropDownList     contentChannelTypePicker = sender as RockDropDownList;
            DynamicControlsPanel containerControl         = contentChannelTypePicker.Parent as DynamicControlsPanel;
            FilterField          filterControl            = containerControl.FirstParentControlOfType <FilterField>();

            containerControl.Controls.Clear();
            containerControl.Controls.Add(contentChannelTypePicker);

            // Create the field selection dropdown
            var ddlProperty = new RockDropDownList();

            ddlProperty.ID = string.Format("{0}_{1}_ddlProperty", containerControl.ID, contentChannelTypePicker.SelectedValue.AsInteger());
            ddlProperty.Attributes["EntityTypeId"] = EntityTypeCache.GetId <Rock.Model.ContentChannelItem>().ToString();
            containerControl.Controls.Add(ddlProperty);

            // add Empty option first
            ddlProperty.Items.Add(new ListItem());

            var entityFields = GetContentChannelItemAttributes(contentChannelTypePicker.SelectedValue.AsIntegerOrNull());

            foreach (var entityField in entityFields)
            {
                string controlId = string.Format("{0}_{1}", containerControl.ID, entityField.UniqueName);
                var    control   = entityField.FieldType.Field.FilterControl(entityField.FieldConfig, controlId, true, filterControl.FilterMode);
                if (control != null)
                {
                    // Add the field to the dropdown of available fields
                    if (AttributeCache.Get(entityField.AttributeGuid.Value)?.EntityTypeQualifierColumn == "ContentChannelTypeId")
                    {
                        ddlProperty.Items.Add(new ListItem(entityField.TitleWithoutQualifier, entityField.UniqueName));
                    }
                    else
                    {
                        ddlProperty.Items.Add(new ListItem(entityField.Title, entityField.UniqueName));
                    }

                    containerControl.Controls.Add(control);
                }
            }

            ddlProperty.AutoPostBack = true;

            // grab the currently selected value off of the request params since we are creating the controls after the Page Init
            var selectedValue = ddlProperty.Page.Request.Params[ddlProperty.UniqueID];

            if (selectedValue != null)
            {
                ddlProperty.SelectedValue = selectedValue;
                ddlProperty_SelectedIndexChanged(ddlProperty, new EventArgs());
            }

            ddlProperty.SelectedIndexChanged += ddlProperty_SelectedIndexChanged;
        }
コード例 #18
0
        private static List <Rock.Model.Communication> CreateCommunications(int sender, CommunicationStatus communicationStatus, DateTime?reviewedDateTime, DateTime?futureSendDateTime, bool AddPendingRecipient, int?listGroupId)
        {
            // Create communication with no recipients.
            var communicationNoReciepients = new Rock.Model.Communication
            {
                Name = $"Test Communication {Guid.NewGuid()}",
                FutureSendDateTime  = futureSendDateTime,
                ListGroupId         = listGroupId,
                Message             = $"Test Communication {Guid.NewGuid()}",
                Subject             = $"Test Communication {Guid.NewGuid()}",
                FromEmail           = "*****@*****.**",
                CommunicationType   = CommunicationType.Email,
                SenderPersonAliasId = sender,
                IsBulkCommunication = false,
                Status           = communicationStatus,
                ReviewedDateTime = reviewedDateTime
            };

            // Create communication with recipients.
            var communicationReciepients = new Rock.Model.Communication
            {
                Name = $"Test Communication {Guid.NewGuid()}",
                FutureSendDateTime  = futureSendDateTime,
                ListGroupId         = listGroupId,
                Message             = $"Test Communication {Guid.NewGuid()}",
                Subject             = $"Test Communication {Guid.NewGuid()}",
                FromEmail           = "*****@*****.**",
                CommunicationType   = CommunicationType.Email,
                SenderPersonAliasId = sender,
                IsBulkCommunication = false,
                Status           = communicationStatus,
                ReviewedDateTime = reviewedDateTime
            };

            foreach (CommunicationRecipientStatus communicationRecipientStatus in Enum.GetValues(typeof(CommunicationRecipientStatus)))
            {
                if (!AddPendingRecipient && communicationRecipientStatus == CommunicationRecipientStatus.Pending)
                {
                    continue;
                }
                communicationReciepients.Recipients.Add(new CommunicationRecipient
                {
                    Status             = communicationRecipientStatus,
                    PersonAliasId      = GetNewPersonAlias(),
                    MediumEntityTypeId = EntityTypeCache.GetId(SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL)
                });
            }

            return(new List <Rock.Model.Communication>
            {
                communicationNoReciepients,
                communicationReciepients
            });
        }
コード例 #19
0
        /// <summary>
        /// Get a History query related to Person.ConnectionStatus property change.
        /// </summary>
        /// <param name="startDate">The start date.</param>
        /// <param name="endDate">The end date.</param>
        /// <param name="originalConnectionStatusId">The original connection status identifier.</param>
        /// <param name="updatedConnectionStatusId">The updated connection status identifier.</param>
        /// <returns></returns>
        private IQueryable <History> GetHistoryQueryBase(DateTime?startDate, DateTime?endDate, int?originalConnectionStatusId, int?updatedConnectionStatusId)
        {
            var historyService = new HistoryService(_DataContext);

            var personEntityTypeId = EntityTypeCache.GetId <Person>();

            var categoryId = CategoryCache.GetId(SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid());

            // Get History records related to Person.ConnectionStatus property change.
            var historyEntriesBaseQuery = historyService.Queryable()
                                          .AsNoTracking()
                                          .Where(x => x.CategoryId == categoryId &&
                                                 x.EntityTypeId == personEntityTypeId &&
                                                 x.ChangeType == "Property" &&
                                                 x.ValueName == "Connection Status");

            // Filter by Date
            // Note: History.CreatedDateTime is used to store the occurence date of the event.
            //       This is inconsistent with the primary use of this field as an audit field.
            //       The data model should be adjusted by moving this data to a new field "EventDateTime".
            if (startDate != null)
            {
                var compareStartDate = startDate.Value;

                historyEntriesBaseQuery = historyEntriesBaseQuery.Where(x => x.CreatedDateTime > compareStartDate);
            }

            if (endDate != null)
            {
                var compareEndDate = endDate.Value.AddDays(1).AddMilliseconds(-1);

                historyEntriesBaseQuery = historyEntriesBaseQuery.Where(x => x.CreatedDateTime < compareEndDate);
            }

            // Filter by Original Connection Status.
            if (originalConnectionStatusId.GetValueOrDefault(0) != 0)
            {
                // Attempt to find a match by StatusId in OldRawValue (Rock v1.9 or higher), or by name in OldValue (Rock v1.8 or lower).
                var statusName = this.GetConnectionStatusNameOrDefault(originalConnectionStatusId.GetValueOrDefault(0), string.Empty);

                historyEntriesBaseQuery = historyEntriesBaseQuery.Where(x => x.OldRawValue == originalConnectionStatusId.ToString() || x.OldValue == statusName);
            }

            // Filter by Updated Connection Status.
            if (updatedConnectionStatusId.GetValueOrDefault(0) != 0)
            {
                // Attempt to find a match by StatusId in OldRawValue (Rock v1.9 or higher), or by name in OldValue (Rock v1.8 or lower).
                var statusName = this.GetConnectionStatusNameOrDefault(updatedConnectionStatusId.GetValueOrDefault(0), string.Empty);

                historyEntriesBaseQuery = historyEntriesBaseQuery.Where(x => x.NewRawValue == updatedConnectionStatusId.ToString() || x.NewValue == statusName);
            }

            return(historyEntriesBaseQuery);
        }
コード例 #20
0
        // used for private variables

        #endregion

        #region Properties

        // used for public / protected properties

        #endregion

        #region Base Control Methods

        //  overrides of the base RockBlock methods (i.e. OnInit, OnLoad)

        /// <summary>
        /// Raises 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);
            gList.GridRebind += gList_GridRebind;

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

            dvDataView.EntityTypeId = EntityTypeCache.GetId(typeof(Person));
        }
コード例 #21
0
        /// <summary>
        /// Initialize the results grid.
        /// </summary>
        private void InitializeGrid()
        {
            gChanges.DataKeyNames    = new string[] { "Id" };
            gChanges.Actions.ShowAdd = false;
            gChanges.GridRebind     += gChanges_GridRebind;
            gChanges.RowDataBound   += gChanges_RowDataBound;
            gChanges.PersonIdField   = "PersonId";

            gChanges.EntityTypeId = EntityTypeCache.GetId <Person>();

            gChanges.RowItemText = "Connection Status Change";
        }
コード例 #22
0
ファイル: DragDropPage.cs プロジェクト: secc/RockPlugins
 public override void ConfigureControls(CoursePage coursePage, List <Control> controls)
 {
     if (controls.Count > 0)
     {
         var widgityControl = ( WidgityControl )controls[0];
         widgityControl.EntityTypeId       = EntityTypeCache.GetId(typeof(CoursePage)).Value;
         widgityControl.EntityGuid         = coursePage.Guid;
         widgityControl.ShowPublishButtons = false;
         widgityControl.DataBind();
         widgityControl.ShowSettings();
     }
 }
コード例 #23
0
        private void DisplaySettings()
        {
            RockContext      rockContext      = new RockContext();
            EntitySetService entitySetService = new EntitySetService(rockContext);
            var entitySet        = entitySetService.Get(PageParameter("EntitySetId").AsInteger());
            var workflowEntityId = EntityTypeCache.GetId(typeof(Rock.Model.Workflow));

            if (entitySet == null || entitySet.EntityTypeId != workflowEntityId)
            {
                return;
            }

            WorkflowService workflowService = new WorkflowService(rockContext);

            var workflowQueryable = workflowService.Queryable();

            var workflows = entitySet.Items
                            .Join(workflowQueryable,
                                  i => i.EntityId,
                                  w => w.Id,
                                  (i, w) => w);

            var firstWorkflow = workflows.FirstOrDefault();

            if (firstWorkflow == null)
            {
                return;
            }

            var workflowTypeId = firstWorkflow.WorkflowTypeId;

            AttributeService attributeService = new AttributeService(rockContext);

            var attributes = attributeService.Queryable()
                             .Where(a => a.EntityTypeId == workflowEntityId &&
                                    a.EntityTypeQualifierColumn == "WorkflowTypeId" &&
                                    a.EntityTypeQualifierValue == workflowTypeId.ToString())
                             .OrderBy(a => a.Order)
                             .ToList();

            rAttributes.DataSource = attributes;
            rAttributes.DataBind();

            var workflowActivityTypes = firstWorkflow.WorkflowType.ActivityTypes;

            ddlActivities.DataSource = workflowActivityTypes;
            ddlActivities.DataBind();
            ddlActivities.Items.Insert(0, new ListItem());

            hfCount.Value            = workflows.Count().ToString();
            hfWorkflowTypeName.Value = firstWorkflow.WorkflowType.Name;
            nbNotification.Text      = string.Format("Updating {0} {1} workflows.", workflows.Count(), firstWorkflow.WorkflowType.Name);
        }
コード例 #24
0
        /// <summary>
        /// Handles the SelectedIndexChanged event of the ddlGroup control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            var ddlGroup = sender as RockDropDownList;

            if (ddlGroup != null)
            {
                if (_transactionEntityType.Id == EntityTypeCache.GetId <GroupMember>())
                {
                    LoadGroupMembersDropDown(ddlGroup);
                }
            }
        }
コード例 #25
0
        /// <summary>
        /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e)
        {
            if (_transactionEntityType != null)
            {
                if (_transactionEntityType.Id == EntityTypeCache.GetId <GroupMember>())
                {
                    foreach (var ddlGroupMember in phTableRows.ControlsOfTypeRecursive <RockDropDownList>().Where(a => a.ID.StartsWith("ddlGroupMember_")))
                    {
                        int?financialTransactionDetailId = ddlGroupMember.ID.Replace("ddlGroupMember_", string.Empty).AsInteger();
                        var dllGroup      = phTableRows.ControlsOfTypeRecursive <RockDropDownList>().Where(a => a.ID == "ddlGroup_" + financialTransactionDetailId.Value.ToString());
                        int?groupMemberId = ddlGroupMember.SelectedValue.AsIntegerOrNull();
                        AssignEntityToTransactionDetail(groupMemberId, financialTransactionDetailId);
                    }
                }
                else if (_transactionEntityType.Id == EntityTypeCache.GetId <Group>())
                {
                    foreach (var ddlGroup in phTableRows.ControlsOfTypeRecursive <RockDropDownList>().Where(a => a.ID.StartsWith("ddlGroup_")))
                    {
                        int?financialTransactionDetailId = ddlGroup.ID.Replace("ddlGroup_", string.Empty).AsInteger();
                        int?groupId = ddlGroup.SelectedValue.AsIntegerOrNull();
                        AssignEntityToTransactionDetail(groupId, financialTransactionDetailId);
                    }
                }
                else if (_transactionEntityType.Id == EntityTypeCache.GetId <DefinedValue>())
                {
                    foreach (var ddlDefinedValue in phTableRows.ControlsOfTypeRecursive <DefinedValuePicker>().Where(a => a.ID.StartsWith("ddlDefinedValue_")))
                    {
                        int?financialTransactionDetailId = ddlDefinedValue.ID.Replace("ddlDefinedValue_", string.Empty).AsInteger();
                        int?definedValueId = ddlDefinedValue.SelectedValue.AsIntegerOrNull();
                        AssignEntityToTransactionDetail(definedValueId, financialTransactionDetailId);
                    }
                }
                else if (_transactionEntityType.SingleValueFieldType != null)
                {
                    foreach (var entityPicker in phTableRows.ControlsOfTypeRecursive <Control>().Where(a => a.ID != null && a.ID.StartsWith("entityPicker_")))
                    {
                        var entityFieldType = _transactionEntityType.SingleValueFieldType.Field as IEntityFieldType;
                        if (entityFieldType != null)
                        {
                            int?financialTransactionDetailId = entityPicker.ID.Replace("entityPicker_", string.Empty).AsIntegerOrNull();
                            if (financialTransactionDetailId.HasValue)
                            {
                                int?entityId = entityFieldType.GetEditValueAsEntityId(entityPicker, new Dictionary <string, ConfigurationValue>());
                                AssignEntityToTransactionDetail(entityId, financialTransactionDetailId);
                            }
                        }
                    }
                }
            }

            nbSaveSuccess.Visible = true;
        }
コード例 #26
0
        /// <summary>
        /// Deletes a RelatedEntity for the given source entity, target entity, purpose key, and qualifier value.
        /// </summary>
        /// <typeparam name="TT">The type of the t.</typeparam>
        /// <param name="entityId">The entity identifier.</param>
        /// <param name="targetEntity">The target entity.</param>
        /// <param name="purposeKey">The purpose key.</param>
        /// <param name="qualifierValue">The qualifier value.</param>
        public void DeleteTargetEntityFromSourceEntity <TT>(int entityId, TT targetEntity, string purposeKey, string qualifierValue = null) where TT : IEntity
        {
            var relatedEntityTypeId = EntityTypeCache.GetId <TT>();
            var sourceEntityTypeId  = EntityTypeCache.GetId <T>();

            var relatedEntityService = new Rock.Model.RelatedEntityService(this.Context as RockContext);
            var relatedEntity        = relatedEntityService.GetRelatedEntityRecordToSource(entityId, sourceEntityTypeId.Value, relatedEntityTypeId.Value, targetEntity.Id, purposeKey, qualifierValue);

            if (relatedEntity != null)
            {
                relatedEntityService.Delete(relatedEntity);
            }
        }
コード例 #27
0
        /// <summary>
        /// Raises 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 += Block_BlockUpdated;
            this.AddConfigurationUpdateTrigger(upnlContent);
            dvpNcoaPersonDataView.EntityTypeId = EntityTypeCache.GetId <Rock.Model.Person>();

            var inactiveRecordReasonDt = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSON_RECORD_STATUS_REASON.AsGuid());

            dvpNcoaInactiveRecordReason.DefinedTypeId = inactiveRecordReasonDt.Id;
        }
コード例 #28
0
        /// <summary>
        /// Ensures that the controls that are created based on the WorkflowType have been created
        /// </summary>
        /// <param name="workflowTypePicker">The workflow type picker.</param>
        private void EnsureSelectedWorkflowTypeControls(WorkflowTypePicker workflowTypePicker)
        {
            DynamicControlsPanel containerControl = workflowTypePicker.Parent as DynamicControlsPanel;
            FilterField          filterControl    = containerControl.FirstParentControlOfType <FilterField>();

            var entityFields = GetWorkflowAttributes(workflowTypePicker.SelectedValueAsId());

            // Create the field selection dropdown
            string           propertyControlId = string.Format("{0}_ddlProperty", containerControl.ID);
            RockDropDownList ddlProperty       = containerControl.Controls.OfType <RockDropDownList>().FirstOrDefault(a => a.ID == propertyControlId);

            if (ddlProperty == null)
            {
                ddlProperty                       = new RockDropDownList();
                ddlProperty.ID                    = propertyControlId;
                ddlProperty.AutoPostBack          = true;
                ddlProperty.SelectedIndexChanged += ddlProperty_SelectedIndexChanged;
                ddlProperty.AddCssClass("js-property-dropdown");
                ddlProperty.Attributes["EntityTypeId"] = EntityTypeCache.GetId <Rock.Model.Workflow>().ToString();
                containerControl.Controls.Add(ddlProperty);
            }

            // update the list of items just in case the WorkflowType changed
            ddlProperty.Items.Clear();

            // add Empty option first
            ddlProperty.Items.Add(new ListItem());
            foreach (var entityField in entityFields)
            {
                // Add the field to the dropdown of available fields
                ddlProperty.Items.Add(new ListItem(entityField.TitleWithoutQualifier, entityField.UniqueName));
            }

            if (workflowTypePicker.Page.IsPostBack)
            {
                ddlProperty.SetValue(workflowTypePicker.Page.Request.Params[ddlProperty.UniqueID]);
            }

            foreach (var entityField in entityFields)
            {
                string controlId = string.Format("{0}_{1}", containerControl.ID, entityField.UniqueName);
                if (!containerControl.Controls.OfType <Control>().Any(a => a.ID == controlId))
                {
                    var control = entityField.FieldType.Field.FilterControl(entityField.FieldConfig, controlId, true, filterControl.FilterMode);
                    if (control != null)
                    {
                        containerControl.Controls.Add(control);
                    }
                }
            }
        }
コード例 #29
0
ファイル: EntityHelper.cs プロジェクト: BricksandMortar/Rock
        /// <summary>
        /// Create an EntityField for an Attribute.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="limitToFilterableAttributes"></param>
        public static EntityField GetEntityFieldForAttribute(AttributeCache attribute, bool limitToFilterableAttributes = true)
        {
            // Ensure field name only has Alpha, Numeric and underscore chars
            string fieldName = attribute.Key.RemoveSpecialCharacters().Replace(".", "");

            EntityField entityField = null;

            // Make sure that the attributes field type actually renders a filter control if limitToFilterableAttributes
            var fieldType = FieldTypeCache.Read(attribute.FieldTypeId);

            if (fieldType != null && (!limitToFilterableAttributes || fieldType.Field.HasFilterControl()))
            {
                entityField       = new EntityField(fieldName, FieldKind.Attribute, typeof(string), attribute.Guid, fieldType);
                entityField.Title = attribute.Name.SplitCase();
                entityField.TitleWithoutQualifier = entityField.Title;

                foreach (var config in attribute.QualifierValues)
                {
                    entityField.FieldConfig.Add(config.Key, config.Value);
                }

                // Special processing for Entity Type "Group" to handle sub-types that are distinguished by GroupTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Group)) && attribute.EntityTypeQualifierColumn == "GroupTypeId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var groupType = new GroupTypeService(rockContext).Get(attribute.EntityTypeQualifierValue.AsInteger());
                        if (groupType != null)
                        {
                            // Append the Qualifier to the title
                            entityField.Title = string.Format("{0} ({1})", attribute.Name, groupType.Name);
                        }
                    }
                }

                // Special processing for Entity Type "ContentChannelItem" to handle sub-types that are distinguished by ContentChannelTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(ContentChannelItem)) && attribute.EntityTypeQualifierColumn == "ContentChannelTypeId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var contentChannelType = new ContentChannelTypeService(rockContext).Get(attribute.EntityTypeQualifierValue.AsInteger());
                        if (contentChannelType != null)
                        {
                            // Append the Qualifier to the title
                            entityField.Title = string.Format("{0} ({1})", attribute.Name, contentChannelType.Name);
                        }
                    }
                }
            }
            return(entityField);
        }
コード例 #30
0
ファイル: LinqExtensions.cs プロジェクト: waldo2590/Rock
        /// <summary>
        /// Wheres the campus.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="campusId">The campus identifier.</param>
        /// <returns></returns>
        public static IQueryable <T> WhereCampus <T>(this IQueryable <T> source, RockContext rockContext, int campusId) where T : Entity <T>, new()
        {
            int entityTypeId = EntityTypeCache.GetId(typeof(T)) ?? 0;

            var entityCampusFilterService = new EntityCampusFilterService(rockContext)
                                            .Queryable()
                                            .Where(e => e.CampusId == campusId)
                                            .Where(e => e.EntityTypeId == entityTypeId)
                                            .Select(e => e.EntityId);

            var result = source.Where(s => entityCampusFilterService.Contains((s as T).Id));

            return(result);
        }