GetByEntityTypeId() публичный Метод

Returns a queryable collection of Rock.Model.Attribute">Attributes by
public GetByEntityTypeId ( int entityTypeId ) : IQueryable
entityTypeId int A representing the EntityTypeId of the to search by.
Результат IQueryable
Пример #1
0
            /// <summary>
            /// Called after the save operation has been executed
            /// </summary>
            /// <remarks>
            /// This method is only called if <see cref="M:Rock.Data.EntitySaveHook`1.PreSave" /> returns
            /// without error.
            /// </remarks>
            protected override void PostSave()
            {
                if (this.State == EntityContextState.Deleted)
                {
                    var qualifierValue     = Entity.Id.ToString();
                    var rockContext        = ( RockContext )this.RockContext;
                    var attributeService   = new AttributeService(rockContext);
                    var existingAttributes = attributeService.GetByEntityTypeId(new ConnectionRequest().TypeId, true)
                                             .AsQueryable()
                                             .Where(a =>
                                                    a.EntityTypeQualifierColumn.Equals("ConnectionTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                    a.EntityTypeQualifierValue.Equals(qualifierValue))
                                             .OrderBy(a => a.Order)
                                             .ThenBy(a => a.Name)
                                             .ToList();

                    foreach (var attr in existingAttributes)
                    {
                        attributeService.Delete(attr);
                        rockContext.SaveChanges();
                    }
                }

                base.PostSave();
            }
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="groupType">Type of the group.</param>
        private void ShowEditDetails( GroupType groupType )
        {
            hlType.Visible = false;
            if ( groupType.Id == 0 )
            {
                lReadOnlyTitle.Text = ActionTitle.Add( GroupType.FriendlyTypeName ).FormatAsHtmlTitle();
                if ( groupType.GroupTypePurposeValue != null )
                {
                    hlType.Text = groupType.GroupTypePurposeValue.Value;
                    hlType.Visible = true;
                }
            }
            else
            {
                lReadOnlyTitle.Text = groupType.Name.FormatAsHtmlTitle();
            }

            SetEditMode( true );

            var rockContext = new RockContext();

            var groupTypeService = new GroupTypeService( rockContext );
            var attributeService = new AttributeService( rockContext );

            LoadDropDowns( groupType.Id );

            // General
            tbName.ReadOnly = groupType.IsSystem;
            tbName.Text = groupType.Name;

            tbDescription.ReadOnly = groupType.IsSystem;
            tbDescription.Text = groupType.Description;

            tbGroupTerm.ReadOnly = groupType.IsSystem;
            tbGroupTerm.Text = groupType.GroupTerm;

            tbGroupMemberTerm.ReadOnly = groupType.IsSystem;
            tbGroupMemberTerm.Text = groupType.GroupMemberTerm;

            ddlGroupTypePurpose.Enabled = !groupType.IsSystem;
            ddlGroupTypePurpose.SetValue( groupType.GroupTypePurposeValueId );

            ChildGroupTypesDictionary = new Dictionary<int, string>();
            groupType.ChildGroupTypes.ToList().ForEach( a => ChildGroupTypesDictionary.Add( a.Id, a.Name ) );
            BindChildGroupTypesGrid();

            // Display
            cbShowInGroupList.Checked = groupType.ShowInGroupList;
            cbShowInNavigation.Checked = groupType.ShowInNavigation;
            tbIconCssClass.Text = groupType.IconCssClass;

            // Locations
            cbAllowMultipleLocations.Enabled = !groupType.IsSystem;
            cbAllowMultipleLocations.Checked = groupType.AllowMultipleLocations;

            cblScheduleTypes.Enabled = !groupType.IsSystem;
            foreach ( ListItem li in cblScheduleTypes.Items )
            {
                ScheduleType scheduleType = (ScheduleType)li.Value.AsInteger();
                li.Selected = ( groupType.AllowedScheduleTypes & scheduleType ) == scheduleType;
            }

            ScheduleExclusionDictionary = new Dictionary<Guid, DateRange>();
            groupType.GroupScheduleExclusions.ToList().ForEach( s => ScheduleExclusionDictionary.Add( s.Guid, new DateRange( s.StartDate, s.EndDate ) ) );
            BindScheduleExclusionsGrid();

            cblLocationSelectionModes.Enabled = !groupType.IsSystem;
            foreach ( ListItem li in cblLocationSelectionModes.Items )
            {
                GroupLocationPickerMode mode = (GroupLocationPickerMode)li.Value.AsInteger();
                li.Selected = ( groupType.LocationSelectionMode & mode ) == mode;
            }

            LocationTypesDictionary = new Dictionary<int, string>();
            groupType.LocationTypes.ToList().ForEach( a => LocationTypesDictionary.Add( a.LocationTypeValueId, a.LocationTypeValue.Value ) );
            BindLocationTypesGrid();

            // Support Location Schedules
            cbEnableLocationSchedules.Enabled = !groupType.IsSystem;
            cbEnableLocationSchedules.Checked = groupType.EnableLocationSchedules ?? false;

            // Check In
            cbTakesAttendance.Checked = groupType.TakesAttendance;
            cbSendAttendanceReminder.Checked = groupType.SendAttendanceReminder;
            ddlAttendanceRule.SetValue( (int)groupType.AttendanceRule );
            ddlPrintTo.SetValue( (int)groupType.AttendancePrintTo );

            // Attributes
            gtpInheritedGroupType.Enabled = !groupType.IsSystem;
            gtpInheritedGroupType.SelectedGroupTypeId = groupType.InheritedGroupTypeId;

            var groupTypeRoles = new List<GroupTypeRole>();
            foreach ( var role in groupType.Roles )
            {
                role.LoadAttributes();
                groupTypeRoles.Add( role );
            }
            GroupTypeRolesState = new ViewStateList<GroupTypeRole>();
            GroupTypeRolesState.AddAll( groupTypeRoles );

            BindGroupTypeRolesGrid();

            string qualifierValue = groupType.Id.ToString();

            GroupTypeAttributesState = new ViewStateList<Attribute>();
            GroupTypeAttributesState.AddAll( attributeService.GetByEntityTypeId( new GroupType().TypeId ).AsQueryable()
                .Where( a =>
                    a.EntityTypeQualifierColumn.Equals( "Id", StringComparison.OrdinalIgnoreCase ) &&
                    a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                .OrderBy( a => a.Order )
                .ThenBy( a => a.Name )
                .ToList() );
            BindGroupTypeAttributesGrid();

            GroupAttributesState = new ViewStateList<Attribute>();
            GroupAttributesState.AddAll( attributeService.GetByEntityTypeId( new Group().TypeId ).AsQueryable()
                .Where( a =>
                    a.EntityTypeQualifierColumn.Equals( "GroupTypeId", StringComparison.OrdinalIgnoreCase ) &&
                    a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                .OrderBy( a => a.Order )
                .ThenBy( a => a.Name )
                .ToList() );
            BindGroupAttributesGrid();

            GroupMemberAttributesState = new ViewStateList<Attribute>();
            GroupMemberAttributesState.AddAll( attributeService.GetByEntityTypeId( new GroupMember().TypeId ).AsQueryable()
                .Where( a =>
                    a.EntityTypeQualifierColumn.Equals( "GroupTypeId", StringComparison.OrdinalIgnoreCase ) &&
                    a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                .OrderBy( a => a.Order )
                .ThenBy( a => a.Name )
                .ToList() );
            BindGroupMemberAttributesGrid();

            BindInheritedAttributes( groupType.InheritedGroupTypeId, groupTypeService, attributeService );
        }
Пример #3
0
        private void LoadStateDetails( WorkflowType workflowType, RockContext rockContext )
        {
            if ( workflowType != null )
            {
                var attributeService = new AttributeService( rockContext );
                AttributesState = attributeService
                    .GetByEntityTypeId( new Workflow().TypeId ).AsQueryable()
                    .Where( a =>
                        a.EntityTypeQualifierColumn.Equals( "WorkflowTypeId", StringComparison.OrdinalIgnoreCase ) &&
                        a.EntityTypeQualifierValue.Equals( workflowType.Id.ToString() ) )
                    .OrderBy( a => a.Order )
                    .ThenBy( a => a.Name )
                    .ToList();

                ActivityTypesState = workflowType.ActivityTypes.OrderBy( a => a.Order ).ToList();
                ActivityAttributesState = new Dictionary<Guid, List<Attribute>>();

                foreach ( var activityType in ActivityTypesState )
                {
                    var activityTypeAttributes = attributeService
                        .GetByEntityTypeId( new WorkflowActivity().TypeId ).AsQueryable()
                        .Where( a =>
                            a.EntityTypeQualifierColumn.Equals( "ActivityTypeId", StringComparison.OrdinalIgnoreCase ) &&
                            a.EntityTypeQualifierValue.Equals( activityType.Id.ToString() ) )
                        .OrderBy( a => a.Order )
                        .ThenBy( a => a.Name )
                        .ToList();

                    ActivityAttributesState.Add( activityType.Guid, activityTypeAttributes );

                    foreach ( var actionType in activityType.ActionTypes )
                    {
                        var action = EntityTypeCache.Read( actionType.EntityTypeId );
                        if ( action != null )
                        {
                            Rock.Attribute.Helper.UpdateAttributes( action.GetEntityType(), actionType.TypeId, "EntityTypeId", actionType.EntityTypeId.ToString(), rockContext );
                            actionType.LoadAttributes( rockContext );
                        }
                    }
                }
            }
            else
            {
                AttributesState = new List<Attribute>();
                ActivityTypesState = new List<WorkflowActivityType>();
                ActivityAttributesState = new Dictionary<Guid, List<Attribute>>();
            }
        }
        /// <summary>
        /// Handles the GridReorder event of the gDefinedTypeAttributes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param>
        void gDefinedTypeAttributes_GridReorder( object sender, GridReorderEventArgs e )
        {
            string qualifierValue = hfDefinedTypeId.Value;

            var rockContext = new RockContext();
            var attributeService = new AttributeService( rockContext );

            int order = 0;
            var attributes = attributeService
                .GetByEntityTypeId( new DefinedValue().TypeId ).AsQueryable()
                .Where( a =>
                    a.EntityTypeQualifierColumn.Equals( "DefinedTypeId", StringComparison.OrdinalIgnoreCase ) &&
                    a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                .OrderBy( a => a.Order )
                .ThenBy( a => a.Name )
                .ToList();

            attributes.ForEach( a => a.Order = order++ );

            var movedItem = attributes.Where( a => a.Order == e.OldIndex ).FirstOrDefault();
            if ( movedItem != null )
            {
                if ( e.NewIndex < e.OldIndex )
                {
                    // Moved up
                    foreach ( var otherItem in attributes.Where( a => a.Order < e.OldIndex && a.Order >= e.NewIndex ) )
                    {
                        otherItem.Order = otherItem.Order + 1;
                    }
                }
                else
                {
                    // Moved Down
                    foreach ( var otherItem in attributes.Where( a => a.Order > e.OldIndex && a.Order <= e.NewIndex ) )
                    {
                        otherItem.Order = otherItem.Order - 1;
                    }
                }

                movedItem.Order = e.NewIndex;
                rockContext.SaveChanges();
            }

            BindDefinedTypeAttributesGrid();
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        public void ShowDetail( string itemKey, int itemKeyValue )
        {
            if ( !itemKey.Equals( "marketingCampaignAdTypeId" ) )
            {
                return;
            }

            pnlDetails.Visible = true;
            MarketingCampaignAdType marketingCampaignAdType = null;

            var rockContext = new RockContext();

            if ( !itemKeyValue.Equals( 0 ) )
            {
                marketingCampaignAdType = new MarketingCampaignAdTypeService( rockContext ).Get( itemKeyValue );
                lActionTitle.Text = "Ad Type Detail".FormatAsHtmlTitle();
            }
            else
            {
                marketingCampaignAdType = new MarketingCampaignAdType { Id = 0 };
                lActionTitle.Text = "Ad Type Detail".FormatAsHtmlTitle();
            }

            LoadDropDowns();

            // load data into UI controls
            AttributesState = new ViewStateList<Attribute>();

            hfMarketingCampaignAdTypeId.Value = marketingCampaignAdType.Id.ToString();
            tbName.Text = marketingCampaignAdType.Name;
            ddlDateRangeType.SetValue( (int)marketingCampaignAdType.DateRangeType );

            AttributeService attributeService = new AttributeService( rockContext );

            string qualifierValue = marketingCampaignAdType.Id.ToString();
            var qry = attributeService.GetByEntityTypeId( new MarketingCampaignAd().TypeId ).AsQueryable()
                .Where( a => a.EntityTypeQualifierColumn.Equals( "MarketingCampaignAdTypeId", StringComparison.OrdinalIgnoreCase )
                && a.EntityTypeQualifierValue.Equals( qualifierValue ) );

            AttributesState.AddAll( qry.ToList() );
            BindMarketingCampaignAdAttributeTypeGrid();

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !IsUserAuthorized( Authorization.EDIT ) )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( MarketingCampaignAdType.FriendlyTypeName );
            }

            if ( marketingCampaignAdType.IsSystem )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem( MarketingCampaignAdType.FriendlyTypeName );
            }

            if ( readOnly )
            {
                lActionTitle.Text = ActionTitle.View( MarketingCampaignAdType.FriendlyTypeName );
                btnCancel.Text = "Close";
            }

            tbName.ReadOnly = readOnly;
            ddlDateRangeType.Enabled = !readOnly;
            gMarketingCampaignAdAttributeTypes.Enabled = !readOnly;

            btnSave.Visible = !readOnly;
        }
Пример #6
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            WorkflowService workflowService = new WorkflowService();
            SortProperty sortProperty = gWorkflows.SortProperty;

            var qry = workflowService.Queryable();

            WorkflowType workflowType = this.ContextEntity<WorkflowType>();

            if ( workflowType == null )
            {
                pnlWorkflowList.Visible = false;
                return;
            }

            // if this isn't currently a persisted workflow type, and there are no records, hide the panel
            if ( !workflowType.IsPersisted )
            {
                if ( qry.Count() == 0 )
                {
                    pnlWorkflowList.Visible = false;
                    return;
                }
            }

            if (!string.IsNullOrWhiteSpace(workflowType.WorkTerm))
            {
                gWorkflows.RowItemText = workflowType.WorkTerm;
                lGridTitle.Text = workflowType.WorkTerm.Pluralize();
            }

            AttributeService attributeService = new AttributeService();

            // add attributes with IsGridColumn to grid
            string qualifierValue = workflowType.Id.ToString();
            var qryWorkflowTypeAttributes = attributeService.GetByEntityTypeId( new Workflow().TypeId ).AsQueryable()
                .Where( a => a.EntityTypeQualifierColumn.Equals( "WorkflowTypeId", StringComparison.OrdinalIgnoreCase )
                && a.EntityTypeQualifierValue.Equals( qualifierValue ) );

            qryWorkflowTypeAttributes = qryWorkflowTypeAttributes.Where( a => a.IsGridColumn );

            List<Attribute> gridItems = qryWorkflowTypeAttributes.ToList();

            foreach ( var item in gWorkflows.Columns.OfType<AttributeField>().ToList() )
            {
                gWorkflows.Columns.Remove( item );
            }

            foreach ( var item in gridItems.OrderBy( a => a.Order ).ThenBy( a => a.Name ) )
            {
                string dataFieldExpression = item.Key;
                bool columnExists = gWorkflows.Columns.OfType<AttributeField>().FirstOrDefault( a => a.DataField.Equals( dataFieldExpression ) ) != null;
                if ( !columnExists )
                {
                    AttributeField boundField = new AttributeField();
                    boundField.DataField = dataFieldExpression;
                    boundField.HeaderText = item.Name;
                    boundField.SortExpression = string.Empty;
                    int insertPos = gWorkflows.Columns.IndexOf( gWorkflows.Columns.OfType<DeleteField>().First() );
                    gWorkflows.Columns.Insert( insertPos, boundField );
                }
            }


            pnlWorkflowList.Visible = true;

            qry = qry.Where( a => a.WorkflowTypeId.Equals( workflowType.Id ) );

            if ( sortProperty != null )
            {
                gWorkflows.DataSource = qry.Sort( sortProperty ).ToList();
            }
            else
            {
                gWorkflows.DataSource = qry.OrderBy( s => s.Name ).ToList();
            }

            gWorkflows.DataBind();
        }
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="group">The group.</param>
        private void ShowEditDetails( Group group )
        {
            if ( group.Id == 0 )
            {
                lReadOnlyTitle.Text = ActionTitle.Add( Group.FriendlyTypeName ).FormatAsHtmlTitle();
                hlInactive.Visible = false;
            }
            else
            {
                lReadOnlyTitle.Text = group.Name.FormatAsHtmlTitle();
            }

            SetEditMode( true );

            tbName.Text = group.Name;
            tbDescription.Text = group.Description;
            cbIsSecurityRole.Checked = group.IsSecurityRole;
            cbIsActive.Checked = group.IsActive;

            var rockContext = new RockContext();

            var groupService = new GroupService( rockContext );
            var attributeService = new AttributeService( rockContext );

            LoadDropDowns();

            gpParentGroup.SetValue( group.ParentGroup ?? groupService.Get( group.ParentGroupId ?? 0 ) );

            // GroupType depends on Selected ParentGroup
            ddlParentGroup_SelectedIndexChanged( null, null );
            gpParentGroup.Label = "Parent Group";

            if ( group.Id == 0 && ddlGroupType.Items.Count > 1 )
            {
                if ( GetAttributeValue( "LimittoSecurityRoleGroups" ).AsBoolean() )
                {
                    // default GroupType for new Group to "Security Roles"  if LimittoSecurityRoleGroups
                    var securityRoleGroupType = GroupTypeCache.GetSecurityRoleGroupType();
                    if ( securityRoleGroupType != null )
                    {
                        ddlGroupType.SetValue( securityRoleGroupType.Id );
                    }
                    else
                    {
                        ddlGroupType.SelectedIndex = 0;
                    }
                }
                else
                {
                    // if this is a new group (and not "LimitToSecurityRoleGroups", and there is more than one choice for GroupType, default to no selection so they are forced to choose (vs unintentionallly choosing the default one)
                    ddlGroupType.SelectedIndex = 0;
                }
            }
            else
            {
                ddlGroupType.SetValue( group.GroupTypeId );
            }

            ddlCampus.SetValue( group.CampusId );

            var groupLocations = new List<GroupLocation>();
            foreach ( var groupLocation in group.GroupLocations )
            {
                var groupLocationState = new GroupLocation();
                groupLocationState.CopyPropertiesFrom( groupLocation );
                if ( groupLocation.Location != null )
                {
                    groupLocationState.Location = new Location();
                    groupLocationState.Location.CopyPropertiesFrom( groupLocation.Location );
                }

                if ( groupLocation.GroupLocationTypeValue != null )
                {
                    groupLocationState.GroupLocationTypeValue = new DefinedValue();
                    groupLocationState.GroupLocationTypeValue.CopyPropertiesFrom( groupLocation.GroupLocationTypeValue );
                }
                groupLocations.Add( groupLocationState );
            }
            GroupLocationsState = new ViewStateList<GroupLocation>();
            GroupLocationsState.AddAll( groupLocations );

            ShowGroupTypeEditDetails( GroupTypeCache.Read( group.GroupTypeId ), group, true );

            // if this block's attribute limit group to SecurityRoleGroups, don't let them edit the SecurityRole checkbox value
            if ( GetAttributeValue( "LimittoSecurityRoleGroups" ).AsBoolean() )
            {
                cbIsSecurityRole.Enabled = false;
                cbIsSecurityRole.Checked = true;
            }

            string qualifierValue = group.Id.ToString();
            GroupMemberAttributesState = new ViewStateList<Attribute>();
            GroupMemberAttributesState.AddAll( attributeService.GetByEntityTypeId( new GroupMember().TypeId ).AsQueryable()
                    .Where( a =>
                        a.EntityTypeQualifierColumn.Equals( "GroupId", StringComparison.OrdinalIgnoreCase ) &&
                        a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                    .OrderBy( a => a.Order )
                    .ThenBy( a => a.Name )
                    .ToList() );
            BindGroupMemberAttributesGrid();

            BindInheritedAttributes( group.GroupTypeId, attributeService );
        }
Пример #8
0
        /// <summary>
        /// Loads the <see cref="P:IHasAttributes.Attributes" /> and <see cref="P:IHasAttributes.AttributeValues" /> of any <see cref="IHasAttributes" /> object
        /// </summary>
        /// <param name="entity">The item.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <remarks>
        /// If a rockContext value is included, this method will save any previous changes made to the context
        /// </remarks>
        public static void LoadAttributes( Rock.Attribute.IHasAttributes entity, RockContext rockContext = null )
        {
            Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>();

            Type entityType = entity.GetType();
            if ( entityType.Namespace == "System.Data.Entity.DynamicProxies" )
                entityType = entityType.BaseType;

            rockContext = rockContext ?? new RockContext();

            // Check for group type attributes
            var groupTypeIds = new List<int>();
            if ( entity is GroupMember || entity is Group || entity is GroupType )
            {
                // Can't use GroupTypeCache here since it loads attributes and would result in a recursive stack overflow situation
                var groupTypeService = new GroupTypeService( rockContext );
                GroupType groupType = null;

                if ( entity is GroupMember )
                {
                    var group = ( (GroupMember)entity ).Group ?? new GroupService( rockContext ).Get( ( (GroupMember)entity ).GroupId );
                    groupType = group.GroupType ?? groupTypeService.Get( group.GroupTypeId );
                }
                else if ( entity is Group )
                {
                    groupType = ( (Group)entity ).GroupType ?? groupTypeService.Get( ( (Group)entity ).GroupTypeId );
                }
                else
                {
                    groupType = ( (GroupType)entity );
                }

                while ( groupType != null )
                {
                    groupTypeIds.Insert(0, groupType.Id );

                    // Check for inherited group type id's
                    groupType = groupType.InheritedGroupType ?? groupTypeService.Get( groupType.InheritedGroupTypeId ?? 0 );
                }

            }

            foreach ( PropertyInfo propertyInfo in entityType.GetProperties() )
                properties.Add( propertyInfo.Name.ToLower(), propertyInfo );

            Rock.Model.AttributeService attributeService = new Rock.Model.AttributeService( rockContext );
            Rock.Model.AttributeValueService attributeValueService = new Rock.Model.AttributeValueService( rockContext );

            var inheritedAttributes = new Dictionary<int, List<Rock.Web.Cache.AttributeCache>>();
            if ( groupTypeIds.Any() )
            {
                groupTypeIds.ForEach( g => inheritedAttributes.Add( g, new List<Rock.Web.Cache.AttributeCache>() ) );
            }
            else
            {
                inheritedAttributes.Add( 0, new List<Rock.Web.Cache.AttributeCache>() );
            }

            var attributes = new List<Rock.Web.Cache.AttributeCache>();

            // Get all the attributes that apply to this entity type and this entity's properties match any attribute qualifiers
            int? entityTypeId = Rock.Web.Cache.EntityTypeCache.Read( entityType ).Id;
            foreach ( Rock.Model.Attribute attribute in attributeService.GetByEntityTypeId( entityTypeId ) )
            {
                // group type ids exist (entity is either GroupMember, Group, or GroupType) and qualifier is for a group type id
                if ( groupTypeIds.Any() && (
                        ( entity is GroupMember && string.Compare( attribute.EntityTypeQualifierColumn, "GroupTypeId", true ) == 0 ) ||
                        ( entity is Group && string.Compare( attribute.EntityTypeQualifierColumn, "GroupTypeId", true ) == 0 ) ||
                        ( entity is GroupType && string.Compare( attribute.EntityTypeQualifierColumn, "Id", true ) == 0 ) ) )
                {
                    int groupTypeIdValue = int.MinValue;
                    if ( int.TryParse( attribute.EntityTypeQualifierValue, out groupTypeIdValue ) && groupTypeIds.Contains( groupTypeIdValue ) )
                    {
                        inheritedAttributes[groupTypeIdValue].Add( Rock.Web.Cache.AttributeCache.Read( attribute ) );
                    }
                }
                    
                else if ( string.IsNullOrEmpty( attribute.EntityTypeQualifierColumn ) ||
                    ( properties.ContainsKey( attribute.EntityTypeQualifierColumn.ToLower() ) &&
                    ( string.IsNullOrEmpty( attribute.EntityTypeQualifierValue ) ||
                    (properties[attribute.EntityTypeQualifierColumn.ToLower()].GetValue( entity, null ) ?? "").ToString() == attribute.EntityTypeQualifierValue ) ) )
                {
                    attributes.Add( Rock.Web.Cache.AttributeCache.Read( attribute ) );
                }
            }

            var allAttributes = new List<Rock.Web.Cache.AttributeCache>();

            foreach ( var attributeGroup in inheritedAttributes )
            {
                foreach ( var attribute in attributeGroup.Value )
                {
                    allAttributes.Add( attribute );
                }
            }
            foreach ( var attribute in attributes )
            {
                allAttributes.Add( attribute );
            }

            var attributeValues = new Dictionary<string, List<Rock.Model.AttributeValue>>();

            if ( allAttributes.Any() )
            {
                foreach ( var attribute in allAttributes )
                {
                    // Add a placeholder for this item's value for each attribute
                    attributeValues.Add( attribute.Key, new List<Rock.Model.AttributeValue>() );
                }

                // Read this item's value(s) for each attribute 
                List<int> attributeIds = allAttributes.Select( a => a.Id ).ToList();
                foreach ( var attributeValue in attributeValueService.Queryable( "Attribute" )
                    .Where( v => v.EntityId == entity.Id && attributeIds.Contains( v.AttributeId ) ) )
                {
                    attributeValues[attributeValue.Attribute.Key].Add( attributeValue.Clone( false ) as Rock.Model.AttributeValue );
                }

                // Look for any attributes that don't have a value and create a default value entry
                foreach ( var attribute in allAttributes )
                {
                    if ( attributeValues[attribute.Key].Count == 0 )
                    {
                        var attributeValue = new Rock.Model.AttributeValue();
                        attributeValue.AttributeId = attribute.Id;
                        if ( entity.AttributeValueDefaults != null && entity.AttributeValueDefaults.ContainsKey( attribute.Name ) )
                        {
                            attributeValue.Value = entity.AttributeValueDefaults[attribute.Name];
                        }
                        else
                        {
                            attributeValue.Value = attribute.DefaultValue;
                        }
                        attributeValues[attribute.Key].Add( attributeValue );
                    }
                    else
                    {
                        if ( !String.IsNullOrWhiteSpace( attribute.DefaultValue ) )
                        {
                            foreach ( var value in attributeValues[attribute.Key] )
                            {
                                if ( String.IsNullOrWhiteSpace( value.Value ) )
                                {
                                    value.Value = attribute.DefaultValue;
                                }

                            }
                        }
                    }
                }
            }

            entity.Attributes = new Dictionary<string, Web.Cache.AttributeCache>();
            allAttributes.ForEach( a => entity.Attributes.Add( a.Key, a ) );

            entity.AttributeValues = attributeValues;
        }
Пример #9
0
        /// <summary>
        /// Copies the specified connection type.
        /// </summary>
        /// <param name="connectionTypeId">The connection type identifier.</param>
        /// <returns>
        /// Return the new ConnectionType ID
        /// </returns>
        public int Copy(int connectionTypeId)
        {
            var              connectionType      = this.Get(connectionTypeId);
            RockContext      rockContext         = ( RockContext )Context;
            int              newConnectionTypeId = 0;
            AttributeService attributeService    = new AttributeService(rockContext);
            var              authService         = new AuthService(rockContext);

            // Get current Opportunity attributes
            var opportunityAttributes = attributeService
                                        .GetByEntityTypeId(new ConnectionOpportunity().TypeId, true).AsQueryable()
                                        .Where(a =>
                                               a.EntityTypeQualifierColumn.Equals("ConnectionTypeId", StringComparison.OrdinalIgnoreCase) &&
                                               a.EntityTypeQualifierValue.Equals(connectionType.Id.ToString()))
                                        .OrderBy(a => a.Order)
                                        .ThenBy(a => a.Name)
                                        .ToList();

            ConnectionType newConnectionType = new ConnectionType();

            rockContext.WrapTransaction(() =>
            {
                newConnectionType.CopyPropertiesFrom(connectionType);
                InitModel(ref newConnectionType);
                newConnectionType.Name = connectionType.Name + " - Copy";
                this.Add(newConnectionType);
                rockContext.SaveChanges();
                newConnectionTypeId = newConnectionType.Id;

                foreach (var connectionActivityTypeState in connectionType.ConnectionActivityTypes)
                {
                    ConnectionActivityType newConnectionActivityType = new ConnectionActivityType();
                    newConnectionActivityType.CopyPropertiesFrom(connectionActivityTypeState);
                    InitModel(ref newConnectionActivityType);
                    newConnectionType.ConnectionActivityTypes.Add(newConnectionActivityType);
                }

                foreach (var connectionStatusState in connectionType.ConnectionStatuses)
                {
                    ConnectionStatus newConnectionStatus = new ConnectionStatus();
                    newConnectionStatus.CopyPropertiesFrom(connectionStatusState);
                    InitModel(ref newConnectionStatus);
                    newConnectionType.ConnectionStatuses.Add(newConnectionStatus);
                    newConnectionStatus.ConnectionTypeId = newConnectionType.Id;
                }

                foreach (ConnectionWorkflow connectionWorkflowState in connectionType.ConnectionWorkflows)
                {
                    ConnectionWorkflow newConnectionWorkflow = new ConnectionWorkflow();
                    newConnectionWorkflow.CopyPropertiesFrom(connectionWorkflowState);
                    InitModel(ref newConnectionWorkflow);
                    newConnectionType.ConnectionWorkflows.Add(newConnectionWorkflow);
                    newConnectionWorkflow.ConnectionTypeId = newConnectionType.Id;
                }

                rockContext.SaveChanges();

                // Clone the Opportunity attributes
                List <Attribute> newAttributesState = new List <Attribute>();
                foreach (var attribute in opportunityAttributes)
                {
                    var newAttribute = attribute.Clone(false);
                    InitModel(ref newAttribute);
                    newAttribute.IsSystem = false;
                    newAttributesState.Add(newAttribute);

                    foreach (var qualifier in attribute.AttributeQualifiers)
                    {
                        var newQualifier      = qualifier.Clone(false);
                        newQualifier.Id       = 0;
                        newQualifier.Guid     = Guid.NewGuid();
                        newQualifier.IsSystem = false;
                        newAttribute.AttributeQualifiers.Add(qualifier);
                    }
                }

                // Save Attributes
                string qualifierValue = newConnectionType.Id.ToString();
                Rock.Attribute.Helper.SaveAttributeEdits(newAttributesState, new ConnectionOpportunity().TypeId, "ConnectionTypeId", qualifierValue, rockContext);

                // Copy Security
                Rock.Security.Authorization.CopyAuthorization(connectionType, newConnectionType, rockContext);
            });

            CopyConnectionOpportunities(connectionType, newConnectionType);
            ConnectionWorkflowService.RemoveCachedTriggers();
            return(newConnectionTypeId);
        }
Пример #10
0
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        private void LoadExistingRockData()
        {
            var attributeValueService = new AttributeValueService();
            var attributeService = new AttributeService();

            IntegerFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.INTEGER ) ).Id;
            TextFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.TEXT ) ).Id;
            PersonEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id;
            BatchEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialBatch" ).Id;

            var personAttributes = attributeService.GetByEntityTypeId( PersonEntityTypeId ).ToList();

            var householdAttribute = personAttributes.FirstOrDefault( a => a.Key == "F1HouseholdId" );
            if ( householdAttribute == null )
            {
                householdAttribute = new Rock.Model.Attribute();
                householdAttribute.Key = "F1HouseholdId";
                householdAttribute.Name = "F1 Household Id";
                householdAttribute.FieldTypeId = IntegerFieldTypeId;
                householdAttribute.EntityTypeId = PersonEntityTypeId;
                householdAttribute.EntityTypeQualifierValue = string.Empty;
                householdAttribute.EntityTypeQualifierColumn = string.Empty;
                householdAttribute.Description = "The FellowshipOne household identifier for the person that was imported";
                householdAttribute.DefaultValue = string.Empty;
                householdAttribute.IsMultiValue = false;
                householdAttribute.IsRequired = false;
                householdAttribute.Order = 0;

                attributeService.Add( householdAttribute, ImportPersonAlias );
                attributeService.Save( householdAttribute, ImportPersonAlias );
                personAttributes.Add( householdAttribute );
            }

            var individualAttribute = personAttributes.FirstOrDefault( a => a.Key == "F1IndividualId" );
            if ( individualAttribute == null )
            {
                individualAttribute = new Rock.Model.Attribute();
                individualAttribute.Key = "F1IndividualId";
                individualAttribute.Name = "F1 Individual Id";
                individualAttribute.FieldTypeId = IntegerFieldTypeId;
                individualAttribute.EntityTypeId = PersonEntityTypeId;
                individualAttribute.EntityTypeQualifierValue = string.Empty;
                individualAttribute.EntityTypeQualifierColumn = string.Empty;
                individualAttribute.Description = "The FellowshipOne individual identifier for the person that was imported";
                individualAttribute.DefaultValue = string.Empty;
                individualAttribute.IsMultiValue = false;
                individualAttribute.IsRequired = false;
                individualAttribute.Order = 0;

                attributeService.Add( individualAttribute, ImportPersonAlias );
                attributeService.Save( individualAttribute, ImportPersonAlias );
                personAttributes.Add( individualAttribute );
            }

            IndividualAttributeId = individualAttribute.Id;
            HouseholdAttributeId = householdAttribute.Id;

            ReportProgress( 0, "Checking for existing people..." );
            var listHouseholdId = attributeValueService.GetByAttributeId( householdAttribute.Id ).Select( av => new { PersonId = av.EntityId, HouseholdId = av.Value } ).ToList();
            var listIndividualId = attributeValueService.GetByAttributeId( individualAttribute.Id ).Select( av => new { PersonId = av.EntityId, IndividualId = av.Value } ).ToList();

            ImportedPeople = listHouseholdId.GroupJoin( listIndividualId, household => household.PersonId,
                individual => individual.PersonId, ( household, individual ) => new ImportedPerson
                {
                    PersonId = household.PersonId,
                    HouseholdId = household.HouseholdId.AsType<int?>(),
                    IndividualId = individual.Select( i => i.IndividualId.AsType<int?>() ).FirstOrDefault()
                } ).ToList();

            var batchAttribute = attributeService.Queryable().FirstOrDefault( a => a.EntityTypeId == BatchEntityTypeId
                && a.Key == "F1BatchId" );
            if ( batchAttribute == null )
            {
                batchAttribute = new Rock.Model.Attribute();
                batchAttribute.Key = "F1BatchId";
                batchAttribute.Name = "F1 Batch Id";
                batchAttribute.FieldTypeId = IntegerFieldTypeId;
                batchAttribute.EntityTypeId = BatchEntityTypeId;
                batchAttribute.EntityTypeQualifierValue = string.Empty;
                batchAttribute.EntityTypeQualifierColumn = string.Empty;
                batchAttribute.Description = "The FellowshipOne identifier for the batch that was imported";
                batchAttribute.DefaultValue = string.Empty;
                batchAttribute.IsMultiValue = false;
                batchAttribute.IsRequired = false;
                batchAttribute.Order = 0;

                attributeService.Add( batchAttribute, ImportPersonAlias );
                attributeService.Save( batchAttribute, ImportPersonAlias );
            }

            BatchAttributeId = batchAttribute.Id;

            ReportProgress( 0, "Checking for existing contributions..." );
            ImportedBatches = new AttributeValueService().GetByAttributeId( batchAttribute.Id )
                .Select( av => new { F1BatchId = av.Value.AsType<int?>(), RockBatchId = av.EntityId } )
                .ToDictionary( t => t.F1BatchId, t => t.RockBatchId );

            CampusList = new CampusService().Queryable().ToList();
        }
