GetByPersonId() public method

Gets an enumerable collection of Rock.Model.UserLogin entities by a Person's PersonId.
public GetByPersonId ( int personId ) : IQueryable
personId int A representing the Id of the to search by. This property is nullable /// to find entities that are not associated with a Person.
return IQueryable
Ejemplo n.º 1
0
        /// <summary>
        /// Handles the Click event of the btnDuplicatesNext 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 btnDuplicatesNext_Click(object sender, EventArgs e)
        {
            int personId = Request.Form["DuplicatePerson"].AsInteger();

            if (personId > 0)
            {
                var userLoginService = new Rock.Model.UserLoginService(new RockContext());
                var userLogins       = userLoginService.GetByPersonId(personId)
                                       .Where(l => l.IsLockedOut != true)
                                       .ToList();

                if (userLogins.Any(ul => !AuthenticationContainer.GetComponent(ul.EntityType.Name).RequiresRemoteAuthentication))
                {
                    DisplaySendLogin(personId, Direction.Forward);
                }
                else
                {
                    DisplayConfirmation(personId);
                }
            }
            else
            {
                DisplaySuccess(CreateUser(CreatePerson(), true));
            }
        }
        /// <summary>
        /// Handles the Click event of the btnSend 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 btnSend_Click( object sender, EventArgs e )
        {
            var url = LinkedPageUrl( "ConfirmationPage" );
            if ( string.IsNullOrWhiteSpace( url ) )
            {
                url = ResolveRockUrl( "~/ConfirmAccount" );
            }

            var mergeObjects = GlobalAttributesCache.GetMergeFields( CurrentPerson );
            mergeObjects.Add( "ConfirmAccountUrl", RootPath + url.TrimStart( new char[] { '/' } ) );
            var results = new List<IDictionary<string, object>>();

            var rockContext = new RockContext();
            var personService = new PersonService( rockContext );
            var userLoginService = new UserLoginService( rockContext );

            foreach ( Person person in personService.GetByEmail( tbEmail.Text )
                .Where( p => p.Users.Any()))
            {
                var users = new List<UserLogin>();
                foreach ( UserLogin user in userLoginService.GetByPersonId( person.Id ) )
                {
                    if ( user.EntityType != null )
                    {
                        var component = AuthenticationContainer.GetComponent( user.EntityType.Name );
                        if ( !component.RequiresRemoteAuthentication )
                        {
                            users.Add( user );
                        }
                    }
                }

                var resultsDictionary = new Dictionary<string, object>();
                resultsDictionary.Add( "Person", person);
                resultsDictionary.Add( "Users", users );
                results.Add( resultsDictionary );
            }

            if ( results.Count > 0 )
            {
                mergeObjects.Add( "Results", results.ToArray() );
                var recipients = new List<RecipientData>();
                recipients.Add( new RecipientData( tbEmail.Text, mergeObjects ) );

                Email.Send( GetAttributeValue( "EmailTemplate" ).AsGuid(), recipients, ResolveRockUrlIncludeRoot( "~/" ), ResolveRockUrlIncludeRoot( "~~/" ) );

                pnlEntry.Visible = false;
                pnlSuccess.Visible = true;
            }
            else
            {
                pnlWarning.Visible = true;
            }
        }
