protected void Page_Load(object sender, EventArgs e) { //Set the person picker to the currently logged in person. PersonService personService = new PersonService(rockContext); var personObject = personService.Get(CurrentPerson.Guid); //Get the person from the URL string qsPersonId = PageParameter("PersonId"); int iPersonId = Int32.Parse(qsPersonId); var thePerson = personService.Get(iPersonId); //Get the URL encoded key from the person object var urlEncodedKey = thePerson.UrlEncodedKey; PageViewHistoryUrl = ResolveUrl("~/page/279?Person=" + urlEncodedKey); }
public void DeleteKnownRelationship( int personId, int relatedPersonId, int relationshipRoleId ) { SetProxyCreation( true ); var rockContext = this.Service.Context as RockContext; var personService = new PersonService( rockContext ); var person = personService.Get( personId ); var relatedPerson = personService.Get( relatedPersonId ); CheckCanEdit( person ); CheckCanEdit( relatedPerson ); System.Web.HttpContext.Current.Items.Add( "CurrentPerson", GetPerson() ); var groupMemberService = new GroupMemberService( rockContext ); groupMemberService.DeleteKnownRelationship( personId, relatedPersonId, relationshipRoleId ); }
public System.Net.Http.HttpResponseMessage CreateKnownRelationship( int personId, int relatedPersonId, int relationshipRoleId ) { SetProxyCreation( true ); var rockContext = this.Service.Context as RockContext; var personService = new PersonService(rockContext); var person = personService.Get(personId); var relatedPerson = personService.Get(relatedPersonId); CheckCanEdit( person ); CheckCanEdit( relatedPerson ); System.Web.HttpContext.Current.Items.Add( "CurrentPerson", GetPerson() ); var groupMemberService = new GroupMemberService(rockContext); groupMemberService.CreateKnownRelationship( personId, relatedPersonId, relationshipRoleId ); return ControllerContext.Request.CreateResponse( HttpStatusCode.Created ); }
/// <summary> /// Handles the Click event of the btnSubmit 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 btnSubmit_Click( object sender, EventArgs e ) { if (_person != null) { var rockContext = new RockContext(); var service = new PersonService( rockContext ); var person = service.Get(_person.Id); if ( person != null ) { switch ( rblEmailPreference.SelectedValue ) { case "0": { person.EmailPreference = EmailPreference.EmailAllowed; break; } case "1": { person.EmailPreference = EmailPreference.NoMassEmails; break; } case "2": case "3": { person.EmailPreference = EmailPreference.DoNotEmail; break; } } if (rblEmailPreference.SelectedValue == "3") { person.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ).Id; person.RecordStatusReasonValueId = ddlInactiveReason.SelectedValue.AsInteger().Value; person.ReviewReasonValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_REVIEW_REASON_SELF_INACTIVATED ).Id; if ( string.IsNullOrWhiteSpace( person.ReviewReasonNote ) ) { person.ReviewReasonNote = tbInactiveNote.Text; } else { person.ReviewReasonNote += " " + tbInactiveNote.Text; } } else { person.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE ).Id; person.RecordStatusReasonValueId = null; } rockContext.SaveChanges(); nbMessage.Visible = true; return; } } }
/// <summary> /// Handles the Delete event of the gBusinessList control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param> protected void gBusinessList_Delete( object sender, Rock.Web.UI.Controls.RowEventArgs e ) { var rockContext = new RockContext(); PersonService service = new PersonService( rockContext ); Person business = service.Get( e.RowKeyId ); if ( business != null ) { business.RecordStatusValueId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id; rockContext.SaveChanges(); } BindGrid(); }
private void BindGrid() { var HtmlService = new HtmlContentService(); var content = HtmlService.GetContent(CurrentBlock.Id, EntityValue()); var personService = new Rock.Model.PersonService(); var versionAudits = new Dictionary <int, Rock.Model.Audit>(); var modifiedPersons = new Dictionary <int, string>(); foreach (var version in content) { var lastAudit = HtmlService.Audits(version) .Where(a => a.AuditType == Rock.Model.AuditType.Add || a.AuditType == Rock.Model.AuditType.Modify) .OrderByDescending(h => h.DateTime) .FirstOrDefault(); if (lastAudit != null) { versionAudits.Add(version.Id, lastAudit); } } foreach (var audit in versionAudits.Values) { if (audit.PersonId.HasValue && !modifiedPersons.ContainsKey(audit.PersonId.Value)) { var modifiedPerson = personService.Get(audit.PersonId.Value, true); modifiedPersons.Add(audit.PersonId.Value, modifiedPerson != null ? modifiedPerson.FullName : string.Empty); } } var versions = content. Select(v => new { v.Id, v.Version, v.Content, ModifiedDateTime = versionAudits.ContainsKey(v.Id) ? versionAudits[v.Id].DateTime.ToElapsedString() : string.Empty, ModifiedByPerson = versionAudits.ContainsKey(v.Id) && versionAudits[v.Id].PersonId.HasValue ? modifiedPersons[versionAudits[v.Id].PersonId.Value] : string.Empty, Approved = v.IsApproved, ApprovedByPerson = v.ApprovedByPerson != null ? v.ApprovedByPerson.FullName : "", v.StartDateTime, v.ExpireDateTime }).ToList(); rGrid.DataSource = versions; rGrid.DataBind(); }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue( System.Web.UI.Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed ) { string formattedValue = string.Empty; if ( !string.IsNullOrWhiteSpace( value ) ) { var service = new PersonService(); var person = service.Get( new Guid( value ) ); if ( person != null ) { formattedValue = person.FullName; } } return base.FormatValue( parentControl, formattedValue, null, condensed ); }
/// <summary> /// Handles the Delete event of the gRestKeyList 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 gRestKeyList_Delete( object sender, RowEventArgs e ) { var rockContext = new RockContext(); var personService = new PersonService( rockContext ); var userLoginService = new UserLoginService( rockContext ); var restUser = personService.Get( e.RowKeyId ); if ( restUser != null ) { restUser.RecordStatusValueId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id; // remove all user logins for key foreach ( var login in restUser.Users.ToList() ) { userLoginService.Delete( login ); } rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Saves the new family. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="familyMembers">The family members.</param> /// <param name="campusId">The campus identifier.</param> /// <param name="savePersonAttributes">if set to <c>true</c> [save person attributes].</param> /// <returns></returns> public static Group SaveNewFamily(RockContext rockContext, List <GroupMember> familyMembers, int?campusId, bool savePersonAttributes) { 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(rockContext); var familyGroup = new Group(); familyGroup.GroupTypeId = familyGroupType.Id; familyGroup.Name = familyMembers.FirstOrDefault().Person.LastName + " Family"; History.EvaluateChange(familyChanges, "Family", string.Empty, familyGroup.Name); if (campusId.HasValue) { History.EvaluateChange(familyChanges, "Campus", string.Empty, CampusCache.Read(campusId.Value).Name); } familyGroup.CampusId = campusId; int?childRoleId = null; var childRole = new GroupTypeRoleService(rockContext).Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD)); if (childRole != null) { childRoleId = childRole.Id; } 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 Type", string.Empty, person.RecordTypeValueId.HasValue ? DefinedValueCache.GetName(person.RecordTypeValueId.Value) : string.Empty); History.EvaluateChange(demographicChanges, "Record Status", string.Empty, person.RecordStatusValueId.HasValue ? DefinedValueCache.GetName(person.RecordStatusValueId.Value) : string.Empty); History.EvaluateChange(demographicChanges, "Record Status Reason", string.Empty, person.RecordStatusReasonValueId.HasValue ? DefinedValueCache.GetName(person.RecordStatusReasonValueId.Value) : string.Empty); History.EvaluateChange(demographicChanges, "Connection Status", string.Empty, person.ConnectionStatusValueId.HasValue ? DefinedValueCache.GetName(person.ConnectionStatusValueId) : string.Empty); History.EvaluateChange(demographicChanges, "Deceased", false.ToString(), (person.IsDeceased).ToString()); 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, "Suffix", string.Empty, person.SuffixValueId.HasValue ? DefinedValueCache.GetName(person.SuffixValueId) : string.Empty); History.EvaluateChange(demographicChanges, "Birth Date", null, person.BirthDate); History.EvaluateChange(demographicChanges, "Gender", null, person.Gender); History.EvaluateChange(demographicChanges, "Marital Status", string.Empty, person.MaritalStatusValueId.HasValue ? DefinedValueCache.GetName(person.MaritalStatusValueId) : string.Empty); History.EvaluateChange(demographicChanges, "Anniversary Date", null, person.AnniversaryDate); History.EvaluateChange(demographicChanges, "Graduation Year", null, person.GraduationYear); History.EvaluateChange(demographicChanges, "Email", string.Empty, person.Email); History.EvaluateChange(demographicChanges, "Email Active", false.ToString(), person.IsEmailActive.ToString()); History.EvaluateChange(demographicChanges, "Email Note", string.Empty, person.EmailNote); History.EvaluateChange(demographicChanges, "Email Preference", null, person.EmailPreference); History.EvaluateChange(demographicChanges, "Inactive Reason Note", string.Empty, person.InactiveReasonNote); History.EvaluateChange(demographicChanges, "System Note", string.Empty, person.SystemNote); familyDemographicChanges.Add(person.Guid, demographicChanges); var memberChanges = new List <string>(); string roleName = familyGroupType.Roles .Where(r => r.Id == familyMember.GroupRoleId) .Select(r => r.Name) .FirstOrDefault(); History.EvaluateChange(memberChanges, "Role", string.Empty, roleName); familyMemberChanges.Add(person.Guid, memberChanges); } } groupService.Add(familyGroup); rockContext.SaveChanges(); var personService = new PersonService(rockContext); foreach (var groupMember in familyMembers) { var person = groupMember.Person; if (savePersonAttributes) { var newValues = person.AttributeValues; person.LoadAttributes(); foreach (var attributeCache in person.Attributes.Select(a => a.Value)) { string oldValue = person.GetAttributeValue(attributeCache.Key) ?? string.Empty; string newValue = string.Empty; if (newValues != null && newValues.ContainsKey(attributeCache.Key) && newValues[attributeCache.Key] != null) { newValue = newValues[attributeCache.Key].Value ?? string.Empty; } if (!oldValue.Equals(newValue)) { History.EvaluateChange(familyDemographicChanges[person.Guid], attributeCache.Name, attributeCache.FieldType.Field.FormatValue(null, oldValue, attributeCache.QualifierValues, false), attributeCache.FieldType.Field.FormatValue(null, newValue, attributeCache.QualifierValues, false)); Rock.Attribute.Helper.SaveAttributeValue(person, attributeCache, newValue); } } } person = personService.Get(groupMember.PersonId); if (person != null) { bool updateRequired = false; var changes = familyDemographicChanges[person.Guid]; if (groupMember.GroupRoleId != childRoleId) { person.GivingGroupId = familyGroup.Id; updateRequired = true; History.EvaluateChange(changes, "Giving Group", string.Empty, familyGroup.Name); } if (updateRequired) { rockContext.SaveChanges(); } HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes); HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), person.Id, familyMemberChanges[person.Guid], familyGroup.Name, typeof(Group), familyGroup.Id); HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), person.Id, familyChanges, familyGroup.Name, typeof(Group), familyGroup.Id); } } return(familyGroup); } return(null); }
/// <summary> /// Displays the success. /// </summary> /// <param name="user">The user.</param> private void DisplaySuccess( Rock.Model.UserLogin user ) { FormsAuthentication.SignOut(); Rock.Security.Authorization.SetAuthCookie( tbUserName.Text, false, false ); if ( user != null && user.PersonId.HasValue ) { PersonService personService = new PersonService( new RockContext() ); Person person = personService.Get( user.PersonId.Value ); if ( person != null ) { try { 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 personDictionary = person.ToLiquid() as Dictionary<string, object>; mergeObjects.Add( "Person", personDictionary ); mergeObjects.Add( "User", user ); var recipients = new Dictionary<string, Dictionary<string, object>>(); recipients.Add( person.Email, mergeObjects ); Email.Send( GetAttributeValue( "AccountCreatedTemplate" ).AsGuid(), recipients, ResolveRockUrl( "~/" ), ResolveRockUrl( "~~/" ) ); } catch ( SystemException ex ) { ExceptionLogService.LogException( ex, Context, RockPage.PageId, RockPage.Site.Id, CurrentPersonAlias ); } string returnUrl = Request.QueryString["returnurl"]; btnContinue.Visible = !string.IsNullOrWhiteSpace( returnUrl ); lSuccessCaption.Text = GetAttributeValue( "SuccessCaption" ); if ( lSuccessCaption.Text.Contains( "{0}" ) ) { lSuccessCaption.Text = string.Format( lSuccessCaption.Text, person.FirstName ); } ShowPanel( 5 ); } else { ShowErrorMessage( "Invalid Person" ); } } else { ShowErrorMessage( "Invalid User" ); } }
/// <summary> /// Displays the send login. /// </summary> /// <param name="personId">The person identifier.</param> /// <param name="direction">The direction.</param> private void DisplaySendLogin( int personId, Direction direction ) { hfSendPersonId.Value = personId.ToString(); lExistingAccountCaption.Text = GetAttributeValue( "ExistingAccountCaption" ); if ( lExistingAccountCaption.Text.Contains( "{0}" ) ) { PersonService personService = new PersonService( new RockContext() ); Person person = personService.Get( personId ); if ( person != null ) { lExistingAccountCaption.Text = string.Format( lExistingAccountCaption.Text, person.FirstName ); } } ShowPanel( 2 ); }
/// <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( () => { var rockContext = new RockContext(); var familyService = new GroupService( rockContext ); var familyMemberService = new GroupMemberService( rockContext ); var personService = new PersonService( rockContext ); var historyService = new HistoryService( rockContext ); var familyChanges = new List<string>(); // SAVE FAMILY _family = familyService.Get( _family.Id ); History.EvaluateChange( familyChanges, "Family 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; rockContext.SaveChanges(); // 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; person.NickName = familyMember.NickName; 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 ); } person.EmailPreference = EmailPreference.EmailAllowed; groupMember.Person = person; } else { // added from other family groupMember.Person = personService.Get( familyMember.Id ); } if ( recordStatusValueID > 0 ) { 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, "Role", string.Empty, role.Name ); groupMember.GroupRoleId = role.Id; } if ( groupMember.Person != null ) { familyMemberService.Add( groupMember ); rockContext.SaveChanges(); familyMember.Id = groupMember.Person.Id; } } 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>(); // 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, "Family", 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 ); rockContext.SaveChanges(); // 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; rockContext.SaveChanges(); var newMemberChanges = new List<string>(); History.EvaluateChange( newMemberChanges, "Role", string.Empty, groupMember.GroupRole.Name ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), groupMember.Person.Id, newFamilyChanges, newFamily.Name, typeof( Group ), newFamily.Id ); newFamilies.Add( newFamily ); History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole.Name, string.Empty ); } 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; if ( recordStatusValueID > 0 ) { 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; } rockContext.SaveChanges(); } } } } // 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; rockContext.SaveChanges(); } var oldMemberChanges = new List<string>(); History.EvaluateChange( oldMemberChanges, "Role", fm.GroupRole.Name, string.Empty ); History.EvaluateChange( oldMemberChanges, "Family", fm.Group.Name, string.Empty ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.Person.Id, oldMemberChanges, fm.Group.Name, typeof( Group ), fm.Group.Id ); familyMemberService.Delete( fm ); rockContext.SaveChanges(); var f = familyService.Queryable() .Where( g => g.Id == otherFamilyMember.GroupId && !g.Members.Any() ) .FirstOrDefault(); if ( f != null ) { familyService.Delete( f ); rockContext.SaveChanges(); } } } HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), familyMember.Id, demographicChanges ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), familyMember.Id, memberChanges, _family.Name, typeof( Group ), _family.Id ); } // SAVE LOCATIONS var groupLocationService = new GroupLocationService( rockContext ); // 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 ); } rockContext.SaveChanges(); foreach ( var familyAddress in FamilyAddresses ) { Location updatedAddress = null; if ( familyAddress.LocationIsDirty ) { updatedAddress = new LocationService( rockContext ).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 ); } 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 + " Is Mailing", groupLocation.IsMailingLocation.ToString(), familyAddress.IsMailing.ToString() ); groupLocation.IsMailingLocation = familyAddress.IsMailing; History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Is Map Location", groupLocation.IsMappedLocation.ToString(), familyAddress.IsLocation.ToString() ); groupLocation.IsMappedLocation = familyAddress.IsLocation; if ( updatedAddress != null ) { History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Location", groupLocation.Location != null ? groupLocation.Location.ToString() : "", updatedAddress.ToString() ); groupLocation.Location = updatedAddress; } rockContext.SaveChanges(); // 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 ); } rockContext.SaveChanges(); } } foreach ( var fm in _family.Members ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.PersonId, familyChanges, _family.Name, typeof( Group ), _family.Id ); } _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 void ShowBusiness() { int? businessId = cblBusiness.SelectedValueAsInt(); if ( businessId.HasValue ) { using ( var rockContext = new RockContext() ) { var personService = new PersonService( rockContext ); var business = personService.Get( businessId.Value ); ShowBusiness( personService, business ); } } else { ShowBusiness( null, null ); } }
/// <summary> /// Gets the person. /// </summary> /// <param name="create">if set to <c>true</c> [create].</param> /// <returns></returns> private Person GetPerson( bool create ) { Person person = null; var rockContext = new RockContext(); var personService = new PersonService( rockContext ); Group familyGroup = null; int personId = ViewState["PersonId"] as int? ?? 0; if ( personId == 0 && _targetPerson != null ) { personId = _targetPerson.Id; } if ( personId != 0 ) { person = personService.Get( personId ); } if ( create && ( !phGiveAsOption.Visible || tglGiveAsOption.Checked ) ) // If tglGiveOption is not checked, then person should not be null { if ( person == null ) { // Check to see if there's only one person with same email, first name, and last name if ( !string.IsNullOrWhiteSpace( txtEmail.Text ) && !string.IsNullOrWhiteSpace( txtFirstName.Text ) && !string.IsNullOrWhiteSpace( txtLastName.Text ) ) { // Same logic as CreatePledge.ascx.cs var personMatches = personService.GetByMatch( txtFirstName.Text, txtLastName.Text, txtEmail.Text ); if ( personMatches.Count() == 1 ) { person = personMatches.FirstOrDefault(); } else { person = null; } } if ( person == null ) { DefinedValueCache dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() ); DefinedValueCache dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() ); // Create Person person = new Person(); person.FirstName = txtFirstName.Text; person.LastName = txtLastName.Text; person.IsEmailActive = true; person.EmailPreference = EmailPreference.EmailAllowed; person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id; if ( dvcConnectionStatus != null ) { person.ConnectionStatusValueId = dvcConnectionStatus.Id; } if ( dvcRecordStatus != null ) { person.RecordStatusValueId = dvcRecordStatus.Id; } // Create Person/Family familyGroup = PersonService.SaveNewPerson( person, rockContext, null, false ); } ViewState["PersonId"] = person != null ? person.Id : 0; } } if ( create && person != null ) // person should never be null at this point { person.Email = txtEmail.Text; if ( GetAttributeValue( "DisplayPhone" ).AsBooleanOrNull() ?? false ) { var numberTypeId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME ) ).Id; var phone = person.PhoneNumbers.FirstOrDefault( p => p.NumberTypeValueId == numberTypeId ); if ( phone == null ) { phone = new PhoneNumber(); person.PhoneNumbers.Add( phone ); phone.NumberTypeValueId = numberTypeId; } phone.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phone.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); } if ( familyGroup == null ) { var groupLocationService = new GroupLocationService( rockContext ); if ( GroupLocationId.HasValue ) { familyGroup = groupLocationService.Queryable() .Where( gl => gl.Id == GroupLocationId.Value ) .Select( gl => gl.Group ) .FirstOrDefault(); } else { familyGroup = personService.GetFamilies( person.Id ).FirstOrDefault(); } } rockContext.SaveChanges(); if ( familyGroup != null ) { GroupService.AddNewGroupAddress( rockContext, familyGroup, GetAttributeValue( "AddressType" ), acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country, true ); } } return person; }
/// <summary> /// Build filter values/summary with user friendly data from filters /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> protected void fExceptionList_DisplayFilterValue( object sender, GridFilter.DisplayFilterValueArgs e ) { switch ( e.Key ) { case "Site": int siteId; if ( int.TryParse( e.Value, out siteId ) ) { var site = SiteCache.Read( siteId ); if ( site != null ) { e.Value = site.Name; } } break; case "Page": int pageId; if ( int.TryParse( e.Value, out pageId ) ) { var page = PageCache.Read( pageId ); if ( page != null ) { e.Value = page.InternalName; } } break; case "User": int userPersonId; if ( int.TryParse( e.Value, out userPersonId ) ) { PersonService personService = new PersonService( new RockContext() ); var user = personService.Get( userPersonId ); if ( user != null ) { e.Value = user.FullName; } } break; } }
/// <summary> /// Handles connecting the saved image file to the person Id specified in the CommandArgument control /// attribute. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RepeaterItemEventArgs"/> instance containing the event data.</param> protected void imageEditor_FileSaved( object sender, EventArgs e ) { var control = (Rock.Web.UI.Controls.ImageEditor)sender; var personId = control.Attributes["CommandArgument"]; if ( personId != null && control.BinaryFileId != null ) { RockContext rockContext = new RockContext(); PersonService personService = new PersonService( rockContext ); var person = personService.Get( personId.AsInteger() ); person.PhotoId = control.BinaryFileId.Value; AddOrUpdatePersonInPhotoRequestGroup( person, rockContext ); rockContext.SaveChanges(); } }
/// <summary> /// Returns a list of each person and their GroupRequiremnt status for this group requirement /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="personQry">The person qry.</param> /// <param name="groupId">The group identifier.</param> /// <param name="groupRoleId">The group role identifier.</param> /// <returns></returns> /// <exception cref="System.Exception">No dataview assigned to Group Requirement Type: " + this.GroupRequirementType.Name</exception> public IEnumerable <PersonGroupRequirementStatus> PersonQueryableMeetsGroupRequirement(RockContext rockContext, IQueryable <Person> personQry, int groupId, int?groupRoleId) { if ((this.GroupRoleId != null) && (groupRoleId != null) && (this.GroupRoleId != groupRoleId)) { // if this GroupRequirement is for a specific role, the groupRole we are checking for is something different var result = personQry.ToList().Select(a => new PersonGroupRequirementStatus { PersonId = a.Id, GroupRequirement = this, MeetsGroupRequirement = MeetsGroupRequirement.NotApplicable }); return(result); } if (this.GroupRequirementType.RequirementCheckType == RequirementCheckType.Dataview) { if (this.GroupRequirementType.DataViewId.HasValue) { var errorMessages = new List <string>(); var personService = new PersonService(rockContext); var paramExpression = personService.ParameterExpression; var dataViewWhereExpression = this.GroupRequirementType.DataView.GetExpression(personService, paramExpression, out errorMessages); var dataViewQry = personService.Get(paramExpression, dataViewWhereExpression); IQueryable <Person> warningDataViewQry = null; if (this.GroupRequirementType.WarningDataViewId.HasValue) { var warningDataViewWhereExpression = this.GroupRequirementType.WarningDataView.GetExpression(personService, paramExpression, out errorMessages); warningDataViewQry = personService.Get(paramExpression, warningDataViewWhereExpression); } if (dataViewQry != null) { var personWithRequirements = from p in personQry join d in dataViewQry on p equals d into oj from d in oj.DefaultIfEmpty() select new { PersonId = p.Id, Included = d != null, WarningIncluded = false }; // if a Warning Database was specified, set the WarningIncluded flag to true if they are included in the Warning Dataview if (warningDataViewQry != null) { personWithRequirements = personWithRequirements.Select(a => new { a.PersonId, a.Included, WarningIncluded = warningDataViewQry.Any(w => w.Id == a.PersonId) }); } var result = personWithRequirements.ToList().Select(a => new PersonGroupRequirementStatus { PersonId = a.PersonId, GroupRequirement = this, MeetsGroupRequirement = a.Included ? (a.WarningIncluded ? MeetsGroupRequirement.MeetsWithWarning : MeetsGroupRequirement.Meets) : MeetsGroupRequirement.NotMet }); return(result); } } else { throw new Exception("No dataview assigned to Group Requirement Type: " + this.GroupRequirementType.Name); } } else if (this.GroupRequirementType.RequirementCheckType == RequirementCheckType.Sql) { // if requirement set on GroupType, this.Group is null var targetGroup = this.Group ?? new GroupService(rockContext).Get(groupId); string formattedSql = this.GroupRequirementType.SqlExpression.ResolveMergeFields(this.GroupRequirementType.GetMergeObjects(targetGroup)); string warningFormattedSql = this.GroupRequirementType.WarningSqlExpression.ResolveMergeFields(this.GroupRequirementType.GetMergeObjects(targetGroup)); try { var tableResult = DbService.GetDataTable(formattedSql, System.Data.CommandType.Text, null); if (tableResult.Columns.Count > 0) { IEnumerable <int> personIds = tableResult.Rows.OfType <System.Data.DataRow>().Select(r => Convert.ToInt32(r[0])); IEnumerable <int> warningPersonIds = null; // if a Warning SQL was specified, get a list of PersonIds that should have a warning with their status if (!string.IsNullOrWhiteSpace(warningFormattedSql)) { var warningTableResult = DbService.GetDataTable(warningFormattedSql, System.Data.CommandType.Text, null); if (warningTableResult.Columns.Count > 0) { warningPersonIds = warningTableResult.Rows.OfType <System.Data.DataRow>().Select(r => Convert.ToInt32(r[0])); } } var result = personQry.Select(a => a.Id).ToList().Select(a => new PersonGroupRequirementStatus { PersonId = a, GroupRequirement = this, MeetsGroupRequirement = personIds.Contains(a) ? ((warningPersonIds != null && warningPersonIds.Contains(a)) ? MeetsGroupRequirement.MeetsWithWarning : MeetsGroupRequirement.Meets ) : MeetsGroupRequirement.NotMet, }); return(result); } } catch (Exception ex) { // Exception occurred (probably due to bad SQL) ExceptionLogService.LogException(ex, System.Web.HttpContext.Current); var result = personQry.Select(a => a.Id).ToList().Select(a => new PersonGroupRequirementStatus { PersonId = a, GroupRequirement = this, MeetsGroupRequirement = MeetsGroupRequirement.Error }); return(result); } } else { // manual var groupMemberRequirementQry = new GroupMemberRequirementService(rockContext).Queryable().Where(a => a.GroupMember.GroupId == groupId && a.GroupRequirementId == this.Id && a.RequirementMetDateTime.HasValue); var result = personQry.ToList().Select(a => new PersonGroupRequirementStatus { PersonId = a.Id, GroupRequirement = this, MeetsGroupRequirement = groupMemberRequirementQry.Any(r => r.GroupMember.PersonId == a.Id) ? MeetsGroupRequirement.Meets : MeetsGroupRequirement.NotMet }); return(result); } // shouldn't happen return(null); }
/// <summary> /// Build filter values/summary with user friendly data from filters /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> protected void fExceptionList_DisplayFilterValue( object sender, GridFilter.DisplayFilterValueArgs e ) { switch ( e.Key ) { case "Site": int siteId; if ( int.TryParse( e.Value, out siteId ) ) { var site = SiteCache.Read( siteId ); if ( site != null ) { e.Value = site.Name; } } break; case "Page": int pageId; if ( int.TryParse( e.Value, out pageId ) ) { var page = PageCache.Read( pageId ); if ( page != null ) { e.Value = page.InternalName; } } break; case "User": int userPersonId; if ( int.TryParse( e.Value, out userPersonId ) ) { PersonService personService = new PersonService( new RockContext() ); var user = personService.Get( userPersonId ); if ( user != null ) { e.Value = user.FullName; } } break; // ignore old filter parameters case "Start Date": case "End Date": e.Value = null; break; case "Date Range": e.Value = SlidingDateRangePicker.FormatDelimitedValues( e.Value ); break; } }
/// <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 ) { var rockContext = new RockContext(); rockContext.WrapTransaction( () => { var personService = new PersonService( rockContext ); var changes = new List<string>(); var person = personService.Get( CurrentPersonId ?? 0 ); if ( person != null ) { 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; 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 ) { // If setting a future birthdate, subtract a century until birthdate is not greater than today. var today = RockDateTime.Today; while ( birthday.Value.CompareTo( today ) > 0 ) { birthday = birthday.Value.AddYears( -100 ); } 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.SetBirthDate( 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 ); var newGender = rblGender.SelectedValue.ConvertToEnum<Gender>(); History.EvaluateChange( changes, "Gender", person.Gender, newGender ); person.Gender = newGender; var phoneNumberTypeIds = new List<int>(); bool smsSelected = false; foreach ( RepeaterItem item in rContactInfo.Items ) { HiddenField hfPhoneType = item.FindControl( "hfPhoneType" ) as HiddenField; PhoneNumberBox pnbPhone = item.FindControl( "pnbPhone" ) as PhoneNumberBox; CheckBox cbUnlisted = item.FindControl( "cbUnlisted" ) as CheckBox; CheckBox cbSms = item.FindControl( "cbSms" ) as CheckBox; if ( hfPhoneType != null && pnbPhone != null && cbSms != null && cbUnlisted != null ) { if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) ) { 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.NumberFormattedWithCountryCode; } phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); // Only allow one number to have SMS selected if ( smsSelected ) { phoneNumber.IsMessagingEnabled = false; } else { phoneNumber.IsMessagingEnabled = cbSms.Checked; smsSelected = cbSms.Checked; } phoneNumber.IsUnlisted = cbUnlisted.Checked; phoneNumberTypeIds.Add( phoneNumberTypeId ); History.EvaluateChange( changes, string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumberTypeId ) ), oldPhoneNumber, phoneNumber.NumberFormattedWithCountryCode ); } } } } // Remove any blank numbers var phoneNumberService = new PhoneNumberService( rockContext ); 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.ToString(), string.Empty ); person.PhoneNumbers.Remove( phoneNumber ); phoneNumberService.Delete( phoneNumber ); } History.EvaluateChange( changes, "Email", person.Email, tbEmail.Text ); person.Email = tbEmail.Text.Trim(); if ( person.IsValid ) { if ( rockContext.SaveChanges() > 0 ) { if ( changes.Any() ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes ); } if ( orphanedPhotoId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( 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; rockContext.SaveChanges(); } } } NavigateToParentPage(); } } } ); }
/// <summary> /// Gets the name of the facebook user. /// </summary> /// <param name="facebookUser">The facebook user.</param> /// <param name="syncFriends">if set to <c>true</c> [synchronize friends].</param> /// <param name="accessToken">The access token.</param> /// <returns></returns> public static string GetFacebookUserName( FacebookUser facebookUser, bool syncFriends = false, string accessToken = "" ) { string username = string.Empty; string facebookId = facebookUser.id; string facebookLink = facebookUser.link; string userName = "******" + facebookId; UserLogin user = null; using ( var rockContext = new RockContext() ) { // Query for an existing user var userLoginService = new UserLoginService( rockContext ); user = userLoginService.GetByUserName( userName ); // If no user was found, see if we can find a match in the person table if ( user == null ) { // Get name/email from Facebook login string lastName = facebookUser.last_name.ToStringSafe(); string firstName = facebookUser.first_name.ToStringSafe(); string email = string.Empty; try { email = facebookUser.email.ToStringSafe(); } catch { } Person person = null; // If person had an email, get the first person with the same name and email address. if ( !string.IsNullOrWhiteSpace( email ) ) { var personService = new PersonService( rockContext ); var people = personService.GetByMatch( firstName, lastName, email ); if ( people.Count() == 1) { person = people.First(); } } var personRecordTypeId = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id; var personStatusPending = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid() ).Id; rockContext.WrapTransaction( () => { if ( person == null ) { person = new Person(); person.IsSystem = false; person.RecordTypeValueId = personRecordTypeId; person.RecordStatusValueId = personStatusPending; person.FirstName = firstName; person.LastName = lastName; person.Email = email; person.IsEmailActive = true; person.EmailPreference = EmailPreference.EmailAllowed; try { if ( facebookUser.gender.ToString() == "male" ) { person.Gender = Gender.Male; } else if ( facebookUser.gender.ToString() == "female" ) { person.Gender = Gender.Female; } else { person.Gender = Gender.Unknown; } } catch { } if ( person != null ) { PersonService.SaveNewPerson( person, rockContext, null, false ); } } if ( person != null ) { int typeId = EntityTypeCache.Read( typeof( Facebook ) ).Id; user = UserLoginService.Create( rockContext, person, AuthenticationServiceType.External, typeId, userName, "fb", true ); } } ); } if ( user != null ) { username = user.UserName; if ( user.PersonId.HasValue ) { var converter = new ExpandoObjectConverter(); var personService = new PersonService( rockContext ); var person = personService.Get( user.PersonId.Value ); if ( person != null ) { // If person does not have a photo, try to get their Facebook photo if ( !person.PhotoId.HasValue ) { var restClient = new RestClient( string.Format( "https://graph.facebook.com/v2.2/{0}/picture?redirect=false&type=square&height=400&width=400", facebookId ) ); var restRequest = new RestRequest( Method.GET ); restRequest.RequestFormat = DataFormat.Json; restRequest.AddHeader( "Accept", "application/json" ); var restResponse = restClient.Execute( restRequest ); if ( restResponse.StatusCode == HttpStatusCode.OK ) { dynamic picData = JsonConvert.DeserializeObject<ExpandoObject>( restResponse.Content, converter ); bool isSilhouette = picData.data.is_silhouette; string url = picData.data.url; // If Facebook returned a photo url if ( !isSilhouette && !string.IsNullOrWhiteSpace( url ) ) { // Download the photo from the url provided restClient = new RestClient( url ); restRequest = new RestRequest( Method.GET ); restResponse = restClient.Execute( restRequest ); if ( restResponse.StatusCode == HttpStatusCode.OK ) { var bytes = restResponse.RawBytes; // Create and save the image BinaryFileType fileType = new BinaryFileTypeService( rockContext ).Get( Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid() ); if ( fileType != null ) { var binaryFileService = new BinaryFileService( rockContext ); var binaryFile = new BinaryFile(); binaryFileService.Add( binaryFile ); binaryFile.IsTemporary = false; binaryFile.BinaryFileType = fileType; binaryFile.MimeType = "image/jpeg"; binaryFile.FileName = user.Person.NickName + user.Person.LastName + ".jpg"; binaryFile.ContentStream = new MemoryStream( bytes ); rockContext.SaveChanges(); person.PhotoId = binaryFile.Id; rockContext.SaveChanges(); } } } } } // Save the facebook social media link var facebookAttribute = AttributeCache.Read( Rock.SystemGuid.Attribute.PERSON_FACEBOOK.AsGuid() ); if ( facebookAttribute != null ) { person.LoadAttributes( rockContext ); person.SetAttributeValue( facebookAttribute.Key, facebookLink ); person.SaveAttributeValues( rockContext ); } if ( syncFriends && !string.IsNullOrWhiteSpace( accessToken ) ) { // Get the friend list (only includes friends who have also authorized this app) var restRequest = new RestRequest( Method.GET ); restRequest.AddParameter( "access_token", accessToken ); restRequest.RequestFormat = DataFormat.Json; restRequest.AddHeader( "Accept", "application/json" ); var restClient = new RestClient( string.Format( "https://graph.facebook.com/v2.2/{0}/friends", facebookId ) ); var restResponse = restClient.Execute( restRequest ); if ( restResponse.StatusCode == HttpStatusCode.OK ) { // Get a list of the facebook ids for each friend dynamic friends = JsonConvert.DeserializeObject<ExpandoObject>( restResponse.Content, converter ); var facebookIds = new List<string>(); foreach ( var friend in friends.data ) { facebookIds.Add( friend.id ); } // Queue a transaction to add/remove friend relationships in Rock var transaction = new Rock.Transactions.UpdateFacebookFriends( person.Id, facebookIds ); Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction ); } } } } } return username; } }
/// <summary> /// Binds the filter. /// </summary> private void BindFilter() { var rockContext = new RockContext(); var sites = new SiteService( rockContext ).Queryable().OrderBy( s => s.Name ).ToList(); ddlSiteFilter.DataSource = sites; ddlSiteFilter.DataBind(); ddlSiteFilter.Items.Insert( 0, Rock.Constants.All.ListItem ); ddlSiteFilter.Visible = sites.Any(); ddlSiteFilter.SetValue( gContentListFilter.GetUserPreference( "Site" ) ); var item = ddlApprovedFilter.Items.FindByValue( gContentListFilter.GetUserPreference( "Approval Status" ) ); if ( item != null ) { item.Selected = true; } else { ddlApprovedFilter.SelectedIndex = 2; } int? personId = gContentListFilter.GetUserPreference( "Approved By" ).AsIntegerOrNull(); if ( personId.HasValue ) { var personService = new PersonService( rockContext ); var person = personService.Get( personId.Value ); if ( person != null ) { ppApprovedByFilter.SetValue( person ); } } }
/// <summary> /// Binds the exception list filter. /// </summary> private void BindExceptionListFilter() { BindSitesFilter(); int siteId; var rockContext = new RockContext(); if ( int.TryParse( fExceptionList.GetUserPreference( "Site" ), out siteId ) && ddlSite.Items.FindByValue( siteId.ToString() ) != null ) { ddlSite.SelectedValue = siteId.ToString(); } int pageId; if ( int.TryParse( fExceptionList.GetUserPreference( "Page" ), out pageId ) ) { PageService pageService = new PageService( rockContext ); ppPage.SetValue( pageService.Get( pageId ) ); } else { ppPage.SetValue( None.Id ); } int userPersonId; if ( int.TryParse( fExceptionList.GetUserPreference( "User" ), out userPersonId ) ) { PersonService personService = new PersonService( rockContext ); ppUser.SetValue( personService.Get( userPersonId ) ); } if ( !String.IsNullOrEmpty( fExceptionList.GetUserPreference( "Status Code" ) ) ) { txtStatusCode.Text = fExceptionList.GetUserPreference( "Status Code" ); } DateTime startDate; if ( DateTime.TryParse( fExceptionList.GetUserPreference( "Start Date" ), out startDate ) ) { dpStartDate.Text = startDate.ToShortDateString(); } DateTime endDate; if ( DateTime.TryParse( fExceptionList.GetUserPreference( "End Date" ), out endDate ) ) { dpEndDate.Text = endDate.ToShortDateString(); } }
/// <summary> /// Handles the filter display for each saved user value /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> /// <exception cref="System.NotImplementedException"></exception> protected void gContentListFilter_DisplayFilterValue( object sender, GridFilter.DisplayFilterValueArgs e ) { switch ( e.Key ) { case "Site": e.Value = ddlSiteFilter.SelectedValue; break; case "Approval Status": e.Value = ddlApprovedFilter.SelectedValue; break; case "Approved By": int personId = 0; if ( int.TryParse( e.Value, out personId ) && personId != 0 ) { var personService = new PersonService( new RockContext() ); var person = personService.Get( personId ); if ( person != null ) { e.Value = person.FullName; } } break; } }
private Person GetPersonOrBusiness( Person person ) { if ( person != null && phGiveAsOption.Visible && !tglGiveAsOption.Checked ) { var rockContext = new RockContext(); var personService = new PersonService( rockContext ); var groupService = new GroupService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); Group familyGroup = null; Person business = null; int? businessId = cblBusiness.SelectedValueAsInt(); if ( businessId.HasValue ) { business = personService.Get( businessId.Value ); } if ( business == null ) { DefinedValueCache dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() ); DefinedValueCache dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() ); // Create Person business = new Person(); business.LastName = txtLastName.Text; business.IsEmailActive = true; business.EmailPreference = EmailPreference.EmailAllowed; business.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid() ).Id; if ( dvcConnectionStatus != null ) { business.ConnectionStatusValueId = dvcConnectionStatus.Id; } if ( dvcRecordStatus != null ) { business.RecordStatusValueId = dvcRecordStatus.Id; } // Create Person/Family familyGroup = PersonService.SaveNewPerson( business, rockContext, null, false ); // Get the relationship roles to use var knownRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid() ); int businessContactRoleId = knownRelationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); int businessRoleId = knownRelationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); int ownerRoleId = knownRelationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); if ( ownerRoleId > 0 && businessContactRoleId > 0 && businessRoleId > 0 ) { // get the known relationship group of the business contact // add the business as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS var contactKnownRelationshipGroup = groupMemberService.Queryable() .Where( g => g.GroupRoleId == ownerRoleId && g.PersonId == person.Id ) .Select( g => g.Group ) .FirstOrDefault(); if ( contactKnownRelationshipGroup == null ) { // In some cases person may not yet have a know relationship group type contactKnownRelationshipGroup = new Group(); groupService.Add( contactKnownRelationshipGroup ); contactKnownRelationshipGroup.Name = "Known Relationship"; contactKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id; var ownerMember = new GroupMember(); ownerMember.PersonId = person.Id; ownerMember.GroupRoleId = ownerRoleId; contactKnownRelationshipGroup.Members.Add( ownerMember ); } var groupMember = new GroupMember(); groupMember.PersonId = business.Id; groupMember.GroupRoleId = businessRoleId; contactKnownRelationshipGroup.Members.Add( groupMember ); // get the known relationship group of the business // add the business contact as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT var businessKnownRelationshipGroup = groupMemberService.Queryable() .Where( g => g.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER ) ) && g.PersonId == business.Id ) .Select( g => g.Group ) .FirstOrDefault(); if ( businessKnownRelationshipGroup == null ) { // In some cases business may not yet have a know relationship group type businessKnownRelationshipGroup = new Group(); groupService.Add( businessKnownRelationshipGroup ); businessKnownRelationshipGroup.Name = "Known Relationship"; businessKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id; var ownerMember = new GroupMember(); ownerMember.PersonId = business.Id; ownerMember.GroupRoleId = ownerRoleId; businessKnownRelationshipGroup.Members.Add( ownerMember ); } var businessGroupMember = new GroupMember(); businessGroupMember.PersonId = person.Id; businessGroupMember.GroupRoleId = businessContactRoleId; businessKnownRelationshipGroup.Members.Add( businessGroupMember ); rockContext.SaveChanges(); } } business.LastName = txtBusinessName.Text; business.Email = txtEmail.Text; if ( GetAttributeValue( "DisplayPhone" ).AsBooleanOrNull() ?? false ) { var numberTypeId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK ) ).Id; var phone = business.PhoneNumbers.FirstOrDefault( p => p.NumberTypeValueId == numberTypeId ); if ( phone == null ) { phone = new PhoneNumber(); business.PhoneNumbers.Add( phone ); phone.NumberTypeValueId = numberTypeId; } phone.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phone.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); } if ( familyGroup == null ) { var groupLocationService = new GroupLocationService( rockContext ); if ( GroupLocationId.HasValue ) { familyGroup = groupLocationService.Queryable() .Where( gl => gl.Id == GroupLocationId.Value ) .Select( gl => gl.Group ) .FirstOrDefault(); } else { familyGroup = personService.GetFamilies( business.Id ).FirstOrDefault(); } } rockContext.SaveChanges(); if ( familyGroup != null ) { GroupService.AddNewGroupAddress( rockContext, familyGroup, Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK, acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country, false ); } return business; } return person; }
/// <summary> /// Saves the new family. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="familyMembers">The family members.</param> /// <param name="campusId">The campus identifier.</param> /// <param name="savePersonAttributes">if set to <c>true</c> [save person attributes].</param> /// <returns></returns> public static Group SaveNewFamily( RockContext rockContext, List<GroupMember> familyMembers, int? campusId, bool savePersonAttributes ) { 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( rockContext ); var familyGroup = new Group(); familyGroup.GroupTypeId = familyGroupType.Id; familyGroup.Name = familyMembers.FirstOrDefault().Person.LastName + " Family"; History.EvaluateChange( familyChanges, "Family", string.Empty, familyGroup.Name ); if ( campusId.HasValue ) { History.EvaluateChange( familyChanges, "Campus", string.Empty, CampusCache.Read( campusId.Value ).Name ); } familyGroup.CampusId = campusId; int? childRoleId = null; var childRole = new GroupTypeRoleService( rockContext ).Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) ); if ( childRole != null ) { childRoleId = childRole.Id; } 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 Type", string.Empty, person.RecordTypeValueId.HasValue ? DefinedValueCache.GetName( person.RecordTypeValueId.Value ) : string.Empty ); History.EvaluateChange( demographicChanges, "Record Status", string.Empty, person.RecordStatusValueId.HasValue ? DefinedValueCache.GetName( person.RecordStatusValueId.Value ) : string.Empty ); History.EvaluateChange( demographicChanges, "Record Status Reason", string.Empty, person.RecordStatusReasonValueId.HasValue ? DefinedValueCache.GetName( person.RecordStatusReasonValueId.Value ) : string.Empty ); History.EvaluateChange( demographicChanges, "Connection Status", string.Empty, person.ConnectionStatusValueId.HasValue ? DefinedValueCache.GetName( person.ConnectionStatusValueId ) : string.Empty ); History.EvaluateChange( demographicChanges, "Deceased", false.ToString(), ( person.IsDeceased ?? false ).ToString() ); 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, "Suffix", string.Empty, person.SuffixValueId.HasValue ? DefinedValueCache.GetName( person.SuffixValueId ) : string.Empty ); History.EvaluateChange( demographicChanges, "Birth Date", null, person.BirthDate ); History.EvaluateChange( demographicChanges, "Gender", null, person.Gender ); History.EvaluateChange( demographicChanges, "Marital Status", string.Empty, person.MaritalStatusValueId.HasValue ? DefinedValueCache.GetName( person.MaritalStatusValueId ) : string.Empty ); History.EvaluateChange( demographicChanges, "Anniversary Date", null, person.AnniversaryDate ); History.EvaluateChange( demographicChanges, "Graduation Year", null, person.GraduationYear ); History.EvaluateChange( demographicChanges, "Email", string.Empty, person.Email ); History.EvaluateChange( demographicChanges, "Email Active", false.ToString(), ( person.IsEmailActive ?? false ).ToString() ); History.EvaluateChange( demographicChanges, "Email Note", string.Empty, person.EmailNote ); History.EvaluateChange( demographicChanges, "Email Preference", null, person.EmailPreference ); History.EvaluateChange( demographicChanges, "Inactive Reason Note", string.Empty, person.InactiveReasonNote ); History.EvaluateChange( demographicChanges, "System Note", string.Empty, person.SystemNote ); familyDemographicChanges.Add( person.Guid, demographicChanges ); var memberChanges = new List<string>(); string roleName = familyGroupType.Roles .Where( r => r.Id == familyMember.GroupRoleId ) .Select( r => r.Name ) .FirstOrDefault(); History.EvaluateChange( memberChanges, "Role", string.Empty, roleName ); familyMemberChanges.Add( person.Guid, memberChanges ); } } groupService.Add( familyGroup ); rockContext.SaveChanges(); var personService = new PersonService( rockContext ); foreach ( var groupMember in familyMembers ) { var person = groupMember.Person; if ( savePersonAttributes ) { var newValues = person.AttributeValues; person.LoadAttributes(); foreach ( var attributeCache in person.Attributes.Select( a => a.Value ) ) { string oldValue = person.GetAttributeValue( attributeCache.Key ) ?? string.Empty; string newValue = string.Empty; if ( newValues != null && newValues.ContainsKey( attributeCache.Key ) && newValues[attributeCache.Key] != null ) { newValue = newValues[attributeCache.Key].Value ?? string.Empty; } if ( !oldValue.Equals( newValue ) ) { History.EvaluateChange( familyDemographicChanges[person.Guid], attributeCache.Name, attributeCache.FieldType.Field.FormatValue( null, oldValue, attributeCache.QualifierValues, false ), attributeCache.FieldType.Field.FormatValue( null, newValue, attributeCache.QualifierValues, false ) ); Rock.Attribute.Helper.SaveAttributeValue( person, attributeCache, newValue ); } } } person = personService.Get( groupMember.PersonId ); if ( person != null ) { bool updateRequired = false; if ( !person.Aliases.Any( a => a.AliasPersonId == person.Id ) ) { person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } ); updateRequired = true; } var changes = familyDemographicChanges[person.Guid]; if ( groupMember.GroupRoleId != childRoleId ) { person.GivingGroupId = familyGroup.Id; updateRequired = true; History.EvaluateChange( changes, "Giving Group", string.Empty, familyGroup.Name ); } if ( updateRequired ) { rockContext.SaveChanges(); } HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), person.Id, familyMemberChanges[person.Guid], familyGroup.Name, typeof( Group ), familyGroup.Id ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), person.Id, familyChanges, familyGroup.Name, typeof( Group ), familyGroup.Id ); } } return familyGroup; } return null; }
private void ShowDetail(Guid personGuid) { using ( var rockContext = new RockContext() ) { var personService = new PersonService( new RockContext() ); var person = personService.Get( personGuid ); if ( person != null ) { lName.Text = person.FullName; string photoTag = Rock.Model.Person.GetPhotoImageTag( person, 120, 120 ); if ( person.PhotoId.HasValue ) { lPhoto.Text = string.Format( "<a href='{0}'>{1}</a>", person.PhotoUrl, photoTag ); } else { lPhoto.Text = photoTag; } lEmail.Visible = !string.IsNullOrWhiteSpace( person.Email ); lEmail.Text = person.GetEmailTag( ResolveRockUrl( "/" ), "btn btn-default", "<i class='fa fa-envelope'></i>" ); var childGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid(); var isFamilyChild = new Dictionary<int, bool>(); var allFamilyMembers = person.GetFamilyMembers( true ).ToList(); allFamilyMembers.Where( m => m.PersonId == person.Id ).ToList().ForEach( m => isFamilyChild.Add( m.GroupId, m.GroupRole.Guid.Equals( childGuid ) ) ); string urlRoot = Request.Url.ToString().ReplaceCaseInsensitive( personGuid.ToString(), "" ); var familyMembers = allFamilyMembers.Where( m => m.PersonId != person.Id ) .OrderBy( m => m.GroupId ) .ThenBy( m => m.Person.BirthDate ) .Select( m => new { Url = urlRoot + m.Person.Guid.ToString(), FullName = m.Person.FullName, Gender = m.Person.Gender, FamilyRole = m.GroupRole, Note = isFamilyChild[m.GroupId] ? ( m.GroupRole.Guid.Equals( childGuid ) ? " (Sibling)" : "(Parent)" ) : ( m.GroupRole.Guid.Equals( childGuid ) ? " (Child)" : "" ) } ) .ToList(); rcwFamily.Visible = familyMembers.Any(); rptrFamily.DataSource = familyMembers; rptrFamily.DataBind(); rptrPhones.DataSource = person.PhoneNumbers.Where( p => !p.IsUnlisted ).ToList(); rptrPhones.DataBind(); var schedules = new ScheduleService( rockContext ).Queryable() .Where( s => s.CheckInStartOffsetMinutes.HasValue ) .ToList(); var scheduleIds = schedules.Select( s => s.Id ).ToList(); var activeScheduleIds = new List<int>(); foreach ( var schedule in schedules ) { if ( schedule.IsScheduleOrCheckInActive ) { activeScheduleIds.Add( schedule.Id ); } } int? personAliasId = person.PrimaryAliasId; if ( !personAliasId.HasValue ) { personAliasId = new PersonAliasService( rockContext ).GetPrimaryAliasId( person.Id ); } var attendances = new AttendanceService( rockContext ) .Queryable( "Schedule,Group,Location" ) .Where( a => a.PersonAliasId.HasValue && a.PersonAliasId == personAliasId && a.ScheduleId.HasValue && a.GroupId.HasValue && a.LocationId.HasValue && a.DidAttend.HasValue && a.DidAttend.Value && scheduleIds.Contains( a.ScheduleId.Value ) ) .OrderByDescending( a => a.StartDateTime ) .Take( 20 ) .Select( a => new AttendanceInfo { Date = a.StartDateTime, GroupId = a.Group.Id, Group = a.Group.Name, LocationId = a.LocationId.Value, Location = a.Location.Name, Schedule = a.Schedule.Name, IsActive = a.StartDateTime > DateTime.Today && activeScheduleIds.Contains( a.ScheduleId.Value ) } ).ToList(); // Set active locations to be a link to the room in manager page var qryParam = new Dictionary<string, string>(); qryParam.Add( "Group", "" ); qryParam.Add( "Location", "" ); foreach ( var attendance in attendances.Where( a => a.IsActive ) ) { qryParam["Group"] = attendance.GroupId.ToString(); qryParam["Location"] = attendance.LocationId.ToString(); attendance.Location = string.Format( "<a href='{0}'>{1}</a>", LinkedPageUrl( "ManagerPage", qryParam ), attendance.Location ); } rcwCheckinHistory.Visible = attendances.Any(); gHistory.DataSource = attendances; gHistory.DataBind(); } } }
/// <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 ) { Rock.Data.RockTransactionScope.WrapTransaction( () => { var rockContext = new RockContext(); var personService = new PersonService( rockContext ); 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 ); DateTime? graduationDate = null; if ( ypGraduation.SelectedYear.HasValue ) { graduationDate = new DateTime( ypGraduation.SelectedYear.Value, _gradeTransitionDate.Month, _gradeTransitionDate.Day ); } History.EvaluateChange( changes, "Anniversary Date", person.GraduationDate, graduationDate ); person.GraduationDate = graduationDate; 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>(); bool smsSelected = false; foreach ( RepeaterItem item in rContactInfo.Items ) { HiddenField hfPhoneType = item.FindControl( "hfPhoneType" ) as HiddenField; PhoneNumberBox pnbPhone = item.FindControl( "pnbPhone" ) as PhoneNumberBox; CheckBox cbUnlisted = item.FindControl( "cbUnlisted" ) as CheckBox; CheckBox cbSms = item.FindControl( "cbSms" ) as CheckBox; if ( hfPhoneType != null && pnbPhone != null && cbSms != null && cbUnlisted != null ) { if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) ) { 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.NumberFormattedWithCountryCode; } phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); // Only allow one number to have SMS selected if ( smsSelected ) { phoneNumber.IsMessagingEnabled = false; } else { phoneNumber.IsMessagingEnabled = cbSms.Checked; smsSelected = cbSms.Checked; } phoneNumber.IsUnlisted = cbUnlisted.Checked; phoneNumberTypeIds.Add( phoneNumberTypeId ); History.EvaluateChange( changes, string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumberTypeId ) ), oldPhoneNumber, phoneNumber.NumberFormattedWithCountryCode ); } } } } // Remove any blank numbers var phoneNumberService = new PhoneNumberService( rockContext ); 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.ToString(), string.Empty ); person.PhoneNumbers.Remove( phoneNumber ); phoneNumberService.Delete( phoneNumber ); } History.EvaluateChange( changes, "Email", person.Email, tbEmail.Text ); person.Email = tbEmail.Text.Trim(); History.EvaluateChange( changes, "Email Active", (person.IsEmailActive ?? true), cbIsEmailActive.Checked ); person.IsEmailActive = cbIsEmailActive.Checked; var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum<EmailPreference>(); History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference ); person.EmailPreference = newEmailPreference; 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 = null; if ( person.RecordStatusValueId.HasValue && person.RecordStatusValueId.Value == DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id ) { newRecordStatusReasonId = ddlReason.SelectedValueAsInt(); } History.EvaluateChange( changes, "Record Status Reason", DefinedValueCache.GetName( person.RecordStatusReasonValueId ), DefinedValueCache.GetName( newRecordStatusReasonId ) ); person.RecordStatusReasonValueId = newRecordStatusReasonId; if ( person.IsValid ) { if ( rockContext.SaveChanges() > 0 ) { if ( changes.Any() ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), Person.Id, changes ); } if ( orphanedPhotoId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( 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; rockContext.SaveChanges(); } } Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false ); } } } ); }
/// <summary> /// Displays the confirmation. /// </summary> /// <param name="personId">The person identifier.</param> private void DisplayConfirmation( int personId ) { PersonService personService = new PersonService( new RockContext() ); Person person = personService.Get( personId ); if ( person != null ) { Rock.Model.UserLogin user = CreateUser( person, false ); 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 personDictionary = person.ToLiquid() as Dictionary<string, object>; mergeObjects.Add( "Person", personDictionary ); mergeObjects.Add( "User", user ); var recipients = new Dictionary<string, Dictionary<string, object>>(); recipients.Add( person.Email, mergeObjects ); Email.Send( GetAttributeValue( "ConfirmAccountTemplate" ).AsGuid(), recipients, ResolveRockUrl( "~/" ), ResolveRockUrl( "~~/" ) ); ShowPanel( 4 ); } else { ShowErrorMessage( "Invalid Person" ); } }
/// <summary> /// Handles the filter display for each saved user value /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> /// <exception cref="System.NotImplementedException"></exception> protected void rFilter_DisplayFilterValue( object sender, Rock.Web.UI.Controls.GridFilter.DisplayFilterValueArgs e ) { switch ( e.Key ) { case "Channel": int entityTypeId = 0; if ( int.TryParse( e.Value, out entityTypeId ) ) { var entity = EntityTypeCache.Read( entityTypeId ); if ( entity != null ) { e.Value = entity.FriendlyName; } } break; case "Status": if ( !string.IsNullOrWhiteSpace( e.Value ) ) { e.Value = ( (CommunicationStatus)System.Enum.Parse( typeof( CommunicationStatus ), e.Value ) ).ConvertToString(); } break; case "Created By": int personId = 0; if ( int.TryParse( e.Value, out personId ) && personId != 0 ) { var personService = new PersonService(); var person = personService.Get( personId ); if ( person != null ) { e.Value = person.FullName; } } break; } }
/// <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 ); }
private void BindFilter() { if ( cpChannel.Items[0].Value != string.Empty ) { cpChannel.Items.Insert( 0, new ListItem( string.Empty, string.Empty ) ); } ddlStatus.BindToEnum( typeof( CommunicationStatus ) ); // Replace the Transient status with an emtyp value (need an empty one, and don't need transient value) ddlStatus.Items[0].Text = string.Empty; ddlStatus.Items[0].Value = string.Empty; if ( !Page.IsPostBack ) { if ( !canApprove ) { rFilter.SaveUserPreference( "Created By", string.Empty ); } tbSubject.Text = rFilter.GetUserPreference( "Subject" ); cpChannel.SelectedValue = rFilter.GetUserPreference( "Channel" ); ddlStatus.SelectedValue = rFilter.GetUserPreference( "Status" ); int personId = 0; if ( int.TryParse( rFilter.GetUserPreference( "Created By" ), out personId ) ) { var personService = new PersonService(); var person = personService.Get( personId ); if ( person != null ) { ppSender.SetValue( person ); } } tbContent.Text = rFilter.GetUserPreference( "Content" ); } }
/// <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 ) { var rockContext = new RockContext(); rockContext.WrapTransaction( () => { var personService = new PersonService( rockContext ); var changes = new List<string>(); var person = personService.Get( CurrentPersonId ?? 0 ); if ( person != null ) { 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; History.EvaluateChange(changes, "Nick Name", person.NickName, tbNickName.Text); person.NickName = tbNickName.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 ) { // If setting a future birthdate, subtract a century until birthdate is not greater than today. var today = RockDateTime.Today; while ( birthday.Value.CompareTo( today ) > 0 ) { birthday = birthday.Value.AddYears( -100 ); } 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.SetBirthDate( 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 ); var newGender = rblGender.SelectedValue.ConvertToEnum<Gender>(); History.EvaluateChange( changes, "Gender", person.Gender, newGender ); person.Gender = newGender; var phoneNumberTypeIds = new List<int>(); bool smsSelected = false; foreach ( RepeaterItem item in rContactInfo.Items ) { HiddenField hfPhoneType = item.FindControl( "hfPhoneType" ) as HiddenField; PhoneNumberBox pnbPhone = item.FindControl( "pnbPhone" ) as PhoneNumberBox; CheckBox cbUnlisted = item.FindControl( "cbUnlisted" ) as CheckBox; CheckBox cbSms = item.FindControl( "cbSms" ) as CheckBox; if ( hfPhoneType != null && pnbPhone != null && cbSms != null && cbUnlisted != null ) { if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) ) { 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.NumberFormattedWithCountryCode; } phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); // Only allow one number to have SMS selected if ( smsSelected ) { phoneNumber.IsMessagingEnabled = false; } else { phoneNumber.IsMessagingEnabled = cbSms.Checked; smsSelected = cbSms.Checked; } phoneNumber.IsUnlisted = cbUnlisted.Checked; phoneNumberTypeIds.Add( phoneNumberTypeId ); History.EvaluateChange( changes, string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumberTypeId ) ), oldPhoneNumber, phoneNumber.NumberFormattedWithCountryCode ); } } } } // Remove any blank numbers var phoneNumberService = new PhoneNumberService( rockContext ); 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.ToString(), string.Empty ); person.PhoneNumbers.Remove( phoneNumber ); phoneNumberService.Delete( phoneNumber ); } History.EvaluateChange( changes, "Email", person.Email, tbEmail.Text ); person.Email = tbEmail.Text.Trim(); var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum<EmailPreference>(); History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference ); person.EmailPreference = newEmailPreference; if ( person.IsValid ) { if ( rockContext.SaveChanges() > 0 ) { if ( changes.Any() ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes ); } if ( orphanedPhotoId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( 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; rockContext.SaveChanges(); } } // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up if ( imgPhoto.CropBinaryFileId.HasValue ) { if ( imgPhoto.CropBinaryFileId != person.PhotoId ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( imgPhoto.CropBinaryFileId.Value ); if ( binaryFile != null && binaryFile.IsTemporary ) { string errorMessage; if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) ) { binaryFileService.Delete( binaryFile ); rockContext.SaveChanges(); } } } } } // save address if ( pnlAddress.Visible ) { Guid? familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull(); if ( familyGroupTypeGuid.HasValue ) { var familyGroup = new GroupService( rockContext ).Queryable() .Where( f => f.GroupType.Guid == familyGroupTypeGuid.Value && f.Members.Any( m => m.PersonId == person.Id ) ) .FirstOrDefault(); if ( familyGroup != null ) { Guid? addressTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull(); if ( addressTypeGuid.HasValue ) { var groupLocationService = new GroupLocationService( rockContext ); var dvHomeAddressType = DefinedValueCache.Read( addressTypeGuid.Value ); var familyAddress = groupLocationService.Queryable().Where( l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id ).FirstOrDefault(); if ( familyAddress != null && string.IsNullOrWhiteSpace( acAddress.Street1 ) ) { // delete the current address History.EvaluateChange( changes, familyAddress.GroupLocationTypeValue.Value + " Location", familyAddress.Location.ToString(), string.Empty ); groupLocationService.Delete( familyAddress ); rockContext.SaveChanges(); } else { if ( !string.IsNullOrWhiteSpace( acAddress.Street1 ) ) { if ( familyAddress == null ) { familyAddress = new GroupLocation(); groupLocationService.Add( familyAddress ); familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id; familyAddress.GroupId = familyGroup.Id; familyAddress.IsMailingLocation = true; familyAddress.IsMappedLocation = true; } else if ( hfStreet1.Value != string.Empty ) { // user clicked move so create a previous address var previousAddress = new GroupLocation(); groupLocationService.Add( previousAddress ); var previousAddressValue = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid() ); if ( previousAddressValue != null ) { previousAddress.GroupLocationTypeValueId = previousAddressValue.Id; previousAddress.GroupId = familyGroup.Id; Location previousAddressLocation = new Location(); previousAddressLocation.Street1 = hfStreet1.Value; previousAddressLocation.Street2 = hfStreet2.Value; previousAddressLocation.City = hfCity.Value; previousAddressLocation.State = hfState.Value; previousAddressLocation.PostalCode = hfPostalCode.Value; previousAddressLocation.Country = hfCountry.Value; previousAddress.Location = previousAddressLocation; } } familyAddress.IsMailingLocation = cbIsMailingAddress.Checked; familyAddress.IsMappedLocation = cbIsPhysicalAddress.Checked; var updatedHomeAddress = new Location(); acAddress.GetValues( updatedHomeAddress ); History.EvaluateChange( changes, dvHomeAddressType.Value + " Location", familyAddress.Location != null ? familyAddress.Location.ToString() : string.Empty, updatedHomeAddress.ToString() ); familyAddress.Location = updatedHomeAddress; rockContext.SaveChanges(); } } HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes ); } } } } NavigateToParentPage(); } } } ); }
/// <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(); }