Example #1
0
        /// <summary>
        /// Gets the ordered person attempts.
        /// </summary>
        /// <param name="attemptsQuery">The attempts query.</param>
        /// <param name="achievementTypeCache">The achievement type cache.</param>
        /// <param name="achieverEntityId">The achiever entity identifier.</param>
        /// <returns></returns>
        public List <AchievementAttempt> GetOrderedAchieverAttempts(IQueryable <AchievementAttempt> attemptsQuery, AchievementTypeCache achievementTypeCache, int achieverEntityId)
        {
            attemptsQuery = attemptsQuery.Where(aa => aa.AchievementTypeId == achievementTypeCache.Id);

            // If the achiever type is person alias we need to add all achievements of this type for that person.
            if (EntityTypeCache.Get <PersonAlias>().Id == achievementTypeCache.AchieverEntityTypeId)
            {
                var personAliasService = new PersonAliasService(( RockContext )Context);
                var personAliasQuery   = personAliasService
                                         .Queryable()
                                         .AsNoTracking()
                                         .Where(pa => pa.Id == achieverEntityId)
                                         .SelectMany(pa => pa.Person.Aliases)
                                         .Select(pa => pa.Id);

                attemptsQuery = attemptsQuery
                                .Where(aa => personAliasQuery.Contains(aa.AchieverEntityId));
            }
            else
            {
                attemptsQuery = attemptsQuery
                                .Where(aa => aa.AchieverEntityId == achieverEntityId);
            }

            return(attemptsQuery
                   .OrderByDescending(saa => saa.AchievementAttemptStartDateTime)
                   .ToList());
        }