Ejemplo n.º 3
0
        protected void btnDuplicatesNext_Click(object sender, EventArgs e)
        {
            int personId = Int32.Parse(Request.Form["DuplicatePerson"]);

            if (personId > 0)
            {
                var userLoginService = new Rock.Model.UserLoginService();
                var userLogins       = userLoginService.GetByPersonId(personId).ToList();
                if (userLogins.Count > 0)
                {
                    DisplaySendLogin(personId, Direction.Forward);
                }
                else
                {
                    DisplayConfirmation(personId);
                }
            }
            else
            {
                DisplaySuccess(CreateUser(CreatePerson(), true));
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Handles the Click event of the btnDuplicatesNext 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 btnDuplicatesNext_Click(object sender, EventArgs e)
        {
            if (tbRockFullName.Text.IsNotNullOrWhiteSpace())
            {
                /* 03/22/2021 MDP
                 *
                 * see https://app.asana.com/0/1121505495628584/1200018171012738/f on why this is done
                 *
                 */

                nbRockFullName.Visible             = true;
                nbRockFullName.NotificationBoxType = NotificationBoxType.Validation;
                nbRockFullName.Text = "Invalid Form Value";
                return;
            }

            int personId = Request.Form["DuplicatePerson"].AsInteger();

            if (personId > 0)
            {
                var userLoginService = new Rock.Model.UserLoginService(new RockContext());
                var userLogins       = userLoginService.GetByPersonId(personId)
                                       .Where(l => l.IsLockedOut != true)
                                       .ToList();

                if (userLogins.Any(ul => !AuthenticationContainer.GetComponent(ul.EntityType.Name).RequiresRemoteAuthentication))
                {
                    DisplaySendLogin(personId, Direction.Forward);
                }
                else
                {
                    DisplayConfirmation(personId);
                }
            }
            else
            {
                DisplaySuccess(CreateUser(CreatePerson(), true));
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Displays the sent login.
        /// </summary>
        /// <param name="direction">The direction.</param>
        private void DisplaySentLogin( Direction direction )
        {
            var rockContext = new RockContext();
            PersonService personService = new PersonService( rockContext );
            Person person = personService.Get( hfSendPersonId.Value.AsInteger() ?? 0 );
            if ( person != null )
            {
                string url = LinkedPageUrl( "ConfirmationPage" );
                if ( string.IsNullOrWhiteSpace( url ) )
                {
                    url = ResolveRockUrl( "~/ConfirmAccount" );
                }

                var mergeObjects = new Dictionary<string, object>();
                mergeObjects.Add( "ConfirmAccountUrl", RootPath + url.TrimStart( new char[] { '/' } ) );

                var personDictionaries = new List<IDictionary<string, object>>();

                var users = new List<UserLogin>();
                var userLoginService = new UserLoginService( rockContext );
                foreach ( UserLogin user in userLoginService.GetByPersonId( person.Id ) )
                {
                    if ( user.EntityType != null )
                    {
                        var component = AuthenticationContainer.GetComponent( user.EntityType.Name );
                        if ( component.ServiceType == AuthenticationServiceType.Internal )
                        {
                            users.Add( user );
                        }
                    }
                }

                if ( users.Count > 0 )
                {
                    var personDictionary = person.ToLiquid() as Dictionary<string, object>;
                    if ( personDictionary.Keys.Contains( "Users" ) )
                    {
                        personDictionary["Users"] = users;
                    }
                    else
                    {
                        personDictionary.Add( "Users", users );
                    }

                    personDictionaries.Add( personDictionary );
                }

                mergeObjects.Add( "Persons", personDictionaries.ToArray() );

                var recipients = new Dictionary<string, Dictionary<string, object>>();
                recipients.Add( person.Email, mergeObjects );

                Email.Send( GetAttributeValue( "ForgotUsernameTemplate" ).AsGuid(), recipients, ResolveRockUrl( "~/" ), ResolveRockUrl( "~~/" ) );
            }
            else
            {
                ShowErrorMessage( "Invalid Person" );
            }

            ShowPanel( 3 );
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Handles the Click event of the btnDuplicatesNext 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 btnDuplicatesNext_Click( object sender, EventArgs e )
 {
     int personId = Request.Form["DuplicatePerson"].AsInteger() ?? 0;
     if ( personId > 0 )
     {
         var userLoginService = new Rock.Model.UserLoginService( new RockContext() );
         var userLogins = userLoginService.GetByPersonId( personId ).ToList();
         if ( userLogins.Count > 0 )
         {
             DisplaySendLogin( personId, Direction.Forward );
         }
         else
         {
             DisplayConfirmation( personId );
         }
     }
     else
     {
         DisplaySuccess( CreateUser( CreatePerson(), true ) );
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Handles the Click event of the btnSend 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 btnSend_Click( object sender, EventArgs e )
        {
            var url = LinkedPageUrl( "ConfirmationPage" );
            if ( string.IsNullOrWhiteSpace( url ) )
            {
                url = ResolveRockUrl( "~/ConfirmAccount" );
            }

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson );
            mergeFields.Add( "ConfirmAccountUrl", RootPath + url.TrimStart( new char[] { '/' } ) );
            var results = new List<IDictionary<string, object>>();

            var rockContext = new RockContext();
            var personService = new PersonService( rockContext );
            var userLoginService = new UserLoginService( rockContext );

            bool hasAccountWithPasswordResetAbility = false;
            List<string> accountTypes = new List<string>();

            foreach ( Person person in personService.GetByEmail( tbEmail.Text )
                .Where( p => p.Users.Any()))
            {
                var users = new List<UserLogin>();
                foreach ( UserLogin user in userLoginService.GetByPersonId( person.Id ) )
                {
                    if ( user.EntityType != null )
                    {
                        var component = AuthenticationContainer.GetComponent( user.EntityType.Name );
                        if ( !component.RequiresRemoteAuthentication )
                        {
                            users.Add( user );
                            hasAccountWithPasswordResetAbility = true;
                        }

                        accountTypes.Add( user.EntityType.FriendlyName );
                    }
                }

                var resultsDictionary = new Dictionary<string, object>();
                resultsDictionary.Add( "Person", person);
                resultsDictionary.Add( "Users", users );
                results.Add( resultsDictionary );
            }

            if ( results.Count > 0 && hasAccountWithPasswordResetAbility )
            {
                mergeFields.Add( "Results", results.ToArray() );
                var recipients = new List<RecipientData>();
                recipients.Add( new RecipientData( tbEmail.Text, mergeFields ) );

                Email.Send( GetAttributeValue( "EmailTemplate" ).AsGuid(), recipients, ResolveRockUrlIncludeRoot( "~/" ), ResolveRockUrlIncludeRoot( "~~/" ), false );

                pnlEntry.Visible = false;
                pnlSuccess.Visible = true;
            }
            else if (results.Count > 0 )
            {
                // the person has user accounts but none of them are allowed to have their passwords reset (Facebook/Google/etc)

                lWarning.Text = string.Format( @"<p>We were able to find the following accounts for this email, but
                                                none of them are able to be reset from this website.</p> <p>Accounts:<br /> {0}</p>
                                                <p>To create a new account with a username and password please see our <a href='{1}'>New Account</a>
                                                page.</p>"
                                    , string.Join( ",", accountTypes )
                                    , ResolveRockUrl( "~/NewAccount" ) );
                pnlWarning.Visible = true;
            }
            else
            {
                pnlWarning.Visible = true;
            }
        }
        /// <summary>
        /// Handles the Click event of the lbSave 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 lbSave_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            var userLoginService = new UserLoginService( rockContext );

            var userLogin = userLoginService.Queryable().Where( a => a.ApiKey == tbKey.Text ).FirstOrDefault();
            if ( userLogin != null && userLogin.PersonId != int.Parse( hfRestUserId.Value ) )
            {
                // this key already exists in the database. Show the error and get out of here.
                nbWarningMessage.Text = "This API Key already exists. Please enter a different one, or generate one by clicking the 'Generate Key' button below. ";
                nbWarningMessage.Visible = true;
                return;
            }

            rockContext.WrapTransaction( () =>
            {
                var personService = new PersonService( rockContext );
                var changes = new List<string>();
                var restUser = new Person();
                if ( int.Parse( hfRestUserId.Value ) != 0 )
                {
                    restUser = personService.Get( int.Parse( hfRestUserId.Value ) );
                }
                else
                {
                    personService.Add( restUser );
                    rockContext.SaveChanges();
                    restUser.Aliases.Add( new PersonAlias { AliasPersonId = restUser.Id, AliasPersonGuid = restUser.Guid } );
                }

                // the rest user name gets saved as the last name on a person
                History.EvaluateChange( changes, "Last Name", restUser.LastName, tbName.Text );
                restUser.LastName = tbName.Text;
                restUser.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_RESTUSER.AsGuid() ).Id;
                if ( cbActive.Checked )
                {
                    restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid() ).Id;
                }
                else
                {
                    restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid() ).Id;
                }

                if ( restUser.IsValid )
                {
                    if ( rockContext.SaveChanges() > 0 )
                    {
                        if ( changes.Any() )
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof( Person ),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                restUser.Id,
                                changes );
                        }
                    }
                }

                // the description gets saved as a system note for the person
                var noteType = new NoteTypeService( rockContext )
                    .Get( Rock.SystemGuid.NoteType.PERSON_TIMELINE.AsGuid() );
                var noteService = new NoteService( rockContext );
                var note = noteService.Get( noteType.Id, restUser.Id ).FirstOrDefault();
                if ( note == null )
                {
                    note = new Note();
                    noteService.Add( note );
                }

                note.NoteTypeId = noteType.Id;
                note.EntityId = restUser.Id;
                note.Text = tbDescription.Text;
                rockContext.SaveChanges();

                // the key gets saved in the api key field of a user login (which you have to create if needed)
                var entityType = new EntityTypeService( rockContext )
                    .Get( "Rock.Security.Authentication.Database" );
                userLogin = userLoginService.GetByPersonId( restUser.Id ).FirstOrDefault();
                if ( userLogin == null )
                {
                    userLogin = new UserLogin();
                    userLoginService.Add( userLogin );
                }

                if ( string.IsNullOrWhiteSpace( userLogin.UserName ) )
                {
                    userLogin.UserName = Guid.NewGuid().ToString();
                }

                userLogin.IsConfirmed = true;
                userLogin.ApiKey = tbKey.Text;
                userLogin.PersonId = restUser.Id;
                userLogin.EntityTypeId = entityType.Id;
                rockContext.SaveChanges();
            } );
            NavigateToParentPage();
        }