Пример #11
0
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        private void LoadExistingRockData()
        {
            var lookupContext = new RockContext();
            var attributeValueService = new AttributeValueService( lookupContext );
            var attributeService = new AttributeService( lookupContext );

            IntegerFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.INTEGER ) ).Id;
            TextFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.TEXT ) ).Id;
            PersonEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id;
            CampusList = CampusCache.All( lookupContext );

            int attributeEntityTypeId = EntityTypeCache.Read( "Rock.Model.Attribute" ).Id;
            int batchEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialBatch" ).Id;
            int userLoginTypeId = EntityTypeCache.Read( "Rock.Model.UserLogin" ).Id;

            int visitInfoCategoryId = new CategoryService( lookupContext ).GetByEntityTypeId( attributeEntityTypeId )
                .Where( c => c.Name == "Visit Information" ).Select( c => c.Id ).FirstOrDefault();

            // Look up and create attributes for F1 unique identifiers if they don't exist
            var personAttributes = attributeService.GetByEntityTypeId( PersonEntityTypeId ).ToList();

            var householdAttribute = personAttributes.FirstOrDefault( a => a.Key == "F1HouseholdId" );
            if ( householdAttribute == null )
            {
                householdAttribute = new Rock.Model.Attribute();
                householdAttribute.Key = "F1HouseholdId";
                householdAttribute.Name = "F1 Household Id";
                householdAttribute.FieldTypeId = IntegerFieldTypeId;
                householdAttribute.EntityTypeId = PersonEntityTypeId;
                householdAttribute.EntityTypeQualifierValue = string.Empty;
                householdAttribute.EntityTypeQualifierColumn = string.Empty;
                householdAttribute.Description = "The FellowshipOne household identifier for the person that was imported";
                householdAttribute.DefaultValue = string.Empty;
                householdAttribute.IsMultiValue = false;
                householdAttribute.IsRequired = false;
                householdAttribute.Order = 0;

                lookupContext.Attributes.Add( householdAttribute );
                lookupContext.SaveChanges( DisableAudit );
                personAttributes.Add( householdAttribute );
            }

            var individualAttribute = personAttributes.FirstOrDefault( a => a.Key == "F1IndividualId" );
            if ( individualAttribute == null )
            {
                individualAttribute = new Rock.Model.Attribute();
                individualAttribute.Key = "F1IndividualId";
                individualAttribute.Name = "F1 Individual Id";
                individualAttribute.FieldTypeId = IntegerFieldTypeId;
                individualAttribute.EntityTypeId = PersonEntityTypeId;
                individualAttribute.EntityTypeQualifierValue = string.Empty;
                individualAttribute.EntityTypeQualifierColumn = string.Empty;
                individualAttribute.Description = "The FellowshipOne individual identifier for the person that was imported";
                individualAttribute.DefaultValue = string.Empty;
                individualAttribute.IsMultiValue = false;
                individualAttribute.IsRequired = false;
                individualAttribute.Order = 0;

                lookupContext.Attributes.Add( individualAttribute );
                lookupContext.SaveChanges( DisableAudit );
                personAttributes.Add( individualAttribute );
            }

            var secondaryEmailAttribute = personAttributes.FirstOrDefault( a => a.Key == "SecondaryEmail" );
            if ( secondaryEmailAttribute == null )
            {
                secondaryEmailAttribute = new Rock.Model.Attribute();
                secondaryEmailAttribute.Key = "SecondaryEmail";
                secondaryEmailAttribute.Name = "Secondary Email";
                secondaryEmailAttribute.FieldTypeId = TextFieldTypeId;
                secondaryEmailAttribute.EntityTypeId = PersonEntityTypeId;
                secondaryEmailAttribute.EntityTypeQualifierValue = string.Empty;
                secondaryEmailAttribute.EntityTypeQualifierColumn = string.Empty;
                secondaryEmailAttribute.Description = "The secondary email for this person";
                secondaryEmailAttribute.DefaultValue = string.Empty;
                secondaryEmailAttribute.IsMultiValue = false;
                secondaryEmailAttribute.IsRequired = false;
                secondaryEmailAttribute.Order = 0;

                lookupContext.Attributes.Add( secondaryEmailAttribute );
                var visitInfoCategory = new CategoryService( lookupContext ).Get( visitInfoCategoryId );
                secondaryEmailAttribute.Categories.Add( visitInfoCategory );
                lookupContext.SaveChanges( DisableAudit );
            }

            IndividualAttributeId = individualAttribute.Id;
            HouseholdAttributeId = householdAttribute.Id;
            SecondaryEmailAttributeId = secondaryEmailAttribute.Id;

            ReportProgress( 0, "Checking for existing data..." );
            var listHouseholdId = attributeValueService.GetByAttributeId( householdAttribute.Id ).Select( av => new { PersonId = av.EntityId, HouseholdId = av.Value } ).ToList();
            var listIndividualId = attributeValueService.GetByAttributeId( individualAttribute.Id ).Select( av => new { PersonId = av.EntityId, IndividualId = av.Value } ).ToList();
            // var listHouseholdId = new PersonService().Queryable().Select( )

            ImportedPeople = listHouseholdId.GroupJoin( listIndividualId,
                household => household.PersonId,
                individual => individual.PersonId,
                ( household, individual ) => new ImportedPerson
                    {
                        PersonAliasId = household.PersonId,
                        HouseholdId = household.HouseholdId.AsType<int?>(),
                        IndividualId = individual.Select( i => i.IndividualId.AsType<int?>() ).FirstOrDefault()
                    }
                ).ToList();

            ImportedBatches = new FinancialBatchService( lookupContext ).Queryable()
                .Where( b => b.ForeignId != null )
                .Select( b => new { F1Id = b.ForeignId, BatchId = b.Id } )
                .ToDictionary( t => t.F1Id.AsType<int>(), t => (int?)t.BatchId );
        }
