Data Access/service class for Rock.Model.Group entity type objects that extends the functionality of Rock.Data.Service
Esempio n. 1
0
        /// <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( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed )
        {
            string formattedValue = string.Empty;

            string[] parts = ( value ?? string.Empty ).Split( '|' );
            Guid? groupTypeGuid = parts[0].AsGuidOrNull();
            Guid? groupGuid = parts[1].AsGuidOrNull();
            var rockContext = new RockContext();
            if ( groupGuid.HasValue )
            {
                var group = new GroupService( rockContext ).Get( groupGuid.Value );
                if ( group != null )
                {
                    formattedValue = "Group: " + group.Name;
                }
            }
            else if ( groupTypeGuid.HasValue )
            {
                var groupType = new GroupTypeService( rockContext ).Get( groupTypeGuid.Value );
                if ( groupType != null )
                {
                    formattedValue = "Group type: " + groupType.Name;
                }
            }

            return base.FormatValue( parentControl, formattedValue, null, condensed );
        }
        /// <summary>
        /// Handles the Load event of the Page 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 Page_Load( object sender, EventArgs e )
        {
            Exception ex = GetSavedValue( "RockLastException" ) as Exception;
            if ( ex != null )
            {
                int? errorLevel = ( GetSavedValue( "RockExceptionOrder" ) ?? "" ).ToString().AsIntegerOrNull();

                ClearSavedValue( "RockExceptionOrder" );
                ClearSavedValue( "RockLastException" );

                bool showDetails = errorLevel.HasValue && errorLevel.Value == 66;
                if ( !showDetails )
                {
                    try
                    {
                        // check to see if the user is an admin, if so allow them to view the error details
                        var userLogin = Rock.Model.UserLoginService.GetCurrentUser();
                        GroupService service = new GroupService( new RockContext() );
                        Group adminGroup = service.GetByGuid( new Guid( Rock.SystemGuid.Group.GROUP_ADMINISTRATORS ) );
                        showDetails = userLogin != null && adminGroup.Members.Where( m => m.PersonId == userLogin.PersonId ).Count() > 0;
                    }
                    catch { }
                }

                if ( showDetails )
                {
                    lErrorInfo.Text = "<h3>Exception Log:</h3>";
                    ProcessException( ex, " " );
                }
            }
        }
Esempio n. 3
0
        /// <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>();

            var parts = ( GetAttributeValue( action, "Group" ) ?? string.Empty ).Split( '|' );
            Guid? groupTypeGuid = null;
            Guid? groupGuid = null;
            if ( parts.Length >= 1 )
            {
                groupTypeGuid = parts[0].AsGuidOrNull();
                if ( parts.Length >= 2 )
                {
                    groupGuid = parts[1].AsGuidOrNull();
                }
            }

            if ( groupGuid.HasValue )
            {
                var group = new GroupService( rockContext ).Get( groupGuid.Value );
                if ( group != null )
                {
                    action.Activity.AssignedPersonAlias = null;
                    action.Activity.AssignedPersonAliasId = null;
                    action.Activity.AssignedGroup = group;
                    action.Activity.AssignedGroupId = group.Id;
                    action.AddLogEntry( string.Format( "Assigned activity to '{0}' group ({1})", group.Name, group.Id ) );
                    return true;
                }
            }

            return false;
        }
        /// <summary>
        /// Formats the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override string FormatSelection( Type entityType, string selection )
        {
            string result = "Group Member";
            string[] selectionValues = selection.Split( '|' );
            if ( selectionValues.Length >= 2 )
            {
                var rockContext = new RockContext();
                var group = new GroupService( rockContext ).Get( selectionValues[0].AsGuid() );

                var groupTypeRoleGuidList = selectionValues[1].Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ).Select( a => a.AsGuid() ).ToList();

                var groupTypeRoles = new GroupTypeRoleService( rockContext ).Queryable().Where( a => groupTypeRoleGuidList.Contains( a.Guid ) ).ToList();

                if ( group != null )
                {
                    result = string.Format( "Not in group: {0}", group.Name );
                    if ( groupTypeRoles.Count() > 0 )
                    {
                        result += string.Format( ", with role(s): {0}", groupTypeRoles.Select( a => a.Name ).ToList().AsDelimited( "," ) );
                    }
                }
            }

            return result;
        }
 /// <summary>
 /// When overridden in a derived class, handles the exception synchronously.
 /// </summary>
 /// <param name="context">The exception handler context.</param>
 public override void Handle( ExceptionHandlerContext context )
 {
      // check to see if the user is an admin, if so allow them to view the error details
     var userLogin = Rock.Model.UserLoginService.GetCurrentUser();
     GroupService service = new GroupService( new RockContext() );
     Group adminGroup = service.GetByGuid( new Guid( Rock.SystemGuid.Group.GROUP_ADMINISTRATORS ) );
     context.RequestContext.IncludeErrorDetail = userLogin != null && adminGroup.Members.Where( m => m.PersonId == userLogin.PersonId ).Count() > 0;
     
     base.Handle( context );
 }
Esempio n. 6
0
        public IQueryable<TreeViewItem> GetChildren( int id, int rootGroupId, bool limitToSecurityRoleGroups, string groupTypeIds )
        {
            var user = CurrentUser();
            if ( user != null )
            {
                var groupService = new GroupService();
                groupService.Repository.SetConfigurationValue( "ProxyCreationEnabled", "false" );
                var qry = groupService.GetNavigationChildren( id, rootGroupId, limitToSecurityRoleGroups, groupTypeIds );

                List<Group> groupList = new List<Group>();
                List<TreeViewItem> groupNameList = new List<TreeViewItem>();

                foreach ( var group in qry )
                {
                    if ( group.IsAuthorized( "View", user.Person ) )
                    {
                        groupList.Add( group );
                        var treeViewItem = new TreeViewItem();
                        treeViewItem.Id = group.Id.ToString();
                        treeViewItem.Name = System.Web.HttpUtility.HtmlEncode( group.Name );

                        // if there a IconCssClass is assigned, use that as the Icon.
                        var groupType = Rock.Web.Cache.GroupTypeCache.Read( group.GroupTypeId );
                        if ( groupType != null )
                        {
                            treeViewItem.IconCssClass = groupType.IconCssClass;
                        }

                        groupNameList.Add( treeViewItem );
                    }
                }

                // try to quickly figure out which items have Children
                List<int> resultIds = groupList.Select( a => a.Id ).ToList();

                var qryHasChildren = from x in Get().Select( a => a.ParentGroupId )
                                     where resultIds.Contains( x.Value )
                                     select x.Value;

                var qryHasChildrenList = qryHasChildren.ToList();

                foreach ( var g in groupNameList )
                {
                    int groupId = int.Parse( g.Id );
                    g.HasChildren = qryHasChildrenList.Any( a => a == groupId );
                }

                return groupNameList.AsQueryable();
            }
            else
            {
                throw new HttpResponseException( HttpStatusCode.Unauthorized );
            }
        }
Esempio n. 7
0
 /// <summary>
 /// Sets the value.
 /// </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 )
     {
         GroupPicker groupPicker = control as GroupPicker;
         int groupId = 0;
         int.TryParse( value, out groupId );
         Group group = new GroupService().Get( groupId );
         groupPicker.SetValue( group );
     }
 }
        /// <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( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed )
        {
            string formattedValue = value;

            Guid? guid = value.AsGuidOrNull();
            if ( guid.HasValue )
            {
                var group = new GroupService( new RockContext() ).Get( guid.Value );
                if ( group != null )
                {
                    formattedValue = group.Name;
                }
            }

            return base.FormatValue( parentControl, formattedValue, configurationValues, condensed );
        }
