/// <summary> /// Executes the specified workflow action. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); Guid? personAliasGuid = GetAttributeValue( action, "Person" ).AsGuidOrNull(); if ( personAliasGuid.HasValue ) { var personAlias = new PersonAliasService( rockContext ).Queryable( "Person" ) .Where( a => a.Guid.Equals( personAliasGuid.Value ) ) .FirstOrDefault(); if (personAlias != null) { action.Activity.AssignedPersonAlias = personAlias; action.Activity.AssignedPersonAliasId = personAlias.Id; action.Activity.AssignedGroup = null; action.Activity.AssignedGroupId = null; action.AddLogEntry( string.Format( "Assigned activity to '{0}' ({1})", personAlias.Person.FullName, personAlias.Person.Id ) ); return true; } } return false; }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); if ( action.Activity.Workflow.InitiatorPersonAliasId.HasValue ) { var personAlias = new PersonAliasService( rockContext ).Get( action.Activity.Workflow.InitiatorPersonAliasId.Value ); if ( personAlias != null ) { // Get the attribute to set Guid guid = GetAttributeValue( action, "PersonAttribute" ).AsGuid(); if ( !guid.IsEmpty() ) { var personAttribute = AttributeCache.Read( guid, rockContext ); if ( personAttribute != null ) { // If this is a person type attribute if ( personAttribute.FieldTypeId == FieldTypeCache.Read( SystemGuid.FieldType.PERSON.AsGuid(), rockContext ).Id ) { SetWorkflowAttributeValue( action, guid, personAlias.Guid.ToString() ); } else if ( personAttribute.FieldTypeId == FieldTypeCache.Read( SystemGuid.FieldType.TEXT.AsGuid(), rockContext ).Id ) { SetWorkflowAttributeValue( action, guid, personAlias.Person.FullName ); } } } } } return true; }
/// <summary> /// Executes the specified workflow action. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); // Get the attribute's guid Guid guid = GetAttributeValue( action, "PersonAttribute" ).AsGuid(); if ( !guid.IsEmpty() ) { // Get the attribute var attribute = AttributeCache.Read( guid, rockContext ); if ( attribute != null ) { if ( attribute.FieldTypeId == FieldTypeCache.Read( SystemGuid.FieldType.PERSON.AsGuid(), rockContext ).Id ) { // If attribute type is a person, value should be person alias id Guid? personAliasGuid = action.GetWorklowAttributeValue( guid ).AsGuidOrNull(); if ( personAliasGuid.HasValue ) { var personAlias = new PersonAliasService( rockContext ).Queryable( "Person" ) .Where( a => a.Guid.Equals( personAliasGuid.Value ) ) .FirstOrDefault(); if ( personAlias != null ) { action.Activity.Workflow.InitiatorPersonAlias = personAlias; action.Activity.Workflow.InitiatorPersonAliasId = personAlias.Id; action.AddLogEntry( string.Format( "Assigned initiator to '{0}' ({1})", personAlias.Person.FullName, personAlias.Person.Id ) ); return true; } } } } } return false; }
/// <summary> /// Gets a filter expression for an attribute value. /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="filterValues">The filter values.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <returns></returns> public override System.Linq.Expressions.Expression AttributeFilterExpression( Dictionary<string, ConfigurationValue> configurationValues, List<string> filterValues, System.Linq.Expressions.ParameterExpression parameterExpression ) { if ( filterValues.Count >= 2 ) { string comparisonValue = filterValues[0]; if ( comparisonValue != "0" ) { Guid guid = filterValues[1].AsGuid(); int personId = new PersonAliasService( new RockContext() ).Queryable() .Where( a => a.Guid.Equals( guid ) ) .Select( a => a.PersonId ) .FirstOrDefault(); if ( personId > 0 ) { ComparisonType comparisonType = comparisonValue.ConvertToEnum<ComparisonType>( ComparisonType.EqualTo ); MemberExpression propertyExpression = Expression.Property( parameterExpression, "ValueAsPersonId" ); ConstantExpression constantExpression = Expression.Constant( personId, typeof( int ) ); return ComparisonHelper.ComparisonExpression( comparisonType, propertyExpression, constantExpression ); } } } return null; }
protected Person GetPersonFromForm(string formId) { AttributeValueService attributeValueService = new AttributeValueService(rockContext); PersonService personService = new PersonService(rockContext); PersonAliasService personAliasService = new PersonAliasService(rockContext); var formAttribute = attributeValueService.Queryable().FirstOrDefault(a => a.Value == formId); var person = personService.Queryable().FirstOrDefault(p => p.Id == formAttribute.EntityId); return person; }
protected void Page_Load(object sender, EventArgs e) { PersonAliasService personAliasService = new PersonAliasService(rockContext); StarsService starsService = new StarsService(starsProjectContext); var starsList = starsService.Queryable().GroupBy(a => a.PersonAlias.Person).Select(g => new { Person = g.Key, Sum = g.Sum(a => a.Value)}).ToList(); gStars.DataSource = starsList; gStars.DataBind(); }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); Guid guid = GetAttributeValue( action, "Attribute" ).AsGuid(); if ( !guid.IsEmpty() ) { var attribute = AttributeCache.Read( guid, rockContext ); if ( attribute != null ) { if ( entity != null ) { if ( entity is Person && attribute.FieldTypeId == FieldTypeCache.Read( SystemGuid.FieldType.PERSON.AsGuid(), rockContext ).Id ) { var person = entity as Person; var primaryAlias = new PersonAliasService(rockContext).Queryable().FirstOrDefault( a => a.AliasPersonId == person.Id ); if ( primaryAlias != null ) { SetWorkflowAttributeValue( action, guid, primaryAlias.Guid.ToString() ); return true; } else { errorMessages.Add( "Could not determine person primary alias!" ); } } else if ( entity is Group && attribute.FieldTypeId == FieldTypeCache.Read( SystemGuid.FieldType.GROUP.AsGuid(), rockContext ).Id ) { var group = entity as Group; SetWorkflowAttributeValue( action, guid, group.Id.ToString() ); return true; } else { errorMessages.Add( "The attribute is not the correct type for the entity!" ); } } } else { errorMessages.Add( "Invalid attribute!" ); } } else { errorMessages.Add( "Invalid attribute!" ); } errorMessages.ForEach( m => action.AddLogEntry( m, true ) ); return false; }
/// <summary> /// Formats the value extended. /// </summary> /// <param name="value">The value.</param> /// <param name="configurationValues">The configuration values.</param> /// <returns></returns> public string UrlLink( string value, Dictionary<string, ConfigurationValue> configurationValues ) { if ( !string.IsNullOrWhiteSpace( value ) ) { Guid guid = value.AsGuid(); int personId = new PersonAliasService( new RockContext() ).Queryable() .Where( a => a.Guid.Equals( guid ) ) .Select( a => a.PersonId ) .FirstOrDefault(); return string.Format( "person/{0}", personId ); } return value; }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue( System.Web.UI.Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed ) { string formattedValue = string.Empty; if ( !string.IsNullOrWhiteSpace( value ) ) { Guid guid = value.AsGuid(); formattedValue = new PersonAliasService( new RockContext() ).Queryable() .Where( a => a.Guid.Equals( guid ) ) .Select( a => a.Person.NickName + " " + a.Person.LastName ) .FirstOrDefault(); } return base.FormatValue( parentControl, formattedValue, null, condensed ); }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); string attributeValue = GetAttributeValue( action, "Attribute" ); Guid guid = attributeValue.AsGuid(); if (!guid.IsEmpty()) { var attribute = AttributeCache.Read( guid, rockContext ); if ( attribute != null ) { string value = GetAttributeValue( action, "Person" ); guid = value.AsGuid(); if ( !guid.IsEmpty() ) { var personAlias = new PersonAliasService( rockContext ).Get( guid ); if ( personAlias != null && personAlias.Person != null ) { action.Activity.Workflow.SetAttributeValue( attribute.Key, value ); action.AddLogEntry( string.Format( "Set '{0}' attribute to '{1}'.", attribute.Name, personAlias.Person.FullName ) ); return true; } else { errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", guid.ToString() ) ); } } else { action.Activity.Workflow.SetAttributeValue( attribute.Key, string.Empty ); action.AddLogEntry( string.Format( "Set '{0}' attribute to nobody.", attribute.Name ) ); return true; } } else { errorMessages.Add( string.Format( "Attribute could not be found for selected attribute value ('{0}')!", guid.ToString() ) ); } } else { errorMessages.Add( string.Format( "Selected attribute value ('{0}') was not a valid Guid!", attributeValue ) ); } errorMessages.ForEach( m => action.AddLogEntry( m, true ) ); return true; }
/// <summary> /// Configures a control to display and toggle following for the specified entity /// </summary> /// <param name="followEntity">The follow entity. NOTE: Make sure to use PersonAlias instead of Person when following a Person</param> /// <param name="followControl">The follow control.</param> /// <param name="follower">The follower.</param> public static void SetFollowing( IEntity followEntity, WebControl followControl, Person follower ) { var followingEntityType = EntityTypeCache.Read( followEntity.GetType() ); if ( follower != null && follower.PrimaryAliasId.HasValue ) { using ( var rockContext = new RockContext() ) { var personAliasService = new PersonAliasService( rockContext ); var followingService = new FollowingService( rockContext ); var followingQry = followingService.Queryable() .Where( f => f.EntityTypeId == followingEntityType.Id && f.PersonAlias.PersonId == follower.Id ); followingQry = followingQry.Where( f => f.EntityId == followEntity.Id ); if ( followingQry.Any() ) { followControl.AddCssClass( "following" ); } else { followControl.RemoveCssClass( "following" ); } } int entityId = followEntity.Id; // only show the following control if the entity has been saved to the database followControl.Visible = entityId > 0; string script = string.Format( @"Rock.controls.followingsToggler.initialize($('#{0}'), {1}, {2}, {3}, {4});", followControl.ClientID, followingEntityType.Id, entityId, follower.Id, follower.PrimaryAliasId ); ScriptManager.RegisterStartupScript( followControl, followControl.GetType(), "following", script, true ); } }
/// <summary> /// Returns the Person sending the SMS communication. /// Will use the Response Recipient if one exists otherwise the Current Person. /// </summary> /// <returns></returns> public Rock.Model.Person GetSMSFromPerson() { // Try to get a from person Rock.Model.Person person = CurrentPerson; // If the response recipient exists use it var fromPersonAliasGuid = FromNumber.GetAttributeValue("ResponseRecipient").AsGuidOrNull(); if (fromPersonAliasGuid.HasValue) { person = new Rock.Model.PersonAliasService(new Data.RockContext()) .Queryable() .AsNoTracking() .Where(p => p.Guid.Equals(fromPersonAliasGuid.Value)) .Select(p => p.Person) .FirstOrDefault(); } return(person); }
/// <summary> /// Handles the Delete event of the gFollowings control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gFollowings_Delete( object sender, RowEventArgs e ) { var rockContext = new RockContext(); var personAliasService = new PersonAliasService( rockContext ); var followingService = new FollowingService( rockContext ); var paQry = personAliasService.Queryable() .Where( p => p.PersonId == e.RowKeyId ) .Select( p => p.Id ); int personAliasEntityTypeId = EntityTypeCache.Read( "Rock.Model.PersonAlias" ).Id; foreach ( var following in followingService.Queryable() .Where( f => f.EntityTypeId == personAliasEntityTypeId && paQry.Contains( f.EntityId ) && f.PersonAliasId == CurrentPersonAlias.Id ) ) { followingService.Delete( following ); } rockContext.SaveChanges(); BindGrid(); }
/// <summary> /// Binds the attendees grid. /// </summary> private void BindAttendeesGrid() { var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( drpSlidingDateRange.DelimitedValues ); if ( dateRange.End == null || dateRange.End > RockDateTime.Now ) { dateRange.End = RockDateTime.Now; } var rockContext = new RockContext(); // make a qryPersonAlias so that the generated SQL will be a "WHERE .. IN ()" instead of an OUTER JOIN (which is incredibly slow for this) var qryPersonAlias = new PersonAliasService( rockContext ).Queryable(); var qryAttendance = new AttendanceService( rockContext ).Queryable(); qryAttendance = qryAttendance.Where( a => a.DidAttend.HasValue && a.DidAttend.Value ); var groupType = this.GetSelectedTemplateGroupType(); var qryAllVisits = qryAttendance; if ( groupType != null ) { var childGroupTypeIds = new GroupTypeService( rockContext ).GetChildGroupTypes( groupType.Id ).Select( a => a.Id ); qryAllVisits = qryAttendance.Where( a => childGroupTypeIds.Any( b => b == a.Group.GroupTypeId ) ); } else { return; } var groupIdList = new List<int>(); string groupIds = GetSelectedGroupIds().AsDelimited( "," ); if ( !string.IsNullOrWhiteSpace( groupIds ) ) { groupIdList = groupIds.Split( ',' ).AsIntegerList(); qryAttendance = qryAttendance.Where( a => a.GroupId.HasValue && groupIdList.Contains( a.GroupId.Value ) ); } //// If campuses were included, filter attendances by those that have selected campuses //// if 'null' is one of the campuses, treat that as a 'CampusId is Null' var includeNullCampus = clbCampuses.SelectedValues.Any( a => a.Equals( "null", StringComparison.OrdinalIgnoreCase ) ); var campusIdList = clbCampuses.SelectedValues.AsIntegerList(); // remove 0 from the list, just in case it is there campusIdList.Remove( 0 ); if ( campusIdList.Any() ) { if ( includeNullCampus ) { // show records that have a campusId in the campusIdsList + records that have a null campusId qryAttendance = qryAttendance.Where( a => ( a.CampusId.HasValue && campusIdList.Contains( a.CampusId.Value ) ) || !a.CampusId.HasValue ); } else { // only show records that have a campusId in the campusIdList qryAttendance = qryAttendance.Where( a => a.CampusId.HasValue && campusIdList.Contains( a.CampusId.Value ) ); } } else if ( includeNullCampus ) { // 'null' was the only campusId in the campusIds parameter, so only show records that have a null CampusId qryAttendance = qryAttendance.Where( a => !a.CampusId.HasValue ); } // have the "Missed" query be the same as the qry before the Main date range is applied since it'll have a different date range var qryMissed = qryAttendance; if ( dateRange.Start.HasValue ) { qryAttendance = qryAttendance.Where( a => a.StartDateTime >= dateRange.Start.Value ); } if ( dateRange.End.HasValue ) { qryAttendance = qryAttendance.Where( a => a.StartDateTime < dateRange.End.Value ); } // we want to get the first 2 visits at a minimum so we can show the date in the grid int nthVisitsTake = 2; int? byNthVisit = null; if ( radByVisit.Checked ) { // If we are filtering by nth visit, we might want to get up to first 5 byNthVisit = ddlNthVisit.SelectedValue.AsIntegerOrNull(); if ( byNthVisit.HasValue && byNthVisit > 2 ) { nthVisitsTake = byNthVisit.Value; } } ChartGroupBy groupBy = hfGroupBy.Value.ConvertToEnumOrNull<ChartGroupBy>() ?? ChartGroupBy.Week; IQueryable<PersonWithSummary> qryByPersonWithSummary = null; if ( byNthVisit.HasValue && byNthVisit.Value == 0 ) { // Show members of the selected groups that did not attend at all during selected date range // Get all the person ids that did attend var attendeePersonIds = qryAttendance.Select( a => a.PersonAlias.PersonId ); // Get all the active members of the selected groups who have no attendance within selected date range and campus qryByPersonWithSummary = new GroupMemberService( rockContext ) .Queryable().AsNoTracking() .Where( m => groupIdList.Contains( m.GroupId ) && !attendeePersonIds.Contains( m.PersonId ) && m.GroupMemberStatus == GroupMemberStatus.Active ) .Select( m => new PersonWithSummary { PersonId = m.PersonId, FirstVisits = new DateTime[] { }.AsQueryable(), LastVisit = new AttendancePersonAlias(), AttendanceSummary = new DateTime[] { }.AsQueryable() } ); } else { var qryAttendanceWithSummaryDateTime = qryAttendance.GetAttendanceWithSummaryDateTime( groupBy ); var qryGroup = new GroupService( rockContext ).Queryable(); var qryJoinPerson = qryAttendance.Join( qryPersonAlias, k1 => k1.PersonAliasId, k2 => k2.Id, ( a, pa ) => new { CampusId = a.CampusId, GroupId = a.GroupId, ScheduleId = a.ScheduleId, StartDateTime = a.StartDateTime, PersonAliasId = pa.Id, PersonAliasPersonId = pa.PersonId } ); var qryJoinFinal = qryJoinPerson.Join( qryGroup, k1 => k1.GroupId, k2 => k2.Id, ( a, g ) => new AttendancePersonAlias { CampusId = a.CampusId, GroupId = a.GroupId, GroupName = g.Name, ScheduleId = a.ScheduleId, StartDateTime = a.StartDateTime, PersonAliasId = a.PersonAliasId, PersonAliasPersonId = a.PersonAliasPersonId } ); var qryByPerson = qryJoinFinal.GroupBy( a => a.PersonAliasPersonId ).Select( a => new { PersonId = a.Key, Attendances = a } ); int? attendedMinCount = null; int? attendedMissedCount = null; DateRange attendedMissedDateRange = new DateRange(); if ( radByPattern.Checked ) { attendedMinCount = tbPatternXTimes.Text.AsIntegerOrNull(); if ( cbPatternAndMissed.Checked ) { attendedMissedCount = tbPatternMissedXTimes.Text.AsIntegerOrNull(); attendedMissedDateRange = new DateRange( drpPatternDateRange.LowerValue, drpPatternDateRange.UpperValue ); if ( !attendedMissedDateRange.Start.HasValue || !attendedMissedDateRange.End.HasValue ) { nbMissedDateRangeRequired.Visible = true; return; } } } nbMissedDateRangeRequired.Visible = false; // get either the first 2 visits or the first 5 visits (using a const take of 2 or 5 vs a variable to help the SQL optimizer) qryByPersonWithSummary = qryByPerson.Select( a => new PersonWithSummary { PersonId = a.PersonId, FirstVisits = qryAllVisits.Where( b => qryPersonAlias.Where( pa => pa.PersonId == a.PersonId ).Any( pa => pa.Id == b.PersonAliasId ) ).Select( s => s.StartDateTime ).OrderBy( x => x ).Take( 2 ), LastVisit = a.Attendances.OrderByDescending( x => x.StartDateTime ).FirstOrDefault(), AttendanceSummary = qryAttendanceWithSummaryDateTime.Where( x => qryPersonAlias.Where( pa => pa.PersonId == a.PersonId ).Any( pa => pa.Id == x.Attendance.PersonAliasId ) ).GroupBy( g => g.SummaryDateTime ).Select( s => s.Key ) } ); if ( nthVisitsTake > 2 ) { qryByPersonWithSummary = qryByPerson.Select( a => new PersonWithSummary { PersonId = a.PersonId, FirstVisits = qryAllVisits.Where( b => qryPersonAlias.Where( pa => pa.PersonId == a.PersonId ).Any( pa => pa.Id == b.PersonAliasId ) ).Select( s => s.StartDateTime ).OrderBy( x => x ).Take( 5 ), LastVisit = a.Attendances.OrderByDescending( x => x.StartDateTime ).FirstOrDefault(), AttendanceSummary = qryAttendanceWithSummaryDateTime.Where( x => qryPersonAlias.Where( pa => pa.PersonId == a.PersonId ).Any( pa => pa.Id == x.Attendance.PersonAliasId ) ).GroupBy( g => g.SummaryDateTime ).Select( s => s.Key ) } ); } if ( byNthVisit.HasValue ) { // only return attendees where their nth visit is within the selected daterange int skipCount = byNthVisit.Value - 1; qryByPersonWithSummary = qryByPersonWithSummary.Where( a => a.FirstVisits.OrderBy( x => x ).Skip( skipCount ).Take( 1 ).Any( d => d >= dateRange.Start && d < dateRange.End ) ); } if ( attendedMinCount.HasValue ) { qryByPersonWithSummary = qryByPersonWithSummary.Where( a => a.AttendanceSummary.Count() >= attendedMinCount ); } if ( attendedMissedCount.HasValue ) { if ( attendedMissedDateRange.Start.HasValue && attendedMissedDateRange.End.HasValue ) { var attendedMissedPossible = GetPossibleAttendancesForDateRange( attendedMissedDateRange, groupBy ); int attendedMissedPossibleCount = attendedMissedPossible.Count(); qryMissed = qryMissed.Where( a => a.StartDateTime >= attendedMissedDateRange.Start.Value && a.StartDateTime < attendedMissedDateRange.End.Value ); var qryMissedAttendanceByPersonAndSummary = qryMissed.GetAttendanceWithSummaryDateTime( groupBy ) .GroupBy( g1 => new { g1.SummaryDateTime, g1.Attendance.PersonAlias.PersonId } ) .GroupBy( a => a.Key.PersonId ) .Select( a => new { PersonId = a.Key, AttendanceCount = a.Count() } ); var qryMissedByPerson = qryMissedAttendanceByPersonAndSummary .Where( x => ( attendedMissedPossibleCount - x.AttendanceCount ) >= attendedMissedCount ); // filter to only people that missed at least X weeks/months/years between specified missed date range qryByPersonWithSummary = qryByPersonWithSummary.Where( a => qryMissedByPerson.Any( b => b.PersonId == a.PersonId ) ); } } } var personService = new PersonService( rockContext ); // Filter by dataview var dataViewId = dvpDataView.SelectedValueAsInt(); if ( dataViewId.HasValue ) { var dataView = new DataViewService( _rockContext ).Get( dataViewId.Value ); if ( dataView != null ) { var errorMessages = new List<string>(); ParameterExpression paramExpression = personService.ParameterExpression; Expression whereExpression = dataView.GetExpression( personService, paramExpression, out errorMessages ); SortProperty sort = null; var dataViewPersonIdQry = personService .Queryable().AsNoTracking() .Where( paramExpression, whereExpression, sort ) .Select( p => p.Id ); qryByPersonWithSummary = qryByPersonWithSummary.Where( a => dataViewPersonIdQry.Contains( a.PersonId ) ); } } // declare the qryResult that we'll use in case they didn't choose IncludeParents or IncludeChildren (and the Anonymous Type will also work if we do include parents or children) var qryPerson = personService.Queryable(); var qryResult = qryByPersonWithSummary.Join( qryPerson, a => a.PersonId, p => p.Id, ( a, p ) => new { a.PersonId, ParentId = (int?)null, ChildId = (int?)null, Person = p, Parent = (Person)null, Child = (Person)null, a.FirstVisits, a.LastVisit, p.PhoneNumbers, a.AttendanceSummary } ); var includeParents = hfViewBy.Value.ConvertToEnumOrNull<ViewBy>().GetValueOrDefault( ViewBy.Attendees ) == ViewBy.ParentsOfAttendees; var includeChildren = hfViewBy.Value.ConvertToEnumOrNull<ViewBy>().GetValueOrDefault( ViewBy.Attendees ) == ViewBy.ChildrenOfAttendees; // if Including Parents, join with qryChildWithParent instead of qryPerson if ( includeParents ) { var qryChildWithParent = new PersonService( rockContext ).GetChildWithParent(); qryResult = qryByPersonWithSummary.Join( qryChildWithParent, a => a.PersonId, p => p.Child.Id, ( a, p ) => new { a.PersonId, ParentId = (int?)p.Parent.Id, ChildId = (int?)null, Person = p.Child, Parent = p.Parent, Child = (Person)null, a.FirstVisits, a.LastVisit, p.Parent.PhoneNumbers, a.AttendanceSummary } ); } if ( includeChildren ) { var qryParentWithChildren = new PersonService( rockContext ).GetParentWithChild(); qryResult = qryByPersonWithSummary.Join( qryParentWithChildren, a => a.PersonId, p => p.Parent.Id, ( a, p ) => new { a.PersonId, ParentId = (int?)null, ChildId = (int?)p.Child.Id, Person = p.Parent, Parent = (Person)null, Child = p.Child, a.FirstVisits, a.LastVisit, p.Child.PhoneNumbers, a.AttendanceSummary } ); } var parentField = gAttendeesAttendance.Columns.OfType<PersonField>().FirstOrDefault( a => a.HeaderText == "Parent" ); if ( parentField != null ) { parentField.Visible = includeParents; } var parentEmailField = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Parent Email" ); if ( parentEmailField != null ) { parentEmailField.ExcelExportBehavior = includeParents ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude; } var childField = gAttendeesAttendance.Columns.OfType<PersonField>().FirstOrDefault( a => a.HeaderText == "Child" ); if ( childField != null ) { childField.Visible = includeChildren; } var childEmailField = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Child Email" ); if ( childEmailField != null ) { childEmailField.ExcelExportBehavior = includeChildren ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude; } SortProperty sortProperty = gAttendeesAttendance.SortProperty; if ( sortProperty != null ) { if ( sortProperty.Property == "AttendanceSummary.Count" ) { if ( sortProperty.Direction == SortDirection.Descending ) { qryResult = qryResult.OrderByDescending( a => a.AttendanceSummary.Count() ); } else { qryResult = qryResult.OrderBy( a => a.AttendanceSummary.Count() ); } } else if ( sortProperty.Property == "FirstVisit.StartDateTime" ) { if ( sortProperty.Direction == SortDirection.Descending ) { qryResult = qryResult.OrderByDescending( a => a.FirstVisits.Min() ); } else { qryResult = qryResult.OrderBy( a => a.FirstVisits.Min() ); } } else { qryResult = qryResult.Sort( sortProperty ); } } else { qryResult = qryResult.OrderBy( a => a.Person.LastName ).ThenBy( a => a.Person.NickName ); } var attendancePercentField = gAttendeesAttendance.Columns.OfType<RockTemplateField>().First( a => a.HeaderText.EndsWith( "Attendance %" ) ); attendancePercentField.HeaderText = string.Format( "{0}ly Attendance %", groupBy.ConvertToString() ); // Calculate all the possible attendance summary dates UpdatePossibleAttendances( dateRange, groupBy ); // pre-load the schedule names since FriendlyScheduleText requires building the ICal object, etc _scheduleNameLookup = new ScheduleService( rockContext ).Queryable() .ToList() .ToDictionary( k => k.Id, v => v.FriendlyScheduleText ); if ( includeParents ) { gAttendeesAttendance.PersonIdField = "ParentId"; gAttendeesAttendance.DataKeyNames = new string[] { "ParentId", "PersonId" }; } else if ( includeChildren ) { gAttendeesAttendance.PersonIdField = "ChildId"; gAttendeesAttendance.DataKeyNames = new string[] { "ChildId", "PersonId" }; } else { gAttendeesAttendance.PersonIdField = "PersonId"; gAttendeesAttendance.DataKeyNames = new string[] { "PersonId" }; } // Create the dynamic attendance grid columns as needed CreateDynamicAttendanceGridColumns(); try { nbAttendeesError.Visible = false; // increase the timeout from 30 to 90. The Query can be slow if SQL hasn't calculated the Query Plan for the query yet. // Sometimes, most of the time consumption is figuring out the Query Plan, but after it figures it out, it caches it so that the next time it'll be much faster rockContext.Database.CommandTimeout = 90; gAttendeesAttendance.SetLinqDataSource( qryResult.AsNoTracking() ); gAttendeesAttendance.DataBind(); } catch ( Exception exception ) { LogAndShowException( exception ); } }
/// <summary> /// Sends a background request to Protect My Ministry /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="workflow">The Workflow initiating the request.</param> /// <param name="personAttribute">The person attribute.</param> /// <param name="ssnAttribute">The SSN attribute.</param> /// <param name="requestTypeAttribute">The request type attribute.</param> /// <param name="billingCodeAttribute">The billing code attribute.</param> /// <param name="errorMessages">The error messages.</param> /// <returns> /// True/False value of whether the request was successfully sent or not /// </returns> /// <exception cref="System.NotImplementedException"></exception> /// <remarks> /// Note: If the associated workflow type does not have attributes with the following keys, they /// will automatically be added to the workflow type configuration in order to store the results /// of the PMM background check request /// ReportStatus: The status returned by PMM /// ReportLink: The location of the background report on PMM server /// ReportRecommendation: PMM's recomendataion /// Report (BinaryFile): The downloaded background report /// </remarks> public override bool SendRequest( RockContext rockContext, Model.Workflow workflow, AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute, AttributeCache billingCodeAttribute, out List<string> errorMessages ) { errorMessages = new List<string>(); try { // Check to make sure workflow is not null if ( workflow == null ) { errorMessages.Add( "The 'ProtectMyMinistry' requires a valid workflow." ); return false; } // Get the person that the request is for Person person = null; if ( personAttribute != null ) { Guid? personAliasGuid = workflow.GetAttributeValue( personAttribute.Key ).AsGuidOrNull(); if ( personAliasGuid.HasValue ) { person = new PersonAliasService( rockContext ).Queryable() .Where( p => p.Guid.Equals( personAliasGuid.Value ) ) .Select( p => p.Person ) .FirstOrDefault(); } } if ( person == null ) { errorMessages.Add( "The 'ProtectMyMinistry' background check requires the workflow to have a 'Person' attribute that contains the person who the background check is for." ); return false; } string password = Encryption.DecryptString( GetAttributeValue( "Password" ) ); XElement rootElement = new XElement( "OrderXML", new XElement( "Method", "SEND ORDER" ), new XElement( "Authentication", new XElement( "Username", GetAttributeValue( "UserName" ) ), new XElement( "Password", password ) ) ); if ( GetAttributeValue( "TestMode" ).AsBoolean() ) { rootElement.Add( new XElement( "TestMode", "YES" ) ); } rootElement.Add( new XElement( "ReturnResultURL", GetAttributeValue( "ReturnURL" ) ) ); XElement orderElement = new XElement( "Order" ); rootElement.Add( orderElement ); if ( billingCodeAttribute != null ) { Guid? campusGuid = workflow.GetAttributeValue( billingCodeAttribute.Key ).AsGuidOrNull(); if ( campusGuid.HasValue ) { var campus = CampusCache.Read( campusGuid.Value ); if ( campus != null ) { orderElement.Add( new XElement( "BillingReferenceCode", campus.Name ) ); } } } XElement subjectElement = new XElement( "Subject", new XElement( "FirstName", person.FirstName ), new XElement( "MiddleName", person.MiddleName ), new XElement( "LastName", person.LastName ) ); orderElement.Add( subjectElement ); if ( person.BirthDate.HasValue ) { subjectElement.Add( new XElement( "DOB", person.BirthDate.Value.ToString( "MM/dd/yyyy" ) ) ); } if ( ssnAttribute != null ) { string ssn = Encryption.DecryptString( workflow.GetAttributeValue( ssnAttribute.Key ) ).AsNumeric(); if ( !string.IsNullOrWhiteSpace( ssn ) && ssn.Length == 9 ) { subjectElement.Add( new XElement( "SSN", ssn.Insert( 5, "-" ).Insert( 3, "-" ) ) ); } } if ( person.Gender == Gender.Male ) { subjectElement.Add( new XElement( "Gender", "Male" ) ); } if ( person.Gender == Gender.Female ) { subjectElement.Add( new XElement( "Gender", "Female" ) ); } var homelocation = person.GetHomeLocation(); if ( homelocation != null) { subjectElement.Add( new XElement( "CurrentAddress", new XElement( "StreetAddress", homelocation.Street1 ), new XElement( "City", homelocation.City ), new XElement( "State", homelocation.State ), new XElement( "Zipcode", homelocation.PostalCode ) ) ); } XElement aliasesElement = new XElement( "Aliases" ); if ( person.NickName != person.FirstName ) { aliasesElement.Add( new XElement( "Alias", new XElement( "FirstName", person.NickName ) ) ); } // foreach ( string lastName in [previous last names] ) //{ // aliasesElement.Add( new XElement( "Alias", new XElement( "LastName", lastName ) ) ); //} if ( aliasesElement.HasElements ) { subjectElement.Add( aliasesElement ); } string packageType = requestTypeAttribute != null ? workflow.GetAttributeValue( requestTypeAttribute.Key ) : string.Empty; if ( string.IsNullOrWhiteSpace(packageType) ) { packageType = "Basic"; } orderElement.Add( new XElement( "PackageServiceCode", packageType, new XAttribute( "OrderId", workflow.Id.ToString() ) ) ); orderElement.Add( new XElement( "OrderDetail", new XAttribute( "OrderId", workflow.Id.ToString() ), new XAttribute( "ServiceCode", "combo" ) ) ); XDocument xdoc = new XDocument( new XDeclaration( "1.0", "UTF-8", "yes" ), rootElement ); XDocument xResult = PostToWebService( xdoc, GetAttributeValue("RequestURL") ); if ( _HTTPStatusCode == HttpStatusCode.OK ) { if ( xResult.Root.Descendants().Count() > 0 ) { SaveResults( xResult, workflow, rockContext ); } return true; } else { errorMessages.Add( "Invalid HttpStatusCode: " + _HTTPStatusCode.ToString() ); } return false; } catch( Exception ex ) { ExceptionLogService.LogException( ex, null ); errorMessages.Add( ex.Message ); return false; } }
/// <summary> /// This method is called in the /// <see cref="M:Rock.Data.Model`1.PreSaveChanges(Rock.Data.DbContext,System.Data.Entity.Infrastructure.DbEntityEntry,System.Data.Entity.EntityState)" /> /// method. Use it to populate <see cref="P:Rock.Data.Model`1.HistoryItems" /> if needed. /// These history items are queued to be written into the database post save (so that they /// are only written if the save actually occurs). /// </summary> /// <param name="dbContext">The database context.</param> /// <param name="entry">The entry.</param> /// <param name="state">The state.</param> protected override void BuildHistoryItems(Data.DbContext dbContext, DbEntityEntry entry, EntityState state) { // Sometimes, especially if the model is being deleted, some properties might not be // populated, but we can query to try to get their original value. We need to use a new // rock context to get the actual value from the DB var rockContext = new RockContext(); var service = new PersonSearchKeyService(rockContext); var originalModel = service.Queryable("PersonAlias") .FirstOrDefault(fpsa => fpsa.Id == Id); // Use the original value for the person alias or the new value if that is not set var personId = (originalModel?.PersonAlias ?? PersonAlias)?.PersonId; if (!personId.HasValue) { // If this model is new, it won't have any virtual properties hydrated or an original // record in the database if (PersonAliasId.HasValue) { var personAliasService = new PersonAliasService(rockContext); var personAlias = personAliasService.Get(PersonAliasId.Value); personId = personAlias?.PersonId; } // We can't log history if we don't know who the saved account belongs to if (!personId.HasValue) { return; } } History.HistoryVerb verb; switch (state) { case EntityState.Added: verb = History.HistoryVerb.Add; break; case EntityState.Deleted: verb = History.HistoryVerb.Delete; break; case EntityState.Modified: verb = History.HistoryVerb.Modify; break; default: // As of now, there is no requirement to log other events return; } var caption = verb == History.HistoryVerb.Modify ? "Person Search Key" : GetCaptionForHistory(originalModel?.SearchValue ?? SearchValue, originalModel?.SearchTypeValueId ?? SearchTypeValueId); var historyChangeList = new History.HistoryChangeList(); if (verb != History.HistoryVerb.Modify) { historyChangeList.AddChange(verb, History.HistoryChangeType.Record, "Person Search Key"); } else { History.EvaluateChange(historyChangeList, $"SearchValue", entry.OriginalValues["SearchValue"].ToStringSafe(), SearchValue, false); var originalSearchType = DefinedValueCache.Get(entry.OriginalValues["SearchTypeValueId"].ToStringSafe().AsInteger()); var currentSearchType = DefinedValueCache.Get(SearchTypeValueId); History.EvaluateChange(historyChangeList, $"SearchType", originalSearchType?.Value, currentSearchType?.Value, false); } HistoryItems = HistoryService.GetChanges( typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON.AsGuid(), personId.Value, historyChangeList, caption, typeof(PersonSearchKey), Id, dbContext.GetCurrentPersonAlias()?.Id, dbContext.SourceOfChange); }
private void LaunchWorkflow( WorkflowType workflowType, FinancialTransaction transaction ) { if ( workflowType != null ) { using ( var rockContext = new RockContext() ) { string workflowName = transaction.TransactionCode; if ( transaction.AuthorizedPersonAliasId != null ) { var person = new PersonAliasService( rockContext ).GetPerson( transaction.AuthorizedPersonAliasId.Value ); if ( person != null ) { workflowName = person.FullName; } } var workflowService = new WorkflowService( rockContext ); var workflow = Rock.Model.Workflow.Activate( workflowType, workflowName, rockContext ); if ( workflow != null ) { List<string> workflowErrors; workflowService.Process( workflow, transaction, out workflowErrors ); } } } }
/// <summary> /// Parses the controls. /// </summary> private void ParseControls( RockContext rockContext = null, bool expandInvalid = false ) { if (rockContext == null) { rockContext = new RockContext(); } if ( Workflow.CompletedDateTime.HasValue && !cbIsCompleted.Checked ) { Workflow.CompletedDateTime = null; } else if ( !Workflow.CompletedDateTime.HasValue && cbIsCompleted.Checked ) { Workflow.CompletedDateTime = RockDateTime.Now; } Workflow.Name = tbName.Text; Workflow.Status = tbStatus.Text; int? initiatorPersonId = ppInitiator.PersonId; if ( initiatorPersonId.HasValue ) { var personAlias = new PersonAliasService( rockContext ).GetByAliasId( initiatorPersonId.Value ); if ( personAlias != null ) { Workflow.InitiatorPersonAlias = personAlias; Workflow.InitiatorPersonAliasId = personAlias.Id; } else { Workflow.InitiatorPersonAlias = null; Workflow.InitiatorPersonAliasId = null; } } Helper.GetEditValues( phAttributes, Workflow ); ExpandedActivities = new List<Guid>(); foreach ( var activityEditor in phActivities.Controls.OfType<WorkflowActivityEditor>() ) { var activity = Workflow.Activities.Where( a => a.Guid.Equals(activityEditor.ActivityGuid)).FirstOrDefault(); if (activity != null) { activityEditor.GetWorkflowActivity(activity, expandInvalid); } if (activityEditor.Expanded) { ExpandedActivities.Add( activity.Guid ); } } }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); Guid? groupGuid = null; Person person = null; Group group = null; string noteValue = string.Empty; string captionValue = string.Empty; bool isAlert = false; // get the group attribute Guid groupAttributeGuid = GetAttributeValue( action, "Group" ).AsGuid(); if ( !groupAttributeGuid.IsEmpty() ) { groupGuid = action.GetWorklowAttributeValue( groupAttributeGuid ).AsGuidOrNull(); if ( groupGuid.HasValue ) { group = new GroupService( rockContext ).Get( groupGuid.Value ); if ( group == null ) { errorMessages.Add( "The group provided does not exist." ); } } else { errorMessages.Add( "Invalid group provided." ); } } // get person alias guid Guid personAliasGuid = Guid.Empty; string personAttribute = GetAttributeValue( action, "Person" ); Guid guid = personAttribute.AsGuid(); if ( !guid.IsEmpty() ) { var attribute = AttributeCache.Read( guid, rockContext ); if ( attribute != null ) { string value = action.GetWorklowAttributeValue( guid ); personAliasGuid = value.AsGuid(); } if ( personAliasGuid != Guid.Empty ) { person = new PersonAliasService( rockContext ).Queryable() .Where( p => p.Guid.Equals( personAliasGuid ) ) .Select( p => p.Person ) .FirstOrDefault(); } else { errorMessages.Add( "The person could not be found!" ); } } // get caption captionValue = GetAttributeValue( action, "Caption" ); guid = captionValue.AsGuid(); if ( guid.IsEmpty() ) { captionValue = captionValue.ResolveMergeFields( GetMergeFields( action ) ); } else { var workflowAttributeValue = action.GetWorklowAttributeValue( guid ); if ( workflowAttributeValue != null ) { captionValue = workflowAttributeValue; } } // get group member note noteValue = GetAttributeValue( action, "Note" ); guid = noteValue.AsGuid(); if ( guid.IsEmpty() ) { noteValue = noteValue.ResolveMergeFields( GetMergeFields( action ) ); } else { var workflowAttributeValue = action.GetWorklowAttributeValue( guid ); if ( workflowAttributeValue != null ) { noteValue = workflowAttributeValue; } } // get alert type string isAlertString = GetAttributeValue( action, "IsAlert" ); guid = isAlertString.AsGuid(); if ( guid.IsEmpty() ) { isAlert = isAlertString.AsBoolean(); } else { var workflowAttributeValue = action.GetWorklowAttributeValue( guid ); if ( workflowAttributeValue != null ) { isAlert = workflowAttributeValue.AsBoolean(); } } // get note type NoteTypeCache noteType = null; Guid noteTypeGuid = GetAttributeValue( action, "NoteType" ).AsGuid(); if ( !noteTypeGuid.IsEmpty() ) { noteType = NoteTypeCache.Read( noteTypeGuid, rockContext ); if (noteType == null ) { errorMessages.Add( "The note type provided does not exist." ); } } else { errorMessages.Add( "Invalid note type provided." ); } // set note if ( group != null && person != null && noteType != null ) { var groupMembers = new GroupMemberService( rockContext ).Queryable() .Where( m => m.Group.Guid == groupGuid && m.PersonId == person.Id ).ToList(); if ( groupMembers.Count() > 0 ) { foreach ( var groupMember in groupMembers ) { NoteService noteservice = new NoteService( rockContext ); Note note = new Note(); noteservice.Add( note ); note.NoteTypeId = noteType.Id; note.Text = noteValue; note.IsAlert = isAlert; note.Caption = captionValue; note.EntityId = groupMember.Id; rockContext.SaveChanges(); } } else { errorMessages.Add( string.Format("{0} is not a member of the group {1}.", person.FullName, group.Name )); } } errorMessages.ForEach( m => action.AddLogEntry( m, true ) ); return true; }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); var mergeFields = GetMergeFields( action ); int? fromId = null; Guid? fromGuid = GetAttributeValue( action, "From" ).AsGuidOrNull(); if ( fromGuid.HasValue ) { var fromValue = DefinedValueCache.Read( fromGuid.Value, rockContext ); if ( fromValue != null ) { fromId = fromValue.Id; } } var recipients = new List<RecipientData>(); string toValue = GetAttributeValue( action, "To" ); Guid guid = toValue.AsGuid(); if ( !guid.IsEmpty() ) { var attribute = AttributeCache.Read( guid, rockContext ); if ( attribute != null ) { string toAttributeValue = action.GetWorklowAttributeValue( guid ); if ( !string.IsNullOrWhiteSpace( toAttributeValue ) ) { switch ( attribute.FieldType.Class ) { case "Rock.Field.Types.TextFieldType": { recipients.Add( new RecipientData( toAttributeValue ) ); break; } case "Rock.Field.Types.PersonFieldType": { Guid personAliasGuid = toAttributeValue.AsGuid(); if ( !personAliasGuid.IsEmpty() ) { var phoneNumber = new PersonAliasService( rockContext ).Queryable() .Where( a => a.Guid.Equals( personAliasGuid ) ) .SelectMany( a => a.Person.PhoneNumbers ) .Where( p => p.IsMessagingEnabled ) .FirstOrDefault(); if ( phoneNumber == null ) { action.AddLogEntry( "Invalid Recipient: Person or valid SMS phone number not found", true ); } else { string smsNumber = phoneNumber.Number; if ( !string.IsNullOrWhiteSpace( phoneNumber.CountryCode ) ) { smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number; } var recipient = new RecipientData( smsNumber ); recipients.Add( recipient ); var person = new PersonAliasService( rockContext ).GetPerson( personAliasGuid ); if ( person != null ) { recipient.MergeFields.Add( "Person", person ); } } } break; } case "Rock.Field.Types.GroupFieldType": case "Rock.Field.Types.SecurityRoleFieldType": { int? groupId = toAttributeValue.AsIntegerOrNull(); Guid? groupGuid = toAttributeValue.AsGuidOrNull(); IQueryable<GroupMember> qry = null; // Handle situations where the attribute value is the ID if ( groupId.HasValue ) { qry = new GroupMemberService( rockContext ).GetByGroupId( groupId.Value ); } // Handle situations where the attribute value stored is the Guid else if ( groupGuid.HasValue ) { qry = new GroupMemberService( rockContext ).GetByGroupGuid( groupGuid.Value ); } else { action.AddLogEntry( "Invalid Recipient: No valid group id or Guid", true ); } if ( qry != null ) { foreach ( var person in qry .Where( m => m.GroupMemberStatus == GroupMemberStatus.Active ) .Select( m => m.Person ) ) { var phoneNumber = person.PhoneNumbers .Where( p => p.IsMessagingEnabled ) .FirstOrDefault(); if ( phoneNumber != null ) { string smsNumber = phoneNumber.Number; if ( !string.IsNullOrWhiteSpace( phoneNumber.CountryCode ) ) { smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number; } var recipient = new RecipientData( smsNumber ); recipients.Add( recipient ); recipient.MergeFields.Add( "Person", person ); } } } break; } } } } } else { if ( !string.IsNullOrWhiteSpace( toValue ) ) { recipients.Add( new RecipientData( toValue.ResolveMergeFields( mergeFields ) ) ); } } string message = GetAttributeValue( action, "Message" ); Guid messageGuid = message.AsGuid(); if ( !messageGuid.IsEmpty() ) { var attribute = AttributeCache.Read( messageGuid, rockContext ); if ( attribute != null ) { string messageAttributeValue = action.GetWorklowAttributeValue( messageGuid ); if ( !string.IsNullOrWhiteSpace( messageAttributeValue ) ) { if ( attribute.FieldType.Class == "Rock.Field.Types.TextFieldType" ) { message = messageAttributeValue; } } } } if ( recipients.Any() && !string.IsNullOrWhiteSpace( message ) ) { var mediumEntity = EntityTypeCache.Read( Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_SMS.AsGuid(), rockContext ); if ( mediumEntity != null ) { var medium = MediumContainer.GetComponent( mediumEntity.Name ); if ( medium != null && medium.IsActive ) { var transport = medium.Transport; if ( transport != null && transport.IsActive ) { var appRoot = GlobalAttributesCache.Read( rockContext ).GetValue( "InternalApplicationRoot" ); foreach ( var recipient in recipients ) { var recipientMergeFields = new Dictionary<string, object>( mergeFields ); foreach ( var mergeField in recipient.MergeFields ) { recipientMergeFields.Add( mergeField.Key, mergeField.Value ); } var mediumData = new Dictionary<string, string>(); mediumData.Add( "FromValue", fromId.Value.ToString() ); mediumData.Add( "Message", message.ResolveMergeFields( recipientMergeFields ) ); var number = new List<string> { recipient.To }; transport.Send( mediumData, number, appRoot, string.Empty ); } } } } } return true; }
/// <summary> /// Handles the Click event of the btnNext 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 btnNext_Click( object sender, EventArgs e ) { var changes = new List<string>(); var rockContext = new RockContext(); var financialTransactionService = new FinancialTransactionService( rockContext ); var financialTransactionDetailService = new FinancialTransactionDetailService( rockContext ); var financialPersonBankAccountService = new FinancialPersonBankAccountService( rockContext ); int txnId = hfTransactionId.Value.AsInteger(); var financialTransaction = financialTransactionService .Queryable( "AuthorizedPersonAlias.Person,ProcessedByPersonAlias.Person" ) .FirstOrDefault( t => t.Id == txnId ); // set the AuthorizedPersonId (the person who wrote the check, for example) to the if the SelectNew person (if selected) or person selected in the drop down (if there is somebody selected) int? authorizedPersonId = ppSelectNew.PersonId ?? ddlIndividual.SelectedValue.AsIntegerOrNull(); var accountNumberSecured = hfCheckMicrHashed.Value; if ( cbTotalAmount.Text.AsDecimalOrNull().HasValue && !authorizedPersonId.HasValue ) { nbSaveError.Text = "Transaction must be matched to a person when the amount is specified."; nbSaveError.Visible = true; return; } // if the transaction was previously matched, but user unmatched it, save it as an unmatched transaction and clear out the detail records (we don't want an unmatched transaction to have detail records) if ( financialTransaction != null && financialTransaction.AuthorizedPersonAliasId.HasValue && !authorizedPersonId.HasValue ) { financialTransaction.AuthorizedPersonAliasId = null; foreach ( var detail in financialTransaction.TransactionDetails ) { History.EvaluateChange( changes, detail.Account != null ? detail.Account.Name : "Unknown", detail.Amount.ToString( "C2" ), string.Empty ); financialTransactionDetailService.Delete( detail ); } changes.Add( "Unmatched transaction" ); HistoryService.SaveChanges( rockContext, typeof( FinancialBatch ), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), financialTransaction.BatchId.Value, changes, string.Format( "Transaction Id: {0}", financialTransaction.Id ), typeof( FinancialTransaction ), financialTransaction.Id, false ); rockContext.SaveChanges(); // if the transaction was unmatched, clear out the ProcessedBy fields since we didn't match the transaction and are moving on to process another transaction MarkTransactionAsNotProcessedByCurrentUser( hfTransactionId.Value.AsInteger() ); } // if the transaction is matched to somebody, attempt to save it. Otherwise, if the transaction was previously matched, but user unmatched it, save it as an unmatched transaction if ( financialTransaction != null && authorizedPersonId.HasValue ) { bool requiresMicr = financialTransaction.FinancialPaymentDetail != null && financialTransaction.FinancialPaymentDetail.CurrencyTypeValue != null && financialTransaction.FinancialPaymentDetail.CurrencyTypeValue.Guid == Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK.AsGuid(); if ( cbTotalAmount.Text.AsDecimalOrNull() == null ) { nbSaveError.Text = "Total amount must be allocated to accounts."; nbSaveError.Visible = true; return; } var personAlias = new PersonAliasService( rockContext ).GetPrimaryAlias( authorizedPersonId.Value ); int? personAliasId = personAlias != null ? personAlias.Id : (int?)null; // if this transaction has an accountnumber associated with it (in other words, it's a valid scanned check), ensure there is a financialPersonBankAccount record if ( financialTransaction.MICRStatus == MICRStatus.Success && !string.IsNullOrWhiteSpace( accountNumberSecured ) ) { var financialPersonBankAccount = financialPersonBankAccountService.Queryable().Where( a => a.AccountNumberSecured == accountNumberSecured && a.PersonAlias.PersonId == authorizedPersonId.Value ).FirstOrDefault(); if ( financialPersonBankAccount == null ) { if ( personAliasId.HasValue ) { financialPersonBankAccount = new FinancialPersonBankAccount(); financialPersonBankAccount.PersonAliasId = personAliasId.Value; financialPersonBankAccount.AccountNumberSecured = accountNumberSecured; var checkMicrClearText = Encryption.DecryptString( financialTransaction.CheckMicrParts ); var parts = checkMicrClearText.Split( '_' ); if ( parts.Length >= 2 ) { financialPersonBankAccount.AccountNumberMasked = parts[1].Masked(); } financialPersonBankAccountService.Add( financialPersonBankAccount ); } } } string prevPerson = ( financialTransaction.AuthorizedPersonAlias != null && financialTransaction.AuthorizedPersonAlias.Person != null ) ? financialTransaction.AuthorizedPersonAlias.Person.FullName : string.Empty; string newPerson = string.Empty; if ( personAliasId.HasValue ) { newPerson = personAlias.Person.FullName; financialTransaction.AuthorizedPersonAliasId = personAliasId; } History.EvaluateChange( changes, "Person", prevPerson, newPerson ); // just in case this transaction is getting re-edited either by the same user, or somebody else, clean out any existing TransactionDetail records foreach ( var detail in financialTransaction.TransactionDetails.ToList() ) { financialTransactionDetailService.Delete( detail ); History.EvaluateChange( changes, detail.Account != null ? detail.Account.Name : "Unknown", detail.Amount.ToString( "C2" ), string.Empty ); } foreach ( var accountBox in rptAccounts.ControlsOfTypeRecursive<CurrencyBox>() ) { var amount = accountBox.Text.AsDecimalOrNull(); if ( amount.HasValue && amount.Value >= 0 ) { var financialTransactionDetail = new FinancialTransactionDetail(); financialTransactionDetail.TransactionId = financialTransaction.Id; financialTransactionDetail.AccountId = accountBox.Attributes["data-account-id"].AsInteger(); financialTransactionDetail.Amount = amount.Value; financialTransactionDetailService.Add( financialTransactionDetail ); History.EvaluateChange( changes, accountBox.Label, 0.0M.ToString( "C2" ), amount.Value.ToString( "C2" ) ); } } financialTransaction.ProcessedByPersonAliasId = this.CurrentPersonAlias.Id; financialTransaction.ProcessedDateTime = RockDateTime.Now; changes.Add( "Matched transaction" ); HistoryService.SaveChanges( rockContext, typeof( FinancialBatch ), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), financialTransaction.BatchId.Value, changes, personAlias != null && personAlias.Person != null ? personAlias.Person.FullName : string.Format( "Transaction Id: {0}", financialTransaction.Id ), typeof( FinancialTransaction ), financialTransaction.Id, false ); rockContext.SaveChanges(); } else { // if the transaction was not matched, clear out the ProcessedBy fields since we didn't match the transaction and are moving on to process another transaction MarkTransactionAsNotProcessedByCurrentUser( hfTransactionId.Value.AsInteger() ); } NavigateToTransaction( Direction.Next ); }
/// <summary> /// Handles the Click event of the btnCreateCommunication 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 btnCreateCommunication_Click(object sender, EventArgs e) { // Create communication var rockContext = new RockContext(); var communicationService = new Rock.Model.CommunicationService(rockContext); var communication = new Rock.Model.Communication(); communication.IsBulkCommunication = false; communication.Status = CommunicationStatus.Transient; communication.SenderPersonAliasId = this.CurrentPersonAliasId; if (this.Request != null && this.Request.Url != null) { communication.UrlReferrer = this.Request.UrlProxySafe().AbsoluteUri.TrimForMaxLength(communication, "UrlReferrer"); } communicationService.Add(communication); // save communication to get Id rockContext.SaveChanges(); int[] scheduleIds = lbSchedules.SelectedValuesAsInt.ToArray(); int[] locationIds = cblLocations.SelectedValuesAsInt.ToArray(); List <int> parentGroupIds = gpGroups.SelectedValuesAsInt().ToList(); var allGroupIds = new List <int>(); allGroupIds.AddRange(parentGroupIds); if (cbIncludeChildGroups.Checked) { var groupService = new GroupService(rockContext); foreach (var groupId in parentGroupIds) { // just the first level of child groups, not all decendants var childGroupIds = groupService.Queryable() .Where(a => a.ParentGroupId == groupId && a.GroupType.IsSchedulingEnabled && !a.DisableScheduling) .Select(a => a.Id).ToList(); allGroupIds.AddRange(childGroupIds); } } allGroupIds = allGroupIds.Distinct().ToList(); var attendanceOccurrenceService = new AttendanceOccurrenceService(rockContext); var sundayDate = ddlWeek.SelectedValue.AsDateTime() ?? RockDateTime.Now.SundayDate(); var attendanceOccurrenceQuery = attendanceOccurrenceService .Queryable() .Where(a => a.ScheduleId.HasValue && a.LocationId.HasValue && a.GroupId.HasValue) .WhereDeducedIsActive() .Where(a => allGroupIds.Contains(a.GroupId.Value)) .Where(a => locationIds.Contains(a.LocationId.Value)) .Where(a => scheduleIds.Contains(a.ScheduleId.Value)) .Where(a => a.SundayDate == sundayDate); ScheduledAttendanceItemStatus[] selectedInviteStatus = cblInviteStatus.SelectedValues .Select(a => a.ConvertToEnum <ScheduledAttendanceItemStatus>()) .ToArray(); // limit attendees to ones based on the selected invite status var scheduledAttendancesForOccurrenceQuery = attendanceOccurrenceQuery .SelectMany(a => a.Attendees) .WhereHasScheduledAttendanceItemStatus(selectedInviteStatus); var personIds = scheduledAttendancesForOccurrenceQuery.Select(a => a.PersonAlias.PersonId).Distinct().ToList(); if (!personIds.Any()) { nbCommunicationWarning.Text = "No people found to send communication to."; nbCommunicationWarning.Visible = true; return; } nbCommunicationWarning.Visible = false; var personAliasService = new Rock.Model.PersonAliasService(new Rock.Data.RockContext()); // Get the primary aliases List <Rock.Model.PersonAlias> primaryAliasList = new List <PersonAlias>(personIds.Count); // get the data in chunks just in case we have a large list of PersonIds (to avoid a SQL Expression limit error) var chunkedPersonIds = personIds.Take(1000); int skipCount = 0; while (chunkedPersonIds.Any()) { var chunkedPrimaryAliasList = personAliasService.Queryable() .Where(p => p.PersonId == p.AliasPersonId && chunkedPersonIds.Contains(p.PersonId)).AsNoTracking().ToList(); primaryAliasList.AddRange(chunkedPrimaryAliasList); skipCount += 1000; chunkedPersonIds = personIds.Skip(skipCount).Take(1000); } // NOTE: Set CreatedDateTime, ModifiedDateTime, etc manually set we are using BulkInsert var currentDateTime = RockDateTime.Now; var currentPersonAliasId = this.CurrentPersonAliasId; var communicationRecipientList = primaryAliasList.Select(a => new Rock.Model.CommunicationRecipient { CommunicationId = communication.Id, PersonAliasId = a.Id, CreatedByPersonAliasId = currentPersonAliasId, ModifiedByPersonAliasId = currentPersonAliasId, CreatedDateTime = currentDateTime, ModifiedDateTime = currentDateTime }).ToList(); // BulkInsert to quickly insert the CommunicationRecipient records. Note: This is much faster, but will bypass EF and Rock processing. var communicationRecipientRockContext = new RockContext(); communicationRecipientRockContext.BulkInsert(communicationRecipientList); var pageRef = this.RockPage.Site.CommunicationPageReference; string communicationUrl; if (pageRef.PageId > 0) { pageRef.Parameters.AddOrReplace("CommunicationId", communication.Id.ToString()); communicationUrl = pageRef.BuildUrl(); } else { communicationUrl = "~/Communication/{0}"; } if (communicationUrl.Contains("{0}")) { communicationUrl = string.Format(communicationUrl, communication.Id); } UserPreferenceConfiguration userPreferenceConfiguration = this.GetBlockUserPreference(UserPreferenceKey.UserPreferenceConfigurationJSON).FromJsonOrNull <UserPreferenceConfiguration>() ?? new UserPreferenceConfiguration(); userPreferenceConfiguration.GroupIds = gpGroups.SelectedValuesAsInt().ToArray(); userPreferenceConfiguration.IncludeChildGroups = cbIncludeChildGroups.Checked; userPreferenceConfiguration.InviteStatuses = cblInviteStatus.SelectedValues.ToArray(); userPreferenceConfiguration.ScheduleIds = lbSchedules.SelectedValuesAsInt.ToArray(); userPreferenceConfiguration.LocationIds = cblLocations.SelectedValuesAsInt.ToArray(); this.SetBlockUserPreference(UserPreferenceKey.UserPreferenceConfigurationJSON, userPreferenceConfiguration.ToJson()); Page.Response.Redirect(communicationUrl, false); Context.ApplicationInstance.CompleteRequest(); }
/// <summary> /// Sets the value (as PersonAlias.Guid) /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="value">The value.</param> public override void SetEditValue( System.Web.UI.Control control, Dictionary<string, ConfigurationValue> configurationValues, string value ) { if ( value != null ) { PersonPicker ppPerson = control as PersonPicker; if ( ppPerson != null ) { Guid guid = Guid.Empty; Guid.TryParse( value, out guid ); var person = new PersonAliasService( new RockContext() ).Queryable() .Where( a => a.Guid.Equals(guid)) .Select( a => a.Person) .FirstOrDefault(); ppPerson.SetValue( person ); } } }
/// <summary> /// Gets the edit value as the IEntity.Id /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <returns></returns> public int? GetEditValueAsEntityId( Control control, Dictionary<string, ConfigurationValue> configurationValues ) { Guid guid = GetEditValue( control, configurationValues ).AsGuid(); var item = new PersonAliasService( new RockContext() ).Get( guid ); return item != null ? item.PersonId : (int?)null; }
/// <summary> /// Reads new values entered by the user for the field (as PersonAlias.Guid) /// </summary> /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param> /// <param name="configurationValues">The configuration values.</param> /// <returns></returns> public override string GetEditValue( System.Web.UI.Control control, Dictionary<string, ConfigurationValue> configurationValues ) { PersonPicker ppPerson = control as PersonPicker; string result = null; if ( ppPerson != null ) { Guid personGuid = Guid.Empty; int? personId = ppPerson.PersonId; if ( personId.HasValue ) { var personAlias = new PersonAliasService( new RockContext() ).GetByAliasId( personId.Value ); if ( personAlias != null ) { result = personAlias.Guid.ToString(); } } } return result; }
/// <summary> /// Gets the communications and response recipients. /// </summary> /// <param name="relatedSmsFromDefinedValueId">The related SMS from defined value identifier.</param> /// <param name="startDateTime">The start date time.</param> /// <param name="showReadMessages">if set to <c>true</c> [show read messages].</param> /// <param name="maxCount">The maximum count.</param> /// <returns></returns> public List <CommunicationRecipientResponse> GetCommunicationResponseRecipients(int relatedSmsFromDefinedValueId, DateTime startDateTime, bool showReadMessages, int maxCount) { var smsMediumEntityTypeId = EntityTypeCache.GetId(SystemGuid.EntityType.COMMUNICATION_MEDIUM_SMS).Value; IQueryable <CommunicationResponse> communicationResponseQuery = this.Queryable() .Where(r => r.RelatedMediumEntityTypeId == smsMediumEntityTypeId && r.RelatedSmsFromDefinedValueId == relatedSmsFromDefinedValueId && r.CreatedDateTime >= startDateTime && r.FromPersonAliasId.HasValue); if (!showReadMessages) { communicationResponseQuery = communicationResponseQuery.Where(r => r.IsRead == false); } var personAliasQuery = new PersonAliasService(this.Context as RockContext).Queryable(); // do an explicit LINQ inner join on PersonAlias to avoid performance issue where it would do an outer join instead var communicationResponseJoinQuery = from cr in communicationResponseQuery join pa in personAliasQuery on cr.FromPersonAliasId equals pa.Id select new { cr, pa }; IQueryable <CommunicationResponse> mostRecentCommunicationResponseQuery = communicationResponseJoinQuery .GroupBy(r => r.pa.PersonId) .Select(a => a.OrderByDescending(x => x.cr.CreatedDateTime).FirstOrDefault()) .OrderByDescending(a => a.cr.CreatedDateTime).Select(a => a.cr); IQueryable <CommunicationRecipient> communicationRecipientQuery = new CommunicationRecipientService(this.Context as RockContext).Queryable() .Where(r => r.MediumEntityTypeId == smsMediumEntityTypeId && r.Communication.SMSFromDefinedValueId == relatedSmsFromDefinedValueId && r.CreatedDateTime >= startDateTime && r.Status == CommunicationRecipientStatus.Delivered); IQueryable <CommunicationRecipient> mostRecentCommunicationRecipientQuery = communicationRecipientQuery .GroupBy(r => r.PersonAlias.PersonId) .Select(a => a.OrderByDescending(x => x.CreatedDateTime).FirstOrDefault()) .OrderByDescending(a => a.CreatedDateTime); var mostRecentCommunicationResponseList = mostRecentCommunicationResponseQuery.Include(a => a.FromPersonAlias.Person).AsNoTracking().Take(maxCount).ToList(); List <CommunicationRecipientResponse> communicationRecipientResponseList = new List <CommunicationRecipientResponse>(); foreach (var mostRecentCommunicationResponse in mostRecentCommunicationResponseList) { var communicationRecipientResponse = new CommunicationRecipientResponse { CreatedDateTime = mostRecentCommunicationResponse.CreatedDateTime, PersonId = mostRecentCommunicationResponse?.FromPersonAlias.PersonId, RecordTypeValueId = mostRecentCommunicationResponse?.FromPersonAlias.Person.RecordTypeValueId, FullName = mostRecentCommunicationResponse?.FromPersonAlias.Person.FullName, IsRead = mostRecentCommunicationResponse.IsRead, MessageKey = mostRecentCommunicationResponse.MessageKey, IsOutbound = false, RecipientPersonAliasId = mostRecentCommunicationResponse.FromPersonAliasId, SMSMessage = mostRecentCommunicationResponse.Response }; communicationRecipientResponseList.Add(communicationRecipientResponse); } var mostRecentCommunicationRecipientList = mostRecentCommunicationRecipientQuery.Take(maxCount).Select(a => new { a.CreatedDateTime, a.PersonAlias.Person, a.PersonAliasId, a.Communication.SMSMessage, a.SentMessage }).ToList(); foreach (var mostRecentCommunicationRecipient in mostRecentCommunicationRecipientList) { var communicationRecipientResponse = new CommunicationRecipientResponse { CreatedDateTime = mostRecentCommunicationRecipient.CreatedDateTime, PersonId = mostRecentCommunicationRecipient?.Person.Id, RecordTypeValueId = mostRecentCommunicationRecipient?.Person.RecordTypeValueId, FullName = mostRecentCommunicationRecipient?.Person.FullName, IsOutbound = true, IsRead = true, MessageKey = null, // communication recipients just need to show their name, not their number RecipientPersonAliasId = mostRecentCommunicationRecipient.PersonAliasId, SMSMessage = mostRecentCommunicationRecipient.SentMessage.IsNullOrWhiteSpace() ? mostRecentCommunicationRecipient.SMSMessage : mostRecentCommunicationRecipient.SentMessage }; if (mostRecentCommunicationRecipient?.Person.IsNameless() == true) { // if the person is nameless, we'll need to know their number since we don't know their name communicationRecipientResponse.MessageKey = mostRecentCommunicationRecipient.Person.PhoneNumbers.FirstOrDefault()?.Number; } else { // If the Person is not nameless, we just need to show their name, not their number communicationRecipientResponse.MessageKey = null; } communicationRecipientResponseList.Add(communicationRecipientResponse); } // NOTE: We actually have up to twice the max count at this point, because we are combining results from // CommunicationRecipient and CommunicationResponse, and we took the maxCount of each of those. // Now, we see what that combination ends up looking like when we sort it by CreatedDateTime communicationRecipientResponseList = communicationRecipientResponseList .GroupBy(r => r.PersonId) .Select(a => a.OrderByDescending(x => x.CreatedDateTime).FirstOrDefault()) .OrderByDescending(a => a.CreatedDateTime).Take(maxCount).ToList(); return(communicationRecipientResponseList); }
private int? AddRegistrantToGroup( RegistrationRegistrant registrant ) { if ( registrant.PersonAliasId.HasValue && registrant.Registration != null && registrant.Registration.Group != null && registrant.Registration.Group.GroupType != null && _template != null ) { var group = registrant.Registration.Group; var groupService = new GroupService( _rockContext ); var personAliasService = new PersonAliasService( _rockContext ); var groupMemberService = new GroupMemberService( _rockContext ); var personAlias = personAliasService.Get( registrant.PersonAliasId.Value ); GroupMember groupMember = group.Members.Where( m => m.PersonId == personAlias.PersonId ).FirstOrDefault(); if ( groupMember == null ) { groupMember = new GroupMember(); groupMemberService.Add( groupMember ); groupMember.GroupId = group.Id; groupMember.PersonId = personAlias.PersonId; if ( _template.GroupTypeId.HasValue && _template.GroupTypeId == group.GroupTypeId && _template.GroupMemberRoleId.HasValue ) { groupMember.GroupRoleId = _template.GroupMemberRoleId.Value; groupMember.GroupMemberStatus = _template.GroupMemberStatus; } else { if ( group.GroupType.DefaultGroupRoleId.HasValue ) { groupMember.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value; } else { groupMember.GroupRoleId = group.GroupType.Roles.Select( r => r.Id ).FirstOrDefault(); } } } groupMember.GroupMemberStatus = GroupMemberStatus.Active; _rockContext.SaveChanges(); return groupMember.Id; } return (int?)null; }
/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbSave_Click( object sender, EventArgs e ) { if ( _group != null && _occurrence != null ) { var rockContext = new RockContext(); var attendanceService = new AttendanceService( rockContext ); var personAliasService = new PersonAliasService( rockContext ); var locationService = new LocationService( rockContext ); bool dateAdjusted = false; DateTime startDate = _occurrence.Date; // If this is a manuall entered occurrence, check to see if date was changed if ( !_occurrence.ScheduleId.HasValue ) { DateTime? originalDate = PageParameter( "Date" ).AsDateTime(); if ( originalDate.HasValue && originalDate.Value.Date != startDate.Date ) { startDate = originalDate.Value.Date; dateAdjusted = true; } } DateTime endDate = startDate.AddDays( 1 ); var existingAttendees = attendanceService .Queryable( "PersonAlias" ) .Where( a => a.GroupId == _group.Id && a.LocationId == _occurrence.LocationId && a.ScheduleId == _occurrence.ScheduleId && a.StartDateTime >= startDate && a.StartDateTime < endDate ); if ( dateAdjusted ) { foreach ( var attendee in existingAttendees ) { attendee.StartDateTime = _occurrence.Date; } } // If did not meet was selected and this was a manually entered occurrence (not based on a schedule/location) // then just delete all the attendance records instead of tracking a 'did not meet' value if ( cbDidNotMeet.Checked && !_occurrence.ScheduleId.HasValue ) { foreach ( var attendance in existingAttendees ) { attendanceService.Delete( attendance ); } } else { int? campusId = locationService.GetCampusIdForLocation( _occurrence.LocationId ); if ( !campusId.HasValue ) { campusId = _group.CampusId; } if ( !campusId.HasValue && _allowCampusFilter ) { var campus = CampusCache.Read( bddlCampus.SelectedValueAsInt() ?? 0 ); if ( campus != null ) { campusId = campus.Id; } } if ( cbDidNotMeet.Checked ) { // If the occurrence is based on a schedule, set the did not meet flags foreach ( var attendance in existingAttendees ) { attendance.DidAttend = null; attendance.DidNotOccur = true; } } foreach ( var attendee in _attendees ) { var attendance = existingAttendees .Where( a => a.PersonAlias.PersonId == attendee.PersonId ) .FirstOrDefault(); if ( attendance == null ) { int? personAliasId = personAliasService.GetPrimaryAliasId( attendee.PersonId ); if ( personAliasId.HasValue ) { attendance = new Attendance(); attendance.GroupId = _group.Id; attendance.ScheduleId = _group.ScheduleId; attendance.PersonAliasId = personAliasId; attendance.StartDateTime = _occurrence.Date.Date.Add( _occurrence.StartTime ); attendance.LocationId = _occurrence.LocationId; attendance.CampusId = campusId; attendance.ScheduleId = _occurrence.ScheduleId; // check that the attendance record is valid cvAttendance.IsValid = attendance.IsValid; if ( !cvAttendance.IsValid ) { cvAttendance.ErrorMessage = attendance.ValidationResults.Select( a => a.ErrorMessage ).ToList().AsDelimited( "<br />" ); return; } attendanceService.Add( attendance ); } } if ( attendance != null ) { if ( cbDidNotMeet.Checked ) { attendance.DidAttend = null; attendance.DidNotOccur = true; } else { attendance.DidAttend = attendee.Attended; attendance.DidNotOccur = null; } } } } if ( _occurrence.LocationId.HasValue ) { Rock.CheckIn.KioskLocationAttendance.Flush( _occurrence.LocationId.Value ); } rockContext.SaveChanges(); WorkflowType workflowType = null; Guid? workflowTypeGuid = GetAttributeValue( "Workflow" ).AsGuidOrNull(); if ( workflowTypeGuid.HasValue ) { var workflowTypeService = new WorkflowTypeService( rockContext ); workflowType = workflowTypeService.Get( workflowTypeGuid.Value ); if ( workflowType != null ) { try { var workflow = Workflow.Activate( workflowType, _group.Name ); workflow.SetAttributeValue( "StartDateTime", _occurrence.Date.ToString( "o" ) ); workflow.SetAttributeValue( "Schedule", _group.Schedule.Guid.ToString() ); List<string> workflowErrors; new WorkflowService( rockContext ).Process( workflow, _group, out workflowErrors ); } catch ( Exception ex ) { ExceptionLogService.LogException( ex, this.Context ); } } } var qryParams = new Dictionary<string, string> { { "GroupId", _group.Id.ToString() } }; var groupTypeIds = PageParameter( "GroupTypeIds" ); if ( !string.IsNullOrWhiteSpace( groupTypeIds ) ) { qryParams.Add( "GroupTypeIds", groupTypeIds ); } NavigateToParentPage( qryParams ); } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); var tagService = new Rock.Model.TagService( rockContext ); Tag tag = null; int tagId = int.Parse( hfId.Value ); if ( tagId != 0 ) { tag = tagService.Get( tagId ); } if ( tag == null ) { tag = new Tag(); tag.IsSystem = false; tagService.Add( tag ); } string name = tbName.Text; int? ownerId = ppOwner.PersonId; int entityTypeId = ddlEntityType.SelectedValueAsId().Value; string qualifierCol = tbEntityTypeQualifierColumn.Text; string qualifierVal = tbEntityTypeQualifierValue.Text; // Verify tag with same name does not already exist if (tagService.Queryable() .Where( t => t.Id != tagId && t.Name == name && ( ( t.OwnerPersonAlias == null && !ownerId.HasValue ) || ( t.OwnerPersonAlias != null && ownerId.HasValue && t.OwnerPersonAlias.PersonId == ownerId.Value ) ) && t.EntityTypeId == entityTypeId && t.EntityTypeQualifierColumn == qualifierCol && t.EntityTypeQualifierValue == qualifierVal ) .Any()) { nbEditError.Heading = "Tag Already Exists"; nbEditError.Text = string.Format("A '{0}' tag already exists for the selected scope, owner, and entity type.", name); nbEditError.Visible = true; } else { int? ownerPersonAliasId = null; if (ownerId.HasValue) { ownerPersonAliasId = new PersonAliasService( rockContext ).GetPrimaryAliasId( ownerId.Value ); } tag.Name = name; tag.Description = tbDescription.Text; tag.OwnerPersonAliasId = ownerPersonAliasId; tag.EntityTypeId = entityTypeId; tag.EntityTypeQualifierColumn = qualifierCol; tag.EntityTypeQualifierValue = qualifierVal; rockContext.SaveChanges(); var qryParams = new Dictionary<string, string>(); qryParams["tagId"] = tag.Id.ToString(); NavigateToPage( RockPage.Guid, qryParams ); } }
private void ShowDetail(Guid personGuid) { using ( var rockContext = new RockContext() ) { var personService = new PersonService( new RockContext() ); var person = personService.Get( personGuid ); if ( person != null ) { lName.Text = person.FullName; string photoTag = Rock.Model.Person.GetPhotoImageTag( person, 120, 120 ); if ( person.PhotoId.HasValue ) { lPhoto.Text = string.Format( "<a href='{0}'>{1}</a>", person.PhotoUrl, photoTag ); } else { lPhoto.Text = photoTag; } lEmail.Visible = !string.IsNullOrWhiteSpace( person.Email ); lEmail.Text = person.GetEmailTag( ResolveRockUrl( "/" ), "btn btn-default", "<i class='fa fa-envelope'></i>" ); var childGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid(); var isFamilyChild = new Dictionary<int, bool>(); var allFamilyMembers = person.GetFamilyMembers( true ).ToList(); allFamilyMembers.Where( m => m.PersonId == person.Id ).ToList().ForEach( m => isFamilyChild.Add( m.GroupId, m.GroupRole.Guid.Equals( childGuid ) ) ); string urlRoot = Request.Url.ToString().ReplaceCaseInsensitive( personGuid.ToString(), "" ); var familyMembers = allFamilyMembers.Where( m => m.PersonId != person.Id ) .OrderBy( m => m.GroupId ) .ThenBy( m => m.Person.BirthDate ) .Select( m => new { Url = urlRoot + m.Person.Guid.ToString(), FullName = m.Person.FullName, Gender = m.Person.Gender, FamilyRole = m.GroupRole, Note = isFamilyChild[m.GroupId] ? ( m.GroupRole.Guid.Equals( childGuid ) ? " (Sibling)" : "(Parent)" ) : ( m.GroupRole.Guid.Equals( childGuid ) ? " (Child)" : "" ) } ) .ToList(); rcwFamily.Visible = familyMembers.Any(); rptrFamily.DataSource = familyMembers; rptrFamily.DataBind(); rptrPhones.DataSource = person.PhoneNumbers.Where( p => !p.IsUnlisted ).ToList(); rptrPhones.DataBind(); var schedules = new ScheduleService( rockContext ).Queryable() .Where( s => s.CheckInStartOffsetMinutes.HasValue ) .ToList(); var scheduleIds = schedules.Select( s => s.Id ).ToList(); var activeScheduleIds = new List<int>(); foreach ( var schedule in schedules ) { if ( schedule.IsScheduleOrCheckInActive ) { activeScheduleIds.Add( schedule.Id ); } } int? personAliasId = person.PrimaryAliasId; if ( !personAliasId.HasValue ) { personAliasId = new PersonAliasService( rockContext ).GetPrimaryAliasId( person.Id ); } var attendances = new AttendanceService( rockContext ) .Queryable( "Schedule,Group,Location" ) .Where( a => a.PersonAliasId.HasValue && a.PersonAliasId == personAliasId && a.ScheduleId.HasValue && a.GroupId.HasValue && a.LocationId.HasValue && a.DidAttend.HasValue && a.DidAttend.Value && scheduleIds.Contains( a.ScheduleId.Value ) ) .OrderByDescending( a => a.StartDateTime ) .Take( 20 ) .Select( a => new AttendanceInfo { Date = a.StartDateTime, GroupId = a.Group.Id, Group = a.Group.Name, LocationId = a.LocationId.Value, Location = a.Location.Name, Schedule = a.Schedule.Name, IsActive = a.StartDateTime > DateTime.Today && activeScheduleIds.Contains( a.ScheduleId.Value ) } ).ToList(); // Set active locations to be a link to the room in manager page var qryParam = new Dictionary<string, string>(); qryParam.Add( "Group", "" ); qryParam.Add( "Location", "" ); foreach ( var attendance in attendances.Where( a => a.IsActive ) ) { qryParam["Group"] = attendance.GroupId.ToString(); qryParam["Location"] = attendance.LocationId.ToString(); attendance.Location = string.Format( "<a href='{0}'>{1}</a>", LinkedPageUrl( "ManagerPage", qryParam ), attendance.Location ); } rcwCheckinHistory.Visible = attendances.Any(); gHistory.DataSource = attendances; gHistory.DataBind(); } } }
/// <summary> /// Gets the giving automation source transaction query by giving identifier. /// </summary> /// <param name="givingId">The giving identifier.</param> /// <returns>IQueryable<FinancialTransaction>.</returns> public IQueryable <FinancialTransaction> GetGivingAutomationSourceTransactionQueryByGivingId(string givingId) { var givingIdPersonAliasIdQuery = new PersonAliasService(this.Context as RockContext).Queryable().Where(a => a.Person.GivingId == givingId).Select(a => a.Id); return(GetGivingAutomationSourceTransactionQuery().Where(a => a.AuthorizedPersonAliasId.HasValue && givingIdPersonAliasIdQuery.Contains(a.AuthorizedPersonAliasId.Value))); }
/// <summary> /// This method is called in the /// <see cref="M:Rock.Data.Model`1.PreSaveChanges(Rock.Data.DbContext,System.Data.Entity.Infrastructure.DbEntityEntry,System.Data.Entity.EntityState)" /> /// method. Use it to populate <see cref="P:Rock.Data.Model`1.HistoryItems" /> if needed. /// These history items are queued to be written into the database post save (so that they /// are only written if the save actually occurs). /// </summary> /// <param name="dbContext">The database context.</param> /// <param name="entry">The entry.</param> /// <param name="state">The state.</param> protected override void BuildHistoryItems(Data.DbContext dbContext, DbEntityEntry entry, EntityState state) { // Sometimes, especially if the model is being deleted, some properties might not be // populated, but we can query to try to get their original value. We need to use a new // rock context to get the actual value from the DB var rockContext = new RockContext(); var service = new FinancialPersonSavedAccountService(rockContext); var originalModel = service.Queryable("PersonAlias, FinancialPaymentDetail") .FirstOrDefault(fpsa => fpsa.Id == Id); // Use the original value for the person alias or the new value if that is not set var personId = (originalModel?.PersonAlias ?? PersonAlias)?.PersonId; if (!personId.HasValue) { // If this model is new, it won't have any virtual properties hydrated or an original // record in the database if (PersonAliasId.HasValue) { var personAliasService = new PersonAliasService(rockContext); var personAlias = personAliasService.Get(PersonAliasId.Value); personId = personAlias?.PersonId; } // We can't log history if we don't know who the saved account belongs to if (!personId.HasValue) { return; } } History.HistoryVerb verb; switch (state) { case EntityState.Added: verb = History.HistoryVerb.Add; break; case EntityState.Deleted: verb = History.HistoryVerb.Delete; break; default: // As of now, there is no requirement to log other events return; } var historyChangeList = new History.HistoryChangeList(); historyChangeList.AddChange(verb, History.HistoryChangeType.Record, "Financial Person Saved Account"); HistoryItems = HistoryService.GetChanges( typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON.AsGuid(), personId.Value, historyChangeList, GetNameForHistory(originalModel?.FinancialPaymentDetail ?? FinancialPaymentDetail), typeof(FinancialPersonSavedAccount), Id, dbContext.GetCurrentPersonAlias()?.Id, dbContext.SourceOfChange); }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); string updateValue = GetAttributeValue( action, "Value" ); Guid? valueGuid = updateValue.AsGuidOrNull(); if ( valueGuid.HasValue ) { updateValue = action.GetWorklowAttributeValue( valueGuid.Value ); } else { updateValue = updateValue.ResolveMergeFields( GetMergeFields( action ) ); } string personAttribute = GetAttributeValue( action, "PersonAttribute" ); Guid guid = personAttribute.AsGuid(); if (!guid.IsEmpty()) { var attribute = AttributeCache.Read( guid, rockContext ); if ( attribute != null ) { string value = GetAttributeValue( action, "Person" ); guid = value.AsGuid(); if ( !guid.IsEmpty() ) { var attributePerson = AttributeCache.Read( guid, rockContext ); if ( attributePerson != null ) { string attributePersonValue = action.GetWorklowAttributeValue( guid ); if ( !string.IsNullOrWhiteSpace( attributePersonValue ) ) { if ( attributePerson.FieldType.Class == "Rock.Field.Types.PersonFieldType" ) { Guid personAliasGuid = attributePersonValue.AsGuid(); if ( !personAliasGuid.IsEmpty() ) { var person = new PersonAliasService( rockContext ).Queryable() .Where( a => a.Guid.Equals( personAliasGuid ) ) .Select( a => a.Person ) .FirstOrDefault(); if ( person != null ) { // update person attribute Rock.Attribute.Helper.SaveAttributeValue( person, attribute, updateValue, rockContext ); action.AddLogEntry( string.Format( "Set '{0}' attribute to '{1}'.", attribute.Name, person.FullName ) ); return true; } else { errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", guid.ToString() ) ); } } } else { errorMessages.Add( "The attribute used to provide the person was not of type 'Person'." ); } } } } } else { errorMessages.Add( string.Format( "Person attribute could not be found for '{0}'!", guid.ToString() ) ); } } else { errorMessages.Add( string.Format( "Selected person attribute ('{0}') was not a valid Guid!", personAttribute ) ); } errorMessages.ForEach( m => action.AddLogEntry( m, true ) ); return true; }
private void ShowReadonlyDetails() { hfMode.Value = "View"; if ( Workflow != null ) { if ( Workflow.IsAuthorized( Authorization.VIEW, CurrentPerson ) ) { tdName.Description = Workflow.Name; tdStatus.Description = Workflow.Status; if ( Workflow.InitiatorPersonAlias != null && Workflow.InitiatorPersonAlias.Person != null ) { var person = Workflow.InitiatorPersonAlias.Person; tdInitiator.Description = string.Format( "<a href='{0}{1}'>{2}</a>", ResolveRockUrl("~/Person/"), person.Id, person.FullName ); } else { tdInitiator.Description = string.Empty; } if ( Workflow.ActivatedDateTime.HasValue ) { tdActivatedWhen.Description = string.Format( "{0} {1} ({2})", Workflow.ActivatedDateTime.Value.ToShortDateString(), Workflow.ActivatedDateTime.Value.ToShortTimeString(), Workflow.ActivatedDateTime.Value.ToRelativeDateString() ); } if ( Workflow.LastProcessedDateTime.HasValue ) { tdLastProcessed.Description = string.Format( "{0} {1} ({2})", Workflow.LastProcessedDateTime.Value.ToShortDateString(), Workflow.LastProcessedDateTime.Value.ToShortTimeString(), Workflow.LastProcessedDateTime.Value.ToRelativeDateString() ); } if ( Workflow.CompletedDateTime.HasValue ) { tdCompletedWhen.Description = string.Format( "{0} {1} ({2})", Workflow.CompletedDateTime.Value.ToShortDateString(), Workflow.CompletedDateTime.Value.ToShortTimeString(), Workflow.CompletedDateTime.Value.ToRelativeDateString() ); } ShowAttributeValues(); var rockContext = new RockContext(); _personAliasService = new PersonAliasService( rockContext ); _groupService = new GroupService( rockContext ); rptrActivities.DataSource = Workflow.Activities.OrderBy( a => a.ActivatedDateTime ).ToList(); rptrActivities.DataBind(); BindLog(); } else { nbNotAuthorized.Visible = true; pnlContent.Visible = false; } } HideSecondaryBlocks( false ); }
/// <summary> /// Handles the Click event of the btnAddConnectionRequestActivity 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 btnAddConnectionRequestActivity_Click( object sender, EventArgs e ) { using ( var rockContext = new RockContext() ) { var connectionRequestService = new ConnectionRequestService( rockContext ); var connectionRequestActivityService = new ConnectionRequestActivityService( rockContext ); var personAliasService = new PersonAliasService( rockContext ); var connectionRequest = connectionRequestService.Get( hfConnectionRequestId.ValueAsInt() ); if ( connectionRequest != null ) { int? activityTypeId = ddlActivity.SelectedValueAsId(); int? personAliasId = personAliasService.GetPrimaryAliasId( ddlActivityConnector.SelectedValueAsId() ?? 0 ); if ( activityTypeId.HasValue && personAliasId.HasValue ) { ConnectionRequestActivity connectionRequestActivity = null; Guid? guid = hfAddConnectionRequestActivityGuid.Value.AsGuidOrNull(); if ( guid.HasValue ) { connectionRequestActivity = connectionRequestActivityService.Get( guid.Value ); } if ( connectionRequestActivity == null ) { connectionRequestActivity = new ConnectionRequestActivity(); connectionRequestActivity.ConnectionRequestId = connectionRequest.Id; connectionRequestActivity.ConnectionOpportunityId = connectionRequest.ConnectionOpportunityId; connectionRequestActivityService.Add( connectionRequestActivity ); } connectionRequestActivity.ConnectionActivityTypeId = activityTypeId.Value; connectionRequestActivity.ConnectorPersonAliasId = personAliasId.Value; connectionRequestActivity.Note = tbNote.Text; rockContext.SaveChanges(); BindConnectionRequestActivitiesGrid( connectionRequest, rockContext ); HideDialog(); } } } }
/// <summary> /// Saves the person notes and history. /// </summary> /// <param name="registrationPersonFirstName">First name of the registration person.</param> /// <param name="registrationPersonLastName">Last name of the registration person.</param> /// <param name="currentPersonAliasId">The current person alias identifier.</param> /// <param name="previousRegistrantPersonIds">The previous registrant person ids.</param> public void SavePersonNotesAndHistory(string registrationPersonFirstName, string registrationPersonLastName, int?currentPersonAliasId, List <int> previousRegistrantPersonIds) { // Setup Note settings Registration registration = this; NoteTypeCache noteType = null; using (RockContext rockContext = new RockContext()) { RegistrationInstance registrationInstance = registration.RegistrationInstance ?? new RegistrationInstanceService(rockContext).Get(registration.RegistrationInstanceId); RegistrationTemplate registrationTemplate = registrationInstance.RegistrationTemplate ?? new RegistrationTemplateService(rockContext).Get(registrationInstance.RegistrationTemplateId); if (registrationTemplate != null && registrationTemplate.AddPersonNote) { noteType = NoteTypeCache.Get(Rock.SystemGuid.NoteType.PERSON_EVENT_REGISTRATION.AsGuid()); if (noteType != null) { var noteService = new NoteService(rockContext); var personAliasService = new PersonAliasService(rockContext); Person registrar = null; if (registration.PersonAliasId.HasValue) { registrar = personAliasService.GetPerson(registration.PersonAliasId.Value); } var registrantNames = new List <string>(); // Get each registrant foreach (var registrantPersonAliasId in registration.Registrants .Where(r => r.PersonAliasId.HasValue) .Select(r => r.PersonAliasId.Value) .ToList()) { var registrantPerson = personAliasService.GetPerson(registrantPersonAliasId); if (registrantPerson != null && (previousRegistrantPersonIds == null || !previousRegistrantPersonIds.Contains(registrantPerson.Id))) { var noteText = new StringBuilder(); noteText.AppendFormat("Registered for {0}", registrationInstance.Name); string registrarFullName = string.Empty; if (registrar != null && registrar.Id != registrantPerson.Id) { registrarFullName = string.Format(" by {0}", registrar.FullName); registrantNames.Add(registrantPerson.FullName); } if (registrar != null && (registrationPersonFirstName != registrar.NickName || registrationPersonLastName != registrar.LastName)) { registrarFullName = string.Format(" by {0}", registrationPersonFirstName + " " + registrationPersonLastName); } noteText.Append(registrarFullName); if (noteText.Length > 0) { var note = new Note(); note.NoteTypeId = noteType.Id; note.IsSystem = false; note.IsAlert = false; note.IsPrivateNote = false; note.EntityId = registrantPerson.Id; note.Caption = string.Empty; note.Text = noteText.ToString(); if (registrar == null) { note.CreatedByPersonAliasId = currentPersonAliasId; } else { note.CreatedByPersonAliasId = registrar.PrimaryAliasId; } noteService.Add(note); } var changes = new History.HistoryChangeList(); changes.AddChange(History.HistoryVerb.Registered, History.HistoryChangeType.Record, null); HistoryService.SaveChanges( rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_REGISTRATION.AsGuid(), registrantPerson.Id, changes, registrationInstance.Name, typeof(Registration), registration.Id, false, currentPersonAliasId, rockContext.SourceOfChange); } } if (registrar != null && registrantNames.Any()) { string namesText = string.Empty; if (registrantNames.Count >= 2) { int lessOne = registrantNames.Count - 1; namesText = registrantNames.Take(lessOne).ToList().AsDelimited(", ") + " and " + registrantNames.Skip(lessOne).Take(1).First() + " "; } else { namesText = registrantNames.First() + " "; } var note = new Note(); note.NoteTypeId = noteType.Id; note.IsSystem = false; note.IsAlert = false; note.IsPrivateNote = false; note.EntityId = registrar.Id; note.Caption = string.Empty; note.Text = string.Format("Registered {0} for {1}", namesText, registrationInstance.Name); noteService.Add(note); var changes = new History.HistoryChangeList(); changes.AddChange(History.HistoryVerb.Registered, History.HistoryChangeType.Record, namesText); HistoryService.SaveChanges( rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_REGISTRATION.AsGuid(), registrar.Id, changes, registrationInstance.Name, typeof(Registration), registration.Id, false, currentPersonAliasId, rockContext.SourceOfChange); } rockContext.SaveChanges(); } } } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { if ( ! ppRequestor.PersonAliasId.HasValue ) { ShowErrorMessage( "Incomplete", "You must select a person to save a request." ); return; } if ( Page.IsValid ) { using ( var rockContext = new RockContext() ) { ConnectionRequestService connectionRequestService = new ConnectionRequestService( rockContext ); ConnectionRequest connectionRequest = null; int connectionRequestId = hfConnectionRequestId.ValueAsInt(); // if adding a new connection request if ( connectionRequestId.Equals( 0 ) ) { connectionRequest = new ConnectionRequest(); connectionRequest.ConnectionOpportunityId = hfConnectionOpportunityId.ValueAsInt(); if ( ddlCampus.SelectedValueAsId().HasValue ) { SetUserPreference( CAMPUS_SETTING, ddlCampus.SelectedValueAsId().Value.ToString() ); } } else { // load existing connection request connectionRequest = connectionRequestService.Get( connectionRequestId ); } var personAliasService = new PersonAliasService( rockContext ); int? oldConnectorPersonAliasId = connectionRequest.ConnectorPersonAliasId; int? newConnectorPersonId = ddlConnectorEdit.SelectedValueAsId(); int? newConnectorPersonAliasId = newConnectorPersonId.HasValue ? personAliasService.GetPrimaryAliasId( newConnectorPersonId.Value ) : (int?)null; connectionRequest.ConnectorPersonAliasId = newConnectorPersonAliasId; connectionRequest.PersonAlias = personAliasService.Get( ppRequestor.PersonAliasId.Value ); connectionRequest.ConnectionState = rblState.SelectedValueAsEnum<ConnectionState>(); connectionRequest.ConnectionStatusId = rblStatus.SelectedValueAsId().Value; if ( ddlCampus.SelectedValueAsId().HasValue ) { connectionRequest.CampusId = ddlCampus.SelectedValueAsId().Value; } connectionRequest.AssignedGroupId = ddlPlacementGroup.SelectedValueAsId(); connectionRequest.AssignedGroupMemberRoleId = ddlPlacementGroupRole.SelectedValueAsInt(); connectionRequest.AssignedGroupMemberStatus = ddlPlacementGroupStatus.SelectedValueAsEnumOrNull<GroupMemberStatus>(); connectionRequest.AssignedGroupMemberAttributeValues = GetGroupMemberAttributeValues(); connectionRequest.Comments = tbComments.Text.ScrubHtmlAndConvertCrLfToBr(); connectionRequest.FollowupDate = dpFollowUp.SelectedDate; if ( !Page.IsValid ) { return; } // if the connectionRequest IsValue is false, and the UI controls didn't report any errors, it is probably // because the custom rules of ConnectionRequest didn't pass. // So, make sure a message is displayed in the validation summary. cvConnectionRequest.IsValid = connectionRequest.IsValid; if ( !cvConnectionRequest.IsValid ) { cvConnectionRequest.ErrorMessage = connectionRequest.ValidationResults.Select( a => a.ErrorMessage ).ToList().AsDelimited( "<br />" ); return; } if ( connectionRequest.Id.Equals( 0 ) ) { connectionRequestService.Add( connectionRequest ); } rockContext.SaveChanges(); if ( newConnectorPersonAliasId.HasValue && !newConnectorPersonAliasId.Equals( oldConnectorPersonAliasId ) ) { var guid = Rock.SystemGuid.ConnectionActivityType.ASSIGNED.AsGuid(); var assignedActivityId = new ConnectionActivityTypeService( rockContext ).Queryable() .Where( t => t.Guid == guid ) .Select( t => t.Id ) .FirstOrDefault(); if ( assignedActivityId > 0 ) { var connectionRequestActivityService = new ConnectionRequestActivityService( rockContext ); var connectionRequestActivity = new ConnectionRequestActivity(); connectionRequestActivity.ConnectionRequestId = connectionRequest.Id; connectionRequestActivity.ConnectionOpportunityId = connectionRequest.ConnectionOpportunityId; connectionRequestActivity.ConnectionActivityTypeId = assignedActivityId; connectionRequestActivity.ConnectorPersonAliasId = newConnectorPersonAliasId; connectionRequestActivityService.Add( connectionRequestActivity ); rockContext.SaveChanges(); } } var qryParams = new Dictionary<string, string>(); qryParams["ConnectionRequestId"] = connectionRequest.Id.ToString(); qryParams["ConnectionOpportunityId"] = connectionRequest.ConnectionOpportunityId.ToString(); NavigateToPage( RockPage.Guid, qryParams ); } } }