Пример #12
0
        /// <summary>
        /// Binds the workflow type attributes grid.
        /// </summary>
        private void BindWorkflowTypeAttributesGrid()
        {
            AttributeService attributeService = new AttributeService();

            int workflowTypeId = hfWorkflowTypeId.ValueAsInt();

            string qualifierValue = workflowTypeId.ToString();
            var qryWorkflowTypeAttributes = attributeService.GetByEntityTypeId( new Workflow().TypeId ).AsQueryable()
                .Where( a => a.EntityTypeQualifierColumn.Equals( "WorkflowTypeId", StringComparison.OrdinalIgnoreCase )
                && a.EntityTypeQualifierValue.Equals( qualifierValue ) );

            gWorkflowTypeAttributes.DataSource = qryWorkflowTypeAttributes.OrderBy( a => a.Name ).ToList();
            gWorkflowTypeAttributes.DataBind();
        }
Пример #13
0
        /// <summary>
        /// Maps the communication data.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapCommunication( IQueryable<Row> tableData )
        {
            var lookupContext = new RockContext();
            var personService = new PersonService( lookupContext );
            var attributeService = new AttributeService( lookupContext );

            var numberTypeValues = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ), lookupContext ).DefinedValues;

            // Look up additional Person attributes (existing)
            var personAttributes = attributeService.GetByEntityTypeId( PersonEntityTypeId ).ToList();

            // Remove previously defined Excavator social attributes & categories if they exist
            var oldFacebookAttribute = personAttributes.Where( a => a.Key == "FacebookUsername" ).FirstOrDefault();
            if ( oldFacebookAttribute != null )
            {
                Rock.Web.Cache.AttributeCache.Flush( oldFacebookAttribute.Id );
                attributeService.Delete( oldFacebookAttribute );
                lookupContext.SaveChanges( true );
            }

            var oldTwitterAttribute = personAttributes.Where( a => a.Key == "TwitterUsername" ).FirstOrDefault();
            if ( oldTwitterAttribute != null )
            {
                Rock.Web.Cache.AttributeCache.Flush( oldTwitterAttribute.Id );
                attributeService.Delete( oldTwitterAttribute );
                lookupContext.SaveChanges( true );
            }

            int attributeEntityTypeId = EntityTypeCache.Read( "Rock.Model.Attribute" ).Id;
            var socialMediaCategory = new CategoryService( lookupContext ).GetByEntityTypeId( attributeEntityTypeId )
                .Where( c => c.Name == "Social Media" &&
                    c.EntityTypeQualifierValue == PersonEntityTypeId.ToString() &&
                    c.IconCssClass == "fa fa-twitter" )
                .FirstOrDefault();
            if ( socialMediaCategory != null )
            {
                lookupContext.Categories.Remove( socialMediaCategory );
                lookupContext.SaveChanges( true );
            }

            // Cached Rock attributes: Facebook, Twitter, Instagram
            var twitterAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "Twitter" ) );
            var facebookAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "Facebook" ) );
            var instagramAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "Instagram" ) );
            var secondaryEmailAttribute = AttributeCache.Read( SecondaryEmailAttributeId );

            var existingNumbers = new PhoneNumberService( lookupContext ).Queryable().ToList();

            var newNumberList = new List<PhoneNumber>();
            var updatedPersonList = new List<Person>();

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying communication import ({0:N0} found, {1:N0} already exist).", totalRows, existingNumbers.Count() ) );

            foreach ( var row in tableData )
            {
                string value = row["Communication_Value"] as string;
                int? individualId = row["Individual_ID"] as int?;
                int? householdId = row["Household_ID"] as int?;
                var personList = new List<int?>();

                if ( individualId != null )
                {
                    int? personId = GetPersonAliasId( individualId, householdId );
                    if ( personId != null )
                    {
                        personList.Add( personId );
                    }
                }
                else
                {
                    List<int?> personIds = GetFamilyByHouseholdId( householdId );
                    if ( personIds.Any() )
                    {
                        personList.AddRange( personIds );
                    }
                }

                if ( personList.Any() && !string.IsNullOrWhiteSpace( value ) )
                {
                    DateTime? lastUpdated = row["LastUpdatedDate"] as DateTime?;
                    string communicationComment = row["Communication_Comment"] as string;
                    string type = row["Communication_Type"] as string;
                    bool isListed = (bool)row["Listed"];
                    value = value.RemoveWhitespace();

                    // Communication value is a number
                    if ( type.Contains( "Phone" ) || type.Contains( "Mobile" ) )
                    {
                        var extension = string.Empty;
                        var countryCode = Rock.Model.PhoneNumber.DefaultCountryCode();
                        var normalizedNumber = string.Empty;
                        var countryIndex = value.IndexOf( '+' );
                        int extensionIndex = value.LastIndexOf( 'x' ) > 0 ? value.LastIndexOf( 'x' ) : value.Length;
                        if ( countryIndex >= 0 )
                        {
                            countryCode = value.Substring( countryIndex, countryIndex + 3 ).AsNumeric();
                            normalizedNumber = value.Substring( countryIndex + 3, extensionIndex - 3 ).AsNumeric();
                            extension = value.Substring( extensionIndex );
                        }
                        else if ( extensionIndex > 0 )
                        {
                            normalizedNumber = value.Substring( 0, extensionIndex ).AsNumeric();
                            extension = value.Substring( extensionIndex ).AsNumeric();
                        }
                        else
                        {
                            normalizedNumber = value.AsNumeric();
                        }

                        if ( !string.IsNullOrWhiteSpace( normalizedNumber ) )
                        {
                            foreach ( var familyPersonId in personList )
                            {
                                bool numberExists = existingNumbers.Any( n => n.PersonId == familyPersonId && n.Number.Equals( value ) );
                                if ( !numberExists )
                                {
                                    var newNumber = new PhoneNumber();
                                    newNumber.CreatedByPersonAliasId = ImportPersonAlias.Id;
                                    newNumber.ModifiedDateTime = lastUpdated;
                                    newNumber.PersonId = (int)familyPersonId;
                                    newNumber.IsMessagingEnabled = false;
                                    newNumber.CountryCode = countryCode;
                                    newNumber.IsUnlisted = !isListed;
                                    newNumber.Extension = extension.Left( 20 );
                                    newNumber.Number = normalizedNumber.Left( 20 );
                                    newNumber.Description = communicationComment;

                                    newNumber.NumberTypeValueId = numberTypeValues.Where( v => type.StartsWith( v.Value ) )
                                        .Select( v => (int?)v.Id ).FirstOrDefault();

                                    newNumberList.Add( newNumber );
                                    existingNumbers.Add( newNumber );
                                }
                            }

                            completed++;
                        }
                    }
                    else
                    {
                        var person = personService.Queryable( includeDeceased: true ).FirstOrDefault( p => p.Id == personList.FirstOrDefault() );
                        person.Attributes = new Dictionary<string, AttributeCache>();
                        person.AttributeValues = new Dictionary<string, AttributeValue>();

                        if ( value.IsValidEmail() )
                        {
                            string secondaryEmail = string.Empty;
                            if ( string.IsNullOrWhiteSpace( person.Email ) )
                            {
                                secondaryEmail = person.Email;
                                person.Email = value.Left( 75 );
                                person.IsEmailActive = isListed;
                                person.ModifiedDateTime = lastUpdated;
                                person.EmailNote = communicationComment;
                                lookupContext.SaveChanges( true );
                            }
                            else if ( !person.Email.Equals( value ) )
                            {
                                secondaryEmail = value;
                            }

                            var existingSecondaryEmail = new AttributeValueService( lookupContext ).Queryable().Where( av => av.AttributeId == SecondaryEmailAttributeId && av.EntityId == person.Id ).FirstOrDefault();

                            if ( !string.IsNullOrWhiteSpace( secondaryEmail ) && existingSecondaryEmail == null )
                            {
                                person.Attributes.Add( secondaryEmailAttribute.Key, secondaryEmailAttribute );
                                person.AttributeValues.Add( secondaryEmailAttribute.Key, new AttributeValue()
                                {
                                    AttributeId = secondaryEmailAttribute.Id,
                                    Value = secondaryEmail
                                } );
                            }
                        }
                        else if ( type.Contains( "Twitter" ) )
                        {
                            person.Attributes.Add( twitterAttribute.Key, twitterAttribute );
                            person.AttributeValues.Add( twitterAttribute.Key, new AttributeValue()
                            {
                                AttributeId = twitterAttribute.Id,
                                Value = value
                            } );
                        }
                        else if ( type.Contains( "Facebook" ) )
                        {
                            var existingFacebook = new AttributeValueService( lookupContext ).Queryable().Where( av => av.AttributeId == facebookAttribute.Id && av.EntityId == person.Id ).FirstOrDefault();
                            if ( existingFacebook == null )
                            {
                                person.Attributes.Add( facebookAttribute.Key, facebookAttribute );
                                person.AttributeValues.Add( facebookAttribute.Key, new AttributeValue()
                                {
                                    AttributeId = facebookAttribute.Id,
                                    Value = value
                                } );
                            }
                        }
                        else if ( type.Contains( "Instagram" ) )
                        {
                            person.Attributes.Add( instagramAttribute.Key, instagramAttribute );
                            person.AttributeValues.Add( instagramAttribute.Key, new AttributeValue()
                            {
                                AttributeId = instagramAttribute.Id,
                                Value = value
                            } );
                        }

                        updatedPersonList.Add( person );
                        completed++;
                    }

                    if ( completed % percentage < 1 )
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress( percentComplete, string.Format( "{0:N0} records imported ({1}% complete).", completed, percentComplete ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        SaveCommunication( newNumberList, updatedPersonList );

                        // reset so context doesn't bloat
                        lookupContext = new RockContext();
                        personService = new PersonService( lookupContext );
                        updatedPersonList.Clear();
                        newNumberList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            if ( newNumberList.Any() || updatedPersonList.Any() )
            {
                SaveCommunication( newNumberList, updatedPersonList );
            }

            ReportProgress( 100, string.Format( "Finished communication import: {0:N0} records imported.", completed ) );
        }
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="marketingCampaignAdTypeId">The marketing campaign ad type id.</param>
        protected void ShowEdit( int marketingCampaignAdTypeId )
        {
            pnlList.Visible = false;
            pnlDetails.Visible = true;

            MarketingCampaignAdTypeService marketingCampaignAdTypeService = new MarketingCampaignAdTypeService();
            MarketingCampaignAdType marketingCampaignAdType = marketingCampaignAdTypeService.Get( marketingCampaignAdTypeId );
            bool readOnly = false;
            AttributesState = new List<Attribute>().ToDto();

            if ( marketingCampaignAdType != null )
            {
                hfMarketingCampaignAdTypeId.Value = marketingCampaignAdType.Id.ToString();
                tbName.Text = marketingCampaignAdType.Name;
                ddlDateRangeType.SelectedValue = ( (int)marketingCampaignAdType.DateRangeType ).ToString();

                AttributeService attributeService = new AttributeService();

                var qry = attributeService.GetByEntityTypeId( new MarketingCampaignAd().TypeId ).AsQueryable()
                    .Where( a => a.EntityTypeQualifierColumn.Equals( "MarketingCampaignAdTypeId", StringComparison.OrdinalIgnoreCase )
                    && a.EntityTypeQualifierValue.Equals( marketingCampaignAdType.Id.ToString() ) );

                AttributesState = qry.ToList().ToDto();

                readOnly = marketingCampaignAdType.IsSystem;

                if ( marketingCampaignAdType.IsSystem )
                {
                    lActionTitle.Text = ActionTitle.View( MarketingCampaignAdType.FriendlyTypeName );
                    btnCancel.Text = "Close";
                }
                else
                {
                    lActionTitle.Text = ActionTitle.Edit( MarketingCampaignAdType.FriendlyTypeName );
                    btnCancel.Text = "Cancel";
                }
            }
            else
            {
                lActionTitle.Text = ActionTitle.Add( MarketingCampaignAdType.FriendlyTypeName );

                hfMarketingCampaignAdTypeId.Value = 0.ToString();
                tbName.Text = string.Empty;
            }

            iconIsSystem.Visible = readOnly;
            btnSave.Visible = !readOnly;

            BindMarketingCampaignAdAttributeTypeGrid();
        }
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="workflowType">Type of the workflow.</param>
        private void ShowEditDetails( WorkflowType workflowType, RockContext rockContext )
        {
            if ( workflowType.Id == 0 )
            {
                lReadOnlyTitle.Text = ActionTitle.Add( WorkflowType.FriendlyTypeName ).FormatAsHtmlTitle();
                hlInactive.Visible = false;
            }

            SetEditMode( true );

            LoadDropDowns();

            tbName.Text = workflowType.Name;
            tbDescription.Text = workflowType.Description;
            cbIsActive.Checked = workflowType.IsActive ?? false;
            cpCategory.SetValue( workflowType.CategoryId );
            tbWorkTerm.Text = workflowType.WorkTerm;
            tbProcessingInterval.Text = workflowType.ProcessingIntervalSeconds != null ? workflowType.ProcessingIntervalSeconds.ToString() : string.Empty;
            cbIsPersisted.Checked = workflowType.IsPersisted;
            ddlLoggingLevel.SetValue( (int)workflowType.LoggingLevel );

            var attributeService = new AttributeService( rockContext );
            AttributesState = new ViewStateList<Attribute>();
            AttributesState.AddAll( attributeService.GetByEntityTypeId( new Workflow().TypeId ).AsQueryable()
                .Where( a =>
                    a.EntityTypeQualifierColumn.Equals( "WorkflowTypeId", StringComparison.OrdinalIgnoreCase ) &&
                    a.EntityTypeQualifierValue.Equals( workflowType.Id.ToString() ) )
                .OrderBy( a => a.Order )
                .ThenBy( a => a.Name )
                .ToList() );
            BindAttributesGrid();

            phActivities.Controls.Clear();
            foreach ( WorkflowActivityType workflowActivityType in workflowType.ActivityTypes.OrderBy( a => a.Order ) )
            {
                CreateWorkflowActivityTypeEditorControls( workflowActivityType );
            }

            RefreshActivityLists();
        }
        /// <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 )
        {
            MarketingCampaignAdType marketingCampaignAdType;
            MarketingCampaignAdTypeService marketingCampaignAdTypeService = new MarketingCampaignAdTypeService();

            int marketingCampaignAdTypeId = int.Parse( hfMarketingCampaignAdTypeId.Value );

            if ( marketingCampaignAdTypeId == 0 )
            {
                marketingCampaignAdType = new MarketingCampaignAdType();
                marketingCampaignAdTypeService.Add( marketingCampaignAdType, CurrentPersonId );
            }
            else
            {
                marketingCampaignAdType = marketingCampaignAdTypeService.Get( marketingCampaignAdTypeId );
            }

            marketingCampaignAdType.Name = tbName.Text;
            marketingCampaignAdType.DateRangeType = (DateRangeTypeEnum)int.Parse( ddlDateRangeType.SelectedValue );

            // check for duplicates
            if ( marketingCampaignAdTypeService.Queryable().Count( a => a.Name.Equals( marketingCampaignAdType.Name, StringComparison.OrdinalIgnoreCase ) && !a.Id.Equals( marketingCampaignAdType.Id ) ) > 0 )
            {
                tbName.ShowErrorMessage( WarningMessage.DuplicateFoundMessage( "name", MarketingCampaignAdType.FriendlyTypeName ) );
                return;
            }

            if ( !marketingCampaignAdType.IsValid )
            {
                // Controls will render the error messages
                return;
            }

            RockTransactionScope.WrapTransaction( () =>
            {
                marketingCampaignAdTypeService.Save( marketingCampaignAdType, CurrentPersonId );

                // get it back to make sure we have a good Id for it for the Attributes
                marketingCampaignAdType = marketingCampaignAdTypeService.Get( marketingCampaignAdType.Guid );

                // delete AdTypeAttributes that are no longer configured in the UI
                AttributeService attributeService = new AttributeService();
                var qry = attributeService.GetByEntityTypeId( new MarketingCampaignAd().TypeId ).AsQueryable()
                    .Where( a => a.EntityTypeQualifierColumn.Equals( "MarketingCampaignAdTypeId", StringComparison.OrdinalIgnoreCase )
                    && a.EntityTypeQualifierValue.Equals( marketingCampaignAdType.Id.ToString() ) );

                var deletedAttributes = from attr in qry
                                        where !( from d in AttributesState
                                                 select d.Guid ).Contains( attr.Guid )
                                        select attr;

                deletedAttributes.ToList().ForEach( a =>
                    {
                        var attr = attributeService.Get( a.Guid );
                        attributeService.Delete( attr, CurrentPersonId );
                        attributeService.Save( attr, CurrentPersonId );
                    } );

                // add/update the AdTypes that are assigned in the UI
                foreach ( var attributeState in AttributesState )
                {
                    Attribute attribute = qry.FirstOrDefault( a => a.Guid.Equals( attributeState.Guid ) );
                    if ( attribute == null )
                    {
                        attribute = attributeState.ToModel();
                        attributeService.Add( attribute, CurrentPersonId );
                    }
                    else
                    {
                        attributeState.Id = attribute.Id;
                        attributeState.CopyToModel( attribute );
                    }

                    attribute.EntityTypeQualifierColumn = "MarketingCampaignAdTypeId";
                    attribute.EntityTypeQualifierValue = marketingCampaignAdType.Id.ToString();
                    attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read( new MarketingCampaignAd().TypeName ).Id;
                    attributeService.Save( attribute, CurrentPersonId );
                }
            } );

            BindGrid();
            pnlDetails.Visible = false;
            pnlList.Visible = true;
        }
Пример #17
0
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="group">The group.</param>
        private void ShowEditDetails( Group group )
        {
            if ( group.Id == 0 )
            {
                lReadOnlyTitle.Text = ActionTitle.Add( Group.FriendlyTypeName ).FormatAsHtmlTitle();

                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }
            else
            {
                lReadOnlyTitle.Text = group.Name.FormatAsHtmlTitle();
            }

            SetHighlightLabelVisibility( group, false );

            ddlGroupType.Visible = group.Id == 0;
            lGroupType.Visible = group.Id != 0;

            SetEditMode( true );

            tbName.Text = group.Name;
            tbDescription.Text = group.Description;
            nbGroupCapacity.Text = group.GroupCapacity.ToString();
            cbIsSecurityRole.Checked = group.IsSecurityRole;
            cbIsActive.Checked = group.IsActive;
            cbIsPublic.Checked = group.IsPublic;

            var rockContext = new RockContext();

            var groupService = new GroupService( rockContext );
            var attributeService = new AttributeService( rockContext );

            LoadDropDowns( rockContext );

            ddlSignatureDocumentTemplate.SetValue( group.RequiredSignatureDocumentTemplateId );
            gpParentGroup.SetValue( group.ParentGroup ?? groupService.Get( group.ParentGroupId ?? 0 ) );

            // hide sync and requirements panel if no admin access
            bool canAdministrate = group.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson );
            wpGroupSync.Visible = canAdministrate;
            wpGroupRequirements.Visible = canAdministrate;
            wpGroupMemberAttributes.Visible = canAdministrate;

            var systemEmails = new SystemEmailService( rockContext ).Queryable().OrderBy( e => e.Title )
                .Select( a => new
                {
                    a.Id,
                    a.Title
                } );

            // add a blank for the first option
            ddlWelcomeEmail.Items.Add( new ListItem() );
            ddlExitEmail.Items.Add( new ListItem() );

            if ( systemEmails.Any() )
            {
                foreach ( var systemEmail in systemEmails )
                {
                    ddlWelcomeEmail.Items.Add( new ListItem( systemEmail.Title, systemEmail.Id.ToString() ) );
                    ddlExitEmail.Items.Add( new ListItem( systemEmail.Title, systemEmail.Id.ToString() ) );
                }
            }

            // set dataview
            dvpSyncDataview.EntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id;
            dvpSyncDataview.SetValue( group.SyncDataViewId );

            if ( group.AddUserAccountsDuringSync.HasValue )
            {
                rbCreateLoginDuringSync.Checked = group.AddUserAccountsDuringSync.Value;
            }

            if ( group.WelcomeSystemEmailId.HasValue )
            {
                ddlWelcomeEmail.SetValue( group.WelcomeSystemEmailId );
            }

            if ( group.ExitSystemEmailId.HasValue )
            {
                ddlExitEmail.SetValue( group.ExitSystemEmailId );
            }

            // GroupType depends on Selected ParentGroup
            ddlParentGroup_SelectedIndexChanged( null, null );
            gpParentGroup.Label = "Parent Group";

            if ( group.Id == 0 && group.GroupType == null && ddlGroupType.Items.Count > 1 )
            {
                if ( GetAttributeValue( "LimittoSecurityRoleGroups" ).AsBoolean() )
                {
                    // default GroupType for new Group to "Security Roles"  if LimittoSecurityRoleGroups
                    var securityRoleGroupType = GroupTypeCache.GetSecurityRoleGroupType();
                    if ( securityRoleGroupType != null )
                    {
                        CurrentGroupTypeId = securityRoleGroupType.Id;
                        ddlGroupType.SetValue( securityRoleGroupType.Id );
                    }
                    else
                    {
                        ddlGroupType.SelectedIndex = 0;
                    }
                }
                else
                {
                    // if this is a new group (and not "LimitToSecurityRoleGroups", and there is more than one choice for GroupType, default to no selection so they are forced to choose (vs unintentionallly choosing the default one)
                    ddlGroupType.SelectedIndex = 0;
                }
            }
            else
            {
                CurrentGroupTypeId = group.GroupTypeId;
                if ( CurrentGroupTypeId == 0 )
                {
                    CurrentGroupTypeId = ddlGroupType.SelectedValueAsInt() ?? 0;
                }

                var groupType = GroupTypeCache.Read( CurrentGroupTypeId, rockContext );
                lGroupType.Text = groupType != null ? groupType.Name : string.Empty;
                ddlGroupType.SetValue( CurrentGroupTypeId );
            }

            ddlCampus.SetValue( group.CampusId );

            GroupRequirementsState = group.GroupRequirements.ToList();
            GroupLocationsState = group.GroupLocations.ToList();

            var groupTypeCache = CurrentGroupTypeCache;
            nbGroupCapacity.Visible = groupTypeCache != null && groupTypeCache.GroupCapacityRule != GroupCapacityRule.None;
            SetScheduleControls( groupTypeCache, group );
            ShowGroupTypeEditDetails( groupTypeCache, group, true );

            // if this block's attribute limit group to SecurityRoleGroups, don't let them edit the SecurityRole checkbox value
            if ( GetAttributeValue( "LimittoSecurityRoleGroups" ).AsBoolean() )
            {
                cbIsSecurityRole.Enabled = false;
                cbIsSecurityRole.Checked = true;
            }

            string qualifierValue = group.Id.ToString();
            GroupMemberAttributesState = attributeService.GetByEntityTypeId( new GroupMember().TypeId ).AsQueryable()
                    .Where( a =>
                        a.EntityTypeQualifierColumn.Equals( "GroupId", StringComparison.OrdinalIgnoreCase ) &&
                        a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                    .OrderBy( a => a.Order )
                    .ThenBy( a => a.Name )
                    .ToList();
            BindGroupMemberAttributesGrid();

            BindInheritedAttributes( group.GroupTypeId, attributeService );

            cbMembersMustMeetRequirementsOnAdd.Checked = group.MustMeetRequirementsToAddMember ?? false;

            BindGroupRequirementsGrid();

            MemberWorkflowTriggersState = new List<GroupMemberWorkflowTrigger>();
            foreach ( var trigger in group.GroupMemberWorkflowTriggers )
            {
                MemberWorkflowTriggersState.Add( trigger );
            }

            BindMemberWorkflowTriggersGrid();
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="contentTypeId">The marketing campaign ad type identifier.</param>
        public void ShowDetail( int contentTypeId )
        {
            var rockContext = new RockContext();
            ContentChannelType contentType = null;

            if ( !contentTypeId.Equals( 0 ) )
            {
                contentType = GetContentChannelType( contentTypeId );
            }
            if ( contentType == null )
            {
                contentType = new ContentChannelType { Id = 0 };
            }

            string title = contentType.Id > 0 ?
                ActionTitle.Edit( ContentChannelType.FriendlyTypeName ) :
                ActionTitle.Add( ContentChannelType.FriendlyTypeName );
            lTitle.Text = title.FormatAsHtmlTitle();

            hfId.Value = contentType.Id.ToString();

            tbName.Text = contentType.Name;
            ddlDateRangeType.BindToEnum<ContentChannelDateType>();
            ddlDateRangeType.SetValue( (int)contentType.DateRangeType );
            cbIncludeTime.Checked = contentType.IncludeTime;
            cbDisablePriority.Checked = contentType.DisablePriority;

            // load attribute data
            ChannelAttributesState = new List<Attribute>();
            ItemAttributesState = new List<Attribute>();

            AttributeService attributeService = new AttributeService( new RockContext() );

            string qualifierValue = contentType.Id.ToString();

            attributeService.GetByEntityTypeId( new ContentChannel().TypeId ).AsQueryable()
                .Where( a =>
                    a.EntityTypeQualifierColumn.Equals( "ContentChannelTypeId", StringComparison.OrdinalIgnoreCase ) &&
                    a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                .ToList()
                .ForEach( a => ChannelAttributesState.Add( a ) );
            BindChannelAttributesGrid();

            attributeService.GetByEntityTypeId( new ContentChannelItem().TypeId ).AsQueryable()
                .Where( a =>
                    a.EntityTypeQualifierColumn.Equals( "ContentChannelTypeId", StringComparison.OrdinalIgnoreCase ) &&
                    a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                .ToList()
                .ForEach( a => ItemAttributesState.Add( a ) );
            BindItemAttributesGrid();
        }
Пример #19
0
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        private void LoadExistingRockData()
        {
            var lookupContext = new RockContext();
            var attributeValueService = new AttributeValueService( lookupContext );
            var attributeService = new AttributeService( lookupContext );

            IntegerFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.INTEGER ) ).Id;
            TextFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.TEXT ) ).Id;
            PersonEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id;
            CampusList = CampusCache.All();

            int attributeEntityTypeId = EntityTypeCache.Read( "Rock.Model.Attribute" ).Id;
            int batchEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialBatch" ).Id;
            int userLoginTypeId = EntityTypeCache.Read( "Rock.Model.UserLogin" ).Id;

            int visitInfoCategoryId = new CategoryService( lookupContext ).GetByEntityTypeId( attributeEntityTypeId )
                .Where( c => c.Name == "Visit Information" ).Select( c => c.Id ).FirstOrDefault();

            // Look up and create attributes for F1 unique identifiers if they don't exist
            var personAttributes = attributeService.GetByEntityTypeId( PersonEntityTypeId ).AsNoTracking().ToList();

            var householdAttribute = personAttributes.FirstOrDefault( a => a.Key.Equals( "F1HouseholdId", StringComparison.InvariantCultureIgnoreCase ) );
            if ( householdAttribute == null )
            {
                householdAttribute = new Rock.Model.Attribute();
                householdAttribute.Key = "F1HouseholdId";
                householdAttribute.Name = "F1 Household Id";
                householdAttribute.FieldTypeId = IntegerFieldTypeId;
                householdAttribute.EntityTypeId = PersonEntityTypeId;
                householdAttribute.EntityTypeQualifierValue = string.Empty;
                householdAttribute.EntityTypeQualifierColumn = string.Empty;
                householdAttribute.Description = "The FellowshipOne household identifier for the person that was imported";
                householdAttribute.DefaultValue = string.Empty;
                householdAttribute.IsMultiValue = false;
                householdAttribute.IsRequired = false;
                householdAttribute.Order = 0;

                lookupContext.Attributes.Add( householdAttribute );
                lookupContext.SaveChanges( DisableAuditing );
                personAttributes.Add( householdAttribute );
            }

            var individualAttribute = personAttributes.FirstOrDefault( a => a.Key.Equals( "F1IndividualId", StringComparison.InvariantCultureIgnoreCase ) );
            if ( individualAttribute == null )
            {
                individualAttribute = new Rock.Model.Attribute();
                individualAttribute.Key = "F1IndividualId";
                individualAttribute.Name = "F1 Individual Id";
                individualAttribute.FieldTypeId = IntegerFieldTypeId;
                individualAttribute.EntityTypeId = PersonEntityTypeId;
                individualAttribute.EntityTypeQualifierValue = string.Empty;
                individualAttribute.EntityTypeQualifierColumn = string.Empty;
                individualAttribute.Description = "The FellowshipOne individual identifier for the person that was imported";
                individualAttribute.DefaultValue = string.Empty;
                individualAttribute.IsMultiValue = false;
                individualAttribute.IsRequired = false;
                individualAttribute.Order = 0;

                lookupContext.Attributes.Add( individualAttribute );
                lookupContext.SaveChanges( DisableAuditing );
                personAttributes.Add( individualAttribute );
            }

            var secondaryEmailAttribute = personAttributes.FirstOrDefault( a => a.Key.Equals( "SecondaryEmail", StringComparison.InvariantCultureIgnoreCase ) );
            if ( secondaryEmailAttribute == null )
            {
                secondaryEmailAttribute = new Rock.Model.Attribute();
                secondaryEmailAttribute.Key = "SecondaryEmail";
                secondaryEmailAttribute.Name = "Secondary Email";
                secondaryEmailAttribute.FieldTypeId = TextFieldTypeId;
                secondaryEmailAttribute.EntityTypeId = PersonEntityTypeId;
                secondaryEmailAttribute.EntityTypeQualifierValue = string.Empty;
                secondaryEmailAttribute.EntityTypeQualifierColumn = string.Empty;
                secondaryEmailAttribute.Description = "The secondary email for this person";
                secondaryEmailAttribute.DefaultValue = string.Empty;
                secondaryEmailAttribute.IsMultiValue = false;
                secondaryEmailAttribute.IsRequired = false;
                secondaryEmailAttribute.Order = 0;

                lookupContext.Attributes.Add( secondaryEmailAttribute );
                var visitInfoCategory = new CategoryService( lookupContext ).Get( visitInfoCategoryId );
                secondaryEmailAttribute.Categories.Add( visitInfoCategory );
                lookupContext.SaveChanges( DisableAuditing );
            }

            var infellowshipLoginAttribute = personAttributes.FirstOrDefault( a => a.Key.Equals( "InFellowshipLogin", StringComparison.InvariantCultureIgnoreCase ) );
            if ( infellowshipLoginAttribute == null )
            {
                infellowshipLoginAttribute = new Rock.Model.Attribute();
                infellowshipLoginAttribute.Key = "InFellowshipLogin";
                infellowshipLoginAttribute.Name = "InFellowship Login";
                infellowshipLoginAttribute.FieldTypeId = TextFieldTypeId;
                infellowshipLoginAttribute.EntityTypeId = PersonEntityTypeId;
                infellowshipLoginAttribute.EntityTypeQualifierValue = string.Empty;
                infellowshipLoginAttribute.EntityTypeQualifierColumn = string.Empty;
                infellowshipLoginAttribute.Description = "The InFellowship login for this person";
                infellowshipLoginAttribute.DefaultValue = string.Empty;
                infellowshipLoginAttribute.IsMultiValue = false;
                infellowshipLoginAttribute.IsRequired = false;
                infellowshipLoginAttribute.Order = 0;

                // don't add a category as this attribute is only used via the API
                lookupContext.Attributes.Add( infellowshipLoginAttribute );
                lookupContext.SaveChanges( DisableAuditing );
            }

            IndividualIdAttribute = AttributeCache.Read( individualAttribute.Id );
            HouseholdIdAttribute = AttributeCache.Read( householdAttribute.Id );
            InFellowshipLoginAttribute = AttributeCache.Read( infellowshipLoginAttribute.Id );
            SecondaryEmailAttribute = AttributeCache.Read( secondaryEmailAttribute.Id );

            // Set AuthProviderEntityTypeId if Apollos/Infellowship provider exists
            var f1AuthProvider = "cc.newspring.F1.Security.Authentication.F1Migrator";
            var cache = EntityTypeCache.Read( f1AuthProvider );
            AuthProviderEntityTypeId = cache == null ? (int?)null : cache.Id;

            var aliasIdList = new PersonAliasService( lookupContext ).Queryable().AsNoTracking()
                .Select( pa => new
                {
                    PersonAliasId = pa.Id,
                    PersonId = pa.PersonId,
                    IndividualId = pa.ForeignId,
                    FamilyRole = pa.Person.ReviewReasonNote
                } ).ToList();
            var householdIdList = attributeValueService.GetByAttributeId( householdAttribute.Id ).AsNoTracking()
                .Select( av => new
                {
                    PersonId = (int)av.EntityId,
                    HouseholdId = av.Value
                } ).ToList();

            ImportedPeople = householdIdList.GroupJoin( aliasIdList,
                household => household.PersonId,
                aliases => aliases.PersonId,
                ( household, aliases ) => new PersonKeys
                    {
                        PersonAliasId = aliases.Select( a => a.PersonAliasId ).FirstOrDefault(),
                        PersonId = household.PersonId,
                        IndividualId = aliases.Select( a => a.IndividualId ).FirstOrDefault(),
                        HouseholdId = household.HouseholdId.AsType<int?>(),
                        FamilyRoleId = aliases.Select( a => a.FamilyRole.ConvertToEnum<FamilyRole>( 0 ) ).FirstOrDefault()
                    }
                ).ToList();

            ImportedBatches = new FinancialBatchService( lookupContext ).Queryable().AsNoTracking()
                .Where( b => b.ForeignId != null )
                .ToDictionary( t => (int)t.ForeignId, t => (int?)t.Id );
        }
Пример #20
0
        /// <summary>
        /// Loads the state details.
        /// </summary>
        /// <param name="eventCalendar">The event calendar.</param>
        /// <param name="rockContext">The rock context.</param>
        private void LoadStateDetails( EventCalendar eventCalendar, RockContext rockContext )
        {
            var attributeService = new AttributeService( rockContext );
            AttributesState = attributeService
                .GetByEntityTypeId( new EventCalendarItem().TypeId ).AsQueryable()
                .Where( a =>
                    a.EntityTypeQualifierColumn.Equals( "EventCalendarId", StringComparison.OrdinalIgnoreCase ) &&
                    a.EntityTypeQualifierValue.Equals( eventCalendar.Id.ToString() ) )
                .OrderBy( a => a.Order )
                .ThenBy( a => a.Name )
                .ToList();

            ContentChannelsState = new Dictionary<Guid,string>();
            new EventCalendarContentChannelService( rockContext )
                .Queryable()
                .Where( c => c.EventCalendarId == eventCalendar.Id )
                .ToList()
                .ForEach( c => ContentChannelsState.Add( c.ContentChannel.Guid, c.ContentChannel.Name ) );
        }
Пример #21
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            IQueryable<Rock.Model.Attribute> query = null;

            AttributeService attributeService = new AttributeService( new RockContext() );
            if ( _configuredType )
            {
                query = attributeService.Get( _entityTypeId, _entityQualifierColumn, _entityQualifierValue );
            }
            else
            {
                int entityTypeId = int.MinValue;
                if ( int.TryParse( rFilter.GetUserPreference( "Entity Type" ), out entityTypeId ) )
                {
                    if ( entityTypeId > 0 )
                    {
                        query = attributeService.GetByEntityTypeId( entityTypeId );
                    }
                }
            }

            if ( query == null )
            {
                query = attributeService.GetByEntityTypeId( null );
            }

            var selectedCategoryIds = new List<int>();
            rFilter.GetUserPreference( "Categories" ).SplitDelimitedValues().ToList().ForEach( s => selectedCategoryIds.Add( int.Parse( s ) ) );
            if ( selectedCategoryIds.Any() )
            {
                query = query.Where( a => a.Categories.Any( c => selectedCategoryIds.Contains( c.Id ) ) );
            }

            SortProperty sortProperty = rGrid.SortProperty;
            if ( sortProperty != null )
            {
                query = query.Sort( sortProperty );
            }
            else
            {
                query = query.OrderBy( a => a.Key );
            }

            rGrid.DataSource = query.ToList();
            rGrid.DataBind();
        }
Пример #22
0
        /// <summary>
        /// Maps the communication data.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapCommunication( IQueryable<Row> tableData )
        {
            var lookupContext = new RockContext();
            var personService = new PersonService( lookupContext );
            var attributeService = new AttributeService( lookupContext );

            var definedTypePhoneType = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ), lookupContext );
            var otherNumberType = definedTypePhoneType.DefinedValues.Where( dv => dv.Value.StartsWith( "Other" ) ).Select( v => (int?)v.Id ).FirstOrDefault();
            if ( otherNumberType == null )
            {
                var otherType = new DefinedValue();
                otherType.IsSystem = false;
                otherType.DefinedTypeId = definedTypePhoneType.Id;
                otherType.Order = 0;
                otherType.Value = "Other";
                otherType.Description = "Imported from FellowshipOne";
                otherType.CreatedByPersonAliasId = ImportPersonAliasId;

                lookupContext.DefinedValues.Add( otherType );
                lookupContext.SaveChanges( DisableAuditing );
            }

            // Look up existing Person attributes
            var personAttributes = attributeService.GetByEntityTypeId( PersonEntityTypeId ).ToList();

            // Cached Rock attributes: Facebook, Twitter, Instagram
            var twitterAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key.Equals( "Twitter", StringComparison.InvariantCultureIgnoreCase ) ) );
            var facebookAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key.Equals( "Facebook", StringComparison.InvariantCultureIgnoreCase ) ) );
            var instagramAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key.Equals( "Instagram", StringComparison.InvariantCultureIgnoreCase ) ) );

            var newNumbers = new List<PhoneNumber>();
            var existingNumbers = new PhoneNumberService( lookupContext ).Queryable().AsNoTracking().ToList();
            var newPeopleAttributes = new Dictionary<int, Person>();

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying communication import ({0:N0} found, {1:N0} already exist).", totalRows, existingNumbers.Count ) );

            foreach ( var groupedRows in tableData.OrderByDescending( r => r["LastUpdatedDate"] ).GroupBy<Row, int?>( r => r["Household_ID"] as int? ) )
            {
                foreach ( var row in groupedRows.Where( r => r != null ) )
                {
                    string value = row["Communication_Value"] as string;
                    int? individualId = row["Individual_ID"] as int?;
                    int? householdId = row["Household_ID"] as int?;
                    var peopleToUpdate = new List<PersonKeys>();

                    if ( individualId != null )
                    {
                        var matchingPerson = GetPersonKeys( individualId, householdId, includeVisitors: false );
                        if ( matchingPerson != null )
                        {
                            peopleToUpdate.Add( matchingPerson );
                        }
                    }
                    else
                    {
                        peopleToUpdate = GetFamilyByHouseholdId( householdId, includeVisitors: false );
                    }

                    if ( peopleToUpdate.Any() && !string.IsNullOrWhiteSpace( value ) )
                    {
                        DateTime? lastUpdated = row["LastUpdatedDate"] as DateTime?;
                        string communicationComment = row["Communication_Comment"] as string;
                        string type = row["Communication_Type"] as string;
                        bool isListed = (bool)row["Listed"];
                        value = value.RemoveWhitespace();

                        // Communication value is a number
                        if ( type.Contains( "Phone" ) || type.Contains( "Mobile" ) )
                        {
                            var extension = string.Empty;
                            var countryCode = PhoneNumber.DefaultCountryCode();
                            var normalizedNumber = string.Empty;
                            var countryIndex = value.IndexOf( '+' );
                            int extensionIndex = value.LastIndexOf( 'x' ) > 0 ? value.LastIndexOf( 'x' ) : value.Length;
                            if ( countryIndex >= 0 )
                            {
                                countryCode = value.Substring( countryIndex, countryIndex + 3 ).AsNumeric();
                                normalizedNumber = value.Substring( countryIndex + 3, extensionIndex - 3 ).AsNumeric();
                                extension = value.Substring( extensionIndex );
                            }
                            else if ( extensionIndex > 0 )
                            {
                                normalizedNumber = value.Substring( 0, extensionIndex ).AsNumeric();
                                extension = value.Substring( extensionIndex ).AsNumeric();
                            }
                            else
                            {
                                normalizedNumber = value.AsNumeric();
                            }

                            if ( !string.IsNullOrWhiteSpace( normalizedNumber ) )
                            {
                                foreach ( var personKeys in peopleToUpdate )
                                {
                                    bool numberExists = existingNumbers.Any( n => n.PersonId == personKeys.PersonId && n.Number.Equals( value ) );
                                    if ( !numberExists )
                                    {
                                        var newNumber = new PhoneNumber();
                                        newNumber.CreatedByPersonAliasId = ImportPersonAliasId;
                                        newNumber.ModifiedDateTime = lastUpdated;
                                        newNumber.PersonId = (int)personKeys.PersonId;
                                        newNumber.IsMessagingEnabled = false;
                                        newNumber.CountryCode = countryCode;
                                        newNumber.IsUnlisted = !isListed;
                                        newNumber.Extension = extension.Left( 20 ) ?? string.Empty;
                                        newNumber.Number = normalizedNumber.Left( 20 );
                                        newNumber.Description = communicationComment;
                                        newNumber.NumberFormatted = PhoneNumber.FormattedNumber( countryCode, newNumber.Number, true );

                                        var matchingNumberType = definedTypePhoneType.DefinedValues.Where( v => type.StartsWith( v.Value ) )
                                            .Select( v => (int?)v.Id ).FirstOrDefault();
                                        newNumber.NumberTypeValueId = matchingNumberType ?? otherNumberType;

                                        newNumbers.Add( newNumber );
                                        existingNumbers.Add( newNumber );
                                    }
                                }

                                completed++;
                            }
                        }
                        else
                        {
                            Person person = null;

                            var personKeys = peopleToUpdate.FirstOrDefault();
                            if ( !newPeopleAttributes.ContainsKey( personKeys.PersonId ) )
                            {
                                // not in dictionary, get person from database
                                person = personService.Queryable( includeDeceased: true ).FirstOrDefault( p => p.Id == personKeys.PersonId );
                            }
                            else
                            {
                                // reuse person from dictionary
                                person = newPeopleAttributes[personKeys.PersonId];
                            }

                            if ( person != null )
                            {
                                if ( person.Attributes == null || person.AttributeValues == null )
                                {
                                    // make sure we have valid objects to assign to
                                    person.Attributes = new Dictionary<string, AttributeCache>();
                                    person.AttributeValues = new Dictionary<string, AttributeValueCache>();
                                }

                                // Check for an InFellowship ID/email before checking other types of email
                                var isLoginValue = type.IndexOf( "InFellowship", StringComparison.OrdinalIgnoreCase ) >= 0;
                                var personAlreadyHasLogin = person.Attributes.ContainsKey( InFellowshipLoginAttribute.Key );
                                if ( isLoginValue && !personAlreadyHasLogin )
                                {
                                    AddPersonAttribute( InFellowshipLoginAttribute, person, value );
                                    AddUserLogin( AuthProviderEntityTypeId, person, value );
                                }
                                else if ( value.IsEmail() )
                                {
                                    // person email is empty
                                    if ( string.IsNullOrWhiteSpace( person.Email ) )
                                    {
                                        person.Email = value.Left( 75 );
                                        person.IsEmailActive = isListed;
                                        person.EmailPreference = isListed ? EmailPreference.EmailAllowed : EmailPreference.DoNotEmail;
                                        person.ModifiedDateTime = lastUpdated;
                                        person.EmailNote = communicationComment;
                                        lookupContext.SaveChanges( DisableAuditing );
                                    }
                                    // this is a different email, assign it to SecondaryEmail
                                    else if ( !person.Email.Equals( value ) && !person.Attributes.ContainsKey( SecondaryEmailAttribute.Key ) )
                                    {
                                        AddPersonAttribute( SecondaryEmailAttribute, person, value );
                                    }
                                }
                                else if ( type.Contains( "Twitter" ) && !person.Attributes.ContainsKey( twitterAttribute.Key ) )
                                {
                                    AddPersonAttribute( twitterAttribute, person, value );
                                }
                                else if ( type.Contains( "Facebook" ) && !person.Attributes.ContainsKey( facebookAttribute.Key ) )
                                {
                                    AddPersonAttribute( facebookAttribute, person, value );
                                }
                                else if ( type.Contains( "Instagram" ) && !person.Attributes.ContainsKey( instagramAttribute.Key ) )
                                {
                                    AddPersonAttribute( instagramAttribute, person, value );
                                }

                                if ( !newPeopleAttributes.ContainsKey( personKeys.PersonId ) )
                                {
                                    newPeopleAttributes.Add( personKeys.PersonId, person );
                                }
                                else
                                {
                                    newPeopleAttributes[personKeys.PersonId] = person;
                                }
                            }

                            completed++;
                        }

                        if ( completed % percentage < 1 )
                        {
                            int percentComplete = completed / percentage;
                            ReportProgress( percentComplete, string.Format( "{0:N0} records imported ({1}% complete).", completed, percentComplete ) );
                        }
                        else if ( completed % ReportingNumber < 1 )
                        {
                            if ( newNumbers.Any() || newPeopleAttributes.Any() )
                            {
                                SaveCommunication( newNumbers, newPeopleAttributes );
                            }

                            // reset so context doesn't bloat
                            lookupContext = new RockContext();
                            personService = new PersonService( lookupContext );
                            newPeopleAttributes.Clear();
                            newNumbers.Clear();
                            ReportPartialProgress();
                        }
                    }
                }
            }

            if ( newNumbers.Any() || newPeopleAttributes.Any() )
            {
                SaveCommunication( newNumbers, newPeopleAttributes );
            }

            ReportProgress( 100, string.Format( "Finished communication import: {0:N0} records imported.", completed ) );
        }