Example #2
0
        /// <summary>
        /// Queries attempts by person alias ids
        /// </summary>
        /// <param name="personAliasIds">The person alias ids.</param>
        /// <returns></returns>
        public IQueryable <AchievementAttempt> QueryByPersonAliasIds(int[] personAliasIds)
        {
            var rockContext             = Context as RockContext;
            var personAliasService      = new PersonAliasService(rockContext);
            var personEntityTypeId      = EntityTypeCache.Get <Person>().Id;
            var personAliasEntityTypeId = EntityTypeCache.Get <PersonAlias>().Id;

            var personIdQuery = personAliasService.Queryable()
                                .AsNoTracking()
                                .Where(pa => personAliasIds.Contains(pa.Id))
                                .Select(pa => pa.PersonId);

            return(Queryable().Where(aa =>
                                     (
                                         aa.AchievementType.AchieverEntityTypeId == personEntityTypeId &&
                                         personIdQuery.Contains(aa.AchieverEntityId)
                                     ) ||
                                     (
                                         aa.AchievementType.AchieverEntityTypeId == personAliasEntityTypeId &&
                                         personAliasIds.Contains(aa.AchieverEntityId)
                                     )));
        }
        /// <summary>
        /// Handles the Delete event of the gFollowings control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gFollowings_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            var personAliasService = new PersonAliasService( rockContext );
            var followingService = new FollowingService( rockContext );

            var paQry = personAliasService.Queryable()
                .Where( p => p.PersonId == e.RowKeyId )
                .Select( p => p.Id );

            int personAliasEntityTypeId = EntityTypeCache.Read( "Rock.Model.PersonAlias" ).Id;
            foreach ( var following in followingService.Queryable()
                .Where( f =>
                    f.EntityTypeId == personAliasEntityTypeId &&
                    paQry.Contains( f.EntityId ) &&
                    f.PersonAliasId == CurrentPersonAlias.Id ) )
            {
                followingService.Delete( following );
            }

            rockContext.SaveChanges();

            BindGrid();
        }
        /// <summary>
        /// Handles the Click event of the btnConfirm 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 btnConfirm_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid )
            {
                var rockContext = new RockContext();
                var personService = new PersonService( rockContext );
                var ids = Individuals.Select( i => i.PersonId ).ToList();

                #region Individual Details Updates

                int? newTitleId = ddlTitle.SelectedValueAsInt();
                int? newSuffixId = ddlSuffix.SelectedValueAsInt();
                int? newConnectionStatusId = ddlStatus.SelectedValueAsInt();
                int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                int? newInactiveReasonId = ddlInactiveReason.SelectedValueAsInt();
                string newInactiveReasonNote = tbInactiveReasonNote.Text;
                Gender newGender = ddlGender.SelectedValue.ConvertToEnum<Gender>();
                int? newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();

                int? newGraduationYear = null;
                if ( ypGraduation.SelectedYear.HasValue )
                {
                    newGraduationYear = ypGraduation.SelectedYear.Value;
                }

                int? newCampusId = cpCampus.SelectedCampusId;

                bool? newEmailActive = null;
                if ( !string.IsNullOrWhiteSpace( ddlIsEmailActive.SelectedValue ) )
                {
                    newEmailActive = ddlIsEmailActive.SelectedValue == "Active";
                }

                EmailPreference? newEmailPreference = ddlEmailPreference.SelectedValue.ConvertToEnumOrNull<EmailPreference>();

                string newEmailNote = tbEmailNote.Text;

                int? newReviewReason = ddlReviewReason.SelectedValueAsInt();
                string newSystemNote = tbSystemNote.Text;
                string newReviewReasonNote = tbReviewReasonNote.Text;

                int inactiveStatusId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ).Id;

                var allChanges = new Dictionary<int, List<string>>();

                var people = personService.Queryable().Where( p => ids.Contains( p.Id ) ).ToList();
                foreach ( var person in people )
                {
                    var changes = new List<string>();
                    allChanges.Add( person.Id, changes );

                    if ( SelectedFields.Contains( ddlTitle.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) );
                        person.TitleValueId = newTitleId;
                    }

                    if ( SelectedFields.Contains( ddlSuffix.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) );
                        person.SuffixValueId = newSuffixId;
                    }

                    if ( SelectedFields.Contains( ddlStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Connection Status", DefinedValueCache.GetName( person.ConnectionStatusValueId ), DefinedValueCache.GetName( newConnectionStatusId ) );
                        person.ConnectionStatusValueId = newConnectionStatusId;
                    }

                    if ( SelectedFields.Contains( ddlRecordStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( person.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) );
                        person.RecordStatusValueId = newRecordStatusId;

                        if ( newRecordStatusId.HasValue && newRecordStatusId.Value == inactiveStatusId )
                        {
                            History.EvaluateChange( changes, "Inactive Reason", DefinedValueCache.GetName( person.RecordStatusReasonValueId ), DefinedValueCache.GetName( newInactiveReasonId ) );
                            person.RecordStatusReasonValueId = newInactiveReasonId;

                            if ( !string.IsNullOrWhiteSpace( newInactiveReasonNote ) )
                            {
                                History.EvaluateChange( changes, "Inactive Reason Note", person.InactiveReasonNote, newInactiveReasonNote );
                                person.InactiveReasonNote = newInactiveReasonNote;
                            }
                        }
                    }

                    if ( SelectedFields.Contains( ddlGender.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Gender", person.Gender, newGender );
                        person.Gender = newGender;
                    }

                    if ( SelectedFields.Contains( ddlMaritalStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) );
                        person.MaritalStatusValueId = newMaritalStatusId;
                    }

                    if ( SelectedFields.Contains( ddlGradePicker.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Graduation Year", person.GraduationYear, newGraduationYear );
                        person.GraduationYear = newGraduationYear;
                    }

                    if ( SelectedFields.Contains( ddlIsEmailActive.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Is Active", person.IsEmailActive ?? true, newEmailActive.Value );
                        person.IsEmailActive = newEmailActive;
                    }

                    if ( SelectedFields.Contains( ddlEmailPreference.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference );
                        person.EmailPreference = newEmailPreference.Value;
                    }

                    if ( SelectedFields.Contains( tbEmailNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Note", person.EmailNote, newEmailNote );
                        person.EmailNote = newEmailNote;
                    }

                    if ( SelectedFields.Contains( tbSystemNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "System Note", person.SystemNote, newSystemNote );
                        person.SystemNote = newSystemNote;
                    }

                    if ( SelectedFields.Contains( ddlReviewReason.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Review Reason", DefinedValueCache.GetName( person.ReviewReasonValueId ), DefinedValueCache.GetName( newReviewReason ) );
                        person.ReviewReasonValueId = newReviewReason;
                    }

                    if ( SelectedFields.Contains( tbReviewReasonNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Review Reason Note", person.ReviewReasonNote, newReviewReasonNote );
                        person.ReviewReasonNote = newReviewReasonNote;
                    }
                }

                if ( SelectedFields.Contains( cpCampus.ClientID ) && cpCampus.SelectedCampusId.HasValue )
                {
                    int campusId = cpCampus.SelectedCampusId.Value;

                    Guid familyGuid = new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY );

                    var familyMembers = new GroupMemberService( rockContext ).Queryable()
                        .Where( m => ids.Contains( m.PersonId ) && m.Group.GroupType.Guid == familyGuid )
                        .Select( m => new { m.PersonId, m.GroupId } )
                        .Distinct()
                        .ToList();

                    var families = new GroupMemberService( rockContext ).Queryable()
                        .Where( m => ids.Contains( m.PersonId ) && m.Group.GroupType.Guid == familyGuid )
                        .Select( m => m.Group )
                        .Distinct()
                        .ToList();

                    foreach ( int personId in ids )
                    {
                        var familyIds = familyMembers.Where( m => m.PersonId == personId ).Select( m => m.GroupId ).ToList();
                        if ( familyIds.Count == 1 )
                        {
                            int familyId = familyIds.FirstOrDefault();
                            var family = families.Where( g => g.Id == familyId ).FirstOrDefault();
                            {
                                if ( family != null )
                                {
                                    family.CampusId = campusId;
                                }
                                familyMembers.RemoveAll( m => m.GroupId == familyId );
                            }
                        }
                    }

                    rockContext.SaveChanges();
                }

                // Update following
                if ( SelectedFields.Contains( ddlFollow.ClientID ) )
                {
                    var personAliasEntityType = EntityTypeCache.Read( "Rock.Model.PersonAlias" );
                    if ( personAliasEntityType != null )
                    {
                        int personAliasEntityTypeId = personAliasEntityType.Id;

                        bool follow = true;
                        if ( !string.IsNullOrWhiteSpace( ddlFollow.SelectedValue ) )
                        {
                            follow = ddlFollow.SelectedValue == "Add";
                        }

                        var personAliasService = new PersonAliasService( rockContext );
                        var followingService = new FollowingService( rockContext );
                        if ( follow )
                        {
                            var paQry = personAliasService.Queryable();

                            var alreadyFollowingIds = followingService.Queryable()
                                .Where( f =>
                                    f.EntityTypeId == personAliasEntityTypeId &&
                                    f.PersonAlias.Id == CurrentPersonAlias.Id )
                                .Join( paQry, f => f.EntityId, p => p.Id, ( f, p ) => new { PersonAlias = p } )
                                .Select( p => p.PersonAlias.PersonId )
                                .Distinct()
                                .ToList();

                            foreach ( int id in ids.Where( id => !alreadyFollowingIds.Contains( id ) ) )
                            {
                                var following = new Following
                                {
                                    EntityTypeId = personAliasEntityTypeId,
                                    EntityId = ( people.FirstOrDefault( p => p.Id == id ).PrimaryAliasId ) ?? 0,
                                    PersonAliasId = CurrentPersonAlias.Id
                                };
                                followingService.Add( following );
                            }
                        }
                        else
                        {
                            var paQry = personAliasService.Queryable()
                                .Where( p => ids.Contains( p.PersonId ) )
                                .Select( p => p.Id );

                            foreach ( var following in followingService.Queryable()
                                .Where( f =>
                                    f.EntityTypeId == personAliasEntityTypeId &&
                                    paQry.Contains( f.EntityId ) &&
                                    f.PersonAlias.Id == CurrentPersonAlias.Id ) )
                            {
                                followingService.Delete( following );
                            }
                        }
                    }
                }

                rockContext.SaveChanges();

                #endregion

                #region Attributes

                var selectedCategories = new List<CategoryCache>();
                foreach ( string categoryGuid in GetAttributeValue( "AttributeCategories" ).SplitDelimitedValues() )
                {
                    var category = CategoryCache.Read( categoryGuid.AsGuid(), rockContext );
                    if ( category != null )
                    {
                        selectedCategories.Add( category );
                    }
                }

                var attributes = new List<AttributeCache>();
                var attributeValues = new Dictionary<int, string>();

                int categoryIndex = 0;
                foreach ( var category in selectedCategories.OrderBy( c => c.Name ) )
                {
                    PanelWidget pw = null;
                    string controlId = "pwAttributes_" + category.Id.ToString();
                    if ( categoryIndex % 2 == 0 )
                    {
                        pw = phAttributesCol1.FindControl( controlId ) as PanelWidget;
                    }
                    else
                    {
                        pw = phAttributesCol2.FindControl( controlId ) as PanelWidget;
                    }
                    categoryIndex++;

                    if ( pw != null )
                    {
                        var orderedAttributeList = new AttributeService( rockContext ).GetByCategoryId( category.Id )
                            .OrderBy( a => a.Order ).ThenBy( a => a.Name );
                        foreach ( var attribute in orderedAttributeList )
                        {
                            if ( attribute.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                            {
                                var attributeCache = AttributeCache.Read( attribute.Id );

                                Control attributeControl = pw.FindControl( string.Format( "attribute_field_{0}", attribute.Id ) );

                                if ( attributeControl != null && SelectedFields.Contains( attributeControl.ClientID ) )
                                {
                                    string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues );
                                    attributes.Add( attributeCache );
                                    attributeValues.Add( attributeCache.Id, newValue );
                                }
                            }
                        }
                    }
                }

                if ( attributes.Any() )
                {
                    foreach ( var person in people )
                    {
                        person.LoadAttributes();
                        foreach ( var attribute in attributes )
                        {
                            string originalValue = person.GetAttributeValue( attribute.Key );
                            string newValue = attributeValues[attribute.Id];
                            if ( ( originalValue ?? string.Empty ).Trim() != ( newValue ?? string.Empty ).Trim() )
                            {
                                Rock.Attribute.Helper.SaveAttributeValue( person, attribute, newValue, rockContext );

                                string formattedOriginalValue = string.Empty;
                                if ( !string.IsNullOrWhiteSpace( originalValue ) )
                                {
                                    formattedOriginalValue = attribute.FieldType.Field.FormatValue( null, originalValue, attribute.QualifierValues, false );
                                }

                                string formattedNewValue = string.Empty;
                                if ( !string.IsNullOrWhiteSpace( newValue ) )
                                {
                                    formattedNewValue = attribute.FieldType.Field.FormatValue( null, newValue, attribute.QualifierValues, false );
                                }

                                History.EvaluateChange( allChanges[person.Id], attribute.Name, formattedOriginalValue, formattedNewValue );
                            }
                        }
                    }
                }

                // Create the history records
                foreach ( var changes in allChanges )
                {
                    if ( changes.Value.Any() )
                    {
                        HistoryService.AddChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                            changes.Key, changes.Value );
                    }
                }
                rockContext.SaveChanges();

                #endregion

                #region Add Note

                if ( !string.IsNullOrWhiteSpace( tbNote.Text ) && CurrentPerson != null )
                {
                    string text = tbNote.Text;
                    bool isAlert = cbIsAlert.Checked;
                    bool isPrivate = cbIsPrivate.Checked;

                    var noteTypeService = new NoteTypeService( rockContext );
                    var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PERSON_TIMELINE.AsGuid() );
                    if ( noteType != null )
                    {
                        var notes = new List<Note>();
                        var noteService = new NoteService( rockContext );

                        foreach ( int id in ids )
                        {
                            var note = new Note();
                            note.IsSystem = false;
                            note.EntityId = id;
                            note.Caption = isPrivate ? "You - Personal Note" : string.Empty;
                            note.Text = tbNote.Text;
                            note.IsAlert = cbIsAlert.Checked;
                            note.NoteType = noteType;
                            notes.Add( note );
                            noteService.Add( note );
                        }

                        rockContext.WrapTransaction( () =>
                        {
                            rockContext.SaveChanges();
                            foreach ( var note in notes )
                            {
                                note.AllowPerson( Authorization.EDIT, CurrentPerson, rockContext );
                                if ( isPrivate )
                                {
                                    note.MakePrivate( Authorization.VIEW, CurrentPerson, rockContext );
                                }
                            }
                        } );

                    }
                }

                #endregion

                #region Group

                int? groupId = gpGroup.SelectedValue.AsIntegerOrNull();
                if ( groupId.HasValue )
                {
                    var group = new GroupService( rockContext ).Get( groupId.Value );
                    if ( group != null )
                    {
                        var groupMemberService = new GroupMemberService( rockContext );

                        var existingMembers = groupMemberService.Queryable( "Group" )
                            .Where( m =>
                                m.GroupId == group.Id &&
                                ids.Contains( m.PersonId ) )
                            .ToList();

                        string action = ddlGroupAction.SelectedValue;
                        if ( action == "Remove" )
                        {
                            groupMemberService.DeleteRange( existingMembers );
                            rockContext.SaveChanges();
                        }
                        else
                        {
                            var roleId = ddlGroupRole.SelectedValueAsInt();
                            var status = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>();

                            // Get the attribute values updated
                            var gm = new GroupMember();
                            gm.Group = group;
                            gm.GroupId = group.Id;
                            gm.LoadAttributes( rockContext );
                            var selectedGroupAttributes = new List<AttributeCache>();
                            var selectedGroupAttributeValues = new Dictionary<string, string>();
                            foreach ( var attributeCache in gm.Attributes.Select( a => a.Value ) )
                            {
                                Control attributeControl = phAttributes.FindControl( string.Format( "attribute_field_{0}", attributeCache.Id ) );
                                if ( attributeControl != null && ( action == "Add" || SelectedFields.Contains( attributeControl.ClientID ) ) )
                                {
                                    string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues );
                                    selectedGroupAttributes.Add( attributeCache );
                                    selectedGroupAttributeValues.Add( attributeCache.Key, newValue );
                                }
                            }

                            if ( action == "Add" )
                            {
                                if ( roleId.HasValue )
                                {
                                    var newGroupMembers = new List<GroupMember>();

                                    var existingIds = existingMembers.Select( m => m.PersonId ).Distinct().ToList();
                                    foreach ( int id in ids.Where( id => !existingIds.Contains( id ) ) )
                                    {
                                        var groupMember = new GroupMember();
                                        groupMember.GroupId = group.Id;
                                        groupMember.GroupRoleId = roleId.Value;
                                        groupMember.GroupMemberStatus = status;
                                        groupMember.PersonId = id;
                                        groupMemberService.Add( groupMember );
                                        newGroupMembers.Add( groupMember );
                                    }

                                    rockContext.SaveChanges();

                                    if ( selectedGroupAttributes.Any() )
                                    {
                                        foreach ( var groupMember in newGroupMembers )
                                        {
                                            foreach ( var attribute in selectedGroupAttributes )
                                            {
                                                Rock.Attribute.Helper.SaveAttributeValue( groupMember, attribute, selectedGroupAttributeValues[attribute.Key], rockContext );
                                            }
                                        }
                                    }
                                }
                            }
                            else // Update
                            {
                                if ( SelectedFields.Contains( ddlGroupRole.ClientID ) && roleId.HasValue )
                                {
                                    foreach ( var member in existingMembers.Where( m => m.GroupRoleId != roleId.Value ) )
                                    {
                                        if ( !existingMembers.Where( m => m.PersonId == member.PersonId && m.GroupRoleId == roleId.Value ).Any() )
                                        {
                                            member.GroupRoleId = roleId.Value;
                                        }
                                    }
                                }

                                if ( SelectedFields.Contains( ddlGroupMemberStatus.ClientID ) )
                                {
                                    foreach ( var member in existingMembers )
                                    {
                                        member.GroupMemberStatus = status;
                                    }
                                }

                                rockContext.SaveChanges();

                                if ( selectedGroupAttributes.Any() )
                                {
                                    foreach ( var groupMember in existingMembers )
                                    {
                                        foreach ( var attribute in selectedGroupAttributes )
                                        {
                                            Rock.Attribute.Helper.SaveAttributeValue( groupMember, attribute, selectedGroupAttributeValues[attribute.Key], rockContext );
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                #endregion

                pnlEntry.Visible = false;
                pnlConfirm.Visible = false;

                nbResult.Text = string.Format( "{0} {1} succesfully updated.",
                    ids.Count().ToString( "N0" ), ( ids.Count() > 1 ? "people were" : "person was" ) ); ;
                pnlResult.Visible = true;
            }
        }
Example #5
0
        /// <summary>
        /// Handles adding families from the given XML element snippet
        /// </summary>
        /// <param name="elemFamilies">The xml element containing all the families.</param>
        /// <param name="rockContext">The rock context.</param>
        private void AddFamilies( XElement elemFamilies, RockContext rockContext )
        {
            if ( elemFamilies == null )
            {
                return;
            }

            // Persist the storage type's settings specific to the photo binary file type
            var settings = new Dictionary<string, string>();
            if ( _personImageBinaryFileType.Attributes == null )
            {
                _personImageBinaryFileType.LoadAttributes();
            }
            foreach ( var attributeValue in _personImageBinaryFileType.AttributeValues )
            {
                settings.Add( attributeValue.Key, attributeValue.Value.Value );
            }
            _personImageBinaryFileTypeSettings = settings.ToJson();

            bool fabricateAttendance = GetAttributeValue( "FabricateAttendance" ).AsBoolean();
            GroupService groupService = new GroupService( rockContext );
            var allFamilies = rockContext.Groups;

            List<Group> allGroups = new List<Group>();
            var attendanceData = new Dictionary<Guid, List<Attendance>>();

            // Next create the family along with its members and related data
            foreach ( var elemFamily in elemFamilies.Elements( "family" ) )
            {
                Guid guid = elemFamily.Attribute( "guid" ).Value.Trim().AsGuid();
                var familyMembers = BuildFamilyMembersFromXml( elemFamily.Element( "members" ), rockContext );

                // Call replica of groupService's SaveNewFamily method in an attempt to speed things up
                Group family = CreateNewFamily( familyMembers, campusId: 1 );
                family.Guid = guid;

                // add the family to the context's list of groups
                allFamilies.Add( family );

                // add the families address(es)
                AddFamilyAddresses( groupService, family, elemFamily.Element( "addresses" ), rockContext );

                // add their attendance data
                if ( fabricateAttendance )
                {
                    AddFamilyAttendance( family, elemFamily, rockContext, attendanceData );
                }

                allGroups.Add( family );

                _stopwatch.Stop();
                AppendFormat( "{0:00}:{1:00}.{2:00} added {3}<br/>", _stopwatch.Elapsed.Minutes, _stopwatch.Elapsed.Seconds, _stopwatch.Elapsed.Milliseconds / 10, family.Name );
                _stopwatch.Start();
            }
            rockContext.ChangeTracker.DetectChanges();
            rockContext.SaveChanges( disablePrePostProcessing: true );

            // Now save each person's attributevalues (who had them defined in the XML)
            // and add each person's ID to a dictionary for use later.
            _stopwatch.Stop();
            AppendFormat( "{0:00}:{1:00}.{2:00} saving attributes for everyone...<br/>", _stopwatch.Elapsed.Minutes, _stopwatch.Elapsed.Seconds, _stopwatch.Elapsed.Milliseconds / 10 );
            _stopwatch.Start();
            AttributeValueService attributeValueService = new AttributeValueService( rockContext );
            foreach ( var gm in allGroups.SelectMany( g => g.Members ) )
            {
                // Put the person's id into the people dictionary for later use.
                if ( !_peopleDictionary.ContainsKey( gm.Person.Guid ) )
                {
                    _peopleDictionary.Add( gm.Person.Guid, gm.Person.Id );
                }

                // Only save if the person had attributes, otherwise it will error.
                if ( _personWithAttributes.ContainsKey( gm.Person.Guid ) )
                {
                    foreach ( var attributeCache in gm.Person.Attributes.Select( a => a.Value ) )
                    {
                        var newValue = gm.Person.AttributeValues[attributeCache.Key];
                        if ( newValue != null )
                        {
                            var attributeValue = new AttributeValue();
                            attributeValue.AttributeId = newValue.AttributeId;
                            attributeValue.EntityId = gm.Person.Id;
                            attributeValue.Value = newValue.Value;
                            rockContext.AttributeValues.Add( attributeValue );
                        }
                    }
                }
            }
            rockContext.ChangeTracker.DetectChanges();
            rockContext.SaveChanges( disablePrePostProcessing: true );

            _stopwatch.Stop();
            AppendFormat( "{0:00}:{1:00}.{2:00} attributes saved<br/>", _stopwatch.Elapsed.Minutes, _stopwatch.Elapsed.Seconds, _stopwatch.Elapsed.Milliseconds / 10 );
            _stopwatch.Start();

            // Create person alias records for each person manually since we set disablePrePostProcessing=true on save
            PersonService personService = new PersonService( rockContext );
            foreach ( var person in personService.Queryable( "Aliases", true )
                .Where( p =>
                    _peopleDictionary.Keys.Contains( p.Guid ) &&
                    !p.Aliases.Any() ) )
            {
                person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } );
            }
            rockContext.ChangeTracker.DetectChanges();
            rockContext.SaveChanges( disablePrePostProcessing: true );

            _stopwatch.Stop();
            AppendFormat( "{0:00}:{1:00}.{2:00} added person aliases<br/>", _stopwatch.Elapsed.Minutes, _stopwatch.Elapsed.Seconds, _stopwatch.Elapsed.Milliseconds / 10 );
            _stopwatch.Start();

            // Put the person alias ids into the people alias dictionary for later use.
            PersonAliasService personAliasService = new PersonAliasService( rockContext );
            foreach ( var personAlias in personAliasService.Queryable( "Person" )
                .Where( a =>
                    _peopleDictionary.Keys.Contains( a.Person.Guid ) &&
                    a.PersonId == a.AliasPersonId ) )
            {
                _peopleAliasDictionary.Add( personAlias.Person.Guid, personAlias.Id );
            }

            // Now that person aliases have been saved, save the attendance records
            var attendanceService = new AttendanceService( rockContext );
            var attendanceGuids = attendanceData.Select( a => a.Key ).ToList();
            foreach ( var aliasKeyValue in _peopleAliasDictionary
                .Where( a => attendanceGuids.Contains( a.Key )) )
            {
                foreach ( var attendance in attendanceData[aliasKeyValue.Key] )
                {
                    attendance.PersonAliasId = aliasKeyValue.Value;
                    attendanceService.Add( attendance );
                }
            }
            rockContext.ChangeTracker.DetectChanges();
            rockContext.SaveChanges( disablePrePostProcessing: true );

            _stopwatch.Stop();
            AppendFormat( "{0:00}:{1:00}.{2:00} added attendance records<br/>", _stopwatch.Elapsed.Minutes, _stopwatch.Elapsed.Seconds, _stopwatch.Elapsed.Milliseconds / 10 );
            _stopwatch.Start();

            // Now re-process the family section looking for any giving data.
            // We do this last because we need the personAliases that were just added.
            // Persist the storage type's settings specific to the contribution binary file type
            settings = new Dictionary<string, string>();
            if ( _checkImageBinaryFileType.Attributes == null )
            {
                _checkImageBinaryFileType.LoadAttributes();
            }
            foreach ( var attributeValue in _checkImageBinaryFileType.AttributeValues )
            {
                settings.Add( attributeValue.Key, attributeValue.Value.Value );
            }
            _checkImageBinaryFileTypeSettings = settings.ToJson();

            foreach ( var elemFamily in elemFamilies.Elements( "family" ) )
            {
                // add the families giving data
                if ( GetAttributeValue( "EnableGiving" ).AsBoolean() )
                {
                    // Support multiple giving elements per family
                    foreach ( var elementGiving in elemFamily.Elements( "giving" ) )
                    {
                        AddFamilyGiving( elementGiving, elemFamily.Attribute( "name" ).Value, rockContext );
                    }
                }
            }

            if ( GetAttributeValue( "EnableGiving" ).AsBoolean() )
            {
                // Now add the batches to the service to be persisted
                var financialBatchService = new FinancialBatchService( rockContext );
                foreach ( var financialBatch in _contributionBatches )
                {
                    financialBatchService.Add( financialBatch.Value );
                }
            }
            rockContext.ChangeTracker.DetectChanges();
            rockContext.SaveChanges( disablePrePostProcessing: true );
        }
Example #6
0
        /// <summary>
        /// Deletes the family's addresses, phone numbers, photos, viewed records, and people.
        /// TODO: delete attendance codes for attendance data that's about to be deleted when
        /// we delete the person record.
        /// </summary>
        /// <param name="families">The families.</param>
        /// <param name="rockContext">The rock context.</param>
        private void DeleteExistingFamilyData( XElement families, RockContext rockContext )
        {
            PersonService personService = new PersonService( rockContext );
            PhoneNumberService phoneNumberService = new PhoneNumberService( rockContext );
            PersonViewedService personViewedService = new PersonViewedService( rockContext );
            PageViewService pageViewService = new PageViewService( rockContext );
            BinaryFileService binaryFileService = new BinaryFileService( rockContext );
            PersonAliasService personAliasService = new PersonAliasService( rockContext );
            PersonDuplicateService personDuplicateService = new PersonDuplicateService( rockContext );
            NoteService noteService = new NoteService( rockContext );
            AuthService authService = new AuthService( rockContext );
            CommunicationService communicationService = new CommunicationService( rockContext );
            CommunicationRecipientService communicationRecipientService = new CommunicationRecipientService( rockContext );
            FinancialBatchService financialBatchService = new FinancialBatchService( rockContext );
            FinancialTransactionService financialTransactionService = new FinancialTransactionService( rockContext );
            PersonPreviousNameService personPreviousNameService = new PersonPreviousNameService( rockContext );
            ConnectionRequestService connectionRequestService = new ConnectionRequestService( rockContext );
            ConnectionRequestActivityService connectionRequestActivityService = new ConnectionRequestActivityService( rockContext );

            // delete the batch data
            List<int> imageIds = new List<int>();
            foreach ( var batch in financialBatchService.Queryable().Where( b => b.Name.StartsWith( "SampleData" ) ) )
            {
                imageIds.AddRange( batch.Transactions.SelectMany( t => t.Images ).Select( i => i.BinaryFileId ).ToList() );
                financialTransactionService.DeleteRange( batch.Transactions );
                financialBatchService.Delete( batch );
            }

            // delete all transaction images
            foreach ( var image in binaryFileService.GetByIds( imageIds ) )
            {
                binaryFileService.Delete( image );
            }

            foreach ( var elemFamily in families.Elements( "family" ) )
            {
                Guid guid = elemFamily.Attribute( "guid" ).Value.Trim().AsGuid();

                GroupService groupService = new GroupService( rockContext );
                Group family = groupService.Get( guid );
                if ( family != null )
                {
                    var groupMemberService = new GroupMemberService( rockContext );
                    var members = groupMemberService.GetByGroupId( family.Id, true );

                    // delete the people records
                    string errorMessage;
                    List<int> photoIds = members.Select( m => m.Person ).Where( p => p.PhotoId != null ).Select( a => (int)a.PhotoId ).ToList();

                    foreach ( var person in members.Select( m => m.Person ) )
                    {
                        person.GivingGroup = null;
                        person.GivingGroupId = null;
                        person.PhotoId = null;

                        // delete phone numbers
                        foreach ( var phone in phoneNumberService.GetByPersonId( person.Id ) )
                        {
                            if ( phone != null )
                            {
                                phoneNumberService.Delete( phone );
                            }
                        }

                        // delete communication recipient
                        foreach ( var recipient in communicationRecipientService.Queryable().Where( r => r.PersonAlias.PersonId == person.Id ) )
                        {
                            communicationRecipientService.Delete( recipient );
                        }

                        // delete communication
                        foreach ( var communication in communicationService.Queryable().Where( c => c.SenderPersonAliasId == person.PrimaryAlias.Id ) )
                        {
                            communicationService.Delete( communication );
                        }

                        // delete person viewed records
                        foreach ( var view in personViewedService.GetByTargetPersonId( person.Id ) )
                        {
                            personViewedService.Delete( view );
                        }

                        // delete page viewed records
                        foreach ( var view in pageViewService.GetByPersonId( person.Id ) )
                        {
                            pageViewService.Delete( view );
                        }

                        // delete notes created by them or on their record.
                        foreach ( var note in noteService.Queryable().Where ( n => n.CreatedByPersonAlias.PersonId == person.Id
                            || (n.NoteType.EntityTypeId == _personEntityTypeId && n.EntityId == person.Id ) ) )
                        {
                            noteService.Delete( note );
                        }

                        // delete previous names on their records
                        foreach ( var previousName in personPreviousNameService.Queryable().Where( r => r.PersonAlias.PersonId == person.Id ) )
                        {
                            personPreviousNameService.Delete( previousName );
                        }

                        // delete any GroupMember records they have
                        foreach ( var groupMember in groupMemberService.Queryable().Where( gm => gm.PersonId == person.Id ) )
                        {
                            groupMemberService.Delete( groupMember );
                        }

                        //// delete any Authorization data
                        //foreach ( var auth in authService.Queryable().Where( a => a.PersonId == person.Id ) )
                        //{
                        //    authService.Delete( auth );
                        //}

                        // delete their aliases
                        foreach ( var alias in personAliasService.Queryable().Where( a => a.PersonId == person.Id ) )
                        {
                            foreach ( var duplicate in personDuplicateService.Queryable().Where( d => d.DuplicatePersonAliasId == alias.Id ) )
                            {
                                personDuplicateService.Delete( duplicate );
                            }

                            personAliasService.Delete( alias );
                        }

                        // delete any connection requests tied to them
                        foreach ( var request in connectionRequestService.Queryable().Where( r => r.PersonAlias.PersonId == person.Id || r.ConnectorPersonAlias.PersonId == person.Id ) )
                        {
                            connectionRequestActivityService.DeleteRange( request.ConnectionRequestActivities );
                            connectionRequestService.Delete( request );
                        }

                        // Save these changes so the CanDelete passes the check...
                        //rockContext.ChangeTracker.DetectChanges();
                        rockContext.SaveChanges( disablePrePostProcessing: true );

                        if ( personService.CanDelete( person, out errorMessage ) )
                        {
                            personService.Delete( person );
                            //rockContext.ChangeTracker.DetectChanges();
                            //rockContext.SaveChanges( disablePrePostProcessing: true );
                        }
                        else
                        {
                            throw new Exception( string.Format( "Trying to delete {0}, but: {1}", person.FullName, errorMessage ) );
                        }
                    }

                    //rockContext.ChangeTracker.DetectChanges();
                    rockContext.SaveChanges( disablePrePostProcessing: true );

                    // delete all member photos
                    foreach ( var photo in binaryFileService.GetByIds( photoIds ) )
                    {
                        binaryFileService.Delete( photo );
                    }

                    DeleteGroupAndMemberData( family, rockContext );
                }
            }
        }
        /// <summary>
        /// Handles the Click event of the lbUnfollow control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        void lbUnfollow_Click( object sender, EventArgs e )
        {
            var itemsSelected = new List<int>();
            gFollowings.SelectedKeys.ToList().ForEach( f => itemsSelected.Add( f.ToString().AsInteger() ) );

            if ( itemsSelected.Any() )
            {
                var rockContext = new RockContext();
                var personAliasService = new PersonAliasService( rockContext );
                var followingService = new FollowingService( rockContext );

                var paQry = personAliasService.Queryable()
                    .Where( p => itemsSelected.Contains( p.PersonId ) )
                    .Select( p => p.Id );

                int personAliasEntityTypeId = EntityTypeCache.Read( "Rock.Model.PersonAlias" ).Id;
                foreach ( var following in followingService.Queryable()
                    .Where( f =>
                        f.EntityTypeId == personAliasEntityTypeId &&
                        paQry.Contains( f.EntityId ) &&
                        f.PersonAliasId == CurrentPersonAlias.Id ) )
                {
                    followingService.Delete( following );
                }

                rockContext.SaveChanges();
            }

            BindGrid();
        }
Example #8
0
        /// <summary>
        /// Gets the suggestions.
        /// </summary>
        /// <param name="followingSuggestionType">Type of the following suggestion.</param>
        /// <param name="followerPersonIds">The follower person ids.</param>
        /// <returns></returns>
        public override List<PersonEntitySuggestion> GetSuggestions( FollowingSuggestionType followingSuggestionType, List<int> followerPersonIds )
        {
            var suggestions = new List<PersonEntitySuggestion>();
            var personAliasEntityType = EntityTypeCache.Read( typeof( Rock.Model.PersonAlias ) );

            bool isAutoFollow = GetAttributeValue( followingSuggestionType, "AutoFollow" ).AsBoolean();

            // Get the grouptype guid
            Guid? groupTypeGuid = GetAttributeValue( followingSuggestionType, "GroupType" ).AsGuidOrNull();
            if ( groupTypeGuid.HasValue )
            {
                using ( var rockContext = new RockContext() )
                {
                    var groupMemberService = new GroupMemberService( rockContext );
                    var personAliasService = new PersonAliasService( rockContext );

                    // Get all the groupmember records for any follower and the selected group type
                    var followers = groupMemberService.Queryable().AsNoTracking()
                        .Where( m =>
                            m.GroupMemberStatus == GroupMemberStatus.Active &&
                            m.Group != null &&
                            m.Group.IsActive &&
                            m.Group.GroupType.Guid.Equals( groupTypeGuid.Value ) &&
                            followerPersonIds.Contains( m.PersonId ) );

                    // If a specific group or security role was specifed, limit groupmembers to only those of the selected group
                    Guid? groupGuid = GetAttributeValue( followingSuggestionType, "Group" ).AsGuidOrNull();
                    if ( !groupGuid.HasValue )
                    {
                        groupGuid = GetAttributeValue( followingSuggestionType, "SecurityRole" ).AsGuidOrNull();
                    }
                    if ( groupGuid.HasValue )
                    {
                        followers = followers.Where( m => m.Group.Guid.Equals( groupGuid.Value ) );
                    }

                    // If a specific role for the follower was specified, limit groupmembers to only those with the selected role
                    Guid? followerRoleGuid = GetAttributeValue( followingSuggestionType, "FollowerGroupType" ).AsGuidOrNull();
                    if ( followerRoleGuid.HasValue )
                    {
                        followers = followers.Where( m => m.GroupRole.Guid.Equals( followerRoleGuid.Value ) );
                    }

                    // Run the query to get all the groups that follower is a member of with selected filters
                    var followerPersonGroup = followers
                        .Select( f => new
                        {
                            f.PersonId,
                            f.GroupId
                        } )
                        .ToList();

                    // Get a unique list of any of the groups that followers belong to
                    var followedGroupIds = followerPersonGroup
                        .Select( f => f.GroupId )
                        .Distinct()
                        .ToList();

                    // Start building query to get the people to follow from any group that contains a follower
                    var followed = groupMemberService
                        .Queryable().AsNoTracking()
                        .Where( m => followedGroupIds.Contains( m.GroupId ) );

                    // If a specific role for the people being followed was specified, limit the query to only those with the selected role
                    Guid? followedRoleGuid = GetAttributeValue( followingSuggestionType, "FollowedGroupType" ).AsGuidOrNull();
                    if ( followedRoleGuid.HasValue )
                    {
                        followed = followed.Where( m => m.GroupRole.Guid.Equals( followedRoleGuid.Value ) );
                    }

                    // Get all the people in any of the groups that contain a follower
                    var followedPersonGroup = followed
                        .Select( f => new
                        {
                            f.PersonId,
                            f.GroupId
                        } )
                        .ToList();

                    // Get distinct list of people
                    var followedPersonIds = followedPersonGroup
                        .Select( f => f.PersonId )
                        .Distinct()
                        .ToList();

                    // Build a dictionary of the personid->personaliasid
                    var personAliasIds = new Dictionary<int, int>();
                    personAliasService.Queryable().AsNoTracking()
                        .Where( a =>
                            followedPersonIds.Contains( a.PersonId ) &&
                            a.PersonId == a.AliasPersonId )
                        .ToList()
                        .ForEach( a => personAliasIds.AddOrIgnore( a.PersonId, a.Id ) );

                    // Loop through each follower/group combination
                    foreach ( var followedGroup in followerPersonGroup )
                    {
                        // Loop through the other people in that group
                        foreach ( int followedPersonId in followedPersonGroup
                            .Where( f =>
                                f.GroupId == followedGroup.GroupId &&
                                f.PersonId != followedGroup.PersonId )
                            .Select( f => f.PersonId ) )
                        {
                            // If the person has a valid personalias id
                            if ( personAliasIds.ContainsKey( followedPersonId ) )
                            {
                                if ( !isAutoFollow )
                                {
                                    // add them to the list of suggestions
                                    suggestions.Add( new PersonEntitySuggestion( followedGroup.PersonId, personAliasIds[followedPersonId] ) );
                                }
                                else
                                {
                                    // auto-add the follow

                                    var followingService = new FollowingService( rockContext );

                                    int followerPersonAliasId = personAliasIds[followedGroup.PersonId];
                                    int followeePersonAliasId = personAliasIds[followedPersonId];

                                    // if person is not already following the person
                                    bool isFollowing = followingService.Queryable().Where( f =>
                                                            f.EntityTypeId == personAliasEntityType.Id
                                                            && f.EntityId == followeePersonAliasId
                                                            && f.PersonAliasId == followerPersonAliasId ).Any();
                                    if ( !isFollowing )
                                    {
                                        var following = new Following();
                                        following.EntityTypeId = personAliasEntityType.Id;
                                        following.EntityId = personAliasIds[followedPersonId];
                                        following.PersonAliasId = personAliasIds[followedGroup.PersonId];
                                        followingService.Add( following );
                                        rockContext.SaveChanges();
                                    }
                                }
                            }
                        }

                    }
                }
            }

            return suggestions;
        }
Example #9
0
        private Person GetPersonAliasFromActionAttribute(string key, RockContext rockContext, WorkflowAction action, List<string> errorMessages)
        {
            string value = GetAttributeValue( action, key );
            Guid guidPersonAttribute = value.AsGuid();
            if (!guidPersonAttribute.IsEmpty())
            {
                var attributePerson = AttributeCache.Read( guidPersonAttribute, rockContext );
                if (attributePerson != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        if (attributePerson.FieldType.Class == "Rock.Field.Types.PersonFieldType")
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                PersonAliasService personAliasService = new PersonAliasService(rockContext);
                                return personAliasService.Queryable().AsNoTracking()
                                    .Where(a => a.Guid.Equals(personAliasGuid))
                                    .Select(a => a.Person)
                                    .FirstOrDefault();
                            }
                            else
                            {
                                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
                                return null;
                            }
                        }
                        else
                        {
                            errorMessages.Add(string.Format("The attribute used for {0} to provide the person was not of type 'Person'.", key));
                            return null;
                        }
                    }
                }
            }

            return null;
        }
        /// <summary>
        /// Deletes the family's addresses, phone numbers, photos, viewed records, and people.
        /// TODO: delete attendance codes for attendance data that's about to be deleted when
        /// we delete the person record.
        /// </summary>
        /// <param name="families">The families.</param>
        /// <param name="rockContext">The rock context.</param>
        private void DeleteExistingFamilyData( XElement families, RockContext rockContext )
        {
            PersonService personService = new PersonService( rockContext );
            PhoneNumberService phoneNumberService = new PhoneNumberService( rockContext );
            PersonViewedService personViewedService = new PersonViewedService( rockContext );
            PageViewService pageViewService = new PageViewService( rockContext );
            BinaryFileService binaryFileService = new BinaryFileService( rockContext );
            PersonAliasService personAliasService = new PersonAliasService( rockContext );
            NoteService noteService = new NoteService( rockContext );
            AuthService authService = new AuthService( rockContext );

            foreach ( var elemFamily in families.Elements( "family" ) )
            {
                Guid guid = elemFamily.Attribute( "guid" ).Value.Trim().AsGuid();

                GroupService groupService = new GroupService( rockContext );
                Group family = groupService.Get( guid );
                if ( family != null )
                {
                    var groupMemberService = new GroupMemberService( rockContext );
                    var members = groupMemberService.GetByGroupId( family.Id );

                    // delete the people records
                    string errorMessage;
                    List<int> photoIds = members.Select( m => m.Person ).Where( p => p.PhotoId != null ).Select( a => (int)a.PhotoId ).ToList();

                    foreach ( var person in members.Select( m => m.Person ) )
                    {
                        person.GivingGroup = null;
                        person.GivingGroupId = null;
                        person.PhotoId = null;

                        // delete phone numbers
                        foreach ( var phone in phoneNumberService.GetByPersonId( person.Id ) )
                        {
                            if ( phone != null )
                            {
                                phoneNumberService.Delete( phone );
                            }
                        }

                        // delete person viewed records
                        foreach ( var view in personViewedService.GetByTargetPersonId( person.Id ) )
                        {
                            personViewedService.Delete( view );
                        }

                        // delete page viewed records
                        foreach ( var view in pageViewService.GetByPersonId( person.Id ) )
                        {
                            pageViewService.Delete( view );
                        }

                        // delete notes created by them or on their record.
                        foreach ( var note in noteService.Queryable().Where ( n => n.CreatedByPersonAlias.PersonId == person.Id
                            || (n.NoteType.EntityTypeId == _personEntityTypeId && n.EntityId == person.Id ) ) )
                        {
                            noteService.Delete( note );
                        }

                        //// delete any GroupMember records they have
                        //foreach ( var groupMember in groupMemberService.Queryable().Where( gm => gm.PersonId == person.Id ) )
                        //{
                        //    groupMemberService.Delete( groupMember );
                        //}

                        //// delete any Authorization data
                        //foreach ( var auth in authService.Queryable().Where( a => a.PersonId == person.Id ) )
                        //{
                        //    authService.Delete( auth );
                        //}

                        // delete their aliases
                        foreach ( var alias in personAliasService.Queryable().Where( a => a.PersonId == person.Id ) )
                        {
                            personAliasService.Delete( alias );
                        }

                        //foreach ( var relationship in person.Gro)

                        // Save these changes so the CanDelete passes the check...
                        //rockContext.ChangeTracker.DetectChanges();
                        rockContext.SaveChanges( disablePrePostProcessing: true );

                        if ( personService.CanDelete( person, out errorMessage ) )
                        {
                            personService.Delete( person );
                            //rockContext.ChangeTracker.DetectChanges();
                            //rockContext.SaveChanges( disablePrePostProcessing: true );
                        }
                    }
                    //rockContext.ChangeTracker.DetectChanges();
                    rockContext.SaveChanges( disablePrePostProcessing: true );

                    // delete all member photos
                    foreach ( var photo in binaryFileService.GetByIds( photoIds ) )
                    {
                        binaryFileService.Delete( photo );
                    }

                    DeleteGroupAndMemberData( family, rockContext );
                }
            }
        }
Example #11
0
        private void SetFollowing()
        {
            var personAliasEntityType = EntityTypeCache.Read( "Rock.Model.PersonAlias" );
            if ( Person != null && CurrentPersonId.HasValue && CurrentPersonAlias != null && personAliasEntityType != null )
            {
                using ( var rockContext = new RockContext() )
                {
                    var personAliasService = new PersonAliasService( rockContext );
                    var followingService = new FollowingService( rockContext );

                    var paQry = personAliasService.Queryable()
                        .Where( p => p.PersonId == Person.Id )
                        .Select( p => p.Id );

                    if ( followingService.Queryable()
                        .Where( f =>
                            f.EntityTypeId == personAliasEntityType.Id &&
                            paQry.Contains( f.EntityId ) &&
                            f.PersonAlias.PersonId == CurrentPersonId )
                        .Any() )
                    {
                        pnlFollow.AddCssClass( "following" );
                    }
                    else
                    {
                        pnlFollow.RemoveCssClass( "following" );
                    }
                }

                string script = string.Format( @"
            $('.following-status').click(function () {{
            var $followingDiv = $(this);
            if ($followingDiv.hasClass('following')) {{
                $.ajax({{
                    type: 'DELETE',
                    url: Rock.settings.get('baseUrl') + 'api/followings/{0}/{1}/{2}',
                    success: function(data, status, xhr){{
                        $followingDiv.removeClass('following');
                    }},
                }});
            }} else {{
                var following = {{ EntityTypeId:{0}, EntityId:{1}, PersonAliasId:{3} }};
                $.ajax({{
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(following),
                    url: Rock.settings.get('baseUrl') + 'api/followings',
                    statusCode: {{
                        201: function () {{
                            $followingDiv.addClass('following');
                        }}
                    }}
                }});
            }}
            }});
            ", personAliasEntityType.Id, Person.PrimaryAliasId, CurrentPersonId.Value, CurrentPersonAlias.Id );
                ScriptManager.RegisterStartupScript( lImage, lImage.GetType(), "following", script, true );
            }
        }
Example #12
0
        /// <summary>
        /// Does cleanup of Person Aliases and Metaphones
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void PersonCleanup( JobDataMap dataMap )
        {
            // Add any missing person aliases
            var personRockContext = new Rock.Data.RockContext();
            PersonService personService = new PersonService( personRockContext );
            PersonAliasService personAliasService = new PersonAliasService( personRockContext );
            var personAliasServiceQry = personAliasService.Queryable();
            foreach ( var person in personService.Queryable( "Aliases" )
                .Where( p => !p.Aliases.Any() && !personAliasServiceQry.Any( pa => pa.AliasPersonId == p.Id ) )
                .Take( 300 ) )
            {
                person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } );
            }

            personRockContext.SaveChanges();

            // Add any missing metaphones
            int namesToProcess = dataMap.GetString( "MaxMetaphoneNames" ).AsInteger();
            if ( namesToProcess > 0 )
            {
                var firstNameQry = personService.Queryable().Select( p => p.FirstName ).Where( p => p != null );
                var nickNameQry = personService.Queryable().Select( p => p.NickName ).Where( p => p != null );
                var lastNameQry = personService.Queryable().Select( p => p.LastName ).Where( p => p != null );
                var nameQry = firstNameQry.Union( nickNameQry.Union( lastNameQry ) );

                var metaphones = personRockContext.Metaphones;
                var existingNames = metaphones.Select( m => m.Name ).Distinct();

                // Get the names that have not yet been processed
                var namesToUpdate = nameQry
                    .Where( n => !existingNames.Contains( n ) )
                    .Take( namesToProcess )
                    .ToList();

                foreach ( string name in namesToUpdate )
                {
                    string mp1 = string.Empty;
                    string mp2 = string.Empty;
                    Rock.Utility.DoubleMetaphone.doubleMetaphone( name, ref mp1, ref mp2 );

                    var metaphone = new Metaphone();
                    metaphone.Name = name;
                    metaphone.Metaphone1 = mp1;
                    metaphone.Metaphone2 = mp2;

                    metaphones.Add( metaphone );
                }

                personRockContext.SaveChanges();
            }
        }