Esempio n. 9
0
        private void BindGrid()
        {
            string type = PageParameter( "SearchType" );
            string term = PageParameter( "SearchTerm" );

            var groupService = new GroupService( new RockContext() );
            var groups = new List<Group>();

            if ( !string.IsNullOrWhiteSpace( type ) && !string.IsNullOrWhiteSpace( term ) )
            {
                switch ( type.ToLower() )
                {
                    case "name":
                        {
                            groups = groupService.Queryable()
                                .Where( g =>
                                    g.GroupType.ShowInNavigation &&
                                    g.Name.Contains( term ) )
                                .OrderBy( g => g.Order )
                                .ThenBy( g => g.Name )
                                .ToList();

                            break;
                        }
                }
            }

            if ( groups.Count == 1 )
            {
                Response.Redirect( string.Format( "~/Group/{0}", groups[0].Id ), false );
                Context.ApplicationInstance.CompleteRequest();
            }
            else
            {
                gGroups.EntityTypeId = EntityTypeCache.Read<Group>().Id;
                gGroups.DataSource = groups
                    .Select( g => new
                    {
                        g.Id,
                        GroupType = g.GroupType.Name,
                        Structure = ParentStructure( g ),
                        MemberCount = g.Members.Count()
                    } )
                    .ToList();
                gGroups.DataBind();
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Creates the control(s) neccessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl( Dictionary<string, ConfigurationValue> configurationValues, string id )
        {
            var editControl = new RockDropDownList { ID = id };

            var roles = new GroupService( new RockContext() ).Queryable().Where(g => g.IsSecurityRole).OrderBy( t => t.Name );
            if ( roles.Any() )
            {
                foreach ( var role in roles )
                {
                    editControl.Items.Add( new ListItem( role.Name, role.Guid.ToString() ) );
                }

                return editControl;
            }

            return null;
        }
Esempio n. 11
0
        /// <summary>
        /// Marks the selected people/photos as verified by setting their group member status Active.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void bbtnVerify_Click( object sender, EventArgs e )
        {
            nbMessage.Visible = true;

            int count = 0;
            RockContext rockContext = new RockContext();
            GroupService groupService = new GroupService( rockContext );
            Group group = groupService.Get( Rock.SystemGuid.Group.GROUP_PHOTO_REQUEST.AsGuid() );

            GroupMember groupMember = null;

            var itemsSelected = new List<int>();

            gList.SelectedKeys.ToList().ForEach( i => itemsSelected.Add( i.ToString().AsInteger() ) );

            if ( itemsSelected.Any() )
            {
                foreach ( int currentRowsPersonId in itemsSelected )
                {
                    groupMember = group.Members.Where( m => m.PersonId == currentRowsPersonId ).FirstOrDefault();
                    if ( groupMember != null )
                    {
                        count++;
                        groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                    }
                }
            }

            if ( count > 0 )
            {
                nbMessage.NotificationBoxType = NotificationBoxType.Success;
                nbMessage.Text = string.Format( "Verified {0} photo{1}.", count, count > 1 ? "s" : "" );
            }
            else
            {
                nbMessage.NotificationBoxType = NotificationBoxType.Warning;
                nbMessage.Text = "No photos selected.";
            }
            rockContext.SaveChanges();
            _photoRequestGroup = group;

            BindGrid();
        }
Esempio n. 12
0
        /// <summary>
        /// When overridden in a derived class, handles the exception synchronously.
        /// </summary>
        /// <param name="context">The exception handler context.</param>
        public override void Handle( ExceptionHandlerContext context )
        {
            // check to see if the user is an admin, if so allow them to view the error details
            var userLogin = Rock.Model.UserLoginService.GetCurrentUser();
            GroupService service = new GroupService( new RockContext() );
            Group adminGroup = service.GetByGuid( new Guid( Rock.SystemGuid.Group.GROUP_ADMINISTRATORS ) );
            context.RequestContext.IncludeErrorDetail = userLogin != null && adminGroup.Members.Where( m => m.PersonId == userLogin.PersonId ).Count() > 0;

            ExceptionResult result = context.Result as ExceptionResult;

            // fix up context.Result.IncludeErrorMessage if it didn't get set when we set context.RequestContext.IncludeErrorDetail
            // see comments in https://aspnetwebstack.codeplex.com/workitem/1248
            if ( result != null && result.IncludeErrorDetail != context.RequestContext.IncludeErrorDetail )
            {

                context.Result = new ExceptionResult( result.Exception, context.RequestContext.IncludeErrorDetail, result.ContentNegotiator, context.Request, result.Formatters );
            }

            base.Handle( context );
        }
Esempio n. 13
0
        /// <summary>
        /// Marks the selected people/photos as verified by setting their group member status Active.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void bbtnVerify_Click( object sender, EventArgs e )
        {
            nbMessage.Visible = true;

            int count = 0;
            RockContext rockContext = new RockContext();
            GroupService groupService = new GroupService( rockContext );
            Group group = groupService.Get( Rock.SystemGuid.Group.GROUP_PHOTO_REQUEST.AsGuid() );

            GroupMember groupMember = null;
            foreach ( GridViewRow row in gList.Rows )
            {
                var cb = row.FindControl( "cbSelected" ) as CheckBox;

                if ( cb != null && cb.Checked )
                {
                    int currentRowsPersonId = (int)gList.DataKeys[row.RowIndex].Value;
                    groupMember = group.Members.Where( m => m.PersonId == currentRowsPersonId ).FirstOrDefault();
                    if ( groupMember != null )
                    {
                        count++;
                        groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                    }
                }
            }

            if ( count > 0 )
            {
                nbMessage.NotificationBoxType = NotificationBoxType.Success;
                nbMessage.Text = string.Format( "Verified {0} photo{1}.", count, count > 1 ? "s" : "" );
            }
            else
            {
                nbMessage.NotificationBoxType = NotificationBoxType.Warning;
                nbMessage.Text = "No changes were made.";
            }
            rockContext.SaveChanges();
            _photoRequestGroup = group;

            BindGrid();
        }
        /// <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? groupGuid = GetAttributeValue( action, "SecurityRole" ).AsGuidOrNull();
            if ( groupGuid.HasValue )
            {
                var group = new GroupService( rockContext ).Get( groupGuid.Value );
                if ( group != null )
                {
                    action.Activity.AssignedPersonAlias = null;
                    action.Activity.AssignedPersonAliasId = null;
                    action.Activity.AssignedGroup = group;
                    action.Activity.AssignedGroupId = group.Id;
                    action.AddLogEntry( string.Format( "Assigned activity to '{0}' security role ({1})", group.Name, group.Id ) );
                    return true;
                }
            }

            return false;
        }
Esempio n. 15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Guid? rootGroupGuid = GetAttributeValue("RootGroup").AsGuidOrNull();
            GroupService gs = new GroupService(new RockContext());

            if (rootGroupGuid != null)
            {
                var staffGroup = gs.Get(rootGroupGuid.Value);
                var groupMembers = staffGroup.Members.OrderByDescending(g => g.GroupMemberStatus).Select(m => m.Person).OrderBy(m => m.LastName).ThenBy(m => m.FirstName).ToList();
                var groupName = staffGroup.Name.ToString();
                this.lblGroupName.Text = groupName;

                var people = new List<PersonData>();

                foreach (var person in groupMembers)
                {
                    person.LoadAttributes();
                    people.Add(new PersonData { Name = person.FullName, PhotoUrl = person.PhotoUrl, Position = person.GetAttributeValue("Position") });
                }

                this.rptStaff.DataSource = people;
                this.rptStaff.DataBind();
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute( IJobExecutionContext context )
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            var emailTemplateGuid = dataMap.Get( "SystemEmail" ).ToString().AsGuid();
            var groupGuid = dataMap.Get( "Group" ).ToString().AsGuid();
            var sendToDescendants = dataMap.Get( "SendToDescendantGroups" ).ToString().AsBoolean();

            var rockContext = new RockContext();
            var group = new GroupService( rockContext ).Get( groupGuid );
            if ( group != null )
            {
                List<int> groupIds = new List<int>();
                GetGroupIds( groupIds, sendToDescendants, group );

                var recipients = new List<RecipientData>();

                var groupMemberList = new GroupMemberService( rockContext ).Queryable().Where( gm =>
                    groupIds.Contains( gm.GroupId ) &&
                    gm.GroupMemberStatus == GroupMemberStatus.Active )
                    .ToList();

                foreach ( GroupMember groupMember in groupMemberList )
                {
                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( null );
                    mergeFields.Add( "Person", groupMember.Person );
                    mergeFields.Add( "GroupMember", groupMember );
                    mergeFields.Add( "Group", groupMember.Group );

                    recipients.Add( new RecipientData( groupMember.Person.Email, mergeFields ) );
                }

                var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "ExternalApplicationRoot" );
                Email.Send( emailTemplateGuid, recipients, appRoot );
                context.Result = string.Format( "{0} emails sent", recipients.Count() );
            }
        }
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute( IJobExecutionContext context )
        {
            var rockContext = new RockContext();

            JobDataMap dataMap = context.JobDetail.JobDataMap;
            Guid? systemEmailGuid = dataMap.GetString( "NotificationEmailTemplate" ).AsGuidOrNull();

            if ( systemEmailGuid.HasValue )
            {

                var selectedGroupTypes = new List<Guid>();
                if ( !string.IsNullOrWhiteSpace( dataMap.GetString( "GroupTypes" ) ) )
                {
                    selectedGroupTypes = dataMap.GetString( "GroupTypes" ).Split( ',' ).Select( Guid.Parse ).ToList();
                }

                var excludedGroupRoleIds = new List<int>();
                if ( !string.IsNullOrWhiteSpace( dataMap.GetString( "ExcludedGroupRoleIds" ) ) )
                {
                    excludedGroupRoleIds = dataMap.GetString( "ExcludedGroupRoleIds" ).Split( ',' ).Select( int.Parse ).ToList();
                }

                var notificationOption = dataMap.GetString( "NotifyParentLeaders" ).ConvertToEnum<NotificationOption>( NotificationOption.None );

                var accountAbilityGroupGuid = dataMap.GetString( "AccountabilityGroup" ).AsGuid();

                // get groups matching of the types provided
                GroupService groupService = new GroupService( rockContext );
                var groups = groupService.Queryable().AsNoTracking()
                                .Where( g => selectedGroupTypes.Contains( g.GroupType.Guid )
                                    && g.IsActive == true
                                    && g.GroupRequirements.Any() );

                foreach ( var group in groups )
                {
                    // check for members that don't meet requirements
                    var groupMembersWithIssues = groupService.GroupMembersNotMeetingRequirements( group.Id, true );

                    if ( groupMembersWithIssues.Count > 0 )
                    {
                        // add issues to issue list
                        GroupsMissingRequirements groupMissingRequirements = new GroupsMissingRequirements();
                        groupMissingRequirements.Id = group.Id;
                        groupMissingRequirements.Name = group.Name;
                        if ( group.GroupType != null )
                        {
                            groupMissingRequirements.GroupTypeId = group.GroupTypeId;
                            groupMissingRequirements.GroupTypeName = group.GroupType.Name;
                        }
                        groupMissingRequirements.AncestorPathName = groupService.GroupAncestorPathName( group.Id );

                        // get list of the group leaders
                        groupMissingRequirements.Leaders = group.Members
                                                            .Where( m => m.GroupRole.IsLeader == true && !excludedGroupRoleIds.Contains( m.GroupRoleId ) )
                                                            .Select( m => new GroupMemberResult
                                                            {
                                                                Id = m.Id,
                                                                PersonId = m.PersonId,
                                                                FullName = m.Person.FullName
                                                            } )
                                                              .ToList();

                        List<GroupMembersMissingRequirements> groupMembers = new List<GroupMembersMissingRequirements>();

                        foreach ( var groupMemberIssue in groupMembersWithIssues )
                        {
                            GroupMembersMissingRequirements groupMember = new GroupMembersMissingRequirements();
                            groupMember.FullName = groupMemberIssue.Key.Person.FullName;
                            groupMember.Id = groupMemberIssue.Key.Id;
                            groupMember.PersonId = groupMemberIssue.Key.PersonId;
                            groupMember.GroupMemberRole = groupMemberIssue.Key.GroupRole.Name;

                            List<MissingRequirement> missingRequirements = new List<MissingRequirement>();
                            foreach ( var issue in groupMemberIssue.Value )
                            {
                                MissingRequirement missingRequirement = new MissingRequirement();
                                missingRequirement.Id = issue.Key.GroupRequirement.GroupRequirementType.Id;
                                missingRequirement.Name = issue.Key.GroupRequirement.GroupRequirementType.Name;
                                missingRequirement.Status = issue.Key.MeetsGroupRequirement;
                                missingRequirement.OccurrenceDate = issue.Value;

                                switch ( issue.Key.MeetsGroupRequirement )
                                {
                                    case MeetsGroupRequirement.Meets:
                                        missingRequirement.Message = issue.Key.GroupRequirement.GroupRequirementType.PositiveLabel;
                                        break;
                                    case MeetsGroupRequirement.MeetsWithWarning:
                                        missingRequirement.Message = issue.Key.GroupRequirement.GroupRequirementType.WarningLabel;
                                        break;
                                    case MeetsGroupRequirement.NotMet:
                                        missingRequirement.Message = issue.Key.GroupRequirement.GroupRequirementType.NegativeLabel;
                                        break;
                                }

                                missingRequirements.Add( missingRequirement );
                            }

                            groupMember.MissingRequirements = missingRequirements;

                            groupMembers.Add( groupMember );
                        }
                        groupMissingRequirements.GroupMembersMissingRequirements = groupMembers;

                        _groupsMissingRequriements.Add( groupMissingRequirements );

                        // add leaders as people to notify
                        foreach ( var leader in group.Members.Where( m => m.GroupRole.IsLeader == true && !excludedGroupRoleIds.Contains( m.GroupRoleId ) ) )
                        {
                            NotificationItem notification = new NotificationItem();
                            notification.GroupId = group.Id;
                            notification.Person = leader.Person;
                            _notificationList.Add( notification );
                        }

                        // notify parents
                        if ( notificationOption != NotificationOption.None )
                        {
                            var parentLeaders = new GroupMemberService( rockContext ).Queryable( "Person" ).AsNoTracking()
                                                    .Where( m => m.GroupRole.IsLeader && !excludedGroupRoleIds.Contains( m.GroupRoleId ) );

                            if ( notificationOption == NotificationOption.DirectParent )
                            {
                                // just the parent group
                                parentLeaders = parentLeaders.Where( m => m.GroupId == group.ParentGroupId );
                            }
                            else
                            {
                                // all parents in the heirarchy
                                var parentIds = groupService.GetAllAncestorIds( group.Id );
                                parentLeaders = parentLeaders.Where( m => parentIds.Contains( m.GroupId ) );
                            }

                            foreach ( var parentLeader in parentLeaders.ToList() )
                            {
                                NotificationItem parentNotification = new NotificationItem();
                                parentNotification.Person = parentLeader.Person;
                                parentNotification.GroupId = group.Id;
                                _notificationList.Add( parentNotification );
                            }
                        }
                    }
                }

                // send out notificatons
                var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "PublicApplicationRoot" );
                var recipients = new List<RecipientData>();

                var notificationRecipients = _notificationList.GroupBy( p => p.Person.Id ).ToList();
                foreach ( var recipientId in notificationRecipients )
                {
                    var recipient = _notificationList.Where( n => n.Person.Id == recipientId.Key ).Select( n => n.Person ).FirstOrDefault();

                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( null );
                    mergeFields.Add( "Person", recipient );

                    var notificationGroupIds = _notificationList
                                                    .Where( n => n.Person.Id == recipient.Id )
                                                    .Select( n => n.GroupId )
                                                    .ToList();

                    var missingRequirements = _groupsMissingRequriements.Where( g => notificationGroupIds.Contains( g.Id ) ).ToList();

                    mergeFields.Add( "GroupsMissingRequirements", missingRequirements );

                    recipients.Add( new RecipientData( recipient.Email, mergeFields ) );
                    Email.Send( systemEmailGuid.Value, recipients, appRoot );

                    recipients.Clear();
                }

                // add accountability group members
                if ( !accountAbilityGroupGuid.IsEmpty() )
                {
                    var accountabilityGroupMembers = new GroupMemberService( rockContext ).Queryable().AsNoTracking()
                                                        .Where( m => m.Group.Guid == accountAbilityGroupGuid )
                                                        .Select( m => m.Person );

                    foreach ( var person in accountabilityGroupMembers )
                    {
                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( null );
                        mergeFields.Add( "Person", person );
                        mergeFields.Add( "GroupsMissingRequirements", _groupsMissingRequriements );

                        recipients.Add( new RecipientData( person.Email, mergeFields ) );
                    }
                }

                Email.Send( systemEmailGuid.Value, recipients, appRoot );

                context.Result = string.Format( "{0} requirement notification {1} sent", recipients.Count, "email".PluralizeIf( recipients.Count() != 1 ) );

            }
            else
            {
                context.Result = "Warning: No NotificationEmailTemplate found";
            }
        }