Пример #23
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        public void ShowEdit()
        {
            int? filterId = hfDataFilterId.Value.AsIntegerOrNull();

            if ( ChannelGuid.HasValue )
            {
                var rockContext = new RockContext();
                var channel = new ContentChannelService( rockContext ).Queryable( "ContentChannelType" )
                    .FirstOrDefault( c => c.Guid.Equals( ChannelGuid.Value ) );
                if ( channel != null )
                {

                    cblStatus.Visible = channel.RequiresApproval;

                    cbSetRssAutodiscover.Visible = channel.EnableRss;

                    var filterService = new DataViewFilterService( rockContext );
                    DataViewFilter filter = null;

                    if ( filterId.HasValue )
                    {
                        filter = filterService.Get( filterId.Value );
                    }

                    if ( filter == null || filter.ExpressionType == FilterExpressionType.Filter )
                    {
                        filter = new DataViewFilter();
                        filter.Guid = new Guid();
                        filter.ExpressionType = FilterExpressionType.GroupAll;
                    }

                    CreateFilterControl( channel, filter, true, rockContext );

                    kvlOrder.CustomKeys = new Dictionary<string, string>();
                    kvlOrder.CustomKeys.Add( "", "" );
                    kvlOrder.CustomKeys.Add( "Title", "Title" );
                    kvlOrder.CustomKeys.Add( "Priority", "Priority" );
                    kvlOrder.CustomKeys.Add( "Status", "Status" );
                    kvlOrder.CustomKeys.Add( "StartDateTime", "Start" );
                    kvlOrder.CustomKeys.Add( "ExpireDateTime", "Expire" );
                    kvlOrder.CustomKeys.Add( "Order", "Order" );


                    // add attributes to the meta description and meta image attribute list
                    ddlMetaDescriptionAttribute.Items.Clear();
                    ddlMetaImageAttribute.Items.Clear();
                    ddlMetaDescriptionAttribute.Items.Add( "" );
                    ddlMetaImageAttribute.Items.Add( "" );

                    string currentMetaDescriptionAttribute = GetAttributeValue( "MetaDescriptionAttribute" ) ?? string.Empty;
                    string currentMetaImageAttribute = GetAttributeValue( "MetaImageAttribute" ) ?? string.Empty;

                    // add channel attributes
                    channel.LoadAttributes();
                    foreach ( var attribute in channel.Attributes )
                    {
                        var field = attribute.Value.FieldType.Field;
                        string computedKey = "C^" + attribute.Key;

                        ddlMetaDescriptionAttribute.Items.Add( new ListItem( "Channel: " + attribute.Value.ToString(), computedKey ) );

                        if ( field is Rock.Field.Types.ImageFieldType )
                        {
                            ddlMetaImageAttribute.Items.Add( new ListItem( "Channel: " + attribute.Value.ToString(), computedKey ) );
                        }
                    }

                    // add item attributes
                    AttributeService attributeService = new AttributeService( rockContext );
                    var itemAttributes = attributeService.GetByEntityTypeId( new ContentChannelItem().TypeId ).AsQueryable()
                                            .Where( a => (
                                                    a.EntityTypeQualifierColumn.Equals( "ContentChannelTypeId", StringComparison.OrdinalIgnoreCase ) &&
                                                    a.EntityTypeQualifierValue.Equals( channel.ContentChannelTypeId.ToString() ) 
                                                ) || (
                                                    a.EntityTypeQualifierColumn.Equals( "ContentChannelId", StringComparison.OrdinalIgnoreCase ) &&
                                                    a.EntityTypeQualifierValue.Equals( channel.Id.ToString() ) 
                                                ) )
                                            .ToList();

                    foreach ( var attribute in itemAttributes )
                    {
                        kvlOrder.CustomKeys.Add( "Attribute:" + attribute.Key, attribute.Name );

                        string computedKey = "I^" + attribute.Key;
                        ddlMetaDescriptionAttribute.Items.Add( new ListItem( "Item: " + attribute.Name, computedKey ) );

                        var field = attribute.FieldType.Name;

                        if ( field == "Image" )
                        {
                            ddlMetaImageAttribute.Items.Add( new ListItem( "Item: " + attribute.Name, computedKey ) );
                        }
                    }

                    // select attributes
                    SetListValue( ddlMetaDescriptionAttribute, currentMetaDescriptionAttribute );
                    SetListValue( ddlMetaImageAttribute, currentMetaImageAttribute );

                }
            }
        }
