protected void btnSaveStars_OnClick(object sender, EventArgs e) { // ddl var x = Convert.ToInt32(ddlStars.SelectedItem.Value); DefinedValueService definedValueService = new DefinedValueService(rockContext); var definedValue = definedValueService.Queryable().FirstOrDefault(a => a.Id == x); definedValue.LoadAttributes(); var attributeValue = definedValue.GetAttributeValue("StarValue"); var starsValue = Convert.ToDecimal(attributeValue); var pa = Person.PrimaryAliasId; //var pa = ppPerson.PersonAliasId; //var value = Decimal.Parse(tbValue.Text); StarsService starsService = new StarsService(starsProjectContext); org.newpointe.Stars.Model.Stars stars = new org.newpointe.Stars.Model.Stars(); stars.PersonAliasId = pa.GetValueOrDefault(); stars.CampusId = 1; stars.TransactionDateTime = DateTime.Now; stars.Value = starsValue; stars.Note = ddlStars.SelectedItem.Text + ". Manually added by " + CurrentPerson.FullName; starsService.Add(stars); starsProjectContext.SaveChanges(); //Refresh Page to update grids Response.Redirect(Request.RawUrl); }
/// <summary> /// Add or update a value for a Defined Type. /// </summary> /// <param name="definedTypeGuidString">A string representing the Guid identifier of the <see cref="Rock.Model.DefinedType"/> to which a new value will be added.</param> /// <param name="value">A string containing the Value of the new <see cref="Rock.Model.DefinedValue"/>.</param> /// <param name="description">A string containing the Description of the new <see cref="Rock.Model.DefinedValue"/>.</param> /// <param name="attributeValues">A dictionary of key-value pairs holding the value of the Attributes associated with the new <see cref="Rock.Model.DefinedValue"/>.</param> public void AddOrUpdateValue(string definedTypeGuidString, string value, string description, Dictionary <string, object> attributeValues) { var dataContext = ( RockContext )this.Context; // Execute this operation in a transaction to allow rollback if there are any problems updating the value attributes. dataContext.WrapTransaction(() => { // Resolve the Defined Type. var definedType = DefinedTypeCache.Get(new Guid(definedTypeGuidString)); if (definedType == null) { throw new Exception($"Defined Type is invalid. Could not map identifier \"{ definedTypeGuidString }\" to an existing Defined Type."); } // Get the existing Defined Value or create a new entry. var definedValueService = new DefinedValueService(dataContext); var definedValue = definedValueService.Queryable().FirstOrDefault(x => x.DefinedTypeId == definedType.Id && x.Value == value); if (definedValue == null) { // Create a new Defined Value. definedValue = new DefinedValue(); definedValueService.Add(definedValue); definedValue.DefinedTypeId = definedType.Id; definedValue.IsSystem = false; definedValue.IsActive = true; } definedValue.Value = value; definedValue.Description = description; dataContext.SaveChanges(); // Set the attributes of the defined value. definedValue.LoadAttributes(); foreach (var keyValuePair in attributeValues) { if (!definedValue.Attributes.ContainsKey(keyValuePair.Key)) { throw new Exception($"Defined Type Attribute is invalid. Could not map key \"{ keyValuePair.Key }\" to an existing Attribute."); } definedValue.SetAttributeValue(keyValuePair.Key, keyValuePair.Value.ToStringSafe()); } definedValue.SaveAttributeValues(dataContext); }); }
/// <summary> /// Loads the cache objects. /// </summary> private void LoadCacheObjects() { using (new Rock.Data.UnitOfWorkScope()) { // Cache all the Field Types var fieldTypeService = new Rock.Model.FieldTypeService(); foreach (var fieldType in fieldTypeService.Queryable().ToList()) { Rock.Web.Cache.FieldTypeCache.Read(fieldType); } // Cache all tha Defined Types var definedTypeService = new Rock.Model.DefinedTypeService(); foreach (var definedType in definedTypeService.Queryable().ToList()) { Rock.Web.Cache.DefinedTypeCache.Read(definedType); } // Cache all the Defined Values var definedValueService = new Rock.Model.DefinedValueService(); foreach (var definedValue in definedValueService.Queryable().ToList()) { Rock.Web.Cache.DefinedValueCache.Read(definedValue); } // Read all the qualifiers first so that EF doesn't perform a query for each attribute when it's cached var qualifiers = new Dictionary <int, Dictionary <string, string> >(); foreach (var attributeQualifier in new Rock.Model.AttributeQualifierService().Queryable()) { if (!qualifiers.ContainsKey(attributeQualifier.AttributeId)) { qualifiers.Add(attributeQualifier.AttributeId, new Dictionary <string, string>()); } qualifiers[attributeQualifier.AttributeId].Add(attributeQualifier.Key, attributeQualifier.Value); } // Cache all the attributes. foreach (var attribute in new Rock.Model.AttributeService().Queryable().ToList()) { if (qualifiers.ContainsKey(attribute.Id)) { Rock.Web.Cache.AttributeCache.Read(attribute, qualifiers[attribute.Id]); } else { Rock.Web.Cache.AttributeCache.Read(attribute, new Dictionary <string, string>()); } } } }
/// <summary> /// Loads the cache objects. /// </summary> private void LoadCacheObjects(RockContext rockContext) { // Read all the qualifiers first so that EF doesn't perform a query for each attribute when it's cached var qualifiers = new Dictionary <int, Dictionary <string, string> >(); foreach (var attributeQualifier in new Rock.Model.AttributeQualifierService(rockContext).Queryable()) { if (!qualifiers.ContainsKey(attributeQualifier.AttributeId)) { qualifiers.Add(attributeQualifier.AttributeId, new Dictionary <string, string>()); } qualifiers[attributeQualifier.AttributeId].Add(attributeQualifier.Key, attributeQualifier.Value); } // Cache all the attributes. foreach (var attribute in new Rock.Model.AttributeService(rockContext).Queryable("Categories").ToList()) { if (qualifiers.ContainsKey(attribute.Id)) { Rock.Web.Cache.AttributeCache.Read(attribute, qualifiers[attribute.Id]); } else { Rock.Web.Cache.AttributeCache.Read(attribute, new Dictionary <string, string>()); } } // Cache all the Field Types var all = Rock.Web.Cache.FieldTypeCache.All(); // DT: When running with production CCV Data, this is taking a considerable amount of time // Cache all tha Defined Types var definedTypeService = new Rock.Model.DefinedTypeService(rockContext); foreach (var definedType in definedTypeService.Queryable().ToList()) { Rock.Web.Cache.DefinedTypeCache.Read(definedType); } // Cache all the Defined Values var definedValueService = new Rock.Model.DefinedValueService(rockContext); foreach (var definedValue in definedValueService.Queryable().ToList()) { Rock.Web.Cache.DefinedValueCache.Read(definedValue); } }
/// <summary> /// Delete a set of values from a Defined Type. /// </summary> /// <param name="definedTypeGuidString">A string representing the Guid identifier of the <see cref="Rock.Model.DefinedType"/> to which a new value will be added.</param> /// <param name="values">A collection of strings containing the Values of the <see cref="Rock.Model.DefinedValue"/> entries to be deleted.</param> public void DeleteValues(string definedTypeGuidString, IEnumerable <string> values) { if (values == null) { return; } var valueList = values.ToList(); if (!valueList.Any()) { return; } var dataContext = ( RockContext )this.Context; // Resolve the Defined Type. var definedType = DefinedTypeCache.Get(new Guid(definedTypeGuidString)); if (definedType == null) { throw new Exception($"Defined Type is invalid. Could not map identifier \"{ definedTypeGuidString }\" to an existing Defined Type."); } // Delete the existing Defined Value if it exists. var definedValueService = new DefinedValueService(dataContext); var definedValues = definedValueService.Queryable().Where(x => x.DefinedTypeId == definedType.Id && valueList.Contains(x.Value)); if (definedValues.Any()) { definedValueService.DeleteRange(definedValues); dataContext.SaveChanges(); } }
/// <summary> /// Loads the cache objects. /// </summary> private void LoadCacheObjects( RockContext rockContext ) { // Read all the qualifiers first so that EF doesn't perform a query for each attribute when it's cached var qualifiers = new Dictionary<int, Dictionary<string, string>>(); foreach ( var attributeQualifier in new Rock.Model.AttributeQualifierService( rockContext ).Queryable() ) { if ( !qualifiers.ContainsKey( attributeQualifier.AttributeId ) ) qualifiers.Add( attributeQualifier.AttributeId, new Dictionary<string, string>() ); qualifiers[attributeQualifier.AttributeId].Add( attributeQualifier.Key, attributeQualifier.Value ); } // Cache all the attributes. foreach ( var attribute in new Rock.Model.AttributeService( rockContext ).Queryable( "Categories" ).ToList() ) { if ( qualifiers.ContainsKey( attribute.Id ) ) Rock.Web.Cache.AttributeCache.Read( attribute, qualifiers[attribute.Id] ); else Rock.Web.Cache.AttributeCache.Read( attribute, new Dictionary<string, string>() ); } // Cache all the Field Types var all = Rock.Web.Cache.FieldTypeCache.All(); // DT: When running with production CCV Data, this is taking a considerable amount of time // Cache all tha Defined Types var definedTypeService = new Rock.Model.DefinedTypeService( rockContext ); foreach ( var definedType in definedTypeService.Queryable().ToList() ) { Rock.Web.Cache.DefinedTypeCache.Read( definedType ); } // Cache all the Defined Values var definedValueService = new Rock.Model.DefinedValueService( rockContext ); foreach ( var definedValue in definedValueService.Queryable().ToList() ) { Rock.Web.Cache.DefinedValueCache.Read( definedValue ); } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { Guid externalApplicationGuid = Rock.SystemGuid.DefinedType.EXTERNAL_APPLICATION.AsGuid(); var definedValueService = new DefinedValueService( new RockContext() ); var queryable = definedValueService.Queryable().Where( f => f.DefinedType.Guid == externalApplicationGuid ); var sortProperty = gExternalApplication.SortProperty; List<DefinedValue> list; if ( sortProperty != null ) { list = queryable.Sort( sortProperty ).ToList(); } else { list = queryable.OrderBy( d => d.Order).ThenBy( d => d.Value ).ToList(); } foreach ( var item in list ) { item.LoadAttributes(); } gExternalApplication.DataSource = list; gExternalApplication.DataBind(); }
/// <summary> /// Handles the GridReorder event of the gDefinedValues control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param> private void gDefinedValues_GridReorder( object sender, GridReorderEventArgs e ) { int definedTypeId = hfDefinedTypeId.ValueAsInt(); DefinedTypeCache.Flush( definedTypeId ); var rockContext = new RockContext(); var definedValueService = new DefinedValueService( rockContext ); var definedValues = definedValueService.Queryable().Where( a => a.DefinedTypeId == definedTypeId ).OrderBy( a => a.Order ).ThenBy( a => a.Name); var changedIds = definedValueService.Reorder( definedValues.ToList(), e.OldIndex, e.NewIndex ); rockContext.SaveChanges(); Rock.Web.Cache.DefinedTypeCache.Flush( definedTypeId ); foreach(int id in changedIds) { Rock.Web.Cache.DefinedValueCache.Flush( id ); } BindDefinedValuesGrid(); }
//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 attendance. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> //private DateTime? StartDateTime { get; set;} private void MapAttendance( IQueryable<Row> tableData ) { var lookupContext = new RockContext(); int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Verifying Attendance import ({0:N0} found).", totalRows ) ); var attendanceList = new List<Rock.Model.Attendance>(); var groupService = new GroupService( lookupContext ); var existingGroupList = new List<Group>(); existingGroupList = groupService.Queryable().ToList(); foreach ( var row in tableData ) { DateTime? startTime = row["Start_Date_Time"] as DateTime?; if ( startTime != null && startTime != DateTime.MinValue) { DateTime startDateTime = (DateTime)startTime; if ( startDateTime.Year == 2014 && startDateTime.Month >= 1 && startDateTime.Month <= 8 ) { //startDateTime = BruteForceDateTime(startTime); var attendance = new Rock.Model.Attendance(); attendance.CreatedByPersonAliasId = ImportPersonAlias.Id; attendance.ModifiedByPersonAliasId = ImportPersonAlias.Id; attendance.CreatedDateTime = DateTime.Today; attendance.ModifiedDateTime = DateTime.Today; attendance.StartDateTime = startDateTime; //(DateTime)startTime; attendance.DidAttend = true; attendance.CampusId = 1; //Campus is needed for attendance to show in attendance analysis. //string position = row["CheckedInAs"] as string; //string jobTitle = row["Job_Title"] as string; //string machineName = row["Checkin_Machine_Name"] as string; int? rlcId = row["RLC_ID"] as int?; int? individualId = row["Individual_ID"] as int?; if ( individualId != null ) { attendance.PersonAliasId = GetPersonAliasId( individualId ); } DateTime? checkInTime = row["Check_In_Time"] as DateTime?; if ( checkInTime != null ) { // set the start time to the time they actually checked in. If null it maintains Start_Date_Time attendance.StartDateTime = (DateTime)checkInTime; //BruteForceDateTime( checkInTime ); } DateTime? checkOutTime = row["Check_Out_Time"] as DateTime?; if ( checkOutTime != null ) { attendance.EndDateTime = (DateTime)checkOutTime; //BruteForceDateTime( checkOutTime ); } //string f1AttendanceCode = row["Tag_Code"] as string; //if ( f1AttendanceCode != null ) //{ // attendance.AttendanceCode = new Rock.Model.AttendanceCode(); // attendance.AttendanceCode.Code = f1AttendanceCode; //} string f1AttendanceCheckedInAs = row["CheckedInAs"] as string; if ( f1AttendanceCheckedInAs != null ) { attendance.Note = f1AttendanceCheckedInAs; } // look up location, schedule, and device -- all of these fields can be null if need be attendance.LocationId = GetLocationId( Convert.ToInt32( rlcId ) ); //look up Group Group rlcGroup = existingGroupList.Where( g => g.ForeignId == ( rlcId.ToString() ) ).FirstOrDefault(); if ( rlcGroup != null ) { attendance.GroupId = rlcGroup.Id; } var dvService = new DefinedValueService( lookupContext ); attendance.SearchTypeValueId = dvService.Queryable().Where( dv => dv.Value == "Phone Number" ).FirstOrDefault().Id; //ReportProgress( 0, string.Format( "{0},{1},{2},{3},{4},{5},{6},{7},{8}", individualId,rlcId,rlcGroup.Name,attendance.CreatedByPersonAliasId,attendance.ModifiedByPersonAliasId,attendance.StartDateTime,attendance.DidAttend,attendance.AttendanceCode,attendance.LocationId ) ); //look into creating DeviceIds and Locations (Generic) // Other Attributes to create: // Tag_Comment // BreakoutGroup_Name // Pager_Code //attendanceList.Add( attendance ); completed++; if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "Completed: {0:N0} Percent Completed: {0:N0} ", completed, percentComplete ) ); } // else if ( completed % ReportingNumber < 1 ) // { // var rockContext = new RockContext(); // rockContext.WrapTransaction( () => //{ // rockContext.Configuration.AutoDetectChangesEnabled = false; // rockContext.Attendances.AddRange( attendanceList ); // rockContext.SaveChanges( DisableAudit ); //} ); // ReportPartialProgress(); // } var rockContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Attendances.Add( attendance ); rockContext.SaveChanges( DisableAudit ); } ); ReportPartialProgress(); } } } }
/// <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> /// Handles the GridReorder event of the gDefinedValues control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param> protected void gDefinedValues_GridReorder( object sender, GridReorderEventArgs e ) { var definedType = DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.PROTECT_MY_MINISTRY_PACKAGES.AsGuid() ); if ( definedType != null ) { var changedIds = new List<int>(); using ( var rockContext = new RockContext() ) { var definedValueService = new DefinedValueService( rockContext ); var definedValues = definedValueService.Queryable().Where( a => a.DefinedTypeId == definedType.Id ).OrderBy( a => a.Order ).ThenBy( a => a.Value ); changedIds = definedValueService.Reorder( definedValues.ToList(), e.OldIndex, e.NewIndex ); rockContext.SaveChanges(); } DefinedTypeCache.Flush( definedType.Id ); foreach ( int id in changedIds ) { Rock.Web.Cache.DefinedValueCache.Flush( id ); } } BindPackageGrid(); }
/// <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> /// 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(); }
/// <summary> /// Maps the Individual Giftedness. /// </summary> /// <param name="tableData">The table data.</param> private void MapIndividualGiftedness( IQueryable<Row> tableData ) { var lookupContext = new RockContext(); var attributeService = new AttributeService( lookupContext ); int rank1Id = attributeService.Queryable().Where( a => a.Key == "Rank1" ).FirstOrDefault().Id; int rank2Id = attributeService.Queryable().Where( a => a.Key == "Rank2" ).FirstOrDefault().Id; int rank3Id = attributeService.Queryable().Where( a => a.Key == "Rank3" ).FirstOrDefault().Id; int rank4Id = attributeService.Queryable().Where( a => a.Key == "Rank4" ).FirstOrDefault().Id; 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 ) ); var newAttributeValueList = new List<AttributeValue>(); foreach ( var row in tableData ) { int? individualId = row["Individual_ID"] as int?; int personId = (int)GetPersonAliasId( individualId ); var newAttributeValue = new AttributeValue(); int? rank = row["Rank"] as int?; int rankId = 0; //not everyone has all 4 ranks, some are missing the fourth and that was causing it to run in the below if condition and try to create a duplicate record. if ( rank == 1 ) { rankId = rank1Id; } if ( rank == 2 ) { rankId = rank2Id; } if ( rank == 3 ) { rankId = rank3Id; } if ( rank == 4 ) { rankId = rank4Id; } if ( personId != 0 && rankId != 0 ) { var attributeValueService = new AttributeValueService( lookupContext ); //checks if they are in the database already or if there is a record currently in the newAttributeValueList if ( attributeValueService.Queryable().Where( a => a.AttributeId == rankId && a.EntityId == personId ).FirstOrDefault() == null && newAttributeValueList.Find(a => a.AttributeId == rankId && a.EntityId == personId) == null ) { DateTime? assessmentDate = row["AssessmentDate"] as DateTime?; int? giftAttributeId = row["GiftAttributeID"] as int?; string giftAttributeIdString = Convert.ToString( giftAttributeId ); var definedValueService = new DefinedValueService( lookupContext ); newAttributeValue.IsSystem = false; newAttributeValue.EntityId = personId; if ( rank == 1 ) { newAttributeValue.AttributeId = rank1Id; } if ( rank == 2 ) { newAttributeValue.AttributeId = rank2Id; } if ( rank == 3 ) { newAttributeValue.AttributeId = rank3Id; } if ( rank == 4 ) { newAttributeValue.AttributeId = rank4Id; } newAttributeValue.Value = Convert.ToString( definedValueService.Queryable().Where( a => a.ForeignId == giftAttributeIdString ).FirstOrDefault().Guid ); newAttributeValue.CreatedDateTime = assessmentDate; newAttributeValueList.Add( newAttributeValue ); completed++; } } if ( newAttributeValueList.Any() ) { if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} spiritual gifts imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { var rockContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.AttributeValues.AddRange( newAttributeValueList ); rockContext.SaveChanges( DisableAudit ); newAttributeValueList.Clear(); } ); ReportPartialProgress(); } } } if ( newAttributeValueList.Any() ) { var rockContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.AttributeValues.AddRange( newAttributeValueList ); rockContext.SaveChanges( DisableAudit ); } ); } ReportProgress( 100, string.Format( "Finished individual gifts import: {0:N0} spiritual gifts imported.", completed ) ); }
/// <summary> /// Handles the GridReorder event of the gLinks control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param> void gLinks_GridReorder( object sender, GridReorderEventArgs e ) { using ( var rockContext = new RockContext() ) { var service = new DefinedValueService( rockContext ); var definedValues = service.Queryable().Where( a => a.DefinedTypeId == _definedType.Id ).OrderBy( a => a.Order ).ThenBy( a => a.Value ); var changedIds = service.Reorder( definedValues.ToList(), e.OldIndex, e.NewIndex ); rockContext.SaveChanges(); foreach ( int id in changedIds ) { Rock.Web.Cache.DefinedValueCache.Flush( id ); } } DefinedTypeCache.Flush( _definedType.Id ); BindGrid(); }
/// <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(); }
/// <summary> /// Loads the cache objects. /// </summary> private void LoadCacheObjects() { using ( new Rock.Data.UnitOfWorkScope() ) { // Cache all the Field Types var fieldTypeService = new Rock.Model.FieldTypeService(); foreach ( var fieldType in fieldTypeService.Queryable().ToList() ) Rock.Web.Cache.FieldTypeCache.Read( fieldType ); // Cache all tha Defined Types var definedTypeService = new Rock.Model.DefinedTypeService(); foreach ( var definedType in definedTypeService.Queryable().ToList() ) Rock.Web.Cache.DefinedTypeCache.Read( definedType ); // Cache all the Defined Values var definedValueService = new Rock.Model.DefinedValueService(); foreach ( var definedValue in definedValueService.Queryable().ToList() ) Rock.Web.Cache.DefinedValueCache.Read( definedValue ); // Read all the qualifiers first so that EF doesn't perform a query for each attribute when it's cached var qualifiers = new Dictionary<int, Dictionary<string, string>>(); foreach ( var attributeQualifier in new Rock.Model.AttributeQualifierService().Queryable() ) { if ( !qualifiers.ContainsKey( attributeQualifier.AttributeId ) ) qualifiers.Add( attributeQualifier.AttributeId, new Dictionary<string, string>() ); qualifiers[attributeQualifier.AttributeId].Add( attributeQualifier.Key, attributeQualifier.Value ); } // Cache all the attributes. foreach ( var attribute in new Rock.Model.AttributeService().Queryable().ToList() ) { if ( qualifiers.ContainsKey( attribute.Id ) ) Rock.Web.Cache.AttributeCache.Read( attribute, qualifiers[attribute.Id] ); else Rock.Web.Cache.AttributeCache.Read( attribute, new Dictionary<string, string>() ); } } }
/// <summary> /// Maps the group attendance. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> //private DateTime? StartDateTime { get; set;} private void MapGroupsAttendance( IQueryable<Row> tableData ) { var lookupContext = new RockContext(); int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Verifying Attendance import ({0:N0} found).", totalRows ) ); var attendanceList = new List<Rock.Model.Attendance>(); var groupService = new GroupService( lookupContext ); var existingGroupList = new List<Group>(); existingGroupList = groupService.Queryable().Where(g => g.ForeignId != null).ToList(); foreach ( var row in tableData ) { DateTime? startTime = row["StartDateTime"] as DateTime?; if ( startTime != null && startTime != DateTime.MinValue ) { int? groupId = row["GroupID"] as int?; if ( existingGroupList.Find(g => g.ForeignId == groupId.ToString()) != null ) //making sure the group has been created. { DateTime startDateTime = (DateTime)startTime; DateTime? endTime = row["EndDateTime"] as DateTime?; int? met = row["Met"] as int?; bool didAttend = true; if ( met == 0 ) { didAttend = false; } string comments = row["Comments"] as string; var attendance = new Rock.Model.Attendance(); attendance.CreatedByPersonAliasId = ImportPersonAlias.Id; attendance.ModifiedByPersonAliasId = ImportPersonAlias.Id; attendance.CreatedDateTime = DateTime.Today; attendance.ModifiedDateTime = DateTime.Today; attendance.StartDateTime = startDateTime; attendance.EndDateTime = endTime; attendance.DidAttend = didAttend; attendance.Note = comments; attendance.CampusId = 1; //Campus is needed for attendance to show in attendance analysis. attendance.GroupId = existingGroupList.Find( g => g.ForeignId == groupId.ToString() ).Id; int? individualId = row["IndividualID"] as int?; if ( individualId != null ) { attendance.PersonAliasId = GetPersonAliasId( individualId ); } ////look up Group //int? groupId = row["GroupID"] as int?; //Group group = existingGroupList.Where( g => g.ForeignId == ( groupId.ToString() ) ).FirstOrDefault(); //if ( group != null ) //{ // attendance.GroupId = group.Id; //} //no other search type right now; small group attendance not currently set up in Rock. var dvService = new DefinedValueService( lookupContext ); attendance.SearchTypeValueId = dvService.Queryable().Where( dv => dv.Value == "Phone Number" ).FirstOrDefault().Id; completed++; if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "Completed: {0:N0} Percent Completed: {0:N0} ", completed, percentComplete ) ); } var rockContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Attendances.Add( attendance ); rockContext.SaveChanges( DisableAudit ); } ); ReportPartialProgress(); } } } }
/// <summary> /// Handles the GridReorder event of the gDefinedValues control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param> private void gDefinedValues_GridReorder( object sender, GridReorderEventArgs e ) { int definedTypeId = hfDefinedTypeId.ValueAsInt(); DefinedTypeCache.Flush( definedTypeId ); using ( new UnitOfWorkScope() ) { var definedValueService = new DefinedValueService(); var definedValues = definedValueService.Queryable().Where( a => a.DefinedTypeId == definedTypeId ).OrderBy( a => a.Order ); definedValueService.Reorder( definedValues.ToList(), e.OldIndex, e.NewIndex, CurrentPersonId ); BindDefinedValuesGrid(); } }
/// <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 groupTypeRoleService = new GroupTypeRoleService(); var attributeService = new AttributeService(); var dvService = new DefinedValueService(); var familyList = new List<Group>(); // Marital statuses: Married, Single, Separated, etc List<DefinedValue> maritalStatusTypes = dvService.Queryable() .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS ) ).ToList(); // Connection statuses: Member, Visitor, Attendee, etc List<DefinedValue> connectionStatusTypes = dvService.Queryable() .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS ) ).ToList(); // Record status reasons: No Activity, Moved, Deceased, etc List<DefinedValue> recordStatusReasons = dvService.Queryable() .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_RECORD_STATUS_REASON ) ).ToList(); // Record statuses: Active, Inactive, Pending int? statusActiveId = dvService.Get( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE ) ).Id; int? statusInactiveId = dvService.Get( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id; int? statusPendingId = dvService.Get( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING ) ).Id; // Record type: Person int? personRecordTypeId = dvService.Get( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON ) ).Id; // Suffix type: Dr., Jr., II, etc List<DefinedValue> suffixTypes = dvService.Queryable() .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_SUFFIX ) ).ToList(); // Title type: Mr., Mrs. Dr., etc List<DefinedValue> titleTypes = dvService.Queryable() .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_TITLE ) ).ToList(); // Note type: Comment int noteCommentTypeId = new NoteTypeService().Get( new Guid( "7E53487C-D650-4D85-97E2-350EB8332763" ) ).Id; // Group roles: Adult, Child, others 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; // Group type: Family int familyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id; // Look up additional Person attributes (existing) var personAttributes = attributeService.GetByEntityTypeId( PersonEntityTypeId ).ToList(); // Cached F1 attributes: IndividualId, HouseholdId, 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" ) ); int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Checking 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 ) { int? individualId = row["Individual_ID"] as int?; int? householdId = row["Household_ID"] as int?; if ( GetPersonId( 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; 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.Name.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.Name.RemoveSpecialCharacters() ) .Select( s => (int?)s.Id ).FirstOrDefault(); } string maritalStatus = row["Marital_Status"] as string; if ( maritalStatus != null ) { person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Name == maritalStatus ) .Select( dv => (int?)dv.Id ).FirstOrDefault(); } else { person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Name == "Unknown" ) .Select( dv => (int?)dv.Id ).FirstOrDefault(); } string familyRole = row["Household_Position"] as string; if ( familyRole != null ) { if ( familyRole == "Child" || person.Age < 18 ) { groupRoleId = childRoleId; } else if ( familyRole == "Visitor" ) { // assign person as a known relationship of this family/group } } string memberStatus = row["Status_Name"] as string; if ( memberStatus == "Member" ) { person.ConnectionStatusValueId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER ) ).Id; person.RecordStatusValueId = statusActiveId; } else if ( memberStatus == "Visitor" ) { person.ConnectionStatusValueId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR ) ).Id; person.RecordStatusValueId = statusActiveId; } else if ( memberStatus == "Deceased" ) { person.IsDeceased = true; person.RecordStatusValueId = statusInactiveId; person.RecordStatusReasonValueId = recordStatusReasons.Where( dv => dv.Name == "Deceased" ) .Select( dv => dv.Id ).FirstOrDefault(); } else { // F1 defaults are Member & Visitor; all others are user-defined var customConnectionType = connectionStatusTypes.Where( dv => dv.Name == memberStatus ) .Select( dv => (int?)dv.Id ).FirstOrDefault(); int attendeeId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( "39F491C5-D6AC-4A9B-8AC0-C431CB17D588" ) ).Id; person.ConnectionStatusValueId = customConnectionType ?? attendeeId; person.RecordStatusValueId = statusActiveId; } string campus = row["SubStatus_Name"] as string; if ( campus != null ) { householdCampusList.Add( campus ); } string status_comment = row["Status_Comment"] as string; if ( status_comment != null ) { var comment = new Note(); comment.Text = status_comment; comment.NoteTypeId = noteCommentTypeId; RockTransactionScope.WrapTransaction( () => { var noteService = new NoteService(); noteService.Save( comment ); } ); } // Map F1 attributes person.Attributes = new Dictionary<string, AttributeCache>(); person.AttributeValues = new Dictionary<string, List<AttributeValue>>(); // individual_id already defined in scope if ( individualId != null ) { person.Attributes.Add( "F1IndividualId", individualIdAttribute ); person.AttributeValues.Add( "F1IndividualId", new List<AttributeValue>() ); person.AttributeValues["F1IndividualId"].Add( new AttributeValue() { AttributeId = individualIdAttribute.Id, Value = individualId.ToString(), Order = 0 } ); } // household_id already defined in scope if ( householdId != null ) { person.Attributes.Add( "F1HouseholdId", householdIdAttribute ); person.AttributeValues.Add( "F1HouseholdId", new List<AttributeValue>() ); person.AttributeValues["F1HouseholdId"].Add( new AttributeValue() { AttributeId = householdIdAttribute.Id, Value = householdId.ToString(), Order = 0 } ); } string previousChurch = row["Former_Church"] as string; if ( previousChurch != null ) { person.Attributes.Add( "PreviousChurch", previousChurchAttribute ); person.AttributeValues.Add( "PreviousChurch", new List<AttributeValue>() ); person.AttributeValues["PreviousChurch"].Add( new AttributeValue() { AttributeId = previousChurchAttribute.Id, Value = previousChurch, Order = 0 } ); } string employer = row["Employer"] as string; if ( employer != null ) { person.Attributes.Add( "Employer", employerAttribute ); person.AttributeValues.Add( "Employer", new List<AttributeValue>() ); person.AttributeValues["Employer"].Add( new AttributeValue() { AttributeId = employerAttribute.Id, Value = employer, Order = 0 } ); } string position = row["Occupation_Name"] as string ?? row["Occupation_Description"] as string; if ( position != null ) { person.Attributes.Add( "Position", positionAttribute ); person.AttributeValues.Add( "Position", new List<AttributeValue>() ); person.AttributeValues["Position"].Add( new AttributeValue() { AttributeId = positionAttribute.Id, Value = position, Order = 0 } ); } string school = row["School_Name"] as string; if ( school != null ) { person.Attributes.Add( "School", schoolAttribute ); person.AttributeValues.Add( "School", new List<AttributeValue>() ); person.AttributeValues["School"].Add( new AttributeValue() { AttributeId = schoolAttribute.Id, Value = school, Order = 0 } ); } DateTime? membershipDate = row["Status_Date"] as DateTime?; if ( membershipDate != null ) { person.CreatedDateTime = membershipDate; person.Attributes.Add( "MembershipDate", membershipDateAttribute ); person.AttributeValues.Add( "MembershipDate", new List<AttributeValue>() ); person.AttributeValues["MembershipDate"].Add( new AttributeValue() { AttributeId = membershipDateAttribute.Id, Value = membershipDate.Value.ToString( "MM/dd/yyyy" ), Order = 0 } ); } DateTime? firstVisit = row["First_Record"] as DateTime?; if ( firstVisit != null ) { person.CreatedDateTime = firstVisit; // will always pick firstVisit if membershipDate is null firstVisit = firstVisit > membershipDate ? membershipDate : firstVisit; person.Attributes.Add( "FirstVisit", firstVisitAttribute ); person.AttributeValues.Add( "FirstVisit", new List<AttributeValue>() ); person.AttributeValues["FirstVisit"].Add( new AttributeValue() { AttributeId = firstVisitAttribute.Id, Value = firstVisit.Value.ToString( "MM/dd/yyyy" ), Order = 0 } ); } // 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; familyGroup.Members.Add( groupMember ); } } if ( familyGroup.Members.Any() ) { familyGroup.Name = familyGroup.Members.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++; 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 ) { RockTransactionScope.WrapTransaction( () => { var groupService = new GroupService(); var personService = new PersonService(); var attributeValueService = new AttributeValueService(); groupService.RockContext.Groups.AddRange( familyList ); groupService.RockContext.SaveChanges(); foreach ( var newFamilyGroup in familyList ) { foreach ( var groupMember in newFamilyGroup.Members ) { var person = groupMember.Person; foreach ( var attributeCache in person.Attributes.Select( a => a.Value ) ) { var newValue = person.AttributeValues[attributeCache.Key].FirstOrDefault(); if ( newValue != null ) { newValue.EntityId = person.Id; attributeValueService.RockContext.AttributeValues.Add( newValue ); } } if ( !person.Aliases.Any( a => a.AliasPersonId == person.Id ) ) { person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } ); } if ( groupMember.GroupRoleId != childRoleId ) { person.GivingGroupId = newFamilyGroup.Id; } } } attributeValueService.RockContext.SaveChanges(); personService.RockContext.SaveChanges(); } ); familyList.Clear(); ReportPartialProgress(); } } } // Save any remaining families in the batch if ( familyList.Any() ) { RockTransactionScope.WrapTransaction( () => { var groupService = new GroupService(); var personService = new PersonService(); var attributeValueService = new AttributeValueService(); groupService.RockContext.Groups.AddRange( familyList ); groupService.RockContext.SaveChanges(); foreach ( var newFamilyGroup in familyList ) { foreach ( var groupMember in newFamilyGroup.Members ) { var person = groupMember.Person; foreach ( var attributeCache in person.Attributes.Select( a => a.Value ) ) { var newValue = person.AttributeValues[attributeCache.Key].FirstOrDefault(); if ( newValue != null ) { newValue.EntityId = person.Id; attributeValueService.RockContext.AttributeValues.Add( newValue ); } } if ( !person.Aliases.Any( a => a.AliasPersonId == person.Id ) ) { person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } ); } if ( groupMember.GroupRoleId != childRoleId ) { person.GivingGroupId = newFamilyGroup.Id; } } } attributeValueService.RockContext.SaveChanges(); personService.RockContext.SaveChanges(); } ); } ReportProgress( 100, string.Format( "Finished person import: {0:N0} people imported.", completed ) ); }
protected void Page_Load(object sender, EventArgs e) { var shapePageReference = new Rock.Web.PageReference(GetAttributeValue("SHAPEAssessmentPage")); var discPageReference = new Rock.Web.PageReference(GetAttributeValue("DISCAssessmentPage")); if (!string.IsNullOrWhiteSpace(PageParameter("FormId"))) { //Load the person based on the FormId var personInUrl = PageParameter("FormId"); SelectedPerson = GetPersonFromForm(personInUrl); PersonEncodedKey = SelectedPerson.UrlEncodedKey; } else if (!string.IsNullOrWhiteSpace(PageParameter("PersonId"))) { //Load the person based on the PersonId SelectedPerson = GetPersonFromId(PageParameter("PersonId")); PersonEncodedKey = SelectedPerson.UrlEncodedKey; } else if (CurrentPerson != null) { //Load the person based on the currently logged in person SelectedPerson = CurrentPerson; PersonEncodedKey = SelectedPerson.UrlEncodedKey; } else { //Show Error Message nbNoPerson.Visible = true; Response.Redirect(shapePageReference.BuildUrl(), true); return; } // Load the attributes AttributeValueService attributeValueService = new AttributeValueService(rockContext); DefinedValueService definedValueService = new DefinedValueService(rockContext); string spiritualGift1 = ""; string spiritualGift2 = ""; string spiritualGift3 = ""; string spiritualGift4 = ""; string heartCategories = ""; string heartCauses = ""; string heartPassion = ""; string ability1 = ""; string ability2 = ""; string people = ""; string places = ""; string events = ""; var spiritualGift1AttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift1" && a.EntityId == SelectedPerson.Id); // Redirect if they haven't taken the Assessment if (spiritualGift1AttributeValue == null) { Response.Redirect(shapePageReference.BuildUrl(), true); } else { var spiritualGift2AttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift2" && a.EntityId == SelectedPerson.Id); var spiritualGift3AttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift3" && a.EntityId == SelectedPerson.Id); var spiritualGift4AttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift4" && a.EntityId == SelectedPerson.Id); var ability1AttributeValue = attributeValueService .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability1" && a.EntityId == SelectedPerson.Id); var ability2AttributeValue = attributeValueService .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability2" && a.EntityId == SelectedPerson.Id); var peopleAttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SHAPEPeople" && a.EntityId == SelectedPerson.Id); var placesAttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SHAPEPlaces" && a.EntityId == SelectedPerson.Id); var eventsAttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SHAPEEvents" && a.EntityId == SelectedPerson.Id); var heartCategoriesAttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "HeartCategories" && a.EntityId == SelectedPerson.Id); var heartCausesAttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "HeartCauses" && a.EntityId == SelectedPerson.Id); var heartPassionAttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "HeartPassion" && a.EntityId == SelectedPerson.Id); if (spiritualGift1AttributeValue.Value != null) spiritualGift1 = spiritualGift1AttributeValue.Value; if (spiritualGift2AttributeValue.Value != null) spiritualGift2 = spiritualGift2AttributeValue.Value; if (spiritualGift3AttributeValue.Value != null) spiritualGift3 = spiritualGift3AttributeValue.Value; if (spiritualGift4AttributeValue.Value != null) spiritualGift4 = spiritualGift4AttributeValue.Value; if (heartCategoriesAttributeValue.Value != null) heartCategories = heartCategoriesAttributeValue.Value; if (heartCausesAttributeValue.Value != null) heartCauses = heartCausesAttributeValue.Value; if (heartPassionAttributeValue.Value != null) heartPassion = heartPassionAttributeValue.Value; if (ability1AttributeValue.Value != null) ability1 = ability1AttributeValue.Value; if (ability2AttributeValue.Value != null) ability2 = ability2AttributeValue.Value; if (peopleAttributeValue.Value != null) people = peopleAttributeValue.Value; if (placesAttributeValue.Value != null) places = placesAttributeValue.Value; if (eventsAttributeValue.Value != null) events = eventsAttributeValue.Value; string spiritualGift1Guid; string spiritualGift2Guid; string spiritualGift3Guid; string spiritualGift4Guid; string ability1Guid; string ability2Guid; // Check to see if there are already values saved as an ID. If so, convert them to GUID if (spiritualGift1.ToString().Length < 5) { if (spiritualGift1 != null) SpiritualGift1 = Int32.Parse(spiritualGift1); if (spiritualGift2 != null) SpiritualGift2 = Int32.Parse(spiritualGift2); if (spiritualGift3 != null) SpiritualGift3 = Int32.Parse(spiritualGift3); if (spiritualGift4 != null) SpiritualGift4 = Int32.Parse(spiritualGift4); if (ability1 != null) Ability1 = Int32.Parse(ability1); if (ability2 != null) Ability2 = Int32.Parse(ability2); var intsOfGifts = definedValueService.GetByIds(new List<int> { SpiritualGift1, SpiritualGift2, SpiritualGift3, SpiritualGift4, Ability1, Ability2 }); spiritualGift1Guid = intsOfGifts.ToList()[SpiritualGift1].Guid.ToString(); spiritualGift2Guid = intsOfGifts.ToList()[SpiritualGift2].Guid.ToString(); spiritualGift3Guid = intsOfGifts.ToList()[SpiritualGift3].Guid.ToString(); spiritualGift4Guid = intsOfGifts.ToList()[SpiritualGift4].Guid.ToString(); ability1Guid = intsOfGifts.ToList()[Ability1].Guid.ToString(); ability2Guid = intsOfGifts.ToList()[Ability2].Guid.ToString(); } else { spiritualGift1Guid = spiritualGift1; spiritualGift2Guid = spiritualGift2; spiritualGift3Guid = spiritualGift3; spiritualGift4Guid = spiritualGift4; ability1Guid = ability1; ability2Guid = ability2; } // Get all of the data about the assiciated gifts and ability categories var shapeGift1Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift1Guid) }).FirstOrDefault(); var shapeGift2Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift2Guid) }).FirstOrDefault(); var shapeGift3Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift3Guid) }).FirstOrDefault(); var shapeGift4Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift4Guid) }).FirstOrDefault(); var ability1Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(ability1Guid) }).FirstOrDefault(); var ability2Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(ability2Guid) }).FirstOrDefault(); shapeGift1Object.LoadAttributes(); shapeGift2Object.LoadAttributes(); shapeGift3Object.LoadAttributes(); shapeGift4Object.LoadAttributes(); ability1Object.LoadAttributes(); ability2Object.LoadAttributes(); // Get heart choices Values from Guids string heartCategoriesString = ""; if (!heartCategories.IsNullOrWhiteSpace()) { string[] heartCategoryArray = heartCategories.Split(','); foreach (string category in heartCategoryArray) { var definedValueObject = definedValueService.Queryable().FirstOrDefault(a => a.Guid == new Guid(category)); if (category.Equals(heartCategoryArray.Last())) { heartCategoriesString += definedValueObject.Value; } else { heartCategoriesString += definedValueObject.Value + ", "; } } } // Get Volunteer Opportunities string gift1AssociatedVolunteerOpportunities = shapeGift1Object.GetAttributeValue("AssociatedVolunteerOpportunities"); string gift2AssociatedVolunteerOpportunities = shapeGift2Object.GetAttributeValue("AssociatedVolunteerOpportunities"); string gift3AssociatedVolunteerOpportunities = shapeGift3Object.GetAttributeValue("AssociatedVolunteerOpportunities"); string gift4AssociatedVolunteerOpportunities = shapeGift4Object.GetAttributeValue("AssociatedVolunteerOpportunities"); string allAssociatedVolunteerOpportunities = gift1AssociatedVolunteerOpportunities + "," + gift2AssociatedVolunteerOpportunities + "," + gift3AssociatedVolunteerOpportunities + "," + gift4AssociatedVolunteerOpportunities; if (allAssociatedVolunteerOpportunities != ",,,") { List<int> associatedVolunteerOpportunitiesList = allAssociatedVolunteerOpportunities.Split(',').Select(t => int.Parse(t)).ToList(); Dictionary<int, int> VolunteerOpportunities = new Dictionary<int, int>(); var i = 0; var q = from x in associatedVolunteerOpportunitiesList group x by x into g let count = g.Count() orderby count descending select new { Value = g.Key, Count = count }; foreach (var x in q) { VolunteerOpportunities.Add(i, x.Value); i++; } ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext); List<ConnectionOpportunity> connectionOpportunityList = new List<ConnectionOpportunity>(); foreach (KeyValuePair<int, int> entry in VolunteerOpportunities.Take(4)) { var connection = connectionOpportunityService.GetByIds(new List<int> { entry.Value }).FirstOrDefault(); // Only display connection if it is marked Active if (connection.IsActive == true) { connectionOpportunityList.Add(connection); } } rpVolunteerOpportunities.DataSource = connectionOpportunityList; rpVolunteerOpportunities.DataBind(); } //Get DISC Info DiscService.AssessmentResults savedScores = DiscService.LoadSavedAssessmentResults(SelectedPerson); if (!string.IsNullOrWhiteSpace(savedScores.PersonalityType)) { ShowResults(savedScores); DISCResults.Visible = true; NoDISCResults.Visible = false; } else { discPageReference.Parameters = new System.Collections.Generic.Dictionary<string, string>(); discPageReference.Parameters.Add("rckipid", SelectedPerson.UrlEncodedKey); Response.Redirect(discPageReference.BuildUrl(), true); } // Build the UI lbPersonName.Text = SelectedPerson.FullName; lbGift1Title.Text = shapeGift1Object.Value; lbGift1BodyHTML.Text = shapeGift1Object.GetAttributeValue("HTMLDescription"); lbGift2Title.Text = shapeGift2Object.Value; lbGift2BodyHTML.Text = shapeGift2Object.GetAttributeValue("HTMLDescription"); lbGift3Title.Text = shapeGift3Object.Value; lbGift3BodyHTML.Text = shapeGift3Object.GetAttributeValue("HTMLDescription"); lbGift4Title.Text = shapeGift4Object.Value; lbGift4BodyHTML.Text = shapeGift4Object.GetAttributeValue("HTMLDescription"); lbAbility1Title.Text = ability1Object.Value; lbAbility1BodyHTML.Text = ability1Object.GetAttributeValue("HTMLDescription"); lbAbility2Title.Text = ability2Object.Value; lbAbility2BodyHTML.Text = ability2Object.GetAttributeValue("HTMLDescription"); lbPeople.Text = people; lbPlaces.Text = places; lbEvents.Text = events; lbHeartCategories.Text = heartCategoriesString; lbHeartCauses.Text = heartCauses; lbHeartPassion.Text = heartPassion; if (spiritualGift1AttributeValue.ModifiedDateTime != null) { lbAssessmentDate.Text = spiritualGift1AttributeValue.ModifiedDateTime.Value.ToShortDateString(); } else { lbAssessmentDate.Text = spiritualGift1AttributeValue.CreatedDateTime.Value.ToShortDateString(); } // Show create account panel if this person doesn't have an account if (SelectedPerson.Users.Count == 0) { pnlAccount.Visible = true; } } }
//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"; //} }