Esempio n. 18
0
 /// <summary>
 /// Loads the drop downs.
 /// </summary>
 private void LoadDropDowns()
 {
     // Controls on Main Campaign Panel
     GroupService groupService = new GroupService( new RockContext() );
     List<Group> groups = groupService.Queryable().Where( a => a.GroupType.Guid.Equals( new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_EVENTATTENDEES ) ) ).OrderBy( a => a.Name ).ToList();
     groups.Insert( 0, new Group { Id = None.Id, Name = None.Text } );
     ddlEventGroup.DataSource = groups;
     ddlEventGroup.DataBind();
 }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            // confirmation was disabled by btnSave on client-side.  So if returning without a redirect,
            // it should be enabled.  If returning with a redirect, the control won't be updated to reflect
            // confirmation being enabled, so it's ok to enable it here
            confirmExit.Enabled = true;

            if ( Page.IsValid )
            {
                confirmExit.Enabled = true;

                RockTransactionScope.WrapTransaction( () =>
                {
                    var rockContext = new RockContext();
                    var familyService = new GroupService( rockContext );
                    var familyMemberService = new GroupMemberService( rockContext );
                    var personService = new PersonService( rockContext );
                    var historyService = new HistoryService( rockContext );

                    var familyChanges = new List<string>();

                    // SAVE FAMILY
                    _family = familyService.Get( _family.Id );

                    History.EvaluateChange( familyChanges, "Family Name", _family.Name, tbFamilyName.Text );
                    _family.Name = tbFamilyName.Text;

                    int? campusId = cpCampus.SelectedValueAsInt();
                    if ( _family.CampusId != campusId )
                    {
                        History.EvaluateChange( familyChanges, "Campus",
                            _family.CampusId.HasValue ? CampusCache.Read( _family.CampusId.Value ).Name : string.Empty,
                            campusId.HasValue ? CampusCache.Read( campusId.Value ).Name : string.Empty );
                        _family.CampusId = campusId;
                    }

                    var familyGroupTypeId = _family.GroupTypeId;

                    rockContext.SaveChanges();

                    // SAVE FAMILY MEMBERS
                    int? recordStatusValueID = ddlRecordStatus.SelectedValueAsInt();
                    int? reasonValueId = ddlReason.SelectedValueAsInt();
                    var newFamilies = new List<Group>();

                    foreach ( var familyMember in FamilyMembers )
                    {
                        var memberChanges = new List<string>();
                        var demographicChanges = new List<string>();

                        var role = familyRoles.Where( r => r.Guid.Equals( familyMember.RoleGuid ) ).FirstOrDefault();
                        if ( role == null )
                        {
                            role = familyRoles.FirstOrDefault();
                        }

                        bool isChild = role != null && role.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) );

                        // People added to family (new or from other family)
                        if ( !familyMember.ExistingFamilyMember )
                        {
                            var groupMember = new GroupMember();

                            if ( familyMember.Id == -1 )
                            {
                                // added new person
                                demographicChanges.Add( "Created" );

                                var person = new Person();
                                person.FirstName = familyMember.FirstName;
                                person.NickName = familyMember.NickName;
                                History.EvaluateChange( demographicChanges, "First Name", string.Empty, person.FirstName );

                                person.LastName = familyMember.LastName;
                                History.EvaluateChange( demographicChanges, "Last Name", string.Empty, person.LastName );

                                person.Gender = familyMember.Gender;
                                History.EvaluateChange( demographicChanges, "Gender", null, person.Gender );

                                person.BirthDate = familyMember.BirthDate;
                                History.EvaluateChange( demographicChanges, "Birth Date", null, person.BirthDate );

                                if ( !isChild )
                                {
                                    person.GivingGroupId = _family.Id;
                                    History.EvaluateChange( demographicChanges, "Giving Group", string.Empty, _family.Name );
                                }

                                person.EmailPreference = EmailPreference.EmailAllowed;

                                groupMember.Person = person;
                            }
                            else
                            {
                                // added from other family
                                groupMember.Person = personService.Get( familyMember.Id );
                            }

                            if ( recordStatusValueID > 0 )
                            {
                                History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( groupMember.Person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) );
                                groupMember.Person.RecordStatusValueId = recordStatusValueID;

                                History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( groupMember.Person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) );
                                groupMember.Person.RecordStatusReasonValueId = reasonValueId;
                            }

                            groupMember.GroupId = _family.Id;
                            if ( role != null )
                            {
                                History.EvaluateChange( memberChanges, "Role", string.Empty, role.Name );
                                groupMember.GroupRoleId = role.Id;
                            }

                            if ( groupMember.Person != null )
                            {
                                familyMemberService.Add( groupMember );
                                rockContext.SaveChanges();
                                familyMember.Id = groupMember.Person.Id;
                            }

                        }
                        else
                        {
                            // existing family members
                            var groupMember = familyMemberService.Queryable( "Person" ).Where( m =>
                                m.PersonId == familyMember.Id &&
                                m.Group.GroupTypeId == familyGroupTypeId &&
                                m.GroupId == _family.Id ).FirstOrDefault();

                            if ( groupMember != null )
                            {
                                if ( familyMember.Removed )
                                {
                                    var newFamilyChanges = new List<string>();

                                    // Family member was removed and should be created in their own new family
                                    var newFamily = new Group();
                                    newFamily.Name = familyMember.LastName + " Family";
                                    History.EvaluateChange( newFamilyChanges, "Family", string.Empty, newFamily.Name );

                                    newFamily.GroupTypeId = familyGroupTypeId;

                                    if ( _family.CampusId.HasValue )
                                    {
                                        History.EvaluateChange( newFamilyChanges, "Campus", string.Empty, CampusCache.Read( _family.CampusId.Value ).Name );
                                    }
                                    newFamily.CampusId = _family.CampusId;

                                    familyService.Add( newFamily );
                                    rockContext.SaveChanges();

                                    // If person's previous giving group was this family, set it to their new family id
                                    if ( groupMember.Person.GivingGroup != null && groupMember.Person.GivingGroupId == _family.Id )
                                    {
                                        History.EvaluateChange( demographicChanges, "Giving Group", groupMember.Person.GivingGroup.Name, _family.Name );
                                        groupMember.Person.GivingGroupId = newFamily.Id;
                                    }

                                    groupMember.Group = newFamily;
                                    rockContext.SaveChanges();

                                    var newMemberChanges = new List<string>();
                                    History.EvaluateChange( newMemberChanges, "Role", string.Empty, groupMember.GroupRole.Name );

                                    HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                        groupMember.Person.Id, newFamilyChanges, newFamily.Name, typeof( Group ), newFamily.Id );

                                    newFamilies.Add( newFamily );

                                    History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole.Name, string.Empty );
                                }
                                else
                                {
                                    // Existing member was not remvoved
                                    if ( role != null )
                                    {
                                        History.EvaluateChange( memberChanges, "Role",
                                            groupMember.GroupRole != null ? groupMember.GroupRole.Name : string.Empty, role.Name );
                                        groupMember.GroupRoleId = role.Id;

                                        if ( recordStatusValueID > 0 )
                                        {
                                            History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( groupMember.Person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) );
                                            groupMember.Person.RecordStatusValueId = recordStatusValueID;

                                            History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( groupMember.Person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) );
                                            groupMember.Person.RecordStatusReasonValueId = reasonValueId;
                                        }

                                        rockContext.SaveChanges();
                                    }
                                }
                            }
                        }

                        // Remove anyone that was moved from another family
                        if ( familyMember.RemoveFromOtherFamilies )
                        {
                            var otherFamilies = familyMemberService.Queryable()
                                .Where( m =>
                                    m.PersonId == familyMember.Id &&
                                    m.Group.GroupTypeId == familyGroupTypeId &&
                                    m.GroupId != _family.Id )
                                .ToList();

                            foreach ( var otherFamilyMember in otherFamilies )
                            {
                                var fm = familyMemberService.Get( otherFamilyMember.Id );

                                // If the person's giving group id was the family they are being removed from, update it to this new family's id
                                if ( fm.Person.GivingGroupId == fm.GroupId )
                                {
                                    var person = personService.Get( fm.PersonId );

                                    History.EvaluateChange( demographicChanges, "Giving Group", person.GivingGroup.Name, _family.Name );
                                    person.GivingGroupId = _family.Id;

                                    rockContext.SaveChanges();
                                }

                                var oldMemberChanges = new List<string>();
                                History.EvaluateChange( oldMemberChanges, "Role", fm.GroupRole.Name, string.Empty );
                                History.EvaluateChange( oldMemberChanges, "Family", fm.Group.Name, string.Empty );
                                HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                    fm.Person.Id, oldMemberChanges, fm.Group.Name, typeof( Group ), fm.Group.Id );

                                familyMemberService.Delete( fm );
                                rockContext.SaveChanges();

                                var f = familyService.Queryable()
                                    .Where( g =>
                                        g.Id == otherFamilyMember.GroupId &&
                                        !g.Members.Any() )
                                    .FirstOrDefault();
                                if ( f != null )
                                {
                                    familyService.Delete( f );
                                    rockContext.SaveChanges();
                                }

                            }
                        }

                        HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                            familyMember.Id, demographicChanges );

                        HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            familyMember.Id, memberChanges, _family.Name, typeof( Group ), _family.Id );
                    }

                    // SAVE LOCATIONS
                    var groupLocationService = new GroupLocationService( rockContext );

                    // delete any group locations that were removed
                    var remainingLocationIds = FamilyAddresses.Where( a => a.Id > 0 ).Select( a => a.Id ).ToList();
                    foreach ( var removedLocation in groupLocationService.Queryable( "GroupLocationTypeValue,Location" )
                        .Where( l => l.GroupId == _family.Id &&
                            !remainingLocationIds.Contains( l.Id ) ) )
                    {
                        History.EvaluateChange( familyChanges, removedLocation.GroupLocationTypeValue.Name + " Location",
                            removedLocation.Location.ToString(), string.Empty );
                        groupLocationService.Delete( removedLocation );
                    }
                    rockContext.SaveChanges();

                    foreach ( var familyAddress in FamilyAddresses )
                    {
                        Location updatedAddress = null;
                        if ( familyAddress.LocationIsDirty )
                        {
                            updatedAddress = new LocationService( rockContext ).Get(
                                familyAddress.Street1, familyAddress.Street2, familyAddress.City,
                                familyAddress.State, familyAddress.Zip );
                        }

                        GroupLocation groupLocation = null;
                        if ( familyAddress.Id > 0 )
                        {
                            groupLocation = groupLocationService.Get( familyAddress.Id );
                        }
                        if ( groupLocation == null )
                        {
                            groupLocation = new GroupLocation();
                            groupLocation.GroupId = _family.Id;
                            groupLocationService.Add( groupLocation );
                        }

                        History.EvaluateChange( familyChanges, "Location Type",
                            groupLocation.GroupLocationTypeValueId.HasValue ? DefinedValueCache.Read( groupLocation.GroupLocationTypeValueId.Value ).Name : string.Empty,
                            familyAddress.LocationTypeName );
                        groupLocation.GroupLocationTypeValueId = familyAddress.LocationTypeId;

                        History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Is Mailing",
                            groupLocation.IsMailingLocation.ToString(), familyAddress.IsMailing.ToString() );
                        groupLocation.IsMailingLocation = familyAddress.IsMailing;

                        History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Is Map Location",
                            groupLocation.IsMappedLocation.ToString(), familyAddress.IsLocation.ToString() );
                        groupLocation.IsMappedLocation = familyAddress.IsLocation;

                        if ( updatedAddress != null )
                        {
                            History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Location",
                                groupLocation.Location != null ? groupLocation.Location.ToString() : "", updatedAddress.ToString() );
                            groupLocation.Location = updatedAddress;
                        }

                        rockContext.SaveChanges();

                        // Add the same locations to any new families created by removing an existing family member
                        if ( newFamilies.Any() )
                        {
                            //reload grouplocation for access to child properties
                            groupLocation = groupLocationService.Get( groupLocation.Id );
                            foreach ( var newFamily in newFamilies )
                            {
                                var newFamilyLocation = new GroupLocation();
                                newFamilyLocation.GroupId = newFamily.Id;
                                newFamilyLocation.LocationId = groupLocation.LocationId;
                                newFamilyLocation.GroupLocationTypeValueId = groupLocation.GroupLocationTypeValueId;
                                newFamilyLocation.IsMailingLocation = groupLocation.IsMailingLocation;
                                newFamilyLocation.IsMappedLocation = groupLocation.IsMappedLocation;
                                groupLocationService.Add( newFamilyLocation );
                            }

                            rockContext.SaveChanges();
                        }
                    }

                    foreach ( var fm in _family.Members )
                    {
                        HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            fm.PersonId, familyChanges, _family.Name, typeof( Group ), _family.Id );
                    }

                    _family = familyService.Get( _family.Id );
                    if ( _family.Members.Any( m => m.PersonId == Person.Id ) )
                    {
                        Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false );
                    }
                    else
                    {
                        var fm = _family.Members
                            .Where( m =>
                                m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) &&
                                m.Person.Gender == Gender.Male )
                            .OrderByDescending( m => m.Person.Age )
                            .FirstOrDefault();
                        if ( fm == null )
                        {
                            fm = _family.Members
                                .Where( m =>
                                    m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) )
                                .OrderByDescending( m => m.Person.Age )
                                .FirstOrDefault();
                        }
                        if ( fm == null )
                        {
                            fm = _family.Members
                                .OrderByDescending( m => m.Person.Age )
                                .FirstOrDefault();
                        }
                        if ( fm != null )
                        {
                            Response.Redirect( string.Format( "~/Person/{0}", fm.PersonId ), false );
                        }
                        else
                        {
                            Response.Redirect( "~", false );
                        }
                    }

                } );
            }
        }