Пример #24
0
        /// <summary>
        /// Binds the defined values grid.
        /// </summary>
        protected void BindDefinedValuesGrid()
        {
            AttributeService attributeService = new AttributeService();

            int definedTypeId = hfDefinedTypeId.ValueAsInt();
            
            // add attributes with IsGridColumn to grid
            string qualifierValue = hfDefinedTypeId.Value;
            var qryDefinedTypeAttributes = attributeService.GetByEntityTypeId( new DefinedValue().TypeId ).AsQueryable()
                .Where( a => a.EntityTypeQualifierColumn.Equals( "DefinedTypeId", StringComparison.OrdinalIgnoreCase )
                && a.EntityTypeQualifierValue.Equals( qualifierValue ) );

            qryDefinedTypeAttributes = qryDefinedTypeAttributes.Where( a => a.IsGridColumn );

            List<Attribute> gridItems = qryDefinedTypeAttributes.ToList();

            foreach ( var item in gDefinedValues.Columns.OfType<AttributeField>().ToList() )
            {
                gDefinedValues.Columns.Remove( item );
            }

            foreach ( var item in gridItems.OrderBy( a => a.Order ).ThenBy( a => a.Name ) )
            {
                string dataFieldExpression = item.Key;
                bool columnExists = gDefinedValues.Columns.OfType<AttributeField>().FirstOrDefault( a => a.DataField.Equals( dataFieldExpression ) ) != null;
                if ( !columnExists )
                {
                    AttributeField boundField = new AttributeField();
                    boundField.DataField = dataFieldExpression;
                    boundField.HeaderText = item.Name;
                    boundField.SortExpression = string.Empty;
                    int insertPos = gDefinedValues.Columns.IndexOf( gDefinedValues.Columns.OfType<DeleteField>().First());
                    gDefinedValues.Columns.Insert(insertPos, boundField );
                }
            }

            var queryable = new DefinedValueService().Queryable().Where( a => a.DefinedTypeId == definedTypeId ).OrderBy( a => a.Order );
            var result = queryable.ToList();

            gDefinedValues.DataSource = result;
            gDefinedValues.DataBind();
        }