Ejemplo n.º 9
0
        protected void btnSend_Click( object sender, EventArgs e )
        {
            var mergeObjects = new Dictionary<string, object>();

            var url = LinkedPageUrl( "ConfirmationPage" );
            if ( string.IsNullOrWhiteSpace( url ) )
            {
                url = ResolveRockUrl( "~/ConfirmAccount" );
            }
            mergeObjects.Add( "ConfirmAccountUrl", RootPath + url.TrimStart( new char[] { '/' } ) );

            var personDictionaries = new List<IDictionary<string, object>>();

            var personService = new PersonService();
            var userLoginService = new UserLoginService();

            foreach ( Person person in personService.GetByEmail( tbEmail.Text ) )
            {
                var users = new List<IDictionary<string,object>>();
                foreach ( UserLogin user in userLoginService.GetByPersonId( person.Id ) )
                {
                    if ( user.EntityType != null )
                    {
                        var component = AuthenticationContainer.GetComponent( user.EntityType.Name );
                        if ( component.ServiceType == AuthenticationServiceType.Internal )
                        {
                            users.Add( user.ToDictionary() );
                        }
                    }
                }

                if (users.Count > 0)
                {
                    IDictionary<string,object> personDictionary = person.ToDictionary();
                    personDictionary.Add("Users", users.ToArray());
                    personDictionaries.Add( personDictionary );
                }
            }

            if ( personDictionaries.Count > 0 )
            {
                mergeObjects.Add( "Persons", personDictionaries.ToArray() );

                var recipients = new Dictionary<string, Dictionary<string, object>>();
                recipients.Add( tbEmail.Text, mergeObjects );

                Email email = new Email( GetAttributeValue( "EmailTemplate" ) );
                email.Send( recipients );

                pnlEntry.Visible = false;
                pnlSuccess.Visible = true;
            }
            else
                pnlWarning.Visible = true;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Handles the Click event of the lbMerge 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 lbMerge_Click( object sender, EventArgs e )
        {
            if ( MergeData.People.Count < 2 )
            {
                nbPeople.Visible = true;
                return;
            }

            bool reconfirmRequired = ( MergeData.People.Select( p => p.Email ).Distinct().Count() > 1 && MergeData.People.Where( p => p.HasLogins ).Any() );

            GetValuesSelection();

            int? primaryPersonId = null;

            var oldPhotos = new List<int>();

            var rockContext = new RockContext();

            rockContext.WrapTransaction( () =>
            {
                var personService = new PersonService( rockContext );
                var userLoginService = new UserLoginService( rockContext );
                var groupService = new GroupService( rockContext );
                var groupMemberService = new GroupMemberService( rockContext );
                var binaryFileService = new BinaryFileService( rockContext );
                var phoneNumberService = new PhoneNumberService( rockContext );
                var taggedItemService = new TaggedItemService( rockContext );

                Person primaryPerson = personService.Get( MergeData.PrimaryPersonId ?? 0 );
                if ( primaryPerson != null )
                {
                    primaryPersonId = primaryPerson.Id;

                    var changes = new List<string>();

                    foreach ( var p in MergeData.People.Where( p => p.Id != primaryPerson.Id ) )
                    {
                        changes.Add( string.Format( "Merged <span class='field-value'>{0} [ID: {1}]</span> with this record.", p.FullName, p.Id ) );
                    }

                    // Photo Id
                    int? newPhotoId = MergeData.GetSelectedValue( MergeData.GetProperty( "Photo" ) ).Value.AsIntegerOrNull();
                    if ( !primaryPerson.PhotoId.Equals( newPhotoId ) )
                    {
                        changes.Add( "Modified the photo." );
                        primaryPerson.PhotoId = newPhotoId;
                    }

                    primaryPerson.TitleValueId = GetNewIntValue( "Title", changes );
                    primaryPerson.FirstName = GetNewStringValue( "FirstName", changes );
                    primaryPerson.NickName = GetNewStringValue( "NickName", changes );
                    primaryPerson.MiddleName = GetNewStringValue( "MiddleName", changes );
                    primaryPerson.LastName = GetNewStringValue( "LastName", changes );
                    primaryPerson.SuffixValueId = GetNewIntValue( "Suffix", changes );
                    primaryPerson.RecordTypeValueId = GetNewIntValue( "RecordType", changes );
                    primaryPerson.RecordStatusValueId = GetNewIntValue( "RecordStatus", changes );
                    primaryPerson.RecordStatusReasonValueId = GetNewIntValue( "RecordStatusReason", changes );
                    primaryPerson.ConnectionStatusValueId = GetNewIntValue( "ConnectionStatus", changes );
                    primaryPerson.IsDeceased = GetNewBoolValue( "Deceased", changes ) ?? false;
                    primaryPerson.Gender = (Gender)GetNewEnumValue( "Gender", typeof( Gender ), changes );
                    primaryPerson.MaritalStatusValueId = GetNewIntValue( "MaritalStatus", changes );
                    primaryPerson.SetBirthDate( GetNewDateTimeValue( "BirthDate", changes ) );
                    primaryPerson.AnniversaryDate = GetNewDateTimeValue( "AnniversaryDate", changes );
                    primaryPerson.GraduationYear = GetNewIntValue( "GraduationYear", changes );
                    primaryPerson.Email = GetNewStringValue( "Email", changes );
                    primaryPerson.IsEmailActive = GetNewBoolValue( "EmailActive", changes ) ?? true;
                    primaryPerson.EmailNote = GetNewStringValue( "EmailNote", changes );
                    primaryPerson.EmailPreference = (EmailPreference)GetNewEnumValue( "EmailPreference", typeof( EmailPreference ), changes );
                    primaryPerson.SystemNote = GetNewStringValue( "InactiveReasonNote", changes );
                    primaryPerson.SystemNote = GetNewStringValue( "SystemNote", changes );

                    // Update phone numbers
                    var phoneTypes = DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE.AsGuid() ).DefinedValues;
                    foreach ( var phoneType in phoneTypes )
                    {
                        var phoneNumber = primaryPerson.PhoneNumbers.Where( p => p.NumberTypeValueId == phoneType.Id ).FirstOrDefault();
                        string oldValue = phoneNumber != null ? phoneNumber.Number : string.Empty;

                        string key = "phone_" + phoneType.Id.ToString();
                        string newValue = GetNewStringValue( key, changes );
                        bool phoneNumberDeleted = false;

                        if ( !oldValue.Equals( newValue, StringComparison.OrdinalIgnoreCase ) )
                        {
                            // New phone doesn't match old

                            if ( !string.IsNullOrWhiteSpace( newValue ) )
                            {
                                // New value exists
                                if ( phoneNumber == null )
                                {
                                    // Old value didn't exist... create new phone record
                                    phoneNumber = new PhoneNumber { NumberTypeValueId = phoneType.Id };
                                    primaryPerson.PhoneNumbers.Add( phoneNumber );
                                }

                                // Update phone number
                                phoneNumber.Number = newValue;
                            }
                            else
                            {
                                // New value doesn't exist
                                if ( phoneNumber != null )
                                {
                                    // old value existed.. delete it
                                    primaryPerson.PhoneNumbers.Remove( phoneNumber );
                                    phoneNumberService.Delete( phoneNumber );
                                    phoneNumberDeleted = true;
                                }
                            }
                        }

                        // check to see if IsMessagingEnabled is true for any of the merged people for this number/numbertype
                        if ( phoneNumber != null && !phoneNumberDeleted && !phoneNumber.IsMessagingEnabled )
                        {
                            var personIds = MergeData.People.Select( a => a.Id ).ToList();
                            var isMessagingEnabled = phoneNumberService.Queryable().Where( a => personIds.Contains( a.PersonId ) && a.Number == phoneNumber.Number && a.NumberTypeValueId == phoneNumber.NumberTypeValueId ).Any( a => a.IsMessagingEnabled );
                            if ( isMessagingEnabled )
                            {
                                phoneNumber.IsMessagingEnabled = true;
                            }
                        }
                    }

                    // Save the new record
                    rockContext.SaveChanges();

                    // Update the attributes
                    primaryPerson.LoadAttributes( rockContext );
                    foreach ( var property in MergeData.Properties.Where( p => p.Key.StartsWith( "attr_" ) ) )
                    {
                        string attributeKey = property.Key.Substring( 5 );
                        string oldValue = primaryPerson.GetAttributeValue( attributeKey ) ?? string.Empty;
                        string newValue = GetNewStringValue( property.Key, changes ) ?? string.Empty;

                        if ( !oldValue.Equals( newValue ) )
                        {
                            var attribute = primaryPerson.Attributes[attributeKey];
                            Rock.Attribute.Helper.SaveAttributeValue( primaryPerson, attribute, newValue, rockContext );
                        }
                    }

                    HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                        primaryPerson.Id, changes );

                    // Delete the unselected photos
                    string photoKeeper = primaryPerson.PhotoId.HasValue ? primaryPerson.PhotoId.Value.ToString() : string.Empty;
                    foreach ( var photoValue in MergeData.Properties
                        .Where( p => p.Key == "Photo" )
                        .SelectMany( p => p.Values )
                        .Where( v => v.Value != "" && v.Value != photoKeeper )
                        .Select( v => v.Value ) )
                    {
                        int photoId = 0;
                        if ( int.TryParse( photoValue, out photoId ) )
                        {
                            var photo = binaryFileService.Get( photoId );
                            if ( photo != null )
                            {
                                string errorMessages;
                                if ( binaryFileService.CanDelete( photo, out errorMessages ) )
                                {
                                    binaryFileService.Delete( photo );
                                }
                            }
                        }
                    }
                    rockContext.SaveChanges();

                    // Delete merged person's family records and any families that would be empty after merge
                    foreach ( var p in MergeData.People.Where( p => p.Id != primaryPersonId.Value ) )
                    {
                        // Delete the merged person's phone numbers (we've already updated the primary persons values)
                        foreach ( var phoneNumber in phoneNumberService.GetByPersonId( p.Id ) )
                        {
                            phoneNumberService.Delete( phoneNumber );
                        }

                        // If there was more than one email address and user has logins, then set any of the local
                        // logins ( database & AD ) to require a reconfirmation
                        if ( reconfirmRequired )
                        {
                            foreach ( var login in userLoginService.GetByPersonId( p.Id ) )
                            {
                                var component = Rock.Security.AuthenticationContainer.GetComponent( login.EntityType.Name );
                                if ( component != null && !component.RequiresRemoteAuthentication )
                                {
                                    login.IsConfirmed = false;
                                }
                            }
                        }

                        rockContext.SaveChanges();

                        // Delete the merged person's other family member records and the family if they were the only one in the family
                        Guid familyGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
                        foreach ( var familyMember in groupMemberService.Queryable().Where( m => m.PersonId == p.Id && m.Group.GroupType.Guid == familyGuid ) )
                        {
                            groupMemberService.Delete( familyMember );

                            rockContext.SaveChanges();

                            // Get the family
                            var family = groupService.Queryable( "Members" ).Where( f => f.Id == familyMember.GroupId ).FirstOrDefault();
                            if ( !family.Members.Any() )
                            {
                                // If there are not any other family members, delete the family record.

                                // If theres any people that have this group as a giving group, set it to null (the person being merged should be the only one)
                                foreach ( Person gp in personService.Queryable().Where( g => g.GivingGroupId == family.Id ) )
                                {
                                    gp.GivingGroupId = null;
                                }

                                // save to the database prior to doing groupService.Delete since .Delete quietly might not delete if thinks the Family is used for a GivingGroupId
                                rockContext.SaveChanges();

                                // Delete the family
                                string errorMessage;
                                if ( groupService.CanDelete( family, out errorMessage ) )
                                {
                                    var oldFamilyChanges = new List<string>();
                                    History.EvaluateChange( oldFamilyChanges, "Family", family.Name, string.Empty );
                                    HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                        primaryPersonId.Value, oldFamilyChanges, family.Name, typeof( Group ), family.Id );

                                    groupService.Delete( family );
                                    rockContext.SaveChanges();
                                }
                            }
                        }
                    }

                    // Flush any security roles that the merged person's other records were a part of
                    foreach ( var p in MergeData.People.Where( p => p.Id != primaryPersonId.Value ) )
                    {
                        foreach ( var groupMember in groupMemberService.Queryable().Where( m => m.PersonId == p.Id ) )
                        {
                            Group group = new GroupService( rockContext ).Get( groupMember.GroupId );
                            if ( group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) )
                            {
                                Rock.Security.Role.Flush( group.Id );
                                Rock.Security.Authorization.Flush();
                            }
                        }
                    }

                    // now that the Merge is complete, the EntitySet can be marked to be deleted by the RockCleanup job
                    var entitySetService = new EntitySetService( rockContext );
                    var entitySet = entitySetService.Get( MergeData.EntitySetId );
                    if ( entitySet != null )
                    {
                        entitySet.ExpireDateTime = RockDateTime.Now.AddMinutes(-1);
                        entitySet.EntitySetPurposeValueId = null;
                        rockContext.SaveChanges();
                    }

                }
            } );

            foreach ( var p in MergeData.People.Where( p => p.Id != primaryPersonId.Value ) )
            {
                // Run merge proc to merge all associated data
                var parms = new Dictionary<string, object>();
                parms.Add( "OldId", p.Id );
                parms.Add( "NewId", primaryPersonId.Value );
                DbService.ExecuteCommand( "spCrm_PersonMerge", CommandType.StoredProcedure, parms );
            }

            NavigateToLinkedPage( "PersonDetailPage", "PersonId", primaryPersonId.Value );
        }