Esempio n. 20
0
        /// <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;
        }
Esempio n. 21
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entityIdProperty">The entity identifier property.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override System.Linq.Expressions.Expression GetExpression( Data.RockContext context, System.Linq.Expressions.MemberExpression entityIdProperty, string selection )
        {
            bool showAsLink = this.GetAttributeValueFromSelection( "ShowAsLink", selection ).AsBooleanOrNull() ?? false;
            var groupQry = new GroupService( context ).Queryable();

            IQueryable<string> groupLinkQry;
            string baseGroupUrl = System.Web.VirtualPathUtility.ToAbsolute( "~/Group/" );

            if ( showAsLink )
            {
                // return string in format: <a href='/group/{groupId}'>Name</a>
                groupLinkQry = groupQry.Select( p => "<a href='" + baseGroupUrl + p.Id.ToString() + "'>" + p.Name + "</a>" );
            }
            else
            {
                groupLinkQry = groupQry.Select( p => p.Name );
            }

            return SelectExpressionExtractor.Extract( groupLinkQry, entityIdProperty, "p" );
        }
        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 );
        }
Esempio n. 23
0
        /// <summary>
        /// Creates a Linq Expression that can be applied to an IQueryable to filter the result set.
        /// </summary>
        /// <param name="entityType">The type of entity in the result set.</param>
        /// <param name="serviceInstance">A service instance that can be queried to obtain the result set.</param>
        /// <param name="parameterExpression">The input parameter that will be injected into the filter expression.</param>
        /// <param name="selection">A formatted string representing the filter settings.</param>
        /// <returns>
        /// A Linq Expression that can be used to filter an IQueryable.
        /// </returns>
        public override Expression GetExpression( Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection )
        {
            var settings = new SelectSettings( selection );

            var context = (RockContext)serviceInstance.Context;

            //
            // Evaluate the Data View that defines the candidate Groups.
            //
            var dataView = DataComponentSettingsHelper.GetDataViewForFilterComponent( settings.DataViewGuid, context );

            var groupService = new GroupService( context );

            var groupQuery = groupService.Queryable();

            if (dataView != null)
            {
                groupQuery = DataComponentSettingsHelper.FilterByDataView( groupQuery, dataView, groupService );
            }
            else
            {
                // Apply a default Group filter to only show Groups that would be visible in a Group List.
                groupQuery = groupQuery.Where( x => x.GroupType.ShowInGroupList );
            }

            var groupKeys = groupQuery.Select( x => x.Id );

            //
            // Construct the Query to return the list of Group Members matching the filter conditions.
            //
            var groupMemberQuery = new GroupMemberService( context ).Queryable();

            // Filter By Group.
            groupMemberQuery = groupMemberQuery.Where( x => groupKeys.Contains( x.GroupId ) );

            // Filter By Group Role Type.
            switch ( settings.RoleType )
            {
                case RoleTypeSpecifier.Member:
                    groupMemberQuery = groupMemberQuery.Where( x => !x.GroupRole.IsLeader );
                    break;

                case RoleTypeSpecifier.Leader:
                    groupMemberQuery = groupMemberQuery.Where( x => x.GroupRole.IsLeader );
                    break;
            }

            // Filter by Group Member Status.
            if ( settings.MemberStatus.HasValue )
            {
                groupMemberQuery = groupMemberQuery.Where( x => x.GroupMemberStatus == settings.MemberStatus.Value );
            }

            //
            // Create a Select Expression to return the Person records referenced by the Group Members.
            //
            var personGroupsQuery = new PersonService( context ).Queryable()
                                                                .Where( p => groupMemberQuery.Select( gm => gm.PersonId ).Contains( p.Id ) );

            var selectExpression = FilterExpressionExtractor.Extract<Model.Person>( personGroupsQuery, parameterExpression, "p" );

            return selectExpression;
        }
Esempio n. 24
0
        private Person GetPersonOrBusiness( Person person )
        {
            if ( person != null && phGiveAsOption.Visible && !tglGiveAsOption.Checked )
            {
                var rockContext = new RockContext();
                var personService = new PersonService( rockContext );
                var groupService = new GroupService( rockContext );
                var groupMemberService = new GroupMemberService( rockContext );

                Group familyGroup = null;

                Person business = null;
                int? businessId = cblBusiness.SelectedValueAsInt();
                if ( businessId.HasValue )
                {
                    business = personService.Get( businessId.Value );
                }

                if ( business == null )
                {
                    DefinedValueCache dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() );
                    DefinedValueCache dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() );

                    // Create Person
                    business = new Person();
                    business.LastName = txtLastName.Text;
                    business.IsEmailActive = true;
                    business.EmailPreference = EmailPreference.EmailAllowed;
                    business.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid() ).Id;
                    if ( dvcConnectionStatus != null )
                    {
                        business.ConnectionStatusValueId = dvcConnectionStatus.Id;
                    }

                    if ( dvcRecordStatus != null )
                    {
                        business.RecordStatusValueId = dvcRecordStatus.Id;
                    }

                    // Create Person/Family
                    familyGroup = PersonService.SaveNewPerson( business, rockContext, null, false );

                    // Get the relationship roles to use
                    var knownRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid() );
                    int businessContactRoleId = knownRelationshipGroupType.Roles
                        .Where( r =>
                            r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT.AsGuid() ) )
                        .Select( r => r.Id )
                        .FirstOrDefault();
                    int businessRoleId = knownRelationshipGroupType.Roles
                        .Where( r =>
                            r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS.AsGuid() ) )
                        .Select( r => r.Id )
                        .FirstOrDefault();
                    int ownerRoleId = knownRelationshipGroupType.Roles
                        .Where( r =>
                            r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid() ) )
                        .Select( r => r.Id )
                        .FirstOrDefault();

                    if ( ownerRoleId > 0 && businessContactRoleId > 0 && businessRoleId > 0 )
                    {
                        // get the known relationship group of the business contact
                        // add the business as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS
                        var contactKnownRelationshipGroup = groupMemberService.Queryable()
                            .Where( g =>
                                g.GroupRoleId == ownerRoleId &&
                                g.PersonId == person.Id )
                            .Select( g => g.Group )
                            .FirstOrDefault();
                        if ( contactKnownRelationshipGroup == null )
                        {
                            // In some cases person may not yet have a know relationship group type
                            contactKnownRelationshipGroup = new Group();
                            groupService.Add( contactKnownRelationshipGroup );
                            contactKnownRelationshipGroup.Name = "Known Relationship";
                            contactKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id;

                            var ownerMember = new GroupMember();
                            ownerMember.PersonId = person.Id;
                            ownerMember.GroupRoleId = ownerRoleId;
                            contactKnownRelationshipGroup.Members.Add( ownerMember );
                        }
                        var groupMember = new GroupMember();
                        groupMember.PersonId = business.Id;
                        groupMember.GroupRoleId = businessRoleId;
                        contactKnownRelationshipGroup.Members.Add( groupMember );

                        // get the known relationship group of the business
                        // add the business contact as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT
                        var businessKnownRelationshipGroup = groupMemberService.Queryable()
                            .Where( g =>
                                g.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER ) ) &&
                                g.PersonId == business.Id )
                            .Select( g => g.Group )
                            .FirstOrDefault();
                        if ( businessKnownRelationshipGroup == null )
                        {
                            // In some cases business may not yet have a know relationship group type
                            businessKnownRelationshipGroup = new Group();
                            groupService.Add( businessKnownRelationshipGroup );
                            businessKnownRelationshipGroup.Name = "Known Relationship";
                            businessKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id;

                            var ownerMember = new GroupMember();
                            ownerMember.PersonId = business.Id;
                            ownerMember.GroupRoleId = ownerRoleId;
                            businessKnownRelationshipGroup.Members.Add( ownerMember );
                        }
                        var businessGroupMember = new GroupMember();
                        businessGroupMember.PersonId = person.Id;
                        businessGroupMember.GroupRoleId = businessContactRoleId;
                        businessKnownRelationshipGroup.Members.Add( businessGroupMember );

                        rockContext.SaveChanges();
                    }
                }

                business.LastName = txtBusinessName.Text;
                business.Email = txtEmail.Text;

                if ( GetAttributeValue( "DisplayPhone" ).AsBooleanOrNull() ?? false )
                {
                    var numberTypeId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK ) ).Id;
                    var phone = business.PhoneNumbers.FirstOrDefault( p => p.NumberTypeValueId == numberTypeId );
                    if ( phone == null )
                    {
                        phone = new PhoneNumber();
                        business.PhoneNumbers.Add( phone );
                        phone.NumberTypeValueId = numberTypeId;
                    }
                    phone.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode );
                    phone.Number = PhoneNumber.CleanNumber( pnbPhone.Number );
                }

                if ( familyGroup == null )
                {
                    var groupLocationService = new GroupLocationService( rockContext );
                    if ( GroupLocationId.HasValue )
                    {
                        familyGroup = groupLocationService.Queryable()
                            .Where( gl => gl.Id == GroupLocationId.Value )
                            .Select( gl => gl.Group )
                            .FirstOrDefault();
                    }
                    else
                    {
                        familyGroup = personService.GetFamilies( business.Id ).FirstOrDefault();
                    }
                }

                rockContext.SaveChanges();

                if ( familyGroup != null )
                {
                    GroupService.AddNewGroupAddress(
                        rockContext,
                        familyGroup,
                        Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK,
                        acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country,
                        false );
                }

                return business;
            }

            return person;
        }