Пример #25
0
        /// <summary>
        /// Maps the person.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="selectedColumns">The selected columns.</param>
        private void MapPerson( IQueryable<Row> tableData, List<string> selectedColumns = null )
        {
            var groupTypeRoleService = new GroupTypeRoleService();
            var attributeService = new AttributeService();
            var dvService = new DefinedValueService();
            var familyList = new List<Group>();

            // Marital statuses: Married, Single, Separated, etc
            List<DefinedValue> maritalStatusTypes = dvService.Queryable()
                .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS ) ).ToList();

            // Connection statuses: Member, Visitor, Attendee, etc
            List<DefinedValue> connectionStatusTypes = dvService.Queryable()
                .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS ) ).ToList();

            // Record status reasons: No Activity, Moved, Deceased, etc
            List<DefinedValue> recordStatusReasons = dvService.Queryable()
                .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_RECORD_STATUS_REASON ) ).ToList();

            // Record statuses: Active, Inactive, Pending
            int? statusActiveId = dvService.Get( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE ) ).Id;
            int? statusInactiveId = dvService.Get( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id;
            int? statusPendingId = dvService.Get( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING ) ).Id;

            // Record type: Person
            int? personRecordTypeId = dvService.Get( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON ) ).Id;

            // Suffix type: Dr., Jr., II, etc
            List<DefinedValue> suffixTypes = dvService.Queryable()
                .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_SUFFIX ) ).ToList();

            // Title type: Mr., Mrs. Dr., etc
            List<DefinedValue> titleTypes = dvService.Queryable()
                .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_TITLE ) ).ToList();

            // Note type: Comment
            int noteCommentTypeId = new NoteTypeService().Get( new Guid( "7E53487C-D650-4D85-97E2-350EB8332763" ) ).Id;

            // Group roles: Adult, Child, others
            int adultRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ).Id;
            int childRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) ).Id;

            // Group type: Family
            int familyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id;

            // Look up additional Person attributes (existing)
            var personAttributes = attributeService.GetByEntityTypeId( PersonEntityTypeId ).ToList();

            // Cached F1 attributes: IndividualId, HouseholdId, PreviousChurch, Position, Employer, School
            var individualIdAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "F1IndividualId" ) );
            var householdIdAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "F1HouseholdId" ) );
            var previousChurchAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "PreviousChurch" ) );
            var employerAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "Employer" ) );
            var positionAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "Position" ) );
            var firstVisitAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "FirstVisit" ) );
            var schoolAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "School" ) );
            var membershipDateAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "MembershipDate" ) );

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Checking person import ({0:N0} found, {1:N0} already exist).", totalRows, ImportedPeople.Count() ) );

            foreach ( var groupedRows in tableData.GroupBy<Row, int?>( r => r["Household_ID"] as int? ) )
            {
                var familyGroup = new Group();
                var householdCampusList = new List<string>();

                foreach ( var row in groupedRows )
                {
                    int? individualId = row["Individual_ID"] as int?;
                    int? householdId = row["Household_ID"] as int?;
                    if ( GetPersonId( individualId, householdId ) == null )
                    {
                        var person = new Person();
                        person.FirstName = row["First_Name"] as string;
                        person.MiddleName = row["Middle_Name"] as string;
                        person.NickName = row["Goes_By"] as string ?? person.FirstName;
                        person.LastName = row["Last_Name"] as string;
                        person.BirthDate = row["Date_Of_Birth"] as DateTime?;
                        person.CreatedByPersonAliasId = ImportPersonAlias.Id;
                        person.RecordTypeValueId = personRecordTypeId;
                        int groupRoleId = adultRoleId;

                        var gender = row["Gender"] as string;
                        if ( gender != null )
                        {
                            person.Gender = (Gender)Enum.Parse( typeof( Gender ), gender );
                        }

                        string prefix = row["Prefix"] as string;
                        if ( prefix != null )
                        {
                            prefix = prefix.RemoveSpecialCharacters().Trim();
                            person.TitleValueId = titleTypes.Where( s => prefix == s.Name.RemoveSpecialCharacters() )
                                .Select( s => (int?)s.Id ).FirstOrDefault();
                        }

                        string suffix = row["Suffix"] as string;
                        if ( suffix != null )
                        {
                            suffix = suffix.RemoveSpecialCharacters().Trim();
                            person.SuffixValueId = suffixTypes.Where( s => suffix == s.Name.RemoveSpecialCharacters() )
                                .Select( s => (int?)s.Id ).FirstOrDefault();
                        }

                        string maritalStatus = row["Marital_Status"] as string;
                        if ( maritalStatus != null )
                        {
                            person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Name == maritalStatus )
                                .Select( dv => (int?)dv.Id ).FirstOrDefault();
                        }
                        else
                        {
                            person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Name == "Unknown" )
                                .Select( dv => (int?)dv.Id ).FirstOrDefault();
                        }

                        string familyRole = row["Household_Position"] as string;
                        if ( familyRole != null )
                        {
                            if ( familyRole == "Child" || person.Age < 18 )
                            {
                                groupRoleId = childRoleId;
                            }
                            else if ( familyRole == "Visitor" )
                            {
                                // assign person as a known relationship of this family/group
                            }
                        }

                        string memberStatus = row["Status_Name"] as string;
                        if ( memberStatus == "Member" )
                        {
                            person.ConnectionStatusValueId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER ) ).Id;
                            person.RecordStatusValueId = statusActiveId;
                        }
                        else if ( memberStatus == "Visitor" )
                        {
                            person.ConnectionStatusValueId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR ) ).Id;
                            person.RecordStatusValueId = statusActiveId;
                        }
                        else if ( memberStatus == "Deceased" )
                        {
                            person.IsDeceased = true;
                            person.RecordStatusValueId = statusInactiveId;
                            person.RecordStatusReasonValueId = recordStatusReasons.Where( dv => dv.Name == "Deceased" )
                                .Select( dv => dv.Id ).FirstOrDefault();
                        }
                        else
                        {
                            // F1 defaults are Member & Visitor; all others are user-defined
                            var customConnectionType = connectionStatusTypes.Where( dv => dv.Name == memberStatus )
                                .Select( dv => (int?)dv.Id ).FirstOrDefault();

                            int attendeeId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( "39F491C5-D6AC-4A9B-8AC0-C431CB17D588" ) ).Id;
                            person.ConnectionStatusValueId = customConnectionType ?? attendeeId;
                            person.RecordStatusValueId = statusActiveId;
                        }

                        string campus = row["SubStatus_Name"] as string;
                        if ( campus != null )
                        {
                            householdCampusList.Add( campus );
                        }

                        string status_comment = row["Status_Comment"] as string;
                        if ( status_comment != null )
                        {
                            var comment = new Note();
                            comment.Text = status_comment;
                            comment.NoteTypeId = noteCommentTypeId;
                            RockTransactionScope.WrapTransaction( () =>
                            {
                                var noteService = new NoteService();
                                noteService.Save( comment );
                            } );
                        }

                        // Map F1 attributes
                        person.Attributes = new Dictionary<string, AttributeCache>();
                        person.AttributeValues = new Dictionary<string, List<AttributeValue>>();

                        // individual_id already defined in scope
                        if ( individualId != null )
                        {
                            person.Attributes.Add( "F1IndividualId", individualIdAttribute );
                            person.AttributeValues.Add( "F1IndividualId", new List<AttributeValue>() );
                            person.AttributeValues["F1IndividualId"].Add( new AttributeValue()
                            {
                                AttributeId = individualIdAttribute.Id,
                                Value = individualId.ToString(),
                                Order = 0
                            } );
                        }

                        // household_id already defined in scope
                        if ( householdId != null )
                        {
                            person.Attributes.Add( "F1HouseholdId", householdIdAttribute );
                            person.AttributeValues.Add( "F1HouseholdId", new List<AttributeValue>() );
                            person.AttributeValues["F1HouseholdId"].Add( new AttributeValue()
                            {
                                AttributeId = householdIdAttribute.Id,
                                Value = householdId.ToString(),
                                Order = 0
                            } );
                        }

                        string previousChurch = row["Former_Church"] as string;
                        if ( previousChurch != null )
                        {
                            person.Attributes.Add( "PreviousChurch", previousChurchAttribute );
                            person.AttributeValues.Add( "PreviousChurch", new List<AttributeValue>() );
                            person.AttributeValues["PreviousChurch"].Add( new AttributeValue()
                            {
                                AttributeId = previousChurchAttribute.Id,
                                Value = previousChurch,
                                Order = 0
                            } );
                        }

                        string employer = row["Employer"] as string;
                        if ( employer != null )
                        {
                            person.Attributes.Add( "Employer", employerAttribute );
                            person.AttributeValues.Add( "Employer", new List<AttributeValue>() );
                            person.AttributeValues["Employer"].Add( new AttributeValue()
                            {
                                AttributeId = employerAttribute.Id,
                                Value = employer,
                                Order = 0
                            } );
                        }

                        string position = row["Occupation_Name"] as string ?? row["Occupation_Description"] as string;
                        if ( position != null )
                        {
                            person.Attributes.Add( "Position", positionAttribute );
                            person.AttributeValues.Add( "Position", new List<AttributeValue>() );
                            person.AttributeValues["Position"].Add( new AttributeValue()
                            {
                                AttributeId = positionAttribute.Id,
                                Value = position,
                                Order = 0
                            } );
                        }

                        string school = row["School_Name"] as string;
                        if ( school != null )
                        {
                            person.Attributes.Add( "School", schoolAttribute );
                            person.AttributeValues.Add( "School", new List<AttributeValue>() );
                            person.AttributeValues["School"].Add( new AttributeValue()
                            {
                                AttributeId = schoolAttribute.Id,
                                Value = school,
                                Order = 0
                            } );
                        }

                        DateTime? membershipDate = row["Status_Date"] as DateTime?;
                        if ( membershipDate != null )
                        {
                            person.CreatedDateTime = membershipDate;
                            person.Attributes.Add( "MembershipDate", membershipDateAttribute );
                            person.AttributeValues.Add( "MembershipDate", new List<AttributeValue>() );
                            person.AttributeValues["MembershipDate"].Add( new AttributeValue()
                            {
                                AttributeId = membershipDateAttribute.Id,
                                Value = membershipDate.Value.ToString( "MM/dd/yyyy" ),
                                Order = 0
                            } );
                        }

                        DateTime? firstVisit = row["First_Record"] as DateTime?;
                        if ( firstVisit != null )
                        {
                            person.CreatedDateTime = firstVisit;
                            // will always pick firstVisit if membershipDate is null
                            firstVisit = firstVisit > membershipDate ? membershipDate : firstVisit;
                            person.Attributes.Add( "FirstVisit", firstVisitAttribute );
                            person.AttributeValues.Add( "FirstVisit", new List<AttributeValue>() );
                            person.AttributeValues["FirstVisit"].Add( new AttributeValue()
                            {
                                AttributeId = firstVisitAttribute.Id,
                                Value = firstVisit.Value.ToString( "MM/dd/yyyy" ),
                                Order = 0
                            } );
                        }

                        // Other Attributes to create:
                        // former name
                        // bar_code
                        // member_env_code
                        // denomination_name

                        var groupMember = new GroupMember();
                        groupMember.Person = person;
                        groupMember.GroupRoleId = groupRoleId;
                        groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                        familyGroup.Members.Add( groupMember );
                    }
                }

                if ( familyGroup.Members.Any() )
                {
                    familyGroup.Name = familyGroup.Members.FirstOrDefault().Person.LastName + " Family";
                    familyGroup.GroupTypeId = familyGroupTypeId;

                    string primaryHouseholdCampus = householdCampusList.GroupBy( c => c ).OrderByDescending( c => c.Count() )
                        .Select( c => c.Key ).FirstOrDefault();
                    if ( primaryHouseholdCampus != null )
                    {
                        familyGroup.CampusId = CampusList.Where( c => c.Name.StartsWith( primaryHouseholdCampus ) || c.ShortCode == primaryHouseholdCampus )
                            .Select( c => (int?)c.Id ).FirstOrDefault();
                    }

                    familyList.Add( familyGroup );
                    completed++;
                    if ( completed % percentage < 1 )
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress( percentComplete, string.Format( "{0:N0} people imported ({1}% complete).", completed, percentComplete ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        RockTransactionScope.WrapTransaction( () =>
                        {
                            var groupService = new GroupService();
                            var personService = new PersonService();
                            var attributeValueService = new AttributeValueService();
                            groupService.RockContext.Groups.AddRange( familyList );
                            groupService.RockContext.SaveChanges();

                            foreach ( var newFamilyGroup in familyList )
                            {
                                foreach ( var groupMember in newFamilyGroup.Members )
                                {
                                    var person = groupMember.Person;
                                    foreach ( var attributeCache in person.Attributes.Select( a => a.Value ) )
                                    {
                                        var newValue = person.AttributeValues[attributeCache.Key].FirstOrDefault();
                                        if ( newValue != null )
                                        {
                                            newValue.EntityId = person.Id;
                                            attributeValueService.RockContext.AttributeValues.Add( newValue );
                                        }
                                    }

                                    if ( !person.Aliases.Any( a => a.AliasPersonId == person.Id ) )
                                    {
                                        person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } );
                                    }

                                    if ( groupMember.GroupRoleId != childRoleId )
                                    {
                                        person.GivingGroupId = newFamilyGroup.Id;
                                    }
                                }
                            }

                            attributeValueService.RockContext.SaveChanges();
                            personService.RockContext.SaveChanges();
                        } );

                        familyList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            // Save any remaining families in the batch
            if ( familyList.Any() )
            {
                RockTransactionScope.WrapTransaction( () =>
                {
                    var groupService = new GroupService();
                    var personService = new PersonService();
                    var attributeValueService = new AttributeValueService();
                    groupService.RockContext.Groups.AddRange( familyList );
                    groupService.RockContext.SaveChanges();

                    foreach ( var newFamilyGroup in familyList )
                    {
                        foreach ( var groupMember in newFamilyGroup.Members )
                        {
                            var person = groupMember.Person;
                            foreach ( var attributeCache in person.Attributes.Select( a => a.Value ) )
                            {
                                var newValue = person.AttributeValues[attributeCache.Key].FirstOrDefault();
                                if ( newValue != null )
                                {
                                    newValue.EntityId = person.Id;
                                    attributeValueService.RockContext.AttributeValues.Add( newValue );
                                }
                            }

                            if ( !person.Aliases.Any( a => a.AliasPersonId == person.Id ) )
                            {
                                person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } );
                            }

                            if ( groupMember.GroupRoleId != childRoleId )
                            {
                                person.GivingGroupId = newFamilyGroup.Id;
                            }
                        }
                    }

                    attributeValueService.RockContext.SaveChanges();
                    personService.RockContext.SaveChanges();
                } );
            }

            ReportProgress( 100, string.Format( "Finished person import: {0:N0} people imported.", completed ) );
        }
