Esempio n. 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 OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            mdCategoryTreeConfig.Visible = false;

            bool canEditBlock = IsUserAuthorized(Authorization.EDIT);

            // hide all the actions if user doesn't have EDIT to the block
            divTreeviewActions.Visible = canEditBlock;

            var detailPageReference = new Rock.Web.PageReference(GetAttributeValue("DetailPage"));

            // NOTE: if the detail page is the current page, use the current route instead of route specified in the DetailPage (to preserve old behavior)
            if (detailPageReference == null || detailPageReference.PageId == this.RockPage.PageId)
            {
                hfPageRouteTemplate.Value = (this.RockPage.RouteData.Route as System.Web.Routing.Route).Url;
                hfDetailPageUrl.Value     = new Rock.Web.PageReference(this.RockPage.PageId).BuildUrl();
            }
            else
            {
                hfPageRouteTemplate.Value = string.Empty;
                var pageCache = PageCache.Read(detailPageReference.PageId);
                if (pageCache != null)
                {
                    var route = pageCache.PageRoutes.FirstOrDefault(a => a.Id == detailPageReference.RouteId);
                    if (route != null)
                    {
                        hfPageRouteTemplate.Value = route.Route;
                    }
                }

                hfDetailPageUrl.Value = detailPageReference.BuildUrl();
            }

            // Get EntityTypeName
            Guid?entityTypeGuid = GetAttributeValue("EntityType").AsGuidOrNull();

            nbWarning.Text    = "Please select an entity type in the block settings.";
            nbWarning.Visible = !entityTypeGuid.HasValue;
            if (entityTypeGuid.HasValue)
            {
                int    entityTypeId             = Rock.Web.Cache.EntityTypeCache.Read(entityTypeGuid.Value).Id;
                string entityTypeQualiferColumn = GetAttributeValue("EntityTypeQualifierProperty");
                string entityTypeQualifierValue = GetAttributeValue("EntityTypeQualifierValue");
                bool   showUnnamedEntityItems   = GetAttributeValue("ShowUnnamedEntityItems").AsBooleanOrNull() ?? true;

                string parms = string.Format("?getCategorizedItems=true&showUnnamedEntityItems={0}", showUnnamedEntityItems.ToTrueFalse().ToLower());
                parms += string.Format("&entityTypeId={0}", entityTypeId);

                var rootCategory = CategoryCache.Read(this.GetAttributeValue("RootCategory").AsGuid());

                // make sure the rootCategory matches the EntityTypeId (just in case they changed the EntityType after setting RootCategory
                if (rootCategory != null && rootCategory.EntityTypeId == entityTypeId)
                {
                    parms += string.Format("&rootCategoryId={0}", rootCategory.Id);
                }

                if (!string.IsNullOrEmpty(entityTypeQualiferColumn))
                {
                    parms += string.Format("&entityQualifier={0}", entityTypeQualiferColumn);

                    if (!string.IsNullOrEmpty(entityTypeQualifierValue))
                    {
                        parms += string.Format("&entityQualifierValue={0}", entityTypeQualifierValue);
                    }
                }

                var        excludeCategoriesGuids = this.GetAttributeValue("ExcludeCategories").SplitDelimitedValues().AsGuidList();
                List <int> excludedCategoriesIds  = new List <int>();
                if (excludeCategoriesGuids != null && excludeCategoriesGuids.Any())
                {
                    foreach (var excludeCategoryGuid in excludeCategoriesGuids)
                    {
                        var excludedCategory = CategoryCache.Read(excludeCategoryGuid);
                        if (excludedCategory != null)
                        {
                            excludedCategoriesIds.Add(excludedCategory.Id);
                        }
                    }

                    parms += string.Format("&excludedCategoryIds={0}", excludedCategoriesIds.AsDelimited(","));
                }

                string defaultIconCssClass = GetAttributeValue("DefaultIconCSSClass");
                if (!string.IsNullOrWhiteSpace(defaultIconCssClass))
                {
                    parms += string.Format("&defaultIconCssClass={0}", defaultIconCssClass);
                }

                RestParms = parms;

                var cachedEntityType = Rock.Web.Cache.EntityTypeCache.Read(entityTypeId);
                if (cachedEntityType != null)
                {
                    string entityTypeFriendlyName = GetAttributeValue("EntityTypeFriendlyName");
                    if (string.IsNullOrWhiteSpace(entityTypeFriendlyName))
                    {
                        entityTypeFriendlyName = cachedEntityType.FriendlyName;
                    }

                    lbAddItem.ToolTip = "Add " + entityTypeFriendlyName;
                    lAddItem.Text     = entityTypeFriendlyName;
                }

                // Attempt to retrieve an EntityId from the Page URL parameters.
                PageParameterName = GetAttributeValue("PageParameterKey");

                string selectedNodeId = null;

                int?   itemId = PageParameter(PageParameterName).AsIntegerOrNull();
                string selectedEntityType;
                if (itemId.HasValue)
                {
                    selectedNodeId     = itemId.ToString();
                    selectedEntityType = (cachedEntityType != null) ? cachedEntityType.Name : string.Empty;
                }
                else
                {
                    // If an EntityId was not specified, check for a CategoryId.
                    itemId = PageParameter("CategoryId").AsIntegerOrNull();

                    selectedNodeId     = CategoryNodePrefix + itemId;
                    selectedEntityType = "category";
                }

                lbAddCategoryRoot.Enabled  = true;
                lbAddCategoryChild.Enabled = false;
                lbAddItem.Enabled          = false;

                CategoryCache selectedCategory = null;

                if (!string.IsNullOrEmpty(selectedNodeId))
                {
                    hfSelectedItemId.Value = selectedNodeId;
                    List <string> parentIdList = new List <string>();

                    if (selectedEntityType.Equals("category"))
                    {
                        selectedCategory = CategoryCache.Read(itemId.GetValueOrDefault());
                        if (selectedCategory != null && !canEditBlock && selectedCategory.IsAuthorized(Authorization.EDIT, CurrentPerson))
                        {
                            // Show the action buttons if user has edit rights to category
                            divTreeviewActions.Visible = true;
                        }
                    }
                    else
                    {
                        if (cachedEntityType != null)
                        {
                            Type entityType = cachedEntityType.GetEntityType();
                            if (entityType != null)
                            {
                                Type         serviceType     = typeof(Rock.Data.Service <>);
                                Type[]       modelType       = { entityType };
                                Type         service         = serviceType.MakeGenericType(modelType);
                                var          serviceInstance = Activator.CreateInstance(service, new object[] { new RockContext() });
                                var          getMethod       = service.GetMethod("Get", new Type[] { typeof(int) });
                                ICategorized entity          = getMethod.Invoke(serviceInstance, new object[] { itemId }) as ICategorized;

                                if (entity != null)
                                {
                                    lbAddCategoryChild.Enabled = false;
                                    if (entity.CategoryId.HasValue)
                                    {
                                        selectedCategory = CategoryCache.Read(entity.CategoryId.Value);
                                        if (selectedCategory != null)
                                        {
                                            string categoryExpandedID = CategoryNodePrefix + selectedCategory.Id.ToString();
                                            parentIdList.Insert(0, CategoryNodePrefix + categoryExpandedID);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // get the parents of the selected item so we can tell the treeview to expand those
                    var category = selectedCategory;
                    while (category != null)
                    {
                        category = category.ParentCategory;
                        if (category != null)
                        {
                            string categoryExpandedID = CategoryNodePrefix + category.Id.ToString();
                            if (!parentIdList.Contains(categoryExpandedID))
                            {
                                parentIdList.Insert(0, categoryExpandedID);
                            }
                            else
                            {
                                // infinite recursion
                                break;
                            }
                        }
                    }
                    // also get any additional expanded nodes that were sent in the Post
                    string postedExpandedIds = this.Request.Params["ExpandedIds"];
                    if (!string.IsNullOrWhiteSpace(postedExpandedIds))
                    {
                        var postedExpandedIdList = postedExpandedIds.Split(',').ToList();
                        foreach (var id in postedExpandedIdList)
                        {
                            if (!parentIdList.Contains(id))
                            {
                                parentIdList.Add(id);
                            }
                        }
                    }

                    hfInitialCategoryParentIds.Value = parentIdList.AsDelimited(",");
                }

                selectedCategory = selectedCategory ?? rootCategory;

                if (selectedCategory != null)
                {
                    lbAddItem.Enabled          = true;
                    lbAddCategoryChild.Enabled = true;
                    this.SelectedCategoryId    = selectedCategory.Id;
                }
                else
                {
                    this.SelectedCategoryId = null;
                }
            }
        }
        private void CreateControls(List <GroupMember> familyMembers, bool setSelection)
        {
            // Load all the attribute controls
            attributeControls.Clear();
            pnlAttributes.Controls.Clear();

            foreach (string categoryGuid in GetAttributeValue("AttributeCategories").SplitDelimitedValues(false))
            {
                Guid guid = Guid.Empty;
                if (Guid.TryParse(categoryGuid, out guid))
                {
                    var category = CategoryCache.Read(guid);
                    if (category != null)
                    {
                        var attributeControl = new NewFamilyAttributes();
                        attributeControl.ClearRows();
                        pnlAttributes.Controls.Add(attributeControl);
                        attributeControls.Add(attributeControl);
                        attributeControl.ID         = "familyAttributes_" + category.Id.ToString();
                        attributeControl.CategoryId = category.Id;

                        foreach (var attribute in new AttributeService(new RockContext()).GetByCategoryId(category.Id))
                        {
                            if (attribute.IsAuthorized(Authorization.EDIT, CurrentPerson))
                            {
                                attributeControl.AttributeList.Add(AttributeCache.Read(attribute));
                            }
                        }
                    }
                }
            }

            nfmMembers.ClearRows();
            nfciContactInfo.ClearRows();

            foreach (var familyMember in familyMembers)
            {
                string familyMemberGuidString = familyMember.Person.Guid.ToString().Replace("-", "_");

                var familyMemberRow = new NewFamilyMembersRow();
                nfmMembers.Controls.Add(familyMemberRow);
                familyMemberRow.ID            = string.Format("row_{0}", familyMemberGuidString);
                familyMemberRow.RoleUpdated  += familyMemberRow_RoleUpdated;
                familyMemberRow.DeleteClick  += familyMemberRow_DeleteClick;
                familyMemberRow.PersonGuid    = familyMember.Person.Guid;
                familyMemberRow.RequireGender = nfmMembers.RequireGender;
                familyMemberRow.RequireGrade  = nfmMembers.RequireGrade;
                familyMemberRow.RoleId        = familyMember.GroupRoleId;
                familyMemberRow.ShowGrade     = familyMember.GroupRoleId == _childRoleId;

                var contactInfoRow = new NewFamilyContactInfoRow();
                nfciContactInfo.Controls.Add(contactInfoRow);
                contactInfoRow.ID         = string.Format("ci_row_{0}", familyMemberGuidString);
                contactInfoRow.PersonGuid = familyMember.Person.Guid;

                if (_homePhone != null)
                {
                    var homePhoneNumber = familyMember.Person.PhoneNumbers.Where(p => p.NumberTypeValueId == _homePhone.Id).FirstOrDefault();
                    if (homePhoneNumber != null)
                    {
                        contactInfoRow.HomePhoneNumber      = homePhoneNumber.NumberFormatted;
                        contactInfoRow.HomePhoneCountryCode = homePhoneNumber.CountryCode;
                    }
                }

                if (_cellPhone != null)
                {
                    var cellPhoneNumber = familyMember.Person.PhoneNumbers.Where(p => p.NumberTypeValueId == _cellPhone.Id).FirstOrDefault();
                    if (cellPhoneNumber != null)
                    {
                        contactInfoRow.CellPhoneNumber      = cellPhoneNumber.NumberFormatted;
                        contactInfoRow.CellPhoneCountryCode = cellPhoneNumber.CountryCode;
                    }
                }

                contactInfoRow.Email = familyMember.Person.Email;

                if (setSelection)
                {
                    if (familyMember.Person != null)
                    {
                        familyMemberRow.TitleValueId            = familyMember.Person.TitleValueId;
                        familyMemberRow.FirstName               = familyMember.Person.FirstName;
                        familyMemberRow.LastName                = familyMember.Person.LastName;
                        familyMemberRow.SuffixValueId           = familyMember.Person.SuffixValueId;
                        familyMemberRow.Gender                  = familyMember.Person.Gender;
                        familyMemberRow.BirthDate               = familyMember.Person.BirthDate;
                        familyMemberRow.ConnectionStatusValueId = familyMember.Person.ConnectionStatusValueId;
                        familyMemberRow.GradeOffset             = familyMember.Person.GradeOffset;
                    }
                }

                foreach (var attributeControl in attributeControls)
                {
                    var attributeRow = new NewFamilyAttributesRow();
                    attributeControl.Controls.Add(attributeRow);
                    attributeRow.ID            = string.Format("{0}_{1}", attributeControl.ID, familyMemberGuidString);
                    attributeRow.AttributeList = attributeControl.AttributeList;
                    attributeRow.PersonGuid    = familyMember.Person.Guid;

                    if (setSelection)
                    {
                        attributeRow.SetEditValues(familyMember.Person);
                    }
                }
            }

            ShowPage(CurrentPageIndex);
        }
Esempio n. 3
0
        /// <summary>
        /// Pres the save changes.
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="state">The state.</param>
        public override void PreSaveChanges(DbContext dbContext, System.Data.Entity.EntityState state)
        {
            try
            {
                string verb   = string.Empty;
                string action = string.Empty;

                var   rockContext = (RockContext)dbContext;
                Group group       = null;

                if (state == System.Data.Entity.EntityState.Added)
                {
                    verb   = "ADD";
                    action = "Added to group.";
                    if (!this.DateTimeAdded.HasValue)
                    {
                        this.DateTimeAdded = RockDateTime.Now;
                    }
                }
                else if (state == System.Data.Entity.EntityState.Modified)
                {
                    verb = "UPDATE";

                    var changeEntry = dbContext.ChangeTracker.Entries <GroupMember>().Where(a => a.Entity == this).FirstOrDefault();
                    if (changeEntry != null)
                    {
                        var origGroupMemberStatus = (GroupMemberStatus)changeEntry.OriginalValues["GroupMemberStatus"];
                        if (origGroupMemberStatus != this.GroupMemberStatus)
                        {
                            action = string.Format("Group member status changed from {0} to {1}", origGroupMemberStatus.ToString(), this.GroupMemberStatus.ToString());
                        }

                        var origGroupRoleId = (int)changeEntry.OriginalValues["GroupRoleId"];
                        if (origGroupRoleId != this.GroupRoleId)
                        {
                            if (group == null)
                            {
                                group = this.Group;
                            }
                            if (group == null)
                            {
                                group = new GroupService(rockContext).Get(this.GroupId);
                            }
                            if (group != null)
                            {
                                var groupType = GroupTypeCache.Read(group.GroupTypeId);
                                if (groupType != null)
                                {
                                    var origRole = groupType.Roles.FirstOrDefault(r => r.Id == origGroupRoleId);
                                    var newRole  = groupType.Roles.FirstOrDefault(r => r.Id == this.GroupRoleId);
                                    action = string.Format("Group role changed from {0} to {1}",
                                                           (origRole != null ? origRole.Name : "??"),
                                                           (newRole != null ? newRole.Name : "??"));
                                }
                            }
                        }
                    }
                }
                else if (state == System.Data.Entity.EntityState.Deleted)
                {
                    verb   = "DELETE";
                    action = "Removed from group.";
                }

                if (!string.IsNullOrWhiteSpace(action))
                {
                    if (group == null)
                    {
                        group = this.Group;
                    }
                    if (group == null)
                    {
                        group = new GroupService(rockContext).Get(this.GroupId);
                    }
                    if (group != null)
                    {
                        var personEntityTypeId        = EntityTypeCache.Read("Rock.Model.Person").Id;
                        var groupEntityTypeId         = EntityTypeCache.Read("Rock.Model.Group").Id;
                        var groupMembershipCategoryId = CategoryCache.Read(Rock.SystemGuid.Category.HISTORY_PERSON_GROUP_MEMBERSHIP.AsGuid(), rockContext).Id;

                        new HistoryService(rockContext).Add(new History
                        {
                            EntityTypeId        = personEntityTypeId,
                            CategoryId          = groupMembershipCategoryId,
                            EntityId            = this.PersonId,
                            Summary             = action,
                            Caption             = group.Name,
                            RelatedEntityTypeId = groupEntityTypeId,
                            RelatedEntityId     = this.GroupId,
                            Verb = verb
                        });
                    }
                }
            }
            catch { }

            base.PreSaveChanges(dbContext, state);
        }
Esempio n. 4
0
        public override bool HasEventHappened(FollowingEventType followingEvent, IEntity entity, DateTime?lastNotified)
        {
            if (followingEvent != null && entity != null)
            {
                var personAlias = entity as PersonAlias;

                if (personAlias != null && personAlias.Person != null)
                {
                    //
                    // Get all the attributes/settings we need.
                    //
                    int    daysBack         = GetAttributeValue(followingEvent, "MaxDaysBack").AsInteger();
                    string targetOldValue   = GetAttributeValue(followingEvent, "OldValue") ?? string.Empty;
                    string targetNewValue   = GetAttributeValue(followingEvent, "NewValue") ?? string.Empty;
                    string targetPersonGuid = GetAttributeValue(followingEvent, "Person");
                    bool   negateChangedBy  = GetAttributeValue(followingEvent, "NegatePerson").AsBoolean();
                    bool   matchBothValues  = GetAttributeValue(followingEvent, "MatchBoth").AsBoolean();
                    var    attributes       = GetAttributeValue(followingEvent, "Fields").Split(',').Select(a => a.Trim());

                    //
                    // Populate all the other random variables we need for processing.
                    //
                    PersonAlias targetPersonAlias  = new PersonAliasService(new RockContext()).Get(targetPersonGuid.AsGuid());
                    DateTime    daysBackDate       = RockDateTime.Now.AddDays(-daysBack);
                    var         person             = personAlias.Person;
                    int         personEntityTypeId = EntityTypeCache.Read(typeof(Person)).Id;
                    int         categoryId         = CategoryCache.Read(Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid()).Id;

                    //
                    // Start building the basic query. We want all History items that are for
                    // people objects and use the Demographic Changes category.
                    //
                    var qry = new HistoryService(new RockContext()).Queryable()
                              .Where(h => h.EntityTypeId == personEntityTypeId && h.EntityId == person.Id && h.CategoryId == categoryId);

                    //
                    // Put in our limiting dates. We always limit by our days back date,
                    // and conditionally limit based on the last time we notified the
                    // stalker - I mean the follower.
                    //
                    if (lastNotified.HasValue)
                    {
                        qry = qry.Where(h => h.CreatedDateTime >= lastNotified.Value);
                    }
                    qry = qry.Where(h => h.CreatedDateTime >= daysBackDate);

                    //
                    // Walk each history item found that matches our filter.
                    //
                    Dictionary <string, List <HistoryChange> > changes = new Dictionary <string, List <HistoryChange> >();
                    foreach (var history in qry.ToList())
                    {
                        Match modified = Regex.Match(history.Summary, ModifiedRegex);
                        Match added    = Regex.Match(history.Summary, AddedRegex);
                        Match deleted  = Regex.Match(history.Summary, DeletedRegex);

                        //
                        // Walk each attribute entered by the user to match against.
                        //
                        foreach (var attribute in attributes)
                        {
                            HistoryChange change = new HistoryChange();
                            string        title  = null;

                            //
                            // Check what kind of change this was.
                            //
                            if (modified.Success)
                            {
                                title      = modified.Groups[1].Value;
                                change.Old = modified.Groups[2].Value;
                                change.New = modified.Groups[3].Value;
                            }
                            else if (added.Success)
                            {
                                title      = added.Groups[1].Value;
                                change.Old = string.Empty;
                                change.New = added.Groups[2].Value;
                            }
                            else if (deleted.Success)
                            {
                                title      = deleted.Groups[1].Value;
                                change.Old = deleted.Groups[2].Value;
                                change.New = string.Empty;
                            }

                            //
                            // Check if this is one of the attributes we are following.
                            //
                            if (title != null && title.Trim() == attribute)
                            {
                                //
                                // Get the ValuePair object to work with.
                                //
                                if (!changes.ContainsKey(attribute))
                                {
                                    changes.Add(attribute, new List <HistoryChange>());
                                }

                                change.PersonId = history.CreatedByPersonId;
                                changes[attribute].Add(change);

                                //
                                // If the value has been changed back to what it was then ignore the change.
                                //
                                if (changes[attribute].Count >= 2)
                                {
                                    var changesList = changes[attribute].ToList();

                                    if (changesList[changesList.Count - 2].Old == changesList[changesList.Count - 1].New)
                                    {
                                        changes.Remove(title);
                                    }
                                }
                            }
                        }
                    }

                    //
                    // Walk the list of final changes and see if we need to notify.
                    //
                    foreach (var items in changes.Values)
                    {
                        foreach (HistoryChange change in items)
                        {
                            //
                            // Check for a match on the person who made the change.
                            //
                            if (targetPersonAlias == null ||
                                targetPersonAlias.Id == 0 ||
                                (!negateChangedBy && targetPersonAlias.PersonId == change.PersonId) ||
                                (negateChangedBy && targetPersonAlias.PersonId != change.PersonId))
                            {
                                bool oldMatch = (string.IsNullOrEmpty(targetOldValue) || targetOldValue == change.Old);
                                bool newMatch = (string.IsNullOrEmpty(targetNewValue) || targetNewValue == change.New);

                                //
                                // If the old value and the new value match then trigger the event.
                                //
                                if ((matchBothValues && oldMatch && newMatch) ||
                                    (!matchBothValues && (oldMatch || newMatch)))
                                {
                                    return(true);
                                }
                            }
                        }
                    }
                }
            }

            return(false);
        }
Esempio n. 5
0
        private void CreateControls(bool setSelection)
        {
            // Load all the attribute controls
            attributeControls.Clear();
            pnlAttributes.Controls.Clear();
            phDuplicates.Controls.Clear();

            var rockContext      = new RockContext();
            var attributeService = new AttributeService(rockContext);
            var locationService  = new LocationService(rockContext);

            foreach (string categoryGuid in GetAttributeValue("AttributeCategories").SplitDelimitedValues(false))
            {
                Guid guid = Guid.Empty;
                if (Guid.TryParse(categoryGuid, out guid))
                {
                    var category = CategoryCache.Read(guid);
                    if (category != null)
                    {
                        var attributeControl = new NewGroupAttributes();
                        attributeControl.ClearRows();
                        pnlAttributes.Controls.Add(attributeControl);
                        attributeControls.Add(attributeControl);
                        attributeControl.ID         = "groupAttributes_" + category.Id.ToString();
                        attributeControl.CategoryId = category.Id;

                        foreach (var attribute in attributeService.GetByCategoryId(category.Id))
                        {
                            if (attribute.IsAuthorized(Authorization.EDIT, CurrentPerson))
                            {
                                attributeControl.AttributeList.Add(AttributeCache.Read(attribute));
                            }
                        }
                    }
                }
            }

            nfmMembers.ClearRows();
            nfciContactInfo.ClearRows();

            var groupMemberService = new GroupMemberService(rockContext);
            int defaultRoleId      = _groupType.DefaultGroupRoleId ?? _groupType.Roles.Select(r => r.Id).FirstOrDefault();

            var location = new Location();

            acAddress.GetValues(location);

            foreach (var groupMember in GroupMembers)
            {
                string groupMemberGuidString = groupMember.Person.Guid.ToString().Replace("-", "_");

                var groupMemberRow = new NewGroupMembersRow();
                groupMemberRow.GroupTypeId = _groupType.Id;
                nfmMembers.Controls.Add(groupMemberRow);
                groupMemberRow.ID              = string.Format("row_{0}", groupMemberGuidString);
                groupMemberRow.RoleUpdated    += groupMemberRow_RoleUpdated;
                groupMemberRow.DeleteClick    += groupMemberRow_DeleteClick;
                groupMemberRow.PersonGuid      = groupMember.Person.Guid;
                groupMemberRow.RequireGender   = nfmMembers.RequireGender;
                groupMemberRow.RequireGrade    = nfmMembers.RequireGrade;
                groupMemberRow.RoleId          = groupMember.GroupRoleId;
                groupMemberRow.ShowGradeColumn = _isFamilyGroupType;
                groupMemberRow.ShowGradePicker = groupMember.GroupRoleId == _childRoleId;
                groupMemberRow.ValidationGroup = BlockValidationGroup;

                var contactInfoRow = new NewGroupContactInfoRow();
                nfciContactInfo.Controls.Add(contactInfoRow);
                contactInfoRow.ID                 = string.Format("ci_row_{0}", groupMemberGuidString);
                contactInfoRow.PersonGuid         = groupMember.Person.Guid;
                contactInfoRow.IsMessagingEnabled = _SMSEnabled;
                contactInfoRow.PersonName         = groupMember.Person.FullName;

                if (_homePhone != null)
                {
                    var homePhoneNumber = groupMember.Person.PhoneNumbers.Where(p => p.NumberTypeValueId == _homePhone.Id).FirstOrDefault();
                    if (homePhoneNumber != null)
                    {
                        contactInfoRow.HomePhoneNumber      = PhoneNumber.FormattedNumber(homePhoneNumber.CountryCode, homePhoneNumber.Number);
                        contactInfoRow.HomePhoneCountryCode = homePhoneNumber.CountryCode;
                    }
                    else
                    {
                        contactInfoRow.HomePhoneNumber      = string.Empty;
                        contactInfoRow.HomePhoneCountryCode = string.Empty;
                    }
                }

                if (_cellPhone != null)
                {
                    var cellPhoneNumber = groupMember.Person.PhoneNumbers.Where(p => p.NumberTypeValueId == _cellPhone.Id).FirstOrDefault();
                    if (cellPhoneNumber != null)
                    {
                        contactInfoRow.CellPhoneNumber      = PhoneNumber.FormattedNumber(cellPhoneNumber.CountryCode, cellPhoneNumber.Number);
                        contactInfoRow.CellPhoneCountryCode = cellPhoneNumber.CountryCode;
                    }
                    else
                    {
                        contactInfoRow.CellPhoneNumber      = string.Empty;
                        contactInfoRow.CellPhoneCountryCode = string.Empty;
                    }
                }

                contactInfoRow.Email = groupMember.Person.Email;

                if (setSelection)
                {
                    if (groupMember.Person != null)
                    {
                        groupMemberRow.TitleValueId            = groupMember.Person.TitleValueId;
                        groupMemberRow.FirstName               = groupMember.Person.FirstName;
                        groupMemberRow.LastName                = groupMember.Person.LastName;
                        groupMemberRow.SuffixValueId           = groupMember.Person.SuffixValueId;
                        groupMemberRow.Gender                  = groupMember.Person.Gender;
                        groupMemberRow.BirthDate               = groupMember.Person.BirthDate;
                        groupMemberRow.ConnectionStatusValueId = groupMember.Person.ConnectionStatusValueId;
                        groupMemberRow.GradeOffset             = groupMember.Person.GradeOffset;
                    }
                }

                foreach (var attributeControl in attributeControls)
                {
                    var attributeRow = new NewGroupAttributesRow();
                    attributeControl.Controls.Add(attributeRow);
                    attributeRow.ID            = string.Format("{0}_{1}", attributeControl.ID, groupMemberGuidString);
                    attributeRow.AttributeList = attributeControl.AttributeList;
                    attributeRow.PersonGuid    = groupMember.Person.Guid;
                    attributeRow.PersonName    = groupMember.Person.FullName;

                    if (setSelection)
                    {
                        attributeRow.SetEditValues(groupMember.Person);
                    }
                }

                if (Duplicates.ContainsKey(groupMember.Person.Guid))
                {
                    var dupRow = new HtmlGenericControl("div");
                    dupRow.AddCssClass("row");
                    dupRow.ID = string.Format("dupRow_{0}", groupMemberGuidString);
                    phDuplicates.Controls.Add(dupRow);

                    var newPersonCol = new HtmlGenericControl("div");
                    newPersonCol.AddCssClass("col-md-6");
                    newPersonCol.ID = string.Format("newPersonCol_{0}", groupMemberGuidString);
                    dupRow.Controls.Add(newPersonCol);

                    newPersonCol.Controls.Add(PersonHtmlPanel(
                                                  groupMemberGuidString,
                                                  groupMember.Person,
                                                  groupMember.GroupRole,
                                                  location,
                                                  rockContext));

                    LinkButton lbRemoveMember = new LinkButton();
                    lbRemoveMember.ID = string.Format("lbRemoveMember_{0}", groupMemberGuidString);
                    lbRemoveMember.AddCssClass("btn btn-danger btn-xs");
                    lbRemoveMember.Text   = "Remove";
                    lbRemoveMember.Click += lbRemoveMember_Click;
                    newPersonCol.Controls.Add(lbRemoveMember);

                    var dupPersonCol = new HtmlGenericControl("div");
                    dupPersonCol.AddCssClass("col-md-6");
                    dupPersonCol.ID = string.Format("dupPersonCol_{0}", groupMemberGuidString);
                    dupRow.Controls.Add(dupPersonCol);

                    var duplicateHeader = new HtmlGenericControl("h4");
                    duplicateHeader.InnerText = "Possible Duplicate Records";
                    dupPersonCol.Controls.Add(duplicateHeader);

                    foreach (var duplicate in Duplicates[groupMember.Person.Guid])
                    {
                        GroupTypeRole groupTypeRole = null;
                        Location      duplocation   = null;

                        var dupGroupMember = groupMemberService.Queryable()
                                             .Where(a => a.PersonId == duplicate.Id)
                                             .Where(a => a.Group.GroupTypeId == _groupType.Id)
                                             .Select(s => new
                        {
                            s.GroupRole,
                            GroupLocation = s.Group.GroupLocations.Where(a => a.GroupLocationTypeValue.Guid.Equals(_locationType.Guid)).Select(a => a.Location).FirstOrDefault()
                        })
                                             .FirstOrDefault();
                        if (dupGroupMember != null)
                        {
                            groupTypeRole = dupGroupMember.GroupRole;
                            duplocation   = dupGroupMember.GroupLocation;
                        }

                        dupPersonCol.Controls.Add(PersonHtmlPanel(
                                                      groupMemberGuidString,
                                                      duplicate,
                                                      groupTypeRole,
                                                      duplocation,
                                                      rockContext));
                    }
                }
            }

            ShowPage();
        }
Esempio n. 6
0
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="category">The category.</param>
        private void ShowEditDetails(Category category)
        {
            if (category.Id > 0)
            {
                lTitle.Text = ActionTitle.Edit(Category.FriendlyTypeName).FormatAsHtmlTitle();
                lIcon.Text  = "<i class='fa fa-square-o'></i>";
            }
            else
            {
                lTitle.Text = ActionTitle.Add(Category.FriendlyTypeName).FormatAsHtmlTitle();

                if (!string.IsNullOrEmpty(category.IconCssClass))
                {
                    lIcon.Text = String.Format("<i class='{0}'></i>", category.IconCssClass);
                }
                else
                {
                    lIcon.Text = "<i class='fa fa-square-o'></i>";
                }
            }

            SetEditMode(true);

            tbName.Text = category.Name;

            if (category.EntityTypeId != 0)
            {
                var entityType = EntityTypeCache.Read(category.EntityTypeId);
                lblEntityTypeName.Text = entityType.Name;
            }
            else
            {
                lblEntityTypeName.Text = string.Empty;
            }

            var        excludeCategoriesGuids = this.GetAttributeValue("ExcludeCategories").SplitDelimitedValues().AsGuidList();
            List <int> excludedCategoriesIds  = new List <int>();

            if (excludeCategoriesGuids != null && excludeCategoriesGuids.Any())
            {
                foreach (var excludeCategoryGuid in excludeCategoriesGuids)
                {
                    var excludedCategory = CategoryCache.Read(excludeCategoryGuid);
                    if (excludedCategory != null)
                    {
                        excludedCategoriesIds.Add(excludedCategory.Id);
                    }
                }
            }

            cpParentCategory.EntityTypeId = category.EntityTypeId;
            cpParentCategory.EntityTypeQualifierColumn = category.EntityTypeQualifierColumn;
            cpParentCategory.EntityTypeQualifierValue  = category.EntityTypeQualifierValue;
            cpParentCategory.ExcludedCategoryIds       = excludedCategoriesIds.AsDelimited(",");
            var rootCategory = CategoryCache.Read(this.GetAttributeValue("RootCategory").AsGuid());

            cpParentCategory.RootCategoryId = rootCategory != null ? rootCategory.Id : (int?)null;
            cpParentCategory.SetValue(category.ParentCategoryId);

            lblEntityTypeQualifierColumn.Visible = !string.IsNullOrWhiteSpace(category.EntityTypeQualifierColumn);
            lblEntityTypeQualifierColumn.Text    = category.EntityTypeQualifierColumn;
            lblEntityTypeQualifierValue.Visible  = !string.IsNullOrWhiteSpace(category.EntityTypeQualifierValue);
            lblEntityTypeQualifierValue.Text     = category.EntityTypeQualifierValue;
            tbIconCssClass.Text   = category.IconCssClass;
            tbHighlightColor.Text = category.HighlightColor;
        }
Esempio n. 7
0
        /// <summary>
        /// Sends the specified communication.
        /// </summary>Medi
        /// <param name="communication">The communication.</param>
        /// <param name="mediumEntityTypeId">The medium entity type identifier.</param>
        /// <param name="mediumAttributes">The medium attributes.</param>
        public override void Send(Rock.Model.Communication communication, int mediumEntityTypeId, Dictionary <string, string> mediumAttributes)
        {
            using (var communicationRockContext = new RockContext())
            {
                // Requery the Communication
                communication = new CommunicationService(communicationRockContext)
                                .Queryable()
                                .Include(a => a.CreatedByPersonAlias.Person)
                                .Include(a => a.CommunicationTemplate)
                                .FirstOrDefault(c => c.Id == communication.Id);

                bool hasPendingRecipients;
                if (communication != null &&
                    communication.Status == Model.CommunicationStatus.Approved &&
                    (!communication.FutureSendDateTime.HasValue || communication.FutureSendDateTime.Value.CompareTo(RockDateTime.Now) <= 0))
                {
                    var qryRecipients = new CommunicationRecipientService(communicationRockContext).Queryable();

                    hasPendingRecipients = qryRecipients
                                           .Where(r =>
                                                  r.CommunicationId == communication.Id &&
                                                  r.Status == Model.CommunicationRecipientStatus.Pending &&
                                                  r.MediumEntityTypeId.HasValue &&
                                                  r.MediumEntityTypeId.Value == mediumEntityTypeId)
                                           .Any();
                }
                else
                {
                    hasPendingRecipients = false;
                }

                if (!hasPendingRecipients)
                {
                    return;
                }

                var    currentPerson      = communication.CreatedByPersonAlias?.Person;
                var    globalAttributes   = Rock.Web.Cache.GlobalAttributesCache.Read();
                string publicAppRoot      = globalAttributes.GetValue("PublicApplicationRoot").EnsureTrailingForwardslash();
                var    mergeFields        = Rock.Lava.LavaHelper.GetCommonMergeFields(null, currentPerson);
                var    cssInliningEnabled = communication.CommunicationTemplate?.CssInliningEnabled ?? false;

                string fromAddress = communication.FromEmail;
                string fromName    = communication.FromName;

                // Resolve any possible merge fields in the from address
                fromAddress = fromAddress.ResolveMergeFields(mergeFields, currentPerson, communication.EnabledLavaCommands);
                fromName    = fromName.ResolveMergeFields(mergeFields, currentPerson, communication.EnabledLavaCommands);

                // From - if none is set, use the one in the Organization's GlobalAttributes.
                if (string.IsNullOrWhiteSpace(fromAddress))
                {
                    fromAddress = globalAttributes.GetValue("OrganizationEmail");
                }

                if (string.IsNullOrWhiteSpace(fromName))
                {
                    fromName = globalAttributes.GetValue("OrganizationName");
                }

                MailMessage message = new MailMessage();

                // Reply To
                try
                {
                    string replyTo = communication.ReplyToEmail;
                    if (!string.IsNullOrWhiteSpace(replyTo))
                    {
                        // Resolve any possible merge fields in the replyTo address
                        message.ReplyToList.Add(new MailAddress(replyTo.ResolveMergeFields(mergeFields, currentPerson)));
                    }
                }
                catch { }

                message.IsBodyHtml = true;
                message.Priority   = MailPriority.Normal;

                using (var smtpClient = GetSmtpClient())
                {
                    var personEntityTypeId        = EntityTypeCache.Read("Rock.Model.Person").Id;
                    var communicationEntityTypeId = EntityTypeCache.Read("Rock.Model.Communication").Id;
                    var communicationCategoryId   = CategoryCache.Read(Rock.SystemGuid.Category.HISTORY_PERSON_COMMUNICATIONS.AsGuid(), communicationRockContext).Id;

                    bool recipientFound = true;
                    while (recipientFound)
                    {
                        // make a new rockContext per recipient
                        var recipientRockContext = new RockContext();
                        var recipient            = Rock.Model.Communication.GetNextPending(communication.Id, mediumEntityTypeId, recipientRockContext);
                        if (recipient != null)
                        {
                            if (ValidRecipient(recipient, communication.IsBulkCommunication))
                            {
                                try
                                {
                                    message.To.Clear();
                                    message.CC.Clear();
                                    message.Bcc.Clear();
                                    message.Headers.Clear();
                                    message.AlternateViews.Clear();

                                    // Set From/To and check safe sender
                                    message.From = new MailAddress(fromAddress, fromName);
                                    message.To.Add(new MailAddress(recipient.PersonAlias.Person.Email, recipient.PersonAlias.Person.FullName));
                                    CheckSafeSender(message, globalAttributes);

                                    // Create merge field dictionary
                                    var mergeObjects = recipient.CommunicationMergeValues(mergeFields);

                                    // CC
                                    string cc = communication.CCEmails;
                                    if (!string.IsNullOrWhiteSpace(cc))
                                    {
                                        // Resolve any possible merge fields in the cc address
                                        cc = cc.ResolveMergeFields(mergeObjects, currentPerson);
                                        foreach (string ccRecipient in cc.SplitDelimitedValues())
                                        {
                                            message.CC.Add(new MailAddress(ccRecipient));
                                        }
                                    }

                                    // BCC
                                    string bcc = communication.BCCEmails;
                                    if (!string.IsNullOrWhiteSpace(bcc))
                                    {
                                        bcc = bcc.ResolveMergeFields(mergeObjects, currentPerson);
                                        foreach (string bccRecipient in bcc.SplitDelimitedValues())
                                        {
                                            // Resolve any possible merge fields in the bcc address
                                            message.Bcc.Add(new MailAddress(bccRecipient));
                                        }
                                    }

                                    // Subject
                                    message.Subject = ResolveText(communication.Subject, currentPerson, communication.EnabledLavaCommands, mergeObjects, publicAppRoot);

                                    // Plain text
                                    if (mediumAttributes.ContainsKey("DefaultPlainText"))
                                    {
                                        string plainText = ResolveText(mediumAttributes["DefaultPlainText"], currentPerson, communication.EnabledLavaCommands, mergeObjects, publicAppRoot);
                                        if (!string.IsNullOrWhiteSpace(plainText))
                                        {
                                            AlternateView plainTextView = AlternateView.CreateAlternateViewFromString(plainText, new System.Net.Mime.ContentType(MediaTypeNames.Text.Plain));
                                            message.AlternateViews.Add(plainTextView);
                                        }
                                    }

                                    // Add Html view
                                    // Get the unsubscribe content and add a merge field for it
                                    string htmlBody = communication.Message;
                                    if (communication.IsBulkCommunication && mediumAttributes.ContainsKey("UnsubscribeHTML"))
                                    {
                                        string unsubscribeHtml = ResolveText(mediumAttributes["UnsubscribeHTML"], currentPerson, communication.EnabledLavaCommands, mergeObjects, publicAppRoot);
                                        mergeObjects.AddOrReplace("UnsubscribeOption", unsubscribeHtml);
                                        htmlBody = ResolveText(htmlBody, currentPerson, communication.EnabledLavaCommands, mergeObjects, publicAppRoot);

                                        // Resolve special syntax needed if option was included in global attribute
                                        if (Regex.IsMatch(htmlBody, @"\[\[\s*UnsubscribeOption\s*\]\]"))
                                        {
                                            htmlBody = Regex.Replace(htmlBody, @"\[\[\s*UnsubscribeOption\s*\]\]", unsubscribeHtml);
                                        }

                                        // Add the unsubscribe option at end if it wasn't included in content
                                        if (!htmlBody.Contains(unsubscribeHtml))
                                        {
                                            htmlBody += unsubscribeHtml;
                                        }
                                    }
                                    else
                                    {
                                        htmlBody = ResolveText(htmlBody, currentPerson, communication.EnabledLavaCommands, mergeObjects, publicAppRoot);
                                        htmlBody = Regex.Replace(htmlBody, @"\[\[\s*UnsubscribeOption\s*\]\]", string.Empty);
                                    }

                                    if (!string.IsNullOrWhiteSpace(htmlBody))
                                    {
                                        if (cssInliningEnabled)
                                        {
                                            // move styles inline to help it be compatible with more email clients
                                            htmlBody = htmlBody.ConvertHtmlStylesToInlineAttributes();
                                        }

                                        // add the main Html content to the email
                                        AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, new System.Net.Mime.ContentType(MediaTypeNames.Text.Html));
                                        message.AlternateViews.Add(htmlView);
                                    }

                                    // Add any additional headers that specific SMTP provider needs
                                    var metaData = new Dictionary <string, string>();
                                    metaData.Add("communication_recipient_guid", recipient.Guid.ToString());
                                    AddAdditionalHeaders(message, metaData);

                                    // Recreate the attachments
                                    message.Attachments.Clear();
                                    foreach (var binaryFile in communication.GetAttachments(CommunicationType.Email).Select(a => a.BinaryFile))
                                    {
                                        message.Attachments.Add(new Attachment(binaryFile.ContentStream, binaryFile.FileName));
                                    }

                                    smtpClient.Send(message);
                                    recipient.Status = CommunicationRecipientStatus.Delivered;

                                    string statusNote = StatusNote;
                                    if (!string.IsNullOrWhiteSpace(statusNote))
                                    {
                                        recipient.StatusNote = statusNote;
                                    }

                                    recipient.TransportEntityTypeName = this.GetType().FullName;

                                    try
                                    {
                                        var historyService = new HistoryService(recipientRockContext);
                                        historyService.Add(new History
                                        {
                                            CreatedByPersonAliasId = communication.SenderPersonAliasId,
                                            EntityTypeId           = personEntityTypeId,
                                            CategoryId             = communicationCategoryId,
                                            EntityId            = recipient.PersonAlias.PersonId,
                                            Summary             = string.Format("Sent communication from <span class='field-value'>{0}</span>.", message.From.DisplayName),
                                            Caption             = message.Subject,
                                            RelatedEntityTypeId = communicationEntityTypeId,
                                            RelatedEntityId     = communication.Id
                                        });
                                    }
                                    catch (Exception ex)
                                    {
                                        ExceptionLogService.LogException(ex, null);
                                    }
                                }

                                catch (Exception ex)
                                {
                                    ExceptionLogService.LogException(ex);
                                    recipient.Status     = CommunicationRecipientStatus.Failed;
                                    recipient.StatusNote = "Exception: " + ex.Messages().AsDelimited(" => ");
                                }
                            }

                            recipientRockContext.SaveChanges();
                        }
                        else
                        {
                            recipientFound = false;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Job that will run quick SQL queries on a schedule.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            Guid?entryWorkflowType = dataMap.GetString("EraEntryWorkflow").AsGuidOrNull();
            Guid?exitWorkflowType  = dataMap.GetString("EraExitWorkflow").AsGuidOrNull();
            bool updateVisitDates  = dataMap.GetBooleanValue("SetVisitDates");
            var  groupTypeList     = dataMap.GetString("GroupTypes");

            // configuration
            //

            // giving
            int exitGivingCount = 1;

            // attendance
            int exitAttendanceCountShort = 1;
            int exitAttendanceCountLong  = 8;

            // get era dataset from stored proc
            var resultContext = new RockContext();


            var eraAttribute      = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_CURRENTLY_AN_ERA.AsGuid());
            var eraStartAttribute = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_START_DATE.AsGuid());
            var eraEndAttribute   = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_END_DATE.AsGuid());

            resultContext.Database.CommandTimeout = 3600;

            var results = resultContext.Database.SqlQuery <EraResult>("spCrm_FamilyAnalyticsEraDataset").ToList();

            int personEntityTypeId        = EntityTypeCache.Read("Rock.Model.Person").Id;
            int attributeEntityTypeId     = EntityTypeCache.Read("Rock.Model.Attribute").Id;
            int eraAttributeId            = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_CURRENTLY_AN_ERA.AsGuid()).Id;
            int personAnalyticsCategoryId = CategoryCache.Read(SystemGuid.Category.HISTORY_PERSON_ANALYTICS.AsGuid()).Id;

            foreach (var result in results)
            {
                // create new rock context for each family (https://weblog.west-wind.com/posts/2014/Dec/21/Gotcha-Entity-Framework-gets-slow-in-long-Iteration-Loops)
                RockContext updateContext         = new RockContext();
                var         attributeValueService = new AttributeValueService(updateContext);
                var         historyService        = new HistoryService(updateContext);

                // if era ensure it still meets requirements
                if (result.IsEra)
                {
                    if (result.ExitGiftCountDuration < exitGivingCount && result.ExitAttendanceCountDurationShort < exitAttendanceCountShort && result.ExitAttendanceCountDurationLong < exitAttendanceCountLong)
                    {
                        // exit era (delete attribute value from each person in family)
                        var family = new GroupService(updateContext).Queryable("Members, Members.Person").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault();

                        if (family != null)
                        {
                            foreach (var person in family.Members.Select(m => m.Person))
                            {
                                // remove the era flag
                                var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                                if (eraAttributeValue != null)
                                {
                                    attributeValueService.Delete(eraAttributeValue);
                                }

                                // set end date
                                var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                                if (eraEndAttributeValue == null)
                                {
                                    eraEndAttributeValue             = new AttributeValue();
                                    eraEndAttributeValue.EntityId    = person.Id;
                                    eraEndAttributeValue.AttributeId = eraEndAttribute.Id;
                                    attributeValueService.Add(eraEndAttributeValue);
                                }
                                eraEndAttributeValue.Value = RockDateTime.Now.ToString();

                                // add a history record
                                if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0)
                                {
                                    History historyRecord = new History();
                                    historyService.Add(historyRecord);
                                    historyRecord.EntityTypeId           = personEntityTypeId;
                                    historyRecord.EntityId               = person.Id;
                                    historyRecord.CreatedDateTime        = RockDateTime.Now;
                                    historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId;
                                    historyRecord.Caption             = "eRA";
                                    historyRecord.Summary             = "Exited eRA Status";
                                    historyRecord.Verb                = "EXITED";
                                    historyRecord.RelatedEntityTypeId = attributeEntityTypeId;
                                    historyRecord.RelatedEntityId     = eraAttributeId;
                                    historyRecord.CategoryId          = personAnalyticsCategoryId;
                                }

                                updateContext.SaveChanges();
                            }

                            // launch exit workflow
                            if (exitWorkflowType.HasValue)
                            {
                                LaunchWorkflow(exitWorkflowType.Value, family);
                            }
                        }
                    }
                }
                else
                {
                    // entered era
                    var family = new GroupService(updateContext).Queryable("Members").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault();

                    if (family != null)
                    {
                        foreach (var person in family.Members.Select(m => m.Person))
                        {
                            // set era attribute to true
                            var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraAttributeValue == null)
                            {
                                eraAttributeValue             = new AttributeValue();
                                eraAttributeValue.EntityId    = person.Id;
                                eraAttributeValue.AttributeId = eraAttribute.Id;
                                attributeValueService.Add(eraAttributeValue);
                            }
                            eraAttributeValue.Value = bool.TrueString;

                            // add start date
                            var eraStartAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraStartAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraStartAttributeValue == null)
                            {
                                eraStartAttributeValue             = new AttributeValue();
                                eraStartAttributeValue.EntityId    = person.Id;
                                eraStartAttributeValue.AttributeId = eraStartAttribute.Id;
                                attributeValueService.Add(eraStartAttributeValue);
                            }
                            eraStartAttributeValue.Value = RockDateTime.Now.ToString();

                            // delete end date if it exists
                            var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraEndAttributeValue != null)
                            {
                                attributeValueService.Delete(eraEndAttributeValue);
                            }

                            // add a history record
                            if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0)
                            {
                                History historyRecord = new History();
                                historyService.Add(historyRecord);
                                historyRecord.EntityTypeId           = personEntityTypeId;
                                historyRecord.EntityId               = person.Id;
                                historyRecord.CreatedDateTime        = RockDateTime.Now;
                                historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId;
                                historyRecord.Caption             = "eRA";
                                historyRecord.Summary             = "Entered eRA Status";
                                historyRecord.Verb                = "ENTERED";
                                historyRecord.RelatedEntityTypeId = attributeEntityTypeId;
                                historyRecord.RelatedEntityId     = eraAttributeId;
                                historyRecord.CategoryId          = personAnalyticsCategoryId;
                            }

                            updateContext.SaveChanges();
                        }

                        // launch entry workflow
                        if (entryWorkflowType.HasValue)
                        {
                            LaunchWorkflow(entryWorkflowType.Value, family);
                        }
                    }
                }

                // update stats
            }

            // load giving attributes
            resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsGiving");

            // load attendance attributes
            resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsAttendance");

            // process history for group types
            if (!string.IsNullOrWhiteSpace(groupTypeList))
            {
                string[] groupTypeGuids = groupTypeList.Split(',');

                var inactiveRecordValue = DefinedValueCache.Read(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE);

                var groupTypeEntityTypeId = EntityTypeCache.Read("Rock.Model.GroupType").Id;

                foreach (var groupTypeGuid in groupTypeGuids)
                {
                    var groupType = GroupTypeCache.Read(groupTypeGuid.AsGuid());

                    if (groupType != null)
                    {
                        // if the person is in a group of that type and the last history record for that group type isn't START write a start
                        RockContext rockContext = new RockContext();

                        // get history for this group type
                        var historyRecords = new HistoryService(rockContext).Queryable()
                                             .Where(h =>
                                                    h.EntityTypeId == personEntityTypeId &&
                                                    h.RelatedEntityTypeId == groupTypeEntityTypeId &&
                                                    h.RelatedEntityId == groupType.Id
                                                    )
                                             .GroupBy(h => h.EntityId)
                                             .Select(g => g.OrderByDescending(h => h.CreatedDateTime).Select(h => new { h.EntityId, h.Verb }).FirstOrDefault())
                                             .ToList();

                        // get group member information
                        var groupMemberInfo = new GroupMemberService(rockContext).Queryable()
                                              .Where(m =>
                                                     m.Group.GroupTypeId == groupType.Id &&
                                                     m.GroupMemberStatus == GroupMemberStatus.Active &&
                                                     m.Group.IsActive
                                                     //&& m.Person.RecordStatusValueId != inactiveRecordValue.Id
                                                     )
                                              .GroupBy(m => m.PersonId)
                                              .Select(g => g.OrderBy(m => m.CreatedDateTime).Select(m => new { m.PersonId, m.CreatedDateTime, PersonAliasId = m.Person.Aliases.Select(p => p.Id).FirstOrDefault() }).FirstOrDefault())
                                              .ToList();

                        var needsStartDate = groupMemberInfo.Where(m => !historyRecords.Any(h => h.EntityId == m.PersonId && h.Verb == "STARTED"));

                        foreach (var startItem in needsStartDate)
                        {
                            using (RockContext updateContext = new RockContext())
                            {
                                var     historyService = new HistoryService(updateContext);
                                History history        = new History();
                                historyService.Add(history);
                                history.EntityTypeId        = personEntityTypeId;
                                history.EntityId            = startItem.PersonId;
                                history.RelatedEntityTypeId = groupTypeEntityTypeId;
                                history.RelatedEntityId     = groupType.Id;
                                history.Caption             = groupType.Name;
                                history.Summary             = "Started Membership in Group Of Type";
                                history.Verb                   = "STARTED";
                                history.CreatedDateTime        = startItem.CreatedDateTime;
                                history.CreatedByPersonAliasId = startItem.PersonAliasId;
                                history.CategoryId             = personAnalyticsCategoryId;

                                updateContext.SaveChanges();
                            }
                        }

                        var needsStoppedDate = historyRecords.Where(h => h.Verb == "STARTED" && !groupMemberInfo.Any(m => m.PersonId == h.EntityId));

                        foreach (var stopItem in needsStoppedDate)
                        {
                            using (RockContext updateContext = new RockContext())
                            {
                                var person = new PersonService(updateContext).Get(stopItem.EntityId);

                                if (person != null)
                                {
                                    var     historyService = new HistoryService(updateContext);
                                    History history        = new History();
                                    historyService.Add(history);
                                    history.EntityTypeId        = personEntityTypeId;
                                    history.EntityId            = person.Id;
                                    history.RelatedEntityTypeId = groupTypeEntityTypeId;
                                    history.RelatedEntityId     = groupType.Id;
                                    history.Caption             = groupType.Name;
                                    history.Summary             = "Stopped Membership in Group Of Type";
                                    history.Verb                   = "STOPPED";
                                    history.CreatedDateTime        = RockDateTime.Now;
                                    history.CreatedByPersonAliasId = person.PrimaryAliasId;
                                    history.CategoryId             = personAnalyticsCategoryId;

                                    updateContext.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }

            // process visit dates
            if (updateVisitDates)
            {
                resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsUpdateVisitDates");
            }
        }
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="mergeTemplate">The merge template.</param>
        public void ShowEditDetails(MergeTemplate mergeTemplate)
        {
            if (mergeTemplate.Id > 0)
            {
                lActionTitle.Text = ActionTitle.Edit(mergeTemplate.ToString()).FormatAsHtmlTitle();
            }
            else
            {
                lActionTitle.Text = ActionTitle.Add(MergeTemplate.FriendlyTypeName).FormatAsHtmlTitle();
            }

            SetEditMode(true);

            var mergeTemplateOwnership = this.GetAttributeValue("MergeTemplatesOwnership").ConvertToEnum <MergeTemplateOwnership>(MergeTemplateOwnership.Global);

            if (this.IsUserAuthorized(Authorization.EDIT))
            {
                // If Authorized to EDIT, owner should be able to be changed, or converted to Global
                ppPerson.Visible               = true;
                ppPerson.Required              = false;
                cpCategory.Visible             = true;
                cpCategory.ExcludedCategoryIds = string.Empty;
            }
            else if (mergeTemplateOwnership == MergeTemplateOwnership.Global)
            {
                ppPerson.Visible               = false;
                ppPerson.Required              = false;
                cpCategory.Visible             = true;
                cpCategory.ExcludedCategoryIds = CategoryCache.Read(Rock.SystemGuid.Category.PERSONAL_MERGE_TEMPLATE.AsGuid()).Id.ToString();
            }
            else if (mergeTemplateOwnership == MergeTemplateOwnership.Personal)
            {
                // if ONLY personal merge templates are permitted, hide the category since it'll always be saved in the personal category
                cpCategory.Visible = false;

                // merge template should be only for the current person, so hide the person picker
                ppPerson.Visible = false;

                // it is required, but not shown..
                ppPerson.Required = false;
            }
            else if (mergeTemplateOwnership == MergeTemplateOwnership.PersonalAndGlobal)
            {
                ppPerson.Visible               = true;
                ppPerson.Required              = false;
                cpCategory.Visible             = true;
                cpCategory.ExcludedCategoryIds = string.Empty;
            }

            tbName.Text        = mergeTemplate.Name;
            tbDescription.Text = mergeTemplate.Description;

            LoadDropDowns();

            ddlMergeTemplateType.SetValue(mergeTemplate.MergeTemplateTypeEntityTypeId);

            fuTemplateBinaryFile.BinaryFileTypeGuid = Rock.SystemGuid.BinaryFiletype.MERGE_TEMPLATE.AsGuid();
            fuTemplateBinaryFile.BinaryFileId       = mergeTemplate.TemplateBinaryFileId;

            cpCategory.AllowMultiSelect = false;
            cpCategory.SetValue(mergeTemplate.CategoryId);
            if (mergeTemplate.PersonAliasId.HasValue)
            {
                ppPerson.SetValue(mergeTemplate.PersonAlias.Person);
            }
            else
            {
                ppPerson.SetValue(null);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Handles the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

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

            RockContext rockContext = new RockContext();

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

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

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

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

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

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

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

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

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

        $('#{0}').on('cross', function(){{
            $('#{3}').prop('disabled', true);
        }});
        $('#{0}').on('uncross', function(){{
            $('#{3}').prop('disabled', false);
        }});
    }};
    $(document).ready(function () {{ SetCharacterLimit(); }});
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(SetCharacterLimit);
";
                string script       = string.Format(scriptFormat, dtbRequest.ClientID, charLimit, lblCount.ClientID, lbSave.ClientID);
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), string.Format("limit-{0}", this.ClientID), script, true);
            }
        }
        /// <summary>
        /// Handles the Click event 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)
        {
            MergeTemplate        mergeTemplate;
            var                  rockContext          = new RockContext();
            MergeTemplateService mergeTemplateService = new MergeTemplateService(rockContext);

            int mergeTemplateId  = hfMergeTemplateId.Value.AsInteger();
            int?origBinaryFileId = null;

            if (mergeTemplateId == 0)
            {
                mergeTemplate = new MergeTemplate();
                mergeTemplateService.Add(mergeTemplate);
            }
            else
            {
                mergeTemplate    = mergeTemplateService.Get(mergeTemplateId);
                origBinaryFileId = mergeTemplate.TemplateBinaryFileId;
            }

            mergeTemplate.Name        = tbName.Text;
            mergeTemplate.Description = tbDescription.Text;
            mergeTemplate.MergeTemplateTypeEntityTypeId = ddlMergeTemplateType.SelectedValue.AsInteger();
            mergeTemplate.TemplateBinaryFileId          = fuTemplateBinaryFile.BinaryFileId ?? 0;
            mergeTemplate.PersonAliasId = ppPerson.PersonAliasId;
            mergeTemplate.CategoryId    = cpCategory.SelectedValue.AsInteger();

            int personalMergeTemplateCategoryId = CategoryCache.Read(Rock.SystemGuid.Category.PERSONAL_MERGE_TEMPLATE.AsGuid()).Id;

            if (mergeTemplate.PersonAliasId.HasValue)
            {
                if (mergeTemplate.CategoryId == 0)
                {
                    // if the category picker isn't shown and/or the category isn't selected, and it's a personal filter...
                    mergeTemplate.CategoryId = personalMergeTemplateCategoryId;
                }

                // ensure Personal templates are only in the Personal merge template category
                if (mergeTemplate.CategoryId != personalMergeTemplateCategoryId)
                {
                    // prohibit personal templates from being in something other than the Personal category
                    cpCategory.Visible = true;
                    cpCategory.ShowErrorMessage("Personal Merge Templates must be in Personal category");
                }
            }
            else
            {
                if (mergeTemplate.CategoryId == personalMergeTemplateCategoryId)
                {
                    // prohibit global templates from being in Personal category
                    cpCategory.ShowErrorMessage("Person is required when using the Personal category");
                }
            }

            if (!mergeTemplate.IsValid || !Page.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            BinaryFileService binaryFileService = new BinaryFileService(rockContext);

            if (origBinaryFileId.HasValue && origBinaryFileId.Value != mergeTemplate.TemplateBinaryFileId)
            {
                // if a new the binaryFile was uploaded, mark the old one as Temporary so that it gets cleaned up
                var oldBinaryFile = binaryFileService.Get(origBinaryFileId.Value);
                if (oldBinaryFile != null && !oldBinaryFile.IsTemporary)
                {
                    oldBinaryFile.IsTemporary = true;
                }
            }

            // ensure the IsTemporary is set to false on binaryFile associated with this MergeTemplate
            var binaryFile = binaryFileService.Get(mergeTemplate.TemplateBinaryFileId);

            if (binaryFile != null && binaryFile.IsTemporary)
            {
                binaryFile.IsTemporary = false;
            }

            rockContext.SaveChanges();

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

            qryParams["ExpandedIds"]     = PageParameter("ExpandedIds");
            qryParams["MergeTemplateId"] = mergeTemplate.Id.ToString();
            NavigateToPage(RockPage.Guid, qryParams);
        }
Esempio n. 12
0
        /// <summary>
        /// Sends the specified communication.
        /// </summary>
        /// <param name="communication">The communication.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        public override void Send(Rock.Model.Communication communication)
        {
            using (var communicationRockContext = new RockContext())
            {
                // Requery the Communication object in case we need to load any properties from the database
                communication = new CommunicationService(communicationRockContext)
                                .Queryable("CreatedByPersonAlias.Person")
                                .FirstOrDefault(c => c.Id == communication.Id);

                bool hasPendingRecipients;
                if (communication != null &&
                    communication.Status == Model.CommunicationStatus.Approved &&
                    (!communication.FutureSendDateTime.HasValue || communication.FutureSendDateTime.Value.CompareTo(RockDateTime.Now) <= 0))
                {
                    var qryRecipients = new CommunicationRecipientService(communicationRockContext).Queryable();
                    hasPendingRecipients = qryRecipients.Where(a => a.CommunicationId == communication.Id).Where(r => r.Status == Model.CommunicationRecipientStatus.Pending).Any();
                }
                else
                {
                    hasPendingRecipients = false;
                }

                if (hasPendingRecipients)
                {
                    var currentPerson      = communication.CreatedByPersonAlias.Person;
                    var globalAttributes   = Rock.Web.Cache.GlobalAttributesCache.Read();
                    var globalConfigValues = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(currentPerson);

                    // From - if none is set, use the one in the Organization's GlobalAttributes.
                    string fromAddress = communication.GetMediumDataValue("FromAddress");
                    if (string.IsNullOrWhiteSpace(fromAddress))
                    {
                        fromAddress = globalAttributes.GetValue("OrganizationEmail");
                    }

                    string fromName = communication.GetMediumDataValue("FromName");
                    if (string.IsNullOrWhiteSpace(fromName))
                    {
                        fromName = globalAttributes.GetValue("OrganizationName");
                    }

                    // Resolve any possible merge fields in the from address
                    fromAddress = fromAddress.ResolveMergeFields(globalConfigValues, currentPerson);
                    fromName    = fromName.ResolveMergeFields(globalConfigValues, currentPerson);

                    MailMessage message = new MailMessage();
                    message.From = new MailAddress(fromAddress, fromName);

                    // Reply To
                    try
                    {
                        string replyTo = communication.GetMediumDataValue("ReplyTo");
                        if (!string.IsNullOrWhiteSpace(replyTo))
                        {
                            message.ReplyToList.Add(new MailAddress(replyTo));
                        }
                    }
                    catch { }

                    CheckSafeSender(message, globalAttributes);

                    // CC
                    string cc = communication.GetMediumDataValue("CC");
                    if (!string.IsNullOrWhiteSpace(cc))
                    {
                        foreach (string ccRecipient in cc.SplitDelimitedValues())
                        {
                            message.CC.Add(new MailAddress(ccRecipient));
                        }
                    }

                    // BCC
                    string bcc = communication.GetMediumDataValue("BCC");
                    if (!string.IsNullOrWhiteSpace(bcc))
                    {
                        foreach (string bccRecipient in bcc.SplitDelimitedValues())
                        {
                            message.Bcc.Add(new MailAddress(bccRecipient));
                        }
                    }

                    message.IsBodyHtml = true;
                    message.Priority   = MailPriority.Normal;

                    using (var smtpClient = GetSmtpClient())
                    {
                        // Add Attachments
                        string attachmentIds = communication.GetMediumDataValue("Attachments");
                        if (!string.IsNullOrWhiteSpace(attachmentIds))
                        {
                            var binaryFileService = new BinaryFileService(communicationRockContext);

                            foreach (string idVal in attachmentIds.SplitDelimitedValues())
                            {
                                int binaryFileId = int.MinValue;
                                if (int.TryParse(idVal, out binaryFileId))
                                {
                                    var binaryFile = binaryFileService.Get(binaryFileId);
                                    if (binaryFile != null)
                                    {
                                        message.Attachments.Add(new Attachment(binaryFile.ContentStream, binaryFile.FileName));
                                    }
                                }
                            }
                        }

                        var personEntityTypeId        = EntityTypeCache.Read("Rock.Model.Person").Id;
                        var communicationEntityTypeId = EntityTypeCache.Read("Rock.Model.Communication").Id;
                        var communicationCategoryId   = CategoryCache.Read(Rock.SystemGuid.Category.HISTORY_PERSON_COMMUNICATIONS.AsGuid(), communicationRockContext).Id;

                        bool recipientFound = true;
                        while (recipientFound)
                        {
                            // make a new rockContext per recipient so that DbChangeTracker doesn't get gummed up on large communications
                            var recipientRockContext = new RockContext();
                            var recipient            = Rock.Model.Communication.GetNextPending(communication.Id, recipientRockContext);
                            if (recipient != null)
                            {
                                if (string.IsNullOrWhiteSpace(recipient.PersonAlias.Person.Email))
                                {
                                    recipient.Status     = CommunicationRecipientStatus.Failed;
                                    recipient.StatusNote = "No Email Address";
                                }
                                else
                                {
                                    try
                                    {
                                        message.To.Clear();
                                        message.Headers.Clear();
                                        message.AlternateViews.Clear();

                                        message.To.Add(new MailAddress(recipient.PersonAlias.Person.Email, recipient.PersonAlias.Person.FullName));

                                        // Create merge field dictionary
                                        var mergeObjects = recipient.CommunicationMergeValues(globalConfigValues);

                                        // Subject
                                        message.Subject = communication.Subject.ResolveMergeFields(mergeObjects, currentPerson);

                                        // convert any special microsoft word characters to normal chars so they don't look funny (for example "Hey “double-quotes” from ‘single quote’")
                                        message.Subject = message.Subject.ReplaceWordChars();

                                        // Add any additional headers that specific SMTP provider needs
                                        AddAdditionalHeaders(message, recipient);

                                        // Add text view first as last view is usually treated as the preferred view by email readers (gmail)
                                        string plainTextBody = Rock.Communication.Medium.Email.ProcessTextBody(communication, globalAttributes, mergeObjects, currentPerson);

                                        // convert any special microsoft word characters to normal chars so they don't look funny
                                        plainTextBody = plainTextBody.ReplaceWordChars();

                                        if (!string.IsNullOrWhiteSpace(plainTextBody))
                                        {
                                            AlternateView plainTextView = AlternateView.CreateAlternateViewFromString(plainTextBody, new System.Net.Mime.ContentType(MediaTypeNames.Text.Plain));
                                            message.AlternateViews.Add(plainTextView);
                                        }

                                        // Add Html view
                                        string htmlBody = Rock.Communication.Medium.Email.ProcessHtmlBody(communication, globalAttributes, mergeObjects, currentPerson);

                                        // convert any special microsoft word characters to normal chars so they don't look funny
                                        htmlBody = htmlBody.ReplaceWordChars();

                                        if (!string.IsNullOrWhiteSpace(htmlBody))
                                        {
                                            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, new System.Net.Mime.ContentType(MediaTypeNames.Text.Html));
                                            message.AlternateViews.Add(htmlView);
                                        }

                                        smtpClient.Send(message);
                                        recipient.Status = CommunicationRecipientStatus.Delivered;

                                        string statusNote = StatusNote;
                                        if (!string.IsNullOrWhiteSpace(statusNote))
                                        {
                                            recipient.StatusNote = statusNote;
                                        }

                                        recipient.TransportEntityTypeName = this.GetType().FullName;

                                        var historyService = new HistoryService(recipientRockContext);
                                        historyService.Add(new History
                                        {
                                            CreatedByPersonAliasId = communication.SenderPersonAliasId,
                                            EntityTypeId           = personEntityTypeId,
                                            CategoryId             = communicationCategoryId,
                                            EntityId            = recipient.PersonAlias.PersonId,
                                            Summary             = string.Format("Sent communication from <span class='field-value'>{0}</span>.", message.From.DisplayName),
                                            Caption             = message.Subject,
                                            RelatedEntityTypeId = communicationEntityTypeId,
                                            RelatedEntityId     = communication.Id
                                        });
                                    }

                                    catch (Exception ex)
                                    {
                                        recipient.Status     = CommunicationRecipientStatus.Failed;
                                        recipient.StatusNote = "Exception: " + ex.Message;
                                    }
                                }

                                recipientRockContext.SaveChanges();
                            }
                            else
                            {
                                recipientFound = false;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 13
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());
            var noteService     = new NoteService(rockContext);
            var prayerComments  = noteService.GetByNoteTypeId(noteType.Id);

            SortProperty sortProperty = gPrayerComments.SortProperty;

            // Filter by Category.  First see if there is a Block Setting, otherwise use the Grid Filter
            CategoryCache categoryFilter    = null;
            var           blockCategoryGuid = GetAttributeValue("PrayerRequestCategory").AsGuidOrNull();

            if (blockCategoryGuid.HasValue)
            {
                categoryFilter = CategoryCache.Read(blockCategoryGuid.Value);
            }

            if (categoryFilter == null && catpPrayerCategoryFilter.Visible)
            {
                int?filterCategoryId = catpPrayerCategoryFilter.SelectedValue.AsIntegerOrNull();
                if (filterCategoryId.HasValue)
                {
                    categoryFilter = CategoryCache.Read(filterCategoryId.Value);
                }
            }

            if (categoryFilter != null)
            {
                // if filtered by category, only show comments for prayer requests in that category or any of its decendent categories
                var categoryService = new CategoryService(rockContext);
                var categories      = new CategoryService(rockContext).GetAllDescendents(categoryFilter.Guid).Select(a => a.Id).ToList();

                var prayerRequestQry = new PrayerRequestService(rockContext).Queryable().Where(a => a.CategoryId.HasValue &&
                                                                                               (a.Category.Guid == categoryFilter.Guid || 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.OrderByDescending(n => n.CreatedDateTime).ToList();
            }

            gPrayerComments.DataBind();
        }
Esempio n. 14
0
        private void CreateControls(List <GroupMember> familyMembers, bool setSelection)
        {
            // Load all the attribute controls
            attributeControls.Clear();
            pnlAttributes.Controls.Clear();

            foreach (string categoryGuid in GetAttributeValue("AttributeCategories").SplitDelimitedValues(false))
            {
                Guid guid = Guid.Empty;
                if (Guid.TryParse(categoryGuid, out guid))
                {
                    var category = CategoryCache.Read(guid);
                    if (category != null)
                    {
                        var attributeControl = new NewFamilyAttributes();
                        attributeControl.ClearRows();
                        pnlAttributes.Controls.Add(attributeControl);
                        attributeControls.Add(attributeControl);
                        attributeControl.ID         = "familyAttributes_" + category.Id.ToString();
                        attributeControl.CategoryId = category.Id;

                        foreach (var attribute in new AttributeService().GetByCategoryId(category.Id))
                        {
                            if (attribute.IsAuthorized("Edit", CurrentPerson))
                            {
                                attributeControl.AttributeList.Add(AttributeCache.Read(attribute));
                            }
                        }
                    }
                }
            }

            nfmMembers.ClearRows();

            int count = 0;

            foreach (var familyMember in familyMembers)
            {
                var familyMemberRow = new NewFamilyMembersRow();
                nfmMembers.Controls.Add(familyMemberRow);
                familyMemberRow.ID            = string.Format("row_{0}", familyMember.Person.Guid.ToString().Replace("-", "_"));
                familyMemberRow.RoleUpdated  += familyMemberRow_RoleUpdated;
                familyMemberRow.DeleteClick  += familyMemberRow_DeleteClick;
                familyMemberRow.PersonGuid    = familyMember.Person.Guid;
                familyMemberRow.RequireGender = _requireGender;
                familyMemberRow.RequireGrade  = _requireGrade;
                familyMemberRow.RoleId        = familyMember.GroupRoleId;
                familyMemberRow.ShowGrade     = familyMember.GroupRoleId == _childRoleId;

                if (setSelection)
                {
                    if (familyMember.Person != null)
                    {
                        familyMemberRow.TitleValueId            = familyMember.Person.TitleValueId;
                        familyMemberRow.FirstName               = familyMember.Person.FirstName;
                        familyMemberRow.NickName                = familyMember.Person.NickName;
                        familyMemberRow.LastName                = familyMember.Person.LastName;
                        familyMemberRow.Gender                  = familyMember.Person.Gender;
                        familyMemberRow.BirthDate               = familyMember.Person.BirthDate;
                        familyMemberRow.ConnectionStatusValueId = familyMember.Person.ConnectionStatusValueId;
                    }
                }

                foreach (var attributeControl in attributeControls)
                {
                    var attributeRow = new NewFamilyAttributesRow();
                    attributeControl.Controls.Add(attributeRow);
                    attributeRow.ID            = string.Format("{0}_{1}", attributeControl.ID, familyMember.Person.Guid);
                    attributeRow.AttributeList = attributeControl.AttributeList;
                    attributeRow.PersonGuid    = familyMember.Person.Guid;

                    if (setSelection)
                    {
                        attributeRow.SetEditValues(familyMember.Person);
                    }
                }

                count++;
            }

            ShowAttributeCategory(CurrentCategoryIndex);
        }
Esempio n. 15
0
        /// <summary>
        /// Sends the specified communication.
        /// </summary>
        /// <param name="communication">The communication.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        public override void Send(Rock.Model.Communication communication)
        {
            var rockContext = new RockContext();

            // Requery the Communication
            communication = new CommunicationService(rockContext).Get(communication.Id);

            if (communication != null &&
                communication.Status == Model.CommunicationStatus.Approved &&
                communication.HasPendingRecipients(rockContext) &&
                (!communication.FutureSendDateTime.HasValue || communication.FutureSendDateTime.Value.CompareTo(RockDateTime.Now) <= 0))
            {
                string fromPhone   = string.Empty;
                string fromValue   = communication.GetMediumDataValue("FromValue");
                int    fromValueId = int.MinValue;
                if (int.TryParse(fromValue, out fromValueId))
                {
                    fromPhone = DefinedValueCache.Read(fromValueId, rockContext).Value;
                }

                if (!string.IsNullOrWhiteSpace(fromPhone))
                {
                    string accountSid = GetAttributeValue("SID");
                    string authToken  = GetAttributeValue("Token");
                    var    twilio     = new TwilioRestClient(accountSid, authToken);

                    var historyService   = new HistoryService(rockContext);
                    var recipientService = new CommunicationRecipientService(rockContext);

                    var personEntityTypeId        = EntityTypeCache.Read("Rock.Model.Person").Id;
                    var communicationEntityTypeId = EntityTypeCache.Read("Rock.Model.Communication").Id;
                    var communicationCategoryId   = CategoryCache.Read(Rock.SystemGuid.Category.HISTORY_PERSON_COMMUNICATIONS.AsGuid(), rockContext).Id;

                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

                    bool recipientFound = true;
                    while (recipientFound)
                    {
                        var recipient = Rock.Model.Communication.GetNextPending(communication.Id, rockContext);
                        if (recipient != null)
                        {
                            try
                            {
                                var phoneNumber = recipient.PersonAlias.Person.PhoneNumbers
                                                  .Where(p => p.IsMessagingEnabled)
                                                  .FirstOrDefault();

                                if (phoneNumber != null)
                                {
                                    // Create merge field dictionary
                                    var    mergeObjects = recipient.CommunicationMergeValues(mergeFields);
                                    string message      = communication.GetMediumDataValue("Message");

                                    // convert any special microsoft word characters to normal chars so they don't look funny (for example "Hey “double-quotes” from ‘single quote’")
                                    message = message.ReplaceWordChars();
                                    message = message.ResolveMergeFields(mergeObjects, communication.EnabledLavaCommands);

                                    string twilioNumber = phoneNumber.Number;
                                    if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                    {
                                        twilioNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                    }

                                    var    globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read();
                                    string callbackUrl      = globalAttributes.GetValue("PublicApplicationRoot") + "Webhooks/Twilio.ashx";

                                    var response = twilio.SendMessage(fromPhone, twilioNumber, message, callbackUrl);

                                    recipient.Status = CommunicationRecipientStatus.Delivered;
                                    recipient.TransportEntityTypeName = this.GetType().FullName;
                                    recipient.UniqueMessageId         = response.Sid;

                                    try
                                    {
                                        historyService.Add(new History
                                        {
                                            CreatedByPersonAliasId = communication.SenderPersonAliasId,
                                            EntityTypeId           = personEntityTypeId,
                                            CategoryId             = communicationCategoryId,
                                            EntityId            = recipient.PersonAlias.PersonId,
                                            Summary             = "Sent SMS message.",
                                            Caption             = message.Truncate(200),
                                            RelatedEntityTypeId = communicationEntityTypeId,
                                            RelatedEntityId     = communication.Id
                                        });
                                    }
                                    catch (Exception ex)
                                    {
                                        ExceptionLogService.LogException(ex, null);
                                    }
                                }
                                else
                                {
                                    recipient.Status     = CommunicationRecipientStatus.Failed;
                                    recipient.StatusNote = "No Phone Number with Messaging Enabled";
                                }
                            }
                            catch (Exception ex)
                            {
                                recipient.Status     = CommunicationRecipientStatus.Failed;
                                recipient.StatusNote = "Twilio Exception: " + ex.Message;
                            }

                            rockContext.SaveChanges();
                        }
                        else
                        {
                            recipientFound = false;
                        }
                    }
                }
            }
        }
Esempio n. 16
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 OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            bool canEditBlock = IsUserAuthorized(Authorization.EDIT);

            // hide all the actions if user doesn't have EDIT to the block
            divTreeviewActions.Visible = canEditBlock;
            hfPageRouteTemplate.Value  = (this.RockPage.RouteData.Route as System.Web.Routing.Route).Url;

            // Get EntityTypeName
            Guid?entityTypeGuid = GetAttributeValue("EntityType").AsGuidOrNull();

            nbWarning.Text    = "Please select an entity type in the block settings.";
            nbWarning.Visible = !entityTypeGuid.HasValue;
            if (entityTypeGuid.HasValue)
            {
                int    entityTypeId             = Rock.Web.Cache.EntityTypeCache.Read(entityTypeGuid.Value).Id;
                string entityTypeQualiferColumn = GetAttributeValue("EntityTypeQualifierProperty");
                string entityTypeQualifierValue = GetAttributeValue("EntityTypeQualifierValue");
                bool   showUnnamedEntityItems   = GetAttributeValue("ShowUnnamedEntityItems").AsBooleanOrNull() ?? true;

                string parms = string.Format("?getCategorizedItems=true&showUnnamedEntityItems={0}", showUnnamedEntityItems.ToTrueFalse().ToLower());
                parms += string.Format("&entityTypeId={0}", entityTypeId);

                var rootCategory = CategoryCache.Read(this.GetAttributeValue("RootCategory").AsGuid());

                // make sure the rootCategory matches the EntityTypeId (just in case they changed the EntityType after setting RootCategory
                if (rootCategory != null && rootCategory.EntityTypeId == entityTypeId)
                {
                    parms += string.Format("&rootCategoryId={0}", rootCategory.Id);
                }

                if (!string.IsNullOrEmpty(entityTypeQualiferColumn))
                {
                    parms += string.Format("&entityQualifier={0}", entityTypeQualiferColumn);

                    if (!string.IsNullOrEmpty(entityTypeQualifierValue))
                    {
                        parms += string.Format("&entityQualifierValue={0}", entityTypeQualifierValue);
                    }
                }

                RestParms = parms;

                var cachedEntityType = Rock.Web.Cache.EntityTypeCache.Read(entityTypeId);
                if (cachedEntityType != null)
                {
                    string entityTypeFriendlyName = GetAttributeValue("EntityTypeFriendlyName");
                    if (string.IsNullOrWhiteSpace(entityTypeFriendlyName))
                    {
                        entityTypeFriendlyName = cachedEntityType.FriendlyName;
                    }

                    lbAddItem.ToolTip = "Add " + entityTypeFriendlyName;
                    lAddItem.Text     = entityTypeFriendlyName;
                }

                PageParameterName = GetAttributeValue("PageParameterKey");
                int?   itemId             = PageParameter(PageParameterName).AsIntegerOrNull();
                string selectedEntityType = cachedEntityType.Name;
                if (!itemId.HasValue)
                {
                    itemId             = PageParameter("CategoryId").AsIntegerOrNull();
                    selectedEntityType = "category";
                }

                lbAddCategoryRoot.Enabled  = true;
                lbAddCategoryChild.Enabled = false;
                lbAddItem.Enabled          = false;

                CategoryCache selectedCategory = null;

                if (itemId.HasValue)
                {
                    hfSelectedItemId.Value = itemId.Value.ToString();
                    List <string> parentIdList = new List <string>();

                    if (selectedEntityType.Equals("category"))
                    {
                        selectedCategory = CategoryCache.Read(itemId.Value);
                    }
                    else
                    {
                        if (cachedEntityType != null)
                        {
                            Type entityType = cachedEntityType.GetEntityType();
                            if (entityType != null)
                            {
                                Type         serviceType     = typeof(Rock.Data.Service <>);
                                Type[]       modelType       = { entityType };
                                Type         service         = serviceType.MakeGenericType(modelType);
                                var          serviceInstance = Activator.CreateInstance(service, new object[] { new RockContext() });
                                var          getMethod       = service.GetMethod("Get", new Type[] { typeof(int) });
                                ICategorized entity          = getMethod.Invoke(serviceInstance, new object[] { itemId }) as ICategorized;

                                if (entity != null)
                                {
                                    lbAddCategoryChild.Enabled = false;
                                    if (entity.CategoryId.HasValue)
                                    {
                                        selectedCategory = CategoryCache.Read(entity.CategoryId.Value);
                                        if (selectedCategory != null)
                                        {
                                            parentIdList.Insert(0, selectedCategory.Id.ToString());
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // get the parents of the selected item so we can tell the treeview to expand those
                    var category = selectedCategory;
                    while (category != null)
                    {
                        category = category.ParentCategory;
                        if (category != null)
                        {
                            parentIdList.Insert(0, category.Id.ToString());
                        }
                    }
                    // also get any additional expanded nodes that were sent in the Post
                    string postedExpandedIds = this.Request.Params["ExpandedIds"];
                    if (!string.IsNullOrWhiteSpace(postedExpandedIds))
                    {
                        var postedExpandedIdList = postedExpandedIds.Split(',').ToList();
                        foreach (var id in postedExpandedIdList)
                        {
                            if (!parentIdList.Contains(id))
                            {
                                parentIdList.Add(id);
                            }
                        }
                    }

                    hfInitialCategoryParentIds.Value = parentIdList.AsDelimited(",");
                }

                selectedCategory = selectedCategory ?? rootCategory;

                if (selectedCategory != null)
                {
                    lbAddItem.Enabled          = true;
                    lbAddCategoryChild.Enabled = true;
                    this.SelectedCategoryId    = selectedCategory.Id;
                }
                else
                {
                    this.SelectedCategoryId = null;
                }
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Creates the specified rock context.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="person">The person.</param>
        /// <param name="serviceType">Type of the service.</param>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <param name="isConfirmed">if set to <c>true</c> [is confirmed].</param>
        /// <param name="isRequirePasswordChange">if set to <c>true</c> [is require password change].</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentOutOfRangeException">username;Username already exists</exception>
        /// <exception cref="System.ArgumentException">
        /// entityTypeId
        /// or
        /// Invalid EntityTypeId, entity does not exist;entityTypeId
        /// or
        /// Invalid Person, person does not exist;person
        /// </exception>
        public static UserLogin Create(RockContext rockContext,
                                       Rock.Model.Person person,
                                       AuthenticationServiceType serviceType,
                                       int entityTypeId,
                                       string username,
                                       string password,
                                       bool isConfirmed,
                                       bool isRequirePasswordChange)
        {
            if (person != null)
            {
                var userLoginService = new UserLoginService(rockContext);

                var entityType = EntityTypeCache.Read(entityTypeId);
                if (entityType != null)
                {
                    UserLogin user = userLoginService.GetByUserName(username);
                    if (user != null)
                    {
                        throw new ArgumentOutOfRangeException("username", "Username already exists");
                    }

                    DateTime createDate = RockDateTime.Now;

                    user              = new UserLogin();
                    user.Guid         = Guid.NewGuid();
                    user.EntityTypeId = entityTypeId;
                    user.UserName     = username;
                    user.IsConfirmed  = isConfirmed;
                    user.LastPasswordChangedDateTime = createDate;
                    user.PersonId = person.Id;
                    user.IsPasswordChangeRequired = isRequirePasswordChange;

                    if (serviceType == AuthenticationServiceType.Internal)
                    {
                        var authenticationComponent = AuthenticationContainer.GetComponent(entityType.Name);
                        if (authenticationComponent == null || !authenticationComponent.IsActive)
                        {
                            throw new ArgumentException(string.Format("'{0}' service does not exist, or is not active", entityType.FriendlyName), "entityTypeId");
                        }

                        user.Password = authenticationComponent.EncodePassword(user, password);
                    }

                    userLoginService.Add(user);
                    rockContext.SaveChanges();

                    var historyCategory = CategoryCache.Read(Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), rockContext);
                    if (historyCategory != null)
                    {
                        var changes = new List <string>();
                        History.EvaluateChange(changes, "User Login", string.Empty, username);
                        HistoryService.SaveChanges(rockContext, typeof(Person), historyCategory.Guid, person.Id, changes);
                    }

                    return(user);
                }
                else
                {
                    throw new ArgumentException("Invalid EntityTypeId, entity does not exist", "entityTypeId");
                }
            }
            else
            {
                throw new ArgumentException("Invalid Person, person does not exist", "person");
            }
        }