public DefinedValueSummary( DefinedValue dv ) { mForeignIdValues = new List<string>(); Id = dv.Id.ToString(); DefinedTypeId = dv.DefinedTypeId.ToString(); Value = dv.Value; Description = dv.Description; ForeignId = dv.ForeignId; Order = dv.Order; IsSystem = dv.IsSystem; }
/// <summary> /// Shows the details. /// </summary> private void ShowDetails() { RockContext rockContext = new RockContext(); pnlAddress.Visible = GetAttributeValue("ShowAddress").AsBoolean(); acAddress.Required = GetAttributeValue("AddressRequired").AsBoolean(); var person = CurrentPerson; if (person != null) { imgPhoto.BinaryFileId = person.PhotoId; imgPhoto.NoPictureUrl = Person.GetPersonPhotoUrl(person, 200, 200); ddlTitle.SelectedValue = person.TitleValueId.HasValue ? person.TitleValueId.Value.ToString() : string.Empty; tbFirstName.Text = person.FirstName; tbNickName.Text = person.NickName; tbLastName.Text = person.LastName; ddlSuffix.SelectedValue = person.SuffixValueId.HasValue ? person.SuffixValueId.Value.ToString() : string.Empty; bpBirthDay.SelectedDate = person.BirthDate; rblGender.SelectedValue = person.Gender.ConvertToString(); tbEmail.Text = person.Email; rblEmailPreference.SelectedValue = person.EmailPreference.ConvertToString(false); Guid?locationTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull(); if (locationTypeGuid.HasValue) { var addressTypeDv = DefinedValueCache.Read(locationTypeGuid.Value); // if address type is home enable the move and is mailing/physical if (addressTypeDv.Guid == Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()) { lbMoved.Visible = true; cbIsMailingAddress.Visible = true; cbIsPhysicalAddress.Visible = true; } else { lbMoved.Visible = false; cbIsMailingAddress.Visible = false; cbIsPhysicalAddress.Visible = false; } lAddressTitle.Text = addressTypeDv.Value + " Address"; var familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull(); if (familyGroupTypeGuid.HasValue) { var familyGroupType = GroupTypeCache.Read(familyGroupTypeGuid.Value); var familyAddress = new GroupLocationService(rockContext).Queryable() .Where(l => l.Group.GroupTypeId == familyGroupType.Id && l.GroupLocationTypeValueId == addressTypeDv.Id && l.Group.Members.Any(m => m.PersonId == person.Id)) .FirstOrDefault(); if (familyAddress != null) { acAddress.SetValues(familyAddress.Location); cbIsMailingAddress.Checked = familyAddress.IsMailingLocation; cbIsPhysicalAddress.Checked = familyAddress.IsMappedLocation; } } } var mobilePhoneType = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE)); var phoneNumbers = new List <PhoneNumber>(); var phoneNumberTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE)); if (phoneNumberTypes.DefinedValues.Any()) { foreach (var phoneNumberType in phoneNumberTypes.DefinedValues) { var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberType.Id); if (phoneNumber == null) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Value = phoneNumberType.Value; phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id; } else { // Update number format, just in case it wasn't saved correctly phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber(phoneNumber.CountryCode, phoneNumber.Number); } phoneNumbers.Add(phoneNumber); } rContactInfo.DataSource = phoneNumbers; rContactInfo.DataBind(); } } }
/// <summary> /// Shows the details. /// </summary> private void ShowDetails() { lTitle.Text = string.Format("Edit: {0}", Person.FullName).FormatAsHtmlTitle(); imgPhoto.BinaryFileId = Person.PhotoId; imgPhoto.NoPictureUrl = Person.GetPersonNoPictureUrl(this.Person, 400, 400); ddlTitle.SelectedValue = Person.TitleValueId.HasValue ? Person.TitleValueId.Value.ToString() : string.Empty; tbFirstName.Text = Person.FirstName; tbNickName.Text = string.IsNullOrWhiteSpace(Person.NickName) ? string.Empty : (Person.NickName.Equals(Person.FirstName, StringComparison.OrdinalIgnoreCase) ? string.Empty : Person.NickName); tbMiddleName.Text = Person.MiddleName; tbLastName.Text = Person.LastName; ddlSuffix.SelectedValue = Person.SuffixValueId.HasValue ? Person.SuffixValueId.Value.ToString() : string.Empty; bpBirthDay.SelectedDate = Person.BirthDate; if (Person.GraduationYear.HasValue) { ypGraduation.SelectedYear = Person.GraduationYear.Value; } else { ypGraduation.SelectedYear = null; } if (!Person.HasGraduated ?? false) { int gradeOffset = Person.GradeOffset.Value; var maxGradeOffset = ddlGradePicker.MaxGradeOffset; // keep trying until we find a Grade that has a gradeOffset that that includes the Person's gradeOffset (for example, there might be combined grades) while (!ddlGradePicker.Items.OfType <ListItem>().Any(a => a.Value.AsInteger() == gradeOffset) && gradeOffset <= maxGradeOffset) { gradeOffset++; } ddlGradePicker.SetValue(gradeOffset); } else { ddlGradePicker.SelectedIndex = 0; } dpAnniversaryDate.SelectedDate = Person.AnniversaryDate; rblGender.SelectedValue = Person.Gender.ConvertToString(false); ddlMaritalStatus.SetValue(Person.MaritalStatusValueId); ddlConnectionStatus.SetValue(Person.ConnectionStatusValueId); lConnectionStatusReadOnly.Text = Person.ConnectionStatusValueId.HasValue ? Person.ConnectionStatusValue.Value : string.Empty; tbEmail.Text = Person.Email; cbIsEmailActive.Checked = Person.IsEmailActive; rblEmailPreference.SelectedValue = Person.EmailPreference.ConvertToString(false); rblCommunicationPreference.SetValue(Person.CommunicationPreference == CommunicationType.SMS ? "2" : "1"); ddlRecordStatus.SetValue(Person.RecordStatusValueId); lRecordStatusReadOnly.Text = Person.RecordStatusValueId.HasValue ? Person.RecordStatusValue.Value : string.Empty; ddlReason.SetValue(Person.RecordStatusReasonValueId); lReasonReadOnly.Text = Person.RecordStatusReasonValueId.HasValue ? Person.RecordStatusReasonValue.Value : string.Empty; tbInactiveReasonNote.Text = Person.InactiveReasonNote; lReasonNoteReadOnly.Text = Person.InactiveReasonNote; ddlRecordStatus_SelectedIndexChanged(null, null); var mobilePhoneType = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE)); var phoneNumbers = new List <PhoneNumber>(); var phoneNumberTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE)); if (phoneNumberTypes.DefinedValues.Any()) { foreach (var phoneNumberType in phoneNumberTypes.DefinedValues) { var phoneNumber = Person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberType.Id); if (phoneNumber == null) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Value = phoneNumberType.Value; phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id; } else { // Update number format, just in case it wasn't saved correctly phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber(phoneNumber.CountryCode, phoneNumber.Number); } phoneNumbers.Add(phoneNumber); } rContactInfo.DataSource = phoneNumbers; rContactInfo.DataBind(); } ddlGivingGroup.SetValue(Person.GivingGroupId); var personGivingEnvelopeAttribute = AttributeCache.Read(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER.AsGuid()); rcwEnvelope.Visible = GlobalAttributesCache.Read().EnableGivingEnvelopeNumber&& personGivingEnvelopeAttribute != null; if (personGivingEnvelopeAttribute != null) { tbGivingEnvelopeNumber.Text = Person.GetAttributeValue(personGivingEnvelopeAttribute.Key); } this.PersonPreviousNamesState = Person.GetPreviousNames().ToList(); BindPersonPreviousNamesGrid(); }
/// <summary> /// Maps the communication data. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapCommunication(IQueryable <Row> tableData) { var lookupContext = new RockContext(); var personService = new PersonService(lookupContext); var attributeService = new AttributeService(lookupContext); var definedTypePhoneType = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE), lookupContext); var otherNumberType = definedTypePhoneType.DefinedValues.Where(dv => dv.Value.StartsWith("Other")).Select(v => (int?)v.Id).FirstOrDefault(); if (otherNumberType == null) { var otherType = new DefinedValue(); otherType.IsSystem = false; otherType.DefinedTypeId = definedTypePhoneType.Id; otherType.Order = 0; otherType.Value = "Other"; otherType.Description = "Imported from FellowshipOne"; otherType.CreatedByPersonAliasId = ImportPersonAliasId; lookupContext.DefinedValues.Add(otherType); lookupContext.SaveChanges(DisableAuditing); } // Look up existing Person attributes var personAttributes = attributeService.GetByEntityTypeId(PersonEntityTypeId).ToList(); // Cached Rock attributes: Facebook, Twitter, Instagram var twitterAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key.Equals("Twitter", StringComparison.InvariantCultureIgnoreCase))); var facebookAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key.Equals("Facebook", StringComparison.InvariantCultureIgnoreCase))); var instagramAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key.Equals("Instagram", StringComparison.InvariantCultureIgnoreCase))); var newNumbers = new List <PhoneNumber>(); var existingNumbers = new PhoneNumberService(lookupContext).Queryable().AsNoTracking().ToList(); var newPeopleAttributes = new Dictionary <int, Person>(); int completed = 0; int totalRows = tableData.Count(); int percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying communication import ({0:N0} found, {1:N0} already exist).", totalRows, existingNumbers.Count)); foreach (var groupedRows in tableData.OrderByDescending(r => r["LastUpdatedDate"]).GroupBy <Row, int?>(r => r["Household_ID"] as int?)) { foreach (var row in groupedRows.Where(r => r != null)) { string value = row["Communication_Value"] as string; int? individualId = row["Individual_ID"] as int?; int? householdId = row["Household_ID"] as int?; var peopleToUpdate = new List <PersonKeys>(); if (individualId != null) { var matchingPerson = GetPersonKeys(individualId, householdId, includeVisitors: false); if (matchingPerson != null) { peopleToUpdate.Add(matchingPerson); } } else { peopleToUpdate = GetFamilyByHouseholdId(householdId, includeVisitors: false); } if (peopleToUpdate.Any() && !string.IsNullOrWhiteSpace(value)) { DateTime?lastUpdated = row["LastUpdatedDate"] as DateTime?; string communicationComment = row["Communication_Comment"] as string; string type = row["Communication_Type"] as string; bool isListed = (bool)row["Listed"]; value = value.RemoveWhitespace(); // Communication value is a number if (type.Contains("Phone") || type.Contains("Mobile")) { var extension = string.Empty; var countryCode = PhoneNumber.DefaultCountryCode(); var normalizedNumber = string.Empty; var countryIndex = value.IndexOf('+'); int extensionIndex = value.LastIndexOf('x') > 0 ? value.LastIndexOf('x') : value.Length; if (countryIndex >= 0) { countryCode = value.Substring(countryIndex, countryIndex + 3).AsNumeric(); normalizedNumber = value.Substring(countryIndex + 3, extensionIndex - 3).AsNumeric(); extension = value.Substring(extensionIndex); } else if (extensionIndex > 0) { normalizedNumber = value.Substring(0, extensionIndex).AsNumeric(); extension = value.Substring(extensionIndex).AsNumeric(); } else { normalizedNumber = value.AsNumeric(); } if (!string.IsNullOrWhiteSpace(normalizedNumber)) { foreach (var personKeys in peopleToUpdate) { bool numberExists = existingNumbers.Any(n => n.PersonId == personKeys.PersonId && n.Number.Equals(value)); if (!numberExists) { var newNumber = new PhoneNumber(); newNumber.CreatedByPersonAliasId = ImportPersonAliasId; newNumber.ModifiedDateTime = lastUpdated; newNumber.PersonId = (int)personKeys.PersonId; newNumber.IsMessagingEnabled = false; newNumber.CountryCode = countryCode; newNumber.IsUnlisted = !isListed; newNumber.Extension = extension.Left(20) ?? string.Empty; newNumber.Number = normalizedNumber.Left(20); newNumber.Description = communicationComment; newNumber.NumberFormatted = PhoneNumber.FormattedNumber(countryCode, newNumber.Number, true); var matchingNumberType = definedTypePhoneType.DefinedValues.Where(v => type.StartsWith(v.Value)) .Select(v => (int?)v.Id).FirstOrDefault(); newNumber.NumberTypeValueId = matchingNumberType ?? otherNumberType; newNumbers.Add(newNumber); existingNumbers.Add(newNumber); } } completed++; } } else { Person person = null; var personKeys = peopleToUpdate.FirstOrDefault(); if (!newPeopleAttributes.ContainsKey(personKeys.PersonId)) { // not in dictionary, get person from database person = personService.Queryable(includeDeceased: true).FirstOrDefault(p => p.Id == personKeys.PersonId); } else { // reuse person from dictionary person = newPeopleAttributes[personKeys.PersonId]; } if (person != null) { if (person.Attributes == null || person.AttributeValues == null) { // make sure we have valid objects to assign to person.Attributes = new Dictionary <string, AttributeCache>(); person.AttributeValues = new Dictionary <string, AttributeValueCache>(); } // Check for an InFellowship ID/email before checking other types of email var isLoginValue = type.IndexOf("InFellowship", StringComparison.OrdinalIgnoreCase) >= 0; var personAlreadyHasLogin = person.Attributes.ContainsKey(InFellowshipLoginAttribute.Key); if (isLoginValue && !personAlreadyHasLogin) { AddPersonAttribute(InFellowshipLoginAttribute, person, value); AddUserLogin(AuthProviderEntityTypeId, person, value); } else if (value.IsEmail()) { // person email is empty if (string.IsNullOrWhiteSpace(person.Email)) { person.Email = value.Left(75); person.IsEmailActive = isListed; person.EmailPreference = isListed ? EmailPreference.EmailAllowed : EmailPreference.DoNotEmail; person.ModifiedDateTime = lastUpdated; person.EmailNote = communicationComment; lookupContext.SaveChanges(DisableAuditing); } // this is a different email, assign it to SecondaryEmail else if (!person.Email.Equals(value) && !person.Attributes.ContainsKey(SecondaryEmailAttribute.Key)) { AddPersonAttribute(SecondaryEmailAttribute, person, value); } } else if (type.Contains("Twitter") && !person.Attributes.ContainsKey(twitterAttribute.Key)) { AddPersonAttribute(twitterAttribute, person, value); } else if (type.Contains("Facebook") && !person.Attributes.ContainsKey(facebookAttribute.Key)) { AddPersonAttribute(facebookAttribute, person, value); } else if (type.Contains("Instagram") && !person.Attributes.ContainsKey(instagramAttribute.Key)) { AddPersonAttribute(instagramAttribute, person, value); } if (!newPeopleAttributes.ContainsKey(personKeys.PersonId)) { newPeopleAttributes.Add(personKeys.PersonId, person); } else { newPeopleAttributes[personKeys.PersonId] = person; } } completed++; } if (completed % percentage < 1) { int percentComplete = completed / percentage; ReportProgress(percentComplete, string.Format("{0:N0} records imported ({1}% complete).", completed, percentComplete)); } else if (completed % ReportingNumber < 1) { if (newNumbers.Any() || newPeopleAttributes.Any()) { SaveCommunication(newNumbers, newPeopleAttributes); } // reset so context doesn't bloat lookupContext = new RockContext(); personService = new PersonService(lookupContext); newPeopleAttributes.Clear(); newNumbers.Clear(); ReportPartialProgress(); } } } } if (newNumbers.Any() || newPeopleAttributes.Any()) { SaveCommunication(newNumbers, newPeopleAttributes); } ReportProgress(100, string.Format("Finished communication import: {0:N0} records imported.", completed)); }
private void ShowAttributeValueEdit(int valueId, bool setValues) { var definedType = DefinedTypeCache.Read( hfDefinedTypeId.ValueAsInt() ); DefinedValue definedValue; if ( !valueId.Equals( 0 ) ) { definedValue = new DefinedValueService().Get( valueId ); if ( definedType != null ) { lActionTitleDefinedValue.Text = ActionTitle.Edit( "defined value for " + definedType.Name ); } } else { definedValue = new DefinedValue { Id = 0 }; definedValue.DefinedTypeId = hfDefinedTypeId.ValueAsInt(); if ( definedType != null ) { lActionTitleDefinedValue.Text = ActionTitle.Add( "defined value for " + definedType.Name ); } } if ( setValues ) { hfDefinedValueId.SetValue( definedValue.Id ); tbValueName.Text = definedValue.Name; tbValueDescription.Text = definedValue.Description; } definedValue.LoadAttributes(); phDefinedValueAttributes.Controls.Clear(); Rock.Attribute.Helper.AddEditControls( definedValue, phDefinedValueAttributes, setValues ); SetValidationGroup( phDefinedValueAttributes.Controls, modalValue.ValidationGroup ); modalValue.Show(); }
/// <summary> /// Adds a new defined value to a given DefinedType. /// </summary> /// <param name="topic">the string value of the new defined value</param> /// <param name="definedTypeCache">a defined type cache to which the defined value will be added.</param> /// <param name="rockContext"></param> /// <returns></returns> private DefinedValueCache AddDefinedTypeValue( string topic, DefinedTypeCache definedTypeCache, RockContext rockContext ) { DefinedValueService definedValueService = new DefinedValueService( rockContext ); DefinedValue definedValue = new DefinedValue { Id = 0, IsSystem = false, Value = topic, Description = "", CreatedDateTime = RockDateTime.Now, DefinedTypeId = definedTypeCache.Id }; definedValueService.Add( definedValue ); rockContext.SaveChanges(); Rock.Web.Cache.DefinedValueCache.Flush( definedValue.Id ); Rock.Web.Cache.DefinedTypeCache.Flush( definedTypeCache.Id ); return DefinedValueCache.Read( definedValue.Id, rockContext ); }
private void AddProperty( string key, int personId, DefinedValue value, bool selected = false ) { AddProperty( key, key.SplitCase(), personId, value, selected ); }
/// <summary> /// Handles the SaveClick event of the dlgLink 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 dlgLink_SaveClick( object sender, EventArgs e ) { DefinedValue definedValue = null; using ( var rockContext = new RockContext() ) { var service = new DefinedValueService( rockContext ); int? definedValueId = hfDefinedValueId.Value.AsIntegerOrNull(); if ( definedValueId.HasValue ) { definedValue = service.Get( definedValueId.Value ); } if ( definedValue == null ) { definedValue = new DefinedValue { Id = 0 }; definedValue.DefinedTypeId = _definedType.Id; definedValue.IsSystem = false; var orders = service.Queryable() .Where( d => d.DefinedTypeId == _definedType.Id ) .Select( d => d.Order ) .ToList(); definedValue.Order = orders.Any() ? orders.Max() + 1 : 0; } definedValue.Value = tbTitle.Text; definedValue.Description = tbLink.Text; definedValue.LoadAttributes(); definedValue.SetAttributeValue( "IsLink", ( rblLinkType.SelectedValue == "Link" ).ToString() ); rockContext.WrapTransaction( () => { if ( definedValue.Id.Equals( 0 ) ) { service.Add( definedValue ); } rockContext.SaveChanges(); definedValue.SaveAttributeValues( rockContext ); } ); Rock.Web.Cache.DefinedTypeCache.Flush( definedValue.DefinedTypeId ); Rock.Web.Cache.DefinedValueCache.Flush( definedValue.Id ); } HideDialog(); BindGrid(); }
private IQueryable <HospitalRow> GetQuery(RockContext rockContext) { var contextEntity = this.ContextEntity(); var workflowService = new WorkflowService(rockContext); var workflowActivityService = new WorkflowActivityService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personAliasService = new PersonAliasService(rockContext); var definedValueService = new DefinedValueService(rockContext); var entityTypeService = new EntityTypeService(rockContext); int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id; string status = (contextEntity != null ? "Completed" : "Active"); Guid hospitalWorkflow = GetAttributeValue("HospitalAdmissionWorkflow").AsGuid(); var workflowType = new WorkflowTypeService(rockContext).Get(hospitalWorkflow); var workflowTypeIdAsString = workflowType.Id.ToString(); var attributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString) .Select(a => a.Id).ToList(); // Look up the activity type for "Visitation" var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault(); var activityAttributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString) .Select(a => a.Id).ToList(); var wfTmpqry = workflowService.Queryable().AsNoTracking() .Where(w => (w.WorkflowType.Guid == hospitalWorkflow) && (w.Status == "Active" || w.Status == status)); if (contextEntity != null) { var personGuid = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList(); var validWorkflowIds = new AttributeValueService(rockContext).Queryable() .Where(av => av.Attribute.Key == "PersonToVisit" && personGuid.Contains(av.Value)).Select(av => av.EntityId); wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id)); gReport.Columns[10].Visible = true; } var visits = workflowActivityService.Queryable() .Join( attributeValueService.Queryable(), wa => wa.Id, av => av.EntityId.Value, (wa, av) => new { WorkflowActivity = wa, AttributeValue = av }) .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(wa => wa.WorkflowActivity) .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }) .ToList(); var workflows = wfTmpqry.Join( attributeValueService.Queryable(), obj => obj.Id, av => av.EntityId.Value, (obj, av) => new { Workflow = obj, AttributeValue = av }) .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(obj => obj.Workflow) .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }) .ToList(); var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (wf, wa) => new { Workflow = wf, WorkflowActivities = wa }) .Select(obj => new { Workflow = obj.Workflow.Workflow, AttributeValues = obj.Workflow.AttributeValues, VisitationActivities = obj.WorkflowActivities }).ToList(); if (contextEntity == null) { // Make sure they aren't deceased qry = qry.AsQueryable().Where(w => ! (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ? personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased : false)).ToList(); } var newQry = qry.Select(w => new HospitalRow { Id = w.Workflow.Id, Workflow = w.Workflow, Name = w.Workflow.Name, Hospital = w.AttributeValues.Where(av => av.AttributeKey == "Hospital").Select(av => av.ValueFormatted).FirstOrDefault(), HospitalAddress = new Func <string>(() => { DefinedValue dv = definedValueService.Get(w.AttributeValues.Where(av => av.AttributeKey == "Hospital").Select(av => av.Value).FirstOrDefault().AsGuid()); dv.LoadAttributes(); return(dv.AttributeValues["Qualifier1"].ValueFormatted + " " + dv.AttributeValues["Qualifier2"].ValueFormatted + " " + dv.AttributeValues["Qualifier3"].ValueFormatted + ", " + dv.AttributeValues["Qualifier4"].ValueFormatted); })(), PersonToVisit = new Func <Person>(() => { PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()); if (pa != null) { return(pa.Person); } return(new Person()); })(), Age = new Func <int?>(() => { PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()); if (pa != null) { return(pa.Person.Age); } return(null); })(), Room = w.AttributeValues.Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(), AdmitDate = w.AttributeValues.Where(av => av.AttributeKey == "AdmitDate").Select(av => av.ValueAsDateTime).FirstOrDefault(), Description = w.AttributeValues.Where(av => av.AttributeKey == "VisitationRequestDescription").Select(av => av.ValueFormatted).FirstOrDefault(), Visits = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(), LastVisitor = new Func <string>(() => { var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault(); if (visitor != null) { return(visitor.ValueFormatted); } return("N/A"); })(), LastVisitDate = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), DischargeDate = w.AttributeValues.Where(av => av.AttributeKey == "DischargeDate").Select(av => av.ValueFormatted).FirstOrDefault(), Status = w.Workflow.Status, Communion = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(), Actions = "" }).ToList().AsQueryable().OrderBy(p => p.Hospital).ThenBy(p => p.PersonToVisit.LastName); return(newQry); }
private void AddProperty(string key, int personId, DefinedValue value, bool selected = false) { AddProperty(key, key.SplitCase(), personId, value, selected); }
public ClassNumber(DefinedValue definedValue) { }
/// <summary> /// Maps the family address. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapFamilyAddress( IQueryable<Row> tableData ) { var lookupContext = new RockContext(); var locationService = new LocationService( lookupContext ); List<GroupMember> familyGroupMemberList = new GroupMemberService( lookupContext ).Queryable().AsNoTracking() .Where( gm => gm.Group.GroupType.Guid == new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY ) ).ToList(); var groupLocationDefinedType = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.GROUP_LOCATION_TYPE ), lookupContext ); int homeGroupLocationTypeId = groupLocationDefinedType.DefinedValues .FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME ) ).Id; int workGroupLocationTypeId = groupLocationDefinedType.DefinedValues .FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK ) ).Id; int previousGroupLocationTypeId = groupLocationDefinedType.DefinedValues .FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS ) ).Id; string otherGroupLocationName = "Other (Imported)"; int? otherGroupLocationTypeId = groupLocationDefinedType.DefinedValues .Where( dv => dv.TypeName == otherGroupLocationName ) .Select( dv => (int?)dv.Id ).FirstOrDefault(); if ( otherGroupLocationTypeId == null ) { var otherGroupLocationType = new DefinedValue(); otherGroupLocationType.Value = otherGroupLocationName; otherGroupLocationType.DefinedTypeId = groupLocationDefinedType.Id; otherGroupLocationType.IsSystem = false; otherGroupLocationType.Order = 0; lookupContext.DefinedValues.Add( otherGroupLocationType ); lookupContext.SaveChanges( DisableAuditing ); otherGroupLocationTypeId = otherGroupLocationType.Id; } var newGroupLocations = new List<GroupLocation>(); int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Verifying address import ({0:N0} found).", totalRows ) ); foreach ( var row in tableData.Where( r => r != null ) ) { int? individualId = row["Individual_ID"] as int?; int? householdId = row["Household_ID"] as int?; var personKeys = GetPersonKeys( individualId, householdId, includeVisitors: false ); if ( personKeys != null ) { var familyGroup = familyGroupMemberList.Where( gm => gm.PersonId == personKeys.PersonId ) .Select( gm => gm.Group ).FirstOrDefault(); if ( familyGroup != null ) { var groupLocation = new GroupLocation(); string street1 = row["Address_1"] as string; string street2 = row["Address_2"] as string; string city = row["City"] as string; string state = row["State"] as string; string country = row["country"] as string; // NOT A TYPO: F1 has property in lower-case string zip = row["Postal_Code"] as string ?? string.Empty; // restrict zip to 5 places to prevent duplicates Location familyAddress = locationService.Get( street1, street2, city, state, zip.Left( 5 ), country, verifyLocation: false ); if ( familyAddress != null ) { familyAddress.CreatedByPersonAliasId = ImportPersonAliasId; familyAddress.Name = familyGroup.Name; familyAddress.IsActive = true; groupLocation.GroupId = familyGroup.Id; groupLocation.LocationId = familyAddress.Id; groupLocation.IsMailingLocation = true; groupLocation.IsMappedLocation = true; string addressType = row["Address_Type"].ToString().ToLower(); if ( addressType.Equals( "primary" ) ) { groupLocation.GroupLocationTypeValueId = homeGroupLocationTypeId; } else if ( addressType.Equals( "business" ) || addressType.ToLower().Equals( "org" ) ) { groupLocation.GroupLocationTypeValueId = workGroupLocationTypeId; } else if ( addressType.Equals( "previous" ) ) { groupLocation.GroupLocationTypeValueId = previousGroupLocationTypeId; } else if ( !string.IsNullOrEmpty( addressType ) ) { // look for existing group location types, otherwise mark as imported var customTypeId = groupLocationDefinedType.DefinedValues.Where( dv => dv.Value.ToLower().Equals( addressType ) ) .Select( dv => (int?)dv.Id ).FirstOrDefault(); groupLocation.GroupLocationTypeValueId = customTypeId ?? otherGroupLocationTypeId; } newGroupLocations.Add( groupLocation ); completed++; if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} addresses imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { SaveFamilyAddress( newGroupLocations ); // Reset context newGroupLocations.Clear(); lookupContext = new RockContext(); locationService = new LocationService( lookupContext ); ReportPartialProgress(); } } } } } if ( newGroupLocations.Any() ) { SaveFamilyAddress( newGroupLocations ); } ReportProgress( 100, string.Format( "Finished address import: {0:N0} addresses imported.", completed ) ); }
public ExceptionSpec(DefinedValue value) { }
/// <summary> /// Maps the Giftedness Program. /// </summary> /// <param name="tableData">The table data.</param> private void MapGiftednessProgram(IQueryable <Row> tableData) { int completed = 0; int totalRows = tableData.Count(); int percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying Giftedness Program import ({0:N0} found).", totalRows)); foreach (var row in tableData) { var rockContext = new RockContext(); var categoryList = new CategoryService(rockContext).Queryable().ToList(); var attributeList = new AttributeService(rockContext).Queryable().ToList(); var definedTypeList = new DefinedTypeService(rockContext).Queryable().ToList(); var definedValueList = new DefinedValueService(rockContext).Queryable().ToList(); //check if category exists string category = row["CategoryName"] as string; if (categoryList.Find(c => c.Name == category) == null) { var entityType = new EntityTypeService(rockContext); //creates if category doesn't exist var newCategory = new Category(); newCategory.IsSystem = false; newCategory.EntityTypeId = entityType.Queryable().Where(e => e.Name == "Rock.Model.Attribute").Select(e => e.Id).FirstOrDefault(); newCategory.EntityTypeQualifierColumn = "EntityTypeId"; newCategory.EntityTypeQualifierValue = Convert.ToString(PersonEntityTypeId); //Convert.ToString(entityType.Queryable().Where( e => e.Name == "Rock.Model.Person" ).Select( e => e.Id ).FirstOrDefault()); newCategory.Name = category; newCategory.Description = "Contains the spiritual gifts attributes"; //var newCategoryContext = new RockContext(); //newCategoryContext.WrapTransaction( () => //{ // newCategoryContext.Configuration.AutoDetectChangesEnabled = false; // newCategoryContext.Categories.Add( newCategory ); // newCategoryContext.SaveChanges( DisableAudit ); //} ); rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Categories.Add(newCategory); rockContext.SaveChanges(DisableAudit); }); } //Check if Attribute exists if (attributeList.Find(a => a.Key == "Rank1") == null || attributeList.Find(a => a.Key == "Rank2") == null || attributeList.Find(a => a.Key == "Rank3") == null || attributeList.Find(a => a.Key == "Rank4") == null) { var fieldType = new FieldTypeService(rockContext); var newAttributeList = new List <Rock.Model.Attribute>(); var fieldTypeId = fieldType.Queryable().Where(e => e.Name == "Defined Value").FirstOrDefault().Id; var category2 = new CategoryService(rockContext).Queryable().Where(gt => gt.Name == "Spiritual Gifts").FirstOrDefault(); if (attributeList.Find(a => a.Key == "Rank1") == null) { //Creates if attribute doesn't exist var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "Rank1"; newAttribute.Name = "Rank 1"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Rank 1"; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.Categories = new List <Category>(); newAttribute.Categories.Add(category2); newAttributeList.Add(newAttribute); } if (attributeList.Find(a => a.Key == "Rank2") == null) { //Creates if attribute doesn't exist var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "Rank2"; newAttribute.Name = "Rank 2"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Rank 2"; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.Categories = new List <Category>(); newAttribute.Categories.Add(category2); newAttributeList.Add(newAttribute); } if (attributeList.Find(a => a.Key == "Rank3") == null) { //Creates if attribute doesn't exist var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "Rank3"; newAttribute.Name = "Rank 3"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Rank 3"; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.Categories = new List <Category>(); newAttribute.Categories.Add(category2); newAttributeList.Add(newAttribute); } if (attributeList.Find(a => a.Key == "Rank4") == null) { //Creates if attribute doesn't exist var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "Rank4"; newAttribute.Name = "Rank 4"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Rank 4"; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.Categories = new List <Category>(); newAttribute.Categories.Add(category2); newAttributeList.Add(newAttribute); } if (newAttributeList.Any()) { //var newAttributeContext = new RockContext(); rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Attributes.AddRange(newAttributeList); rockContext.SaveChanges(DisableAudit); newAttributeList.Clear(); }); } } //checks if Defined Type exists if (definedTypeList.Find(d => d.Name == "Spiritual Gifts") == null) { var fieldTypeService = new FieldTypeService(rockContext); //creates Defined Type var newDefinedType = new DefinedType(); newDefinedType.IsSystem = false; newDefinedType.FieldTypeId = fieldTypeService.Queryable().Where(f => f.Name == "Text").Select(f => f.Id).FirstOrDefault(); newDefinedType.Name = "Spiritual Gifts"; newDefinedType.Description = "Defined Type for Spiritual Gifts values"; newDefinedType.CategoryId = categoryList.Find(c => c.Name == "Person").Id; //var newDTContext = new RockContext(); rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.DefinedTypes.Add(newDefinedType); rockContext.SaveChanges(DisableAudit); }); } //checks if Defined Value exists var spiritualGiftsDefineType = new DefinedTypeService(rockContext).Queryable().Where(d => d.Name == "Spiritual Gifts").FirstOrDefault(); string attributeName = row["AttributeName"] as string; int? giftAttributeId = row["GiftAttributeID"] as int?; if (definedValueList.Find(d => d.DefinedTypeId == spiritualGiftsDefineType.Id && d.Value == attributeName) == null) { var definedTypeService = new DefinedTypeService(rockContext); //creates Defined Value var newDefinedValue = new DefinedValue(); newDefinedValue.IsSystem = false; newDefinedValue.DefinedTypeId = definedTypeService.Queryable().Where(d => d.Name == "Spiritual Gifts").Select(d => d.Id).FirstOrDefault(); newDefinedValue.Value = attributeName; newDefinedValue.Description = "Spiritual Gift attribute value: " + attributeName; newDefinedValue.ForeignId = Convert.ToString(giftAttributeId); //var newDVContext = new RockContext(); rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.DefinedValues.Add(newDefinedValue); rockContext.SaveChanges(DisableAudit); }); } completed++; if (completed % percentage < 1) { int percentComplete = completed / percentage; ReportProgress(percentComplete, string.Format("{0:N0} spiritual gifts attributes imported ({1}% complete).", completed, percentComplete)); } else if (completed % ReportingNumber < 1) { ReportPartialProgress(); } } ReportProgress(100, string.Format("Finished spiritual gifts import: {0:N0} spiritual gifts attributes imported.", completed)); }
/// <summary> /// Handles the Click event of the btnSaveDefinedValue 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 btnSaveValue_Click(object sender, EventArgs e) { DefinedValue definedValue; var rockContext = new RockContext(); DefinedValueService definedValueService = new DefinedValueService(rockContext); int definedValueId = hfDefinedValueId.ValueAsInt(); if (definedValueId.Equals(0)) { int definedTypeId = hfDefinedTypeId.ValueAsInt(); definedValue = new DefinedValue { Id = 0 }; definedValue.DefinedTypeId = definedTypeId; definedValue.IsSystem = false; var orders = definedValueService.Queryable() .Where(d => d.DefinedTypeId == definedTypeId) .Select(d => d.Order) .ToList(); definedValue.Order = orders.Any() ? orders.Max() + 1 : 0; } else { definedValue = definedValueService.Get(definedValueId); } definedValue.Value = tbValueName.Text; definedValue.Description = tbValueDescription.Text; definedValue.LoadAttributes(); Rock.Attribute.Helper.GetEditValues(phDefinedValueAttributes, definedValue); if (!Page.IsValid) { return; } if (!definedValue.IsValid) { // Controls will render the error messages return; } Rock.Web.Cache.DefinedTypeCache.Flush(definedValue.DefinedTypeId); Rock.Web.Cache.DefinedValueCache.Flush(definedValue.Id); rockContext.WrapTransaction(() => { if (definedValue.Id.Equals(0)) { definedValueService.Add(definedValue); } rockContext.SaveChanges(); definedValue.SaveAttributeValues(rockContext); }); BindDefinedValuesGrid(); hfDefinedValueId.Value = string.Empty; modalValue.Hide(); }
/// <summary> /// Maps the contribution. /// </summary> /// <param name="csvData">The table data.</param> private int MapContribution(CSVInstance csvData) { var lookupContext = new RockContext(); var currencyTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE)); var currencyTypeACH = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH))).Id; var currencyTypeCash = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CASH))).Id; var currencyTypeCheck = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK))).Id; var currencyTypeCreditCard = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD))).Id; var currencyTypeNonCash = currencyTypes.DefinedValues.Where(dv => dv.Value.Equals("Non-Cash")).Select(dv => (int?)dv.Id).FirstOrDefault(); if (currencyTypeNonCash == null) { var newTenderNonCash = new DefinedValue { Value = "Non-Cash", Description = "Non-Cash", DefinedTypeId = currencyTypes.Id }; lookupContext.DefinedValues.Add(newTenderNonCash); lookupContext.SaveChanges(); currencyTypeNonCash = newTenderNonCash.Id; } var creditCardTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE)).DefinedValues; var sourceTypeOnsite = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_ONSITE_COLLECTION), lookupContext).Id; var sourceTypeWebsite = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_WEBSITE), lookupContext).Id; var sourceTypeKiosk = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_KIOSK), lookupContext).Id; var refundReasons = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON), lookupContext).DefinedValues; var accountList = new FinancialAccountService(lookupContext).Queryable().AsNoTracking().ToList(); int?defaultBatchId = null; if (ImportedBatches.ContainsKey(0)) { defaultBatchId = ImportedBatches[0]; } // Look for custom attributes in the Contribution file var allFields = csvData.TableNodes.FirstOrDefault().Children.Select((node, index) => new { node = node, index = index }).ToList(); var customAttributes = allFields .Where(f => f.index > ContributionCreditCardType) .ToDictionary(f => f.index, f => f.node.Name); // Get all imported contributions var importedContributions = new FinancialTransactionService(lookupContext).Queryable().AsNoTracking() .Where(c => c.ForeignId != null) .Select(t => (int)t.ForeignId) .OrderBy(t => t).ToList(); // List for batching new contributions var newTransactions = new List <FinancialTransaction>(); var completed = 0; ReportProgress(0, $"Verifying contribution import ({importedContributions.Count:N0} already exist)."); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { var individualIdKey = row[IndividualID]; var contributionIdKey = row[ContributionID]; var contributionId = contributionIdKey.AsType <int?>(); if (contributionId != null && !importedContributions.Contains((int)contributionId)) { var transaction = new FinancialTransaction { CreatedByPersonAliasId = ImportPersonAliasId, ModifiedByPersonAliasId = ImportPersonAliasId, TransactionTypeValueId = TransactionTypeContributionId, ForeignKey = contributionId.ToString(), ForeignId = contributionId }; int?giverAliasId = null; var personKeys = GetPersonKeys(individualIdKey); if (personKeys != null && personKeys.PersonAliasId > 0) { giverAliasId = personKeys.PersonAliasId; transaction.CreatedByPersonAliasId = giverAliasId; transaction.AuthorizedPersonAliasId = giverAliasId; transaction.ProcessedByPersonAliasId = giverAliasId; } else if (AnonymousGiverAliasId != null && AnonymousGiverAliasId > 0) { giverAliasId = AnonymousGiverAliasId; transaction.AuthorizedPersonAliasId = giverAliasId; transaction.ProcessedByPersonAliasId = giverAliasId; } var summary = row[Memo] as string; if (!string.IsNullOrWhiteSpace(summary)) { transaction.Summary = summary; } var batchIdKey = row[ContributionBatchID]; var batchId = batchIdKey.AsType <int?>(); if (batchId != null && ImportedBatches.Any(b => b.Key.Equals(batchId))) { transaction.BatchId = ImportedBatches.FirstOrDefault(b => b.Key.Equals(batchId)).Value; } else { // use the default batch for any non-matching transactions transaction.BatchId = defaultBatchId; } var receivedDateKey = row[ReceivedDate]; var receivedDate = receivedDateKey.AsType <DateTime?>(); if (receivedDate != null) { transaction.TransactionDateTime = receivedDate; transaction.CreatedDateTime = receivedDate; transaction.ModifiedDateTime = ImportDateTime; } var contributionType = row[ContributionTypeName]; var creditCardType = row[ContributionCreditCardType]; if (!string.IsNullOrWhiteSpace(contributionType)) { // set default source to onsite, exceptions listed below transaction.SourceTypeValueId = sourceTypeOnsite; int?paymentCurrencyTypeId = null, creditCardTypeId = null; if (contributionType.Equals("cash", StringComparison.CurrentCultureIgnoreCase)) { paymentCurrencyTypeId = currencyTypeCash; } else if (contributionType.Equals("check", StringComparison.CurrentCultureIgnoreCase)) { paymentCurrencyTypeId = currencyTypeCheck; } else if (contributionType.Equals("ach", StringComparison.CurrentCultureIgnoreCase)) { paymentCurrencyTypeId = currencyTypeACH; transaction.SourceTypeValueId = sourceTypeWebsite; } else if (contributionType.Equals("credit card", StringComparison.CurrentCultureIgnoreCase)) { paymentCurrencyTypeId = currencyTypeCreditCard; transaction.SourceTypeValueId = sourceTypeWebsite; // Determine CC Type if (!string.IsNullOrWhiteSpace(creditCardType)) { creditCardTypeId = creditCardTypes.Where(c => c.Value.StartsWith(creditCardType, StringComparison.CurrentCultureIgnoreCase) || c.Description.StartsWith(creditCardType, StringComparison.CurrentCultureIgnoreCase)) .Select(c => c.Id).FirstOrDefault(); } } else { paymentCurrencyTypeId = currencyTypeNonCash; } var paymentDetail = new FinancialPaymentDetail { CreatedDateTime = receivedDate, CreatedByPersonAliasId = giverAliasId, ModifiedDateTime = ImportDateTime, ModifiedByPersonAliasId = giverAliasId, CurrencyTypeValueId = paymentCurrencyTypeId, CreditCardTypeValueId = creditCardTypeId, ForeignKey = contributionId.ToString(), ForeignId = contributionId }; transaction.FinancialPaymentDetail = paymentDetail; } var transactionCode = row[CheckNumber] as string; // if transaction code provided, put it in the transaction code if (!string.IsNullOrEmpty(transactionCode)) { transaction.TransactionCode = transactionCode; // check for SecureGive kiosk transactions if (transactionCode.StartsWith("SG")) { transaction.SourceTypeValueId = sourceTypeKiosk; } } var fundName = row[FundName] as string; var subFund = row[SubFundName] as string; var fundGLAccount = row[FundGLAccount] as string; var subFundGLAccount = row[SubFundGLAccount] as string; var isFundActiveKey = row[FundIsActive]; var isFundActive = isFundActiveKey.AsType <bool?>(); var isSubFundActiveKey = row[SubFundIsActive]; var isSubFundActive = isSubFundActiveKey.AsType <bool?>(); var statedValueKey = row[StatedValue]; var statedValue = statedValueKey.AsType <decimal?>(); var amountKey = row[Amount]; var amount = amountKey.AsType <decimal?>(); if (!string.IsNullOrWhiteSpace(fundName) & amount != null) { int transactionAccountId; var parentAccount = accountList.FirstOrDefault(a => a.Name.Equals(fundName.Truncate(50))); if (parentAccount == null) { parentAccount = AddAccount(lookupContext, fundName, fundGLAccount, null, null, isFundActive, null, null, null, null, "", "", null); accountList.Add(parentAccount); } if (!string.IsNullOrWhiteSpace(subFund)) { int?campusFundId = null; // assign a campus if the subfund is a campus fund var campusFund = CampusList.FirstOrDefault(c => subFund.Contains(c.Name) || subFund.Contains(c.ShortCode)); if (campusFund != null) { campusFundId = campusFund.Id; } // add info to easily find/assign this fund in the view subFund = $"{fundName} {subFund}"; var childAccount = accountList.FirstOrDefault(c => c.Name.Equals(subFund.Truncate(50)) && c.ParentAccountId == parentAccount.Id); if (childAccount == null) { // create a child account with a campusId if it was set childAccount = AddAccount(lookupContext, subFund, subFundGLAccount, campusFundId, parentAccount.Id, isSubFundActive, null, null, null, null, "", "", null); accountList.Add(childAccount); } transactionAccountId = childAccount.Id; } else { transactionAccountId = parentAccount.Id; } if (amount == 0 && statedValue != null && statedValue != 0) { amount = statedValue; } var transactionDetail = new FinancialTransactionDetail { Amount = (decimal)amount, CreatedDateTime = receivedDate, AccountId = transactionAccountId }; transaction.TransactionDetails.Add(transactionDetail); if (amount < 0) { transaction.RefundDetails = new FinancialTransactionRefund(); transaction.RefundDetails.CreatedDateTime = receivedDate; transaction.RefundDetails.RefundReasonValueId = refundReasons.Where(dv => summary != null && dv.Value.Contains(summary)) .Select(dv => (int?)dv.Id).FirstOrDefault(); transaction.RefundDetails.RefundReasonSummary = summary; } } newTransactions.Add(transaction); completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, $"{completed:N0} contributions imported."); } else if (completed % ReportingNumber < 1) { SaveContributions(newTransactions); newTransactions.Clear(); ReportPartialProgress(); } } } if (newTransactions.Any()) { SaveContributions(newTransactions); } ReportProgress(100, $"Finished contribution import: {completed:N0} contributions imported."); return(completed); }
protected void dlgPackage_SaveClick( object sender, EventArgs e ) { int definedValueId = hfDefinedValueId.Value.AsInteger(); var definedType = DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.PROTECT_MY_MINISTRY_PACKAGES.AsGuid() ); if ( definedType != null ) { using ( var rockContext = new RockContext() ) { var service = new DefinedValueService( rockContext ); DefinedValue definedValue = null; if ( !definedValueId.Equals( 0 ) ) { definedValue = service.Get( definedValueId ); } if ( definedValue == null ) { definedValue = new DefinedValue(); definedValue.DefinedTypeId = definedType.Id; service.Add( definedValue ); } definedValue.Value = tbTitle.Text; definedValue.Description = tbDescription.Text; rockContext.SaveChanges(); definedValue.LoadAttributes( rockContext ); Guid? dvJurisdicationCodeGuid = null; int? dvJurisdictionCodeId = ddlMVRJurisdication.SelectedValueAsInt(); if ( dvJurisdictionCodeId.HasValue && dvJurisdictionCodeId.Value > 0 ) { var dvJurisdicationCode = DefinedValueCache.Read( dvJurisdictionCodeId.Value ); if ( dvJurisdicationCode != null ) { dvJurisdicationCodeGuid = dvJurisdicationCode.Guid; } } definedValue.SetAttributeValue( "PMMPackageName", tbPackageName.Text ); definedValue.SetAttributeValue( "DefaultCounty", tbDefaultCounty.Text ); definedValue.SetAttributeValue( "SendHomeCounty", cbSendCounty.Checked.ToString() ); definedValue.SetAttributeValue( "DefaultState", tbDefaultState.Text ); definedValue.SetAttributeValue( "SendHomeState", cbSendState.Checked.ToString() ); definedValue.SetAttributeValue( "MVRJurisdiction", dvJurisdicationCodeGuid.HasValue ? dvJurisdicationCodeGuid.Value.ToString() : string.Empty ); definedValue.SetAttributeValue( "SendHomeStateMVR", cbSendStateMVR.Checked.ToString() ); definedValue.SaveAttributeValues( rockContext ); DefinedTypeCache.Flush( definedType.Id ); DefinedValueCache.Flush( definedValue.Id ); } } BindPackageGrid(); HideDialog(); }
/// <summary> /// Maps the Giftedness Program. /// </summary> /// <param name="tableData">The table data.</param> private void MapGiftednessProgram( IQueryable<Row> tableData ) { int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Verifying Giftedness Program import ({0:N0} found).", totalRows ) ); foreach ( var row in tableData ) { var rockContext = new RockContext(); var categoryList = new CategoryService( rockContext ).Queryable().ToList(); var attributeList = new AttributeService( rockContext ).Queryable().ToList(); var definedTypeList = new DefinedTypeService( rockContext ).Queryable().ToList(); var definedValueList = new DefinedValueService( rockContext ).Queryable().ToList(); //check if category exists string category = row["CategoryName"] as string; if ( categoryList.Find( c => c.Name == category ) == null ) { var entityType = new EntityTypeService( rockContext ); //creates if category doesn't exist var newCategory = new Category(); newCategory.IsSystem = false; newCategory.EntityTypeId = entityType.Queryable().Where( e => e.Name == "Rock.Model.Attribute" ).Select( e => e.Id ).FirstOrDefault(); newCategory.EntityTypeQualifierColumn = "EntityTypeId"; newCategory.EntityTypeQualifierValue = Convert.ToString( PersonEntityTypeId ); //Convert.ToString(entityType.Queryable().Where( e => e.Name == "Rock.Model.Person" ).Select( e => e.Id ).FirstOrDefault()); newCategory.Name = category; newCategory.Description = "Contains the spiritual gifts attributes"; //var newCategoryContext = new RockContext(); //newCategoryContext.WrapTransaction( () => //{ // newCategoryContext.Configuration.AutoDetectChangesEnabled = false; // newCategoryContext.Categories.Add( newCategory ); // newCategoryContext.SaveChanges( DisableAudit ); //} ); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Categories.Add( newCategory ); rockContext.SaveChanges( DisableAudit ); } ); } //Check if Attribute exists if ( attributeList.Find( a => a.Key == "Rank1" ) == null || attributeList.Find( a => a.Key == "Rank2" ) == null || attributeList.Find( a => a.Key == "Rank3" ) == null || attributeList.Find( a => a.Key == "Rank4" ) == null ) { var fieldType = new FieldTypeService( rockContext ); var newAttributeList = new List<Rock.Model.Attribute>(); var fieldTypeId = fieldType.Queryable().Where( e => e.Name == "Defined Value" ).FirstOrDefault().Id; var category2 = new CategoryService( rockContext ).Queryable().Where( gt => gt.Name == "Spiritual Gifts" ).FirstOrDefault(); if ( attributeList.Find( a => a.Key == "Rank1" ) == null ) { //Creates if attribute doesn't exist var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "Rank1"; newAttribute.Name = "Rank 1"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Rank 1"; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.Categories = new List<Category>(); newAttribute.Categories.Add( category2 ); newAttributeList.Add( newAttribute ); } if ( attributeList.Find( a => a.Key == "Rank2" ) == null ) { //Creates if attribute doesn't exist var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "Rank2"; newAttribute.Name = "Rank 2"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Rank 2"; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.Categories = new List<Category>(); newAttribute.Categories.Add( category2 ); newAttributeList.Add( newAttribute ); } if ( attributeList.Find( a => a.Key == "Rank3" ) == null ) { //Creates if attribute doesn't exist var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "Rank3"; newAttribute.Name = "Rank 3"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Rank 3"; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.Categories = new List<Category>(); newAttribute.Categories.Add( category2 ); newAttributeList.Add( newAttribute ); } if ( attributeList.Find( a => a.Key == "Rank4" ) == null ) { //Creates if attribute doesn't exist var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "Rank4"; newAttribute.Name = "Rank 4"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Rank 4"; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.Categories = new List<Category>(); newAttribute.Categories.Add( category2 ); newAttributeList.Add( newAttribute ); } if ( newAttributeList.Any() ) { //var newAttributeContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Attributes.AddRange( newAttributeList ); rockContext.SaveChanges( DisableAudit ); newAttributeList.Clear(); } ); } } //checks if Defined Type exists if ( definedTypeList.Find( d => d.Name == "Spiritual Gifts" ) == null ) { var fieldTypeService = new FieldTypeService( rockContext ); //creates Defined Type var newDefinedType = new DefinedType(); newDefinedType.IsSystem = false; newDefinedType.FieldTypeId = fieldTypeService.Queryable().Where( f => f.Name == "Text" ).Select( f => f.Id ).FirstOrDefault(); newDefinedType.Name = "Spiritual Gifts"; newDefinedType.Description = "Defined Type for Spiritual Gifts values"; newDefinedType.CategoryId = categoryList.Find( c => c.Name == "Person" ).Id; //var newDTContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.DefinedTypes.Add( newDefinedType ); rockContext.SaveChanges( DisableAudit ); } ); } //checks if Defined Value exists var spiritualGiftsDefineType = new DefinedTypeService( rockContext ).Queryable().Where( d => d.Name == "Spiritual Gifts" ).FirstOrDefault(); string attributeName = row["AttributeName"] as string; int? giftAttributeId = row["GiftAttributeID"] as int?; if ( definedValueList.Find( d => d.DefinedTypeId == spiritualGiftsDefineType.Id && d.Value == attributeName ) == null ) { var definedTypeService = new DefinedTypeService( rockContext ); //creates Defined Value var newDefinedValue = new DefinedValue(); newDefinedValue.IsSystem = false; newDefinedValue.DefinedTypeId = definedTypeService.Queryable().Where( d => d.Name == "Spiritual Gifts" ).Select( d => d.Id ).FirstOrDefault(); newDefinedValue.Value = attributeName; newDefinedValue.Description = "Spiritual Gift attribute value: " + attributeName; newDefinedValue.ForeignId = Convert.ToString(giftAttributeId); //var newDVContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.DefinedValues.Add( newDefinedValue ); rockContext.SaveChanges( DisableAudit ); } ); } completed++; if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} spiritual gifts attributes imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { ReportPartialProgress(); } } ReportProgress( 100, string.Format( "Finished spiritual gifts import: {0:N0} spiritual gifts attributes imported.", completed ) ); }
/// <summary> /// Loads the individual data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadIndividuals( CSVInstance csvData ) { var lookupContext = new RockContext(); var groupTypeRoleService = new GroupTypeRoleService( lookupContext ); var groupMemberService = new GroupMemberService( lookupContext ); // Marital statuses: Married, Single, Separated, etc var maritalStatusTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS ), lookupContext ).DefinedValues; // Connection statuses: Member, Visitor, Attendee, etc var connectionStatusTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS ), lookupContext ).DefinedValues; int memberConnectionStatusId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER ) ).Id; int visitorConnectionStatusId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR ) ).Id; int attendeeConnectionStatusId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_ATTENDEE ) ).Id; // Suffix type: Dr., Jr., II, etc var suffixTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_SUFFIX ), lookupContext ).DefinedValues; // Title type: Mr., Mrs. Dr., etc var titleTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_TITLE ), lookupContext ).DefinedValues; // Record statuses: Active, Inactive, Pending int? recordStatusActiveId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE ), lookupContext ).Id; int? recordStatusInactiveId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ), lookupContext ).Id; int? recordStatusPendingId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING ), lookupContext ).Id; // Deceased record status reason (others available: No Activity, Moved, etc) var recordStatusDeceasedId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_REASON_DECEASED ) ).Id; // Record type: Person int? personRecordTypeId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON ), lookupContext ).Id; // Group roles: Owner, Adult, Child, others GroupTypeRole ownerRole = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER ) ); int adultRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ).Id; int childRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) ).Id; // Phone types: Home, Work, Mobile var numberTypeValues = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ), lookupContext ).DefinedValues; // Personal note type id var personalNoteTypeId = new NoteTypeService( lookupContext ).Get( new Guid( Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE ) ).Id; // School defined type var schoolDefinedType = DefinedTypeCache.Read( new Guid( "576FF1E2-6225-4565-A16D-230E26167A3D" ) ); // Look up existing Person attributes var personAttributes = new AttributeService( lookupContext ).GetByEntityTypeId( PersonEntityTypeId ).ToList(); var schoolAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "School" ) ); // Text field type id int textFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.TEXT ), lookupContext ).Id; int dateFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.DATE ), lookupContext ).Id; // Attribute entity type id int attributeEntityTypeId = EntityTypeCache.Read( "Rock.Model.Attribute" ).Id; // Visit info category var visitInfoCategory = new CategoryService( lookupContext ).GetByEntityTypeId( attributeEntityTypeId ) .Where( c => c.Name == "Visit Information" ).FirstOrDefault(); // Look for custom attributes in the Individual file var allFields = csvData.TableNodes.FirstOrDefault().Children.Select( ( node, index ) => new { node = node, index = index } ).ToList(); Dictionary<int, string> customAttributes = allFields .Where( f => f.index > SecurityNote ) .ToDictionary( f => f.index, f => f.node.Name.RemoveWhitespace() ); // Add any attributes if they don't already exist if ( customAttributes.Any() ) { var newAttributes = new List<Rock.Model.Attribute>(); foreach ( var newAttributePair in customAttributes.Where( ca => !personAttributes.Any( a => a.Key == ca.Value ) ) ) { var newAttribute = new Rock.Model.Attribute(); newAttribute.Name = newAttributePair.Value; newAttribute.Key = newAttributePair.Value.RemoveWhitespace(); newAttribute.Description = newAttributePair.Value + " created by CSV import"; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.FieldTypeId = textFieldTypeId; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsGridColumn = false; newAttribute.IsRequired = false; newAttribute.Order = 0; newAttributes.Add( newAttribute ); } lookupContext.Attributes.AddRange( newAttributes ); lookupContext.SaveChanges( DisableAuditing ); personAttributes.AddRange( newAttributes ); } // Set the supported date formats var dateFormats = new[] { "yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy" }; var currentFamilyGroup = new Group(); var newFamilyList = new List<Group>(); var newVisitorList = new List<Group>(); var newNoteList = new List<Note>(); int completed = 0; int newFamilies = 0; int newPeople = 0; ReportProgress( 0, string.Format( "Starting Individual import ({0:N0} already exist).", ImportedPeopleKeys.Count() ) ); string[] row; row = csvData.Database.FirstOrDefault(); while ( row != null ) { int groupRoleId = adultRoleId; bool isFamilyRelationship = true; string rowFamilyName = row[FamilyName]; string rowFamilyKey = row[FamilyId]; string rowPersonKey = row[PersonId]; int? rowFamilyId = rowFamilyKey.AsType<int?>(); int? rowPersonId = rowPersonKey.AsType<int?>(); // Check that this person isn't already in our data var personExists = ImportedFamilies.Any( g => g.Members.Any( m => m.Person.ForeignKey == rowPersonKey ) ); if ( !personExists ) { #region person create var person = new Person(); person.ForeignKey = rowPersonKey; person.ForeignId = rowPersonId; person.SystemNote = string.Format( "Imported via Excavator on {0}", ImportDateTime ); person.RecordTypeValueId = personRecordTypeId; person.CreatedByPersonAliasId = ImportPersonAliasId; string firstName = row[FirstName].Left( 50 ); string nickName = row[NickName].Left( 50 ); person.FirstName = firstName; person.NickName = string.IsNullOrWhiteSpace( nickName ) ? firstName : nickName; person.MiddleName = row[MiddleName].Left( 50 ); person.LastName = row[LastName].Left( 50 ); DateTime createdDateValue; if ( DateTime.TryParseExact( row[CreatedDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDateValue ) ) { person.CreatedDateTime = createdDateValue; person.ModifiedDateTime = ImportDateTime; } else { person.CreatedDateTime = ImportDateTime; person.ModifiedDateTime = ImportDateTime; } DateTime birthDate; if ( DateTime.TryParseExact( row[DateOfBirth], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate ) ) { person.BirthDay = birthDate.Day; person.BirthMonth = birthDate.Month; person.BirthYear = birthDate.Year; } DateTime graduationDate; if ( DateTime.TryParseExact( row[GraduationDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out graduationDate ) ) { person.GraduationYear = graduationDate.Year; } DateTime anniversary; if ( DateTime.TryParseExact( row[Anniversary], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out anniversary ) ) { person.AnniversaryDate = anniversary; } string gender = row[Gender]; if ( gender != null ) { switch ( gender.Trim().ToLower() ) { case "m": case "male": person.Gender = Rock.Model.Gender.Male; break; case "f": case "female": person.Gender = Rock.Model.Gender.Female; break; default: person.Gender = Rock.Model.Gender.Unknown; break; } } string prefix = row[Prefix]; if ( !string.IsNullOrWhiteSpace( prefix ) ) { prefix = prefix.RemoveSpecialCharacters().Trim(); person.TitleValueId = titleTypes.Where( s => prefix == s.Value.RemoveSpecialCharacters() ) .Select( s => (int?)s.Id ).FirstOrDefault(); } string suffix = row[Suffix]; if ( !string.IsNullOrWhiteSpace( suffix ) ) { suffix = suffix.RemoveSpecialCharacters().Trim(); person.SuffixValueId = suffixTypes.Where( s => suffix == s.Value.RemoveSpecialCharacters() ) .Select( s => (int?)s.Id ).FirstOrDefault(); } string maritalStatus = row[MaritalStatus]; if ( !string.IsNullOrWhiteSpace( maritalStatus ) ) { person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Value == maritalStatus ) .Select( dv => (int?)dv.Id ).FirstOrDefault(); } else { person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Value == "Unknown" ) .Select( dv => ( int? )dv.Id ).FirstOrDefault(); } string familyRole = row[FamilyRole]; if ( !string.IsNullOrWhiteSpace( familyRole ) ) { if ( familyRole == "Visitor" ) { isFamilyRelationship = false; } if ( familyRole == "Child" || person.Age < 18 ) { groupRoleId = childRoleId; } } string connectionStatus = row[ConnectionStatus]; if ( !string.IsNullOrWhiteSpace( connectionStatus ) ) { if ( connectionStatus == "Member" ) { person.ConnectionStatusValueId = memberConnectionStatusId; } else if ( connectionStatus == "Visitor" ) { person.ConnectionStatusValueId = visitorConnectionStatusId; } else { // look for user-defined connection type or default to Attendee var customConnectionType = connectionStatusTypes.Where( dv => dv.Value == connectionStatus ) .Select( dv => (int?)dv.Id ).FirstOrDefault(); person.ConnectionStatusValueId = customConnectionType ?? attendeeConnectionStatusId; person.RecordStatusValueId = recordStatusActiveId; } } string recordStatus = row[RecordStatus]; if ( !string.IsNullOrWhiteSpace( recordStatus ) ) { switch ( recordStatus.Trim().ToLower() ) { case "active": person.RecordStatusValueId = recordStatusActiveId; break; case "inactive": person.RecordStatusValueId = recordStatusInactiveId; break; default: person.RecordStatusValueId = recordStatusPendingId; break; } } string isDeceasedValue = row[IsDeceased]; if ( !string.IsNullOrWhiteSpace( isDeceasedValue ) ) { switch ( isDeceasedValue.Trim().ToLower() ) { case "y": case "yes": person.IsDeceased = true; person.RecordStatusReasonValueId = recordStatusDeceasedId; person.RecordStatusValueId = recordStatusInactiveId; break; default: person.IsDeceased = false; break; } } var personNumbers = new Dictionary<string, string>(); personNumbers.Add( "Home", row[HomePhone] ); personNumbers.Add( "Mobile", row[MobilePhone] ); personNumbers.Add( "Work", row[WorkPhone] ); string smsAllowed = row[AllowSMS]; foreach ( var numberPair in personNumbers.Where( n => !string.IsNullOrWhiteSpace( n.Value ) ) ) { var extension = string.Empty; var countryCode = Rock.Model.PhoneNumber.DefaultCountryCode(); var normalizedNumber = string.Empty; var countryIndex = numberPair.Value.IndexOf( '+' ); int extensionIndex = numberPair.Value.LastIndexOf( 'x' ) > 0 ? numberPair.Value.LastIndexOf( 'x' ) : numberPair.Value.Length; if ( countryIndex >= 0 ) { countryCode = numberPair.Value.Substring( countryIndex, countryIndex + 3 ).AsNumeric(); normalizedNumber = numberPair.Value.Substring( countryIndex + 3, extensionIndex - 3 ).AsNumeric().TrimStart( new Char[] { '0' } ); extension = numberPair.Value.Substring( extensionIndex ); } else if ( extensionIndex > 0 ) { normalizedNumber = numberPair.Value.Substring( 0, extensionIndex ).AsNumeric(); extension = numberPair.Value.Substring( extensionIndex ).AsNumeric(); } else { normalizedNumber = numberPair.Value.AsNumeric(); } if ( !string.IsNullOrWhiteSpace( normalizedNumber ) ) { var currentNumber = new PhoneNumber(); currentNumber.CountryCode = countryCode; currentNumber.CreatedByPersonAliasId = ImportPersonAliasId; currentNumber.Extension = extension.Left( 20 ); currentNumber.Number = normalizedNumber.TrimStart( new Char[] { '0' } ).Left( 20 ); currentNumber.NumberFormatted = PhoneNumber.FormattedNumber( currentNumber.CountryCode, currentNumber.Number ); currentNumber.NumberTypeValueId = numberTypeValues.Where( v => v.Value.Equals( numberPair.Key ) ) .Select( v => ( int? )v.Id ).FirstOrDefault(); if ( numberPair.Key == "Mobile" ) { switch ( smsAllowed.Trim().ToLower() ) { case "y": case "yes": case "active": currentNumber.IsMessagingEnabled = true; break; default: currentNumber.IsMessagingEnabled = false; break; } } person.PhoneNumbers.Add( currentNumber ); } } // Map Person attributes person.Attributes = new Dictionary<string, AttributeCache>(); person.AttributeValues = new Dictionary<string, AttributeValueCache>(); bool isEmailActive; switch ( row[IsEmailActive].Trim().ToLower() ) { case "n": case "no": case "inactive": isEmailActive = false; break; default: isEmailActive = true; break; } EmailPreference emailPreference; switch ( row[AllowBulkEmail].Trim().ToLower() ) { case "n": case "no": case "inactive": emailPreference = EmailPreference.NoMassEmails; break; default: emailPreference = EmailPreference.EmailAllowed; break; } person.EmailPreference = emailPreference; string primaryEmail = row[Email].Trim().Left( 75 ); if ( !string.IsNullOrWhiteSpace( primaryEmail ) ) { if ( primaryEmail.IsEmail() ) { person.Email = primaryEmail; person.IsEmailActive = isEmailActive; } else { LogException( "InvalidPrimaryEmail", string.Format( "PersonId: {0} - Email: {1}", rowPersonKey, primaryEmail ) ); } } string schoolName = row[School]; if ( !string.IsNullOrWhiteSpace( schoolName ) ) { // Add school if it doesn't exist Guid schoolGuid; var schoolExists = lookupContext.DefinedValues.Any( s => s.DefinedTypeId == schoolDefinedType.Id && s.Value.Equals( schoolName ) ); if ( !schoolExists ) { var newSchool = new DefinedValue(); newSchool.DefinedTypeId = schoolDefinedType.Id; newSchool.Value = schoolName; newSchool.Order = 0; lookupContext.DefinedValues.Add( newSchool ); lookupContext.SaveChanges(); schoolGuid = newSchool.Guid; } else { schoolGuid = lookupContext.DefinedValues.FirstOrDefault( s => s.Value.Equals( schoolName ) ).Guid; } AddPersonAttribute( schoolAttribute, person, schoolGuid.ToString().ToUpper() ); } foreach ( var attributePair in customAttributes ) { string newAttributeValue = row[attributePair.Key]; if ( !string.IsNullOrWhiteSpace( newAttributeValue ) ) { // check if this attribute value is a date DateTime valueAsDateTime; if ( DateTime.TryParseExact( newAttributeValue, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out valueAsDateTime ) ) { newAttributeValue = valueAsDateTime.ToString( "yyyy-MM-dd" ); } int? newAttributeId = personAttributes.Where( a => a.Key == attributePair.Value.RemoveWhitespace() ) .Select( a => (int?)a.Id ).FirstOrDefault(); if ( newAttributeId != null ) { var newAttribute = AttributeCache.Read( (int)newAttributeId ); AddPersonAttribute( newAttribute, person, newAttributeValue ); } } } // Add notes to timeline var notePairs = new Dictionary<string, string>(); notePairs.Add( "General", row[GeneralNote] ); notePairs.Add( "Medical", row[MedicalNote] ); notePairs.Add( "Security", row[SecurityNote] ); foreach ( var notePair in notePairs.Where( n => !string.IsNullOrWhiteSpace( n.Value ) ) ) { var newNote = new Note(); newNote.NoteTypeId = personalNoteTypeId; newNote.CreatedByPersonAliasId = ImportPersonAliasId; newNote.CreatedDateTime = ImportDateTime; newNote.Text = notePair.Value; newNote.ForeignKey = rowPersonKey; newNote.ForeignId = rowPersonId; newNote.Caption = string.Format( "{0} Note", notePair.Key ); if ( !notePair.Key.Equals( "General" ) ) { newNote.IsAlert = true; } newNoteList.Add( newNote ); } #endregion person create var groupMember = new GroupMember(); groupMember.Person = person; groupMember.GroupRoleId = groupRoleId; groupMember.CreatedDateTime = ImportDateTime; groupMember.ModifiedDateTime = ImportDateTime; groupMember.CreatedByPersonAliasId = ImportPersonAliasId; groupMember.GroupMemberStatus = GroupMemberStatus.Active; if ( rowFamilyKey != currentFamilyGroup.ForeignKey ) { // person not part of the previous family, see if that family exists or create a new one currentFamilyGroup = ImportedFamilies.FirstOrDefault( g => g.ForeignKey == rowFamilyKey ); if ( currentFamilyGroup == null ) { currentFamilyGroup = CreateFamilyGroup( row[FamilyName], rowFamilyKey ); newFamilyList.Add( currentFamilyGroup ); newFamilies++; } else { lookupContext.Groups.Attach( currentFamilyGroup ); lookupContext.Entry( currentFamilyGroup ).State = EntityState.Modified; } currentFamilyGroup.Members.Add( groupMember ); } else { // person is part of this family group, check if they're a visitor if ( isFamilyRelationship || currentFamilyGroup.Members.Count() < 1 ) { currentFamilyGroup.Members.Add( groupMember ); } else { var visitorFamily = CreateFamilyGroup( person.LastName + " Family", rowFamilyKey ); visitorFamily.Members.Add( groupMember ); newFamilyList.Add( visitorFamily ); newVisitorList.Add( visitorFamily ); newFamilies++; } } // look ahead 1 row string rowNextFamilyKey = "-1"; if ( (row = csvData.Database.FirstOrDefault()) != null ) { rowNextFamilyKey = row[FamilyId]; } newPeople++; completed++; if ( completed % (ReportingNumber * 10) < 1 ) { ReportProgress( 0, string.Format( "{0:N0} people imported.", completed ) ); } if ( newPeople >= ReportingNumber && rowNextFamilyKey != currentFamilyGroup.ForeignKey ) { SaveIndividuals( newFamilyList, newVisitorList, newNoteList ); lookupContext.SaveChanges(); ReportPartialProgress(); // Clear out variables currentFamilyGroup = new Group(); newFamilyList.Clear(); newVisitorList.Clear(); newNoteList.Clear(); newPeople = 0; } } else { row = csvData.Database.FirstOrDefault(); } } // Save any changes to new families if ( newFamilyList.Any() ) { SaveIndividuals( newFamilyList, newVisitorList, newNoteList ); } // Save any changes to existing families lookupContext.SaveChanges(); DetachAllInContext( lookupContext ); lookupContext.Dispose(); ReportProgress( 0, string.Format( "Finished individual import: {0:N0} families and {1:N0} people added.", newFamilies, completed ) ); return completed; }
/// <summary> /// Handles the Click event of the btnSaveValue 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 btnSaveValue_Click( object sender, EventArgs e ) { using ( new Rock.Data.UnitOfWorkScope() ) { DefinedValueService valueService = new DefinedValueService(); DefinedValue definedValue; int valueId = ( ( hfIdValue.Value ) != null && hfIdValue.Value != String.Empty ) ? Int32.Parse( hfIdValue.Value ) : 0; if ( valueId == 0 ) { definedValue = new DefinedValue(); definedValue.IsSystem = false; definedValue.DefinedTypeId = Int32.Parse( hfIdType.Value ); valueService.Add( definedValue, CurrentPersonId ); } else { Rock.Web.Cache.AttributeCache.Flush( valueId ); definedValue = valueService.Get( valueId ); } definedValue.Name = tbValueName.Text; definedValue.Description = tbValueDescription.Text; /* Parse attribute values from controls list */ if ( phAttrControl.Controls.Count > 0 ) { } valueService.Save( definedValue, CurrentPersonId ); } rGridValue_Bind( hfIdType.Value ); modalValues.Hide(); pnlValues.Visible = true; }
/// <summary> /// Adds a new defined value to a given DefinedType. /// </summary> /// <param name="stringValue">the string value of the new defined value</param> /// <param name="definedType">a defined type to which the defined value will be added.</param> /// <param name="rockContext"></param> /// <returns></returns> private DefinedValue AddDefinedTypeValue( string stringValue, DefinedType definedType, RockContext rockContext ) { DefinedValueService definedValueService = new DefinedValueService( rockContext ); DefinedTypeService definedTypeService = new DefinedTypeService( rockContext ); DefinedValue definedValue = new DefinedValue { Id = 0, IsSystem = false, Value = stringValue, Description = string.Empty, CreatedDateTime = RockDateTime.Now, DefinedTypeId = definedType.Id }; definedValueService.Add( definedValue ); rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges( disablePrePostProcessing: true ); return definedValue; }
/// <summary> /// Shows the edit person details. /// </summary> /// <param name="personId">The person identifier.</param> /// <param name="groupId">The group identifier.</param> private void ShowEditPersonDetails( int personId ) { var childGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid(); RockContext rockContext = new RockContext(); if ( ddlGroup.SelectedValueAsId().HasValue ) { var group = new GroupService( rockContext ).Get( ddlGroup.SelectedValueAsId().Value ); if ( group != null ) { hfPersonId.Value = personId.ToString(); var person = new Person(); if ( personId == 0 ) { rblRole.DataSource = group.GroupType.Roles.OrderBy( r => r.Order ).ToList(); rblRole.DataBind(); rblRole.Visible = true; rblRole.Required = true; } else { person = new PersonService( rockContext ).Get( personId ); } if ( ddlGroup.SelectedValueAsId().HasValue ) { if ( person != null ) { imgPhoto.BinaryFileId = person.PhotoId; imgPhoto.NoPictureUrl = Person.GetPersonPhotoUrl( person, 200, 200 ); ddlTitle.SelectedValue = person.TitleValueId.HasValue ? person.TitleValueId.Value.ToString() : string.Empty; tbFirstName.Text = person.FirstName; tbNickName.Text = person.NickName; tbLastName.Text = person.LastName; ddlSuffix.SelectedValue = person.SuffixValueId.HasValue ? person.SuffixValueId.Value.ToString() : string.Empty; bpBirthDay.SelectedDate = person.BirthDate; rblGender.SelectedValue = person.Gender.ConvertToString(); if ( group.Members.Where( gm => gm.PersonId == person.Id && gm.GroupRole.Guid == childGuid ).Any() ) { if ( person.GraduationYear.HasValue ) { ypGraduation.SelectedYear = person.GraduationYear.Value; } else { ypGraduation.SelectedYear = null; } ddlGradePicker.Visible = true; if ( !person.HasGraduated ?? false ) { int gradeOffset = person.GradeOffset.Value; var maxGradeOffset = ddlGradePicker.MaxGradeOffset; // keep trying until we find a Grade that has a gradeOffset that that includes the Person's gradeOffset (for example, there might be combined grades) while ( !ddlGradePicker.Items.OfType<ListItem>().Any( a => a.Value.AsInteger() == gradeOffset ) && gradeOffset <= maxGradeOffset ) { gradeOffset++; } ddlGradePicker.SetValue( gradeOffset ); } else { ddlGradePicker.SelectedIndex = 0; } } tbEmail.Text = person.Email; rblEmailPreference.SelectedValue = person.EmailPreference.ConvertToString( false ); // Person Attributes var displayedAttributeGuids = GetPersonAttributeGuids( person.Id ); if ( !displayedAttributeGuids.Any() || personId == 0 ) { pnlPersonAttributes.Visible = false; } else { pnlPersonAttributes.Visible = true; DisplayEditAttributes( person, displayedAttributeGuids, phPersonAttributes, pnlPersonAttributes, true ); } // Family Attributes if ( person.Id == CurrentPerson.Id ) { List<Guid> familyAttributeGuidList = GetAttributeValue( "FamilyAttributes" ).SplitDelimitedValues().AsGuidList(); if ( familyAttributeGuidList.Any() ) { pnlFamilyAttributes.Visible = true; DisplayEditAttributes( group, familyAttributeGuidList, phFamilyAttributes, pnlFamilyAttributes, true ); } else { pnlFamilyAttributes.Visible = false; } Guid? locationTypeGuid = GetAttributeValue( "AddressType" ).AsGuidOrNull(); if ( locationTypeGuid.HasValue ) { pnlAddress.Visible = true; var addressTypeDv = DefinedValueCache.Read( locationTypeGuid.Value ); // if address type is home enable the move and is mailing/physical if ( addressTypeDv.Guid == Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid() ) { lbMoved.Visible = true; cbIsMailingAddress.Visible = true; cbIsPhysicalAddress.Visible = true; } else { lbMoved.Visible = false; cbIsMailingAddress.Visible = false; cbIsPhysicalAddress.Visible = false; } lAddressTitle.Text = addressTypeDv.Value + " Address"; var familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull(); if ( familyGroupTypeGuid.HasValue ) { var familyGroupType = GroupTypeCache.Read( familyGroupTypeGuid.Value ); var familyAddress = new GroupLocationService( rockContext ).Queryable() .Where( l => l.Group.GroupTypeId == familyGroupType.Id && l.GroupLocationTypeValueId == addressTypeDv.Id && l.Group.Members.Any( m => m.PersonId == person.Id ) ) .FirstOrDefault(); if ( familyAddress != null ) { acAddress.SetValues( familyAddress.Location ); cbIsMailingAddress.Checked = familyAddress.IsMailingLocation; cbIsPhysicalAddress.Checked = familyAddress.IsMappedLocation; } } } } else { pnlFamilyAttributes.Visible = false; pnlAddress.Visible = false; } var mobilePhoneType = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE ) ); var phoneNumbers = new List<PhoneNumber>(); var phoneNumberTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ) ); var selectedPhoneTypeGuids = GetAttributeValue( "PhoneNumbers" ).Split( ',' ).AsGuidList(); if ( phoneNumberTypes.DefinedValues.Where( pnt => selectedPhoneTypeGuids.Contains( pnt.Guid ) ).Any() ) { foreach ( var phoneNumberType in phoneNumberTypes.DefinedValues.Where( pnt => selectedPhoneTypeGuids.Contains( pnt.Guid ) ) ) { var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberType.Id ); if ( phoneNumber == null ) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Value = phoneNumberType.Value; phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id; } else { // Update number format, just in case it wasn't saved correctly phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber( phoneNumber.CountryCode, phoneNumber.Number ); } phoneNumbers.Add( phoneNumber ); } rContactInfo.DataSource = phoneNumbers; rContactInfo.DataBind(); } } } } } pnlView.Visible = false; pnlEdit.Visible = true; }
/// <summary> /// Shows the details. /// </summary> private void ShowDetails() { var person = CurrentPerson; if ( person != null ) { imgPhoto.BinaryFileId = person.PhotoId; imgPhoto.NoPictureUrl = Person.GetPhotoUrl( null, person.Age, person.Gender ); ddlTitle.SelectedValue = person.TitleValueId.HasValue ? person.TitleValueId.Value.ToString() : string.Empty; tbFirstName.Text = person.FirstName; tbLastName.Text = person.LastName; ddlSuffix.SelectedValue = person.SuffixValueId.HasValue ? person.SuffixValueId.Value.ToString() : string.Empty; bpBirthDay.SelectedDate = person.BirthDate; rblGender.SelectedValue = person.Gender.ConvertToString(); tbEmail.Text = person.Email; var mobilePhoneType = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE ) ); var phoneNumbers = new List<PhoneNumber>(); var phoneNumberTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ) ); if ( phoneNumberTypes.DefinedValues.Any() ) { foreach ( var phoneNumberType in phoneNumberTypes.DefinedValues ) { var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberType.Id ); if ( phoneNumber == null ) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Value = phoneNumberType.Value; phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id; } else { // Update number format, just in case it wasn't saved correctly phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber( phoneNumber.CountryCode, phoneNumber.Number ); } phoneNumbers.Add( phoneNumber ); } rContactInfo.DataSource = phoneNumbers; rContactInfo.DataBind(); } } }
/// <summary> /// Check DB if school already listed in Defined Value /// </summary> /// <param name="school">The School Name</param> /// <returns>School ID as string</returns> private string checkSchool( string school ) { var lookupContext = new RockContext(); var dvService = new DefinedValueService( lookupContext ); var dtService = new DefinedTypeService( lookupContext ); int schoolDefinedTypeId = dtService.Queryable().Where( dt => dt.Name == "School" ).FirstOrDefault().Id; var schoolList = new List<DefinedValue>(); var checkedSchool = new DefinedValue(); //var schoolAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "School" ) ); //Checks if school is in DB //Gets Defined Type and seaches Defined Values for the schoolDefinedTypeId schoolList = dvService.Queryable() .Where( dv => dv.DefinedTypeId == schoolDefinedTypeId ).ToList(); //Defined Type should equal 34 (CCC) //Gets school info if it is present in DB checkedSchool = schoolList.Where(s => s.Value == school.Trim()).FirstOrDefault(); int count = 0; //If it isn't in the DB it will add it. while ( checkedSchool == null ) { var newSchool = new DefinedValue(); var newSchoolList = new List<DefinedValue>(); newSchool.IsSystem = false; newSchool.DefinedTypeId = 34; newSchool.Order = 0; newSchool.Value = school.Trim(); newSchool.Guid = new Guid(); newSchoolList.Add( newSchool ); var rockContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.DefinedValues.AddRange( newSchoolList ); rockContext.SaveChanges( DisableAudit ); } ); ReportProgress( 0, string.Format( "New School Added: {0}.", school.Trim() ) ); count++; if ( count > 3 ) { ReportProgress( 0, string.Format( "Stuck in Loop and school is not being added properly.", school.Trim() ) ); return "173"; } } //If School is already in Defined Value Table, its Id is returned. return Convert.ToString(checkedSchool.Id); throw new NotImplementedException(); }
public NamedNumber(string name, DefinedValue value) { }
/// <summary> /// Maps the person. /// </summary> /// <param name="tableData">The table data.</param> /// <param name="selectedColumns">The selected columns.</param> private void MapPerson( IQueryable<Row> tableData, List<string> selectedColumns = null ) { var lookupContext = new RockContext(); var groupTypeRoleService = new GroupTypeRoleService( lookupContext ); var dvService = new DefinedValueService( lookupContext ); var schoolList = new List<DefinedValue>(); var newSchool = new DefinedValue(); var existingSchoolLookUp = dvService.Queryable() .Where( dv => dv.DefinedTypeId == 34 ).ToList(); // Marital statuses: Married, Single, Separated, etc var maritalStatusTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS ), lookupContext ).DefinedValues; // Connection statuses: Member, Visitor, Attendee, etc var connectionStatusTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS ), lookupContext ).DefinedValues; // Record status reasons: No Activity, Moved, Deceased, etc var recordStatusReasons = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_RECORD_STATUS_REASON ), lookupContext ).DefinedValues; // Record statuses: Active, Inactive, Pending int? recordStatusActiveId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE ), lookupContext ).Id; int? recordStatusInactiveId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ), lookupContext ).Id; int? recordStatusPendingId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING ), lookupContext ).Id; // Record type: Person int? personRecordTypeId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON ), lookupContext ).Id; // Suffix type: Dr., Jr., II, etc var suffixTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_SUFFIX ) ).DefinedValues; // Title type: Mr., Mrs. Dr., etc var titleTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_TITLE ), lookupContext ).DefinedValues; // Note type: Comment int noteCommentTypeId = new NoteTypeService( lookupContext ).Get( new Guid( "7E53487C-D650-4D85-97E2-350EB8332763" ) ).Id; // Group roles: Owner, Adult, Child, others GroupTypeRole ownerRole = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER ) ); int adultRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ).Id; int childRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) ).Id; int inviteeRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_INVITED ) ).Id; int invitedByRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_INVITED_BY ) ).Id; int canCheckInRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_CAN_CHECK_IN ) ).Id; int allowCheckInByRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_ALLOW_CHECK_IN_BY ) ).Id; // Group type: Family int familyGroupTypeId = new GroupTypeService( lookupContext ).Get( new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY ) ).Id; // Look up additional Person attributes (existing) var personAttributes = new AttributeService( lookupContext ).GetByEntityTypeId( PersonEntityTypeId ).ToList(); // Cached F1 attributes: IndividualId, HouseholdId // Core attributes: PreviousChurch, Position, Employer, School var individualIdAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "F1IndividualId" ) ); var householdIdAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "F1HouseholdId" ) ); var previousChurchAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "PreviousChurch" ) ); var employerAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "Employer" ) ); var positionAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "Position" ) ); var firstVisitAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "FirstVisit" ) ); var schoolAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "School" ) ); var membershipDateAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "MembershipDate" ) ); var familyList = new List<Group>(); var visitorList = new List<Group>(); int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Verifying person import ({0:N0} found, {1:N0} already exist).", totalRows, ImportedPeople.Count() ) ); foreach ( var groupedRows in tableData.GroupBy<Row, int?>( r => r["Household_ID"] as int? ) ) { var familyGroup = new Group(); var householdCampusList = new List<string>(); foreach ( var row in groupedRows ) { bool isFamilyRelationship = true; string currentCampus = string.Empty; int? individualId = row["Individual_ID"] as int?; int? householdId = row["Household_ID"] as int?; if ( GetPersonAliasId( individualId, householdId ) == null ) { var person = new Person(); person.FirstName = row["First_Name"] as string; person.MiddleName = row["Middle_Name"] as string; person.NickName = row["Goes_By"] as string ?? person.FirstName; person.LastName = row["Last_Name"] as string; person.BirthDate = row["Date_Of_Birth"] as DateTime?; person.CreatedByPersonAliasId = ImportPersonAlias.Id; person.RecordTypeValueId = personRecordTypeId; person.ForeignId = individualId.ToString(); int groupRoleId = adultRoleId; var gender = row["Gender"] as string; if ( gender != null ) { person.Gender = (Gender)Enum.Parse( typeof( Gender ), gender ); } string prefix = row["Prefix"] as string; if ( prefix != null ) { prefix = prefix.RemoveSpecialCharacters().Trim(); person.TitleValueId = titleTypes.Where( s => prefix == s.Value.RemoveSpecialCharacters() ) .Select( s => (int?)s.Id ).FirstOrDefault(); } string suffix = row["Suffix"] as string; if ( suffix != null ) { suffix = suffix.RemoveSpecialCharacters().Trim(); person.SuffixValueId = suffixTypes.Where( s => suffix == s.Value.RemoveSpecialCharacters() ) .Select( s => (int?)s.Id ).FirstOrDefault(); } string maritalStatus = row["Marital_Status"] as string; if ( maritalStatus != null ) { person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Value == maritalStatus ) .Select( dv => (int?)dv.Id ).FirstOrDefault(); } else { person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Value == "Unknown" ) .Select( dv => (int?)dv.Id ).FirstOrDefault(); } string familyRole = row["Household_Position"].ToString().ToLower(); if ( familyRole != null ) { if ( familyRole == "visitor" ) { isFamilyRelationship = false; } if ( familyRole == "child" || person.Age < 18 ) { groupRoleId = childRoleId; } } string memberStatus = row["Status_Name"].ToString().ToLower(); string subStatus = row["SubStatus_Name"] as string; int attendeeId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_ATTENDEE ) ).Id; if ( memberStatus == "member" ) { if ( subStatus == "Baptism" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Member > Baptism" ) .Select( dv => dv.Id ).FirstOrDefault(); // ReportProgress( 0, string.Format( "***BAPTISM ConnectionStatusValueId: {0}, {1}, {2}", person.ConnectionStatusValueId, memberStatus, subStatus ) ); } else if ( subStatus == "Connected" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Member > Connected" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( subStatus == "Transfer" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Member > Transfer" ) .Select( dv => dv.Id ).FirstOrDefault(); } else { person.ConnectionStatusValueId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER ) ).Id; person.RecordStatusValueId = recordStatusActiveId; //ReportProgress( 0, string.Format( "***MEMBER ELSE ConnectionStatusValueId: {0}, {1}, {2}", person.ConnectionStatusValueId, memberStatus, subStatus ) ); } } else if ( memberStatus == "visitor" ) { person.ConnectionStatusValueId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR ) ).Id; person.RecordStatusValueId = recordStatusActiveId; } else if ( memberStatus == "deceased" ) { person.IsDeceased = true; person.RecordStatusReasonValueId = recordStatusReasons.Where( dv => dv.Value == "Deceased" ) .Select( dv => dv.Id ).FirstOrDefault(); person.RecordStatusValueId = recordStatusInactiveId; } else if (memberStatus == "dropped") //Crossroads Related { if (subStatus == "Member") { person.RecordStatusValueId = recordStatusInactiveId; person.RecordStatusReasonValueId = recordStatusReasons.Where(dv => dv.Value == "Dropped Member") .Select(dv => dv.Id).FirstOrDefault(); person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Dropped > Member" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if (subStatus == "Non-Member") { person.RecordStatusValueId = recordStatusInactiveId; person.RecordStatusReasonValueId = recordStatusReasons.Where( dv => dv.Value == "Dropped Non-Member" ) .Select(dv => dv.Id).FirstOrDefault(); person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Dropped > Non-Member" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( subStatus == "Beliefs" ) { person.RecordStatusValueId = recordStatusInactiveId; person.RecordStatusReasonValueId = recordStatusReasons.Where( dv => dv.Value == "Beliefs" ) .Select( dv => dv.Id ).FirstOrDefault(); person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Dropped > Beliefs" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( subStatus == "Disagreement" ) { person.RecordStatusValueId = recordStatusInactiveId; person.RecordStatusReasonValueId = recordStatusReasons.Where( dv => dv.Value == "Disagreement" ) .Select( dv => dv.Id ).FirstOrDefault(); person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Dropped > Disagreement" ) .Select( dv => dv.Id ).FirstOrDefault(); } else { person.RecordStatusValueId = recordStatusInactiveId; person.RecordStatusReasonValueId = recordStatusReasons.Where(dv => dv.Value == "Dropped") .Select(dv => dv.Id).FirstOrDefault(); person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Dropped" ) .Select( dv => dv.Id ).FirstOrDefault(); } } else if ( memberStatus == "child of member" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Child of Member" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "connected" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Connected" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "1st time" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "1st Time" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "2nd time" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "2nd Time" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "angel tree recipient" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Angel Tree Recipient" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "attendee" ) { if ( subStatus == "Baptism" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Attendee > Baptism" ) .Select( dv => dv.Id ).FirstOrDefault(); } else { person.ConnectionStatusValueId = attendeeId; person.RecordStatusValueId = recordStatusActiveId; //person.RecordStatusValueId = recordStatusActiveId; //person.RecordStatusReasonValueId = recordStatusReasons.Where( dv => dv.Value == "Attendee" ) // .Select( dv => dv.Id ).FirstOrDefault(); } } else if ( memberStatus == "camp only" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Camp Only" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "camp parent" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Camp Parent" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "contributor only" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Contributor Only" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "divorce care only" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Divorce Care Only" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "easter saturday 2014" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Easter Saturday 2014" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "evacuee" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Evacuee" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "event only" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Event Only" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "event prospect" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Event Prospect" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "mdo only" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "MDO Only" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "out of town" ) { if ( subStatus == "Away at College" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Out of Town > Away at College" ) .Select( dv => dv.Id ).FirstOrDefault(); } else { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Out of Town" ) .Select( dv => dv.Id ).FirstOrDefault(); } } else if ( memberStatus == "preschool playdate only" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Preschool Playdate Only" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "sports only" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Sports Only" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "supported missionary" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "Supported Missionary" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "vbs only" ) { person.RecordStatusValueId = recordStatusActiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "VBS Only" ) .Select( dv => dv.Id ).FirstOrDefault(); } else if ( memberStatus == "inactive member" ) { person.RecordStatusValueId = recordStatusInactiveId; person.ConnectionStatusValueId = connectionStatusTypes.Where( dv => dv.Value == "VBS Only" ) .Select( dv => dv.Id ).FirstOrDefault(); } else { // F1 defaults are Member & Visitor; all others are user-defined var customConnectionType = connectionStatusTypes.Where( dv => dv.Value == memberStatus ) .Select( dv => (int?)dv.Id ).FirstOrDefault(); person.ConnectionStatusValueId = customConnectionType ?? attendeeId; person.RecordStatusValueId = recordStatusActiveId; // ReportProgress( 0, string.Format( "***ELSE ConnectionStatusValueId: {0}, {1}, {2}", person.ConnectionStatusValueId, memberStatus, subStatus ) ); } //ReportProgress( 0, string.Format( "ConnectionStatusValueId: {0}, {1}, {2}, [ {3} ]", person.ConnectionStatusValueId, memberStatus, subStatus, person.RecordStatusReasonValueId ) ); string campus = row["SubStatus_Name"] as string; if ( campus != null ) { currentCampus = campus; } string status_comment = row["Status_Comment"] as string; if ( status_comment != null ) { person.SystemNote = status_comment; var noteList = new List<Note>(); //Seeing if these will add to the timeline. var note = new Note(); note.ForeignId = string.Format( "{0}", individualId ); note.Text = status_comment; note.NoteTypeId = 1; noteList.Add( note ); if ( noteList.Any() ) { var rockContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Notes.AddRange( noteList ); rockContext.SaveChanges( DisableAudit ); } ); } } // Map F1 attributes person.Attributes = new Dictionary<string, AttributeCache>(); person.AttributeValues = new Dictionary<string, AttributeValue>(); // individual_id already defined in scope AddPersonAttribute( individualIdAttribute, person, individualId.ToString() ); // household_id already defined in scope AddPersonAttribute( householdIdAttribute, person, householdId.ToString(), familyRole ); string previousChurch = row["Former_Church"] as string; AddPersonAttribute( previousChurchAttribute, person, previousChurch ); string employer = row["Employer"] as string; AddPersonAttribute( employerAttribute, person, employer ); string position = row["Occupation_Name"] as string ?? row["Occupation_Description"] as string; AddPersonAttribute( positionAttribute, person, position ); string school = row["School_Name"] as string; if ( school != null ) { school = school.Trim(); var schoolNameInList = new DefinedValue(); if ( existingSchoolLookUp.FirstOrDefault( s => s.Value == school ) != null ) { schoolNameInList = existingSchoolLookUp.FirstOrDefault( s => s.Value == school ); } if ( ( !string.IsNullOrEmpty( schoolNameInList.Value ) ) ) { person.Attributes.Add( schoolAttribute.Key, schoolAttribute ); person.AttributeValues.Add( schoolAttribute.Key, new AttributeValue() { AttributeId = schoolAttribute.Id, Value = string.Format( "{0}", existingSchoolLookUp.FirstOrDefault( s => s.Value == school ).Guid /*schoolNameInList.Guid*/), } ); } //AddPersonAttribute( schoolAttribute, person, school ); } DateTime? membershipDate = row["Status_Date"] as DateTime?; if ( membershipDate != null ) { person.CreatedDateTime = membershipDate; AddPersonAttribute( membershipDateAttribute, person, membershipDate.Value.ToString( "MM/dd/yyyy" ) ); } DateTime? firstVisit = row["First_Record"] as DateTime?; if ( firstVisit != null ) { person.CreatedDateTime = firstVisit; AddPersonAttribute( firstVisitAttribute, person, firstVisit.Value.ToString( "MM/dd/yyyy" ) ); } // Other Attributes to create: // former name // bar_code // member_env_code // denomination_name var groupMember = new GroupMember(); groupMember.Person = person; groupMember.GroupRoleId = groupRoleId; groupMember.GroupMemberStatus = GroupMemberStatus.Active; if ( isFamilyRelationship ) { householdCampusList.Add( currentCampus ); familyGroup.Members.Add( groupMember ); familyGroup.ForeignId = householdId.ToString(); } else { var visitorGroup = new Group(); visitorGroup.ForeignId = householdId.ToString(); visitorGroup.Members.Add( groupMember ); visitorGroup.GroupTypeId = familyGroupTypeId; visitorGroup.Name = person.LastName + " Family"; visitorGroup.CampusId = CampusList.Where( c => c.Name.StartsWith( currentCampus ) || c.ShortCode == currentCampus ) .Select( c => (int?)c.Id ).FirstOrDefault(); familyList.Add( visitorGroup ); completed += visitorGroup.Members.Count; visitorList.Add( visitorGroup ); } } } if ( familyGroup.Members.Any() ) { familyGroup.Name = familyGroup.Members.OrderByDescending( p => p.Person.Age ) .FirstOrDefault().Person.LastName + " Family"; familyGroup.GroupTypeId = familyGroupTypeId; string primaryHouseholdCampus = householdCampusList.GroupBy( c => c ).OrderByDescending( c => c.Count() ) .Select( c => c.Key ).FirstOrDefault(); if ( primaryHouseholdCampus != null ) { familyGroup.CampusId = CampusList.Where( c => c.Name.StartsWith( primaryHouseholdCampus ) || c.ShortCode == primaryHouseholdCampus ) .Select( c => (int?)c.Id ).FirstOrDefault(); } familyList.Add( familyGroup ); completed += familyGroup.Members.Count; if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} people imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { SavePeople( familyList, visitorList, ownerRole, childRoleId, inviteeRoleId, invitedByRoleId, canCheckInRoleId, allowCheckInByRoleId ); familyList.Clear(); visitorList.Clear(); ReportPartialProgress(); } } } // Save any remaining families in the batch if ( familyList.Any() ) { SavePeople( familyList, visitorList, ownerRole, childRoleId, inviteeRoleId, invitedByRoleId, canCheckInRoleId, allowCheckInByRoleId ); } ReportProgress( 100, string.Format( "Finished person import: {0:N0} people imported.", completed ) ); }
/// <summary> /// Maps the contribution. /// </summary> /// <param name="tableData">The table data.</param> /// <param name="totalRows">The total rows.</param> private void MapContribution(IQueryable <Row> tableData, long totalRows = 0) { var lookupContext = new RockContext(); var transactionTypeContributionId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid(), lookupContext).Id; var currencyTypes = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE)); var currencyTypeACH = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH))).Id; var currencyTypeCash = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CASH))).Id; var currencyTypeCheck = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK))).Id; var currencyTypeCreditCard = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD))).Id; var currencyTypeNonCash = currencyTypes.DefinedValues.Where(dv => dv.Value.Equals("Non-Cash")).Select(dv => ( int? )dv.Id).FirstOrDefault(); if (currencyTypeNonCash == null) { var newTenderNonCash = new DefinedValue { Value = "Non-Cash", Description = "Non-Cash", DefinedTypeId = currencyTypes.Id }; lookupContext.DefinedValues.Add(newTenderNonCash); lookupContext.SaveChanges(); currencyTypeNonCash = newTenderNonCash.Id; } var creditCardTypes = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE)).DefinedValues; var refundReasons = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON), lookupContext).DefinedValues; var accountList = new FinancialAccountService(lookupContext).Queryable().AsNoTracking().ToList(); int?defaultBatchId = null; if (ImportedBatches.ContainsKey(0)) { defaultBatchId = ImportedBatches[0]; } // Get all imported contributions var importedContributions = new FinancialTransactionService(lookupContext).Queryable().AsNoTracking() .Where(c => c.ForeignId != null) .ToDictionary(t => ( int )t.ForeignId, t => ( int? )t.Id); // List for batching new contributions var newTransactions = new List <FinancialTransaction>(); if (totalRows == 0) { totalRows = tableData.Count(); } var completedItems = 0; var percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, $"Verifying contribution import ({totalRows:N0} found, {importedContributions.Count:N0} already exist)."); foreach (var row in tableData.Where(r => r != null)) { var individualId = row["Individual_ID"] as int?; var householdId = row["Household_ID"] as int?; var contributionId = row["ContributionID"] as int?; if (contributionId.HasValue && !importedContributions.ContainsKey(( int )contributionId)) { var transaction = new FinancialTransaction { CreatedByPersonAliasId = ImportPersonAliasId, ModifiedByPersonAliasId = ImportPersonAliasId, TransactionTypeValueId = transactionTypeContributionId, ForeignKey = contributionId.ToString(), ForeignId = contributionId }; int?giverAliasId = null; var personKeys = GetPersonKeys(individualId, householdId); if (personKeys != null && personKeys.PersonAliasId > 0) { giverAliasId = personKeys.PersonAliasId; transaction.CreatedByPersonAliasId = giverAliasId; transaction.AuthorizedPersonAliasId = giverAliasId; transaction.ProcessedByPersonAliasId = giverAliasId; } var summary = row["Memo"] as string; if (!string.IsNullOrWhiteSpace(summary)) { transaction.Summary = summary; } var batchId = row["BatchID"] as int?; if (batchId.HasValue && ImportedBatches.Any(b => b.Key.Equals(batchId))) { transaction.BatchId = ImportedBatches.FirstOrDefault(b => b.Key.Equals(batchId)).Value; } else { // use the default batch for any non-matching transactions transaction.BatchId = defaultBatchId; } var receivedDate = row["Received_Date"] as DateTime?; if (receivedDate.HasValue) { transaction.TransactionDateTime = receivedDate; transaction.CreatedDateTime = receivedDate; transaction.ModifiedDateTime = ImportDateTime; } var contributionFields = row.Columns.Select(c => c.Name).ToList(); var cardType = contributionFields.Contains("Card_Type") ? row["Card_Type"] as string : string.Empty; var cardLastFour = contributionFields.Contains("Last_Four") ? row["Last_Four"] as string : string.Empty; var contributionType = contributionFields.Contains("Contribution_Type_Name") ? row["Contribution_Type_Name"] as string : string.Empty; if (!string.IsNullOrWhiteSpace(contributionType)) { // set default source to onsite, exceptions listed below transaction.SourceTypeValueId = TransactionSourceTypeOnsiteId; int?paymentCurrencyTypeId = null, creditCardTypeId = null; switch (contributionType.ToLower()) { case "cash": paymentCurrencyTypeId = currencyTypeCash; break; case "check": paymentCurrencyTypeId = currencyTypeCheck; break; case "ach": paymentCurrencyTypeId = currencyTypeACH; transaction.SourceTypeValueId = TransactionSourceTypeWebsiteId; break; case "credit card": paymentCurrencyTypeId = currencyTypeCreditCard; transaction.SourceTypeValueId = TransactionSourceTypeWebsiteId; if (!string.IsNullOrWhiteSpace(cardType)) { creditCardTypeId = creditCardTypes.Where(t => t.Value.Equals(cardType, StringComparison.CurrentCultureIgnoreCase)) .Select(t => ( int? )t.Id).FirstOrDefault(); } break; default: paymentCurrencyTypeId = currencyTypeNonCash; break; } var paymentDetail = new FinancialPaymentDetail { CreatedDateTime = receivedDate, CreatedByPersonAliasId = giverAliasId, ModifiedDateTime = ImportDateTime, ModifiedByPersonAliasId = giverAliasId, CurrencyTypeValueId = paymentCurrencyTypeId, CreditCardTypeValueId = creditCardTypeId, AccountNumberMasked = cardLastFour, ForeignKey = contributionId.ToString(), ForeignId = contributionId }; transaction.FinancialPaymentDetail = paymentDetail; } var checkNumber = row["Check_Number"] as string; // if the check number is valid, put it in the transaction code if (checkNumber.AsType <int?>().HasValue) { transaction.TransactionCode = checkNumber; } // check for SecureGive kiosk transactions else if (!string.IsNullOrWhiteSpace(checkNumber) && checkNumber.StartsWith("SG")) { transaction.SourceTypeValueId = TransactionSourceTypeKioskId; } var fundName = contributionFields.Contains("Fund_Name") ? row["Fund_Name"] as string : string.Empty; var subFund = contributionFields.Contains("Sub_Fund_Name") ? row["Sub_Fund_Name"] as string : string.Empty; var fundGLAccount = contributionFields.Contains("Fund_GL_Account") ? row["Fund_GL_Account"] as string : string.Empty; var subFundGLAccount = contributionFields.Contains("Sub_Fund_GL_Account") ? row["Sub_Fund_GL_Account"] as string : string.Empty; var isFundActive = contributionFields.Contains("Fund_Is_active") ? row["Fund_Is_active"] as string : null; var statedValue = row["Stated_Value"] as decimal?; var amount = row["Amount"] as decimal?; if (!string.IsNullOrWhiteSpace(fundName) && amount.HasValue) { int transactionAccountId; var parentAccount = accountList.FirstOrDefault(a => !a.CampusId.HasValue && a.Name.Equals(fundName.Truncate(50), StringComparison.CurrentCultureIgnoreCase)); if (parentAccount == null) { parentAccount = AddFinancialAccount(lookupContext, fundName, $"{fundName} imported {ImportDateTime}", fundGLAccount, null, null, isFundActive.AsBooleanOrNull(), receivedDate, fundName.RemoveSpecialCharacters()); accountList.Add(parentAccount); } if (!string.IsNullOrWhiteSpace(subFund)) { int?campusFundId = null; // assign a campus if the subfund is a campus fund var campusFund = CampusList.FirstOrDefault(c => subFund.StartsWith(c.Name, StringComparison.CurrentCultureIgnoreCase) || subFund.StartsWith(c.ShortCode, StringComparison.CurrentCultureIgnoreCase)); if (campusFund != null) { // use full campus name as the subfund subFund = campusFund.Name; campusFundId = campusFund.Id; } // add info to easily find/assign this fund in the view subFund = $"{subFund} {fundName}"; var childAccount = accountList.FirstOrDefault(c => c.ParentAccountId == parentAccount.Id && c.Name.Equals(subFund.Truncate(50), StringComparison.CurrentCultureIgnoreCase)); if (childAccount == null) { // create a child account with a campusId if it was set childAccount = AddFinancialAccount(lookupContext, subFund, $"{subFund} imported {ImportDateTime}", subFundGLAccount, campusFundId, parentAccount.Id, isFundActive.AsBooleanOrNull(), receivedDate, subFund.RemoveSpecialCharacters()); accountList.Add(childAccount); } transactionAccountId = childAccount.Id; } else { transactionAccountId = parentAccount.Id; } if (amount == 0 && statedValue.HasValue && statedValue != 0) { amount = statedValue; } var transactionDetail = new FinancialTransactionDetail { Amount = ( decimal )amount, CreatedDateTime = receivedDate, AccountId = transactionAccountId }; transaction.TransactionDetails.Add(transactionDetail); if (amount < 0) { transaction.RefundDetails = new FinancialTransactionRefund(); transaction.RefundDetails.CreatedDateTime = receivedDate; transaction.RefundDetails.RefundReasonValueId = refundReasons.Where(dv => summary != null && dv.Value.Contains(summary)) .Select(dv => ( int? )dv.Id).FirstOrDefault(); transaction.RefundDetails.RefundReasonSummary = summary; } } newTransactions.Add(transaction); completedItems++; if (completedItems % percentage < 1) { var percentComplete = completedItems / percentage; ReportProgress(percentComplete, $"{completedItems:N0} contributions imported ({percentComplete}% complete)."); } if (completedItems % ReportingNumber < 1) { SaveContributions(newTransactions); newTransactions.Clear(); ReportPartialProgress(); } } } if (newTransactions.Any()) { SaveContributions(newTransactions); } ReportProgress(100, $"Finished contribution import: {completedItems:N0} contributions imported."); }
/// <summary> /// Adds the account. /// </summary> /// <param name="lookupContext">The lookup context.</param> /// <param name="fundName">Name of the fund.</param> /// <param name="fundCampusId">The fund campus identifier.</param> /// <returns></returns> private FinancialAccount AddAccount(RockContext lookupContext, string fundName, int?fundCampusId, string parentAccountName = "", int?parentAcountId = null) { if (lookupContext == null) { lookupContext = new RockContext(); } var account = new FinancialAccount(); account.Name = fundName; account.PublicName = fundName; int financialAccountTypeId = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_ACCOUNT_TYPE)).Id; //Adding Account Type Value var givingAccountTypeValue = new DefinedValueService(lookupContext).Queryable().Where(d => d.DefinedTypeId == financialAccountTypeId && d.Value == "Giving").FirstOrDefault(); if (givingAccountTypeValue == null) { var accountType = new DefinedValue(); accountType.IsSystem = false; accountType.DefinedTypeId = financialAccountTypeId; accountType.Value = "Giving"; accountType.Description = "For Contributions"; lookupContext.DefinedValues.Add(accountType); lookupContext.SaveChanges(DisableAudit); } givingAccountTypeValue = new DefinedValueService(lookupContext).Queryable().Where(d => d.DefinedTypeId == financialAccountTypeId && d.Value == "Giving").FirstOrDefault(); var eventAccountTypeValue = new DefinedValueService(lookupContext).Queryable().Where(d => d.DefinedTypeId == financialAccountTypeId && d.Value == "Events/Receipts").FirstOrDefault(); if (eventAccountTypeValue == null) { var accountType = new DefinedValue(); accountType.IsSystem = false; accountType.DefinedTypeId = financialAccountTypeId; accountType.Value = "Events/Receipts"; accountType.Description = "For Events and Receipts (F1)"; lookupContext.DefinedValues.Add(accountType); lookupContext.SaveChanges(DisableAudit); } eventAccountTypeValue = new DefinedValueService(lookupContext).Queryable().Where(d => d.DefinedTypeId == financialAccountTypeId && d.Value == "Events/Receipts").FirstOrDefault(); //Crossroads funds that start with Receipts are for Event Registrations and are not Tax Deductible. if (fundName.StartsWith("Receipts -") || fundName.StartsWith("Receipt -") || parentAccountName.StartsWith("Receipt -")) { account.IsTaxDeductible = false; account.AccountTypeValueId = eventAccountTypeValue.Id; } else { account.IsTaxDeductible = true; account.AccountTypeValueId = givingAccountTypeValue.Id; } if (parentAcountId != null) { account.ParentAccountId = parentAcountId; } account.IsActive = true; account.CampusId = fundCampusId; account.CreatedByPersonAliasId = ImportPersonAlias.Id; lookupContext.FinancialAccounts.Add(account); lookupContext.SaveChanges(DisableAudit); return(account); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(System.EventArgs e) { base.OnLoad(e); pnlMessage.Controls.Clear(); pnlMessage.Visible = false; PagePanels[0] = phUserInfo; PagePanels[1] = phDuplicates; PagePanels[2] = phSendLoginInfo; PagePanels[3] = phSentLoginInfo; PagePanels[4] = phConfirmation; PagePanels[5] = phSuccess; if (!Page.IsPostBack) { DisplayUserInfo(Direction.Forward); // show/hide address and phone panels pnlAddress.Visible = GetAttributeValue("ShowAddress").AsBoolean(); pnlPhoneNumbers.Visible = GetAttributeValue("ShowPhoneNumbers").AsBoolean(); acAddress.Required = GetAttributeValue("AddressRequired").AsBoolean(); // set birthday picker required if minimum age > 0 if (GetAttributeValue("MinimumAge").AsInteger() > 0) { bdaypBirthDay.Required = true; } var phoneNumbers = new List <PhoneNumber>(); // add phone number types if (pnlPhoneNumbers.Visible) { var phoneNumberTypeDefinedType = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE)); if (!string.IsNullOrWhiteSpace(GetAttributeValue("PhoneTypes"))) { var selectedPhoneTypeGuids = GetAttributeValue("PhoneTypes").Split(',').Select(Guid.Parse).ToList(); var selectedPhoneTypes = phoneNumberTypeDefinedType.DefinedValues .Where(v => selectedPhoneTypeGuids.Contains(v.Guid)) .ToList(); foreach (var phoneNumberType in selectedPhoneTypes) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Value = phoneNumberType.Value; numberType.Guid = phoneNumberType.Guid; var phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumbers.Add(phoneNumber); } if (!string.IsNullOrWhiteSpace(GetAttributeValue("PhoneTypesRequired"))) { _RequiredPhoneNumberGuids = GetAttributeValue("PhoneTypesRequired").Split(',').Select(Guid.Parse).ToList(); } rPhoneNumbers.DataSource = phoneNumbers; rPhoneNumbers.DataBind(); } } } }
/// <summary> /// Loads the individual data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadIndividuals(CsvDataModel csvData) { var lookupContext = new RockContext(); var groupTypeRoleService = new GroupTypeRoleService(lookupContext); var groupMemberService = new GroupMemberService(lookupContext); // Marital statuses: Married, Single, Separated, etc var maritalStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS), lookupContext).DefinedValues; // Connection statuses: Member, Visitor, Attendee, etc var connectionStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS), lookupContext).DefinedValues; int memberConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER)).Id; int visitorConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR)).Id; int attendeeConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_ATTENDEE)).Id; // Suffix type: Dr., Jr., II, etc var suffixTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_SUFFIX), lookupContext).DefinedValues; // Title type: Mr., Mrs. Dr., etc var titleTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_TITLE), lookupContext).DefinedValues; // Record statuses: Active, Inactive, Pending int?recordStatusActiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE), lookupContext).Id; int?recordStatusInactiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE), lookupContext).Id; int?recordStatusPendingId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING), lookupContext).Id; // Deceased record status reason (others available: No Activity, Moved, etc) var recordStatusDeceasedId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_REASON_DECEASED)).Id; // Record type: Person int?personRecordTypeId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON), lookupContext).Id; // Group roles: Owner, Adult, Child, others GroupTypeRole ownerRole = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER)); int adultRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id; int childRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD)).Id; // Phone types: Home, Work, Mobile var numberTypeValues = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE), lookupContext).DefinedValues; // Timeline note type id var noteTimelineTypeId = new NoteTypeService(lookupContext).Get(new Guid("7E53487C-D650-4D85-97E2-350EB8332763")).Id; // School defined type var schoolDefinedType = DefinedTypeCache.Read(new Guid("576FF1E2-6225-4565-A16D-230E26167A3D")); // Look up additional Person attributes (existing) var personAttributes = new AttributeService(lookupContext).GetByEntityTypeId(PersonEntityTypeId).ToList(); // Core attributes: PreviousChurch, Position, Employer, School, etc var previousChurchAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "PreviousChurch")); var employerAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Employer")); var positionAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Position")); var firstVisitAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "FirstVisit")); var schoolAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "School")); var membershipDateAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "MembershipDate")); var baptismDateAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "BaptismDate")); var facebookAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Facebook")); var twitterAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Twitter")); var instagramAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Instagram")); // Text field type id int textFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT), lookupContext).Id; // Attribute entity type id int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id; // Visit info category var visitInfoCategory = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId) .Where(c => c.Name == "Visit Information").FirstOrDefault(); // Add a Secondary Email attribute if it doesn't exist var secondaryEmail = personAttributes.FirstOrDefault(a => a.Key == "SecondaryEmail"); if (secondaryEmail == null) { secondaryEmail = new Rock.Model.Attribute(); secondaryEmail.Key = "SecondaryEmail"; secondaryEmail.Name = "Secondary Email"; secondaryEmail.FieldTypeId = textFieldTypeId; secondaryEmail.EntityTypeId = PersonEntityTypeId; secondaryEmail.EntityTypeQualifierValue = string.Empty; secondaryEmail.EntityTypeQualifierColumn = string.Empty; secondaryEmail.Description = "The secondary email for this person"; secondaryEmail.DefaultValue = string.Empty; secondaryEmail.IsMultiValue = false; secondaryEmail.IsRequired = false; secondaryEmail.Order = 0; lookupContext.Attributes.Add(secondaryEmail); secondaryEmail.Categories.Add(visitInfoCategory); lookupContext.SaveChanges(true); } var secondaryEmailAttribute = AttributeCache.Read(secondaryEmail.Id, lookupContext); // Add a former name attribute var formerName = personAttributes.FirstOrDefault(a => a.Key == "FormerName"); if (formerName == null) { formerName = new Rock.Model.Attribute(); formerName.Key = "FormerName"; formerName.Name = "Former Name"; formerName.FieldTypeId = textFieldTypeId; formerName.EntityTypeId = PersonEntityTypeId; formerName.EntityTypeQualifierValue = string.Empty; formerName.EntityTypeQualifierColumn = string.Empty; formerName.Description = "The former name for this person"; formerName.DefaultValue = string.Empty; formerName.IsMultiValue = false; formerName.IsRequired = false; formerName.Order = 0; lookupContext.Attributes.Add(formerName); secondaryEmail.Categories.Add(visitInfoCategory); lookupContext.SaveChanges(true); } var formerNameAttribute = AttributeCache.Read(formerName.Id, lookupContext); // Look for custom attributes in the Individual file var allFields = csvData.TableNodes.FirstOrDefault().Columns.Select((node, index) => new { node = node, index = index }).ToList(); Dictionary <int, string> customAttributes = allFields.Where(f => f.index > Twitter).ToDictionary(f => f.index, f => f.node.Name); // Add any if they don't already exist if (customAttributes.Any()) { var newAttributes = new List <Rock.Model.Attribute>(); foreach (var newAttributePair in customAttributes.Where(ca => !personAttributes.Any(a => a.Name == ca.Value))) { var newAttribute = new Rock.Model.Attribute(); newAttribute.Name = newAttributePair.Value; newAttribute.Key = newAttributePair.Value.RemoveWhitespace(); newAttribute.Description = newAttributePair.Value + " created by CSV import"; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.FieldTypeId = textFieldTypeId; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsGridColumn = false; newAttribute.IsRequired = false; newAttribute.Order = 0; newAttributes.Add(newAttribute); } lookupContext.Attributes.AddRange(newAttributes); lookupContext.SaveChanges(true); personAttributes.AddRange(newAttributes); } var dateFormats = new[] { "MM/dd/yyyy", "MM/dd/yy" }; var currentFamilyGroup = new Group(); var newFamilyList = new List <Group>(); var newVisitorList = new List <Group>(); var importDate = DateTime.Now; int completed = 0; ReportProgress(0, string.Format("Starting Individual import ({0:N0} already exist).", ImportedPeople.Count(p => p.Members.Any(m => m.Person.ForeignId != null)))); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { int groupRoleId = adultRoleId; bool isFamilyRelationship = true; string rowFamilyId = row[FamilyId]; string rowPersonId = row[PersonId]; string rowFamilyName = row[FamilyName]; if (!string.IsNullOrWhiteSpace(rowFamilyId) && rowFamilyId != currentFamilyGroup.ForeignId) { currentFamilyGroup = ImportedPeople.FirstOrDefault(p => p.ForeignId == rowFamilyId); if (currentFamilyGroup == null) { currentFamilyGroup = new Group(); currentFamilyGroup.ForeignId = rowFamilyId; currentFamilyGroup.Name = row[FamilyName]; currentFamilyGroup.CreatedByPersonAliasId = ImportPersonAlias.Id; currentFamilyGroup.GroupTypeId = FamilyGroupTypeId; } } // Verify this person isn't already in our data var personExists = ImportedPeople.Any(p => p.Members.Any(m => m.Person.ForeignId == rowPersonId)); if (!personExists) { var person = new Person(); person.ForeignId = rowPersonId; person.SystemNote = string.Format("Imported via Excavator on {0}", importDate.ToString()); person.RecordTypeValueId = personRecordTypeId; person.CreatedByPersonAliasId = ImportPersonAlias.Id; string firstName = row[FirstName]; person.FirstName = firstName; person.NickName = row[NickName] ?? firstName; person.MiddleName = row[MiddleName]; person.LastName = row[LastName]; #region Assign values to the Person record DateTime birthDate; if (DateTime.TryParseExact(row[DateOfBirth], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate)) { person.BirthDate = birthDate; } DateTime anniversary; if (DateTime.TryParseExact(row[Anniversary], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out anniversary)) { person.AnniversaryDate = anniversary; } string gender = row[Gender]; if (gender != null) { switch (gender.Trim().ToLower()) { case "m": case "male": person.Gender = Rock.Model.Gender.Male; break; case "f": case "female": person.Gender = Rock.Model.Gender.Female; break; default: person.Gender = Rock.Model.Gender.Unknown; break; } } string prefix = row[Prefix]; if (!string.IsNullOrWhiteSpace(prefix)) { prefix = prefix.RemoveSpecialCharacters().Trim(); person.TitleValueId = titleTypes.Where(s => prefix == s.Value.RemoveSpecialCharacters()) .Select(s => (int?)s.Id).FirstOrDefault(); } string suffix = row[Suffix]; if (!string.IsNullOrWhiteSpace(suffix)) { suffix = suffix.RemoveSpecialCharacters().Trim(); person.SuffixValueId = suffixTypes.Where(s => suffix == s.Value.RemoveSpecialCharacters()) .Select(s => (int?)s.Id).FirstOrDefault(); } string maritalStatus = row[MaritalStatus]; if (!string.IsNullOrWhiteSpace(maritalStatus)) { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == maritalStatus) .Select(dv => (int?)dv.Id).FirstOrDefault(); } else { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == "Unknown") .Select(dv => (int?)dv.Id).FirstOrDefault(); } string familyRole = row[FamilyRole]; if (!string.IsNullOrWhiteSpace(familyRole)) { if (familyRole == "Visitor") { isFamilyRelationship = false; } if (familyRole == "Child" || person.Age < 18) { groupRoleId = childRoleId; } } string connectionStatus = row[ConnectionStatus]; if (!string.IsNullOrWhiteSpace(connectionStatus)) { if (connectionStatus == "Member") { person.ConnectionStatusValueId = memberConnectionStatusId; } else if (connectionStatus == "Visitor") { person.ConnectionStatusValueId = visitorConnectionStatusId; } else if (connectionStatus == "Deceased") { person.IsDeceased = true; person.RecordStatusReasonValueId = recordStatusDeceasedId; } else { // look for user-defined connection type or default to Attendee var customConnectionType = connectionStatusTypes.Where(dv => dv.Value == connectionStatus) .Select(dv => (int?)dv.Id).FirstOrDefault(); person.ConnectionStatusValueId = customConnectionType ?? attendeeConnectionStatusId; person.RecordStatusValueId = recordStatusActiveId; } } string recordStatus = row[RecordStatus]; if (!string.IsNullOrWhiteSpace(recordStatus)) { switch (recordStatus.Trim()) { case "Active": person.RecordStatusValueId = recordStatusActiveId; break; case "Inactive": person.RecordStatusValueId = recordStatusInactiveId; break; default: person.RecordStatusValueId = recordStatusPendingId; break; } } var personNumbers = new Dictionary <string, string>(); personNumbers.Add("Home", row[HomePhone]); personNumbers.Add("Mobile", row[MobilePhone]); personNumbers.Add("Work", row[WorkPhone]); string smsAllowed = row[AllowSMS]; foreach (var numberPair in personNumbers.Where(n => !string.IsNullOrWhiteSpace(n.Value))) { var extension = string.Empty; var countryCode = Rock.Model.PhoneNumber.DefaultCountryCode(); var normalizedNumber = string.Empty; var countryIndex = numberPair.Value.IndexOf('+'); int extensionIndex = numberPair.Value.LastIndexOf('x') > 0 ? numberPair.Value.LastIndexOf('x') : numberPair.Value.Length; if (countryIndex >= 0) { countryCode = numberPair.Value.Substring(countryIndex, countryIndex + 3).AsNumeric(); normalizedNumber = numberPair.Value.Substring(countryIndex + 3, extensionIndex - 3).AsNumeric(); extension = numberPair.Value.Substring(extensionIndex); } else if (extensionIndex > 0) { normalizedNumber = numberPair.Value.Substring(0, extensionIndex).AsNumeric(); extension = numberPair.Value.Substring(extensionIndex).AsNumeric(); } else { normalizedNumber = numberPair.Value.AsNumeric(); } if (!string.IsNullOrWhiteSpace(normalizedNumber)) { var currentNumber = new PhoneNumber(); currentNumber.CountryCode = countryCode; currentNumber.CreatedByPersonAliasId = ImportPersonAlias.Id; currentNumber.Extension = extension.Left(20); currentNumber.Number = normalizedNumber.Left(20); currentNumber.NumberTypeValueId = numberTypeValues.Where(v => v.Value.Equals(numberPair.Key)) .Select(v => (int?)v.Id).FirstOrDefault(); if (numberPair.Key == "Mobile") { switch (smsAllowed.Trim().ToLower()) { case "y": case "yes": case "active": currentNumber.IsMessagingEnabled = true; break; default: currentNumber.IsMessagingEnabled = false; break; } } person.PhoneNumbers.Add(currentNumber); } } // Map Person attributes person.Attributes = new Dictionary <string, AttributeCache>(); person.AttributeValues = new Dictionary <string, AttributeValue>(); string formerNameValue = row[FormerName]; if (!string.IsNullOrWhiteSpace(formerNameValue)) { AddPersonAttribute(formerNameAttribute, person, formerNameValue); } bool isEmailActive; switch (row[IsEmailActive].Trim().ToLower()) { case "n": case "no": case "inactive": isEmailActive = false; break; default: isEmailActive = true; break; } EmailPreference emailPreference; switch (row[AllowBulkEmail].Trim().ToLower()) { case "n": case "no": case "inactive": emailPreference = EmailPreference.NoMassEmails; break; default: emailPreference = EmailPreference.EmailAllowed; break; } string primaryEmail = row[Email]; if (!string.IsNullOrWhiteSpace(primaryEmail)) { person.Email = primaryEmail; person.IsEmailActive = isEmailActive; person.EmailPreference = emailPreference; } string secondaryEmailValue = row[SecondaryEmail]; if (!string.IsNullOrWhiteSpace(secondaryEmailValue)) { AddPersonAttribute(secondaryEmailAttribute, person, secondaryEmailValue); } DateTime membershipDateValue; if (DateTime.TryParseExact(row[MembershipDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out membershipDateValue)) { AddPersonAttribute(membershipDateAttribute, person, membershipDateValue.ToString()); } DateTime baptismDateValue; if (DateTime.TryParseExact(row[BaptismDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out baptismDateValue)) { AddPersonAttribute(baptismDateAttribute, person, baptismDateValue.ToString()); } DateTime firstVisitValue; if (DateTime.TryParseExact(row[FirstVisit], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out firstVisitValue)) { AddPersonAttribute(firstVisitAttribute, person, firstVisitValue.ToString()); } string previousChurchValue = row[PreviousChurch]; if (!string.IsNullOrWhiteSpace(previousChurchValue)) { AddPersonAttribute(previousChurchAttribute, person, previousChurchValue); } string positionValue = row[Occupation]; if (!string.IsNullOrWhiteSpace(positionValue)) { AddPersonAttribute(positionAttribute, person, positionValue); } string employerValue = row[Employer]; if (!string.IsNullOrWhiteSpace(employerValue)) { AddPersonAttribute(employerAttribute, person, employerValue); } string schoolName = row[School]; if (!string.IsNullOrWhiteSpace(schoolName)) { // Add school if it doesn't exist Guid schoolGuid; var schoolExists = schoolDefinedType.DefinedValues.Any(s => s.Value.Equals(schoolName)); if (!schoolExists) { var newSchool = new DefinedValue(); newSchool.DefinedTypeId = schoolDefinedType.Id; newSchool.Value = schoolName; newSchool.Order = 0; lookupContext.DefinedValues.Add(newSchool); lookupContext.SaveChanges(); schoolGuid = newSchool.Guid; } else { schoolGuid = schoolDefinedType.DefinedValues.FirstOrDefault(s => s.Value.Equals(schoolName)).Guid; } AddPersonAttribute(schoolAttribute, person, schoolGuid.ToString()); } string facebookValue = row[Facebook]; if (!string.IsNullOrWhiteSpace(facebookValue)) { AddPersonAttribute(facebookAttribute, person, facebookValue); } string twitterValue = row[Twitter]; if (!string.IsNullOrWhiteSpace(twitterValue)) { AddPersonAttribute(twitterAttribute, person, twitterValue); } string instagramValue = row[Instagram]; if (!string.IsNullOrWhiteSpace(instagramValue)) { AddPersonAttribute(instagramAttribute, person, instagramValue); } foreach (var attributePair in customAttributes) { string newAttributeValue = row[attributePair.Key]; if (!string.IsNullOrWhiteSpace(newAttributeValue)) { int?newAttributeId = personAttributes.Where(a => a.Key == attributePair.Value) .Select(a => (int?)a.Id).FirstOrDefault(); if (newAttributeId != null) { var newAttribute = AttributeCache.Read((int)newAttributeId); AddPersonAttribute(newAttribute, person, newAttributeValue); } } } // Add notes to timeline var notePairs = new Dictionary <string, string>(); notePairs.Add("General", row[GeneralNote]); notePairs.Add("Medical", row[MedicalNote]); notePairs.Add("Security", row[SecurityNote]); var newNoteList = new List <Note>(); foreach (var notePair in notePairs.Where(n => !string.IsNullOrWhiteSpace(n.Value))) { var newNote = new Note(); newNote.CreatedByPersonAliasId = ImportPersonAlias.Id; newNote.CreatedDateTime = importDate; newNote.EntityId = person.Id; newNote.Text = notePair.Value; newNote.NoteTypeId = noteTimelineTypeId; newNote.Caption = string.Format("{0} Note", notePair.Key); if (!notePair.Key.Equals("General")) { newNote.IsAlert = true; } newNoteList.Add(newNote); } if (newNoteList.Any()) { lookupContext.Notes.AddRange(newNoteList); lookupContext.SaveChanges(true); } #endregion var groupMember = new GroupMember(); groupMember.Person = person; groupMember.GroupRoleId = groupRoleId; groupMember.GroupMemberStatus = GroupMemberStatus.Active; if (isFamilyRelationship || currentFamilyGroup.Members.Count() < 1) { currentFamilyGroup.Members.Add(groupMember); newFamilyList.Add(currentFamilyGroup); completed++; } else { var visitorGroup = new Group(); visitorGroup.ForeignId = rowFamilyId.ToString(); visitorGroup.Members.Add(groupMember); visitorGroup.GroupTypeId = FamilyGroupTypeId; visitorGroup.Name = person.LastName + " Family"; newFamilyList.Add(visitorGroup); completed++; newVisitorList.Add(visitorGroup); } if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, string.Format("{0:N0} people imported.", completed)); } else if (completed % ReportingNumber < 1) { SaveIndividuals(newFamilyList, newVisitorList); ReportPartialProgress(); newFamilyList.Clear(); } } } if (newFamilyList.Any()) { SaveIndividuals(newFamilyList, newVisitorList); } ReportProgress(0, string.Format("Finished individual import: {0:N0} people imported.", completed)); return(completed); }
private void DisplayForm(Person person) { pnlMain.Visible = true; ddlTitle.SetValue(person.TitleValueId); iuPhoto.BinaryFileId = person.PhotoId; tbNickName.Text = person.NickName; tbFirstName.Text = person.FirstName; tbMiddleName.Text = person.MiddleName; tbLastName.Text = person.LastName; ddlSuffix.SetValue(person.SuffixValueId); var families = person.GetFamilies(); //If there is more than one family don't show family role if (families.Count() > 1) { ddlFamilyRole.Visible = false; } else { ddlFamilyRole.SelectedValue = person.GetFamilyRole().Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ? "A" : "C"; var familyMemberRole = person.GetFamilyMembers(true) .Where(m => person.Id == m.PersonId) .Select(m => m.GroupRole) .FirstOrDefault(); if (familyMemberRole != null) { ddlFamilyRole.SelectedValue = familyMemberRole.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ? "A" : "C"; } } //PhoneNumber var mobilePhoneType = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE)); var phoneNumbers = new List <PhoneNumber>(); var phoneNumberTypes = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE)); if (phoneNumberTypes.DefinedValues.Any()) { foreach (var phoneNumberType in phoneNumberTypes.DefinedValues) { var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberType.Id); if (phoneNumber == null) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Value = phoneNumberType.Value; phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id; } else { // Update number format, just in case it wasn't saved correctly phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber(phoneNumber.CountryCode, phoneNumber.Number); } phoneNumbers.Add(phoneNumber); } } rContactInfo.DataSource = phoneNumbers; rContactInfo.DataBind(); //email tbEmail.Text = person.Email; cbIsEmailActive.Checked = person.IsEmailActive; rblEmailPreference.SetValue(person.EmailPreference.ConvertToString(false)); rblCommunicationPreference.SetValue(person.CommunicationPreference == CommunicationType.SMS ? "2" : "1"); //demographics bpBirthday.SelectedDate = person.BirthDate; ddlGender.SetValue(person.Gender.ConvertToInt()); ddlMaritalStatus.SetValue(person.MaritalStatusValueId); dpAnniversaryDate.SelectedDate = person.AnniversaryDate; if (!person.HasGraduated ?? false) { int gradeOffset = person.GradeOffset.Value; var maxGradeOffset = ddlGradePicker.MaxGradeOffset; // keep trying until we find a Grade that has a gradeOffset that that includes the Person's gradeOffset (for example, there might be combined grades) while (!ddlGradePicker.Items.OfType <ListItem>().Any(a => a.Value.AsInteger() == gradeOffset) && gradeOffset <= maxGradeOffset) { gradeOffset++; } ddlGradePicker.SetValue(gradeOffset); ypGraduation.SelectedYear = person.GraduationYear; } else { ddlGradePicker.SelectedIndex = 0; ypGraduation.SelectedYear = person.GraduationYear; } ScriptManager.RegisterStartupScript(ddlGradePicker, ddlGradePicker.GetType(), "grade-selection-" + BlockId.ToString(), ddlGradePicker.GetJavascriptForYearPicker(ypGraduation), true); //Family Info var location = person.GetHomeLocation(); acAddress.SetValues(location); ddlCampus.SetValue(person.GetCampus()); }
/// <summary> /// Get the Checkr packages and update the list on the server. /// </summary> /// <param name="errorMessages">The error messages.</param> /// <returns>True/False value of whether the request was successfully sent or not.</returns> public static bool UpdatePackages(List <string> errorMessages) { GetPackagesResponse getPackagesResponse; if (!CheckrApiUtility.GetPackages(out getPackagesResponse, errorMessages)) { return(false); } Dictionary <string, DefinedValue> packages; using (var rockContext = new RockContext()) { var definedType = DefinedTypeCache.Get(SystemGuid.DefinedType.BACKGROUND_CHECK_TYPES.AsGuid()); DefinedValueService definedValueService = new DefinedValueService(rockContext); packages = definedValueService .GetByDefinedTypeGuid(SystemGuid.DefinedType.BACKGROUND_CHECK_TYPES.AsGuid()) .Where(v => v.ForeignId == 2) .ToList() .Select(v => { v.LoadAttributes(rockContext); return(v); }) // v => v.Value.Substring( CheckrConstants.TYPENAME_PREFIX.Length ) ) .ToDictionary(v => v.GetAttributeValue("PMMPackageName").ToString(), v => v); foreach (var packageRestResponse in getPackagesResponse.Data) { string packageName = packageRestResponse.Slug; if (!packages.ContainsKey(packageName)) { DefinedValue definedValue = null; definedValue = new DefinedValue() { IsActive = true, DefinedTypeId = definedType.Id, ForeignId = 2, Value = CheckrConstants.CHECKR_TYPENAME_PREFIX + packageName.Replace('_', ' ').FixCase(), Description = packageRestResponse.Name == "Educatio Report" ? "Education Report" : packageRestResponse.Name }; definedValueService.Add(definedValue); rockContext.SaveChanges(); definedValue.LoadAttributes(rockContext); definedValue.SetAttributeValue("PMMPackageName", packageName); definedValue.SetAttributeValue("DefaultCounty", string.Empty); definedValue.SetAttributeValue("SendHomeCounty", "False"); definedValue.SetAttributeValue("DefaultState", string.Empty); definedValue.SetAttributeValue("SendHomeState", "False"); definedValue.SetAttributeValue("MVRJurisdiction", string.Empty); definedValue.SetAttributeValue("SendHomeStateMVR", "False"); definedValue.SaveAttributeValues(rockContext); } } var packageRestResponseNames = getPackagesResponse.Data.Select(pr => pr.Slug); foreach (var package in packages) { package.Value.IsActive = packageRestResponseNames.Contains(package.Key); } rockContext.SaveChanges(); } DefinedValueCache.Clear(); return(true); }
/// <summary> /// Shows the package edit. /// </summary> /// <param name="definedValueId">The defined value identifier.</param> public void ShowPackageEdit( int definedValueId ) { var definedType = DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.PROTECT_MY_MINISTRY_PACKAGES.AsGuid() ); if ( definedType != null ) { DefinedValue definedValue = null; if ( !definedValueId.Equals( 0 ) ) { definedValue = new DefinedValueService( new RockContext() ).Get( definedValueId ); } if ( definedValue != null ) { hfDefinedValueId.Value = definedValue.Id.ToString(); dlgPackage.Title = definedValue.Value; } else { definedValue = new DefinedValue(); definedValue.DefinedTypeId = definedType.Id; hfDefinedValueId.Value = string.Empty; dlgPackage.Title = "New Package"; } tbTitle.Text = definedValue.Value; tbDescription.Text = definedValue.Description; definedValue.LoadAttributes(); ddlMVRJurisdication.SetValue( 0 ); Guid? mvrJurisdicationGuid = definedValue.GetAttributeValue( "MVRJurisdiction" ).AsGuidOrNull(); if ( mvrJurisdicationGuid.HasValue ) { var mvrJurisdication = DefinedValueCache.Read( mvrJurisdicationGuid.Value ); if ( mvrJurisdication != null ) { ddlMVRJurisdication.SetValue( mvrJurisdication.Id ); } } tbPackageName.Text = definedValue.GetAttributeValue( "PMMPackageName" ); tbDefaultCounty.Text = definedValue.GetAttributeValue( "DefaultCounty" ); cbSendCounty.Checked = definedValue.GetAttributeValue( "SendHomeCounty" ).AsBoolean(); tbDefaultState.Text = definedValue.GetAttributeValue( "DefaultState" ); cbSendState.Checked = definedValue.GetAttributeValue( "SendHomeState" ).AsBoolean(); cbSendStateMVR.Checked = definedValue.GetAttributeValue( "SendHomeStateMVR" ).AsBoolean(); ShowDialog( "Package" ); } }
/// <summary> /// Loads the individual data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadIndividuals(CSVInstance csvData) { var lookupContext = new RockContext(); var groupTypeRoleService = new GroupTypeRoleService(lookupContext); var groupMemberService = new GroupMemberService(lookupContext); // Marital statuses: Married, Single, Separated, etc var maritalStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS), lookupContext).DefinedValues; // Connection statuses: Member, Visitor, Attendee, etc var connectionStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS), lookupContext).DefinedValues; int memberConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER)).Id; int visitorConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR)).Id; int attendeeConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_ATTENDEE)).Id; // Suffix type: Dr., Jr., II, etc var suffixTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_SUFFIX), lookupContext).DefinedValues; // Title type: Mr., Mrs. Dr., etc var titleTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_TITLE), lookupContext).DefinedValues; // Record statuses: Active, Inactive, Pending int?recordStatusActiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE), lookupContext).Id; int?recordStatusInactiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE), lookupContext).Id; int?recordStatusPendingId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING), lookupContext).Id; // Deceased record status reason (others available: No Activity, Moved, etc) var recordStatusDeceasedId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_REASON_DECEASED)).Id; // Record type: Person int?personRecordTypeId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON), lookupContext).Id; // Group roles: Owner, Adult, Child, others GroupTypeRole ownerRole = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER)); int adultRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id; int childRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD)).Id; // Phone types: Home, Work, Mobile var numberTypeValues = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE), lookupContext).DefinedValues; // Personal note type id var personalNoteTypeId = new NoteTypeService(lookupContext).Get(new Guid(Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE)).Id; // School defined type var schoolDefinedType = DefinedTypeCache.Read(new Guid("576FF1E2-6225-4565-A16D-230E26167A3D")); // Look up existing Person attributes var personAttributes = new AttributeService(lookupContext).GetByEntityTypeId(PersonEntityTypeId).ToList(); var schoolAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "School")); // Text field type id int textFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT), lookupContext).Id; int dateFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.DATE), lookupContext).Id; // Attribute entity type id int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id; // Visit info category var visitInfoCategory = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId) .Where(c => c.Name == "Visit Information").FirstOrDefault(); // Look for custom attributes in the Individual file var allFields = csvData.TableNodes.FirstOrDefault().Children.Select((node, index) => new { node = node, index = index }).ToList(); Dictionary <int, string> customAttributes = allFields .Where(f => f.index > SecurityNote) .ToDictionary(f => f.index, f => f.node.Name.RemoveWhitespace()); // Add any attributes if they don't already exist if (customAttributes.Any()) { var newAttributes = new List <Rock.Model.Attribute>(); foreach (var newAttributePair in customAttributes.Where(ca => !personAttributes.Any(a => a.Key == ca.Value))) { var newAttribute = new Rock.Model.Attribute(); newAttribute.Name = newAttributePair.Value; newAttribute.Key = newAttributePair.Value.RemoveWhitespace(); newAttribute.Description = newAttributePair.Value + " created by CSV import"; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.FieldTypeId = textFieldTypeId; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsGridColumn = false; newAttribute.IsRequired = false; newAttribute.Order = 0; newAttributes.Add(newAttribute); } lookupContext.Attributes.AddRange(newAttributes); lookupContext.SaveChanges(DisableAuditing); personAttributes.AddRange(newAttributes); } // Set the supported date formats var dateFormats = new[] { "yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy" }; var currentFamilyGroup = new Group(); var newFamilyList = new List <Group>(); var newVisitorList = new List <Group>(); var newNoteList = new List <Note>(); int completed = 0; int newFamilies = 0; int newPeople = 0; ReportProgress(0, string.Format("Starting Individual import ({0:N0} already exist).", ImportedPeopleKeys.Count())); string[] row; row = csvData.Database.FirstOrDefault(); while (row != null) { int groupRoleId = adultRoleId; bool isFamilyRelationship = true; string rowFamilyName = row[FamilyName]; string rowFamilyKey = row[FamilyId]; string rowPersonKey = row[PersonId]; int? rowFamilyId = rowFamilyKey.AsType <int?>(); int? rowPersonId = rowPersonKey.AsType <int?>(); // Check that this person isn't already in our data var personExists = ImportedFamilies.Any(g => g.Members.Any(m => m.Person.ForeignKey == rowPersonKey)); if (!personExists) { #region person create var person = new Person(); person.ForeignKey = rowPersonKey; person.ForeignId = rowPersonId; person.SystemNote = string.Format("Imported via Excavator on {0}", ImportDateTime); person.RecordTypeValueId = personRecordTypeId; person.CreatedByPersonAliasId = ImportPersonAliasId; string firstName = row[FirstName].Left(50); string nickName = row[NickName].Left(50); person.FirstName = firstName; person.NickName = string.IsNullOrWhiteSpace(nickName) ? firstName : nickName; person.MiddleName = row[MiddleName].Left(50); person.LastName = row[LastName].Left(50); DateTime createdDateValue; if (DateTime.TryParseExact(row[CreatedDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDateValue)) { person.CreatedDateTime = createdDateValue; person.ModifiedDateTime = ImportDateTime; } else { person.CreatedDateTime = ImportDateTime; person.ModifiedDateTime = ImportDateTime; } DateTime birthDate; if (DateTime.TryParseExact(row[DateOfBirth], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate)) { person.BirthDay = birthDate.Day; person.BirthMonth = birthDate.Month; person.BirthYear = birthDate.Year; } DateTime graduationDate; if (DateTime.TryParseExact(row[GraduationDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out graduationDate)) { person.GraduationYear = graduationDate.Year; } DateTime anniversary; if (DateTime.TryParseExact(row[Anniversary], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out anniversary)) { person.AnniversaryDate = anniversary; } string gender = row[Gender]; if (gender != null) { switch (gender.Trim().ToLower()) { case "m": case "male": person.Gender = Rock.Model.Gender.Male; break; case "f": case "female": person.Gender = Rock.Model.Gender.Female; break; default: person.Gender = Rock.Model.Gender.Unknown; break; } } string prefix = row[Prefix]; if (!string.IsNullOrWhiteSpace(prefix)) { prefix = prefix.RemoveSpecialCharacters().Trim(); person.TitleValueId = titleTypes.Where(s => prefix == s.Value.RemoveSpecialCharacters()) .Select(s => (int?)s.Id).FirstOrDefault(); } string suffix = row[Suffix]; if (!string.IsNullOrWhiteSpace(suffix)) { suffix = suffix.RemoveSpecialCharacters().Trim(); person.SuffixValueId = suffixTypes.Where(s => suffix == s.Value.RemoveSpecialCharacters()) .Select(s => (int?)s.Id).FirstOrDefault(); } string maritalStatus = row[MaritalStatus]; if (!string.IsNullOrWhiteSpace(maritalStatus)) { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == maritalStatus) .Select(dv => (int?)dv.Id).FirstOrDefault(); } else { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == "Unknown") .Select(dv => ( int? )dv.Id).FirstOrDefault(); } string familyRole = row[FamilyRole]; if (!string.IsNullOrWhiteSpace(familyRole)) { if (familyRole == "Visitor") { isFamilyRelationship = false; } if (familyRole == "Child" || person.Age < 18) { groupRoleId = childRoleId; } } string connectionStatus = row[ConnectionStatus]; if (!string.IsNullOrWhiteSpace(connectionStatus)) { if (connectionStatus == "Member") { person.ConnectionStatusValueId = memberConnectionStatusId; } else if (connectionStatus == "Visitor") { person.ConnectionStatusValueId = visitorConnectionStatusId; } else { // look for user-defined connection type or default to Attendee var customConnectionType = connectionStatusTypes.Where(dv => dv.Value == connectionStatus) .Select(dv => (int?)dv.Id).FirstOrDefault(); person.ConnectionStatusValueId = customConnectionType ?? attendeeConnectionStatusId; person.RecordStatusValueId = recordStatusActiveId; } } string recordStatus = row[RecordStatus]; if (!string.IsNullOrWhiteSpace(recordStatus)) { switch (recordStatus.Trim().ToLower()) { case "active": person.RecordStatusValueId = recordStatusActiveId; break; case "inactive": person.RecordStatusValueId = recordStatusInactiveId; break; default: person.RecordStatusValueId = recordStatusPendingId; break; } } string isDeceasedValue = row[IsDeceased]; if (!string.IsNullOrWhiteSpace(isDeceasedValue)) { switch (isDeceasedValue.Trim().ToLower()) { case "y": case "yes": person.IsDeceased = true; person.RecordStatusReasonValueId = recordStatusDeceasedId; person.RecordStatusValueId = recordStatusInactiveId; break; default: person.IsDeceased = false; break; } } var personNumbers = new Dictionary <string, string>(); personNumbers.Add("Home", row[HomePhone]); personNumbers.Add("Mobile", row[MobilePhone]); personNumbers.Add("Work", row[WorkPhone]); string smsAllowed = row[AllowSMS]; foreach (var numberPair in personNumbers.Where(n => !string.IsNullOrWhiteSpace(n.Value))) { var extension = string.Empty; var countryCode = Rock.Model.PhoneNumber.DefaultCountryCode(); var normalizedNumber = string.Empty; var countryIndex = numberPair.Value.IndexOf('+'); int extensionIndex = numberPair.Value.LastIndexOf('x') > 0 ? numberPair.Value.LastIndexOf('x') : numberPair.Value.Length; if (countryIndex >= 0) { countryCode = numberPair.Value.Substring(countryIndex, countryIndex + 3).AsNumeric(); normalizedNumber = numberPair.Value.Substring(countryIndex + 3, extensionIndex - 3).AsNumeric().TrimStart(new Char[] { '0' }); extension = numberPair.Value.Substring(extensionIndex); } else if (extensionIndex > 0) { normalizedNumber = numberPair.Value.Substring(0, extensionIndex).AsNumeric(); extension = numberPair.Value.Substring(extensionIndex).AsNumeric(); } else { normalizedNumber = numberPair.Value.AsNumeric(); } if (!string.IsNullOrWhiteSpace(normalizedNumber)) { var currentNumber = new PhoneNumber(); currentNumber.CountryCode = countryCode; currentNumber.CreatedByPersonAliasId = ImportPersonAliasId; currentNumber.Extension = extension.Left(20); currentNumber.Number = normalizedNumber.TrimStart(new Char[] { '0' }).Left(20); currentNumber.NumberFormatted = PhoneNumber.FormattedNumber(currentNumber.CountryCode, currentNumber.Number); currentNumber.NumberTypeValueId = numberTypeValues.Where(v => v.Value.Equals(numberPair.Key)) .Select(v => ( int? )v.Id).FirstOrDefault(); if (numberPair.Key == "Mobile") { switch (smsAllowed.Trim().ToLower()) { case "y": case "yes": case "active": currentNumber.IsMessagingEnabled = true; break; default: currentNumber.IsMessagingEnabled = false; break; } } person.PhoneNumbers.Add(currentNumber); } } // Map Person attributes person.Attributes = new Dictionary <string, AttributeCache>(); person.AttributeValues = new Dictionary <string, AttributeValueCache>(); bool isEmailActive; switch (row[IsEmailActive].Trim().ToLower()) { case "n": case "no": case "inactive": isEmailActive = false; break; default: isEmailActive = true; break; } EmailPreference emailPreference; switch (row[AllowBulkEmail].Trim().ToLower()) { case "n": case "no": case "inactive": emailPreference = EmailPreference.NoMassEmails; break; default: emailPreference = EmailPreference.EmailAllowed; break; } person.EmailPreference = emailPreference; string primaryEmail = row[Email].Trim().Left(75); if (!string.IsNullOrWhiteSpace(primaryEmail)) { if (primaryEmail.IsEmail()) { person.Email = primaryEmail; person.IsEmailActive = isEmailActive; } else { LogException("InvalidPrimaryEmail", string.Format("PersonId: {0} - Email: {1}", rowPersonKey, primaryEmail)); } } string schoolName = row[School]; if (!string.IsNullOrWhiteSpace(schoolName)) { // Add school if it doesn't exist Guid schoolGuid; var schoolExists = lookupContext.DefinedValues.Any(s => s.DefinedTypeId == schoolDefinedType.Id && s.Value.Equals(schoolName)); if (!schoolExists) { var newSchool = new DefinedValue(); newSchool.DefinedTypeId = schoolDefinedType.Id; newSchool.Value = schoolName; newSchool.Order = 0; lookupContext.DefinedValues.Add(newSchool); lookupContext.SaveChanges(); schoolGuid = newSchool.Guid; } else { schoolGuid = lookupContext.DefinedValues.FirstOrDefault(s => s.Value.Equals(schoolName)).Guid; } AddPersonAttribute(schoolAttribute, person, schoolGuid.ToString().ToUpper()); } foreach (var attributePair in customAttributes) { string newAttributeValue = row[attributePair.Key]; if (!string.IsNullOrWhiteSpace(newAttributeValue)) { // check if this attribute value is a date DateTime valueAsDateTime; if (DateTime.TryParseExact(newAttributeValue, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out valueAsDateTime)) { newAttributeValue = valueAsDateTime.ToString("yyyy-MM-dd"); } int?newAttributeId = personAttributes.Where(a => a.Key == attributePair.Value.RemoveWhitespace()) .Select(a => (int?)a.Id).FirstOrDefault(); if (newAttributeId != null) { var newAttribute = AttributeCache.Read((int)newAttributeId); AddPersonAttribute(newAttribute, person, newAttributeValue); } } } // Add notes to timeline var notePairs = new Dictionary <string, string>(); notePairs.Add("General", row[GeneralNote]); notePairs.Add("Medical", row[MedicalNote]); notePairs.Add("Security", row[SecurityNote]); foreach (var notePair in notePairs.Where(n => !string.IsNullOrWhiteSpace(n.Value))) { var newNote = new Note(); newNote.NoteTypeId = personalNoteTypeId; newNote.CreatedByPersonAliasId = ImportPersonAliasId; newNote.CreatedDateTime = ImportDateTime; newNote.Text = notePair.Value; newNote.ForeignKey = rowPersonKey; newNote.ForeignId = rowPersonId; newNote.Caption = string.Format("{0} Note", notePair.Key); if (!notePair.Key.Equals("General")) { newNote.IsAlert = true; } newNoteList.Add(newNote); } #endregion person create var groupMember = new GroupMember(); groupMember.Person = person; groupMember.GroupRoleId = groupRoleId; groupMember.CreatedDateTime = ImportDateTime; groupMember.ModifiedDateTime = ImportDateTime; groupMember.CreatedByPersonAliasId = ImportPersonAliasId; groupMember.GroupMemberStatus = GroupMemberStatus.Active; if (rowFamilyKey != currentFamilyGroup.ForeignKey) { // person not part of the previous family, see if that family exists or create a new one currentFamilyGroup = ImportedFamilies.FirstOrDefault(g => g.ForeignKey == rowFamilyKey); if (currentFamilyGroup == null) { currentFamilyGroup = CreateFamilyGroup(row[FamilyName], rowFamilyKey); newFamilyList.Add(currentFamilyGroup); newFamilies++; } else { lookupContext.Groups.Attach(currentFamilyGroup); lookupContext.Entry(currentFamilyGroup).State = EntityState.Modified; } currentFamilyGroup.Members.Add(groupMember); } else { // person is part of this family group, check if they're a visitor if (isFamilyRelationship || currentFamilyGroup.Members.Count() < 1) { currentFamilyGroup.Members.Add(groupMember); } else { var visitorFamily = CreateFamilyGroup(person.LastName + " Family", rowFamilyKey); visitorFamily.Members.Add(groupMember); newFamilyList.Add(visitorFamily); newVisitorList.Add(visitorFamily); newFamilies++; } } // look ahead 1 row string rowNextFamilyKey = "-1"; if ((row = csvData.Database.FirstOrDefault()) != null) { rowNextFamilyKey = row[FamilyId]; } newPeople++; completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, string.Format("{0:N0} people imported.", completed)); } if (newPeople >= ReportingNumber && rowNextFamilyKey != currentFamilyGroup.ForeignKey) { SaveIndividuals(newFamilyList, newVisitorList, newNoteList); lookupContext.SaveChanges(); ReportPartialProgress(); // Clear out variables currentFamilyGroup = new Group(); newFamilyList.Clear(); newVisitorList.Clear(); newNoteList.Clear(); newPeople = 0; } } else { row = csvData.Database.FirstOrDefault(); } } // Save any changes to new families if (newFamilyList.Any()) { SaveIndividuals(newFamilyList, newVisitorList, newNoteList); } // Save any changes to existing families lookupContext.SaveChanges(); DetachAllInContext(lookupContext); lookupContext.Dispose(); ReportProgress(0, string.Format("Finished individual import: {0:N0} families and {1:N0} people added.", newFamilies, completed)); return(completed); }
/// <summary> /// Shows the details. /// </summary> private void ShowDetails() { lTitle.Text = string.Format( "Edit: {0}", Person.FullName ).FormatAsHtmlTitle(); imgPhoto.BinaryFileId = Person.PhotoId; imgPhoto.NoPictureUrl = Person.GetPersonPhotoUrl( Person, 400, 400 ); ddlTitle.SelectedValue = Person.TitleValueId.HasValue ? Person.TitleValueId.Value.ToString() : string.Empty; tbFirstName.Text = Person.FirstName; tbNickName.Text = string.IsNullOrWhiteSpace( Person.NickName ) ? string.Empty : ( Person.NickName.Equals( Person.FirstName, StringComparison.OrdinalIgnoreCase ) ? string.Empty : Person.NickName ); tbMiddleName.Text = Person.MiddleName; tbLastName.Text = Person.LastName; ddlSuffix.SelectedValue = Person.SuffixValueId.HasValue ? Person.SuffixValueId.Value.ToString() : string.Empty; bpBirthDay.SelectedDate = Person.BirthDate; if ( Person.GraduationYear.HasValue ) { ypGraduation.SelectedYear = Person.GraduationYear.Value; } else { ypGraduation.SelectedYear = null; } if ( !Person.HasGraduated ?? false ) { int gradeOffset = Person.GradeOffset.Value; var maxGradeOffset = ddlGradePicker.MaxGradeOffset; // keep trying until we find a Grade that has a gradeOffset that that includes the Person's gradeOffset (for example, there might be combined grades) while ( !ddlGradePicker.Items.OfType<ListItem>().Any( a => a.Value.AsInteger() == gradeOffset ) && gradeOffset <= maxGradeOffset ) { gradeOffset++; } ddlGradePicker.SetValue( gradeOffset ); } else { ddlGradePicker.SelectedIndex = 0; } dpAnniversaryDate.SelectedDate = Person.AnniversaryDate; rblGender.SelectedValue = Person.Gender.ConvertToString( false ); ddlMaritalStatus.SelectedValue = Person.MaritalStatusValueId.HasValue ? Person.MaritalStatusValueId.Value.ToString() : string.Empty; ddlConnectionStatus.SelectedValue = Person.ConnectionStatusValueId.HasValue ? Person.ConnectionStatusValueId.Value.ToString() : string.Empty; tbEmail.Text = Person.Email; cbIsEmailActive.Checked = Person.IsEmailActive; rblEmailPreference.SelectedValue = Person.EmailPreference.ConvertToString( false ); ddlRecordStatus.SelectedValue = Person.RecordStatusValueId.HasValue ? Person.RecordStatusValueId.Value.ToString() : string.Empty; ddlReason.SelectedValue = Person.RecordStatusReasonValueId.HasValue ? Person.RecordStatusReasonValueId.Value.ToString() : string.Empty; tbInactiveReasonNote.Text = Person.InactiveReasonNote; bool showInactiveReason = ( Person.RecordStatusValueId.HasValue && Person.RecordStatusValueId.Value == DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id ); ddlReason.Visible = showInactiveReason; tbInactiveReasonNote.Visible = showInactiveReason; var mobilePhoneType = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE ) ); var phoneNumbers = new List<PhoneNumber>(); var phoneNumberTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ) ); if ( phoneNumberTypes.DefinedValues.Any() ) { foreach ( var phoneNumberType in phoneNumberTypes.DefinedValues ) { var phoneNumber = Person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberType.Id ); if ( phoneNumber == null ) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Value = phoneNumberType.Value; phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id; } else { // Update number format, just in case it wasn't saved correctly phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber( phoneNumber.CountryCode, phoneNumber.Number ); } phoneNumbers.Add( phoneNumber ); } rContactInfo.DataSource = phoneNumbers; rContactInfo.DataBind(); } ddlGivingGroup.SetValue( Person.GivingGroupId ); this.PersonPreviousNamesState = Person.GetPreviousNames().ToList(); BindPersonPreviousNamesGrid(); }
//using this to enter the Year Multi-Select GUID of a defined Year that is already in Rock private string MultiSelectYearGUID( DateTime? f1StartDate ) { DateTime startDate = (DateTime)f1StartDate; var lookupContext = new RockContext(); var dvService = new DefinedValueService( lookupContext ); var dtService = new DefinedTypeService( lookupContext ); var yearInList = new DefinedValue(); int dtInList; //= new DefinedType(); var yearMultiSelectDefinedType = dtService.Queryable() .Where( dt => dt.Name == "Year Multi-Selection" ).ToList(); //finds all rows in Defined Type with this name (only one present) dtInList = yearMultiSelectDefinedType.Where( dt => dt.Name == "Year Multi-Selection" ) //sets the above Defined Type ID to this variable. .Select( dt => dt.Id ).FirstOrDefault(); var existingDefinedYears = dvService.Queryable() .Where( dv => dv.DefinedTypeId == dtInList ).ToList(); //finds all Definded Values with the Defined Type ID from the item above. string guid = string.Format( "{0}", existingDefinedYears.Where( dt => dt.Value == string.Format( "{0}", startDate.Year ) ).Select( dt => dt.Guid ).FirstOrDefault() ); //the value that will be returned. return guid; //if (f1StartDate != null) //{ // switch (startDate.Year) // { // case 2001: // guid = "B9A40993-7758-49A3-BE6B-00E930FCF690"; // break; // case 2002: // guid = "56BF96EF-561E-424D-BA85-A93674569B47"; // break; // case 2003: // guid = "74EB6703-DEB4-4CEA-81E2-5EC7ED81BB18"; // break; // case 2004: // guid = "DD28ACBD-8B2C-49CC-81C9-B7FFE4D8E3C2"; // break; // case 2005: // guid = "F18A88B7-5228-4B7D-8079-4B118DF792C7"; // break; // case 2006: // guid = "719DF19D-B5AF-4125-B708-BDC22EB64E8F"; // break; // case 2007: // guid = "CE44EA17-020E-4B97-8975-4DE01830163D"; // break; // case 2008: // guid = "6810C1C9-85BD-42E9-9E04-85801A93096D"; // break; // case 2009: // guid = "2C8B55AF-B5E2-41F9-9E08-C2E6F4624550"; // break; // case 2010: // guid = "FB260D37-AEF4-4277-959C-5884E579E1AC"; // break; // case 2011: // guid = "6E84915B-CC11-4E66-954E-9B1D786B2E6F"; // break; // case 2012: // guid = "4ED12DFD-BA8F-4760-A045-E7AC898BEC50"; // break; // case 2013: // guid = "AFEC8401-3E49-4895-B320-6FF4918A5F4D"; // break; // case 2014: // guid = "F80B2BEA-5FA5-48C4-82FF-AC5E1A15C763"; // break; // default: // guid = "none"; // break; // } // return guid; //} //else //{ // return "none"; //} }
public ExceptionSpec(DefinedValue value) { }
//using this to enter the Connect Group Seasons GUID of a defined Year that is already in Rock private string CrossroadsSportsCampYears( DateTime? f1StartDate, string playVol ) { DateTime startDate = (DateTime)f1StartDate; var lookupContext = new RockContext(); var dvService = new DefinedValueService( lookupContext ); var dtService = new DefinedTypeService( lookupContext ); var yearInList = new DefinedValue(); int dtInList; //= new DefinedType(); var yearMultiSelectDefinedType = dtService.Queryable() .Where( dt => dt.Name == "Crossroads Sports Camp Years" ).ToList(); //finds all rows in Defined Type with this name (only one present) dtInList = yearMultiSelectDefinedType.Where( dt => dt.Name == "Crossroads Sports Camp Years" ) //sets the above Defined Type ID to this variable. .Select( dt => dt.Id ).FirstOrDefault(); var existingDefinedYears = dvService.Queryable() .Where( dv => dv.DefinedTypeId == dtInList ).ToList(); //finds all Definded Values with the Defined Type ID from the item above. string guid = string.Format( "{0}", existingDefinedYears.Where( dt => dt.Value == string.Format( "{0} ({1})", startDate.Year, playVol ) ).Select( dt => dt.Guid ).FirstOrDefault() ); //the value that will be returned. Takes on two properties, the start date and the second word (Play) etc. return guid; }
/// <summary> /// Maps the contribution. /// </summary> /// <param name="tableData">The table data.</param> /// <param name="selectedColumns">The selected columns.</param> private void MapContribution( IQueryable<Row> tableData, List<string> selectedColumns = null ) { var lookupContext = new RockContext(); int transactionEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialTransaction" ).Id; var transactionTypeContributionId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ), lookupContext ).Id; var currencyTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE ) ); int currencyTypeACH = currencyTypes.DefinedValues.FirstOrDefault( dv => dv.Guid.Equals( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH ) ) ).Id; int currencyTypeCash = currencyTypes.DefinedValues.FirstOrDefault( dv => dv.Guid.Equals( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CASH ) ) ).Id; int currencyTypeCheck = currencyTypes.DefinedValues.FirstOrDefault( dv => dv.Guid.Equals( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK ) ) ).Id; int currencyTypeCreditCard = currencyTypes.DefinedValues.FirstOrDefault( dv => dv.Guid.Equals( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD ) ) ).Id; int? currencyTypeNonCash = currencyTypes.DefinedValues.Where( dv => dv.Value.Equals( "Non-Cash" ) ).Select( dv => (int?)dv.Id ).FirstOrDefault(); if ( currencyTypeNonCash == null ) { var newTenderNonCash = new DefinedValue(); newTenderNonCash.Value = "Non-Cash"; newTenderNonCash.Description = "Non-Cash"; newTenderNonCash.DefinedTypeId = currencyTypes.Id; lookupContext.DefinedValues.Add( newTenderNonCash ); lookupContext.SaveChanges(); currencyTypeNonCash = newTenderNonCash.Id; } var creditCardTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE ) ).DefinedValues; int sourceTypeOnsite = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_ONSITE_COLLECTION ), lookupContext ).Id; int sourceTypeWebsite = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_WEBSITE ), lookupContext ).Id; int sourceTypeKiosk = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_KIOSK ), lookupContext ).Id; var refundReasons = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON ), lookupContext ).DefinedValues; var accountList = new FinancialAccountService( lookupContext ).Queryable().AsNoTracking().ToList(); int? defaultBatchId = null; if ( ImportedBatches.ContainsKey( 0 ) ) { defaultBatchId = ImportedBatches[0]; } // Get all imported contributions var importedContributions = new FinancialTransactionService( lookupContext ).Queryable().AsNoTracking() .Where( c => c.ForeignId != null ) .ToDictionary( t => (int)t.ForeignId, t => (int?)t.Id ); // List for batching new contributions var newTransactions = new List<FinancialTransaction>(); int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Verifying contribution import ({0:N0} found, {1:N0} already exist).", totalRows, importedContributions.Count ) ); foreach ( var row in tableData.Where( r => r != null ) ) { int? individualId = row["Individual_ID"] as int?; int? householdId = row["Household_ID"] as int?; int? contributionId = row["ContributionID"] as int?; if ( contributionId != null && !importedContributions.ContainsKey( (int)contributionId ) ) { var transaction = new FinancialTransaction(); transaction.CreatedByPersonAliasId = ImportPersonAliasId; transaction.ModifiedByPersonAliasId = ImportPersonAliasId; transaction.TransactionTypeValueId = transactionTypeContributionId; transaction.ForeignKey = contributionId.ToString(); transaction.ForeignId = contributionId; int? giverAliasId = null; var personKeys = GetPersonKeys( individualId, householdId ); if ( personKeys != null && personKeys.PersonAliasId > 0 ) { giverAliasId = personKeys.PersonAliasId; transaction.CreatedByPersonAliasId = giverAliasId; transaction.AuthorizedPersonAliasId = giverAliasId; transaction.ProcessedByPersonAliasId = giverAliasId; } string summary = row["Memo"] as string; if ( summary != null ) { transaction.Summary = summary; } int? batchId = row["BatchID"] as int?; if ( batchId != null && ImportedBatches.Any( b => b.Key.Equals( batchId ) ) ) { transaction.BatchId = ImportedBatches.FirstOrDefault( b => b.Key.Equals( batchId ) ).Value; } else { // use the default batch for any non-matching transactions transaction.BatchId = defaultBatchId; } DateTime? receivedDate = row["Received_Date"] as DateTime?; if ( receivedDate != null ) { transaction.TransactionDateTime = receivedDate; transaction.CreatedDateTime = receivedDate; transaction.ModifiedDateTime = ImportDateTime; } string cardType = row["Card_Type"] as string; string cardLastFour = row["Last_Four"] as string; string contributionType = row["Contribution_Type_Name"].ToStringSafe().ToLower(); if ( contributionType != null ) { // set default source to onsite, exceptions listed below transaction.SourceTypeValueId = sourceTypeOnsite; int? paymentCurrencyTypeId = null, creditCardTypeId = null; if ( contributionType == "cash" ) { paymentCurrencyTypeId = currencyTypeCash; } else if ( contributionType == "check" ) { paymentCurrencyTypeId = currencyTypeCheck; } else if ( contributionType == "ach" ) { paymentCurrencyTypeId = currencyTypeACH; transaction.SourceTypeValueId = sourceTypeWebsite; } else if ( contributionType == "credit card" ) { paymentCurrencyTypeId = currencyTypeCreditCard; transaction.SourceTypeValueId = sourceTypeWebsite; if ( cardType != null ) { creditCardTypeId = creditCardTypes.Where( t => t.Value.Equals( cardType ) ).Select( t => (int?)t.Id ).FirstOrDefault(); } } else { paymentCurrencyTypeId = currencyTypeNonCash; } var paymentDetail = new FinancialPaymentDetail(); paymentDetail.CreatedDateTime = receivedDate; paymentDetail.CreatedByPersonAliasId = giverAliasId; paymentDetail.ModifiedDateTime = ImportDateTime; paymentDetail.ModifiedByPersonAliasId = giverAliasId; paymentDetail.CurrencyTypeValueId = paymentCurrencyTypeId; paymentDetail.CreditCardTypeValueId = creditCardTypeId; paymentDetail.AccountNumberMasked = cardLastFour; paymentDetail.ForeignKey = contributionId.ToString(); paymentDetail.ForeignId = contributionId; transaction.FinancialPaymentDetail = paymentDetail; } string checkNumber = row["Check_Number"] as string; // if the check number is valid, put it in the transaction code if ( checkNumber.AsType<int?>() != null ) { transaction.TransactionCode = checkNumber; } // check for SecureGive kiosk transactions else if ( !string.IsNullOrEmpty( checkNumber ) && checkNumber.StartsWith( "SG" ) ) { transaction.SourceTypeValueId = sourceTypeKiosk; } string fundName = row["Fund_Name"] as string; string subFund = row["Sub_Fund_Name"] as string; string fundGLAccount = row["Fund_GL_Account"] as string; string subFundGLAccount = row["Sub_Fund_GL_Account"] as string; Boolean? isFundActive = row["Fund_Is_active"] as Boolean?; decimal? statedValue = row["Stated_Value"] as decimal?; decimal? amount = row["Amount"] as decimal?; if ( fundName != null & amount != null ) { int transactionAccountId; var parentAccount = accountList.FirstOrDefault( a => a.Name.Equals( fundName ) && a.CampusId == null ); if ( parentAccount == null ) { parentAccount = AddAccount( lookupContext, fundName, fundGLAccount, null, null, isFundActive ); accountList.Add( parentAccount ); } if ( subFund != null ) { int? campusFundId = null; // assign a campus if the subfund is a campus fund var campusFund = CampusList.FirstOrDefault( c => subFund.StartsWith( c.Name ) || subFund.StartsWith( c.ShortCode ) ); if ( campusFund != null ) { // use full campus name as the subfund subFund = campusFund.Name; campusFundId = campusFund.Id; } // add info to easily find/assign this fund in the view subFund = string.Format( "{0} {1}", subFund, fundName ); var childAccount = accountList.FirstOrDefault( c => c.Name.Equals( subFund ) && c.ParentAccountId == parentAccount.Id ); if ( childAccount == null ) { // create a child account with a campusId if it was set childAccount = AddAccount( lookupContext, subFund, subFundGLAccount, campusFundId, parentAccount.Id, isFundActive ); accountList.Add( childAccount ); } transactionAccountId = childAccount.Id; } else { transactionAccountId = parentAccount.Id; } if ( amount == 0 && statedValue != null && statedValue != 0 ) { amount = statedValue; } var transactionDetail = new FinancialTransactionDetail(); transactionDetail.Amount = (decimal)amount; transactionDetail.CreatedDateTime = receivedDate; transactionDetail.AccountId = transactionAccountId; transaction.TransactionDetails.Add( transactionDetail ); if ( amount < 0 ) { transaction.RefundDetails = new FinancialTransactionRefund(); transaction.RefundDetails.CreatedDateTime = receivedDate; transaction.RefundDetails.RefundReasonValueId = refundReasons.Where( dv => summary != null && dv.Value.Contains( summary ) ) .Select( dv => (int?)dv.Id ).FirstOrDefault(); transaction.RefundDetails.RefundReasonSummary = summary; } } newTransactions.Add( transaction ); completed++; if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} contributions imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { SaveContributions( newTransactions ); newTransactions.Clear(); ReportPartialProgress(); } } } if ( newTransactions.Any() ) { SaveContributions( newTransactions ); } ReportProgress( 100, string.Format( "Finished contribution import: {0:N0} contributions imported.", completed ) ); }
/// <summary> /// Shows the details. /// </summary> private void ShowDetails() { lTitle.Text = String.Format("Edit: {0}", Person.FullName).FormatAsHtmlTitle(); imgPhoto.BinaryFileId = Person.PhotoId; imgPhoto.NoPictureUrl = Person.GetPhotoUrl(null, Person.Gender); ddlTitle.SelectedValue = Person.TitleValueId.HasValue ? Person.TitleValueId.Value.ToString() : string.Empty; tbFirstName.Text = Person.FirstName; tbNickName.Text = string.IsNullOrWhiteSpace(Person.NickName) ? "" : (Person.NickName.Equals(Person.FirstName, StringComparison.OrdinalIgnoreCase) ? "" : Person.NickName); tbMiddleName.Text = Person.MiddleName; tbLastName.Text = Person.LastName; ddlSuffix.SelectedValue = Person.SuffixValueId.HasValue ? Person.SuffixValueId.Value.ToString() : string.Empty; bpBirthDay.SelectedDate = Person.BirthDate; string selectedGrade = ""; if (Person.GraduationDate.HasValue) { int gradeMaxFactorReactor = (RockDateTime.Now < _gradeTransitionDate) ? 12 : 13; int grade = gradeMaxFactorReactor - (Person.GraduationDate.Value.Year - RockDateTime.Now.Year); if (grade >= 0 && grade <= 12) { selectedGrade = grade.ToString(); } ypGraduation.SelectedYear = Person.GraduationDate.Value.Year; } else { ypGraduation.SelectedYear = null; } ddlGrade.SelectedValue = selectedGrade; dpAnniversaryDate.SelectedDate = Person.AnniversaryDate; rblGender.SelectedValue = Person.Gender.ConvertToString(false); rblMaritalStatus.SelectedValue = Person.MaritalStatusValueId.HasValue ? Person.MaritalStatusValueId.Value.ToString() : string.Empty; rblStatus.SelectedValue = Person.ConnectionStatusValueId.HasValue ? Person.ConnectionStatusValueId.Value.ToString() : string.Empty; tbEmail.Text = Person.Email; cbIsEmailActive.Checked = Person.IsEmailActive ?? true; rblEmailPreference.SelectedValue = Person.EmailPreference.ConvertToString(false); ddlRecordStatus.SelectedValue = Person.RecordStatusValueId.HasValue ? Person.RecordStatusValueId.Value.ToString() : string.Empty; ddlReason.SelectedValue = Person.RecordStatusReasonValueId.HasValue ? Person.RecordStatusReasonValueId.Value.ToString() : string.Empty; ddlReason.Visible = Person.RecordStatusReasonValueId.HasValue && Person.RecordStatusValueId.Value == DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id; var mobilePhoneType = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE)); var phoneNumbers = new List <PhoneNumber>(); var phoneNumberTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE)); if (phoneNumberTypes.DefinedValues.Any()) { foreach (var phoneNumberType in phoneNumberTypes.DefinedValues) { var phoneNumber = Person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberType.Id); if (phoneNumber == null) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Name = phoneNumberType.Name; phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id; } else { // Update number format, just in case it wasn't saved correctly phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber(phoneNumber.CountryCode, phoneNumber.Number); } phoneNumbers.Add(phoneNumber); } rContactInfo.DataSource = phoneNumbers; rContactInfo.DataBind(); } ddlGivingGroup.SetValue(Person.GivingGroupId); }
private void AddProperty( string key, string label, int personId, DefinedValue value, bool selected = false ) { var property = GetProperty( key, true, label ); var propertyValue = property.Values.Where( v => v.PersonId == personId ).FirstOrDefault(); if ( propertyValue == null ) { propertyValue = new PersonPropertyValue { PersonId = personId }; property.Values.Add( propertyValue ); } propertyValue.Value = value != null ? value.Id.ToString() : string.Empty; propertyValue.FormattedValue = value != null ? value.Value : string.Empty; propertyValue.Selected = selected; }
/// <summary> /// Shows the details. /// </summary> private void ShowDetails() { lTitle.Text = String.Format("Edit: {0}", Person.FullName).FormatAsHtmlTitle(); imgPhoto.BinaryFileId = Person.PhotoId; imgPhoto.NoPictureUrl = Person.GetPhotoUrl(null, Person.Age, Person.Gender); ddlTitle.SelectedValue = Person.TitleValueId.HasValue ? Person.TitleValueId.Value.ToString() : string.Empty; tbFirstName.Text = Person.FirstName; tbNickName.Text = string.IsNullOrWhiteSpace(Person.NickName) ? "" : (Person.NickName.Equals(Person.FirstName, StringComparison.OrdinalIgnoreCase) ? "" : Person.NickName); tbMiddleName.Text = Person.MiddleName; tbLastName.Text = Person.LastName; ddlSuffix.SelectedValue = Person.SuffixValueId.HasValue ? Person.SuffixValueId.Value.ToString() : string.Empty; bpBirthDay.SelectedDate = Person.BirthDate; if (Person.GraduationYear.HasValue) { ypGraduation.SelectedYear = Person.GraduationYear.Value; } else { ypGraduation.SelectedYear = null; } if (!Person.HasGraduated ?? false) { int gradeOffset = Person.GradeOffset.Value; var maxGradeOffset = ddlGradePicker.MaxGradeOffset;; // keep trying until we find a Grade that has a gradeOffset that that includes the Person's gradeOffset (for example, there might be combined grades) while (!ddlGradePicker.Items.OfType <ListItem>().Any(a => a.Value.AsInteger() == gradeOffset) && gradeOffset <= maxGradeOffset) { gradeOffset++; } ddlGradePicker.SetValue(gradeOffset); } else { ddlGradePicker.SelectedIndex = 0; } dpAnniversaryDate.SelectedDate = Person.AnniversaryDate; rblGender.SelectedValue = Person.Gender.ConvertToString(false); ddlMaritalStatus.SelectedValue = Person.MaritalStatusValueId.HasValue ? Person.MaritalStatusValueId.Value.ToString() : string.Empty; ddlConnectionStatus.SelectedValue = Person.ConnectionStatusValueId.HasValue ? Person.ConnectionStatusValueId.Value.ToString() : string.Empty; tbEmail.Text = Person.Email; cbIsEmailActive.Checked = Person.IsEmailActive ?? true; rblEmailPreference.SelectedValue = Person.EmailPreference.ConvertToString(false); ddlRecordStatus.SelectedValue = Person.RecordStatusValueId.HasValue ? Person.RecordStatusValueId.Value.ToString() : string.Empty; ddlReason.SelectedValue = Person.RecordStatusReasonValueId.HasValue ? Person.RecordStatusReasonValueId.Value.ToString() : string.Empty; tbInactiveReasonNote.Text = Person.InactiveReasonNote; bool showInactiveReason = (Person.RecordStatusValueId.HasValue && Person.RecordStatusValueId.Value == DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id); ddlReason.Visible = showInactiveReason; tbInactiveReasonNote.Visible = showInactiveReason; var mobilePhoneType = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE)); var phoneNumbers = new List <PhoneNumber>(); var phoneNumberTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE)); if (phoneNumberTypes.DefinedValues.Any()) { foreach (var phoneNumberType in phoneNumberTypes.DefinedValues) { var phoneNumber = Person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberType.Id); if (phoneNumber == null) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Value = phoneNumberType.Value; phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id; } else { // Update number format, just in case it wasn't saved correctly phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber(phoneNumber.CountryCode, phoneNumber.Number); } phoneNumbers.Add(phoneNumber); } rContactInfo.DataSource = phoneNumbers; rContactInfo.DataBind(); } ddlGivingGroup.SetValue(Person.GivingGroupId); }
/// <summary> /// Maps the communication data. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapCommunication( IQueryable<Row> tableData ) { var lookupContext = new RockContext(); var personService = new PersonService( lookupContext ); var attributeService = new AttributeService( lookupContext ); var definedTypePhoneType = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ), lookupContext ); var otherNumberType = definedTypePhoneType.DefinedValues.Where( dv => dv.Value.StartsWith( "Other" ) ).Select( v => (int?)v.Id ).FirstOrDefault(); if ( otherNumberType == null ) { var otherType = new DefinedValue(); otherType.IsSystem = false; otherType.DefinedTypeId = definedTypePhoneType.Id; otherType.Order = 0; otherType.Value = "Other"; otherType.Description = "Imported from FellowshipOne"; otherType.CreatedByPersonAliasId = ImportPersonAliasId; lookupContext.DefinedValues.Add( otherType ); lookupContext.SaveChanges( DisableAuditing ); } // Look up existing Person attributes var personAttributes = attributeService.GetByEntityTypeId( PersonEntityTypeId ).ToList(); // Cached Rock attributes: Facebook, Twitter, Instagram var twitterAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key.Equals( "Twitter", StringComparison.InvariantCultureIgnoreCase ) ) ); var facebookAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key.Equals( "Facebook", StringComparison.InvariantCultureIgnoreCase ) ) ); var instagramAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key.Equals( "Instagram", StringComparison.InvariantCultureIgnoreCase ) ) ); var newNumbers = new List<PhoneNumber>(); var existingNumbers = new PhoneNumberService( lookupContext ).Queryable().AsNoTracking().ToList(); var newPeopleAttributes = new Dictionary<int, Person>(); int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Verifying communication import ({0:N0} found, {1:N0} already exist).", totalRows, existingNumbers.Count ) ); foreach ( var groupedRows in tableData.OrderByDescending( r => r["LastUpdatedDate"] ).GroupBy<Row, int?>( r => r["Household_ID"] as int? ) ) { foreach ( var row in groupedRows.Where( r => r != null ) ) { string value = row["Communication_Value"] as string; int? individualId = row["Individual_ID"] as int?; int? householdId = row["Household_ID"] as int?; var peopleToUpdate = new List<PersonKeys>(); if ( individualId != null ) { var matchingPerson = GetPersonKeys( individualId, householdId, includeVisitors: false ); if ( matchingPerson != null ) { peopleToUpdate.Add( matchingPerson ); } } else { peopleToUpdate = GetFamilyByHouseholdId( householdId, includeVisitors: false ); } if ( peopleToUpdate.Any() && !string.IsNullOrWhiteSpace( value ) ) { DateTime? lastUpdated = row["LastUpdatedDate"] as DateTime?; string communicationComment = row["Communication_Comment"] as string; string type = row["Communication_Type"] as string; bool isListed = (bool)row["Listed"]; value = value.RemoveWhitespace(); // Communication value is a number if ( type.Contains( "Phone" ) || type.Contains( "Mobile" ) ) { var extension = string.Empty; var countryCode = PhoneNumber.DefaultCountryCode(); var normalizedNumber = string.Empty; var countryIndex = value.IndexOf( '+' ); int extensionIndex = value.LastIndexOf( 'x' ) > 0 ? value.LastIndexOf( 'x' ) : value.Length; if ( countryIndex >= 0 ) { countryCode = value.Substring( countryIndex, countryIndex + 3 ).AsNumeric(); normalizedNumber = value.Substring( countryIndex + 3, extensionIndex - 3 ).AsNumeric(); extension = value.Substring( extensionIndex ); } else if ( extensionIndex > 0 ) { normalizedNumber = value.Substring( 0, extensionIndex ).AsNumeric(); extension = value.Substring( extensionIndex ).AsNumeric(); } else { normalizedNumber = value.AsNumeric(); } if ( !string.IsNullOrWhiteSpace( normalizedNumber ) ) { foreach ( var personKeys in peopleToUpdate ) { bool numberExists = existingNumbers.Any( n => n.PersonId == personKeys.PersonId && n.Number.Equals( value ) ); if ( !numberExists ) { var newNumber = new PhoneNumber(); newNumber.CreatedByPersonAliasId = ImportPersonAliasId; newNumber.ModifiedDateTime = lastUpdated; newNumber.PersonId = (int)personKeys.PersonId; newNumber.IsMessagingEnabled = false; newNumber.CountryCode = countryCode; newNumber.IsUnlisted = !isListed; newNumber.Extension = extension.Left( 20 ) ?? string.Empty; newNumber.Number = normalizedNumber.Left( 20 ); newNumber.Description = communicationComment; newNumber.NumberFormatted = PhoneNumber.FormattedNumber( countryCode, newNumber.Number, true ); var matchingNumberType = definedTypePhoneType.DefinedValues.Where( v => type.StartsWith( v.Value ) ) .Select( v => (int?)v.Id ).FirstOrDefault(); newNumber.NumberTypeValueId = matchingNumberType ?? otherNumberType; newNumbers.Add( newNumber ); existingNumbers.Add( newNumber ); } } completed++; } } else { Person person = null; var personKeys = peopleToUpdate.FirstOrDefault(); if ( !newPeopleAttributes.ContainsKey( personKeys.PersonId ) ) { // not in dictionary, get person from database person = personService.Queryable( includeDeceased: true ).FirstOrDefault( p => p.Id == personKeys.PersonId ); } else { // reuse person from dictionary person = newPeopleAttributes[personKeys.PersonId]; } if ( person != null ) { if ( person.Attributes == null || person.AttributeValues == null ) { // make sure we have valid objects to assign to person.Attributes = new Dictionary<string, AttributeCache>(); person.AttributeValues = new Dictionary<string, AttributeValueCache>(); } // Check for an InFellowship ID/email before checking other types of email var isLoginValue = type.IndexOf( "InFellowship", StringComparison.OrdinalIgnoreCase ) >= 0; var personAlreadyHasLogin = person.Attributes.ContainsKey( InFellowshipLoginAttribute.Key ); if ( isLoginValue && !personAlreadyHasLogin ) { AddPersonAttribute( InFellowshipLoginAttribute, person, value ); AddUserLogin( AuthProviderEntityTypeId, person, value ); } else if ( value.IsEmail() ) { // person email is empty if ( string.IsNullOrWhiteSpace( person.Email ) ) { person.Email = value.Left( 75 ); person.IsEmailActive = isListed; person.EmailPreference = isListed ? EmailPreference.EmailAllowed : EmailPreference.DoNotEmail; person.ModifiedDateTime = lastUpdated; person.EmailNote = communicationComment; lookupContext.SaveChanges( DisableAuditing ); } // this is a different email, assign it to SecondaryEmail else if ( !person.Email.Equals( value ) && !person.Attributes.ContainsKey( SecondaryEmailAttribute.Key ) ) { AddPersonAttribute( SecondaryEmailAttribute, person, value ); } } else if ( type.Contains( "Twitter" ) && !person.Attributes.ContainsKey( twitterAttribute.Key ) ) { AddPersonAttribute( twitterAttribute, person, value ); } else if ( type.Contains( "Facebook" ) && !person.Attributes.ContainsKey( facebookAttribute.Key ) ) { AddPersonAttribute( facebookAttribute, person, value ); } else if ( type.Contains( "Instagram" ) && !person.Attributes.ContainsKey( instagramAttribute.Key ) ) { AddPersonAttribute( instagramAttribute, person, value ); } if ( !newPeopleAttributes.ContainsKey( personKeys.PersonId ) ) { newPeopleAttributes.Add( personKeys.PersonId, person ); } else { newPeopleAttributes[personKeys.PersonId] = person; } } completed++; } if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} records imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { if ( newNumbers.Any() || newPeopleAttributes.Any() ) { SaveCommunication( newNumbers, newPeopleAttributes ); } // reset so context doesn't bloat lookupContext = new RockContext(); personService = new PersonService( lookupContext ); newPeopleAttributes.Clear(); newNumbers.Clear(); ReportPartialProgress(); } } } } if ( newNumbers.Any() || newPeopleAttributes.Any() ) { SaveCommunication( newNumbers, newPeopleAttributes ); } ReportProgress( 100, string.Format( "Finished communication import: {0:N0} records imported.", completed ) ); }
/// <summary> /// Shows the details. /// </summary> private void ShowDetails() { lTitle.Text = String.Format( "Edit: {0}", Person.FullName ).FormatAsHtmlTitle(); imgPhoto.BinaryFileId = Person.PhotoId; ddlTitle.SelectedValue = Person.TitleValueId.HasValue ? Person.TitleValueId.Value.ToString() : string.Empty; tbFirstName.Text = Person.FirstName; tbNickName.Text = string.IsNullOrWhiteSpace( Person.NickName ) ? "" : ( Person.NickName.Equals( Person.FirstName, StringComparison.OrdinalIgnoreCase ) ? "" : Person.NickName ); tbMiddleName.Text = Person.MiddleName; tbLastName.Text = Person.LastName; ddlSuffix.SelectedValue = Person.SuffixValueId.HasValue ? Person.SuffixValueId.Value.ToString() : string.Empty; bpBirthDay.SelectedDate = Person.BirthDate; dpAnniversaryDate.SelectedDate = Person.AnniversaryDate; rblGender.SelectedValue = Person.Gender.ConvertToString(); rblMaritalStatus.SelectedValue = Person.MaritalStatusValueId.HasValue ? Person.MaritalStatusValueId.Value.ToString() : string.Empty; rblStatus.SelectedValue = Person.ConnectionStatusValueId.HasValue ? Person.ConnectionStatusValueId.Value.ToString() : string.Empty; tbEmail.Text = Person.Email; ddlRecordStatus.SelectedValue = Person.RecordStatusValueId.HasValue ? Person.RecordStatusValueId.Value.ToString() : string.Empty; ddlReason.SelectedValue = Person.RecordStatusReasonValueId.HasValue ? Person.RecordStatusReasonValueId.Value.ToString() : string.Empty; var mobilePhoneType = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE ) ); var phoneNumbers = new List<PhoneNumber>(); var phoneNumberTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ) ); if ( phoneNumberTypes.DefinedValues.Any() ) { foreach ( var phoneNumberType in phoneNumberTypes.DefinedValues ) { var phoneNumber = Person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberType.Id ); if ( phoneNumber == null ) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Name = phoneNumberType.Name; phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id; } phoneNumbers.Add( phoneNumber ); } rContactInfo.DataSource = phoneNumbers; rContactInfo.DataBind(); } ddlGivingGroup.SetValue( Person.GivingGroupId ); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad( System.EventArgs e ) { base.OnLoad( e ); pnlMessage.Controls.Clear(); pnlMessage.Visible = false; PagePanels[0] = phUserInfo; PagePanels[1] = phDuplicates; PagePanels[2] = phSendLoginInfo; PagePanels[3] = phSentLoginInfo; PagePanels[4] = phConfirmation; PagePanels[5] = phSuccess; if ( !Page.IsPostBack ) { DisplayUserInfo( Direction.Forward ); // show/hide address and phone panels pnlAddress.Visible = GetAttributeValue( "ShowAddress" ).AsBoolean(); pnlPhoneNumbers.Visible = GetAttributeValue( "ShowPhoneNumbers" ).AsBoolean(); acAddress.Required = GetAttributeValue( "AddressRequired" ).AsBoolean(); var phoneNumbers = new List<PhoneNumber>(); // add phone number types if ( pnlPhoneNumbers.Visible ) { var phoneNumberTypeDefinedType = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ) ); if (!string.IsNullOrWhiteSpace( GetAttributeValue( "PhoneTypes" ) ) ) { var selectedPhoneTypeGuids = GetAttributeValue( "PhoneTypes" ).Split( ',' ).Select( Guid.Parse ).ToList(); var selectedPhoneTypes = phoneNumberTypeDefinedType.DefinedValues.Where( v => selectedPhoneTypeGuids.Contains( v.Guid ) ).ToList(); foreach ( var phoneNumberType in selectedPhoneTypes ) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Value = phoneNumberType.Value; var phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumbers.Add( phoneNumber ); } rPhoneNumbers.DataSource = phoneNumbers; rPhoneNumbers.DataBind(); } } } }
/// <summary> /// Maps the contribution. /// </summary> /// <param name="csvData">The table data.</param> private int MapContribution(CSVInstance csvData) { var lookupContext = new RockContext(); int transactionEntityTypeId = EntityTypeCache.Read("Rock.Model.FinancialTransaction").Id; var transactionTypeContributionId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION), lookupContext).Id; var currencyTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE)); int currencyTypeACH = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH))).Id; int currencyTypeCash = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CASH))).Id; int currencyTypeCheck = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK))).Id; int currencyTypeCreditCard = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD))).Id; int?currencyTypeNonCash = currencyTypes.DefinedValues.Where(dv => dv.Value.Equals("Non-Cash")).Select(dv => (int?)dv.Id).FirstOrDefault(); if (currencyTypeNonCash == null) { var newTenderNonCash = new DefinedValue(); newTenderNonCash.Value = "Non-Cash"; newTenderNonCash.Description = "Non-Cash"; newTenderNonCash.DefinedTypeId = currencyTypes.Id; lookupContext.DefinedValues.Add(newTenderNonCash); lookupContext.SaveChanges(); currencyTypeNonCash = newTenderNonCash.Id; } var creditCardTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE)).DefinedValues; int sourceTypeOnsite = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_ONSITE_COLLECTION), lookupContext).Id; int sourceTypeWebsite = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_WEBSITE), lookupContext).Id; int sourceTypeKiosk = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_KIOSK), lookupContext).Id; var refundReasons = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON), lookupContext).DefinedValues; var accountList = new FinancialAccountService(lookupContext).Queryable().AsNoTracking().ToList(); int?defaultBatchId = null; if (ImportedBatches.ContainsKey(0)) { defaultBatchId = ImportedBatches[0]; } // Get all imported contributions var importedContributions = new FinancialTransactionService(lookupContext).Queryable().AsNoTracking() .Where(c => c.ForeignId != null) .ToDictionary(t => (int)t.ForeignId, t => (int?)t.Id); // List for batching new contributions var newTransactions = new List <FinancialTransaction>(); int completed = 0; ReportProgress(0, string.Format("Verifying contribution import ({0:N0} already exist).", importedContributions.Count)); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { string individualIdKey = row[IndividualID]; int? individualId = individualIdKey.AsType <int?>(); string contributionIdKey = row[ContributionID]; int? contributionId = contributionIdKey.AsType <int?>(); if (contributionId != null && !importedContributions.ContainsKey((int)contributionId)) { var transaction = new FinancialTransaction(); transaction.CreatedByPersonAliasId = ImportPersonAliasId; transaction.ModifiedByPersonAliasId = ImportPersonAliasId; transaction.TransactionTypeValueId = transactionTypeContributionId; transaction.ForeignKey = contributionId.ToString(); transaction.ForeignId = contributionId; int?giverAliasId = null; var personKeys = GetPersonKeys(individualId); if (personKeys != null && personKeys.PersonAliasId > 0) { giverAliasId = personKeys.PersonAliasId; transaction.CreatedByPersonAliasId = giverAliasId; transaction.AuthorizedPersonAliasId = giverAliasId; transaction.ProcessedByPersonAliasId = giverAliasId; } string summary = row[Memo] as string; if (summary != null) { transaction.Summary = summary; } string batchIdKey = row[ContributionBatchID]; int? batchId = batchIdKey.AsType <int?>(); if (batchId != null && ImportedBatches.Any(b => b.Key.Equals(batchId))) { transaction.BatchId = ImportedBatches.FirstOrDefault(b => b.Key.Equals(batchId)).Value; } else { // use the default batch for any non-matching transactions transaction.BatchId = defaultBatchId; } string receivedDateKey = row[ReceivedDate]; DateTime?receivedDate = receivedDateKey.AsType <DateTime?>(); if (receivedDate != null) { transaction.TransactionDateTime = receivedDate; transaction.CreatedDateTime = receivedDate; transaction.ModifiedDateTime = ImportDateTime; } string contributionType = row[ContributionTypeName].ToStringSafe().ToLower(); if (contributionType != null) { // set default source to onsite, exceptions listed below transaction.SourceTypeValueId = sourceTypeOnsite; int?paymentCurrencyTypeId = null, creditCardTypeId = null; if (contributionType == "cash") { paymentCurrencyTypeId = currencyTypeCash; } else if (contributionType == "check") { paymentCurrencyTypeId = currencyTypeCheck; } else if (contributionType == "ach") { paymentCurrencyTypeId = currencyTypeACH; transaction.SourceTypeValueId = sourceTypeWebsite; } else if (contributionType == "credit card") { paymentCurrencyTypeId = currencyTypeCreditCard; transaction.SourceTypeValueId = sourceTypeWebsite; } else { paymentCurrencyTypeId = currencyTypeNonCash; } var paymentDetail = new FinancialPaymentDetail(); paymentDetail.CreatedDateTime = receivedDate; paymentDetail.CreatedByPersonAliasId = giverAliasId; paymentDetail.ModifiedDateTime = ImportDateTime; paymentDetail.ModifiedByPersonAliasId = giverAliasId; paymentDetail.CurrencyTypeValueId = paymentCurrencyTypeId; paymentDetail.CreditCardTypeValueId = creditCardTypeId; paymentDetail.ForeignKey = contributionId.ToString(); paymentDetail.ForeignId = contributionId; transaction.FinancialPaymentDetail = paymentDetail; } string checkNumber = row[CheckNumber] as string; // if the check number is valid, put it in the transaction code if (checkNumber.AsType <int?>() != null) { transaction.TransactionCode = checkNumber; } // check for SecureGive kiosk transactions else if (!string.IsNullOrEmpty(checkNumber) && checkNumber.StartsWith("SG")) { transaction.SourceTypeValueId = sourceTypeKiosk; } string fundName = row[FundName] as string; string subFund = row[SubFundName] as string; string fundGLAccount = row[FundGLAccount] as string; string subFundGLAccount = row[SubFundGLAccount] as string; string isFundActiveKey = row[FundIsActive]; Boolean?isFundActive = isFundActiveKey.AsType <Boolean?>(); string statedValueKey = row[StatedValue]; decimal?statedValue = statedValueKey.AsType <decimal?>(); string amountKey = row[Amount]; decimal?amount = amountKey.AsType <decimal?>(); if (fundName != null & amount != null) { int transactionAccountId; var parentAccount = accountList.FirstOrDefault(a => a.Name.Equals(fundName) && a.CampusId == null); if (parentAccount == null) { parentAccount = AddAccount(lookupContext, fundName, fundGLAccount, null, null, isFundActive); accountList.Add(parentAccount); } if (!String.IsNullOrWhiteSpace(subFund)) { int?campusFundId = null; // assign a campus if the subfund is a campus fund var campusFund = CampusList.FirstOrDefault(c => subFund.StartsWith(c.Name) || subFund.StartsWith(c.ShortCode)); if (campusFund != null) { // use full campus name as the subfund subFund = campusFund.Name; campusFundId = campusFund.Id; } // add info to easily find/assign this fund in the view subFund = string.Format("{0} {1}", subFund, fundName); var childAccount = accountList.FirstOrDefault(c => c.Name.Equals(subFund) && c.ParentAccountId == parentAccount.Id); if (childAccount == null) { // create a child account with a campusId if it was set childAccount = AddAccount(lookupContext, subFund, subFundGLAccount, campusFundId, parentAccount.Id, isFundActive); accountList.Add(childAccount); } transactionAccountId = childAccount.Id; } else { transactionAccountId = parentAccount.Id; } if (amount == 0 && statedValue != null && statedValue != 0) { amount = statedValue; } var transactionDetail = new FinancialTransactionDetail(); transactionDetail.Amount = (decimal)amount; transactionDetail.CreatedDateTime = receivedDate; transactionDetail.AccountId = transactionAccountId; transaction.TransactionDetails.Add(transactionDetail); if (amount < 0) { transaction.RefundDetails = new FinancialTransactionRefund(); transaction.RefundDetails.CreatedDateTime = receivedDate; transaction.RefundDetails.RefundReasonValueId = refundReasons.Where(dv => summary != null && dv.Value.Contains(summary)) .Select(dv => (int?)dv.Id).FirstOrDefault(); transaction.RefundDetails.RefundReasonSummary = summary; } } newTransactions.Add(transaction); completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, string.Format("{0:N0} contributions imported.", completed)); } else if (completed % ReportingNumber < 1) { SaveContributions(newTransactions); newTransactions.Clear(); ReportPartialProgress(); } } } if (newTransactions.Any()) { SaveContributions(newTransactions); } ReportProgress(100, string.Format("Finished contribution import: {0:N0} contributions imported.", completed)); return(completed); }
/// <summary> /// Handles the Click event of the btnSaveDefinedValue 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 btnSaveValue_Click( object sender, EventArgs e ) { DefinedValue definedValue; DefinedValueService definedValueService = new DefinedValueService(); int definedValueId = hfDefinedValueId.ValueAsInt(); if ( definedValueId.Equals( 0 ) ) { int definedTypeId = hfDefinedTypeId.ValueAsInt(); definedValue = new DefinedValue { Id = 0 }; definedValue.DefinedTypeId = definedTypeId; definedValue.IsSystem = false; var orders = definedValueService.Queryable() .Where( d => d.DefinedTypeId == definedTypeId ) .Select( d => d.Order) .ToList(); definedValue.Order = orders.Any() ? orders.Max() + 1 : 0; } else { definedValue = definedValueService.Get( definedValueId ); } definedValue.Name = tbValueName.Text; definedValue.Description = tbValueDescription.Text; definedValue.LoadAttributes(); Rock.Attribute.Helper.GetEditValues( phDefinedValueAttributes, definedValue ); if ( !Page.IsValid ) { return; } if ( !definedValue.IsValid ) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction( () => { if ( definedValue.Id.Equals( 0 ) ) { definedValueService.Add( definedValue, CurrentPersonId ); } definedValueService.Save( definedValue, CurrentPersonId ); Rock.Attribute.Helper.SaveAttributeValues( definedValue, CurrentPersonId ); Rock.Web.Cache.DefinedTypeCache.Flush( definedValue.DefinedTypeId ); Rock.Web.Cache.DefinedValueCache.Flush( definedValue.Id ); } ); BindDefinedValuesGrid(); hfDefinedValueId.Value = string.Empty; modalValue.Hide(); }
/// <summary> /// Binds the defined values grid. /// </summary> protected void AddAttributeColumns() { // Remove attribute columns foreach ( var column in gDefinedValues.Columns.OfType<AttributeField>().ToList() ) { gDefinedValues.Columns.Remove( column ); } if ( _definedType != null ) { // Add attribute columns int entityTypeId = new DefinedValue().TypeId; string qualifier = _definedType.Id.ToString(); foreach ( var attribute in new AttributeService( new RockContext() ).Queryable() .Where( a => a.EntityTypeId == entityTypeId && a.IsGridColumn && a.EntityTypeQualifierColumn.Equals( "DefinedTypeId", StringComparison.OrdinalIgnoreCase ) && a.EntityTypeQualifierValue.Equals( qualifier ) ) .OrderBy( a => a.Order ) .ThenBy( a => a.Name ) ) { string dataFieldExpression = attribute.Key; bool columnExists = gDefinedValues.Columns.OfType<AttributeField>().FirstOrDefault( a => a.DataField.Equals( dataFieldExpression ) ) != null; if ( !columnExists ) { AttributeField boundField = new AttributeField(); boundField.DataField = dataFieldExpression; boundField.HeaderText = attribute.Name; boundField.SortExpression = string.Empty; var attributeCache = Rock.Web.Cache.AttributeCache.Read( attribute.Id ); if ( attributeCache != null ) { boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue; } gDefinedValues.Columns.Add( boundField ); } } } }
/// <summary> /// Shows the details. /// </summary> private void ShowDetails() { lTitle.Text = String.Format( "Edit: {0}", Person.FullName ).FormatAsHtmlTitle(); imgPhoto.BinaryFileId = Person.PhotoId; imgPhoto.NoPictureUrl = Person.GetPhotoUrl( null, Person.Gender ); ddlTitle.SelectedValue = Person.TitleValueId.HasValue ? Person.TitleValueId.Value.ToString() : string.Empty; tbFirstName.Text = Person.FirstName; tbNickName.Text = string.IsNullOrWhiteSpace( Person.NickName ) ? "" : ( Person.NickName.Equals( Person.FirstName, StringComparison.OrdinalIgnoreCase ) ? "" : Person.NickName ); tbMiddleName.Text = Person.MiddleName; tbLastName.Text = Person.LastName; ddlSuffix.SelectedValue = Person.SuffixValueId.HasValue ? Person.SuffixValueId.Value.ToString() : string.Empty; bpBirthDay.SelectedDate = Person.BirthDate; string selectedGrade = ""; if ( Person.GraduationDate.HasValue ) { int gradeMaxFactorReactor = ( RockDateTime.Now < _gradeTransitionDate ) ? 12 : 13; int grade = gradeMaxFactorReactor - ( Person.GraduationDate.Value.Year - RockDateTime.Now.Year ); if (grade >= 0 && grade <= 12) { selectedGrade = grade.ToString(); } ypGraduation.SelectedYear = Person.GraduationDate.Value.Year; } else { ypGraduation.SelectedYear = null; } ddlGrade.SelectedValue = selectedGrade; dpAnniversaryDate.SelectedDate = Person.AnniversaryDate; rblGender.SelectedValue = Person.Gender.ConvertToString(false); rblMaritalStatus.SelectedValue = Person.MaritalStatusValueId.HasValue ? Person.MaritalStatusValueId.Value.ToString() : string.Empty; rblStatus.SelectedValue = Person.ConnectionStatusValueId.HasValue ? Person.ConnectionStatusValueId.Value.ToString() : string.Empty; tbEmail.Text = Person.Email; cbIsEmailActive.Checked = Person.IsEmailActive ?? true; rblEmailPreference.SelectedValue = Person.EmailPreference.ConvertToString(false); ddlRecordStatus.SelectedValue = Person.RecordStatusValueId.HasValue ? Person.RecordStatusValueId.Value.ToString() : string.Empty; ddlReason.SelectedValue = Person.RecordStatusReasonValueId.HasValue ? Person.RecordStatusReasonValueId.Value.ToString() : string.Empty; ddlReason.Visible = Person.RecordStatusReasonValueId.HasValue && Person.RecordStatusValueId.Value == DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id; var mobilePhoneType = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE ) ); var phoneNumbers = new List<PhoneNumber>(); var phoneNumberTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ) ); if ( phoneNumberTypes.DefinedValues.Any() ) { foreach ( var phoneNumberType in phoneNumberTypes.DefinedValues ) { var phoneNumber = Person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberType.Id ); if ( phoneNumber == null ) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Name = phoneNumberType.Name; phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id; } else { // Update number format, just in case it wasn't saved correctly phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber( phoneNumber.CountryCode, phoneNumber.Number ); } phoneNumbers.Add( phoneNumber ); } rContactInfo.DataSource = phoneNumbers; rContactInfo.DataBind(); } ddlGivingGroup.SetValue( Person.GivingGroupId ); }
/// <summary> /// Maps the contribution. /// </summary> /// <param name="tableData">The table data.</param> /// <param name="selectedColumns">The selected columns.</param> private void MapContribution(IQueryable <Row> tableData, List <string> selectedColumns = null) { var lookupContext = new RockContext(); int transactionEntityTypeId = EntityTypeCache.Read("Rock.Model.FinancialTransaction").Id; var transactionTypeContributionId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION), lookupContext).Id; var currencyTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE)); int currencyTypeACH = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH))).Id; int currencyTypeCash = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CASH))).Id; int currencyTypeCheck = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK))).Id; int currencyTypeCreditCard = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD))).Id; int?currencyTypeNonCash = currencyTypes.DefinedValues.Where(dv => dv.Value.Equals("Non-Cash")).Select(dv => (int?)dv.Id).FirstOrDefault(); if (currencyTypeNonCash == null) { var newTenderNonCash = new DefinedValue(); newTenderNonCash.Value = "Non-Cash"; newTenderNonCash.Description = "Non-Cash"; newTenderNonCash.DefinedTypeId = currencyTypes.Id; lookupContext.DefinedValues.Add(newTenderNonCash); lookupContext.SaveChanges(); currencyTypeNonCash = newTenderNonCash.Id; } var creditCardTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE)).DefinedValues; int sourceTypeOnsite = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_ONSITE_COLLECTION), lookupContext).Id; int sourceTypeWebsite = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_WEBSITE), lookupContext).Id; int sourceTypeKiosk = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_KIOSK), lookupContext).Id; var refundReasons = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON), lookupContext).DefinedValues; var accountList = new FinancialAccountService(lookupContext).Queryable().AsNoTracking().ToList(); int?defaultBatchId = null; if (ImportedBatches.ContainsKey(0)) { defaultBatchId = ImportedBatches[0]; } // Get all imported contributions var importedContributions = new FinancialTransactionService(lookupContext).Queryable().AsNoTracking() .Where(c => c.ForeignId != null) .ToDictionary(t => (int)t.ForeignId, t => (int?)t.Id); // List for batching new contributions var newTransactions = new List <FinancialTransaction>(); int completed = 0; int totalRows = tableData.Count(); int percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying contribution import ({0:N0} found, {1:N0} already exist).", totalRows, importedContributions.Count)); foreach (var row in tableData.Where(r => r != null)) { int?individualId = row["Individual_ID"] as int?; int?householdId = row["Household_ID"] as int?; int?contributionId = row["ContributionID"] as int?; if (contributionId != null && !importedContributions.ContainsKey((int)contributionId)) { var transaction = new FinancialTransaction(); transaction.CreatedByPersonAliasId = ImportPersonAliasId; transaction.ModifiedByPersonAliasId = ImportPersonAliasId; transaction.TransactionTypeValueId = transactionTypeContributionId; transaction.ForeignKey = contributionId.ToString(); transaction.ForeignId = contributionId; int?giverAliasId = null; var personKeys = GetPersonKeys(individualId, householdId); if (personKeys != null && personKeys.PersonAliasId > 0) { giverAliasId = personKeys.PersonAliasId; transaction.CreatedByPersonAliasId = giverAliasId; transaction.AuthorizedPersonAliasId = giverAliasId; transaction.ProcessedByPersonAliasId = giverAliasId; } string summary = row["Memo"] as string; if (summary != null) { transaction.Summary = summary; } int?batchId = row["BatchID"] as int?; if (batchId != null && ImportedBatches.Any(b => b.Key.Equals(batchId))) { transaction.BatchId = ImportedBatches.FirstOrDefault(b => b.Key.Equals(batchId)).Value; } else { // use the default batch for any non-matching transactions transaction.BatchId = defaultBatchId; } DateTime?receivedDate = row["Received_Date"] as DateTime?; if (receivedDate != null) { transaction.TransactionDateTime = receivedDate; transaction.CreatedDateTime = receivedDate; transaction.ModifiedDateTime = ImportDateTime; } var contributionFields = row.Columns.Select(c => c.Name).ToList(); string cardType = contributionFields.Contains("Card_Type") ? row["Card_Type"] as string : string.Empty; string cardLastFour = contributionFields.Contains("Last_Four") ? row["Last_Four"] as string : string.Empty; string contributionType = contributionFields.Contains("Contribution_Type_Name") ? row["Contribution_Type_Name"] as string : string.Empty; if (!string.IsNullOrEmpty(contributionType)) { // set default source to onsite, exceptions listed below transaction.SourceTypeValueId = sourceTypeOnsite; contributionType = contributionType.ToLower(); int?paymentCurrencyTypeId = null, creditCardTypeId = null; if (contributionType == "cash") { paymentCurrencyTypeId = currencyTypeCash; } else if (contributionType == "check") { paymentCurrencyTypeId = currencyTypeCheck; } else if (contributionType == "ach") { paymentCurrencyTypeId = currencyTypeACH; transaction.SourceTypeValueId = sourceTypeWebsite; } else if (contributionType == "credit card") { paymentCurrencyTypeId = currencyTypeCreditCard; transaction.SourceTypeValueId = sourceTypeWebsite; if (!string.IsNullOrEmpty(cardType)) { creditCardTypeId = creditCardTypes.Where(t => t.Value.Equals(cardType)).Select(t => (int?)t.Id).FirstOrDefault(); } } else { paymentCurrencyTypeId = currencyTypeNonCash; } var paymentDetail = new FinancialPaymentDetail(); paymentDetail.CreatedDateTime = receivedDate; paymentDetail.CreatedByPersonAliasId = giverAliasId; paymentDetail.ModifiedDateTime = ImportDateTime; paymentDetail.ModifiedByPersonAliasId = giverAliasId; paymentDetail.CurrencyTypeValueId = paymentCurrencyTypeId; paymentDetail.CreditCardTypeValueId = creditCardTypeId; paymentDetail.AccountNumberMasked = cardLastFour; paymentDetail.ForeignKey = contributionId.ToString(); paymentDetail.ForeignId = contributionId; transaction.FinancialPaymentDetail = paymentDetail; } string checkNumber = row["Check_Number"] as string; // if the check number is valid, put it in the transaction code if (checkNumber.AsType <int?>() != null) { transaction.TransactionCode = checkNumber; } // check for SecureGive kiosk transactions else if (!string.IsNullOrEmpty(checkNumber) && checkNumber.StartsWith("SG")) { transaction.SourceTypeValueId = sourceTypeKiosk; } string fundName = contributionFields.Contains("Fund_Name") ? row["Fund_Name"] as string : string.Empty; string subFund = contributionFields.Contains("Sub_Fund_Name") ? row["Sub_Fund_Name"] as string : string.Empty; string fundGLAccount = contributionFields.Contains("Fund_GL_Account") ? row["Fund_GL_Account"] as string : string.Empty; string subFundGLAccount = contributionFields.Contains("Sub_Fund_GL_Account") ? row["Sub_Fund_GL_Account"] as string : string.Empty; string isFundActive = contributionFields.Contains("Fund_Is_active") ? row["Fund_Is_active"] as string : null; decimal?statedValue = row["Stated_Value"] as decimal?; decimal?amount = row["Amount"] as decimal?; if (fundName != null & amount != null) { int transactionAccountId; var parentAccount = accountList.FirstOrDefault(a => a.Name.Equals(fundName.Left(50)) && a.CampusId == null); if (parentAccount == null) { parentAccount = AddAccount(lookupContext, fundName, fundGLAccount, null, null, isFundActive.AsBooleanOrNull()); accountList.Add(parentAccount); } if (subFund != null) { int?campusFundId = null; // assign a campus if the subfund is a campus fund var campusFund = CampusList.FirstOrDefault(c => subFund.StartsWith(c.Name) || subFund.StartsWith(c.ShortCode)); if (campusFund != null) { // use full campus name as the subfund subFund = campusFund.Name; campusFundId = campusFund.Id; } // add info to easily find/assign this fund in the view subFund = string.Format("{0} {1}", subFund, fundName); var childAccount = accountList.FirstOrDefault(c => c.Name.Equals(subFund.Left(50)) && c.ParentAccountId == parentAccount.Id); if (childAccount == null) { // create a child account with a campusId if it was set childAccount = AddAccount(lookupContext, subFund, subFundGLAccount, campusFundId, parentAccount.Id, isFundActive.AsBooleanOrNull()); accountList.Add(childAccount); } transactionAccountId = childAccount.Id; } else { transactionAccountId = parentAccount.Id; } if (amount == 0 && statedValue != null && statedValue != 0) { amount = statedValue; } var transactionDetail = new FinancialTransactionDetail(); transactionDetail.Amount = (decimal)amount; transactionDetail.CreatedDateTime = receivedDate; transactionDetail.AccountId = transactionAccountId; transaction.TransactionDetails.Add(transactionDetail); if (amount < 0) { transaction.RefundDetails = new FinancialTransactionRefund(); transaction.RefundDetails.CreatedDateTime = receivedDate; transaction.RefundDetails.RefundReasonValueId = refundReasons.Where(dv => summary != null && dv.Value.Contains(summary)) .Select(dv => (int?)dv.Id).FirstOrDefault(); transaction.RefundDetails.RefundReasonSummary = summary; } } newTransactions.Add(transaction); completed++; if (completed % percentage < 1) { int percentComplete = completed / percentage; ReportProgress(percentComplete, string.Format("{0:N0} contributions imported ({1}% complete).", completed, percentComplete)); } else if (completed % ReportingNumber < 1) { SaveContributions(newTransactions); newTransactions.Clear(); ReportPartialProgress(); } } } if (newTransactions.Any()) { SaveContributions(newTransactions); } ReportProgress(100, string.Format("Finished contribution import: {0:N0} contributions imported.", completed)); }
/// <summary> /// Shows the details. /// </summary> private void ShowDetails() { RockContext rockContext = new RockContext(); pnlAddress.Visible = GetAttributeValue( "ShowAddress" ).AsBoolean(); acAddress.Required = GetAttributeValue( "AddressRequired" ).AsBoolean(); var person = CurrentPerson; if ( person != null ) { imgPhoto.BinaryFileId = person.PhotoId; imgPhoto.NoPictureUrl = Person.GetPersonPhotoUrl( person, 200, 200 ); ddlTitle.SelectedValue = person.TitleValueId.HasValue ? person.TitleValueId.Value.ToString() : string.Empty; tbFirstName.Text = person.FirstName; tbNickName.Text = person.NickName; tbLastName.Text = person.LastName; ddlSuffix.SelectedValue = person.SuffixValueId.HasValue ? person.SuffixValueId.Value.ToString() : string.Empty; bpBirthDay.SelectedDate = person.BirthDate; rblGender.SelectedValue = person.Gender.ConvertToString(); tbEmail.Text = person.Email; rblEmailPreference.SelectedValue = person.EmailPreference.ConvertToString( false ); Guid? locationTypeGuid = GetAttributeValue( "LocationType" ).AsGuidOrNull(); if ( locationTypeGuid.HasValue ) { var addressTypeDv = DefinedValueCache.Read( locationTypeGuid.Value ); // if address type is home enable the move and is mailing/physical if (addressTypeDv.Guid == Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid() ) { lbMoved.Visible = true; cbIsMailingAddress.Visible = true; cbIsPhysicalAddress.Visible = true; } else { lbMoved.Visible = false; cbIsMailingAddress.Visible = false; cbIsPhysicalAddress.Visible = false; } lAddressTitle.Text = addressTypeDv.Value + " Address"; var familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull(); if ( familyGroupTypeGuid.HasValue ) { var familyGroupType = GroupTypeCache.Read( familyGroupTypeGuid.Value ); var familyAddress = new GroupLocationService( rockContext ).Queryable() .Where( l => l.Group.GroupTypeId == familyGroupType.Id && l.GroupLocationTypeValueId == addressTypeDv.Id && l.Group.Members.Any( m => m.PersonId == person.Id)) .FirstOrDefault(); if ( familyAddress != null ) { acAddress.SetValues( familyAddress.Location ); cbIsMailingAddress.Checked = familyAddress.IsMailingLocation; cbIsPhysicalAddress.Checked = familyAddress.IsMappedLocation; } } } var mobilePhoneType = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE ) ); var phoneNumbers = new List<PhoneNumber>(); var phoneNumberTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ) ); if ( phoneNumberTypes.DefinedValues.Any() ) { foreach ( var phoneNumberType in phoneNumberTypes.DefinedValues ) { var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberType.Id ); if ( phoneNumber == null ) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Value = phoneNumberType.Value; phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id; } else { // Update number format, just in case it wasn't saved correctly phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber( phoneNumber.CountryCode, phoneNumber.Number ); } phoneNumbers.Add( phoneNumber ); } rContactInfo.DataSource = phoneNumbers; rContactInfo.DataBind(); } } }
/// <summary> /// Maps the family address. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapFamilyAddress(IQueryable <Row> tableData) { var lookupContext = new RockContext(); var locationService = new LocationService(lookupContext); List <GroupMember> familyGroupMemberList = new GroupMemberService(lookupContext).Queryable().AsNoTracking() .Where(gm => gm.Group.GroupType.Guid == new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY)).ToList(); var groupLocationDefinedType = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.GROUP_LOCATION_TYPE), lookupContext); int homeGroupLocationTypeId = groupLocationDefinedType.DefinedValues .FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME)).Id; int workGroupLocationTypeId = groupLocationDefinedType.DefinedValues .FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK)).Id; int previousGroupLocationTypeId = groupLocationDefinedType.DefinedValues .FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS)).Id; string otherGroupLocationName = "Other (Imported)"; int? otherGroupLocationTypeId = groupLocationDefinedType.DefinedValues .Where(dv => dv.TypeName == otherGroupLocationName) .Select(dv => (int?)dv.Id).FirstOrDefault(); if (otherGroupLocationTypeId == null) { var otherGroupLocationType = new DefinedValue(); otherGroupLocationType.Value = otherGroupLocationName; otherGroupLocationType.DefinedTypeId = groupLocationDefinedType.Id; otherGroupLocationType.IsSystem = false; otherGroupLocationType.Order = 0; lookupContext.DefinedValues.Add(otherGroupLocationType); lookupContext.SaveChanges(DisableAuditing); otherGroupLocationTypeId = otherGroupLocationType.Id; } var newGroupLocations = new List <GroupLocation>(); int completed = 0; int totalRows = tableData.Count(); int percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying address import ({0:N0} found).", totalRows)); foreach (var row in tableData.Where(r => r != null)) { int?individualId = row["Individual_ID"] as int?; int?householdId = row["Household_ID"] as int?; var personKeys = GetPersonKeys(individualId, householdId, includeVisitors: false); if (personKeys != null) { var familyGroup = familyGroupMemberList.Where(gm => gm.PersonId == personKeys.PersonId) .Select(gm => gm.Group).FirstOrDefault(); if (familyGroup != null) { var groupLocation = new GroupLocation(); string street1 = row["Address_1"] as string; string street2 = row["Address_2"] as string; string city = row["City"] as string; string state = row["State"] as string; string country = row["country"] as string; // NOT A TYPO: F1 has property in lower-case string zip = row["Postal_Code"] as string ?? string.Empty; // restrict zip to 5 places to prevent duplicates Location familyAddress = locationService.Get(street1, street2, city, state, zip.Left(5), country, verifyLocation: false); if (familyAddress != null) { familyAddress.CreatedByPersonAliasId = ImportPersonAliasId; familyAddress.Name = familyGroup.Name; familyAddress.IsActive = true; groupLocation.GroupId = familyGroup.Id; groupLocation.LocationId = familyAddress.Id; groupLocation.IsMailingLocation = true; groupLocation.IsMappedLocation = true; string addressType = row["Address_Type"].ToString().ToLower(); if (addressType.Equals("primary")) { groupLocation.GroupLocationTypeValueId = homeGroupLocationTypeId; } else if (addressType.Equals("business") || addressType.ToLower().Equals("org")) { groupLocation.GroupLocationTypeValueId = workGroupLocationTypeId; } else if (addressType.Equals("previous")) { groupLocation.GroupLocationTypeValueId = previousGroupLocationTypeId; } else if (!string.IsNullOrEmpty(addressType)) { // look for existing group location types, otherwise mark as imported var customTypeId = groupLocationDefinedType.DefinedValues.Where(dv => dv.Value.ToLower().Equals(addressType)) .Select(dv => (int?)dv.Id).FirstOrDefault(); groupLocation.GroupLocationTypeValueId = customTypeId ?? otherGroupLocationTypeId; } newGroupLocations.Add(groupLocation); completed++; if (completed % percentage < 1) { int percentComplete = completed / percentage; ReportProgress(percentComplete, string.Format("{0:N0} addresses imported ({1}% complete).", completed, percentComplete)); } else if (completed % ReportingNumber < 1) { SaveFamilyAddress(newGroupLocations); // Reset context newGroupLocations.Clear(); lookupContext = new RockContext(); locationService = new LocationService(lookupContext); ReportPartialProgress(); } } } } } if (newGroupLocations.Any()) { SaveFamilyAddress(newGroupLocations); } ReportProgress(100, string.Format("Finished address import: {0:N0} addresses imported.", completed)); }