Ejemplo n.º 11
0
        private void DisplaySentLogin( Direction direction )
        {
            using ( new Rock.Data.UnitOfWorkScope() )
            {
                PersonService personService = new PersonService();
                Person person = personService.Get( Int32.Parse( hfSendPersonId.Value ) );
                if ( person != null )
                {
                    string url = LinkedPageUrl( "ConfirmationPage" );
                    if (string.IsNullOrWhiteSpace(url))
                    {
                        url = ResolveRockUrl( "~/ConfirmAccount" );
                    }
                    var mergeObjects = new Dictionary<string, object>();
                    mergeObjects.Add( "ConfirmAccountUrl", RootPath + url.TrimStart(new char[]{'/'}) );

                    var personDictionaries = new List<IDictionary<string, object>>();

                    var users = new List<IDictionary<string, object>>();
                    var userLoginService = new UserLoginService();
                    foreach ( UserLogin user in userLoginService.GetByPersonId( person.Id ) )
                    {
                        if ( user.EntityType != null )
                        {
                            var component = AuthenticationContainer.GetComponent( user.EntityType.Name );
                            if ( component.ServiceType == AuthenticationServiceType.Internal )
                            {
                                users.Add( user.ToDictionary() );
                            }
                        }
                    }

                    if ( users.Count > 0 )
                    {
                        IDictionary<string, object> personDictionary = person.ToDictionary();
                        personDictionary.Add( "Users", users.ToArray() );
                        personDictionaries.Add( personDictionary );
                    }

                    mergeObjects.Add( "Persons", personDictionaries.ToArray() );

                    var recipients = new Dictionary<string, Dictionary<string, object>>();
                    recipients.Add( person.Email, mergeObjects );

                    Email email = new Email( GetAttributeValue( "ForgotUsernameTemplate" ) );
                    email.Send( recipients );
                }
                else
                    ShowErrorMessage( "Invalid Person" );
            }

            ShowPanel( 3 );
        }