Esempio n. 25
0
        /// <summary>
        /// Gets the Location ID of a location already in Rock. --looks under dbo.group.foreignId then compares group.description with location name.
        /// </summary>
        /// <param name="rlcID">rlc ID </param>
        /// <returns>Location ID</returns>
        private int GetLocationId(int rlcId)
        {
            var lookupContext = new RockContext();
            var groupService = new GroupService(lookupContext);
            var rlcGroup = new Group();
            string rlcIdString = rlcId.ToString();
            rlcGroup = groupService.Queryable().Where(g => g.ForeignId == (rlcIdString)).FirstOrDefault();
            string groupLocation = String.Empty;
            if ( rlcGroup != null ) { groupLocation = rlcGroup.Description; }

            if (!String.IsNullOrWhiteSpace(groupLocation))
            {
                var locationService = new LocationService(lookupContext);
                var location = new List<Location>();
                location = locationService.Queryable().Where(l => l.ParentLocationId.HasValue).ToList();

                switch (groupLocation)
                {
                    case "A201":
                        {
                            return location.Where(l => l.Name == "A201").FirstOrDefault().Id;
                        }
                    case "A202":
                        {
                            return location.Where(l => l.Name == "A202").FirstOrDefault().Id;
                        }
                    case "Area X Basketball":
                        {
                            return location.Where(l => l.Name == "Area X").FirstOrDefault().Id;
                        }
                    case "Area X Main Area":
                        {
                            return location.Where(l => l.Name == "Area X").FirstOrDefault().Id;
                        }
                    case "Auditorium":
                        {
                            return location.Where(l => l.Name == "Auditorium").FirstOrDefault().Id;
                        }
                    case "Auditorium Recording Booth":
                        {
                            return location.Where(l => l.Name == "Auditorium").FirstOrDefault().Id;
                        }
                    case "Auditorium Sound Booth":
                        {
                            return location.Where(l => l.Name == "Auditorium").FirstOrDefault().Id;
                        }
                    case "Bookstore Downstairs":
                        {
                            return location.Where(l => l.Name == "Bookstore").FirstOrDefault().Id;
                        }
                    case "Bookstore Upstairs":
                        {
                            return location.Where(l => l.Name == "Bookstore").FirstOrDefault().Id;
                        }
                    case "Bug 117":
                        {
                            return location.Where(l => l.Name == "Bug").FirstOrDefault().Id;
                        }
                    case "Bunny 114":
                        {
                            return location.Where(l => l.Name == "Bunny").FirstOrDefault().Id;
                        }
                    case "Butterfly 108":
                        {
                            return location.Where(l => l.Name == "Butterfly").FirstOrDefault().Id;
                        }
                    case "C201":
                        {
                            return location.Where(l => l.Name == "C201").FirstOrDefault().Id;
                        }
                    case "C202":
                        {
                            return location.Where(l => l.Name == "C202").FirstOrDefault().Id;
                        }
                    case "C203":
                        {
                            return location.Where(l => l.Name == "C203").FirstOrDefault().Id;
                        }
                    case "Car 1":
                        {
                            return location.Where(l => l.Name == "Car 1").FirstOrDefault().Id;
                        }
                    case "Car 10":
                        {
                            return location.Where(l => l.Name == "Car 10").FirstOrDefault().Id;
                        }
                    case "Car 2":
                        {
                            return location.Where(l => l.Name == "Car 2").FirstOrDefault().Id;
                        }
                    case "Car 3":
                        {
                            return location.Where(l => l.Name == "Car 3").FirstOrDefault().Id;
                        }
                    case "Car 4":
                        {
                            return location.Where(l => l.Name == "Car 4").FirstOrDefault().Id;
                        }
                    case "Car 5":
                        {
                            return location.Where(l => l.Name == "Car 5").FirstOrDefault().Id;
                        }
                    case "Car 6":
                        {
                            return location.Where(l => l.Name == "Car 6").FirstOrDefault().Id;
                        }
                    case "Car 7":
                        {
                            return location.Where(l => l.Name == "Car 7").FirstOrDefault().Id;
                        }
                    case "Car 8":
                        {
                            return location.Where(l => l.Name == "Car 8").FirstOrDefault().Id;
                        }
                    case "Car 9":
                        {
                            return location.Where(l => l.Name == "Car 9").FirstOrDefault().Id;
                        }
                    case "Catapiller 107":
                        {
                            return location.Where( l => l.Name == "Caterpillar" ).FirstOrDefault().Id;
                        }
                    case "Chapel":
                        {
                            return location.Where(l => l.Name == "Chapel").FirstOrDefault().Id;
                        }
                    case "Chapel 101":
                        {
                            return location.Where(l => l.Name == "Chapel 101").FirstOrDefault().Id;
                        }
                    case "Chapel 102":
                        {
                            return location.Where( l => l.Name == "Chapel 102" ).FirstOrDefault().Id;
                        }
                    case "Chapel Hallway":
                        {
                            return location.Where(l => l.Name == "Chapel Entrance").FirstOrDefault().Id;
                        }
                    case "Chapel Sound Booth":
                        {
                            return location.Where(l => l.Name == "Chapel").FirstOrDefault().Id;
                        }
                    //case "Children's Lobby":  //Kayla doesn't know what location this is
                    //    {
                    //        return location.Where(l => l.Name == "A201").FirstOrDefault().Id;
                    //    }
                    case "College House":
                        {
                            return location.Where(l => l.Name == "The College House").FirstOrDefault().Id;
                        }
                    case "Communion Prep Room":
                        {
                            return location.Where(l => l.Name == "Communion Prep Room").FirstOrDefault().Id;
                        }
                    case "Cross Street Classroom":
                        {
                            return location.Where(l => l.Name == "Cross Street").FirstOrDefault().Id;
                        }
                    case "Cross Street Main Area":
                        {
                            return location.Where(l => l.Name == "Cross Street").FirstOrDefault().Id;
                        }
                    case "Crossroads Station Registration":
                        {
                            return location.Where(l => l.Name == "Crossroads Station").FirstOrDefault().Id;
                        }
                    case "Decision Room A":
                        {
                            return location.Where(l => l.Name == "Decision Room - A").FirstOrDefault().Id;
                        }
                    case "Decision Room B":
                        {
                            return location.Where(l => l.Name == "Decision Room - B").FirstOrDefault().Id;
                        }
                    case "Decision Room C":
                        {
                            return location.Where( l => l.Name == "Decision Room - C" ).FirstOrDefault().Id;
                        }
                    case "Duck 116":
                        {
                            return location.Where(l => l.Name == "Duck").FirstOrDefault().Id;
                        }
                    case "Giggleville Hallway":
                        {
                            return location.Where(l => l.Name == "Giggleville").FirstOrDefault().Id;
                        }
                    case "Giggleville Registration":
                        {
                            return location.Where(l => l.Name == "Giggleville").FirstOrDefault().Id;
                        }
                    case "Grand Hall":
                        {
                            return location.Where(l => l.Name == "Grand Hall").FirstOrDefault().Id;
                        }
                    case "Grand Hall 105":
                        {
                            return location.Where(l => l.Name == "Grand Hall").FirstOrDefault().Id;
                        }
                    case "Helping Hands House":
                        {
                            return location.Where(l => l.Name == "Helping Hands").FirstOrDefault().Id;
                        }
                    case "Kitchen":
                        {
                            return location.Where(l => l.Name == "Kitchen").FirstOrDefault().Id;
                        }
                    case "Lamb 115":
                        {
                            return location.Where(l => l.Name == "Lamb").FirstOrDefault().Id;
                        }
                    case "Main Lobby":
                        {
                            return location.Where(l => l.Name == "Main Lobby").FirstOrDefault().Id;
                        }
                    case "Main Lobby Upstairs":
                        {
                            return location.Where(l => l.Name == "Main Lobby").FirstOrDefault().Id;
                        }
                    case "Music Suite Main Area":
                        {
                            return location.Where(l => l.Name == "Music Suite").FirstOrDefault().Id;
                        }
                    case "Music Suite Room B":
                        {
                            return location.Where(l => l.Name == "Music Suite").FirstOrDefault().Id;
                        }
                    case "North Lobby":
                        {
                            return location.Where(l => l.Name == "North Lobby").FirstOrDefault().Id;
                        }
                    case "North Lobby Upstairs":
                        {
                            return location.Where(l => l.Name == "North Lobby").FirstOrDefault().Id;
                        }
                    case "Parking Lot A":
                        {
                            return location.Where(l => l.Name == "Parking Lot A").FirstOrDefault().Id;
                        }
                    case "Parking Lot B":
                        {
                            return location.Where(l => l.Name == "Parking Lot B").FirstOrDefault().Id;
                        }
                    case "Parking Lot C":
                        {
                            return location.Where(l => l.Name == "Parking Lot C").FirstOrDefault().Id;
                        }
                    case "Parking Lot D":
                        {
                            return location.Where(l => l.Name == "Parking Lot D").FirstOrDefault().Id;
                        }
                    case "Patio 1A":
                        {
                            return location.Where(l => l.Name == "Patio 1A").FirstOrDefault().Id;
                        }
                    case "Patio 1B":
                        {
                            return location.Where(l => l.Name == "Patio 1B").FirstOrDefault().Id;
                        }
                    case "Patio 2A":
                        {
                            return location.Where(l => l.Name == "Patio 2A").FirstOrDefault().Id;
                        }
                    case "Patio 2B":
                        {
                            return location.Where(l => l.Name == "Patio 2B").FirstOrDefault().Id;
                        }
                    case "Patio 2C":
                        {
                            return location.Where(l => l.Name == "Patio 2C").FirstOrDefault().Id;
                        }
                    case "Patio 3A":
                        {
                            return location.Where(l => l.Name == "Patio 3A").FirstOrDefault().Id;
                        }
                    case "Patio 3B":
                        {
                            return location.Where(l => l.Name == "Patio 3B").FirstOrDefault().Id;
                        }
                    case "Patio 3C":
                        {
                            return location.Where(l => l.Name == "Patio 3C").FirstOrDefault().Id;
                        }
                    case "Patio 4A":
                        {
                            return location.Where(l => l.Name == "Patio 4A").FirstOrDefault().Id;
                        }
                    case "Patio 4B":
                        {
                            return location.Where(l => l.Name == "Patio 4B").FirstOrDefault().Id;
                        }
                    case "Prayer Room":
                        {
                            return location.Where(l => l.Name == "Prayer Room").FirstOrDefault().Id;
                        }
                    case "Puppy 118":
                        {
                            return location.Where(l => l.Name == "Puppy").FirstOrDefault().Id;
                        }
                    case "South Lobby":
                        {
                            return location.Where(l => l.Name == "South Lobby").FirstOrDefault().Id;
                        }
                    case "Sportcenter":
                        {
                            return location.Where(l => l.Name == "SportCenter").FirstOrDefault().Id;
                        }
                    case "Squirrel 113":
                        {
                            return location.Where(l => l.Name == "Squirrel").FirstOrDefault().Id;
                        }
                    case "Texas Hall - Dallas":
                        {
                            return location.Where(l => l.Name == "Dallas").FirstOrDefault().Id;
                        }
                    case "Texas Hall - Fort Worth":
                        {
                            return location.Where(l => l.Name == "Fort Worth").FirstOrDefault().Id;
                        }
                    case "Texas Hall - Houston":
                        {
                            return location.Where(l => l.Name == "Houston").FirstOrDefault().Id;
                        }
                    case "Texas Hall - San Antonio":
                        {
                            return location.Where(l => l.Name == "San Antonio").FirstOrDefault().Id;
                        }
                    case "Youth Cafe":
                        {
                            return location.Where(l => l.Name == "Doulos").FirstOrDefault().Id;
                        }
                    case "Youth Lobby":
                        {
                            return location.Where(l => l.Name == "Doulos").FirstOrDefault().Id;
                        }
                    case "Youth Main Area":
                        {
                            return location.Where(l => l.Name == "Doulos").FirstOrDefault().Id;
                        }
                    default:
                        return location.Where(l => l.Name == "Main Building").FirstOrDefault().Id;
               }
            }
            else
            {
                var locationService = new LocationService(lookupContext);
                var location = new Location();
                location = locationService.Queryable().Where(l => l.Name == "Main Building").FirstOrDefault();
                return location.Id;
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void ShowResults()
        {
            // Get the group types that we're interested in
            Guid? groupTypeGuid = GetAttributeValue( "GroupType" ).AsGuidOrNull();
            if ( !groupTypeGuid.HasValue )
            {
                ShowError( "A valid Group Type is required." );
                return;
            }

            gGroups.Columns[1].Visible = GetAttributeValue( "ShowDescription" ).AsBoolean();
            gGroups.Columns[2].Visible = GetAttributeValue( "ShowSchedule" ).AsBoolean();
            gGroups.Columns[3].Visible = GetAttributeValue( "ShowCount" ).AsBoolean();
            gGroups.Columns[4].Visible = GetAttributeValue( "ShowAge" ).AsBoolean();

            bool showProximity = GetAttributeValue( "ShowProximity" ).AsBoolean();
            gGroups.Columns[5].Visible = showProximity;  // Distance

            // Get query of groups of the selected group type
            var rockContext = new RockContext();
            var groupService = new GroupService( rockContext );
            var groupQry = groupService
                .Queryable( "GroupLocations.Location" )
                .Where( g => g.IsActive && g.GroupType.Guid.Equals( groupTypeGuid.Value ) && g.IsPublic );

            var groupParameterExpression = groupService.ParameterExpression;
            var schedulePropertyExpression = Expression.Property( groupParameterExpression, "Schedule" );

            var dowFilterControl = phFilterControls.FindControl( "filter_dow" );
            if ( dowFilterControl != null )
            {
                var field = FieldTypeCache.Read( Rock.SystemGuid.FieldType.DAY_OF_WEEK ).Field;

                var filterValues = field.GetFilterValues( dowFilterControl, null, Rock.Reporting.FilterMode.SimpleFilter );
                var expression = field.PropertyFilterExpression( null, filterValues, schedulePropertyExpression, "WeeklyDayOfWeek", typeof( DayOfWeek? ) );
                groupQry = groupQry.Where( groupParameterExpression, expression, null );
            }

            var timeFilterControl = phFilterControls.FindControl( "filter_time" );
            if ( timeFilterControl != null )
            {
                var field = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TIME ).Field;

                var filterValues = field.GetFilterValues( timeFilterControl, null, Rock.Reporting.FilterMode.SimpleFilter );
                var expression = field.PropertyFilterExpression( null, filterValues, schedulePropertyExpression, "WeeklyTimeOfDay", typeof( TimeSpan? ) );
                groupQry = groupQry.Where( groupParameterExpression, expression, null );
            }

            // Filter query by any configured attribute filters
            if ( AttributeFilters != null && AttributeFilters.Any() )
            {
                var attributeValueService = new AttributeValueService( rockContext );
                var parameterExpression = attributeValueService.ParameterExpression;

                foreach ( var attribute in AttributeFilters )
                {
                    var filterControl = phFilterControls.FindControl( "filter_" + attribute.Id.ToString() );
                    if ( filterControl != null )
                    {
                        var filterValues = attribute.FieldType.Field.GetFilterValues( filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter );
                        var expression = attribute.FieldType.Field.AttributeFilterExpression( attribute.QualifierValues, filterValues, parameterExpression );
                        if ( expression != null )
                        {
                            var attributeValues = attributeValueService
                                .Queryable()
                                .Where( v => v.Attribute.Id == attribute.Id );

                            attributeValues = attributeValues.Where( parameterExpression, expression, null );

                            groupQry = groupQry.Where( w => attributeValues.Select( v => v.EntityId ).Contains( w.Id ) );
                        }
                    }
                }
            }

            List<GroupLocation> fences = null;
            List<Group> groups = null;

            // Run query to get list of matching groups
            SortProperty sortProperty = gGroups.SortProperty;
            if ( sortProperty != null )
            {
                groups = groupQry.Sort( sortProperty ).ToList();
            }
            else
            {
                groups = groupQry.OrderBy( g => g.Name ).ToList();
            }

            int? fenceGroupTypeId = GetGroupTypeId( GetAttributeValue( "GeofencedGroupType" ).AsGuidOrNull() );
            bool showMap = GetAttributeValue( "ShowMap" ).AsBoolean();
            bool showFences = showMap && GetAttributeValue( "ShowFence" ).AsBoolean();

            var distances = new Dictionary<int, double>();

            // If we care where these groups are located...
            if ( fenceGroupTypeId.HasValue || showMap || showProximity )
            {
                // Get the location for the address entered
                Location personLocation = null;
                if ( fenceGroupTypeId.HasValue || showProximity )
                {
                    personLocation = new LocationService( rockContext )
                        .Get( acAddress.Street1, acAddress.Street2, acAddress.City,
                            acAddress.State, acAddress.PostalCode, acAddress.Country );
                }

                // If showing a map, and person's location was found, save a mapitem for this location
                FinderMapItem personMapItem = null;
                if ( showMap && personLocation != null && personLocation.GeoPoint != null )
                {
                    var infoWindow = string.Format( @"
            <div style='width:250px'>
            <div class='clearfix'>
            <strong>Your Location</strong>
            <br/>{0}
            </div>
            </div>
            ", personLocation.FormattedHtmlAddress );

                    personMapItem = new FinderMapItem( personLocation );
                    personMapItem.Name = "Your Location";
                    personMapItem.InfoWindow = HttpUtility.HtmlEncode( infoWindow.Replace( Environment.NewLine, string.Empty ).Replace( "\n", string.Empty ).Replace( "\t", string.Empty ) );
                }

                // Get the locations, and optionally calculate the distance for each of the groups
                var groupLocations = new List<GroupLocation>();
                foreach ( var group in groups )
                {
                    foreach ( var groupLocation in group.GroupLocations
                        .Where( gl => gl.Location.GeoPoint != null ) )
                    {
                        groupLocations.Add( groupLocation );

                        if ( showProximity && personLocation != null && personLocation.GeoPoint != null )
                        {
                            double meters = groupLocation.Location.GeoPoint.Distance( personLocation.GeoPoint ) ?? 0.0D;
                            double miles = meters * Location.MilesPerMeter;

                            // If this group already has a distance calculated, see if this location is closer and if so, use it instead
                            if ( distances.ContainsKey( group.Id ) )
                            {
                                if ( distances[group.Id] < miles )
                                {
                                    distances[group.Id] = miles;
                                }
                            }
                            else
                            {
                                distances.Add( group.Id, miles );
                            }
                        }
                    }
                }

                // If groups should be limited by a geofence
                var fenceMapItems = new List<MapItem>();
                if ( fenceGroupTypeId.HasValue )
                {
                    fences = new List<GroupLocation>();
                    if ( personLocation != null && personLocation.GeoPoint != null )
                    {
                        fences = new GroupLocationService( rockContext )
                            .Queryable( "Group,Location" )
                            .Where( gl =>
                                gl.Group.GroupTypeId == fenceGroupTypeId &&
                                gl.Location.GeoFence != null &&
                                personLocation.GeoPoint.Intersects( gl.Location.GeoFence ) )
                            .ToList();
                    }

                    // Limit the group locations to only those locations inside one of the fences
                    groupLocations = groupLocations
                        .Where( gl =>
                            fences.Any( f => gl.Location.GeoPoint.Intersects( f.Location.GeoFence ) ) )
                        .ToList();

                    // Limit the groups to the those that still contain a valid location
                    groups = groups
                        .Where( g =>
                            groupLocations.Any( gl => gl.GroupId == g.Id ) )
                        .ToList();

                    // If the map and fences should be displayed, create a map item for each fence
                    if ( showMap && showFences )
                    {
                        foreach ( var fence in fences )
                        {
                            var mapItem = new FinderMapItem( fence.Location );
                            mapItem.EntityTypeId = EntityTypeCache.Read( "Rock.Model.Group" ).Id;
                            mapItem.EntityId = fence.GroupId;
                            mapItem.Name = fence.Group.Name;
                            fenceMapItems.Add( mapItem );
                        }
                    }
                }

                // if not sorting by ColumnClick and SortByDistance, then sort the groups by distance
                if ( gGroups.SortProperty == null && GetAttributeValue( "SortByDistance" ).AsBoolean() )
                {
                    // only show groups with a known location, and sort those by distance
                    groups = groups.Where( a => distances.Select( b => b.Key ).Contains( a.Id ) ).ToList();
                    groups = groups.OrderBy( a => distances[a.Id] ).ThenBy( a => a.Name ).ToList();
                }

                // if limiting by PageSize, limit to the top X groups
                int? pageSize = ddlPageSize.SelectedValue.AsIntegerOrNull();
                if ( pageSize.HasValue && pageSize > 0 )
                {
                    groups = groups.Take( pageSize.Value ).ToList();
                }

                // If a map is to be shown
                if ( showMap && groups.Any() )
                {

                    Template template = Template.Parse( GetAttributeValue( "MapInfo" ) );

                    bool showDebug = UserCanEdit && GetAttributeValue( "MapInfoDebug" ).AsBoolean();
                    lMapInfoDebug.Visible = showDebug;

                    // Add mapitems for all the remaining valid group locations
                    var groupMapItems = new List<MapItem>();
                    foreach ( var gl in groupLocations )
                    {
                        var group = groups.Where( g => g.Id == gl.GroupId ).FirstOrDefault();
                        if ( group != null )
                        {
                            // Resolve info window lava template
                            var linkedPageParams = new Dictionary<string, string> { { "GroupId", group.Id.ToString() } };
                            var mergeFields = new Dictionary<string, object>();
                            mergeFields.Add( "Group", gl.Group );
                            mergeFields.Add( "Location", gl.Location );

                            Dictionary<string, object> linkedPages = new Dictionary<string, object>();
                            linkedPages.Add( "GroupDetailPage", LinkedPageRoute( "GroupDetailPage" ) );

                            if ( _targetPersonGuid != Guid.Empty )
                            {
                                linkedPages.Add( "RegisterPage", LinkedPageUrl( "RegisterPage", _urlParms ) );
                            }
                            else
                            {
                                linkedPages.Add( "RegisterPage", LinkedPageUrl( "RegisterPage", null ) );
                            }

                            mergeFields.Add( "LinkedPages", linkedPages );

                            // add collection of allowed security actions
                            Dictionary<string, object> securityActions = new Dictionary<string, object>();
                            securityActions.Add( "View", group.IsAuthorized( Authorization.VIEW, CurrentPerson ) );
                            securityActions.Add( "Edit", group.IsAuthorized( Authorization.EDIT, CurrentPerson ) );
                            securityActions.Add( "Administrate", group.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson ) );
                            mergeFields.Add( "AllowedActions", securityActions );

                            string infoWindow = template.Render( Hash.FromDictionary( mergeFields ) );

                            if ( showDebug )
                            {
                                lMapInfoDebug.Text = mergeFields.lavaDebugInfo( null, "<span class='label label-info'>Lava used for the map window.</span>", "" );
                                showDebug = false;
                            }

                            // Add a map item for group
                            var mapItem = new FinderMapItem( gl.Location );
                            mapItem.EntityTypeId = EntityTypeCache.Read( "Rock.Model.Group" ).Id;
                            mapItem.EntityId = group.Id;
                            mapItem.Name = group.Name;
                            mapItem.InfoWindow = HttpUtility.HtmlEncode( infoWindow.Replace( Environment.NewLine, string.Empty ).Replace( "\n", string.Empty ).Replace( "\t", string.Empty ) );
                            groupMapItems.Add( mapItem );
                        }
                    }

                    // Show the map
                    Map( personMapItem, fenceMapItems, groupMapItems );
                    pnlMap.Visible = true;
                }
                else
                {
                    pnlMap.Visible = false;
                }
            }
            else
            {
                pnlMap.Visible = false;
            }

            // Should a lava output be displayed
            if ( GetAttributeValue( "ShowLavaOutput" ).AsBoolean() )
            {
                string template = GetAttributeValue( "LavaOutput" );

                var mergeFields = new Dictionary<string, object>();
                if ( fences != null )
                {
                    mergeFields.Add( "Fences", fences.Select( f => f.Group ).ToList() );
                }
                else
                {
                    mergeFields.Add( "Fences", new Dictionary<string, object>() );
                }

                mergeFields.Add( "Groups", groups );

                Dictionary<string, object> linkedPages = new Dictionary<string, object>();
                linkedPages.Add( "GroupDetailPage", LinkedPageUrl( "GroupDetailPage", null ) );

                if ( _targetPersonGuid != Guid.Empty )
                {
                    linkedPages.Add( "RegisterPage", LinkedPageUrl( "RegisterPage", _urlParms ) );
                }
                else
                {
                    linkedPages.Add( "RegisterPage", LinkedPageUrl( "RegisterPage", null ) );
                }

                mergeFields.Add( "LinkedPages", linkedPages );

                lLavaOverview.Text = template.ResolveMergeFields( mergeFields );

                bool showDebug = UserCanEdit && GetAttributeValue( "LavaOutputDebug" ).AsBoolean();
                lLavaOutputDebug.Visible = showDebug;
                if ( showDebug )
                {
                    lLavaOutputDebug.Text = mergeFields.lavaDebugInfo( null, "<span class='label label-info'>Lava used for the summary info.</span>" );
                }

                pnlLavaOutput.Visible = true;
            }
            else
            {
                pnlLavaOutput.Visible = false;
            }

            // Should a grid be displayed
            if ( GetAttributeValue( "ShowGrid" ).AsBoolean() )
            {
                pnlGrid.Visible = true;

                // Save the groups into the grid's object list since it is not being bound to actual group objects
                gGroups.ObjectList = new Dictionary<string, object>();
                groups.ForEach( g => gGroups.ObjectList.Add( g.Id.ToString(), g ) );

                // Bind the grid
                gGroups.DataSource = groups.Select( g =>
                {
                    var qryMembers = new GroupMemberService( rockContext ).Queryable().Where( a => a.GroupId == g.Id );
                    var groupType = GroupTypeCache.Read( g.GroupTypeId );

                    return new
                    {
                        Id = g.Id,
                        Name = g.Name,
                        GroupTypeName = groupType.Name,
                        GroupOrder = g.Order,
                        GroupTypeOrder = groupType.Order,
                        Description = g.Description,
                        IsSystem = g.IsSystem,
                        IsActive = g.IsActive,
                        GroupRole = string.Empty,
                        DateAdded = DateTime.MinValue,
                        Schedule = g.Schedule,
                        MemberCount = qryMembers.Count(),
                        AverageAge = Math.Round( qryMembers.Select( m => m.Person.BirthDate ).ToList().Select( a => Person.GetAge( a ) ).Average() ?? 0.0D ),
                        Distance = distances.Where( d => d.Key == g.Id )
                            .Select( d => d.Value ).FirstOrDefault()
                    };
                } ).ToList();
                gGroups.DataBind();
            }
            else
            {
                pnlGrid.Visible = false;
            }

            // Show the results
            pnlResults.Visible = true;
        }
Esempio n. 27
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            rockContext.WrapTransaction( () =>
            {
                var personService = new PersonService( rockContext );

                var changes = new List<string>();

                var person = personService.Get( CurrentPersonId ?? 0 );
                if ( person != null )
                {
                    int? orphanedPhotoId = null;
                    if ( person.PhotoId != imgPhoto.BinaryFileId )
                    {
                        orphanedPhotoId = person.PhotoId;
                        person.PhotoId = imgPhoto.BinaryFileId;

                        if ( orphanedPhotoId.HasValue )
                        {
                            if ( person.PhotoId.HasValue )
                            {
                                changes.Add( "Modified the photo." );
                            }
                            else
                            {
                                changes.Add( "Deleted the photo." );
                            }
                        }
                        else if ( person.PhotoId.HasValue )
                        {
                            changes.Add( "Added a photo." );
                        }
                    }

                    int? newTitleId = ddlTitle.SelectedValueAsInt();
                    History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) );
                    person.TitleValueId = newTitleId;

                    History.EvaluateChange( changes, "First Name", person.FirstName, tbFirstName.Text );
                    person.FirstName = tbFirstName.Text;

                    History.EvaluateChange(changes, "Nick Name", person.NickName, tbNickName.Text);
                    person.NickName = tbNickName.Text;

                    History.EvaluateChange( changes, "Last Name", person.LastName, tbLastName.Text );
                    person.LastName = tbLastName.Text;

                    int? newSuffixId = ddlSuffix.SelectedValueAsInt();
                    History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) );
                    person.SuffixValueId = newSuffixId;

                    var birthMonth = person.BirthMonth;
                    var birthDay = person.BirthDay;
                    var birthYear = person.BirthYear;

                    var birthday = bpBirthDay.SelectedDate;
                    if ( birthday.HasValue )
                    {
                        // If setting a future birthdate, subtract a century until birthdate is not greater than today.
                        var today = RockDateTime.Today;
                        while ( birthday.Value.CompareTo( today ) > 0 )
                        {
                            birthday = birthday.Value.AddYears( -100 );
                        }

                        person.BirthMonth = birthday.Value.Month;
                        person.BirthDay = birthday.Value.Day;
                        if ( birthday.Value.Year != DateTime.MinValue.Year )
                        {
                            person.BirthYear = birthday.Value.Year;
                        }
                        else
                        {
                            person.BirthYear = null;
                        }
                    }
                    else
                    {
                        person.SetBirthDate( null );
                    }

                    History.EvaluateChange( changes, "Birth Month", birthMonth, person.BirthMonth );
                    History.EvaluateChange( changes, "Birth Day", birthDay, person.BirthDay );
                    History.EvaluateChange( changes, "Birth Year", birthYear, person.BirthYear );

                    var newGender = rblGender.SelectedValue.ConvertToEnum<Gender>();
                    History.EvaluateChange( changes, "Gender", person.Gender, newGender );
                    person.Gender = newGender;

                    var phoneNumberTypeIds = new List<int>();

                    bool smsSelected = false;

                    foreach ( RepeaterItem item in rContactInfo.Items )
                    {
                        HiddenField hfPhoneType = item.FindControl( "hfPhoneType" ) as HiddenField;
                        PhoneNumberBox pnbPhone = item.FindControl( "pnbPhone" ) as PhoneNumberBox;
                        CheckBox cbUnlisted = item.FindControl( "cbUnlisted" ) as CheckBox;
                        CheckBox cbSms = item.FindControl( "cbSms" ) as CheckBox;

                        if ( hfPhoneType != null &&
                            pnbPhone != null &&
                            cbSms != null &&
                            cbUnlisted != null )
                        {
                            if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) )
                            {
                                int phoneNumberTypeId;
                                if ( int.TryParse( hfPhoneType.Value, out phoneNumberTypeId ) )
                                {
                                    var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberTypeId );
                                    string oldPhoneNumber = string.Empty;
                                    if ( phoneNumber == null )
                                    {
                                        phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId };
                                        person.PhoneNumbers.Add( phoneNumber );
                                    }
                                    else
                                    {
                                        oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                                    }

                                    phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode );
                                    phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number );

                                    // Only allow one number to have SMS selected
                                    if ( smsSelected )
                                    {
                                        phoneNumber.IsMessagingEnabled = false;
                                    }
                                    else
                                    {
                                        phoneNumber.IsMessagingEnabled = cbSms.Checked;
                                        smsSelected = cbSms.Checked;
                                    }

                                    phoneNumber.IsUnlisted = cbUnlisted.Checked;
                                    phoneNumberTypeIds.Add( phoneNumberTypeId );

                                    History.EvaluateChange(
                                        changes,
                                        string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumberTypeId ) ),
                                        oldPhoneNumber,
                                        phoneNumber.NumberFormattedWithCountryCode );
                                }
                            }
                        }
                    }

                    // Remove any blank numbers
                    var phoneNumberService = new PhoneNumberService( rockContext );
                    foreach ( var phoneNumber in person.PhoneNumbers
                        .Where( n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains( n.NumberTypeValueId.Value ) )
                        .ToList() )
                    {
                        History.EvaluateChange(
                            changes,
                            string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumber.NumberTypeValueId ) ),
                            phoneNumber.ToString(),
                            string.Empty );

                        person.PhoneNumbers.Remove( phoneNumber );
                        phoneNumberService.Delete( phoneNumber );
                    }

                    History.EvaluateChange( changes, "Email", person.Email, tbEmail.Text );
                    person.Email = tbEmail.Text.Trim();

                    var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum<EmailPreference>();
                    History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference );
                    person.EmailPreference = newEmailPreference;

                    if ( person.IsValid )
                    {
                        if ( rockContext.SaveChanges() > 0 )
                        {
                            if ( changes.Any() )
                            {
                                HistoryService.SaveChanges(
                                    rockContext,
                                    typeof( Person ),
                                    Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                    person.Id,
                                    changes );
                            }

                            if ( orphanedPhotoId.HasValue )
                            {
                                BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                                var binaryFile = binaryFileService.Get( orphanedPhotoId.Value );
                                if ( binaryFile != null )
                                {
                                    // marked the old images as IsTemporary so they will get cleaned up later
                                    binaryFile.IsTemporary = true;
                                    rockContext.SaveChanges();
                                }
                            }

                            // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up
                            if ( imgPhoto.CropBinaryFileId.HasValue )
                            {
                                if ( imgPhoto.CropBinaryFileId != person.PhotoId )
                                {
                                    BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                                    var binaryFile = binaryFileService.Get( imgPhoto.CropBinaryFileId.Value );
                                    if ( binaryFile != null && binaryFile.IsTemporary )
                                    {
                                        string errorMessage;
                                        if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) )
                                        {
                                            binaryFileService.Delete( binaryFile );
                                            rockContext.SaveChanges();
                                        }
                                    }
                                }
                            }
                        }

                        // save address
                        if ( pnlAddress.Visible )
                        {
                            Guid? familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();
                            if ( familyGroupTypeGuid.HasValue )
                            {
                                var familyGroup = new GroupService( rockContext ).Queryable()
                                                .Where( f => f.GroupType.Guid == familyGroupTypeGuid.Value
                                                    && f.Members.Any( m => m.PersonId == person.Id ) )
                                                .FirstOrDefault();
                                if ( familyGroup != null )
                                {
                                    Guid? addressTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull();
                                    if ( addressTypeGuid.HasValue )
                                    {
                                        var groupLocationService = new GroupLocationService( rockContext );

                                        var dvHomeAddressType = DefinedValueCache.Read( addressTypeGuid.Value );
                                        var familyAddress = groupLocationService.Queryable().Where( l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id ).FirstOrDefault();
                                        if ( familyAddress != null && string.IsNullOrWhiteSpace( acAddress.Street1 ) )
                                        {
                                            // delete the current address
                                            History.EvaluateChange( changes, familyAddress.GroupLocationTypeValue.Value + " Location", familyAddress.Location.ToString(), string.Empty );
                                            groupLocationService.Delete( familyAddress );
                                            rockContext.SaveChanges();
                                        }
                                        else
                                        {
                                            if ( !string.IsNullOrWhiteSpace( acAddress.Street1 ) )
                                            {
                                                if ( familyAddress == null )
                                                {
                                                    familyAddress = new GroupLocation();
                                                    groupLocationService.Add( familyAddress );
                                                    familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id;
                                                    familyAddress.GroupId = familyGroup.Id;
                                                    familyAddress.IsMailingLocation = true;
                                                    familyAddress.IsMappedLocation = true;
                                                }
                                                else if ( hfStreet1.Value != string.Empty ) {

                                                    // user clicked move so create a previous address
                                                    var previousAddress = new GroupLocation();
                                                    groupLocationService.Add( previousAddress );

                                                    var previousAddressValue = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid() );
                                                    if ( previousAddressValue  != null )
                                                    {
                                                        previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                                        previousAddress.GroupId = familyGroup.Id;

                                                        Location previousAddressLocation = new Location();
                                                        previousAddressLocation.Street1 = hfStreet1.Value;
                                                        previousAddressLocation.Street2 = hfStreet2.Value;
                                                        previousAddressLocation.City = hfCity.Value;
                                                        previousAddressLocation.State = hfState.Value;
                                                        previousAddressLocation.PostalCode = hfPostalCode.Value;
                                                        previousAddressLocation.Country = hfCountry.Value;

                                                        previousAddress.Location = previousAddressLocation;
                                                    }
                                                }

                                                familyAddress.IsMailingLocation = cbIsMailingAddress.Checked;
                                                familyAddress.IsMappedLocation = cbIsPhysicalAddress.Checked;

                                                var updatedHomeAddress = new Location();
                                                acAddress.GetValues( updatedHomeAddress );

                                                History.EvaluateChange( changes, dvHomeAddressType.Value + " Location", familyAddress.Location != null ? familyAddress.Location.ToString() : string.Empty, updatedHomeAddress.ToString() );

                                                familyAddress.Location = updatedHomeAddress;
                                                rockContext.SaveChanges();
                                            }
                                        }

                                        HistoryService.SaveChanges(
                                            rockContext,
                                            typeof( Person ),
                                            Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                            person.Id,
                                            changes );
                                    }
                                }
                            }
                        }

                        NavigateToParentPage();
                    }
                }
            } );
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            try
            {
                var groupGuid = GetAttributeValue( "Group" ).AsGuidOrNull();
                string personKey = PageParameter( "Person" );

                if ( !groupGuid.HasValue )
                {
                    ShowConfigError( "The 'Group' configuration for this block has not been set." );
                }
                else if ( string.IsNullOrWhiteSpace( personKey ) )
                {
                    ShowError( "Missing Parameter Value" );
                }
                else
                {
                    RockContext rockContext = new RockContext();
                    Person targetPerson = null;
                    targetPerson = new PersonService( rockContext ).GetByUrlEncodedKey( personKey );

                    if ( targetPerson == null )
                    {
                        ShowError( "We can't find a record in our system for you." );
                    }
                    else
                    {
                        GroupService groupService = new GroupService( rockContext );
                        Group group = groupService.Get( groupGuid.Value );
                        if ( group == null )
                        {
                            ShowConfigError( "The 'Group' configuration for this block is incorrect." );
                        }
                        else
                        {
                            AddOrUpdatePersonInGroup( targetPerson, group, rockContext );
                        }
                    }
                }
            }
            catch ( System.FormatException )
            {
                ShowError( "Something is wrong with that link.  Are you sure you copied it correctly?" );
            }
            catch ( SystemException ex )
            {
                ShowError( ex.Message );
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute( IJobExecutionContext context )
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            var groupType = GroupTypeCache.Read( dataMap.GetString( "GroupType" ).AsGuid() );
            int attendanceRemindersSent = 0;
            if ( groupType.TakesAttendance && groupType.SendAttendanceReminder )
            {

                // Get the occurrence dates that apply
                var dates = new List<DateTime>();
                dates.Add( RockDateTime.Today );
                try
                {
                    string[] reminderDays = dataMap.GetString( "SendReminders" ).Split( ',' );
                    foreach ( string reminderDay in reminderDays )
                    {
                        if ( reminderDay.Trim() != string.Empty )
                        {
                            var reminderDate = RockDateTime.Today.AddDays( 0 - Convert.ToInt32( reminderDay ) );
                            if ( !dates.Contains( reminderDate ) )
                            {
                                dates.Add( reminderDate );
                            }
                        }
                    }
                }
                catch { }

                var rockContext = new RockContext();
                var groupService = new GroupService( rockContext );
                var groupMemberService = new GroupMemberService( rockContext );
                var scheduleService = new ScheduleService( rockContext );
                var attendanceService = new AttendanceService( rockContext );

                var startDate = dates.Min();
                var endDate = dates.Max().AddDays( 1 );

                // Find all 'occurrences' for the groups that occur on the affected dates
                var occurrences = new Dictionary<int, List<DateTime>>();
                foreach ( var group in groupService
                    .Queryable( "Schedule" ).AsNoTracking()
                    .Where( g =>
                        g.GroupTypeId == groupType.Id &&
                        g.IsActive &&
                        g.Schedule != null &&
                        g.Members.Any( m =>
                            m.GroupMemberStatus == GroupMemberStatus.Active &&
                            m.GroupRole.IsLeader &&
                            m.Person.Email != null &&
                            m.Person.Email != "" ) ) )
                {
                    // Add the group
                    occurrences.Add( group.Id, new List<DateTime>() );

                    // Check for a iCal schedule
                    if ( !string.IsNullOrWhiteSpace( group.Schedule.iCalendarContent ) )
                    {
                        // If schedule has an iCal schedule, get occurrences between first and last dates
                        foreach ( var occurrence in group.Schedule.GetOccurrences( startDate, endDate ) )
                        {
                            var startTime = occurrence.Period.StartTime.Value;
                            if ( dates.Contains( startTime.Date ) )
                            {
                                occurrences[group.Id].Add( startTime );
                            }
                        }
                    }
                    else
                    {
                        // if schedule does not have an iCal, then check for weekly schedule and calculate occurrences starting with first attendance or current week
                        if ( group.Schedule.WeeklyDayOfWeek.HasValue )
                        {
                            foreach ( var date in dates )
                            {
                                if ( date.DayOfWeek == group.Schedule.WeeklyDayOfWeek.Value )
                                {
                                    var startTime = date;
                                    if ( group.Schedule.WeeklyTimeOfDay.HasValue )
                                    {
                                        startTime = startTime.Add( group.Schedule.WeeklyTimeOfDay.Value );
                                    }
                                    occurrences[group.Id].Add( startTime );
                                }
                            }
                        }
                    }
                }

                // Remove any occurrences during group type exclusion date ranges
                foreach ( var exclusion in groupType.GroupScheduleExclusions )
                {
                    if ( exclusion.Start.HasValue && exclusion.End.HasValue )
                    {
                        foreach ( var keyVal in occurrences )
                        {
                            foreach ( var occurrenceDate in keyVal.Value.ToList() )
                            {
                                if ( occurrenceDate >= exclusion.Start.Value &&
                                    occurrenceDate < exclusion.End.Value.AddDays( 1 ) )
                                {
                                    keyVal.Value.Remove( occurrenceDate );
                                }
                            }
                        }
                    }
                }

                // Remove any 'occurrenes' that already have attendance data entered
                foreach ( var occurrence in attendanceService
                    .Queryable().AsNoTracking()
                    .Where( a =>
                        a.StartDateTime >= startDate &&
                        a.StartDateTime < endDate &&
                        occurrences.Keys.Contains( a.GroupId.Value ) &&
                        a.ScheduleId.HasValue )
                    .Select( a => new
                    {
                        GroupId = a.GroupId.Value,
                        a.StartDateTime
                    } )
                    .Distinct()
                    .ToList() )
                {
                    occurrences[occurrence.GroupId].RemoveAll( d => d.Date == occurrence.StartDateTime.Date );
                }

                // Get the groups that have occurrences
                var groupIds = occurrences.Where( o => o.Value.Any() ).Select( o => o.Key ).ToList();

                // Get the leaders of those groups
                var leaders = groupMemberService
                    .Queryable( "Group,Person" ).AsNoTracking()
                    .Where( m =>
                        groupIds.Contains( m.GroupId ) &&
                        m.GroupMemberStatus == GroupMemberStatus.Active &&
                        m.GroupRole.IsLeader &&
                        m.Person.Email != null &&
                        m.Person.Email != "" )
                    .ToList();

                // Loop through the leaders
                foreach ( var leader in leaders )
                {
                    foreach ( var group in occurrences.Where( o => o.Key == leader.GroupId ) )
                    {
                        var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(  null, leader.Person );
                        mergeObjects.Add( "Person", leader.Person );
                        mergeObjects.Add( "Group", leader.Group );
                        mergeObjects.Add( "Occurrence", group.Value.Max() );

                        var recipients = new List<RecipientData>();
                        recipients.Add( new RecipientData( leader.Person.Email, mergeObjects ) );

                        Email.Send( dataMap.GetString( "SystemEmail" ).AsGuid(), recipients );
                        attendanceRemindersSent++;

                    }
                }
            }

            context.Result = string.Format( "{0} attendance reminders sent", attendanceRemindersSent );
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            if ( !Page.IsPostBack )
            {
                RockContext rockContext = new RockContext();

                Group group = null;
                Guid personGuid = Guid.Empty;

                // get group from url
                if ( Request["GroupId"] != null || Request["GroupGuid"] != null )
                {
                    if ( Request["GroupId"] != null )
                    {
                        int groupId = 0;
                        if ( Int32.TryParse( Request["GroupId"], out groupId ) )
                        {
                            group = new GroupService( rockContext ).Queryable().Where( g => g.Id == groupId ).FirstOrDefault();
                        }
                    }
                    else
                    {
                        Guid groupGuid = Request["GroupGuid"].AsGuid();
                        group = new GroupService( rockContext ).Queryable().Where( g => g.Guid == groupGuid ).FirstOrDefault();
                    }
                }
                else
                {
                    Guid groupGuid = Guid.Empty;
                    if ( Guid.TryParse( GetAttributeValue( "DefaultGroup" ), out groupGuid ) ) {
                        group = new GroupService( rockContext ).Queryable().Where( g => g.Guid == groupGuid ).FirstOrDefault(); ;
                    }
                }

                if ( group == null )
                {
                    lAlerts.Text = "Could not determine the group to add to.";
                    return;
                }

                // get person
                Person person = null;

                if ( !string.IsNullOrWhiteSpace(Request["PersonGuid"]) )
                {
                    person = new PersonService( rockContext ).Get( Request["PersonGuid"].AsGuid() );
                }

                if ( person == null )
                {
                    lAlerts.Text += "A person could not be found for the identifier provided.";
                    return;
                }

                // hide alert
                divAlert.Visible = false;

                // get status
                var groupMemberStatus = this.GetAttributeValue( "GroupMemberStatus" ).ConvertToEnum<GroupMemberStatus>( GroupMemberStatus.Active );

                // load merge fields
                var mergeFields = new Dictionary<string, object>();
                mergeFields.Add( "Group", group );
                mergeFields.Add( "Person", person );
                mergeFields.Add( "CurrentPerson", CurrentPerson );

                // show debug info?
                bool enableDebug = GetAttributeValue( "EnableDebug" ).AsBoolean();
                if ( enableDebug && IsUserAuthorized( Authorization.EDIT ) )
                {
                    lDebug.Visible = true;
                    lDebug.Text = mergeFields.lavaDebugInfo();
                }

                var groupMemberService = new GroupMemberService(rockContext);

                var groupMemberList = groupMemberService.Queryable()
                                        .Where( m => m.GroupId == group.Id && m.PersonId == person.Id )
                                        .ToList();

                if (groupMemberList.Count > 0 )
                {
                    foreach(var groupMember in groupMemberList )
                    {
                        if ( GetAttributeValue( "Inactivate" ).AsBoolean() )
                        {
                            groupMember.GroupMemberStatus = GroupMemberStatus.Inactive;
                        }
                        else
                        {
                            groupMemberService.Delete( groupMember );
                        }

                        rockContext.SaveChanges();
                    }

                    lContent.Text = GetAttributeValue( "SuccessMessage" ).ResolveMergeFields( mergeFields );
                }
                else
                {
                    if ( GetAttributeValue( "WarnWhenNotInGroup").AsBoolean() )
                    {
                        lContent.Text = GetAttributeValue( "NotInGroupMessage" ).ResolveMergeFields( mergeFields );
                    }
                    else
                    {
                        lContent.Text = GetAttributeValue( "SuccessMessage" ).ResolveMergeFields( mergeFields );
                    }
                }
            }
        }