Пример #26
0
 /// <summary>
 /// Loads the state details.
 /// </summary>
 /// <param name="connectionType">Type of the connection.</param>
 /// <param name="rockContext">The rock context.</param>
 private void LoadStateDetails( ConnectionType connectionType, RockContext rockContext )
 {
     var attributeService = new AttributeService( rockContext );
     AttributesState = attributeService
         .GetByEntityTypeId( new ConnectionOpportunity().TypeId ).AsQueryable()
         .Where( a =>
             a.EntityTypeQualifierColumn.Equals( "ConnectionTypeId", StringComparison.OrdinalIgnoreCase ) &&
             a.EntityTypeQualifierValue.Equals( connectionType.Id.ToString() ) )
         .OrderBy( a => a.Order )
         .ThenBy( a => a.Name )
         .ToList();
 }
Пример #27
0
        /// <summary>
        /// Binds the defined type attributes grid.
        /// </summary>
        private void BindDefinedTypeAttributesGrid()
        {
            AttributeService attributeService = new AttributeService();

            string qualifierValue = hfDefinedTypeId.Value;
            var qryDefinedTypeAttributes = attributeService.GetByEntityTypeId( new DefinedValue().TypeId ).AsQueryable()
                .Where( a => a.EntityTypeQualifierColumn.Equals( "DefinedTypeId", StringComparison.OrdinalIgnoreCase )
                && a.EntityTypeQualifierValue.Equals( qualifierValue ) );

            gDefinedTypeAttributes.DataSource = qryDefinedTypeAttributes.OrderBy( a => a.Name ).ToList();
            gDefinedTypeAttributes.DataBind();
        }
        /// <summary>
        /// Binds the inherited attributes.
        /// </summary>
        /// <param name="inheritedGroupTypeId">The inherited group type identifier.</param>
        /// <param name="groupTypeService">The group type service.</param>
        /// <param name="attributeService">The attribute service.</param>
        private void BindInheritedAttributes( int? inheritedGroupTypeId, GroupTypeService groupTypeService, AttributeService attributeService )
        {
            GroupTypeAttributesInheritedState = new List<InheritedAttribute>();
            GroupAttributesInheritedState = new List<InheritedAttribute>();
            GroupMemberAttributesInheritedState = new List<InheritedAttribute>();

            while ( inheritedGroupTypeId.HasValue )
            {
                var inheritedGroupType = groupTypeService.Get( inheritedGroupTypeId.Value );
                if ( inheritedGroupType != null )
                {
                    string qualifierValue = inheritedGroupType.Id.ToString();

                    foreach ( var attribute in attributeService.GetByEntityTypeId( new GroupType().TypeId ).AsQueryable()
                        .Where( a =>
                            a.EntityTypeQualifierColumn.Equals( "Id", StringComparison.OrdinalIgnoreCase ) &&
                            a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                        .OrderBy( a => a.Order )
                        .ThenBy( a => a.Name )
                        .ToList() )
                    {
                        GroupTypeAttributesInheritedState.Add( new InheritedAttribute(
                            attribute.Name,
                            attribute.Key,
                            attribute.Description,
                            Page.ResolveUrl( "~/GroupType/" + attribute.EntityTypeQualifierValue ),
                            inheritedGroupType.Name ) );
                    }

                    foreach ( var attribute in attributeService.GetByEntityTypeId( new Group().TypeId ).AsQueryable()
                        .Where( a =>
                            a.EntityTypeQualifierColumn.Equals( "GroupTypeId", StringComparison.OrdinalIgnoreCase ) &&
                            a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                        .OrderBy( a => a.Order )
                        .ThenBy( a => a.Name )
                        .ToList() )
                    {
                        GroupAttributesInheritedState.Add( new InheritedAttribute(
                            attribute.Name,
                            attribute.Key,
                            attribute.Description,
                            Page.ResolveUrl( "~/GroupType/" + attribute.EntityTypeQualifierValue ),
                            inheritedGroupType.Name ) );
                    }

                    foreach ( var attribute in attributeService.GetByEntityTypeId( new GroupMember().TypeId ).AsQueryable()
                        .Where( a =>
                            a.EntityTypeQualifierColumn.Equals( "GroupTypeId", StringComparison.OrdinalIgnoreCase ) &&
                            a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                        .OrderBy( a => a.Order )
                        .ThenBy( a => a.Name )
                        .ToList() )
                    {
                        GroupMemberAttributesInheritedState.Add( new InheritedAttribute(
                            attribute.Name,
                            attribute.Key,
                            attribute.Description,
                            Page.ResolveUrl( "~/GroupType/" + attribute.EntityTypeQualifierValue ),
                            inheritedGroupType.Name ) );
                    }

                    inheritedGroupTypeId = inheritedGroupType.InheritedGroupTypeId;
                }
                else
                {
                    inheritedGroupTypeId = null;
                }
            }

            BindGroupTypeAttributesInheritedGrid();
            BindGroupAttributesInheritedGrid();
            BindGroupMemberAttributesInheritedGrid();
        }
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        public void ShowDetail( string itemKey, int itemKeyValue )
        {
            if ( !itemKey.Equals( "binaryFileTypeId" ) )
            {
                return;
            }

            pnlDetails.Visible = true;
            BinaryFileType binaryFileType;

            var rockContext = new RockContext();

            if ( !itemKeyValue.Equals( 0 ) )
            {
                binaryFileType = new BinaryFileTypeService( rockContext ).Get( itemKeyValue );
                lActionTitle.Text = ActionTitle.Edit( BinaryFileType.FriendlyTypeName ).FormatAsHtmlTitle();
            }
            else
            {
                binaryFileType = new BinaryFileType { Id = 0 };
                lActionTitle.Text = ActionTitle.Add( BinaryFileType.FriendlyTypeName ).FormatAsHtmlTitle();
            }

            BinaryFileAttributesState = new ViewStateList<Attribute>();

            hfBinaryFileTypeId.Value = binaryFileType.Id.ToString();
            tbName.Text = binaryFileType.Name;
            tbDescription.Text = binaryFileType.Description;
            tbIconCssClass.Text = binaryFileType.IconCssClass;
            cbAllowCaching.Checked = binaryFileType.AllowCaching;
            cbRequiresSecurity.Checked = binaryFileType.RequiresSecurity;

            if ( binaryFileType.StorageEntityType != null )
            {
                cpStorageType.SelectedValue = binaryFileType.StorageEntityType.Guid.ToString().ToUpper();
            }

            AttributeService attributeService = new AttributeService( rockContext );

            string qualifierValue = binaryFileType.Id.ToString();
            var qryBinaryFileAttributes = attributeService.GetByEntityTypeId( new BinaryFile().TypeId ).AsQueryable()
                .Where( a => a.EntityTypeQualifierColumn.Equals( "BinaryFileTypeId", StringComparison.OrdinalIgnoreCase )
                && a.EntityTypeQualifierValue.Equals( qualifierValue ) );

            BinaryFileAttributesState.AddAll( qryBinaryFileAttributes.ToList() );
            BindBinaryFileAttributesGrid();

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !IsUserAuthorized( Authorization.EDIT ) )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( BinaryFileType.FriendlyTypeName );
            }

            if ( binaryFileType.IsSystem )
            {
                nbEditModeMessage.Text = EditModeMessage.System( BinaryFileType.FriendlyTypeName );
            }

            phAttributes.Controls.Clear();
            binaryFileType.LoadAttributes();

            if ( readOnly || binaryFileType.IsSystem)
            {
                lActionTitle.Text = ActionTitle.View( BinaryFileType.FriendlyTypeName ).FormatAsHtmlTitle();
                btnCancel.Text = "Close";
                Rock.Attribute.Helper.AddDisplayControls( binaryFileType, phAttributes );
            }
            else
            {
                Rock.Attribute.Helper.AddEditControls( binaryFileType, phAttributes, true );
            }

            tbName.ReadOnly = readOnly || binaryFileType.IsSystem;
            tbDescription.ReadOnly = readOnly || binaryFileType.IsSystem;
            tbIconCssClass.ReadOnly = readOnly || binaryFileType.IsSystem;
            cbAllowCaching.Enabled = !readOnly && !binaryFileType.IsSystem;
            cbRequiresSecurity.Enabled = !readOnly && !binaryFileType.IsSystem;
            gBinaryFileAttributes.Enabled = !readOnly && !binaryFileType.IsSystem;

            // allow storagetype to be edited if IsSystem
            cpStorageType.Enabled = !readOnly;

            // allow save to be clicked if IsSystem since some things can be edited
            btnSave.Visible = !readOnly ;
        }
Пример #30
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="binaryFileTypeId">The binary file type identifier.</param>
        public void ShowDetail( int binaryFileTypeId )
        {
            pnlDetails.Visible = true;
            BinaryFileType binaryFileType = null;

            var rockContext = new RockContext();

            if ( !binaryFileTypeId.Equals( 0 ) )
            {
                binaryFileType = new BinaryFileTypeService( rockContext ).Get( binaryFileTypeId );
                lActionTitle.Text = ActionTitle.Edit( BinaryFileType.FriendlyTypeName ).FormatAsHtmlTitle();
            }

            if ( binaryFileType == null )
            {
                binaryFileType = new BinaryFileType { Id = 0 };
                lActionTitle.Text = ActionTitle.Add( BinaryFileType.FriendlyTypeName ).FormatAsHtmlTitle();
            }

            BinaryFileAttributesState = new List<Attribute>();

            hfBinaryFileTypeId.Value = binaryFileType.Id.ToString();
            tbName.Text = binaryFileType.Name;
            tbDescription.Text = binaryFileType.Description;
            tbIconCssClass.Text = binaryFileType.IconCssClass;
            cbAllowCaching.Checked = binaryFileType.AllowCaching;
            cbRequiresViewSecurity.Checked = binaryFileType.RequiresViewSecurity;

            nbMaxWidth.Text = binaryFileType.MaxWidth.ToString();
            nbMaxHeight.Text = binaryFileType.MaxHeight.ToString();

            ddlPreferredFormat.BindToEnum<Format>();
            ddlPreferredFormat.SetValue( (int)binaryFileType.PreferredFormat );

            ddlPreferredResolution.BindToEnum<Resolution>();
            ddlPreferredResolution.SetValue( (int)binaryFileType.PreferredResolution );

            ddlPreferredColorDepth.BindToEnum<ColorDepth>();
            ddlPreferredColorDepth.SetValue( (int)binaryFileType.PreferredColorDepth );

            cbPreferredRequired.Checked = binaryFileType.PreferredRequired;

            if ( binaryFileType.StorageEntityType != null )
            {
                cpStorageType.SelectedValue = binaryFileType.StorageEntityType.Guid.ToString().ToUpper();
            }

            AttributeService attributeService = new AttributeService( rockContext );

            string qualifierValue = binaryFileType.Id.ToString();
            var qryBinaryFileAttributes = attributeService.GetByEntityTypeId( new BinaryFile().TypeId ).AsQueryable()
                .Where( a => a.EntityTypeQualifierColumn.Equals( "BinaryFileTypeId", StringComparison.OrdinalIgnoreCase )
                && a.EntityTypeQualifierValue.Equals( qualifierValue ) );

            BinaryFileAttributesState = qryBinaryFileAttributes.ToList();

            BindBinaryFileAttributesGrid();

            // render UI based on Authorized and IsSystem
            bool readOnly = false;
            bool restrictedEdit = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !IsUserAuthorized( Authorization.EDIT ) )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( BinaryFileType.FriendlyTypeName );
            }

            if ( binaryFileType.IsSystem )
            {
                restrictedEdit = true;
                nbEditModeMessage.Text = EditModeMessage.System( BinaryFileType.FriendlyTypeName );
            }

            phAttributes.Controls.Clear();
            binaryFileType.LoadAttributes();

            if ( readOnly )
            {
                lActionTitle.Text = ActionTitle.View( BinaryFileType.FriendlyTypeName ).FormatAsHtmlTitle();
                btnCancel.Text = "Close";
            }

            if ( readOnly )
            {
                Rock.Attribute.Helper.AddDisplayControls( binaryFileType, phAttributes );
            }
            else
            {
                Rock.Attribute.Helper.AddEditControls( binaryFileType, phAttributes, true, BlockValidationGroup );
            }

            // the only thing we'll restrict for restrictedEdit is the Name (plus they won't be able to remove Attributes that are marked as IsSystem
            tbName.ReadOnly = readOnly || restrictedEdit;

            gBinaryFileAttributes.Enabled = !readOnly;
            gBinaryFileAttributes.Columns.OfType<EditField>().First().Visible = !readOnly;
            gBinaryFileAttributes.Actions.ShowAdd = !readOnly;

            // allow these to be edited in restricted edit mode if not readonly
            tbDescription.ReadOnly = readOnly;
            tbIconCssClass.ReadOnly = readOnly;
            cbAllowCaching.Enabled = !readOnly;
            cbRequiresViewSecurity.Enabled = !readOnly;
            cpStorageType.Enabled = !readOnly;
            nbMaxWidth.ReadOnly = readOnly;
            nbMaxHeight.ReadOnly = readOnly;
            ddlPreferredFormat.Enabled = !readOnly;
            ddlPreferredResolution.Enabled = !readOnly;
            ddlPreferredColorDepth.Enabled = !readOnly;
            cbPreferredRequired.Enabled = !readOnly;
            btnSave.Visible = !readOnly;
        }