Example #13
0
        //Just mapping Connect Groups and not People Lists (Wonder if People lists could be Tags?)
        /// <summary>
        /// Maps the Connect Groups.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapGroups( IQueryable<Row> tableData )
        {
            var lookupContext = new RockContext();
            int completedMembers = 0;
            int completedGroups = 0;
            int completedLifeStages = 0;
            int completedTags = 0;
            int completedIndividualTags = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying group import ({0:N0} found. Total may vary based on Group Type Name).", totalRows ) );

            foreach ( var row in tableData )
            {
                var rockContext = new RockContext();
                var lifeStageContext = new RockContext();
                var connectGroupContext = new RockContext();
                var connectGroupMemberContext = new RockContext();

                string groupTypeName = row["Group_Type_Name"] as string;
                if ( groupTypeName.Trim() == "Connect Groups" )            //Moves Connect Groups into Rock Groups
                {

                    var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault();
                    var connectGroupsId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Connect Groups" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault();
                    var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault();

                    string groupName = row["Group_Name"] as string;
                    int? groupId = row["Group_ID"] as int?;
                    int? individualId = row["Individual_ID"] as int?;
                    int? personId = GetPersonAliasId( individualId );
                    DateTime? createdDateTime = row["Created_Date"] as DateTime?;

                    //Check to see if Head of Connect Group Tree exists

                    //If it doesn't exist
                    if ( connectGroupsId == 0 )
                    {
                        //Create one.
                        var connectGroupTree = new Group();
                        connectGroupTree.IsSystem = false;
                        connectGroupTree.GroupTypeId = groupTypeIdSection;
                        connectGroupTree.CampusId = 1;
                        connectGroupTree.Name = "Connect Groups";
                        connectGroupTree.Description = "Crossroads Connect Group Ministry";
                        connectGroupTree.IsActive = true;
                        //connectGroupTree.Order = 0;
                        connectGroupTree.CreatedByPersonAliasId = 1;
                        connectGroupTree.CreatedDateTime = DateTime.Now;

                        //save group
                        rockContext.WrapTransaction( () =>
                        {
                            rockContext.Configuration.AutoDetectChangesEnabled = false;
                            rockContext.Groups.Add( connectGroupTree );
                            rockContext.SaveChanges( DisableAudit );
                        } );
                    }

                    //check to see if life stage exists
                    //getting the life stage name
                    string lifeStage = groupName;
                    int index = lifeStage.IndexOf( "-" );
                    if ( index > 0 )
                        lifeStage = lifeStage.Substring( 0, index ).Trim();

                    //checks to see if it exists
                    int existingLifeStage = new GroupService( lookupContext ).Queryable().Where( g => g.Name == lifeStage ).Select( a => a.Id ).FirstOrDefault();
                    if ( existingLifeStage == 0 )
                    {
                        //Create one.
                        var connectGroupsLifeStage = new Group();
                        connectGroupsLifeStage.IsSystem = false;
                        connectGroupsLifeStage.ParentGroupId = connectGroupsId;
                        connectGroupsLifeStage.GroupTypeId = groupTypeIdSection;
                        connectGroupsLifeStage.CampusId = 1;
                        connectGroupsLifeStage.Name = lifeStage;
                        connectGroupsLifeStage.Description = "";
                        connectGroupsLifeStage.IsActive = true;
                        //connectGroupsLifeStage.Order = 0;
                        connectGroupsLifeStage.CreatedByPersonAliasId = 1;
                        connectGroupsLifeStage.CreatedDateTime = DateTime.Now;

                        //save Life Stage

                        lifeStageContext.WrapTransaction( () =>
                        {
                            lifeStageContext.Configuration.AutoDetectChangesEnabled = false;
                            lifeStageContext.Groups.Add( connectGroupsLifeStage );
                            lifeStageContext.SaveChanges( DisableAudit );
                        } );
                        completedLifeStages++;
                    }

                    int existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault();
                    existingLifeStage = new GroupService( lookupContext ).Queryable().Where( g => g.Name == lifeStage ).Select( a => a.Id ).FirstOrDefault();
                    //check to see if Connect Group exists.
                    if ( existingConnectGroup == 0 )
                    {
                        //Create one.
                        var connectGroups = new Group();
                        connectGroups.IsSystem = false;
                        connectGroups.GroupTypeId = groupTypeIdSmallGroup;
                        connectGroups.ParentGroupId = existingLifeStage;
                        connectGroups.CampusId = 1;
                        connectGroups.Name = groupName;
                        connectGroups.Description = "";
                        connectGroups.IsActive = true;
                        //connectGroups.Order = 0;
                        connectGroups.CreatedByPersonAliasId = 1;
                        connectGroups.CreatedDateTime = createdDateTime;
                        connectGroups.ForeignId = groupId.ToString(); //Will use this for GroupsAttendance

                        //Save Group
                        connectGroupContext.WrapTransaction( () =>
                        {
                            connectGroupContext.Configuration.AutoDetectChangesEnabled = false;
                            connectGroupContext.Groups.Add( connectGroups );
                            connectGroupContext.SaveChanges( DisableAudit );
                        } );
                        completedGroups++;
                    }

                    existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault();

                    //Adds Group Member(s)
                    //makes sure Connect Group Exists
                    if ( existingConnectGroup != 0 )
                    {
                        int memberGroupTypeRoleId = new GroupTypeRoleService( lookupContext ).Queryable().Where( g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member" ).Select( a => a.Id ).FirstOrDefault();
                        int groupMemberExists = new GroupMemberService( lookupContext ).Queryable().Where( g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId ).Select( a => a.Id ).FirstOrDefault();
                        if ( groupMemberExists == 0 )
                        {
                            //adds member
                            var connectGroupMember = new GroupMember();
                            connectGroupMember.IsSystem = false;
                            connectGroupMember.GroupId = existingConnectGroup;
                            connectGroupMember.PersonId = (int)personId;
                            connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member
                           // ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) );

                            //Save Member
                            connectGroupMemberContext.WrapTransaction( () =>
                            {
                                connectGroupMemberContext.Configuration.AutoDetectChangesEnabled = false;
                                connectGroupMemberContext.GroupMembers.Add( connectGroupMember );
                                connectGroupMemberContext.SaveChanges( DisableAudit );
                            } );
                            completedMembers++;
                        }
                    }

                    if ( completedMembers % percentage < 1 )
                    {
                        int percentComplete = completedMembers / percentage;
                        //ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) );
                    }
                    else if ( completedMembers % ReportingNumber < 1 )
                    {
                        ReportPartialProgress();
                    }

                }

                if ( groupTypeName.Trim() == "Care Ministries" )            //Moves Care Ministries into Rock Groups
                {

                    var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault();
                    var careMinistriesId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Care Ministries" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault();
                    var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault();

                    string groupName = row["Group_Name"] as string;
                    int? groupId = row["Group_ID"] as int?;
                    int? individualId = row["Individual_ID"] as int?;
                    int? personId = GetPersonAliasId( individualId );
                    DateTime? createdDateTime = row["Created_Date"] as DateTime?;

                    //Check to see if Head of Care Ministries Tree exists

                    //If it doesn't exist
                    if ( careMinistriesId == 0 )
                    {
                        //Create one.
                        var connectGroupTree = new Group();
                        connectGroupTree.IsSystem = false;
                        connectGroupTree.GroupTypeId = groupTypeIdSection;
                        connectGroupTree.CampusId = 1;
                        connectGroupTree.Name = "Care Ministries";
                        connectGroupTree.Description = "Crossroads Care Ministries";
                        connectGroupTree.IsActive = true;
                        //connectGroupTree.Order = 0;
                        connectGroupTree.CreatedByPersonAliasId = 1;
                        connectGroupTree.CreatedDateTime = DateTime.Now;

                        //save group
                        var careMinistryContext = new RockContext();
                        careMinistryContext.WrapTransaction( () =>
                        {
                            careMinistryContext.Configuration.AutoDetectChangesEnabled = false;
                            careMinistryContext.Groups.Add( connectGroupTree );
                            careMinistryContext.SaveChanges( DisableAudit );
                        } );
                    }

                    int existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault();
                    int existingCareMinistries = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Care Ministries" ).Select( a => a.Id ).FirstOrDefault();

                    //check to see if Connect Group exists.
                    if ( existingConnectGroup == 0 )
                    {
                        //Create one.
                        var careGroup = new Group();
                        careGroup.IsSystem = false;
                        careGroup.GroupTypeId = groupTypeIdSmallGroup;
                        careGroup.ParentGroupId = existingCareMinistries;
                        careGroup.CampusId = 1;
                        careGroup.Name = groupName;
                        careGroup.Description = "";
                        careGroup.IsActive = true;
                        //connectGroups.Order = 0;
                        careGroup.CreatedByPersonAliasId = 1;
                        careGroup.CreatedDateTime = createdDateTime;
                        careGroup.ForeignId = groupId.ToString(); //will use this later for GroupsAttendance

                        //Save Group
                        var careMinistryGroupContext = new RockContext();
                        careMinistryGroupContext.WrapTransaction( () =>
                        {
                            careMinistryGroupContext.Configuration.AutoDetectChangesEnabled = false;
                            careMinistryGroupContext.Groups.Add( careGroup );
                            careMinistryGroupContext.SaveChanges( DisableAudit );
                        } );
                        completedGroups++;
                    }

                    existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault();

                    //Adds Group Member(s)
                    //makes sure Connect Group Exists
                    if ( existingConnectGroup != 0 )
                    {
                        int memberGroupTypeRoleId = new GroupTypeRoleService( lookupContext ).Queryable().Where( g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member" ).Select( a => a.Id ).FirstOrDefault();
                        int groupMemberExists = new GroupMemberService( lookupContext ).Queryable().Where( g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId ).Select( a => a.Id ).FirstOrDefault();
                        if ( groupMemberExists == 0 )
                        {
                            //adds member
                            var connectGroupMember = new GroupMember();
                            connectGroupMember.IsSystem = false;
                            connectGroupMember.GroupId = existingConnectGroup;
                            connectGroupMember.PersonId = (int)personId;
                            connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member
                            //ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) );

                            //Save Member
                            var careGroupMemberContext = new RockContext();
                            careGroupMemberContext.WrapTransaction( () =>
                            {
                                careGroupMemberContext.Configuration.AutoDetectChangesEnabled = false;
                                careGroupMemberContext.GroupMembers.Add( connectGroupMember );
                                careGroupMemberContext.SaveChanges( DisableAudit );
                            } );
                            completedMembers++;
                        }
                    }

                    if ( completedMembers % percentage < 1 )
                    {
                        int percentComplete = completedMembers / percentage;
                       // ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) );
                    }
                    else if ( completedMembers % ReportingNumber < 1 )
                    {
                        ReportPartialProgress();
                    }

                }

                if ( groupTypeName.Trim() == "Intro Connect Groups" )            //Moves Intro Connect Groups into Rock Groups
                {

                    var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault();
                    var introConnectGroupsId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Intro Connect Groups" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault();
                    var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault();

                    string groupName = row["Group_Name"] as string;
                    int? groupId = row["Group_ID"] as int?;
                    int? individualId = row["Individual_ID"] as int?;
                    int? personId = GetPersonAliasId( individualId );
                    DateTime? createdDateTime = row["Created_Date"] as DateTime?;

                    //Check to see if Head of Care Ministries Tree exists

                    //If it doesn't exist
                    if ( introConnectGroupsId == 0 )
                    {
                        //Create one.
                        var connectGroupTree = new Group();
                        connectGroupTree.IsSystem = false;
                        connectGroupTree.GroupTypeId = groupTypeIdSection;
                        connectGroupTree.CampusId = 1;
                        connectGroupTree.Name = "Intro Connect Groups";
                        connectGroupTree.Description = "Crossroads Intro Connect Groups";
                        connectGroupTree.IsActive = true;
                        //connectGroupTree.Order = 0;
                        connectGroupTree.CreatedByPersonAliasId = 1;
                        connectGroupTree.CreatedDateTime = DateTime.Now;

                        //save group
                        var introConnectGroupTreeContext = new RockContext();
                         introConnectGroupTreeContext.WrapTransaction( () =>
                        {
                            introConnectGroupTreeContext.Configuration.AutoDetectChangesEnabled = false;
                            introConnectGroupTreeContext.Groups.Add( connectGroupTree );
                            introConnectGroupTreeContext.SaveChanges( DisableAudit );
                        } );
                    }

                    int existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault();
                    int existingIntroConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Intro Connect Groups" ).Select( a => a.Id ).FirstOrDefault();

                    //check to see if Connect Group exists.
                    if ( existingConnectGroup == 0 )
                    {
                        //Create one.
                        var introConnectGroup = new Group();
                        introConnectGroup.IsSystem = false;
                        introConnectGroup.GroupTypeId = groupTypeIdSmallGroup;
                        introConnectGroup.ParentGroupId = existingIntroConnectGroup;
                        introConnectGroup.CampusId = 1;
                        introConnectGroup.Name = groupName;
                        introConnectGroup.Description = "";
                        introConnectGroup.IsActive = true;
                        //connectGroups.Order = 0;
                        introConnectGroup.CreatedByPersonAliasId = 1;
                        introConnectGroup.CreatedDateTime = createdDateTime;
                        introConnectGroup.ForeignId = groupId.ToString(); //will use this later for GroupsAttendance

                        //Save Group
                        var introConnectGroupConext = new RockContext();
                        introConnectGroupConext.WrapTransaction( () =>
                        {
                            introConnectGroupConext.Configuration.AutoDetectChangesEnabled = false;
                            introConnectGroupConext.Groups.Add( introConnectGroup );
                            introConnectGroupConext.SaveChanges( DisableAudit );
                        } );
                        completedGroups++;
                    }

                    existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault();

                    //Adds Group Member(s)
                    //makes sure Connect Group Exists
                    if ( existingConnectGroup != 0 )
                    {
                        int memberGroupTypeRoleId = new GroupTypeRoleService( lookupContext ).Queryable().Where( g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member" ).Select( a => a.Id ).FirstOrDefault();
                        int groupMemberExists = new GroupMemberService( lookupContext ).Queryable().Where( g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId ).Select( a => a.Id ).FirstOrDefault();
                        if ( groupMemberExists == 0 )
                        {
                            //adds member
                            var connectGroupMember = new GroupMember();
                            connectGroupMember.IsSystem = false;
                            connectGroupMember.GroupId = existingConnectGroup;
                            connectGroupMember.PersonId = (int)personId;
                            connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member
                            //ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) );

                            //Save Member
                            var introConnectGroupMemberConext = new RockContext();
                            introConnectGroupMemberConext.WrapTransaction( () =>
                            {
                                introConnectGroupMemberConext.Configuration.AutoDetectChangesEnabled = false;
                                introConnectGroupMemberConext.GroupMembers.Add( connectGroupMember );
                                introConnectGroupMemberConext.SaveChanges( DisableAudit );
                            } );
                            completedMembers++;
                        }
                    }

                    if ( completedMembers % percentage < 1 )
                    {
                        int percentComplete = completedMembers / percentage;
                       // ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) );
                    }
                    else if ( completedMembers % ReportingNumber < 1 )
                    {
                        ReportPartialProgress();
                    }

                }

                if ( groupTypeName.Trim() == "People List" )    //Places People Lists in tags
                {

                    var tagService = new TagService( lookupContext );
                    var entityTypeService = new EntityTypeService( lookupContext );
                    var taggedItemService = new TaggedItemService( lookupContext );
                    var personService = new PersonService( lookupContext );

                    //var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault();
                    //var connectGroupsId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Connect Groups" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault();
                    //var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault();

                    string peopleListName = row["Group_Name"] as string;
                    int? groupId = row["Group_ID"] as int?;
                    int? individualId = row["Individual_ID"] as int?;
                    int? personId = GetPersonAliasId( individualId );
                    DateTime? createdDateTime = row["Created_Date"] as DateTime?;

                    if ( personId != null )
                    {
                        //check if tag exists
                        if ( tagService.Queryable().Where( t => t.Name == peopleListName ).FirstOrDefault() == null )
                        {
                            //create if it doesn't
                            var newTag = new Tag();
                            newTag.IsSystem = false;
                            newTag.Name = peopleListName;
                            newTag.EntityTypeQualifierColumn = string.Empty;
                            newTag.EntityTypeQualifierValue = string.Empty;
                            newTag.EntityTypeId = entityTypeService.Queryable().Where( e => e.Name == "Rock.Model.Person" ).FirstOrDefault().Id;

                            //Save tag
                            var tagContext = new RockContext();
                            tagContext.WrapTransaction( () =>
                            {
                                tagContext.Configuration.AutoDetectChangesEnabled = false;
                                tagContext.Tags.Add( newTag );
                                tagContext.SaveChanges( DisableAudit );
                            } );

                            completedTags++;
                        }

                        var personAlias = new PersonAlias();
                        personAlias = null;

                        if ( tagService.Queryable().Where( t => t.Name == peopleListName ).FirstOrDefault() != null ) //Makes sure tag exists
                        {
                            //selects the ID of the current people list / tag
                            int tagId = tagService.Queryable().Where( t => t.Name == peopleListName ).FirstOrDefault().Id;

                            //gets the person instance in order to use person's GUID later.
                            var personTagged = personService.Queryable().Where( p => p.Id == personId ).FirstOrDefault();
                            if ( personTagged == null )
                            {
                                var personAliasService = new PersonAliasService(lookupContext);
                                personAlias = personAliasService.Queryable().Where( p => p.PersonId == (int)personId ).FirstOrDefault();
                                //ReportProgress( 0, string.Format( "Not able to tag person Id: {0} Tag Name: {1} F1 groupId: {2} Tag Id: {3}. ", personId, peopleListName, groupId, tagId ) );

                            }

                            //check if person already has this tag
                            if ( personTagged != null && taggedItemService.Queryable().Where( t => t.EntityGuid == personTagged.Guid && t.TagId == tagId ).FirstOrDefault() == null )
                            {

                                //add tag if one doesn't exist for person.
                                var taggedItem = new TaggedItem();
                                taggedItem.IsSystem = false;
                                taggedItem.TagId = tagId;
                                taggedItem.EntityGuid = personTagged.Guid;
                                taggedItem.CreatedDateTime = createdDateTime;

                                //save tag
                                var tagContext = new RockContext();
                                tagContext.WrapTransaction( () =>
                                {
                                    tagContext.Configuration.AutoDetectChangesEnabled = false;
                                    tagContext.TaggedItems.Add( taggedItem );
                                    tagContext.SaveChanges( DisableAudit );
                                } );

                                completedIndividualTags++;
                            }
                            if ( personAlias != null && taggedItemService.Queryable().Where( t => t.EntityGuid == personAlias.AliasPersonGuid && t.TagId == tagId ).FirstOrDefault() == null )
                            {

                                //add tag if one doesn't exist for person.
                                var taggedItem = new TaggedItem();
                                taggedItem.IsSystem = false;
                                taggedItem.TagId = tagId;
                                taggedItem.EntityGuid = personAlias.AliasPersonGuid;
                                taggedItem.CreatedDateTime = createdDateTime;

                                //save tag
                                var tagContext = new RockContext();
                                tagContext.WrapTransaction( () =>
                                {
                                    tagContext.Configuration.AutoDetectChangesEnabled = false;
                                    tagContext.TaggedItems.Add( taggedItem );
                                    tagContext.SaveChanges( DisableAudit );
                                } );

                                completedIndividualTags++;
                            }
                        }
                        //report Progress
                        if ( completedIndividualTags != 0 )
                        {
                            if ( completedIndividualTags % percentage < 1 )
                            {
                                int percentComplete = completedIndividualTags / percentage;
                               // ReportProgress( percentComplete, string.Format( "People Lists / Tags Imported: {0:N0}, Tagged Individuals: {1:N0} ({2:N0}% complete). ", completedTags, completedIndividualTags, percentComplete ) );
                            }
                            else if ( completedMembers % ReportingNumber < 1 )
                            {
                                ReportPartialProgress();
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Handles the Click event of the btnCreateCommunication 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 btnCreateCommunication_Click(object sender, EventArgs e)
        {
            // Create communication
            var rockContext          = new RockContext();
            var communicationService = new Rock.Model.CommunicationService(rockContext);
            var communication        = new Rock.Model.Communication();

            communication.IsBulkCommunication = false;
            communication.Status = CommunicationStatus.Transient;
            communication.SenderPersonAliasId = this.CurrentPersonAliasId;

            if (this.Request != null && this.Request.Url != null)
            {
                communication.UrlReferrer = this.Request.UrlProxySafe().AbsoluteUri.TrimForMaxLength(communication, "UrlReferrer");
            }

            communicationService.Add(communication);

            // save communication to get Id
            rockContext.SaveChanges();

            int[]      scheduleIds    = lbSchedules.SelectedValuesAsInt.ToArray();
            int[]      locationIds    = cblLocations.SelectedValuesAsInt.ToArray();
            List <int> parentGroupIds = gpGroups.SelectedValuesAsInt().ToList();

            var allGroupIds = new List <int>();

            allGroupIds.AddRange(parentGroupIds);

            if (cbIncludeChildGroups.Checked)
            {
                var groupService = new GroupService(rockContext);
                foreach (var groupId in parentGroupIds)
                {
                    // just the first level of child groups, not all decendants
                    var childGroupIds = groupService.Queryable()
                                        .Where(a => a.ParentGroupId == groupId && a.GroupType.IsSchedulingEnabled && !a.DisableScheduling)
                                        .Select(a => a.Id).ToList();
                    allGroupIds.AddRange(childGroupIds);
                }
            }

            allGroupIds = allGroupIds.Distinct().ToList();

            var attendanceOccurrenceService = new AttendanceOccurrenceService(rockContext);

            var sundayDate = ddlWeek.SelectedValue.AsDateTime() ?? RockDateTime.Now.SundayDate();

            var attendanceOccurrenceQuery = attendanceOccurrenceService
                                            .Queryable()
                                            .Where(a => a.ScheduleId.HasValue && a.LocationId.HasValue && a.GroupId.HasValue)
                                            .WhereDeducedIsActive()
                                            .Where(a => allGroupIds.Contains(a.GroupId.Value))
                                            .Where(a => locationIds.Contains(a.LocationId.Value))
                                            .Where(a => scheduleIds.Contains(a.ScheduleId.Value))
                                            .Where(a => a.SundayDate == sundayDate);

            ScheduledAttendanceItemStatus[] selectedInviteStatus = cblInviteStatus.SelectedValues
                                                                   .Select(a => a.ConvertToEnum <ScheduledAttendanceItemStatus>())
                                                                   .ToArray();

            // limit attendees to ones based on the selected invite status
            var scheduledAttendancesForOccurrenceQuery = attendanceOccurrenceQuery
                                                         .SelectMany(a => a.Attendees)
                                                         .WhereHasScheduledAttendanceItemStatus(selectedInviteStatus);

            var personIds = scheduledAttendancesForOccurrenceQuery.Select(a => a.PersonAlias.PersonId).Distinct().ToList();

            if (!personIds.Any())
            {
                nbCommunicationWarning.Text    = "No people found to send communication to.";
                nbCommunicationWarning.Visible = true;
                return;
            }

            nbCommunicationWarning.Visible = false;

            var personAliasService = new Rock.Model.PersonAliasService(new Rock.Data.RockContext());

            // Get the primary aliases
            List <Rock.Model.PersonAlias> primaryAliasList = new List <PersonAlias>(personIds.Count);

            // get the data in chunks just in case we have a large list of PersonIds (to avoid a SQL Expression limit error)
            var chunkedPersonIds = personIds.Take(1000);
            int skipCount        = 0;

            while (chunkedPersonIds.Any())
            {
                var chunkedPrimaryAliasList = personAliasService.Queryable()
                                              .Where(p => p.PersonId == p.AliasPersonId && chunkedPersonIds.Contains(p.PersonId)).AsNoTracking().ToList();
                primaryAliasList.AddRange(chunkedPrimaryAliasList);
                skipCount       += 1000;
                chunkedPersonIds = personIds.Skip(skipCount).Take(1000);
            }

            // NOTE: Set CreatedDateTime, ModifiedDateTime, etc manually set we are using BulkInsert
            var currentDateTime      = RockDateTime.Now;
            var currentPersonAliasId = this.CurrentPersonAliasId;

            var communicationRecipientList = primaryAliasList.Select(a => new Rock.Model.CommunicationRecipient
            {
                CommunicationId         = communication.Id,
                PersonAliasId           = a.Id,
                CreatedByPersonAliasId  = currentPersonAliasId,
                ModifiedByPersonAliasId = currentPersonAliasId,
                CreatedDateTime         = currentDateTime,
                ModifiedDateTime        = currentDateTime
            }).ToList();

            // BulkInsert to quickly insert the CommunicationRecipient records. Note: This is much faster, but will bypass EF and Rock processing.
            var communicationRecipientRockContext = new RockContext();

            communicationRecipientRockContext.BulkInsert(communicationRecipientList);

            var    pageRef = this.RockPage.Site.CommunicationPageReference;
            string communicationUrl;

            if (pageRef.PageId > 0)
            {
                pageRef.Parameters.AddOrReplace("CommunicationId", communication.Id.ToString());
                communicationUrl = pageRef.BuildUrl();
            }
            else
            {
                communicationUrl = "~/Communication/{0}";
            }

            if (communicationUrl.Contains("{0}"))
            {
                communicationUrl = string.Format(communicationUrl, communication.Id);
            }

            UserPreferenceConfiguration userPreferenceConfiguration = this.GetBlockUserPreference(UserPreferenceKey.UserPreferenceConfigurationJSON).FromJsonOrNull <UserPreferenceConfiguration>() ?? new UserPreferenceConfiguration();

            userPreferenceConfiguration.GroupIds           = gpGroups.SelectedValuesAsInt().ToArray();
            userPreferenceConfiguration.IncludeChildGroups = cbIncludeChildGroups.Checked;
            userPreferenceConfiguration.InviteStatuses     = cblInviteStatus.SelectedValues.ToArray();
            userPreferenceConfiguration.ScheduleIds        = lbSchedules.SelectedValuesAsInt.ToArray();
            userPreferenceConfiguration.LocationIds        = cblLocations.SelectedValuesAsInt.ToArray();
            this.SetBlockUserPreference(UserPreferenceKey.UserPreferenceConfigurationJSON, userPreferenceConfiguration.ToJson());

            Page.Response.Redirect(communicationUrl, false);
            Context.ApplicationInstance.CompleteRequest();
        }
Example #15
0
        /// <summary>
        /// Reads new values entered by the user for the field (as PersonAlias.Guid)
        /// </summary>
        /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public override string GetEditValue( System.Web.UI.Control control, Dictionary<string, ConfigurationValue> configurationValues )
        {
            PersonPicker ppPerson = control as PersonPicker;
            string result = null;

            if ( ppPerson != null )
            {
                Guid personGuid = Guid.Empty;
                int? personId = ppPerson.PersonId;

                if ( personId.HasValue )
                {
                    var rockContext = new RockContext();

                    var personAliasService = new PersonAliasService( rockContext );
                    var personAlias = personAliasService.Queryable()
                        .Where( a => a.AliasPersonId == personId )
                        .FirstOrDefault();
                    if ( personAlias != null )
                    {
                        result = personAlias.Guid.ToString();
                    }
                    else
                    {
                        // If the personId is valid, there should be a personAlias with the AliasPersonID equal 
                        // to that personId.  If there isn't for some reason, create it now...
                        var person = new PersonService( rockContext ).Get( personId.Value );
                        if ( person != null )
                        {
                            personAlias = new PersonAlias();
                            personAlias.Guid = Guid.NewGuid();
                            personAlias.AliasPersonId = person.Id;
                            personAlias.AliasPersonGuid = person.Guid;
                            personAlias.PersonId = person.Id;
                            result = personAlias.Guid.ToString();

                            personAliasService.Add( personAlias );
                            rockContext.SaveChanges();
                        }
                    }
                }
            }

            return result;
        }