protected void btnUpdate_Click( object sender, EventArgs e ) { if ( Page.IsValid && person != null) { PersonService personService = new PersonService(); person.GivenName = txtFirstName.Text; person.NickName = txtNickName.Text; person.LastName = txtLastName.Text; if ( person.Guid == Guid.Empty ) personService.Add( person, CurrentPersonId ); personService.Save( person, CurrentPersonId ); } }
/// <summary> /// Finds the person if they're logged in, or by email and name. If not found, creates a new person. /// </summary> /// <returns></returns> private Person FindPerson() { Person person; var personService = new PersonService(); if ( CurrentPerson != null ) { person = CurrentPerson; } else { person = personService.GetByEmail( tbEmail.Text ) .FirstOrDefault( p => p.FirstName == tbFirstName.Text && p.LastName == tbLastName.Text ); } if ( person == null ) { var definedValue = DefinedValueCache.Read( new Guid( GetAttributeValue( "DefaultConnectionStatus" ) ) ); person = new Person { FirstName = tbFirstName.Text, LastName = tbLastName.Text, Email = tbEmail.Text, ConnectionStatusValueId = definedValue.Id, }; personService.Add( person, CurrentPersonId ); personService.Save( person, CurrentPersonId ); } return person; }
private Person CreatePerson() { Rock.Model.PersonService personService = new PersonService(); Person person = new Person(); person.FirstName = tbFirstName.Text; person.LastName = tbLastName.Text; person.Email = tbEmail.Text; switch(ddlGender.SelectedValue) { case "M": person.Gender = Gender.Male; break; case "F": person.Gender = Gender.Female; break; default: person.Gender = Gender.Unknown; break; } var birthday = bdaypBirthDay.SelectedDate; if ( birthday.HasValue ) { person.BirthMonth = birthday.Value.Month; person.BirthDay = birthday.Value.Day; if ( birthday.Value.Year != DateTime.MinValue.Year ) { person.BirthYear = birthday.Value.Year; } } personService.Add(person, CurrentPersonId); personService.Save(person, CurrentPersonId); return person; }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { // confirmation was disabled by btnSave on client-side. So if returning without a redirect, // it should be enabled. If returning with a redirect, the control won't be updated to reflect // confirmation being enabled, so it's ok to enable it here confirmExit.Enabled = true; if ( Page.IsValid ) { confirmExit.Enabled = true; RockTransactionScope.WrapTransaction( () => { using ( new UnitOfWorkScope() ) { var familyService = new GroupService(); var familyMemberService = new GroupMemberService(); var personService = new PersonService(); var historyService = new HistoryService(); var familyChanges = new List<string>(); // SAVE FAMILY _family = familyService.Get( _family.Id ); History.EvaluateChange( familyChanges, "Name", _family.Name, tbFamilyName.Text ); _family.Name = tbFamilyName.Text; int? campusId = cpCampus.SelectedValueAsInt(); if ( _family.CampusId != campusId ) { History.EvaluateChange( familyChanges, "Campus", _family.CampusId.HasValue ? CampusCache.Read( _family.CampusId.Value ).Name : string.Empty, campusId.HasValue ? CampusCache.Read( campusId.Value ).Name : string.Empty ); _family.CampusId = campusId; } var familyGroupTypeId = _family.GroupTypeId; familyService.Save( _family, CurrentPersonId ); // SAVE FAMILY MEMBERS int? recordStatusValueID = ddlRecordStatus.SelectedValueAsInt(); int? reasonValueId = ddlReason.SelectedValueAsInt(); var newFamilies = new List<Group>(); foreach ( var familyMember in FamilyMembers ) { var memberChanges = new List<string>(); var demographicChanges = new List<string>(); var role = familyRoles.Where( r => r.Guid.Equals( familyMember.RoleGuid ) ).FirstOrDefault(); if ( role == null ) { role = familyRoles.FirstOrDefault(); } bool isChild = role != null && role.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) ); // People added to family (new or from other family) if ( !familyMember.ExistingFamilyMember ) { var groupMember = new GroupMember(); if ( familyMember.Id == -1 ) { // added new person demographicChanges.Add( "Created" ); var person = new Person(); person.FirstName = familyMember.FirstName; History.EvaluateChange( demographicChanges, "First Name", string.Empty, person.FirstName ); person.LastName = familyMember.LastName; History.EvaluateChange( demographicChanges, "Last Name", string.Empty, person.LastName ); person.Gender = familyMember.Gender; History.EvaluateChange( demographicChanges, "Gender", null, person.Gender ); person.BirthDate = familyMember.BirthDate; History.EvaluateChange( demographicChanges, "Birth Date", null, person.BirthDate ); if ( !isChild ) { person.GivingGroupId = _family.Id; History.EvaluateChange( demographicChanges, "Giving Group", string.Empty, _family.Name ); } groupMember.Person = person; } else { // added from other family groupMember.Person = personService.Get( familyMember.Id ); } History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( groupMember.Person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) ); groupMember.Person.RecordStatusValueId = recordStatusValueID; History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( groupMember.Person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) ); groupMember.Person.RecordStatusReasonValueId = reasonValueId; groupMember.GroupId = _family.Id; if ( role != null ) { History.EvaluateChange( memberChanges, string.Format( "Role", _family.Name ), string.Empty, role.Name ); groupMember.GroupRoleId = role.Id; } if ( groupMember.Person != null ) { familyMemberService.Add( groupMember, CurrentPersonId ); familyMemberService.Save( groupMember, CurrentPersonId ); } } else { // existing family members var groupMember = familyMemberService.Queryable( "Person" ).Where( m => m.PersonId == familyMember.Id && m.Group.GroupTypeId == familyGroupTypeId && m.GroupId == _family.Id ).FirstOrDefault(); if ( groupMember != null ) { if ( familyMember.Removed ) { var newFamilyChanges = new List<string>(); newFamilyChanges.Add( "Created" ); // Family member was removed and should be created in their own new family var newFamily = new Group(); newFamily.Name = familyMember.LastName + " Family"; History.EvaluateChange( newFamilyChanges, "Name", string.Empty, newFamily.Name ); newFamily.GroupTypeId = familyGroupTypeId; if ( _family.CampusId.HasValue ) { History.EvaluateChange( newFamilyChanges, "Campus", string.Empty, CampusCache.Read( _family.CampusId.Value ).Name ); } newFamily.CampusId = _family.CampusId; familyService.Add( newFamily, CurrentPersonId ); familyService.Save( newFamily, CurrentPersonId ); historyService.SaveChanges( typeof( Group ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), newFamily.Id, newFamilyChanges, CurrentPersonId ); // If person's previous giving group was this family, set it to their new family id if ( groupMember.Person.GivingGroup != null && groupMember.Person.GivingGroupId == _family.Id ) { History.EvaluateChange( demographicChanges, "Giving Group", groupMember.Person.GivingGroup.Name, _family.Name ); groupMember.Person.GivingGroupId = newFamily.Id; } groupMember.Group = newFamily; familyMemberService.Save( groupMember, CurrentPersonId ); var newMemberChanges = new List<string>(); History.EvaluateChange( newMemberChanges, "Role", string.Empty, groupMember.GroupRole.Name ); historyService.SaveChanges( typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), groupMember.Person.Id, newMemberChanges, CurrentPersonId ); History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole.Name, string.Empty ); newFamilies.Add( newFamily ); } else { // Existing member was not remvoved if ( role != null ) { History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole != null ? groupMember.GroupRole.Name : string.Empty, role.Name ); groupMember.GroupRoleId = role.Id; History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( groupMember.Person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) ); groupMember.Person.RecordStatusValueId = recordStatusValueID; History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( groupMember.Person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) ); groupMember.Person.RecordStatusReasonValueId = reasonValueId; familyMemberService.Save( groupMember, CurrentPersonId ); } } } } // Remove anyone that was moved from another family if ( familyMember.RemoveFromOtherFamilies ) { var otherFamilies = familyMemberService.Queryable() .Where( m => m.PersonId == familyMember.Id && m.Group.GroupTypeId == familyGroupTypeId && m.GroupId != _family.Id ) .ToList(); foreach ( var otherFamilyMember in otherFamilies ) { var fm = familyMemberService.Get( otherFamilyMember.Id ); // If the person's giving group id was the family they are being removed from, update it to this new family's id if ( fm.Person.GivingGroupId == fm.GroupId ) { var person = personService.Get( fm.PersonId ); History.EvaluateChange( demographicChanges, "Giving Group", person.GivingGroup.Name, _family.Name ); person.GivingGroupId = _family.Id; personService.Save( person, CurrentPersonId ); } var oldMemberChanges = new List<string>(); History.EvaluateChange( oldMemberChanges, "Role", fm.GroupRole.Name, string.Empty ); familyMemberService.Delete( fm, CurrentPersonId ); familyMemberService.Save( fm, CurrentPersonId ); historyService.SaveChanges( typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.Person.Id, oldMemberChanges, CurrentPersonId ); var f = familyService.Queryable() .Where( g => g.Id == otherFamilyMember.GroupId && !g.Members.Any() ) .FirstOrDefault(); if ( f != null ) { var oldFamilyChanges = new List<string>(); oldFamilyChanges.Add( "Deleted" ); historyService.SaveChanges( typeof( Group ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), f.Id, oldFamilyChanges, CurrentPersonId ); familyService.Delete( f, CurrentPersonId ); familyService.Save( f, CurrentPersonId ); } } } historyService.SaveChanges( typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), familyMember.Id, demographicChanges, CurrentPersonId ); historyService.SaveChanges( typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), familyMember.Id, memberChanges, _family.Name, typeof( Group ), _family.Id, CurrentPersonId ); } // SAVE LOCATIONS var groupLocationService = new GroupLocationService(); // delete any group locations that were removed var remainingLocationIds = FamilyAddresses.Where( a => a.Id > 0 ).Select( a => a.Id ).ToList(); foreach ( var removedLocation in groupLocationService.Queryable( "GroupLocationTypeValue,Location" ) .Where( l => l.GroupId == _family.Id && !remainingLocationIds.Contains( l.Id ) ) ) { History.EvaluateChange( familyChanges, removedLocation.GroupLocationTypeValue.Name + " Location", removedLocation.Location.ToString(), string.Empty ); groupLocationService.Delete( removedLocation, CurrentPersonId ); groupLocationService.Save( removedLocation, CurrentPersonId ); } foreach ( var familyAddress in FamilyAddresses ) { Location updatedAddress = null; if ( familyAddress.LocationIsDirty ) { updatedAddress = new LocationService().Get( familyAddress.Street1, familyAddress.Street2, familyAddress.City, familyAddress.State, familyAddress.Zip ); } GroupLocation groupLocation = null; if ( familyAddress.Id > 0 ) { groupLocation = groupLocationService.Get( familyAddress.Id ); } if ( groupLocation == null ) { groupLocation = new GroupLocation(); groupLocation.GroupId = _family.Id; groupLocationService.Add( groupLocation, CurrentPersonId ); } History.EvaluateChange( familyChanges, "Location Type", groupLocation.GroupLocationTypeValueId.HasValue ? DefinedValueCache.Read( groupLocation.GroupLocationTypeValueId.Value ).Name : string.Empty, familyAddress.LocationTypeName ); groupLocation.GroupLocationTypeValueId = familyAddress.LocationTypeId; History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Location Is Mailing", groupLocation.IsMailingLocation.ToString(), familyAddress.IsMailing.ToString() ); groupLocation.IsMailingLocation = familyAddress.IsMailing; History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Location Is Location", groupLocation.IsMappedLocation.ToString(), familyAddress.IsLocation.ToString() ); groupLocation.IsMappedLocation = familyAddress.IsLocation; if ( updatedAddress != null ) { History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Location", groupLocation.Location.ToString(), updatedAddress.ToString() ); groupLocation.Location = updatedAddress; } groupLocationService.Save( groupLocation, CurrentPersonId ); // Add the same locations to any new families created by removing an existing family member if ( newFamilies.Any() ) { //reload grouplocation for access to child properties groupLocation = groupLocationService.Get( groupLocation.Id ); foreach ( var newFamily in newFamilies ) { var newFamilyLocation = new GroupLocation(); newFamilyLocation.GroupId = newFamily.Id; newFamilyLocation.LocationId = groupLocation.LocationId; newFamilyLocation.GroupLocationTypeValueId = groupLocation.GroupLocationTypeValueId; newFamilyLocation.IsMailingLocation = groupLocation.IsMailingLocation; newFamilyLocation.IsMappedLocation = groupLocation.IsMappedLocation; groupLocationService.Add( newFamilyLocation, CurrentPersonId ); groupLocationService.Save( newFamilyLocation, CurrentPersonId ); } } } historyService.SaveChanges( typeof( Group ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), _family.Id, familyChanges, CurrentPersonId ); _family = familyService.Get( _family.Id ); if ( _family.Members.Any( m => m.PersonId == Person.Id ) ) { Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false ); } else { var fm = _family.Members .Where( m => m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) && m.Person.Gender == Gender.Male ) .OrderByDescending( m => m.Person.Age ) .FirstOrDefault(); if ( fm == null ) { fm = _family.Members .Where( m => m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) ) .OrderByDescending( m => m.Person.Age ) .FirstOrDefault(); } if ( fm == null ) { fm = _family.Members .OrderByDescending( m => m.Person.Age ) .FirstOrDefault(); } if ( fm != null ) { Response.Redirect( string.Format( "~/Person/{0}", fm.PersonId ), false ); } else { Response.Redirect( "~", false ); } } } } ); } }
private Person CreatePerson() { Rock.Model.PersonService personService = new PersonService(); Person person = new Person(); person.GivenName = tbFirstName.Text; person.LastName = tbLastName.Text; person.Email = tbEmail.Text; switch(ddlGender.SelectedValue) { case "M": person.Gender = Gender.Male; break; case "F": person.Gender = Gender.Female; break; default: person.Gender = Gender.Unknown; break; } if (ddlBirthMonth.SelectedValue != "0") person.BirthMonth = Int32.Parse(ddlBirthMonth.SelectedValue); if (ddlBirthDay.SelectedValue != "0") person.BirthDay = Int32.Parse(ddlBirthDay.SelectedValue); if (ddlBirthYear.SelectedValue != "0") person.BirthYear = Int32.Parse(ddlBirthYear.SelectedValue); personService.Add(person, CurrentPersonId); personService.Save(person, CurrentPersonId); return person; }
/// <summary> /// Authenticates the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="username">The username.</param> /// <param name="returnUrl">The return URL.</param> /// <returns></returns> public override Boolean Authenticate( HttpRequest request, out string username, out string returnUrl ) { var fbClient = new FacebookClient(); FacebookOAuthResult oAuthResult; if ( fbClient.TryParseOAuthCallbackUrl( request.Url, out oAuthResult ) && oAuthResult.IsSuccess ) { try { var redirectUri = new Uri( GetRedirectUrl( request ) ); dynamic parameters = new ExpandoObject(); parameters.client_id = GetAttributeValue( "AppID" ); parameters.client_secret = GetAttributeValue( "AppSecret" ); parameters.redirect_uri = redirectUri.AbsoluteUri; parameters.code = oAuthResult.Code; dynamic result = fbClient.Post( "oauth/access_token", parameters ); string accessToken = result.access_token; fbClient = new FacebookClient( accessToken ); dynamic me = fbClient.Get( "me" ); string facebookId = "FACEBOOK_" + me.id.ToString(); // query for matching id in the user table var userLoginService = new UserLoginService(); var user = userLoginService.GetByUserName( facebookId ); // if not user was found see if we can find a match in the person table if ( user == null ) { try { // determine if we can find a match and if so add an user login record // get properties from Facebook dynamic object string lastName = me.last_name.ToString(); string firstName = me.first_name.ToString(); string email = me.email.ToString(); var personService = new PersonService(); var person = personService.Queryable().FirstOrDefault( u => u.LastName == lastName && u.FirstName == firstName && u.Email == email ); if ( person != null ) { // since we have the data enter the birthday from Facebook to the db if we don't have it yet DateTime birthdate = Convert.ToDateTime( me.birthday.ToString() ); if ( person.BirthDay == null ) { person.BirthDate = birthdate; personService.Save( person, person.Id ); } } else { var dvService = new DefinedValueService(); person = new Person(); person.IsSystem = false; person.RecordTypeValueId = dvService.GetIdByGuid( new Guid( SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON ) ); person.RecordStatusValueId = dvService.GetIdByGuid( new Guid( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE ) ); person.FirstName = me.first_name.ToString(); person.LastName = me.last_name.ToString(); person.Email = me.email.ToString(); if ( me.gender.ToString() == "male" ) person.Gender = Gender.Male; else if ( me.gender.ToString() == "female" ) person.Gender = Gender.Female; else person.Gender = Gender.Unknown; person.BirthDate = Convert.ToDateTime( me.birthday.ToString() ); person.DoNotEmail = false; personService.Add( person, null ); personService.Save( person, null ); } user = userLoginService.Create( person, AuthenticationServiceType.External, this.TypeId, facebookId, "fb", true, person.Id ); } catch ( Exception ex ) { string msg = ex.Message; // TODO: probably should report something... } // TODO: Show label indicating inability to find user corresponding to facebook id } username = user.UserName; returnUrl = oAuthResult.State; return true; } catch ( FacebookOAuthException oae ) { string msg = oae.Message; // TODO: Add error handeling // Error validating verification code. (usually from wrong return url very picky with formatting) // Error validating client secret. // Error validating application. } } username = null; returnUrl = null; return false; }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { using ( new Rock.Data.UnitOfWorkScope() ) { Rock.Data.RockTransactionScope.WrapTransaction( () => { var personService = new PersonService(); var changes = new List<string>(); var person = personService.Get( Person.Id ); int? orphanedPhotoId = null; if ( person.PhotoId != imgPhoto.BinaryFileId ) { orphanedPhotoId = person.PhotoId; person.PhotoId = imgPhoto.BinaryFileId; if ( orphanedPhotoId.HasValue ) { if ( person.PhotoId.HasValue ) { changes.Add( "Modified the photo." ); } else { changes.Add( "Deleted the photo." ); } } else if ( person.PhotoId.HasValue ) { changes.Add( "Added a photo." ); } } int? newTitleId = ddlTitle.SelectedValueAsInt(); History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) ); person.TitleValueId = newTitleId; History.EvaluateChange( changes, "First Name", person.FirstName, tbFirstName.Text ); person.FirstName = tbFirstName.Text; string nickName = string.IsNullOrWhiteSpace( tbNickName.Text ) ? tbFirstName.Text : tbNickName.Text; History.EvaluateChange( changes, "Nick Name", person.NickName, nickName ); person.NickName = tbNickName.Text; History.EvaluateChange( changes, "Middle Name", person.MiddleName, tbMiddleName.Text ); person.MiddleName = tbMiddleName.Text; History.EvaluateChange( changes, "Last Name", person.LastName, tbLastName.Text ); person.LastName = tbLastName.Text; int? newSuffixId = ddlSuffix.SelectedValueAsInt(); History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) ); person.SuffixValueId = newSuffixId; var birthMonth = person.BirthMonth; var birthDay = person.BirthDay; var birthYear = person.BirthYear; var birthday = bpBirthDay.SelectedDate; if ( birthday.HasValue ) { person.BirthMonth = birthday.Value.Month; person.BirthDay = birthday.Value.Day; if ( birthday.Value.Year != DateTime.MinValue.Year ) { person.BirthYear = birthday.Value.Year; } else { person.BirthYear = null; } } else { person.BirthDate = null; } History.EvaluateChange( changes, "Birth Month", birthMonth, person.BirthMonth ); History.EvaluateChange( changes, "Birth Day", birthDay, person.BirthDay ); History.EvaluateChange( changes, "Birth Year", birthYear, person.BirthYear ); History.EvaluateChange( changes, "Anniversary Date", person.AnniversaryDate, dpAnniversaryDate.SelectedDate ); person.AnniversaryDate = dpAnniversaryDate.SelectedDate; var newGender = rblGender.SelectedValue.ConvertToEnum<Gender>(); History.EvaluateChange( changes, "Gender", person.Gender, newGender ); person.Gender = newGender; int? newMaritalStatusId = rblMaritalStatus.SelectedValueAsInt(); History.EvaluateChange( changes, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) ); person.MaritalStatusValueId = newMaritalStatusId; int? newConnectionStatusId = rblStatus.SelectedValueAsInt(); History.EvaluateChange( changes, "Connection Status", DefinedValueCache.GetName( person.ConnectionStatusValueId ), DefinedValueCache.GetName( newConnectionStatusId ) ); person.ConnectionStatusValueId = newConnectionStatusId; var phoneNumberTypeIds = new List<int>(); foreach ( RepeaterItem item in rContactInfo.Items ) { HiddenField hfPhoneType = item.FindControl( "hfPhoneType" ) as HiddenField; TextBox tbPhone = item.FindControl( "tbPhone" ) as TextBox; CheckBox cbUnlisted = item.FindControl( "cbUnlisted" ) as CheckBox; CheckBox cbSms = item.FindControl( "cbSms" ) as CheckBox; if ( hfPhoneType != null && tbPhone != null && cbSms != null && cbUnlisted != null ) { if ( !string.IsNullOrWhiteSpace( tbPhone.Text ) ) { int phoneNumberTypeId; if ( int.TryParse( hfPhoneType.Value, out phoneNumberTypeId ) ) { var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberTypeId ); string oldPhoneNumber = string.Empty; if ( phoneNumber == null ) { phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId }; person.PhoneNumbers.Add( phoneNumber ); } else { oldPhoneNumber = phoneNumber.NumberFormatted; } phoneNumber.Number = PhoneNumber.CleanNumber( tbPhone.Text ); phoneNumber.IsMessagingEnabled = cbSms.Checked; phoneNumber.IsUnlisted = cbUnlisted.Checked; phoneNumberTypeIds.Add( phoneNumberTypeId ); History.EvaluateChange( changes, string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumberTypeId ) ), oldPhoneNumber, phoneNumber.NumberFormatted ); } } } } // Remove any blank numbers var phoneNumberService = new PhoneNumberService(); foreach ( var phoneNumber in person.PhoneNumbers .Where( n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains( n.NumberTypeValueId.Value ) ) .ToList() ) { History.EvaluateChange( changes, string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumber.NumberTypeValueId ) ), phoneNumber.NumberFormatted, string.Empty ); person.PhoneNumbers.Remove( phoneNumber ); phoneNumberService.Delete( phoneNumber, CurrentPersonId ); } History.EvaluateChange( changes, "Email", person.Email, tbEmail.Text ); person.Email = tbEmail.Text.Trim(); int? newGivingGroupId = ddlGivingGroup.SelectedValueAsId(); if ( person.GivingGroupId != newGivingGroupId ) { string oldGivingGroupName = person.GivingGroup != null ? person.GivingGroup.Name : string.Empty; string newGivingGroupName = newGivingGroupId.HasValue ? ddlGivingGroup.Items.FindByValue( newGivingGroupId.Value.ToString() ).Text : string.Empty; History.EvaluateChange( changes, "Giving Group", oldGivingGroupName, newGivingGroupName ); } int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt(); History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( person.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) ); person.RecordStatusValueId = newRecordStatusId; int? newRecordStatusReasonId = ddlReason.SelectedValueAsInt(); History.EvaluateChange( changes, "Record Status Reason", DefinedValueCache.GetName( person.RecordStatusReasonValueId ), DefinedValueCache.GetName( newRecordStatusReasonId ) ); person.RecordStatusReasonValueId = newRecordStatusReasonId; if ( !person.IsValid ) { return; } if ( personService.Save( person, CurrentPersonId ) ) { if ( changes.Any() ) { new HistoryService().SaveChanges( typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), Person.Id, changes, CurrentPersonId ); } if ( orphanedPhotoId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( personService.RockContext ); var binaryFile = binaryFileService.Get( orphanedPhotoId.Value ); if ( binaryFile != null ) { // marked the old images as IsTemporary so they will get cleaned up later binaryFile.IsTemporary = true; binaryFileService.Save( binaryFile, CurrentPersonId ); } } } } ); } Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false ); }
#pragma warning restore #endregion #region Methods /// <summary> /// Transforms the data from the dataset. /// </summary> public override int TransformData( string importUser = null ) { // Report progress to the main thread so it can update the UI ReportProgress( 0, "Starting import..." ); // Connects to the source database (already loaded in memory by the UI) var scanner = new DataScanner( database ); // List of tables the user would like to import var tableList = TableNodes.Where( n => n.Checked != false ).Select( n => n.Name ).ToList(); // Supplies a lazy-loaded database queryable var tableData = scanner.ScanTable( "TableName" ).AsQueryable(); // Hold a count of how many records have been imported int completed = 0; // Pick a method to save data to Rock: #1 (simple) or #2 (fast) // Option #1. Standard way to put data in Rock foreach ( var dataRow in tableData ) { // Get a value from the row. This has to be a nullable type. string columnValue = dataRow["ColumnName"] as string; // Create a Rock model and assign data to it Person person = new Person(); person.LastName = columnValue; RockTransactionScope.WrapTransaction( () => { // Instantiate the object model service var personService = new PersonService(); // If it's a new model, add it to the database first personService.Add( person, ImportPersonAlias ); // Save the data to the database personService.Save( person, ImportPersonAlias ); } ); completed++; } // end option #1 // Option #2. More efficient way to import large data sets var newPersonList = new List<Person>(); foreach ( var dataRow in tableData ) { // Get a value from the row. This has to be a nullable type. string columnValue = dataRow["ColumnName"] as string; // Create a Rock model and assign data to it Person person = new Person(); newPersonList.Add( new Person() ); completed++; // Save 100 people at a time if ( completed % 100 < 1 ) { RockTransactionScope.WrapTransaction( () => { var personService = new PersonService(); personService.RockContext.People.AddRange( newPersonList ); personService.RockContext.SaveChanges(); } ); } } // Outside foreach, save any that haven't been saved yet if ( newPersonList.Any() ) { RockTransactionScope.WrapTransaction( () => { var personService = new PersonService(); personService.RockContext.People.AddRange( newPersonList ); personService.RockContext.SaveChanges(); } ); } // end option #2 // Report the final imported count ReportProgress( 100, string.Format( "Completed import: {0:N0} records imported.", completed ) ); return completed; }
/// <summary> /// Adds a new person. /// </summary> /// <param name="firstName">The first name.</param> /// <param name="lastName">The last name.</param> /// <param name="DOB">The DOB.</param> /// <param name="gender">The gender</param> /// <param name="attribute">The attribute.</param> protected Person CreatePerson( string firstName, string lastName, DateTime? dob, int? gender, string ability, string abilityGroup ) { Person person = new Person().Clone( false ); person.FirstName = firstName; person.LastName = lastName; person.BirthDate = dob; if ( gender != null ) { person.Gender = (Gender)gender; } PersonService ps = new PersonService(); Rock.Data.RockTransactionScope.WrapTransaction( () => { ps.Add( person, CurrentPersonId ); ps.Save( person, CurrentPersonId ); } ); if ( !string.IsNullOrWhiteSpace( ability ) ) { if ( abilityGroup == "Grade" ) { person.Grade = (int)ability.ConvertToEnum<GradeLevel>(); ps.Save( person, CurrentPersonId ); } else if ( abilityGroup == "Ability" ) { Person p = new PersonService().Get( person.Id ); if ( p != null ) { p.LoadAttributes(); p.SetAttributeValue( "AbilityLevel", ability ); Rock.Attribute.Helper.SaveAttributeValues( p, CurrentPersonId ); } } } return person; }
protected void btnNext_Click( object sender, EventArgs e ) { if ( Page.IsValid ) { if ( CurrentCategoryIndex < attributeControls.Count ) { CurrentCategoryIndex++; ShowAttributeCategory( CurrentCategoryIndex ); } else { var familyMembers = GetControlData(); if ( familyMembers.Any() ) { RockTransactionScope.WrapTransaction( () => { using ( new UnitOfWorkScope() ) { var familyGroupType = GroupTypeCache.GetFamilyGroupType(); var familyChanges = new List<string>(); var familyMemberChanges = new Dictionary<Guid, List<string>>(); var familyDemographicChanges = new Dictionary<Guid, List<string>>(); if ( familyGroupType != null ) { var groupService = new GroupService(); var groupTypeRoleService = new GroupTypeRoleService(); var familyGroup = new Group(); familyGroup.GroupTypeId = familyGroupType.Id; familyChanges.Add("Created"); familyGroup.Name = familyMembers.FirstOrDefault().Person.LastName + " Family"; History.EvaluateChange( familyChanges, "Name", string.Empty, familyGroup.Name ); int? campusId = cpCampus.SelectedValueAsInt(); if (campusId.HasValue) { History.EvaluateChange( familyChanges, "Campus", string.Empty, CampusCache.Read( campusId.Value ).Name ); } familyGroup.CampusId = campusId; foreach(var familyMember in familyMembers) { var person = familyMember.Person; if ( person != null ) { familyGroup.Members.Add( familyMember ); var demographicChanges = new List<string>(); demographicChanges.Add( "Created" ); History.EvaluateChange( demographicChanges, "Record Status", string.Empty, person.RecordStatusReasonValueId.HasValue ? DefinedValueCache.GetName( person.RecordStatusReasonValueId.Value ) : string.Empty ); History.EvaluateChange( demographicChanges, "Title", string.Empty, person.TitleValueId.HasValue ? DefinedValueCache.GetName( person.TitleValueId ) : string.Empty ); History.EvaluateChange( demographicChanges, "First Name", string.Empty, person.FirstName); History.EvaluateChange( demographicChanges, "Nick Name", string.Empty, person.NickName ); History.EvaluateChange( demographicChanges, "Middle Name", string.Empty, person.MiddleName ); History.EvaluateChange( demographicChanges, "Last Name", string.Empty, person.LastName ); History.EvaluateChange( demographicChanges, "Gender", null, person.Gender ); History.EvaluateChange( demographicChanges, "Birth Date", null, person.BirthDate ); History.EvaluateChange( demographicChanges, "Connection Status", string.Empty, person.ConnectionStatusValueId.HasValue ? DefinedValueCache.GetName( person.ConnectionStatusValueId ) : string.Empty ); History.EvaluateChange( demographicChanges, "Graduation Date", null, person.GraduationDate ); familyDemographicChanges.Add( person.Guid, demographicChanges ); var memberChanges = new List<string>(); string roleName = familyGroupType.Roles[familyMember.GroupRoleId] ?? string.Empty; History.EvaluateChange( memberChanges, "Role", string.Empty, roleName ); familyMemberChanges.Add( person.Guid, memberChanges ); } } if ( !String.IsNullOrWhiteSpace( tbStreet1.Text ) || !String.IsNullOrWhiteSpace( tbStreet2.Text ) || !String.IsNullOrWhiteSpace( tbCity.Text ) || !String.IsNullOrWhiteSpace( tbZip.Text ) ) { string addressChangeField = "Address"; var groupLocation = new GroupLocation(); var location = new LocationService().Get( tbStreet1.Text, tbStreet2.Text, tbCity.Text, ddlState.SelectedValue, tbZip.Text ); groupLocation.Location = location; Guid locationTypeGuid = Guid.Empty; if ( Guid.TryParse( GetAttributeValue( "LocationType" ), out locationTypeGuid ) ) { var locationType = Rock.Web.Cache.DefinedValueCache.Read( locationTypeGuid ); if ( locationType != null ) { addressChangeField = string.Format("{0} Address", locationType.Name); groupLocation.GroupLocationTypeValueId = locationType.Id; } } familyGroup.GroupLocations.Add( groupLocation ); History.EvaluateChange( familyChanges, addressChangeField, string.Empty, groupLocation.Location.ToString() ); } groupService.Add( familyGroup, CurrentPersonId ); groupService.Save( familyGroup, CurrentPersonId ); var historyService = new HistoryService(); historyService.SaveChanges( typeof( Group ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), familyGroup.Id, familyChanges, CurrentPersonId ); var personService = new PersonService(); foreach ( var groupMember in familyMembers ) { var person = personService.Get( groupMember.PersonId ); if ( person != null ) { var changes = familyDemographicChanges[person.Guid]; if ( groupMember.GroupRoleId != _childRoleId ) { person.GivingGroupId = familyGroup.Id; personService.Save( person, CurrentPersonId ); History.EvaluateChange( changes, "Giving Group", string.Empty, familyGroup.Name ); } foreach ( var attributeControl in attributeControls ) { foreach ( var attribute in attributeControl.AttributeList ) { string attributeValue = person.GetAttributeValue( attribute.Key ); if ( !string.IsNullOrWhiteSpace( attributeValue ) ) { Rock.Attribute.Helper.SaveAttributeValue( person, attribute, attributeValue, CurrentPersonId ); attributeValue = attribute.FieldType.Field.FormatValue( null, attributeValue, attribute.QualifierValues, false ); History.EvaluateChange( changes, attribute.Name, string.Empty, attributeValue ); } } } historyService.SaveChanges( typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes, CurrentPersonId ); historyService.SaveChanges( typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), person.Id, familyMemberChanges[person.Guid], familyGroup.Name, typeof( Group), familyGroup.Id, CurrentPersonId ); } } } } } ); Response.Redirect( string.Format( "~/Person/{0}", familyMembers[0].Person.Id ), false ); } } } }