Пример #31
0
        private IQueryable<Rock.Model.Attribute> GetData( RockContext rockContext )
        {
            IQueryable<Rock.Model.Attribute> query = null;

            AttributeService attributeService = new AttributeService( rockContext );
            if ( _configuredType )
            {
                query = attributeService.Get( _entityTypeId, _entityQualifierColumn, _entityQualifierValue );
            }
            else
            {
                int? entityTypeId = rFilter.GetUserPreference( "Entity Type" ).AsIntegerOrNull();
                if ( entityTypeId.HasValue )
                {
                    if ( entityTypeId.Value == 0 )
                    {
                        // Global Attributes
                        query = attributeService.GetByEntityTypeId( null );
                    }
                    else
                    {
                        query = attributeService.GetByEntityTypeId( entityTypeId );
                    }
                }
                else
                {
                    // All entity attribute
                    query = attributeService.Queryable()
                        .Where( a =>
                            ( a.EntityType != null && a.EntityType.IsEntity ) ||    // Entity Attributes
                            ( a.EntityType == null && a.EntityTypeQualifierColumn == "" && a.EntityTypeQualifierValue == "" ) // Global Attributes
                        );
                }
            }

            // if filtering by block setting of categories
            if (!string.IsNullOrWhiteSpace( GetAttributeValue( "CategoryFilter" ) ) )
            {
                try {
                    var categoryGuids = GetAttributeValue( "CategoryFilter" ).Split( ',' ).Select( Guid.Parse ).ToList();

                    query = query.Where( a => a.Categories.Any( c => categoryGuids.Contains( c.Guid ) ) );
                }
                catch { }
            }

            var selectedCategoryIds = new List<int>();
            rFilter.GetUserPreference( "Categories" ).SplitDelimitedValues().ToList().ForEach( s => selectedCategoryIds.Add( int.Parse( s ) ) );
            if ( selectedCategoryIds.Any() )
            {
                query = query.Where( a => a.Categories.Any( c => selectedCategoryIds.Contains( c.Id ) ) );
            }

            if ( _enableOrdering )
            {
                query = query.OrderBy( a => a.Order );
            }
            else
            {
                SortProperty sortProperty = rGrid.SortProperty;
                if ( sortProperty != null )
                {
                    query = query.Sort( sortProperty );
                }
                else
                {
                    query = query.OrderBy( a => a.Key );
                }
            }

            return query;
        }
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="contentChannel">Type of the content.</param>
        protected void ShowEditDetails( ContentChannel contentChannel )
        {
            if ( contentChannel != null )
            {
                hfId.Value = contentChannel.Id.ToString();
                string title = contentChannel.Id > 0 ?
                    ActionTitle.Edit( ContentChannel.FriendlyTypeName ) :
                    ActionTitle.Add( ContentChannel.FriendlyTypeName );

                SetHeadingInfo( contentChannel, title );

                SetEditMode( true );

                LoadDropdowns();

                tbName.Text = contentChannel.Name;
                tbDescription.Text = contentChannel.Description;
                ddlChannelType.SetValue( contentChannel.ContentChannelTypeId );
                ddlContentControlType.SetValue( contentChannel.ContentControlType.ConvertToInt().ToString() );
                tbRootImageDirectory.Text = contentChannel.RootImageDirectory;
                tbRootImageDirectory.Visible = contentChannel.ContentControlType == ContentControlType.HtmlEditor;
                tbIconCssClass.Text = contentChannel.IconCssClass;
                cbRequireApproval.Checked = contentChannel.RequiresApproval;
                cbItemsManuallyOrdered.Checked = contentChannel.ItemsManuallyOrdered;
                cbChildItemsManuallyOrdered.Checked = contentChannel.ChildItemsManuallyOrdered;
                cbEnableRss.Checked = contentChannel.EnableRss;

                divRss.Attributes["style"] = cbEnableRss.Checked ? "display:block" : "display:none";
                tbChannelUrl.Text = contentChannel.ChannelUrl;
                tbItemUrl.Text = contentChannel.ItemUrl;
                nbTimetoLive.Text = ( contentChannel.TimeToLive ?? 0 ).ToString();

                ChildContentChannelsList = new List<int>();
                contentChannel.ChildContentChannels.ToList().ForEach( a => ChildContentChannelsList.Add( a.Id ) );
                BindChildContentChannelsGrid();

                AddAttributeControls( contentChannel );

                // load attribute data
                ItemAttributesState = new List<Attribute>();
                AttributeService attributeService = new AttributeService( new RockContext() );

                string qualifierValue = contentChannel.Id.ToString();

                attributeService.GetByEntityTypeId( new ContentChannelItem().TypeId ).AsQueryable()
                    .Where( a =>
                        a.EntityTypeQualifierColumn.Equals( "ContentChannelId", StringComparison.OrdinalIgnoreCase ) &&
                        a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                    .ToList()
                    .ForEach( a => ItemAttributesState.Add( a ) );

                // Set order
                int newOrder = 0;
                ItemAttributesState.ForEach( a => a.Order = newOrder++ );

                BindItemAttributesGrid();
            }
        }
Пример #33
0
        /// <summary>
        /// Loads the <see cref="P:IHasAttributes.Attributes"/> and <see cref="P:IHasAttributes.AttributeValues"/> of any <see cref="IHasAttributes"/> object
        /// </summary>
        /// <param name="entity">The item.</param>
        public static void LoadAttributes(Rock.Attribute.IHasAttributes entity)
        {
            Dictionary <string, PropertyInfo> properties = new Dictionary <string, PropertyInfo>();

            Type entityType = entity.GetType();

            if (entityType.Namespace == "System.Data.Entity.DynamicProxies")
            {
                entityType = entityType.BaseType;
            }

            // Check for group type attributes
            var groupTypeIds = new List <int>();

            if (entity is GroupMember || entity is Group || entity is GroupType)
            {
                // Can't use GroupTypeCache here since it loads attributes and would result in a recursive stack overflow situation
                var       groupTypeService = new GroupTypeService();
                GroupType groupType        = null;

                if (entity is GroupMember)
                {
                    var group = ((GroupMember)entity).Group ?? new GroupService().Get(((GroupMember)entity).GroupId);
                    groupType = group.GroupType ?? groupTypeService.Get(group.GroupTypeId);
                }
                else if (entity is Group)
                {
                    groupType = ((Group)entity).GroupType ?? groupTypeService.Get(((Group)entity).GroupTypeId);
                }
                else
                {
                    groupType = ((GroupType)entity);
                }

                while (groupType != null)
                {
                    groupTypeIds.Insert(0, groupType.Id);

                    // Check for inherited group type id's
                    groupType = groupType.InheritedGroupType ?? groupTypeService.Get(groupType.InheritedGroupTypeId ?? 0);
                }
            }

            foreach (PropertyInfo propertyInfo in entityType.GetProperties())
            {
                properties.Add(propertyInfo.Name.ToLower(), propertyInfo);
            }

            Rock.Model.AttributeService      attributeService      = new Rock.Model.AttributeService();
            Rock.Model.AttributeValueService attributeValueService = new Rock.Model.AttributeValueService();

            var inheritedAttributes = new Dictionary <int, List <Rock.Web.Cache.AttributeCache> >();

            if (groupTypeIds.Any())
            {
                groupTypeIds.ForEach(g => inheritedAttributes.Add(g, new List <Rock.Web.Cache.AttributeCache>()));
            }
            else
            {
                inheritedAttributes.Add(0, new List <Rock.Web.Cache.AttributeCache>());
            }

            var attributes = new List <Rock.Web.Cache.AttributeCache>();

            // Get all the attributes that apply to this entity type and this entity's properties match any attribute qualifiers
            int?entityTypeId = Rock.Web.Cache.EntityTypeCache.Read(entityType).Id;

            foreach (Rock.Model.Attribute attribute in attributeService.GetByEntityTypeId(entityTypeId))
            {
                // group type ids exist (entity is either GroupMember, Group, or GroupType) and qualifier is for a group type id
                if (groupTypeIds.Any() && (
                        (entity is GroupMember && string.Compare(attribute.EntityTypeQualifierColumn, "GroupTypeId", true) == 0) ||
                        (entity is Group && string.Compare(attribute.EntityTypeQualifierColumn, "GroupTypeId", true) == 0) ||
                        (entity is GroupType && string.Compare(attribute.EntityTypeQualifierColumn, "Id", true) == 0)))
                {
                    int groupTypeIdValue = int.MinValue;
                    if (int.TryParse(attribute.EntityTypeQualifierValue, out groupTypeIdValue) && groupTypeIds.Contains(groupTypeIdValue))
                    {
                        inheritedAttributes[groupTypeIdValue].Add(Rock.Web.Cache.AttributeCache.Read(attribute));
                    }
                }

                else if (string.IsNullOrEmpty(attribute.EntityTypeQualifierColumn) ||
                         (properties.ContainsKey(attribute.EntityTypeQualifierColumn.ToLower()) &&
                          (string.IsNullOrEmpty(attribute.EntityTypeQualifierValue) ||
                           (properties[attribute.EntityTypeQualifierColumn.ToLower()].GetValue(entity, null) ?? "").ToString() == attribute.EntityTypeQualifierValue)))
                {
                    attributes.Add(Rock.Web.Cache.AttributeCache.Read(attribute));
                }
            }

            var allAttributes = new List <Rock.Web.Cache.AttributeCache>();

            foreach (var attributeGroup in inheritedAttributes)
            {
                foreach (var attribute in attributeGroup.Value)
                {
                    allAttributes.Add(attribute);
                }
            }
            foreach (var attribute in attributes)
            {
                allAttributes.Add(attribute);
            }

            var attributeValues = new Dictionary <string, List <Rock.Model.AttributeValue> >();

            if (allAttributes.Any())
            {
                foreach (var attribute in allAttributes)
                {
                    // Add a placeholder for this item's value for each attribute
                    attributeValues.Add(attribute.Key, new List <Rock.Model.AttributeValue>());
                }

                // Read this item's value(s) for each attribute
                List <int> attributeIds = allAttributes.Select(a => a.Id).ToList();
                foreach (var attributeValue in attributeValueService.Queryable("Attribute")
                         .Where(v => v.EntityId == entity.Id && attributeIds.Contains(v.AttributeId)))
                {
                    attributeValues[attributeValue.Attribute.Key].Add(attributeValue.Clone(false) as Rock.Model.AttributeValue);
                }

                // Look for any attributes that don't have a value and create a default value entry
                foreach (var attribute in allAttributes)
                {
                    if (attributeValues[attribute.Key].Count == 0)
                    {
                        var attributeValue = new Rock.Model.AttributeValue();
                        attributeValue.AttributeId = attribute.Id;
                        if (entity.AttributeValueDefaults != null && entity.AttributeValueDefaults.ContainsKey(attribute.Name))
                        {
                            attributeValue.Value = entity.AttributeValueDefaults[attribute.Name];
                        }
                        else
                        {
                            attributeValue.Value = attribute.DefaultValue;
                        }
                        attributeValues[attribute.Key].Add(attributeValue);
                    }
                    else
                    {
                        if (!String.IsNullOrWhiteSpace(attribute.DefaultValue))
                        {
                            foreach (var value in attributeValues[attribute.Key])
                            {
                                if (String.IsNullOrWhiteSpace(value.Value))
                                {
                                    value.Value = attribute.DefaultValue;
                                }
                            }
                        }
                    }
                }
            }

            entity.Attributes = new Dictionary <string, Web.Cache.AttributeCache>();
            allAttributes.ForEach(a => entity.Attributes.Add(a.Key, a));

            entity.AttributeValues = attributeValues;
        }